Skip to main content

crcbl_render/
forward.rs

1//! The frame milestones 3, 4 and 5 draw: a lit mesh into an HDR target, then a
2//! tonemap into whatever the caller is presenting to.
3//!
4//! ```text
5//! ┌ cull ───────────┐ ┌ draw-args ──────┐ ┌ forward ──────────┐ ┌ tonemap ──────┐
6//! │ instances ─────▶│ │ visible ───────▶│ │ scene-color Clear │ │ reads it      │
7//! │ visible list    │ │ per-bucket runs │ │ scene-depth Clear │ │ writes the    │
8//! │ + a GPU count   │ │ + indirect args │ │ one indirect call │ │ target        │
9//! │                 │ │ + a draw count  │ │ per bucket        │ │               │
10//! └─────────────────┘ └─────────────────┘ └───────────────────┘ └───────────────┘
11//! ```
12//!
13//! Two passes and one graph. Everything that makes them ordered, everything that
14//! transitions `scene-color` from a colour attachment into a sampled texture,
15//! and everything that returns the target to [`ResourceState::Present`] is
16//! computed by [`crate::graph`] — **there is not one hand-written barrier in
17//! this file, or anywhere above the seam.**
18//!
19//! # Scope
20//!
21//! Stage 2's ladder rungs 3–5, and nothing beyond:
22//!
23//! * **3** — depth-tested spinning mesh, perspective camera in a uniform buffer.
24//! * **4** — one directional light (in `mesh.slang`). The rung's own wording is
25//!   "Lambert+Blinn"; what shipped is Lambert plus a Cook-Torrance GGX lobe over
26//!   a glTF metallic-roughness row, which is that rung's "real material model"
27//!   arriving early rather than a different rung.
28//! * **5** — orthographic mode, which is [`Camera::projection`] and *nothing
29//!   else*: no second pipeline, no branch in this file, no shader permutation.
30//!
31//! Explicitly not here: bindless at scale (P3), shadows and real post (P7),
32//! material authoring (topic 37), asset loading (P9). The mesh is a constant in
33//! `crcbl-shaders` because rung 3 says "hardcoded cube/sphere".
34//!
35//! What *is* here since 2026-08 is [`crate::material_table`]: §3.2's material
36//! table, holding **both** halves of "texture indices + factors", with
37//! [`mesh::GpuInstance::material`] selecting a row. Three rows are resident and
38//! two of them exist to be seen: [`scene::DEMO_TINTED`] differs from the default
39//! row in its factor and its roughness, and [`scene::DEMO_TEXTURED`] in its
40//! base-colour page layer alone. Which rows those are is [`crate::scene::demo`]'s
41//! to say, and so is why the shading factor rides on that row rather than on a
42//! fourth.
43//!
44//! The page is the texture side, and it is one `D2Array` image rather than an
45//! array of descriptors — `BindingModel::ArrayPages` rather than `Bindless`.
46//! That is the whole of the binding-model decision §3.2 leaves open, taken
47//! here because a layer index needs nothing of a device where a descriptor
48//! array needs `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws. So
49//! there is one lookup, one layout and one artifact rather than a permutation,
50//! and a device that reports the feature runs the same declaration. What
51//! bindless buys later is capacity, not a second path — see [`crate::scene::PageDesc`]
52//! and the layout entry for binding 7.
53//!
54//! What *was* on that list until 2026-08 is GPU culling and the indirect draw
55//! count, and both are here now: [`crate::draw_gen`] runs `cull.slang` and
56//! `draw_gen.slang` in front of this pass, and the draws below come out of the
57//! arguments they wrote. See that module for what a bucket is and why the
58//! arguments are per bucket rather than per surviving instance.
59//!
60//! # The CPU records a fixed number of draws
61//!
62//! One per bucket, whatever the scene holds — topic 03's
63//! headline goal, "10 objects and 10,000 objects record roughly the same
64//! commands". Adding an object is an instance in the pool and nothing else;
65//! removing one is [`InstancePool::remove`] and nothing else. Neither changes a
66//! single command this file records, because what varies — how many instances a
67//! bucket draws, and which — is written by a compute pass into a buffer the
68//! draw reads.
69//!
70//! Which *call* those draws are is the one branch: [`GeometryPath::IndirectCount`]
71//! takes the count from GPU memory too, and [`GeometryPath::IndirectPerBatch`] —
72//! Metal, whose API has multi-draw-indirect and no GPU-side count — reads each
73//! bucket's one argument structure unconditionally and leans on its instance
74//! count being zero.
75//!
76//! What *is* here, since 2026-08, is [`crate::mesh_pool`]: the cube is the first
77//! resident of the global vertex and index pools rather than owning two buffers
78//! of its own, so it is `{base_vertex, base_index, index_count}` like everything
79//! P7 will draw. Same geometry, different residence.
80//!
81//! And since the same month, [`crate::instance_pool`]: the cube's model matrix
82//! is a `GpuInstance` in a storage buffer rather than a field of the frame's
83//! uniform block, uploaded by delta. It holds the same matrix `begin_frame` used
84//! to write into the uniform, which is why the golden images did not move.
85//!
86//! # A second resident, and how it finds its own vertices
87//!
88//! A pool whose only mesh is at base vertex 0 cannot tell a base vertex that
89//! works from one that is silently cancelled out, and `mesh.slang`'s header
90//! shows the four targets disagreeing about exactly that: the SPIR-V subtracts
91//! `BaseVertex` back out of `SV_VertexID`, so the pool's base — passed through
92//! `draw_indexed`'s own argument — reached the shader as zero, while WGSL and
93//! MSL kept it. The same disagreement covers `SV_InstanceID`, which is what
94//! [`crate::sprite_pass`] paid for first.
95//!
96//! So **every draw this pass records passes zero for both of its bases**, and
97//! the real ones arrive as data. The base vertex comes from
98//! [`MeshPool`]'s mesh table, indexed by the drawn instance's
99//! [`mesh::GpuInstance::mesh`] — so it is resolved per instance, by the GPU,
100//! and one draw could cover instances of different meshes. The instance comes
101//! from the bucket's run of survivors, walked with `SV_InstanceID`, which counts
102//! from zero on every target *because* the first instance is zero. All a draw
103//! says for itself is which word holds its run's start — the start is the GPU's,
104//! per frame — in a [`mesh::DrawConstants`] block reached through a dynamic
105//! offset: one block per bucket, written once at build.
106//!
107//! That is what makes the pool's *second* resident,
108//! [`mesh::pyramid_vertices`], draw its own geometry rather than the cube's.
109//!
110//! The pyramid is in the pools from `new` but has no *instance* until a caller
111//! places one with [`ForwardRenderer::add_instance`] — an instance in the pool
112//! is an object in the scene now that culling decides what draws. The frame the
113//! samples draw is still the cube alone, which is why their golden images did
114//! not move either.
115//!
116//! # A third resident, and how it finds its own clusters
117//!
118//! The same argument one layer down. A mesh that fits **one** cluster cannot
119//! tell a per-cluster offset that works from one that is lost, and the cube and
120//! the pyramid fit one each — 24 and 16 vertices against a bound of 64. So the
121//! pool's third resident is [`mesh::open_box_vertices`], five clusters of one
122//! flat face each, four of them at a `Meshlet::vertex_offset` that is not zero.
123//! It is [`crate::cluster_pool`]'s counterpart to what the pyramid is for
124//! [`crate::mesh_pool`], and it is what §3.5's per-cluster culling will need
125//! before a surviving-cluster count can mean anything.
126//!
127//! It arrives on the pyramid's terms exactly: resident from `new`, in the scene
128//! only when a caller places it, so no golden moved for it either.
129//!
130//! # Uniforms are a ring, and they have to be
131//!
132//! The camera spins, so the uniform block is rewritten every frame — and the
133//! previous frame may still be reading it. One buffer would be a
134//! read-after-write hazard *across* submissions, which is precisely what
135//! `CRCBL_VK_SYNC_VALIDATION=1` exists to find and precisely what
136//! stage 2 called its headline risk. So there
137//! is one uniform buffer and one bind group per frame in flight, and
138//! [`ForwardRenderer::begin_frame`] rotates them.
139
140use crcbl_hal::{
141    BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
142    BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
143    BufferUsage, ColorTargetState, CompareOp, CullMode, DepthBias, DepthStencilState, Device,
144    DeviceCaps, Features, FilterMode, Format, GeometryPath, GraphicsPipelineDesc,
145    GraphicsPipelineHandle, HalError, ImageDesc, ImageHandle, ImageSubresourceRange, ImageType,
146    ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
147    MeshPipelineDesc, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PolygonMode,
148    PrimitiveState, QueueHandle, Rect2d, ResourceState, SampleType, SamplerAddressMode,
149    SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc, ShaderModuleHandle, ShaderStages,
150    StoreOp, Viewport, check_portable_storage_buffers,
151};
152use crcbl_shaders::meshlet::MeshClusters;
153use crcbl_shaders::probe_gather::PunctualProducer;
154use crcbl_shaders::{
155    MESH, MESH_CLUSTER, Stage, TONEMAP, contact_shadows, dfg, level_select, ltc, mesh, ssao, ssr,
156    tonemap,
157};
158use glam::{Mat4, Quat, Vec3};
159use std::sync::Arc;
160use std::sync::atomic::{AtomicU64, Ordering};
161
162use crate::camera::{Atmosphere, Camera, DirectionalLight, Fog, Sky};
163use crate::cluster_pool::{ClusterPool, ClusterRange, PooledMesh};
164use crate::contact_shadows::ContactShadows;
165use crate::counters::FrameCounters;
166use crate::cull::Frustum;
167use crate::cull_stats::CullStatsRing;
168use crate::debug_draw::DebugDraw;
169use crate::draw_gen::{DrawGen, DrawGenDesc, FrameCull, GeneratedDraws};
170use crate::effects::{EffectRequest, RenderEffects};
171use crate::graph::{
172    BufferId, ImageId, ImportedBuffer, ImportedImage, InitialClaim, PassBuilder, RenderGraph,
173};
174// Renamed on the way in, because [`crate::light_grid::Grid`] already holds the
175// bare name here and means the froxel grid — the collision [`crate::grid`]'s
176// header predicted.
177use crate::atlas_view::AtlasView;
178use crate::bloom::Bloom;
179use crate::cmaa2::Cmaa2;
180use crate::exposure::{Exposure, ExposureAdaptation, ExposureBuffers};
181use crate::fxaa::Fxaa;
182use crate::grass::{Grass, GrassFrame, GrassScene};
183use crate::grid::{Grid as GroundGrid, GridStyle};
184use crate::hiz::Hiz;
185use crate::instance_pool::{InstanceHandle, InstancePool, InstancePoolDesc, InstancePoolError};
186use crate::light::{Light, sun_row};
187use crate::light_grid::{FROXEL_CAPACITY, FrameView, Grid, LightGrid, LightGridDesc};
188use crate::material_table::{MaterialTable, MaterialTableDesc};
189use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolDesc, MeshPoolError, MeshUpload};
190use crate::occlusion_cull::{OcclusionCulling, OcclusionPyramid};
191use crate::probe::{ProbeTable, ProbeTableDesc};
192use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
193use crate::rsm;
194use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
195use crate::shadow::{self, Cascades};
196use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
197use crate::sky_pass::SkyPass;
198use crate::ssao::{Ssao, cached_group};
199use crate::ssr::{Ssr, SsrEnvironment, SsrImages};
200use crate::stack::CameraStack;
201use crate::texture::{
202    UploadedTexture, upload_texture, upload_texture_layers, upload_texture_mip_layers,
203};
204use crate::transient::TransientPool;
205use crate::upscale::Upscale;
206use crate::volumetric::{FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricReads};
207use crate::water::{Water, WaterBodies, WaterFrame, WaterImages, WaterInputs};
208use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};
209
210mod bucket_draws;
211mod frame_prepare;
212mod pages;
213mod shadow_inputs;
214mod view;
215
216use pages::{PageBindings, RetiredPage, upload_page};
217
218pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};
219
220use bucket_draws::{BucketDraws, EmitTail, RegionStep};
221
222use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput};
223pub use view::{
224    FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
225};
226
227/// The clear behind the mesh, in **linear** light.
228///
229/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
230/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
231/// display-referred colour here would come out visibly paler, which is the
232/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
233pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
234
235/// How many frames of uniform buffers to keep. Matches the frame loop's
236/// frames-in-flight.
237pub const FRAMES_IN_FLIGHT: usize = 2;
238
239/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
240/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
241///
242/// The floor exists so that the control cannot be driven somewhere it cannot be
243/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
244/// unclamped input has two dead ends: far enough down and every pixel rounds to
245/// the same black byte, far enough up and every pixel saturates to white — and
246/// in both the picture stops carrying the information a user would need to see
247/// which way to go. Five stops is well inside either: it is a sixteenth of the
248/// scene's brightness, dark but plainly still a picture, and it is the range a
249/// camera's exposure-compensation dial covers.
250pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
251
252/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
253/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
254/// [`EXPOSURE_MIN`]'s reason.
255pub const EXPOSURE_MAX: f32 = 32.0;
256
257/// The default has to be reachable from both ends of the range, or a control
258/// that steps by a ratio starts somewhere it can only leave in one direction.
259const _: () = assert!(
260    EXPOSURE_MIN > 0.0
261        && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
262        && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
263);
264
265/// The format the frame's depth buffer is created with, taken from the
266/// description that creates it rather than written down a second time.
267///
268/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
269/// depth attachment before there is a frame to ask. The extent is irrelevant to
270/// a format, which is why any is passed.
271pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
272
273/// The format the frame's HDR scene target is created with, taken from the
274/// description that creates it rather than written down a second time.
275///
276/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
277/// chain of HDR passes ended with — every one of them is a
278/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
279/// which is why any is passed.
280pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
281
282/// The format §3.2's base-colour page is created with.
283///
284/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
285/// for it is at the `upload_texture_mip_layers` call inside
286/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
287/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
288/// the image was created with, and a barrier naming a format the image is not in
289/// picks the wrong aspects.
290const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
291
292/// The format topic 43 §2's **normal** page is
293/// created with.
294///
295/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
296/// Topic 44's rung 2 argues it: a base-colour texel is a
297/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
298/// the sampler decode it; a normal texel is a *number* — three components of a
299/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
300/// transfer curve is wrong by a gamma. What that looks like is not an error but
301/// a surface that leans further off vertical than the author drew, which is why
302/// the mistake survives review everywhere it is made.
303///
304/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
305/// worth having because the four constants sit a few lines apart and the wrong
306/// one compiles.
307const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
308
309/// The format topic 43 §2's **metallic-roughness-
310/// occlusion** page is created with.
311///
312/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
313/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
314/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
315/// linear factors — and a surface shaded through an sRGB decode of them is
316/// smoother and shinier than the author drew, which is a failure that survives
317/// review because it looks like a choice.
318///
319/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
320/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
321/// one of them wanted a different format should be an edit here rather than a
322/// search for which callers of a shared name meant which page.
323const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
324
325/// The format topic 43 §2's **emissive** page is
326/// created with.
327///
328/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
329/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
330/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
331/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
332/// what puts the two in one space before they are multiplied.
333///
334/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
335/// and `the_page_formats_split_colour_from_number` is the guard that the four
336/// do not drift into one another.
337const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
338
339/// What the renderer needs of a [`PageKind`] to create and fill its image.
340///
341/// Written here rather than in [`crate::scene`] because the two answers are the
342/// device's: the format is the one [`base_color_page_import`] and
343/// [`normal_page_import`] have to declare, and the filter is the one
344/// [`crate::mip`] builds the chain with. A kind added by
345/// topic 43 §2's rung 3 is a new arm in each.
346///
347/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
348/// [`normal_page_import`]: ForwardRenderer::normal_page_import
349impl PageKind {
350    /// The format this kind's image is created with.
351    ///
352    /// The sRGB in one and its absence in the other is the whole colour-space
353    /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
354    /// which is where each is argued.
355    const fn format(self) -> Format {
356        match self {
357            Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
358            Self::Normal => NORMAL_PAGE_FORMAT,
359            Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
360            Self::Emissive => EMISSIVE_PAGE_FORMAT,
361        }
362    }
363
364    /// Every mip level below `level0`, built on the host with this kind's own
365    /// filter.
366    ///
367    /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
368    /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
369    /// weights by alpha. A normal map mipped through the colour filter leans
370    /// further off vertical at every level than the map it was built from, and
371    /// nothing in a frame reports it.
372    fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
373        match self {
374            Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
375            Self::Normal => crate::mip::normal_chain(level0, extent),
376            Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
377        }
378    }
379
380    /// The device label this kind's image is created under.
381    const fn upload_label(self) -> &'static str {
382        match self {
383            Self::BaseColor => "material base colour",
384            Self::Normal => "material normals",
385            Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
386            Self::Emissive => "material emissive",
387        }
388    }
389}
390
391/// The one texel a page **nothing names** is created with.
392///
393/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
394/// every bind group of the mesh layout has to fill both page bindings whether or
395/// not the description carried either page — so a [`PageKind`] with no layers
396/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
397/// nobody samples. That is the whole of what row (d) bought back:
398/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
399/// every scene in the tree that has no normal map used to carry a full neutral
400/// layer and a third again for its chain.
401///
402/// **Magenta, and it is never sampled for its value.** A material naming no page
403/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
404/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
405/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
406/// at all. So nothing should ever read this — and the value is chosen so that if
407/// something does, the frame says so in a colour no lit surface in this engine
408/// produces. White would blend into every untextured surface and black would
409/// read as a shadow; both are failures a golden could pass.
410const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
411
412/// The format the motion-vector target is created with: two channels of half
413/// float, topic 43 §9's third colour attachment.
414///
415/// **Named here rather than in [`crate::targets::motion`]**, on
416/// [`crate::graph`]'s other format-owning descriptions' terms: the description
417/// and
418/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
419/// pipeline is the one that owns the answer.
420///
421/// # The convention the target holds, so a consumer never has to guess it
422///
423/// **Current minus previous, in texture coordinates, `+y` down.** A pass
424/// holding the previous frame reads its history at `uv - motion`, and a surface
425/// travelling right and down the screen has both components positive.
426/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
427/// is the same sentence on the host side, because the first consumer will read
428/// one of the two and not both.
429///
430/// # Two channels and half float
431///
432/// A motion vector is a screen-space offset and has no third component. Half
433/// float rather than a normalised integer because the value is signed and
434/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
435/// — and because the interesting magnitudes are small: a surface moving a
436/// tenth of a pixel is the case a temporal filter is most sensitive to, and
437/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
438/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
439/// names motion vectors as the use for.
440pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
441
442/// Which picture the colour pass draws instead of the shaded one.
443///
444/// The engine's debug views, as one value rather than as independent booleans,
445/// because they are not independent: every one of them rides in a single lane of
446/// the frame's uniform block and the shaders test the thresholds outermost
447/// first, so a renderer with two of them set draws exactly one.
448/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
449/// answers with — so a menu row, a debug panel and the picture cannot disagree
450/// about which view is on.
451///
452/// **The declaration order is not the precedence** — each view was appended as
453/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
454/// decided. The sentinels in
455/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
456/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
457/// first.
458#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
459pub enum DebugView {
460    /// The lit picture. What every frame draws unless a caller asked otherwise.
461    #[default]
462    Shaded,
463    /// Each cluster shaded by the projected screen-space error the LOD
464    /// selection judged it on — [`ForwardRenderer::set_heatmap`].
465    Heatmap,
466    /// Each cluster tinted by the DAG level it was decimated to —
467    /// [`ForwardRenderer::set_lod_view`].
468    LodTint,
469    /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
470    Normals,
471    /// The ambient-occlusion channel alone, as grey —
472    /// [`ForwardRenderer::set_occlusion_view`].
473    AmbientOcclusion,
474    /// The motion vector each fragment wrote, stretched and centred on grey —
475    /// [`ForwardRenderer::set_motion_view`].
476    Motion,
477    /// The bent direction the occlusion channel carries beside its scalar, as
478    /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
479    /// every other view.**
480    BentNormal,
481    /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
482    /// atlas itself, letterboxed over the finished frame with a border round
483    /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
484    ///
485    /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
486    /// therefore the one whose lane is the off sentinel: the colour pass draws
487    /// the shaded picture exactly as it always did and `crate::atlas_view`
488    /// replaces it afterwards. That module's header is where the placement is
489    /// argued.
490    ///
491    /// It resolves **below every view above and above [`Self::Cascades`]** — see
492    /// [`ForwardRenderer::debug_view`].
493    ShadowAtlas,
494    /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
495    /// was sampled from, with the cross-fade band drawn as the blend of the two
496    /// — [`ForwardRenderer::set_cascade_view`].
497    ///
498    /// **Loses to every other view**, and it is the only one that does. The views
499    /// above draw something *instead of* the shaded picture; this one draws the
500    /// shaded picture and multiplies it, so there is nothing left for it to
501    /// modulate as soon as one of them is on. See
502    /// [`ForwardRenderer::debug_view`].
503    Cascades,
504}
505
506impl DebugView {
507    /// What a panel row or a summary line calls it.
508    #[must_use]
509    pub const fn label(self) -> &'static str {
510        match self {
511            Self::Shaded => "shaded",
512            Self::Heatmap => "heatmap",
513            Self::LodTint => "lod tint",
514            Self::Normals => "normals",
515            Self::AmbientOcclusion => "ambient occlusion",
516            Self::Motion => "motion",
517            Self::BentNormal => "bent normal",
518            Self::ShadowAtlas => "shadow atlas",
519            Self::Cascades => "cascades",
520        }
521    }
522}
523
524// Mesh-only resources follow the complete common fragment binding range.
525// Metal assigns dense native indices by resource-table order, so inserting a
526// mesh-only buffer before lights/probes would shift the layout away from the
527// independently compiled fragment stage. Sparse logical bindings cost no slots.
528const CLUSTERS_BINDING: u32 = 32;
529const CLUSTER_VERTICES_BINDING: u32 = 33;
530const CLUSTER_CORNERS_BINDING: u32 = 34;
531const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
532const CLUSTER_CULL_BINDING: u32 = 36;
533const CLUSTER_CULL_STATS_BINDING: u32 = 37;
534const CLUSTER_SELECT_BINDING: u32 = 38;
535const CLUSTER_SELECTION_BINDING: u32 = 39;
536const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
537
538/// The shared fragment shader's shadow atlas slot. Historical logical gaps
539/// remain reserved so the raster shader bindings stay unchanged.
540const SHADOW_ATLAS_BINDING: u32 = 15;
541
542/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
543const SHADOW_SAMPLER_BINDING: u32 = 16;
544
545/// The bind-group slot the base-colour page is bound to.
546///
547/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
548/// of the mesh layout, as it does each page's binding — see
549/// `pages::page_binding`.
550const BASE_COLOR_PAGE_BINDING: u32 = 7;
551
552/// The bind-group slot the base-colour page's sampler is bound to.
553///
554/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
555/// in every group of the mesh layout: a sampler is a resource a group holds by
556/// handle, so a new sampler is a new group, and the rebuild finds the entry by
557/// this number.
558const PAGE_SAMPLER_BINDING: u32 = 8;
559
560/// The shared fragment shader's light list. Both shader modules declare it
561/// before mesh-only buffers so native buffer index 7 is common to both stages.
562const LIGHT_LIST_BINDING: u32 = 20;
563
564/// The bind-group slot the froxel grid is read through.
565const LIGHT_GRID_BINDING: u32 = 21;
566
567/// The fragment shader's screen-space occlusion texture. Mesh-only additions
568/// are buffers, so this resource does not shift their native argument table.
569const AMBIENT_OCCLUSION_BINDING: u32 = 22;
570
571/// The shared irradiance probe table, native buffer 9 in both shader modules.
572/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
573const PROBE_TABLE_BINDING: u32 = 23;
574
575/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
576/// Its logical binding stays 24; after the shared fragment buffer prefix it is
577/// native buffer 10. The raster path does not declare this storage buffer.
578const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
579
580/// The bind-group slot the split-sum `DFG` table is fetched through — how much
581/// of the light arriving at a GGX lobe that lobe hands back.
582///
583/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
584/// after the shared prefix. The fragment shader's `specular_dfg` remains at
585/// native texture 3, following `ambient_occlusion` at texture 2.
586///
587/// **An image rather than a storage buffer, and that is forced.** The table is
588/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
589/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
590/// Metal backend materialises every global into every entry point — so a row
591/// bound to the fragment stage alone would be a global the vertex stage names
592/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
593/// binding 7's `geometry` visibility.
594const SPECULAR_DFG_BINDING: u32 = 25;
595
596/// The bind-group slot §2's normal page is sampled through.
597///
598/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
599/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
600/// next index in its Metal argument table by counting the same-table entries of
601/// this layout, and Slang numbers a stage's arguments by declaration order, so
602/// the two agree only while both ascend. No mirror is needed in
603/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
604///
605/// **No sampler of its own.** The page is read through
606/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
607/// base-colour page uses, because it is sampled at the same UV over an image of
608/// the same extent. A second sampler would be a second layout entry, a second
609/// index in Metal's sampler argument table, and a second thing
610/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
611/// be identical.
612const NORMAL_PAGE_BINDING: u32 = 26;
613
614/// The bind-group slot topic 44's rung 5 reads its linearly
615/// transformed cosine table through.
616///
617/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
618/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
619/// Metal argument table by counting the same-table entries of this layout, and
620/// Slang numbers a stage's arguments by declaration order, so the two agree only
621/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
622/// needs no mirror there and no index anything already owns moves.
623///
624/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
625/// blend written out in the shader, because a hardware filter's weights are
626/// fixed-function arithmetic four rasterisers compute independently and these
627/// goldens are compared across all four.
628const LTC_TABLE_BINDING: u32 = 27;
629
630/// The bind-group slot topic 45's contact-shadow channel is
631/// read through.
632///
633/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
634/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
635/// argument table by counting the same-table entries of this layout, and Slang
636/// numbers a stage's arguments by declaration order, so the two agree only while
637/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
638/// no mirror there and no index anything already owns moves.
639///
640/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
641/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
642/// the frame on every pass that computed one.
643const CONTACT_SHADOW_BINDING: u32 = 28;
644
645/// The bind-group slot the irradiance probes' per-probe
646/// visibility maps are read through: one `Rg32Float` layer per probe.
647///
648/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
649/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
650/// Metal argument table by counting the same-table entries of this layout, and
651/// Slang numbers a stage's arguments by declaration order, so the two agree only
652/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
653/// needs no mirror there and no index anything already owns moves —
654/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
655///
656/// **A texture rather than a storage buffer, and that is forced**: the raster
657/// path's vertex stage is already at every storage buffer a WebGPU device
658/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
659///
660/// **No sampler**, like the occlusion channel and both cooked tables:
661/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
662/// out, because a hardware filter's weights are fixed-function arithmetic four
663/// rasterisers compute independently — and because `Rg32Float` is not a
664/// filterable format on WebGPU without an optional feature.
665const PROBE_VISIBILITY_BINDING: u32 = 29;
666
667/// The bind-group slot topic 43 §2's packed
668/// **metallic-roughness-occlusion** page is sampled through.
669///
670/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
671/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
672/// next index in its Metal argument table by counting the same-table entries of
673/// this layout, and Slang numbers a stage's arguments by declaration order, so
674/// the two agree only while both ascend. No mirror is needed in
675/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
676///
677/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
678/// read at the same UV over an image of the same shape as the base-colour one,
679/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
680/// Metal's sampler argument table.
681const MRO_PAGE_BINDING: u32 = 30;
682
683/// The bind-group slot topic 43 §2's **emissive**
684/// page is sampled through.
685///
686/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
687/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
688/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
689/// mirror there and no index anything already owns moves.
690const EMISSIVE_PAGE_BINDING: u32 = 31;
691
692/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
693///
694/// The table is square, and its size is a compile-time constant, so the
695/// conversion belongs here rather than as a fallible one at the upload.
696const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
697
698/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
699///
700/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
701/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
702/// what says the two tables are the same square, and each upload naming its own
703/// module is what would make a day they were not into a compile error here
704/// rather than a stretched image.
705const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
706
707/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
708///
709/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
710/// what `mesh.slang` reads on a frame drawing without
711/// [`RenderEffects::AMBIENT_OCCLUSION`].
712///
713/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
714/// this and the term is untouched. Any other value would be a silent global
715/// ambient scale.
716///
717/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
718/// direction** — the sentinel the occlusion chain writes wherever it has no
719/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
720/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
721/// direction at this pixel" are one case with one answer, and a frame drawn
722/// with the effect off is the frame this renderer drew before the channel was
723/// widened. Encoding a direction here instead would tilt every ambient term in
724/// such a frame towards one world axis.
725const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
726    0xFF,
727    ssao::BENT_NORMAL_NONE,
728    ssao::BENT_NORMAL_NONE,
729    ssao::BENT_NORMAL_NONE,
730];
731
732/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
733///
734/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
735/// what `mesh.slang` reads on a frame drawing without
736/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
737/// and the cascades have the last word alone. Any other value would be a silent
738/// global scale on the sun.
739///
740/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
741/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
742/// placeholders stand for different facts, and a day one of them wanted a
743/// different value should be an edit here rather than a search for which
744/// callers of a shared name meant which thing.
745const CONTACT_SHADOW_NONE: u8 = 0xFF;
746
747/// The one `Rg32Float` texel that occludes nothing: a mean distance of
748/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
749/// square.
750///
751/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
752/// what `mesh.slang` reads on a frame drawn before anything was captured or with
753/// `r_probe_visibility` off. No surface in any scene is further away than that,
754/// so `probe_weight` answers one for every probe and every fragment, and the
755/// grid is the unweighted trilinear blend it was before this rung — which is
756/// what makes the off position bit-identical rather than merely close.
757///
758/// Any *smaller* value would be a silent occluder: every probe in every scene
759/// would read as being behind a wall, and the whole grid would collapse onto
760/// `PROBE_OCCLUDED_WEIGHT`.
761fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
762    let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
763    let far = crcbl_shaders::probe_visibility::FAR;
764    texel[..4].copy_from_slice(&far.to_le_bytes());
765    texel[4..].copy_from_slice(&(far * far).to_le_bytes());
766    texel
767}
768
769/// The reversed-Z far plane, in the two places that have to agree about it.
770///
771/// `ssao.slang` leaves early at exactly this depth because the unprojection there
772/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
773/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
774/// the mirror is checked here — which is the only place both names are in scope.
775const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
776
777/// How many buckets a resident mesh occupies, which is **not the same on every
778/// geometry path** — the one place in this renderer the two differ in shape
779/// rather than in the call they record.
780///
781/// A flat mesh is one bucket either way. A DAG is one bucket on
782/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
783/// topic 25's per-cluster selection is that one dispatch covers
784/// several levels at once, so the run is every level's clusters end to end and
785/// the bucket's mesh id is level 0's.
786///
787/// On the two indirect tails a DAG is one bucket **per level**, because there
788/// the same plan takes a uniform cut and a level is drawn as an ordinary index
789/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
790/// selects one per instance, and a bucket is what an indexed draw of one index
791/// range *is*. See [`ForwardRenderer::level_buckets`].
792const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
793    if emit.is_mesh() { 1 } else { levels }
794}
795
796/// Every material mode this renderer routes a draw by, and the order the bucket
797/// table lays its per-mode runs of every mesh's levels down in.
798///
799/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
800/// the routing is total rather than checked: a row's mode is
801/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
802/// double-sided one, and the four combinations of them are these — so no
803/// material can carry a mode that is not in this list and no instance can
804/// scatter into a bucket that does not exist. Widening the mask means adding the
805/// mode here **and** giving it a depth pipeline in
806/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
807/// producer and the consumer of one list.
808///
809/// **A scene emits a twin per mode its own materials carry**, not one per
810/// entry here: two materials of two modes are two twins whichever two they are,
811/// and only a scene actually holding all four pays for four. The build below is
812/// where that filter is, and this module's
813/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
814const DEPTH_MODES: [u32; 4] = [
815    0,
816    mesh::GpuMaterial::ALPHA_MODE_MASK,
817    mesh::GpuMaterial::DOUBLE_SIDED,
818    mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
819];
820
821/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
822/// draw single-sided and double-sided buckets of one frame.
823///
824/// **A pipeline rather than a per-draw state, because no backend seam exposes
825/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
826/// is the precedent for why one would not be added: a raster state a recorded
827/// stream carried per draw is a state every backend has to be able to change
828/// between two indirect calls, and the portable answer to "this draw rasterises
829/// differently" is a second pipeline. Which draws take which is
830/// [`ForwardRenderer::sided_partitions`].
831///
832/// Four passes need the pair — the colour pass, the two depth-only ones and the
833/// reflective shadow map — so it is a type rather than eight fields, and the
834/// twins are built together so a renderer can never hold one without the other.
835#[derive(Clone, Copy, Debug, PartialEq, Eq)]
836struct SidedPipelines {
837    /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
838    /// every bucket of every scene that does not use `doubleSided`.
839    single: GraphicsPipelineHandle,
840    /// [`CullMode::None`]: the buckets whose material carries
841    /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED).
842    ///
843    /// Built on every scene rather than only on one that has such a material,
844    /// for [`MeshModules::depth_masked_pipeline`]'s stated reason: the modules
845    /// are released inside `build` and a pipeline built later would need them
846    /// back, which is a second shader compilation.
847    double: GraphicsPipelineHandle,
848}
849
850/// The pixel budget topic 25's descent compares a group's projected
851/// error against, unless a caller sets another with
852/// [`ForwardRenderer::set_lod_error_budget`].
853///
854/// One pixel, because that is what the metric is *for*: a level's error is how
855/// far its simplification may have moved the surface, so a budget of a pixel is
856/// the point at which a level change stops being something a viewer can see.
857/// The plan's "correct thresholds make pops sub-pixel by definition" is this
858/// number.
859const LOD_ERROR_BUDGET: f32 = 1.0;
860
861/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
862/// it holds.
863///
864/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
865/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
866/// because which one a bucket holds is the geometry path's decision and the
867/// buffer, its dynamic stride and the range the bind group names are all fixed
868/// before that decision reaches them.
869///
870/// **The bound range is the half that bites.** A range sized for the smaller
871/// block leaves the larger one's tail outside it, and a uniform read past the
872/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
873/// path's `group_stride` read back as zero and every instance descended against
874/// instance zero's LOD state.
875const DRAW_CONSTANTS_BLOCK: u64 =
876    if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
877        mesh::DRAW_CONSTANTS_SIZE as u64
878    } else {
879        crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
880    };
881
882/// How far below the budget an already-expanded group is held before it
883/// collapses again — topic 25's "switch-up and switch-down differ",
884/// as a fraction of [`LOD_ERROR_BUDGET`].
885///
886/// A ratio and not an offset because the band has to scale with the budget: a
887/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
888/// one. A fifth of the budget is a deadband a camera has to move decisively out
889/// of, and one a camera drifting along a boundary never leaves — which is the
890/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
891/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
892/// the setting that shows the band is what stops the flicker.
893const LOD_HOLD_RATIO: f32 = 0.8;
894
895/// How much larger than the camera's the pixel budget a shadow cascade selects
896/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
897/// selects +1/+2 coarser levels — casters are cheap where it never shows".
898///
899/// # A budget factor, because a level is not a parameter of the rule
900///
901/// The descent compares a group's projected error to a pixel budget; it never
902/// names a level. So "one or two levels coarser" is an *intent*, and the budget
903/// that produces it is the setting — and the two do not convert, because how far
904/// apart two levels' errors are is a property of the mesh. The committed dunes
905/// DAG is the demonstration: the step from one level's error to the next is
906/// several times larger in the middle of that hierarchy than at its base, and
907/// across its top levels there is no step at all — they report one error and are
908/// never separately selected by any budget. A bias expressed in levels would
909/// mean something different at each of those. `cook-clusters` prints the per
910/// level errors it built.
911///
912/// Four, then, is two doublings of the budget: enough that a caster is drawn
913/// coarser than the same object is in the colour pass, and small enough to stay
914/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
915/// the atlas is read through a comparison sampler with linear filtering, so an
916/// edge arrives already spread over neighbouring texels — and that the atlas
917/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
918/// samples it.
919///
920/// # Why one number, applied to the whole pass
921///
922/// **A cut is a cover only while expansion is monotone up the DAG**, and this
923/// scaling is what keeps it so. Multiplying both budgets by one positive
924/// constant leaves the rule in
925/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
926/// that module's induction turns on the projected error being monotone up the
927/// DAG rather than on what the constants are — so the shadow pass's cut is a
928/// cover for exactly the reason the camera's is. A bias that varied by cluster,
929/// by group, by level or by cascade would not be: two groups on one branch would
930/// be judged against different budgets, and a child expanding under an
931/// unexpanded parent is a hole.
932///
933/// Being larger than one also makes the shadow pass's expanded set a **subset**
934/// of the colour pass's, since the two now select from one eye at one scale: a
935/// group over `k` times the budget is over the budget. So the shadow cut is
936/// never finer than the camera's anywhere, which is the property
937/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
938/// and asserts.
939pub const SHADOW_LOD_BIAS: f32 = 4.0;
940
941/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
942/// light**, whatever kind of light it is.
943///
944/// Topic 18's fourth decision, as a number. A point light's six faces share the
945/// light's sphere — which is what a cull tests against — so they share one
946/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
947/// viewport. Six generators per light would be six copies of
948/// [`TileBuffers::group_state`], which is where the cost of one is written down.
949const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
950
951/// How many shadow *views* there are: one per cascade, and one per face of every
952/// light slot.
953///
954/// A view is what has a matrix, so it is what has a frame-block copy, a bind
955/// group and a cut of its own — while a *tile* is where a view lands in the
956/// atlas and a *cull* is which visible set it draws. The three were one number
957/// until a light could own six tiles.
958///
959/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
960/// point or a spot, because a bind group names its buffers when it is created
961/// and the kind of light holding a slot changes per frame. A spot uses face 0's
962/// view and the other five are never recorded — they cost a uniform buffer and a
963/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
964/// would cost.
965const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
966
967/// Cascade 0's view, which is the one the irradiance probes'
968/// reflective shadow map is drawn through.
969///
970/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
971/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
972/// [`shadow::CASCADES`], so it is not the function to reach for here.
973const CASCADE_ZERO_VIEW: usize = 0;
974
975const _: () = assert!(
976    CASCADE_ZERO_VIEW < shadow::CASCADES,
977    "cascade 0's view has to be one of the cascades' own, not a light slot's"
978);
979
980/// Which view is face `face` of light slot `slot`.
981const fn shadow_view(slot: usize, face: usize) -> usize {
982    shadow::CASCADES + slot * shadow::POINT_FACES + face
983}
984
985/// Which cull light slot `slot` draws from.
986const fn shadow_cull(slot: usize) -> usize {
987    shadow::CASCADES + slot
988}
989
990/// One punctual shadow face this frame draws into the punctual reflective
991/// shadow map, and everything both halves of the updater need of it.
992///
993/// The irradiance probes' punctual producer. It carries no
994/// matrix and no visible set: a face's transform is already in the uniform block
995/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
996/// slot's cull generated for the atlas — which is what makes this rung cost no
997/// second cull and no second matrix.
998#[derive(Clone, Copy, Debug)]
999struct PunctualFace {
1000    /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1001    /// of the bind group whose block holds that face's own `view_proj`.
1002    view: usize,
1003    /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1004    /// answer for the slot this face belongs to.
1005    cull: usize,
1006    /// Which face of its light this is, and so — where the light's cull tagged
1007    /// its casters by face — which draw region it draws.
1008    face: usize,
1009    /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1010    /// rectangle the pass sets its viewport to *and* the one the gather reads
1011    /// this face's texels out of.
1012    tile: shadow::TileRect,
1013    /// The light this is a face of, as the gather weighs its texels.
1014    producer: PunctualProducer,
1015}
1016
1017/// The draw region face `face` of a light draws: its own region where the
1018/// light's cull tagged casters by face, and region 0 — every survivor — where it
1019/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1020fn face_region(by_face: bool, face: usize) -> u32 {
1021    if by_face {
1022        crcbl_shaders::draw_gen::FACE_REGION_BASE
1023            + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1024    } else {
1025        0
1026    }
1027}
1028
1029/// One light's row in the gather's producer table, for the face standing at
1030/// `tile`.
1031///
1032/// **Built out of the light's own row**, which is the one place a light becomes
1033/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1034/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1035/// than a second reading of the same fields that could round or widen
1036/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1037/// because a producer occludes through nothing: the gather gates a texel with
1038/// the probe's own visibility map, not with the light's.
1039fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1040    let row = light.row(None);
1041    PunctualProducer {
1042        position: [row.position[0], row.position[1], row.position[2]],
1043        radius: row.position[3],
1044        color: [row.color[0], row.color[1], row.color[2]],
1045        cos_outer: row.direction[3],
1046        axis: [row.direction[0], row.direction[1], row.direction[2]],
1047        cos_inner: row.cos_inner,
1048        origin: [tile.x, tile.y],
1049        side: tile.side,
1050        kind: row.kind,
1051    }
1052}
1053
1054const _: () = assert!(
1055    SHADOW_CULLS == shadow::GROUPS,
1056    "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1057     dispatches, and two different counts would schedule a group nothing draws"
1058);
1059
1060/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1061/// generates from `SV_VertexID`. No geometry is bound.
1062const TILE_CLEAR_VERTICES: u32 = 3;
1063
1064const _: () = assert!(
1065    crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1066    "the stage that resets one tile writes a depth the attachment's own clear \
1067     does not, so a held tile and a cleared one would answer differently where \
1068     nothing was drawn"
1069);
1070
1071/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1072///
1073/// The rectangle the allocator handed out — the same one the fragment stage
1074/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1075/// the whole atlas before the pass body ran, and this is what narrows it: the
1076/// same clip-space matrix mapped into a different part of the image, and for a
1077/// point light six different matrices into six of them off one visible set.
1078///
1079/// A function rather than the two calls inline, because the tile clear and the
1080/// draws that follow it walk the same tiles and a viewport set one way for one
1081/// of them would clear a rectangle nothing draws into.
1082fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1083    let rect = Rect2d {
1084        x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1085        y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1086        width: tile.side,
1087        height: tile.side,
1088    };
1089    encoder.set_viewport(&Viewport {
1090        x: rect.x as f32,
1091        y: rect.y as f32,
1092        width: rect.width as f32,
1093        height: rect.height as f32,
1094        ..Viewport::from_size(rect.width, rect.height)
1095    });
1096    encoder.set_scissor(&rect);
1097}
1098
1099/// What the last executed graph left the renderer-owned import `image` in, as an
1100/// [`ImportedImage::initial`].
1101///
1102/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1103/// fallback around one.** The ledger records what a graph *executed*, so nothing
1104/// recorded means nothing has run against this image on this pool — a freshly
1105/// created image before its first frame, and an image whose pool has been
1106/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1107/// barrier has moved is in. It is also the only declaration that lets the
1108/// incoming barrier hand the image a layout at all: every other state names an
1109/// old layout the image is not in.
1110///
1111/// The reason this is a lookup and not a field the renderer advances: a graph is
1112/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1113/// stepped forward while the passes were declared would have moved for a frame
1114/// that never reached the GPU, and the next frame's declaration — now wrong —
1115/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1116/// it through. One source of truth is what removes that gap rather than
1117/// narrowing it.
1118fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1119    pool.imported_image_use(image)
1120        .unwrap_or(ResourceState::Undefined)
1121}
1122
1123/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1124/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1125/// the debug draw layer, the tonemap, the ground grid and the
1126/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1127/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1128/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1129///
1130/// [`AtlasView::PASSES`] has no term of its own and is inside
1131/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1132/// viewer and the resolve are never both recorded.
1133///
1134/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1135/// ground grid's terms: all three are off unless a scene's
1136/// [`ProbeUpdate`] asks for them, and a bound short
1137/// of the frame that does ask would silently stop timing its last pass. The
1138/// punctual map is a pass whether or not the frame has a punctual light to draw
1139/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1140/// gather reads on a frame that lights none.
1141///
1142/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1143/// [`LightGrid`], which is why this is the only count written here rather than
1144/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1145/// though a device that refused the readback records one fewer: this is a
1146/// ceiling, and one that came up short would silently stop timing the last pass
1147/// of every frame. It is the **all-effects-on** count for the same reason: a
1148/// frame that switched one off records fewer, and a bound that tracked the
1149/// toggles would have to be re-sized whenever they moved.
1150///
1151/// The ground grid is counted on the same terms, even though it is off by
1152/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1153/// records one more pass, and a bound short of that would silently stop timing
1154/// the last pass of every frame it drew. The render-scale upscale is the second
1155/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1156/// therefore absent until a caller moves it. The debug draw layer is the third,
1157/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1158///
1159/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1160/// counts**: a chain's length is a function of the target's extent — see
1161/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1162/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1163/// either an extent or a console is known. The frame that lands on
1164/// it is a large one with bloom switched on; every smaller frame records fewer,
1165/// exactly as a frame with a free shadow slot does.
1166const RENDER_PASSES: u32 = 8
1167    // The occlusion cull's late depth prepass and its farthest pyramid, on the
1168    // ground grid's terms: off unless a caller switches the cull on.
1169    + 1
1170    + OcclusionPyramid::PASSES
1171    + DebugDraw::MAX_PASSES
1172    + ProbeGather::PASSES
1173    + Ssao::MAX_PASSES
1174    + ContactShadows::PASSES
1175    + Hiz::PASSES
1176    + Ssr::PASSES
1177    + Volumetric::PASSES
1178    + Water::PASSES
1179    + Grass::PASSES
1180    + Exposure::PASSES
1181    + Bloom::MAX_PASSES
1182    + POST_TONEMAP_PASSES
1183    + Upscale::PASSES;
1184
1185/// What the frame's one resolve slot costs at its widest: the larger of the two
1186/// antialiasing tiers.
1187///
1188/// **The larger and not the sum**, because the two are never both recorded —
1189/// [`RenderEffects::CMAA2`] carries that in writing and
1190/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1191/// all-effects-on count as well as the ceiling, which is the property
1192/// [`RENDER_PASSES`] needs from every term it adds up.
1193///
1194/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1195const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1196    Fxaa::PASSES
1197} else {
1198    Cmaa2::PASSES
1199};
1200
1201/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1202/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1203/// filtering it.
1204///
1205/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1206/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1207/// antialiasing tiers off for every debug view, and the atlas viewer records
1208/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1209/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1210/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1211/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1212/// is what holds the arithmetic to a frame that was actually recorded.
1213const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1214    RESOLVE_PASSES
1215} else {
1216    AtlasView::PASSES
1217};
1218
1219/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1220///
1221/// The smallest fraction of the target extent a frame may be drawn at.
1222///
1223/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1224/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1225/// stops being a picture of the scene and starts being a picture of the filter,
1226/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1227/// engine's resolution slider bottoms out somewhere; this is where this one
1228/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1229/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1230/// draw.
1231pub const MIN_RENDER_SCALE: f32 = 0.25;
1232
1233/// The anisotropy the base-colour page is sampled with where the device grants
1234/// [`Features::SAMPLER_ANISOTROPY`].
1235///
1236/// Eight, which is topic 43's filtering rung's
1237/// default and the figure current engines default their own slider to: past it
1238/// the footprint's long axis is already sampled finely enough that sixteen is
1239/// invisible at a grazing angle and costs the same again in fetches. A device
1240/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1241/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1242/// device without the feature gets one, which is the value that turns it off.
1243pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1244
1245/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1246/// because these are the only draws in this file whose instance and triangle
1247/// counts the CPU knows exactly — everything else here goes through an indirect
1248/// call.
1249const FULLSCREEN_DRAWS: u64 = 1;
1250
1251/// How many full-screen passes a frame drawing `effects` at `extent` records:
1252/// the tonemap, always, and each switched-on effect's passes beside it.
1253///
1254/// **A function of the frame rather than a constant**, since
1255/// topic 48's toggles: it was the tonemap alone, then
1256/// five, and either written down is a number that stops matching the frame. The
1257/// tonemap is the one that is not conditional — a frame has to reach the
1258/// swapchain.
1259///
1260/// **`extent` is here because the bloom chain's length depends on it** — see
1261/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1262/// size. A frame too small for even one chain level records none of them, which
1263/// is the same arithmetic as the toggle being off. It is the **internal** render
1264/// extent for the same reason: that is the extent every one of these passes runs
1265/// at.
1266///
1267/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1268/// resolution, not an effect — so it arrives as its own argument, on the ground
1269/// grid's terms. It is false on every frame at full render scale, which is the
1270/// frame this function counted before the knob existed.
1271///
1272/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1273/// variable rather than an effect bit, and it is the caller's job to read it
1274/// **once** for the frame. Reading it here as well would be a second read that
1275/// a command landing between the two could disagree with, and the disagreement
1276/// would be a counter describing a frame that was not recorded.
1277fn fullscreen_passes(
1278    effects: RenderEffects,
1279    extent: (u32, u32),
1280    upscaling: bool,
1281    ssao_blurs: u32,
1282) -> u64 {
1283    let mut passes = 1;
1284    if upscaling {
1285        passes += Upscale::PASSES as u64;
1286    }
1287    if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1288        passes += u64::from(Ssao::passes(ssao_blurs));
1289    }
1290    if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1291        passes += u64::from(ContactShadows::PASSES);
1292    }
1293    if effects.contains(RenderEffects::REFLECTIONS) {
1294        // The march's pair, and the pyramid it climbs — which is as long as the
1295        // extent allows and is zero on a frame too small to halve once, so this
1296        // term is the only one here that is not a constant per effect.
1297        passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1298    }
1299    if effects.contains(RenderEffects::BLOOM) {
1300        passes += u64::from(Bloom::passes_for(extent));
1301    }
1302    // **One resolve slot, and the higher tier takes it.** Both bits set is a
1303    // frame with CMAA2's passes and no FXAA pass at all, which is what
1304    // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1305    // an `else if` rather than two independent terms.
1306    //
1307    // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1308    // function counts is full-screen *draws*, and two of that tier's three
1309    // passes are compute dispatches. [`crate::exposure`]'s three are left out
1310    // of this arithmetic for the same reason.
1311    if effects.contains(RenderEffects::CMAA2) {
1312        passes += Cmaa2::FULLSCREEN_PASSES;
1313    } else if effects.contains(RenderEffects::ANTIALIASING) {
1314        passes += Fxaa::PASSES as u64;
1315    }
1316    if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1317        // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1318        // scatter and the column scan are compute dispatches; what this
1319        // function counts is full-screen *draws*, and only the composite is
1320        // one. An atmosphere runs the composite without the effect, and the
1321        // caller adds that one — it is not an effect bit.
1322        passes += u64::from(Volumetric::COMPOSITE_PASSES);
1323    }
1324    // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1325    // entry here: all three of its passes are compute dispatches, and the
1326    // exposure they measure reaches the picture through the tonemap's own draw.
1327    passes
1328}
1329
1330/// The budget an **orthographic** camera selects under: one no group satisfies,
1331/// so every group expands and the base level is drawn whole.
1332///
1333/// The metric divides a projected error by the distance to the group's sphere,
1334/// and an orthographic projection has no such falloff — see
1335/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1336/// Drawing the finest level is the conservative answer and the honest one; a
1337/// distance term invented for a projection that has none would be neither.
1338///
1339/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1340const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1341
1342/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1343/// [`SkinnedMesh`] where the description's mesh index would be.
1344///
1345/// The mesh is a reservation rather than an index because a skinned draw is not
1346/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1347/// fills, and which of the reservation's two runs that is changes every frame.
1348/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1349/// here carries a parity.
1350#[derive(Clone, Copy, Debug)]
1351pub struct SkinnedInstanceDesc<'a> {
1352    /// The region this object is drawn out of, from
1353    /// [`ForwardRenderer::reserve_skinned`].
1354    pub mesh: &'a SkinnedMesh,
1355    /// Which [`SceneDesc::materials`] row it shades through, exactly as
1356    /// [`InstanceDesc::material`].
1357    pub material: usize,
1358    /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1359    ///
1360    /// The joints are **not** in it — a palette carries each joint's global
1361    /// transform times its inverse bind matrix, and this is what puts the
1362    /// deformed mesh in the world. See
1363    /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1364    pub transform: Mat4,
1365}
1366
1367/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1368///
1369/// **The two projections are cached beside the LUT rather than taken per
1370/// frame**, which is what makes a frame under a sun that has not moved do no
1371/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1372/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1373/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1374/// rows per frame, because those are writes into the frame's own ring slots
1375/// rather than projections.
1376#[derive(Clone, Debug)]
1377struct PresentedSky {
1378    /// The normalised sun and viewpoint the LUT was marched for, which is what
1379    /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1380    /// against.
1381    parameters: crcbl_shaders::atmosphere::Atmosphere,
1382    /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1383    /// samples.
1384    view: SkyView,
1385    /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1386    /// pass's block carries.
1387    gradient: crcbl_shaders::sky::SkyGradient,
1388    /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1389    irradiance: crcbl_shaders::probe::GpuProbe,
1390}
1391
1392impl PresentedSky {
1393    /// Takes both projections from a LUT that has just been marched.
1394    fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1395        Self {
1396            parameters,
1397            gradient: view.gradient_fit(),
1398            irradiance: view.irradiance(),
1399            view,
1400        }
1401    }
1402}
1403
1404/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1405/// secondary view begun after it writes its blocks against the same sun, light
1406/// rows and shadow matrices the primary camera's were written against.
1407///
1408/// Everything here is decided by the primary camera and drawn once: the rows
1409/// carry the shadow tiles the primary camera's selection handed out, and the
1410/// cascades are fitted to its frustum. A secondary view samples the maps those
1411/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1412#[derive(Clone, Debug)]
1413struct FrameScene {
1414    light: DirectionalLight,
1415    rows: Vec<crcbl_shaders::light::GpuLight>,
1416    cascades: Cascades,
1417    shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1418    light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1419    atlas_rects: [[f32; 4]; shadow::TILES],
1420}
1421
1422/// The bucket and level tables a scene's generators are all built from, kept
1423/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1424/// returned.
1425#[derive(Debug)]
1426struct DrawTables {
1427    bucket_meshes: Vec<u32>,
1428    bucket_clusters: Vec<u32>,
1429    bucket_cluster_bases: Vec<u32>,
1430    mesh_levels: Vec<level_select::MeshLevels>,
1431    level_groups: Vec<level_select::LevelGroup>,
1432    level_meshes: Vec<u32>,
1433    instance_capacity: u32,
1434    light_capacity: u32,
1435}
1436
1437/// The primary frame attachments an overlay may use before antialiasing and
1438/// render-scale reconstruction.
1439///
1440/// `display` is the display-space image the tonemap and post-tonemap overlays
1441/// have written. `depth` is the matching internal scene depth image, retained
1442/// as a read-only attachment for depth-tested overlays. Both have
1443/// `internal_extent` dimensions.
1444#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1445pub struct ForwardOverlayTargets {
1446    pub display: ImageId,
1447    pub depth: ImageId,
1448    pub internal_extent: (u32, u32),
1449}
1450
1451/// Everything the forward frame owns, created once.
1452#[derive(Debug)]
1453pub struct ForwardRenderer {
1454    // Geometry: the global pools, and the meshes resident in them. Each
1455    // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1456    // for a mesh whose upload has completed — so there is no way to reach a
1457    // draw below with a mesh the GPU has not received.
1458    pool: MeshPool,
1459    /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1460    /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1461    /// [`buckets_for`] says is a property of the path as well as of the scene.
1462    ///
1463    /// **The whole of what the CPU still says per draw.** Everything else a
1464    /// draw needs — how many instances, which indices, which vertices — is in
1465    /// the arguments the GPU wrote or in a table it resolves them through.
1466    bucket_constants: Vec<u32>,
1467    /// What one draw region adds to a bucket's offsets — the same for every
1468    /// generator this renderer built, because they share one bucket table.
1469    region_step: RegionStep,
1470    /// The material mode of each bucket, in the same order — the copy the
1471    /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1472    /// against.
1473    ///
1474    /// What it is for: the depth prepass and the shadow atlas partition their
1475    /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1476    /// scene with a cutout in it keeps the vertex-only stage. See
1477    /// [`ForwardRenderer::depth_partitions`].
1478    ///
1479    /// All zeroes for a scene whose materials are all opaque — every demo and
1480    /// every golden in this tree — which is exactly one bucket per mesh and one
1481    /// partition, byte for byte the stream they recorded before modes existed.
1482    bucket_modes: Vec<u32>,
1483
1484    // The instance array, and the objects' places in it. Nothing here is
1485    // rewritten per frame: the pool uploads what a caller changed and nothing
1486    // else, so a scene nobody moved costs no transfer at all.
1487    instances: InstancePool,
1488    /// The mesh table id of each description mesh's **level 0**, in
1489    /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1490    /// resolves through.
1491    ///
1492    /// Level 0's and not the whole run, because that is the entry an instance
1493    /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1494    /// levels approximate the same surface inside the same box. The coarser
1495    /// entries are resident and no instance names one — a cluster reaches its
1496    /// own level's vertices through
1497    /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1498    /// uniform cut reaches them through the bucket table.
1499    ///
1500    /// Kept rather than resolved per call because every write of an instance
1501    /// writes the whole record, and an instance that lost its mesh id would
1502    /// resolve to entry 0 — which is a mesh, and the wrong one.
1503    mesh_ids: Vec<u32>,
1504    /// Level 0's pool handle for each description mesh that can be skinned, in
1505    /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1506    /// [`ResidentMesh::skinnable`].
1507    ///
1508    /// What [`ForwardRenderer::reserve_skinned`] resolves an
1509    /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1510    /// there is no way back from a table id to the handle that owns it: an id is
1511    /// a bare index and a [`MeshHandle`] is generational.
1512    skinnable_meshes: Vec<Option<MeshHandle>>,
1513    /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1514    /// two base vertices it alternates between.
1515    ///
1516    /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1517    /// at the half of its region *this* frame's dispatch fills. Entries whose
1518    /// instance has gone stale are dropped as it walks, so
1519    /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1520    /// skinning.
1521    skinned_instances: Vec<SkinnedInstance>,
1522
1523    /// §3.2's material table, and the rows in it.
1524    ///
1525    /// One buffer shared by every frame's bind group, not a ring — see
1526    /// [`crate::material_table`], which is where that decision lives.
1527    materials: MaterialTable,
1528    /// The table row of each description material, in [`SceneDesc::materials`]
1529    /// order — what an [`InstanceDesc::material`] index resolves through.
1530    ///
1531    /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1532    /// whole record, and an instance that lost its material id would name row 0
1533    /// by accident, which is a material and only *happens* to be the untinted
1534    /// one.
1535    material_ids: Vec<u32>,
1536    /// Topic 50's irradiance grid, row by row.
1537    ///
1538    /// One buffer shared by every frame's bind group, like the material table
1539    /// and for a stronger version of its reason: a probe is written when the
1540    /// scene is made resident and there is no call that rewrites one. See
1541    /// [`crate::probe`].
1542    probes: ProbeTable,
1543    /// Where those rows are, which rides in the frame block rather than in a
1544    /// buffer of its own — a fragment needs it before it knows which row to
1545    /// fetch.
1546    ///
1547    /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1548    /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1549    /// grid of nothing, which is what a description with no probes leaves here
1550    /// and what makes the whole feature add zero.
1551    probe_volume: crcbl_shaders::probe::ProbeVolume,
1552    /// §3.2's texture side: one `D2Array` image whose layers the material rows
1553    /// index. One page, bound once, for every material — see the module docs on
1554    /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1555    /// a bindless descriptor array.
1556    base_color_page: UploadedTexture,
1557    /// §2's second page: one `D2Array` image of tangent-space normals, whose
1558    /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1559    /// indexes.
1560    ///
1561    /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1562    /// through the same UV and the same sampler, and **created linear** — see
1563    /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1564    /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1565    /// base-colour one is what the caller wrote and what this holds.
1566    normal_page: UploadedTexture,
1567    /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1568    /// roughness and metallic, whose layers
1569    /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1570    /// indexes.
1571    ///
1572    /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1573    /// same UV and the same sampler, and **created linear** — see
1574    /// [`MRO_PAGE_FORMAT`].
1575    mro_page: UploadedTexture,
1576    /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1577    /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1578    ///
1579    /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1580    /// **created sRGB** rather than linear, because an emissive texel is a
1581    /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1582    emissive_page: UploadedTexture,
1583    /// Each [`PageKind`]'s image size in texels, as a width and a height,
1584    /// indexed by [`PageKind::index`].
1585    ///
1586    /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1587    /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1588    /// named no layer of, which is the placeholder's extent and not the
1589    /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1590    /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1591    /// to the graph and an [`ImportedImage`] names an extent, and the
1592    /// description they came from is the caller's, read once at build.
1593    page_extents: [(u32, u32); PageKind::ALL.len()],
1594    /// The sampler the page is read through.
1595    base_color_sampler: SamplerHandle,
1596    /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1597    /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1598    anisotropy: f32,
1599    /// How many layers each [`PageKind`]'s page holds, indexed by
1600    /// [`PageKind::index`] — zero for a kind the description named none of.
1601    ///
1602    /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1603    /// replacement to, so every material row's layer number goes on naming the
1604    /// same texture.
1605    page_layers: [usize; PageKind::ALL.len()],
1606    /// `[frame]`: the page sampler and the four page views that slot's
1607    /// mesh-layout groups name.
1608    ///
1609    /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1610    /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1611    /// so this is what says which slots still name a sampler
1612    /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1613    /// [`replace_page`](ForwardRenderer::replace_page) did.
1614    slot_pages: Vec<PageBindings>,
1615    /// Page samplers and pages replaced while some slot may still name them.
1616    /// Each is destroyed as the last slot naming it moves off, or at
1617    /// [`destroy`](ForwardRenderer::destroy).
1618    retired_pages: Vec<RetiredPage>,
1619
1620    /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1621    /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1622    ///
1623    /// Kept rather than recomputed because the shadow pass's share is the number
1624    /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1625    /// out from topic 45's tile allocation and nothing outside
1626    /// it can restate without becoming the second copy that drifts.
1627    recorded_draws: u64,
1628    /// Which call the forward pass records — the device's [`GeometryPath`],
1629    /// resolved once.
1630    emit: EmitTail,
1631    /// The most buckets one call of the geometry passes draws, or `None` where
1632    /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1633    /// build with [`emit`](Self::emit) and for its reason.
1634    range_limit: Option<u32>,
1635    /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1636    /// tails draw the same geometry out of the index pool and read none of
1637    /// this. `None` is therefore the ordinary state on most devices rather than
1638    /// a failure, and it is also what makes a fall-through impossible — see
1639    /// [`ForwardRenderer::geometry_path`].
1640    clusters: Option<ClusterPool>,
1641    /// Whether the mesh pipeline was built with §3.5's amplification stage in
1642    /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1643    /// what it means is written down.
1644    culls_clusters: bool,
1645    /// Where each description mesh's clusters are in
1646    /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1647    /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1648    /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1649    mesh_clusters: Vec<ClusterRange>,
1650    /// The bucket each level of each description mesh draws through, finest
1651    /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1652    /// [`ForwardRenderer::level_buckets`].
1653    ///
1654    /// **The run for the scene's first material mode**, which is `OPAQUE`
1655    /// wherever the scene has an opaque material at all: the table is every
1656    /// mesh's levels once per mode the scene holds, mode by mode, and this
1657    /// names a mesh's levels in the first of those runs. See
1658    /// [`ForwardRenderer::bucket_modes`].
1659    mesh_level_buckets: Vec<Vec<u32>>,
1660    /// The pixel budget topic 25's descent compares a group's
1661    /// projected error against. [`LOD_ERROR_BUDGET`] until
1662    /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1663    lod_error_budget: f32,
1664    /// How far below that an expanded group is held before it collapses again.
1665    /// [`LOD_HOLD_RATIO`] until
1666    /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1667    lod_hold_ratio: f32,
1668    /// The same three numbers the shadow cascades selected under, which is
1669    /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1670    /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1671    ///
1672    /// Kept beside the camera's for its reason: a reader comparing the two cuts
1673    /// takes both pairs from here rather than re-deriving the bias, which would
1674    /// be comparing two copies of one arithmetic instead of two selections.
1675    shadow_lod_params: [f32; 3],
1676
1677    /// The lights a caller set beside the sun, as
1678    /// [`ForwardRenderer::set_lights`] was handed them.
1679    ///
1680    /// Kept rather than converted on the way in, because a row is the *frame's*
1681    /// artefact: the sun arrives per frame at
1682    /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1683    /// frame uploads cannot be assembled until then.
1684    extra_lights: Vec<Light>,
1685
1686    /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1687    /// alignment apart. Shared by every frame's bind group rather than ringed,
1688    /// because nothing rewrites it after `build`: a mesh's base vertex and an
1689    /// object's instance index are decided when the pools allocate them.
1690    draw_constants: BufferHandle,
1691    /// The camera's resources and history — see [`view`], which is where the
1692    /// line between a camera's state and the scene's is drawn.
1693    primary: View,
1694    /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1695    /// [`ViewId::index`] less one — a free id is `None`.
1696    views: Vec<Option<View>>,
1697    /// The tables a view's generator is built from — see [`DrawTables`].
1698    draw_tables: DrawTables,
1699    /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1700    /// say which frame it was last begun for — see [`View::begun`].
1701    frame_serial: u64,
1702    /// The frame the last `begin_frame` opened, for
1703    /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1704    frame_scene: Option<FrameScene>,
1705    /// Which frame-in-flight slot is current. Set from
1706    /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1707    /// uniform ring and the instance ring cannot drift apart.
1708    frame: usize,
1709
1710    mesh_layout: BindGroupLayoutHandle,
1711    mesh_pipeline_layout: PipelineLayoutHandle,
1712    mesh_pipeline: SidedPipelines,
1713    /// [`ForwardRenderer::mesh_pipeline`] again in
1714    /// [`PolygonMode::Line`], for
1715    /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1716    ///
1717    /// [`None`] until a caller first switches the view on — the ground grid's
1718    /// arrangement exactly, and for its reason: a second pipeline compiled at
1719    /// build would be paid for by every sample, golden and headless run that
1720    /// never asks for a wireframe, which is all of them. Once built it is kept,
1721    /// because switching the view off is
1722    /// [`ForwardRenderer::wireframe_on`] and not a release.
1723    ///
1724    /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1725    /// does not disable culling: a single-sided wireframe drawn over a
1726    /// double-sided bucket would leave a surface out of the debug view that the
1727    /// shaded frame beside it draws, which is a view of the document that
1728    /// disagrees with the document.
1729    wireframe_pipeline: Option<SidedPipelines>,
1730    /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1731    /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1732    /// default**: a wireframe is a tool's view of a document, and every sample
1733    /// and every golden image predates it.
1734    wireframe_on: bool,
1735    /// The occlusion and small-feature culls a caller asked for — see
1736    /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1737    occlusion_culling: OcclusionCulling,
1738    /// Whether a point light's six faces cull separately — see
1739    /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1740    point_face_culls: bool,
1741    /// What a test asked every shadow view's uploaded block to be rewritten
1742    /// with — see
1743    /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1744    /// [`None`] outside a test.
1745    shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1746    /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1747    /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1748    /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1749    /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1750    ///
1751    /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1752    /// exactly: it is a tool's view of a document, and every sample and every
1753    /// golden image predates it.
1754    ///
1755    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1756    normals_view: bool,
1757
1758    /// The exponential height fog the colour pass composites over its
1759    /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1760    ///
1761    /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1762    /// terms: a caller who never asks for fog draws the frame this renderer
1763    /// drew before the feature existed, and exactly that frame — the shader's
1764    /// composite is an identity at zero density rather than an interpolation
1765    /// that nearly is.
1766    fog: Fog,
1767
1768    /// The gradient sky whose irradiance the colour pass adds to the ambient
1769    /// term — see [`set_sky`](ForwardRenderer::set_sky).
1770    ///
1771    /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1772    /// gradient projects to coefficients that are all zero, so the three dot
1773    /// products the fragment stage adds are zero and no frame drawn before a
1774    /// sky existed moves.
1775    sky: Sky,
1776    /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1777    /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1778    ///
1779    /// `None` by default, so a renderer nobody calls that on is the renderer it
1780    /// was.
1781    atmosphere: Option<Atmosphere>,
1782    /// The marched sky-view LUT this renderer is drawing, with the parameters
1783    /// it was marched for and the projections taken from it.
1784    ///
1785    /// **Cached against the parameters rather than rebuilt per frame**, because
1786    /// the march is tens of milliseconds of CPU and the sun in most frames has
1787    /// not moved. The stored parameters are the *normalised* ones the shader
1788    /// crate takes, so a caller handing over the same sun spelled two lengths
1789    /// does not force a rebuild.
1790    ///
1791    /// This is the LUT a frame is **drawn from**, which is not the one being
1792    /// marched: see [`Self::sky_view_build`].
1793    sky_view: Option<PresentedSky>,
1794    /// The march in flight, when the sun has moved away from
1795    /// [`Self::sky_view`]'s.
1796    ///
1797    /// [`ForwardRenderer::refresh_sky_view`] steps it
1798    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1799    /// [`Self::sky_view`] when it finishes.
1800    ///
1801    /// **The host side is where the double buffer is**: the LUT being drawn and
1802    /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1803    /// device ring is untouched. Putting the stripe on the device instead would
1804    /// mean writing part of a ring slot per frame, and that ring's slots are
1805    /// written whole precisely because each is a frame in flight — a partial
1806    /// write would have to track, per slot, which rows of *which* sun that slot
1807    /// already holds, which is bookkeeping the host copy does not need at all.
1808    sky_view_build: Option<SkyViewBuild>,
1809
1810    /// Whether the colour pass tints each cluster by its DAG level instead of
1811    /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1812    ///
1813    /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1814    /// because one uniform lane carries both switches and the fragment stage
1815    /// tests the LOD threshold first. `crcbl_shaders`'
1816    /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1817    /// order true.
1818    lod_view: bool,
1819
1820    /// Whether the colour pass shades each cluster by the projected error the
1821    /// LOD selection judged it on, instead of shading it or tinting it — see
1822    /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1823    ///
1824    /// **Wins over both [`lod_view`](Self::lod_view) and
1825    /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1826    /// reason: one uniform lane carries all three switches and the shaders test
1827    /// the outermost threshold first. `crcbl_shaders`'
1828    /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1829    /// order true, and
1830    /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1831    /// holds this side to it.
1832    heatmap: bool,
1833
1834    /// Whether the colour pass draws the ambient-occlusion channel as grey
1835    /// instead of shading — see
1836    /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1837    ///
1838    /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1839    /// for its reason: one uniform lane, outermost threshold first.
1840    /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1841    /// what keeps that order true, and
1842    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1843    /// this side to it.
1844    occlusion_view: bool,
1845
1846    /// Whether the colour pass draws the motion vector instead of shading — see
1847    /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1848    ///
1849    /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1850    /// terms and for its reason: one uniform lane, outermost threshold first.
1851    /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1852    /// is what keeps that order true, and
1853    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1854    /// this side to it.
1855    motion_view: bool,
1856    /// Whether the colour pass draws the occlusion channel's bent direction
1857    /// instead of shading — see
1858    /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1859    ///
1860    /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1861    /// terms: it is the outermost sentinel in the lane, and
1862    /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1863    /// is what holds the shader's branch order to it.
1864    bent_normal_view: bool,
1865
1866    /// Whether the colour pass tints the shaded picture by the cascade each
1867    /// sun-lit fragment's shadow was sampled from — see
1868    /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1869    ///
1870    /// **Loses to every other view**, which is the opposite of every field
1871    /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1872    /// replaces the shaded picture and this one multiplies it, so a frame drawing
1873    /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1874    /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1875    /// holds the shader to the same order, from the other end of the lane.
1876    cascade_view: bool,
1877
1878    /// Whether the frame draws the shadow atlas over the finished picture — see
1879    /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1880    ///
1881    /// **Not a lane of the frame block**, unlike every field above: this view is
1882    /// a pass rather than a branch in `mesh.slang`, so what reads this is
1883    /// [`ForwardRenderer::add_passes`] deciding whether to record
1884    /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1885    /// [`cascade_view`](Self::cascade_view) — see
1886    /// [`ForwardRenderer::debug_view`].
1887    atlas_view: bool,
1888
1889    /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1890    /// topic 25's selection from, when that is not the camera's own
1891    /// eye — see
1892    /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1893    ///
1894    /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1895    /// every frame the engine has drawn so far did: the eye handed to
1896    /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1897    /// never sets this writes the parameter block it wrote before this field
1898    /// existed.
1899    ///
1900    /// **Not a [`DebugView`]**, and deliberately: the three views are one
1901    /// picture chosen between, while this is a change to what the *selection*
1902    /// answers and leaves the picture's choice alone. A reviewer freezing the
1903    /// cut and then reading it off the LOD tint is the combination the feature
1904    /// exists for, so the two cannot be alternatives.
1905    frozen_selection_eye: Option<Vec3>,
1906
1907    /// Topic 18's shadow atlas: one `D32Float` image holding
1908    /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1909    /// first, then one per shadowed light.
1910    ///
1911    /// Owned here rather than created by the graph per frame, because its
1912    /// extent is a **quality setting and not a window size** — nothing about it
1913    /// changes on a resize, so a transient would be re-created for no reason
1914    /// and could not be read back by a test that does not own the graph.
1915    shadow_atlas: ImageHandle,
1916    shadow_atlas_view: ImageViewHandle,
1917    /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1918    /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1919    ///
1920    /// Both halves of that sentence are forced:
1921    ///
1922    /// * **The slot has to be filled.** Slang's Metal backend materialises every
1923    ///   global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
1924    ///   `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
1925    ///   depth-only pipeline sharing this layout still declares the argument. A
1926    ///   layout with the slot removed would break Metal alone, on a runner this
1927    ///   team cannot debug on, which is the trap binding 6's comment already
1928    ///   records.
1929    /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
1930    ///   attachment and a bind-group resource in the same pass, and the shadow
1931    ///   pass is exactly that pass.
1932    ///
1933    /// Nothing samples it: the shadow pipeline has no fragment stage. It is
1934    /// brought into the graph beside the atlas so its layout transition is the
1935    /// graph's like every other, rather than a hand-written barrier.
1936    shadow_placeholder: ImageHandle,
1937    shadow_placeholder_view: ImageViewHandle,
1938    /// The **comparison** sampler the atlas is read through — hardware PCF.
1939    shadow_sampler: SamplerHandle,
1940    /// The depth-only pipeline every tile is rendered with — and, driven with
1941    /// the camera's own draws, the depth prepass's: `mesh.slang`'s
1942    /// `depthVertexMain` where the geometry comes from a vertex stage, the same
1943    /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
1944    /// a mesh one, and no fragment stage in either case.
1945    shadow_pipeline: SidedPipelines,
1946    /// The same two passes' pipeline for the buckets whose material mode cuts
1947    /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
1948    /// [`MeshModules::depth_masked_pipeline`].
1949    ///
1950    /// Built on every scene rather than only on one that has a masked material,
1951    /// for [`ForwardRenderer::rsm_pipeline`]'s reason: the modules are released
1952    /// inside `build` and a pipeline built later would need them back, which is
1953    /// a second shader compilation. Which buckets are drawn with it is
1954    /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
1955    /// frame's draws** rather than a choice for the whole frame.
1956    depth_masked_pipeline: SidedPipelines,
1957    /// The pipeline that resets one tile of the atlas before it is redrawn, on a
1958    /// frame that is keeping some of the others — see
1959    /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
1960    /// for it lives.
1961    shadow_clear_pipeline: GraphicsPipelineHandle,
1962    /// The irradiance probes' reflective shadow map — see
1963    /// [`MeshModules::rsm_pipeline`]. Built on every scene and bound only by a
1964    /// frame whose volume asked for [`ProbeUpdate::EveryFrame`].
1965    rsm_pipeline: SidedPipelines,
1966    /// The compute pass that reads that map into the probe rows, and [`None`]
1967    /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
1968    /// whole of what the default costs such a scene: no pipeline, no buffers, no
1969    /// pass and no frame time.
1970    probe_gather: Option<ProbeGather>,
1971    /// Whether cascade 0's view block and cull parameters were written for the
1972    /// frame being recorded, so the reflective shadow map can be drawn from
1973    /// them.
1974    ///
1975    /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
1976    /// *atlas*: a frame drawing without
1977    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
1978    /// cascade 0 for the map and writes no tile, and overloading that flag would
1979    /// report a cascade as redrawn when nothing drew it.
1980    rsm_cull_ready: bool,
1981    /// What the scene said fills the probe rows.
1982    ///
1983    /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
1984    /// shadow atlas's static-cache hold when the updater is on, because the map
1985    /// is that cascade's own draws — and by the pass recording below.
1986    probe_update: ProbeUpdate,
1987    /// How far cascade 0 reached on the frame being recorded, which is the
1988    /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
1989    /// reads it.
1990    ///
1991    /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
1992    /// themselves, rather than recomputed at pass-record time: a frame that
1993    /// scaled its gather by one cascade's footprint while drawing the map
1994    /// through another's would be a bounce that is uniformly wrong, and nothing
1995    /// in the frame could see it.
1996    cascade_reach: f32,
1997    /// The sun's colour premultiplied by its intensity, this frame.
1998    ///
1999    /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2000    /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2001    /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2002    /// The sun's *direction* is not carried beside it: the gather needs none, on
2003    /// `probe_gather.slang`'s own derivation.
2004    sun_color: Vec3,
2005    /// One cull and draw-argument pass **per cascade and per shadowed light**,
2006    /// which is topic 18's "one cull dispatch per cascade against the same
2007    /// instance/geometry pools" with a shadowed light counting as a cascade does.
2008    ///
2009    /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2010    /// the same indirect call the colour pass does, so it needs the same
2011    /// arguments, and there is no "cull only" constructor to reach for. The cost
2012    /// is that each duplicates the clear and draw-argument pipelines and
2013    /// [`DrawGen`]'s own per-instance state — see
2014    /// [`TileBuffers::group_state`], which is where that price is written down,
2015    /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2016    /// than six.
2017    ///
2018    /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2019    /// [`shadow_cull`] is where a light slot's is.
2020    shadow_draws: Vec<DrawGen>,
2021    /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2022    /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2023    /// mesh stages rather than a second transform path.
2024    shadow_uniforms: Vec<Vec<BufferHandle>>,
2025    /// Empty between frame preparations, with capacity retained for assembly.
2026    shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2027    /// Empty between frame preparations, with capacity retained for frusta.
2028    shadow_prepare_culls: Vec<(usize, Frustum)>,
2029    /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2030    /// the survivors of the cull its slot owns.
2031    shadow_groups: Vec<Vec<BindGroupHandle>>,
2032    /// `[frame][view]`: the cut that view's amplification stage chose, one word
2033    /// per resident cluster — and empty where there is no such stage.
2034    ///
2035    /// **A buffer per view rather than the camera's**, unlike every other
2036    /// resource these passes share: the colour pass is recorded last and writes
2037    /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2038    /// so a view writing there leaves nothing behind to read. Without one of
2039    /// these the shadow pass's descent is unobservable — which is the state
2040    /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2041    /// would have stayed in.
2042    shadow_selection: Vec<Vec<BufferHandle>>,
2043    /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2044    /// in the atlas's light region its tiles are, and the memory that keeps that
2045    /// answer from flickering.
2046    ///
2047    /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2048    /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2049    /// occupied slot and a viewport per face it has, and nothing at all for the
2050    /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2051    /// "nothing stored, fully lit" wherever anything did sample it.
2052    shadow_lights: shadow::Selection,
2053    /// `[group]`: everything that group's maps would be drawn from, as
2054    /// [`ForwardRenderer::shadow_group_record`] spells it.
2055    ///
2056    /// Kept only to tell one frame's answer from the last one's: it is compared
2057    /// and then replaced, and what travels from there is the number below.
2058    ///
2059    /// **Per group rather than per atlas**, since the cadence rung: a group is a
2060    /// cascade or a light slot's whole run of tiles, and holding one map while
2061    /// redrawing another is the whole of what that rung buys.
2062    shadow_group_inputs: Vec<Vec<u8>>,
2063    /// `[group]`: a number that moves whenever that group's entry of
2064    /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2065    /// value it has had.
2066    ///
2067    /// So "the image already holds this" is one integer comparison, which is
2068    /// what lets the pass body below carry the answer out of the graph.
2069    shadow_group_id: Vec<u64>,
2070    /// `[group]`: how many instance writes that group's cull could have seen,
2071    /// over the renderer's life — the per-group stand-in for
2072    /// [`InstancePool::revision`] in
2073    /// [`ForwardRenderer::shadow_group_record`], moved by
2074    /// [`ForwardRenderer::note_caster_writes`].
2075    shadow_group_writes: Vec<u64>,
2076    /// `[element]`: where each element of the instance array could draw into a
2077    /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2078    /// which is what a write's *before* is read from. Grows to the highest
2079    /// element written; an element past its end has never been written and is
2080    /// [`shadow_inputs::CasterFootprint::Nowhere`].
2081    shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2082    /// The live elements whose mesh has a DAG, and so whose level the selection
2083    /// eye chooses — the ones that put the eye into a light group's record.
2084    shadow_dag_elements: std::collections::BTreeSet<u32>,
2085    /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2086    /// an instance does not allocate its list.
2087    shadow_written: Vec<u32>,
2088    /// This frame's written elements' footprints, before and after the write,
2089    /// from [`ForwardRenderer::note_caster_writes`] for
2090    /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2091    /// written in.
2092    shadow_moved: Vec<(
2093        shadow_inputs::CasterFootprint,
2094        shadow_inputs::CasterFootprint,
2095    )>,
2096    /// The number given to the shadow pass this renderer recorded last.
2097    ///
2098    /// Moves once per recorded pass, so the body below can say *which* pass ran
2099    /// with one integer.
2100    shadow_pass_id: u64,
2101    /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2102    /// **ran**, written by that pass's own body.
2103    ///
2104    /// By the body rather than by the call that recorded it, and that is the
2105    /// whole of why this is shared state rather than a plain field: a frame
2106    /// whose graph was refused — or built and dropped — recorded a pass that
2107    /// never executed, so the image still holds whatever the frame before it
2108    /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2109    /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2110    /// imported images uses for the same reason.
2111    ///
2112    /// Zero until a pass has run, and the ids start above it, so the first frame
2113    /// of all draws.
2114    shadow_pass_ran: Arc<AtomicU64>,
2115    /// What the shadow pass recorded last would leave the image holding, if its
2116    /// body ran.
2117    ///
2118    /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2119    /// the only place that can tell whether it did — see
2120    /// [`ForwardRenderer::shadow_pass_ran`].
2121    shadow_pending: Option<ShadowCommit>,
2122    /// `[group]`: the id, the centre that group's maps were projected from and
2123    /// how far they reach, as the record the **image** holds describes them.
2124    ///
2125    /// The id is what says a map is out of date. The centre and reach are what
2126    /// say it is about somewhere else: a map whose own centre has moved further
2127    /// than its own reach covers ground it was never drawn for, and holding
2128    /// that is worse than a shadow that lags — see
2129    /// [`ForwardRenderer::shadow_cadence_reset`].
2130    shadow_group_held: Vec<(u64, Vec3, f32)>,
2131    /// `[group]`: whether this frame redraws that group's maps.
2132    ///
2133    /// Frozen by [`ForwardRenderer::begin_frame`] for
2134    /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2135    /// `add_passes` acts on it, and a value that moved between them would skip
2136    /// a cull whose draws were recorded, or the other way about.
2137    shadow_group_redrawn: Vec<bool>,
2138    /// Where every atlas slot's map was laid out on the frame the **image** was
2139    /// drawn from, so a frame can tell whether the texels it is keeping still
2140    /// describe the layout it is about to sample through.
2141    ///
2142    /// A layout that has moved is what makes a frame clear the whole attachment
2143    /// and redraw every group: a tile left over from a different layout is
2144    /// texels nothing this frame can account for. Promoted beside
2145    /// [`ForwardRenderer::shadow_group_held`].
2146    ///
2147    /// [`None`] until a pass has drawn, which is **not** the layout a frame
2148    /// with shadows off produces: an image no pass has touched holds undefined
2149    /// memory rather than a clear, so the first frame of all has to write one
2150    /// whatever it is asked for.
2151    shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2152    /// Whether any map this frame samples is one an earlier frame drew, rather
2153    /// than one this frame did.
2154    ///
2155    /// The cadence's own readback — see
2156    /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2157    /// atlas.
2158    shadow_atlas_cached: bool,
2159    /// Whether this frame ignored the cadence because some map's region moved
2160    /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2161    shadow_cadence_reset: bool,
2162    /// How many tiles this frame redraws — see
2163    /// [`ForwardRenderer::shadow_faces_redrawn`].
2164    shadow_faces_redrawn: u32,
2165    /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2166    ///
2167    /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2168    /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2169    /// process-global, and an application that wants a tier's own pair — or a
2170    /// test that wants a frame nothing else in the process can move — needs one
2171    /// that is not.
2172    shadow_cadence_request: Option<shadow::Cadence>,
2173    /// Whether this frame's shadow pass clears the whole attachment, rather
2174    /// than loading it and resetting only the tiles it redraws.
2175    ///
2176    /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2177    /// reason: the decision is `begin_frame`'s and the recording is
2178    /// `add_shadow_pass`'s, and a value that moved between them would load an
2179    /// attachment whose tiles nothing had reset.
2180    shadow_atlas_clears: bool,
2181    /// How many frames have been opened, which is what the cadence is keyed to.
2182    ///
2183    /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2184    /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2185    /// keyed to that would repeat every few frames and bound nothing.
2186    shadow_frame: u64,
2187    /// Whether this frame dispatches skinning, and so rewrites part of the
2188    /// vertex pool the shadow pass draws from.
2189    ///
2190    /// The atlas's one **always redraw**: a skinned caster's vertices are
2191    /// produced by a compute pass into the pool, so there is nothing on the
2192    /// host to compare a frame's geometry against — the palette a caller hands
2193    /// over is not the vertices, and the vertices are never read back. Set by
2194    /// [`ForwardRenderer::begin_skinned_frame`], which is the only call that
2195    /// can make it true, and cleared by [`ForwardRenderer::begin_frame`], which
2196    /// dispatches none.
2197    frame_skins: bool,
2198
2199    /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2200    /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2201    /// the latency are argued.
2202    ///
2203    /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2204    /// statistics buffer of their own and none of them is read: a cascade's
2205    /// survivor count is a different question about a different frustum, and
2206    /// added into this one it would produce a number larger than the pool holds.
2207    ///
2208    /// [`None`] on a device that would not give out the buffers, which is what
2209    /// makes the counters row degrade to `indirect` rather than fail.
2210    cull_stats: Option<CullStatsRing>,
2211
2212    tonemap_layout: BindGroupLayoutHandle,
2213    tonemap_pipeline_layout: PipelineLayoutHandle,
2214    tonemap_pipeline: GraphicsPipelineHandle,
2215    sampler: SamplerHandle,
2216    /// The multiplier the tonemap pass applies before its clamp — see
2217    /// [`set_exposure`](ForwardRenderer::set_exposure).
2218    ///
2219    /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2220    /// the only thing that writes it and it clamps.
2221    exposure: f32,
2222    /// How far auto-exposure may move in one frame — see
2223    /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2224    ///
2225    /// [`None`] until a caller says otherwise, and that is the whole distance in
2226    /// one frame: the picture the pass drew before adaptation existed.
2227    exposure_adaptation: Option<ExposureAdaptation>,
2228    /// Which operator the tonemap pass runs — see
2229    /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2230    ///
2231    /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2232    /// a caller says otherwise: this renderer shades in linear HDR, so the
2233    /// filmic roll-off is what a view that has said nothing wants. A
2234    /// display-referred view — a 2D sample, or a fixture whose assertions
2235    /// predict a code value — asks for
2236    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2237    /// which is the identity on `0..=1`.
2238    tonemap_curve: tonemap::TonemapCurve,
2239
2240    /// The format the tonemap pipeline was built for. A swapchain format change
2241    /// needs a new pipeline, which is why it is remembered rather than assumed.
2242    target_format: Format,
2243
2244    /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2245    /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2246    /// occlusion image that does not exist yet.
2247    ///
2248    /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2249    /// The shadow pass and the depth prepass name it and never sample it — a
2250    /// depth-only pipeline has no fragment stage — and **the forward pass names
2251    /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2252    /// where it is the whole of that effect's off-switch. An AO-on frame binds
2253    /// the occlusion pair's blurred output instead.
2254    ///
2255    /// **It is white because that is the value that occludes nothing**, which is
2256    /// what makes it an honest stand-in for "no occlusion was computed" rather
2257    /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2258    /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2259    /// texel is zero on every backend, so the shader clamps the coordinate to the
2260    /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2261    ///
2262    /// It is uploaded rather than cleared, so it is in
2263    /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2264    /// declare it to give it a layout.
2265    ambient_occlusion_placeholder: UploadedTexture,
2266    /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2267    /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2268    /// contact-shadow image that does not exist yet.
2269    ///
2270    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2271    /// binding along and with one difference worth stating: an unclamped `Load`
2272    /// past this one's single texel would cost the frame its **sun**, not its
2273    /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2274    contact_shadow_placeholder: UploadedTexture,
2275    /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2276    /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2277    /// has been captured — and so the console switch has something to name when
2278    /// the maps are turned off.
2279    ///
2280    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2281    /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2282    /// against `GetDimensions`, so all four of its taps land on this image's one
2283    /// texel and every probe reads as unobstructed.
2284    probe_visibility_placeholder: UploadedTexture,
2285    /// The captured maps, one `Rg32Float` layer per probe — `None` until
2286    /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2287    /// frame drawn by a caller that never calls it.
2288    probe_visibility: Option<UploadedTexture>,
2289    /// The scene's static triangles, kept for that capture and for nothing else.
2290    ///
2291    /// Empty for a description that reserved no probes, which is what makes the
2292    /// retention cost of this rung zero for every caller that does not use it —
2293    /// see [`crate::probe_visibility`].
2294    probe_occluders: crate::probe_visibility::Occluders,
2295    /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2296    /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2297    /// by every area light's specular term.
2298    ///
2299    /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2300    /// again: it is a property of the GGX lobe rather than of a scene, a view or
2301    /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2302    /// it this is not a stand-in for anything — there is no path on which the
2303    /// table is absent, because there is no path on which the lobe is.
2304    specular_dfg: UploadedTexture,
2305    /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2306    /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2307    ///
2308    /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2309    /// terms exactly and for the same reason: it is a property of the lobe, and
2310    /// it is bound on every path because Slang's Metal backend materialises
2311    /// every global into every entry point.
2312    ltc_table: UploadedTexture,
2313    /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2314    /// from.
2315    ///
2316    /// Kept for one rebuild only: the pages' and their sampler's, which
2317    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2318    /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2319    shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2320
2321    /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2322    ///
2323    /// [`None`] until a caller first switches it on with
2324    /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2325    /// keeps a sample that never asks for a grid from building a pipeline and a
2326    /// ring of blocks for a pass it does not record. Once built it is kept —
2327    /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2328    /// release, because releasing a uniform ring the frames in flight may still
2329    /// be reading is exactly what the ring exists to prevent.
2330    ground_grid: Option<GroundGrid>,
2331    /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2332    /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2333    /// every sample and every golden image predates it.
2334    ground_grid_on: bool,
2335
2336    /// The debug draw layer's immediate-mode buffer and its pass — see
2337    /// [`crate::debug_draw`].
2338    ///
2339    /// Always present and empty by default, because appending to it is what a
2340    /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2341    /// it are what stay unbuilt until a frame has both a segment and
2342    /// [`crate::debug_draw::r_debug_draw`] switched on.
2343    debug_draw: DebugDraw,
2344
2345    /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2346    /// but the one [`debug_view`](Self::debug_view) resolved to
2347    /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2348    /// [`set_atlas_view`](Self::set_atlas_view).
2349    atlas_viewer: AtlasView,
2350    /// How large the internal render target is as a fraction of the extent a
2351    /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2352    render_scale: f32,
2353
2354    /// The three layers a caller supplies — see [`crate::effects`].
2355    effect_request: EffectRequest,
2356    /// The fourth layer: what this device can draw, which clamps last and
2357    /// absolutely.
2358    ///
2359    /// **Every effect, and that is a fact about the effects rather than an
2360    /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2361    /// words — "there is no device fact to gate on … inventing a capability that
2362    /// is really a performance opinion is what topic 39 exists to prevent" — and
2363    /// the reflection pair's module says it of itself. The shadow atlas is a
2364    /// `D32Float` image and a depth-only pass, which is not something a device
2365    /// that got this far can be missing either: one too small for the atlas
2366    /// fails to *build* this renderer rather than degrading past it.
2367    ///
2368    /// So the clamp is real and its rule set is empty. The first rule arrives
2369    /// with the ray-traced variants of these same three effects, which
2370    /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2371    /// builds yet.
2372    device_effects: RenderEffects,
2373    /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2374    /// draws, resolved once there.
2375    ///
2376    /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2377    /// parameter write when shadows are off and
2378    /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2379    /// changed between the two would dispatch a cull whose counters nothing
2380    /// zeroed, which is a plausible frame drawn off last frame's numbers.
2381    frame_effects: RenderEffects,
2382    /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2383    /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2384    /// read once there.
2385    ///
2386    /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2387    /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2388    /// full-screen triangles and records its passes, and a console command
2389    /// landing between the two reads would leave `counters` describing a frame
2390    /// that was never submitted.
2391    frame_ssao_blurs: u32,
2392    /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2393    /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2394    /// as submitted beside the pool's instances.
2395    ///
2396    /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2397    /// `counters` describes the frame that *was* recorded, and a request set
2398    /// after it would otherwise change the count of a frame already submitted.
2399    recorded_fullscreen: u64,
2400
2401    /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2402    /// debug draw layer's pass, as the one direct draw it costs.
2403    ///
2404    /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2405    /// a full-screen triangle: it is one line-list draw of every segment this
2406    /// frame appended. Both are direct draws of one instance, which is what
2407    /// [`ForwardRenderer::direct_draws`] adds up.
2408    recorded_debug_draw: u64,
2409    /// How many tiles of the shadow atlas the last
2410    /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2411    /// than with the attachment's own clear.
2412    ///
2413    /// Zero on every frame that clears the whole attachment, which is every
2414    /// frame until the cadence is switched on — see
2415    /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2416    /// instance each, so it joins the full-screen draws rather than the
2417    /// indirect ones.
2418    recorded_tile_clears: u64,
2419    /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2420    /// buffers every view draws them from — see [`crate::water`]. Empty until
2421    /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2422    /// pass.
2423    water: WaterBodies,
2424    /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2425    /// recorded for the primary camera: one indexed draw per body, each of one
2426    /// instance, so they join the direct draws on the debug draw layer's terms.
2427    recorded_water_draws: u64,
2428    /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2429    /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2430    /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2431    /// pass.
2432    grass: GrassScene,
2433    /// The wind block every view writes into its own ring — see
2434    /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2435    wind: crcbl_shaders::wind::WindParams,
2436    /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2437    /// recorded for the primary camera: one per tile slot per look the field
2438    /// draws.
2439    ///
2440    /// **Not among the direct draws**, unlike the water surface's: every one of
2441    /// them is an indirect call whose instance count lives in a buffer a
2442    /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2443    /// nothing about how many blades came out of them.
2444    recorded_grass_draws: u64,
2445}
2446
2447/// What a partly-built [`ForwardRenderer`] has to give back.
2448///
2449/// `new` creates a dozen objects with `?` between them, and the seam's
2450/// `destroy_*` is explicit — so a failure half way through used to leak
2451/// everything created before it. The recorder's leak assertions cover the happy
2452/// path; this covers the other one.
2453#[derive(Debug, Default)]
2454struct Rollback {
2455    buffers: Vec<BufferHandle>,
2456    bind_groups: Vec<BindGroupHandle>,
2457    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2458    pipeline_layouts: Vec<PipelineLayoutHandle>,
2459    pipelines: Vec<GraphicsPipelineHandle>,
2460    samplers: Vec<SamplerHandle>,
2461    /// The shadow atlas and its placeholder, which are created here rather than
2462    /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2463    /// with their views beside them.
2464    images: Vec<ImageHandle>,
2465    image_views: Vec<ImageViewHandle>,
2466    /// Uploaded images, which own a view each and so cannot be rolled back as
2467    /// one list of handles.
2468    textures: Vec<UploadedTexture>,
2469    /// The geometry pool, which owns two buffers, a semaphore and anything
2470    /// still staged — so it cannot be rolled back as a list of handles.
2471    pool: Option<MeshPool>,
2472    /// The instance pool, which owns one buffer per frame in flight.
2473    instances: Option<InstancePool>,
2474    /// The material table, which owns one buffer.
2475    materials: Option<MaterialTable>,
2476    /// The irradiance probe table, which owns one buffer.
2477    probes: Option<ProbeTable>,
2478    /// The irradiance probes' updater, which owns one pipeline,
2479    /// one layout and a ring of blocks — and only exists for a scene whose
2480    /// volume asked to be updated.
2481    probe_gather: Option<ProbeGather>,
2482    /// The cull and draw-argument passes, which own two pipelines and a ring of
2483    /// buffers each — and which clean themselves up on their own failure path,
2484    /// so this only carries one that was built.
2485    draws: Option<DrawGen>,
2486    /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2487    /// `Option`, because a failure part way through the tiles has to release the
2488    /// ones already built.
2489    shadow_draws: Vec<DrawGen>,
2490    /// The cluster buffers, which own three buffers and are built on the
2491    /// mesh-shader path alone.
2492    clusters: Option<ClusterPool>,
2493    /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2494    /// three buffers — and which clean themselves up on their own failure path,
2495    /// so this only carries one that was built.
2496    lights: Option<LightGrid>,
2497    /// Topic 46's occlusion pair, which owns two
2498    /// pipelines, two layouts and a ring of blocks.
2499    ssao: Option<Ssao>,
2500    /// Topic 45's contact-shadow march, which owns one
2501    /// pipeline, one layout and a ring of blocks.
2502    contact_shadows: Option<ContactShadows>,
2503    /// Topic 47's depth pyramid, which owns one
2504    /// pipeline, one layout and a ring of blocks per level.
2505    hiz: Option<Hiz>,
2506    /// Topic 03 §3.3's farthest-depth pyramid,
2507    /// which owns one pipeline, one layout and — once a frame culled — a chain
2508    /// of level images.
2509    occlusion_pyramid: Option<OcclusionPyramid>,
2510    /// Topic 47's reflection march, which owns one
2511    /// pipeline, one layout and a ring of blocks.
2512    ssr: Option<Ssr>,
2513    /// The froxel volume, which owns three
2514    /// pipelines, two layouts and two rings of buffers.
2515    volumetric: Option<Volumetric>,
2516    /// Topic 43 §6's auto-exposure, which owns three
2517    /// pipelines, one layout and three rings of buffers.
2518    exposure: Option<Exposure>,
2519    /// Topic 48's bloom chain, which owns three
2520    /// pipelines, two layouts, a sampler and a ring of blocks.
2521    bloom: Option<Bloom>,
2522    /// The cheap antialiasing tier, which owns one
2523    /// pipeline, one layout, a sampler and a ring of blocks.
2524    fxaa: Option<Fxaa>,
2525    /// The higher antialiasing tier, which owns
2526    /// four compute pipelines, one graphics pipeline, two layouts and a ring of
2527    /// blocks.
2528    cmaa2: Option<Cmaa2>,
2529    upscale: Option<Upscale>,
2530    /// The background pass, which owns one pipeline, one layout and a ring of
2531    /// blocks and groups.
2532    sky_pass: Option<SkyPass>,
2533    /// The water surface's two pipelines, their layouts and a ring of blocks.
2534    water: Option<Water>,
2535    /// The grass passes' pipelines, their layouts and their rings of
2536    /// blocks.
2537    grass: Option<Grass>,
2538    /// The shadow atlas viewer, which owns one pipeline, one layout and a ring
2539    /// of blocks and groups.
2540    atlas_viewer: Option<AtlasView>,
2541    /// The camera, once [`View::build`] has made it whole — released as one,
2542    /// by [`View::destroy`].
2543    primary: Option<View>,
2544}
2545
2546impl Rollback {
2547    /// Releases everything, in the same dependency order as
2548    /// [`ForwardRenderer::destroy`].
2549    fn run(self, device: &dyn Device) {
2550        if let Some(view) = self.primary {
2551            view.destroy(device);
2552        }
2553        for texture in self.textures {
2554            texture.destroy(device);
2555        }
2556        for handle in self.samplers {
2557            device.destroy_sampler(handle);
2558        }
2559        for handle in self.image_views {
2560            device.destroy_image_view(handle);
2561        }
2562        for handle in self.images {
2563            device.destroy_image(handle);
2564        }
2565        for handle in self.pipelines {
2566            device.destroy_graphics_pipeline(handle);
2567        }
2568        for handle in self.pipeline_layouts {
2569            device.destroy_pipeline_layout(handle);
2570        }
2571        for handle in self.bind_groups {
2572            device.destroy_bind_group(handle);
2573        }
2574        for handle in self.bind_group_layouts {
2575            device.destroy_bind_group_layout(handle);
2576        }
2577        for handle in self.buffers {
2578            device.destroy_buffer(handle);
2579        }
2580        if let Some(clusters) = self.clusters {
2581            clusters.destroy(device);
2582        }
2583        for draws in self.shadow_draws {
2584            draws.destroy(device);
2585        }
2586        if let Some(lights) = self.lights {
2587            lights.destroy(device);
2588        }
2589        if let Some(atlas_viewer) = self.atlas_viewer {
2590            atlas_viewer.destroy(device);
2591        }
2592        if let Some(grass) = self.grass {
2593            grass.destroy(device);
2594        }
2595        if let Some(water) = self.water {
2596            water.destroy(device);
2597        }
2598        if let Some(sky_pass) = self.sky_pass {
2599            sky_pass.destroy(device);
2600        }
2601        if let Some(upscale) = self.upscale {
2602            upscale.destroy(device);
2603        }
2604        if let Some(cmaa2) = self.cmaa2 {
2605            cmaa2.destroy(device);
2606        }
2607        if let Some(fxaa) = self.fxaa {
2608            fxaa.destroy(device);
2609        }
2610        if let Some(bloom) = self.bloom {
2611            bloom.destroy(device);
2612        }
2613        if let Some(exposure) = self.exposure {
2614            exposure.destroy(device);
2615        }
2616        if let Some(volumetric) = self.volumetric {
2617            volumetric.destroy(device);
2618        }
2619        if let Some(ssr) = self.ssr {
2620            ssr.destroy(device);
2621        }
2622        if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2623            occlusion_pyramid.destroy(device);
2624        }
2625        if let Some(hiz) = self.hiz {
2626            hiz.destroy(device);
2627        }
2628        if let Some(contact_shadows) = self.contact_shadows {
2629            contact_shadows.destroy(device);
2630        }
2631        if let Some(ssao) = self.ssao {
2632            ssao.destroy(device);
2633        }
2634        if let Some(draws) = self.draws {
2635            draws.destroy(device);
2636        }
2637        // Before the table, because its bind groups name that table's rows.
2638        if let Some(gather) = self.probe_gather {
2639            gather.destroy(device);
2640        }
2641        if let Some(table) = self.probes {
2642            table.destroy(device);
2643        }
2644        if let Some(table) = self.materials {
2645            table.destroy(device);
2646        }
2647        if let Some(pool) = self.instances {
2648            pool.destroy(device);
2649        }
2650        if let Some(pool) = self.pool {
2651            pool.destroy(device);
2652        }
2653    }
2654}
2655
2656/// What every bind group of the mesh layout names identically.
2657///
2658/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2659/// the claim: a resource here cannot differ between the colour pass's group and
2660/// a cascade's, and one there must be looked at.
2661struct SharedBindings<'a> {
2662    vertices: BufferHandle,
2663    draw_constants: BufferHandle,
2664    mesh_table: BufferHandle,
2665    materials: BufferHandle,
2666    /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2667    /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2668    /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2669    /// beside them — as this frame slot names them, which is what
2670    /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2671    pages: PageBindings,
2672    /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2673    /// what decides whether the mesh-only bindings exist at all.
2674    clusters: Option<&'a ClusterPool>,
2675    shadow_sampler: SamplerHandle,
2676    /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2677    /// slots of the light ring.
2678    ///
2679    /// Shared rather than per-group, unlike the instance array beside them, and
2680    /// that is the claim: **a cascade shades nothing**, so it reads the same
2681    /// list and the same grid the colour pass does — the depth-only pipeline
2682    /// simply never looks. Two buffers per pass would be two clustering
2683    /// dispatches for one camera.
2684    lights: BufferHandle,
2685    light_grid: BufferHandle,
2686    /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2687    /// grid's ring.
2688    ///
2689    /// Shared across the *groups of one frame* rather than across frames, which
2690    /// is the light list's arrangement exactly: a cascade shades nothing, so it
2691    /// reads the same rows the colour pass does and the depth-only pipeline
2692    /// simply never looks. What it is not is shared across the ring — see
2693    /// [`crate::probe`] for why the table is per-frame at all.
2694    probes: BufferHandle,
2695    /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2696    ///
2697    /// Shared rather than per-group for the probe grid's reason exactly: the
2698    /// regions are written when a mesh becomes resident and never per frame, so
2699    /// a cascade and the colour pass read the same words. What varies between
2700    /// them is the *budget* the mesh stage projects against, and that rides in
2701    /// each pass's own frame block.
2702    tables: BufferHandle,
2703    /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2704    /// [`ForwardRenderer::specular_dfg`].
2705    ///
2706    /// Shared rather than per-group for the probe grid's reason and more
2707    /// strongly: it is cooked into the binary, uploaded once at build and
2708    /// identical for every view this engine will ever draw. A cascade names it
2709    /// and never looks.
2710    specular_dfg: ImageViewHandle,
2711    /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2712    /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2713    ltc_table: ImageViewHandle,
2714}
2715
2716/// The half of a mesh-layout bind group that differs between the colour pass and
2717/// each shadow cascade.
2718///
2719/// One description for both, so the two cannot drift: a cascade's group is the
2720/// colour pass's with six resources swapped, and swapping the wrong five of them
2721/// is a shadow map rendered from the camera — which looks like a shadow map.
2722struct MeshGroup {
2723    /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2724    /// `view_proj` is that cascade's matrix.
2725    uniforms: BufferHandle,
2726    /// Binding 2. This frame's slot of the instance ring.
2727    instances: BufferHandle,
2728    /// Binding 5. Whose survivors this group draws.
2729    runs: BufferHandle,
2730    /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2731    /// read as data.
2732    args: BufferHandle,
2733    /// Binding 13, where there is an amplification stage: the frustum it culls
2734    /// clusters against.
2735    cull_params: BufferHandle,
2736    /// Binding 14, likewise: what it counts survivors into.
2737    cull_stats: BufferHandle,
2738    /// Binding 18, likewise: the cut the descent chose, one word per resident
2739    /// cluster. `None` exactly where there is no amplification stage, which is
2740    /// where the layout has no CLUSTER_SELECTION_BINDING either.
2741    ///
2742    /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2743    /// so a cascade writing the camera's would leave nothing of its own to read.
2744    /// See [`ForwardRenderer::shadow_selection`].
2745    cluster_selection: Option<BufferHandle>,
2746    /// Binding 19, likewise: topic 25's hysteresis state, which the
2747    /// draw-argument pass wrote this frame and this one only reads.
2748    ///
2749    /// **A buffer per pass** as well, because the colour pass and a cascade
2750    /// judge the same groups under different budgets — see
2751    /// [`TileBuffers::group_state`].
2752    group_state: Option<BufferHandle>,
2753    /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2754    /// and the placeholder for the pass that writes it — see
2755    /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2756    shadow_map: ImageViewHandle,
2757    /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2758    /// a forward pass that computed one, and the white placeholder everywhere
2759    /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2760    ///
2761    /// **Every group built at `build` names the placeholder**, including the
2762    /// camera's: the occlusion image may be a graph transient whose view exists
2763    /// only at execute time, so the camera's group is rebuilt against whatever
2764    /// the frame bound inside the forward pass and cached — the shape
2765    /// [`View::tonemap_groups`] already has.
2766    ambient_occlusion: ImageViewHandle,
2767    /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2768    /// forward pass that marched one, and the white placeholder everywhere else
2769    /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2770    ///
2771    /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2772    /// group built at `build` names the placeholder.
2773    contact_shadow: ImageViewHandle,
2774    /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2775    /// maps for the camera's pass, and the one-texel placeholder everywhere
2776    /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2777    ///
2778    /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2779    /// is not a graph transient but an ordinary uploaded texture, so what makes
2780    /// this a per-frame swap is the console switch and whether a capture has
2781    /// happened yet — neither of which is known at `build`.
2782    probe_visibility: ImageViewHandle,
2783}
2784
2785impl MeshGroup {
2786    fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2787        let mut entries = vec![
2788            BindGroupEntry {
2789                binding: 0,
2790                array_index: 0,
2791                resource: BindingResource::whole_buffer(self.uniforms),
2792            },
2793            BindGroupEntry {
2794                binding: 1,
2795                array_index: 0,
2796                resource: BindingResource::whole_buffer(shared.vertices),
2797            },
2798            BindGroupEntry {
2799                binding: 2,
2800                array_index: 0,
2801                // **This frame's slot of the instance ring, not a shared
2802                // buffer.** Binding one buffer here for every group would undo
2803                // the ring and reintroduce the cross-submission
2804                // read-after-write hazard it exists to prevent.
2805                resource: BindingResource::whole_buffer(self.instances),
2806            },
2807            BindGroupEntry {
2808                binding: 3,
2809                array_index: 0,
2810                // **One block, not the whole buffer.** The binding is dynamic,
2811                // so the bind's offset is added on top of this one and both
2812                // Vulkan and WebGPU require `offset + dynamic + size` to stay
2813                // inside the buffer — bound whole, the very first non-zero
2814                // dynamic offset would be out of range.
2815                resource: BindingResource::Buffer {
2816                    buffer: shared.draw_constants,
2817                    offset: 0,
2818                    size: DRAW_CONSTANTS_BLOCK,
2819                },
2820            },
2821            BindGroupEntry {
2822                binding: 4,
2823                array_index: 0,
2824                // The same table in every group, unlike the instance array
2825                // above it: the pool writes an entry when a mesh is uploaded or
2826                // freed, neither of which happens between frames here.
2827                resource: BindingResource::whole_buffer(shared.mesh_table),
2828            },
2829            BindGroupEntry {
2830                binding: 5,
2831                array_index: 0,
2832                // Whose cull this group draws from. This is the binding a
2833                // cascade's group differs in most consequentially: it is what
2834                // makes the shadow pass draw what the *light* can see rather
2835                // than what the camera can.
2836                resource: BindingResource::whole_buffer(self.runs),
2837            },
2838            BindGroupEntry {
2839                binding: 6,
2840                array_index: 0,
2841                resource: BindingResource::whole_buffer(shared.materials),
2842            },
2843            BindGroupEntry {
2844                binding: BASE_COLOR_PAGE_BINDING,
2845                array_index: 0,
2846                // **One entry, `array_index: 0`**, because the page is one
2847                // image and the layer is chosen in the shader. A bindless array
2848                // would be one entry per texture at ascending array indices,
2849                // which is the write path `BindGroupEntry`'s own docs describe
2850                // and the one this pass does not take.
2851                resource: BindingResource::ImageView(
2852                    shared.pages.views[PageKind::BaseColor.index()],
2853                ),
2854            },
2855            BindGroupEntry {
2856                binding: PAGE_SAMPLER_BINDING,
2857                array_index: 0,
2858                resource: BindingResource::Sampler(shared.pages.sampler),
2859            },
2860        ];
2861        if let Some(clusters) = shared.clusters {
2862            entries.extend([
2863                BindGroupEntry {
2864                    binding: CLUSTERS_BINDING,
2865                    array_index: 0,
2866                    // The same three buffers in every group, on the mesh table's
2867                    // terms: clusters are written when the pool is built and
2868                    // never again.
2869                    resource: BindingResource::whole_buffer(clusters.clusters()),
2870                },
2871                BindGroupEntry {
2872                    binding: CLUSTER_VERTICES_BINDING,
2873                    array_index: 0,
2874                    resource: BindingResource::whole_buffer(clusters.vertices()),
2875                },
2876                BindGroupEntry {
2877                    binding: CLUSTER_CORNERS_BINDING,
2878                    array_index: 0,
2879                    resource: BindingResource::whole_buffer(clusters.corners()),
2880                },
2881                BindGroupEntry {
2882                    binding: CLUSTER_DRAW_ARGS_BINDING,
2883                    array_index: 0,
2884                    // **Arguments read as data.** The mesh path records no
2885                    // indirect draw at all; what it wants out of this buffer is
2886                    // the one word only the GPU knows — how many instances
2887                    // survived into each bucket.
2888                    resource: BindingResource::whole_buffer(self.args),
2889                },
2890            ]);
2891        }
2892        // Both mesh entry points retain these native buffer arguments even
2893        // when no amplification stage reads them.
2894        if shared.clusters.is_some() {
2895            entries.extend([
2896                BindGroupEntry {
2897                    binding: CLUSTER_CULL_BINDING,
2898                    array_index: 0,
2899                    resource: BindingResource::whole_buffer(self.cull_params),
2900                },
2901                BindGroupEntry {
2902                    binding: CLUSTER_CULL_STATS_BINDING,
2903                    array_index: 0,
2904                    resource: BindingResource::whole_buffer(self.cull_stats),
2905                },
2906            ]);
2907        }
2908        entries.push(BindGroupEntry {
2909            binding: SHADOW_ATLAS_BINDING,
2910            array_index: 0,
2911            resource: BindingResource::ImageView(self.shadow_map),
2912        });
2913        entries.push(BindGroupEntry {
2914            binding: SHADOW_SAMPLER_BINDING,
2915            array_index: 0,
2916            resource: BindingResource::Sampler(shared.shadow_sampler),
2917        });
2918        // Mesh-only buffers are sorted after the common fragment prefix below.
2919        if let Some(clusters) = shared.clusters {
2920            entries.push(BindGroupEntry {
2921                binding: CLUSTER_SELECT_BINDING,
2922                array_index: 0,
2923                // Bound with the geometry rather than with the cull, because
2924                // `vertex_base` *is* geometry: it is which level of a DAG a
2925                // cluster's vertices live in, and both mesh entry points resolve
2926                // a vertex through it.
2927                resource: BindingResource::whole_buffer(clusters.selection()),
2928            });
2929        }
2930        if let Some(selection) = self.cluster_selection {
2931            entries.push(BindGroupEntry {
2932                binding: CLUSTER_SELECTION_BINDING,
2933                array_index: 0,
2934                resource: BindingResource::whole_buffer(selection),
2935            });
2936        }
2937        if let Some(state) = self.group_state {
2938            entries.push(BindGroupEntry {
2939                binding: CLUSTER_GROUP_STATE_BINDING,
2940                array_index: 0,
2941                resource: BindingResource::whole_buffer(state),
2942            });
2943        }
2944        // Topic 18's pair, on every path and in every group — see the layout,
2945        // which has no configuration that omits them either.
2946        entries.push(BindGroupEntry {
2947            binding: LIGHT_LIST_BINDING,
2948            array_index: 0,
2949            resource: BindingResource::whole_buffer(shared.lights),
2950        });
2951        entries.push(BindGroupEntry {
2952            binding: LIGHT_GRID_BINDING,
2953            array_index: 0,
2954            resource: BindingResource::whole_buffer(shared.light_grid),
2955        });
2956        // Shared fragment textures and probes retain their raster bindings.
2957        entries.push(BindGroupEntry {
2958            binding: AMBIENT_OCCLUSION_BINDING,
2959            array_index: 0,
2960            resource: BindingResource::ImageView(self.ambient_occlusion),
2961        });
2962        // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
2963        entries.push(BindGroupEntry {
2964            binding: PROBE_TABLE_BINDING,
2965            array_index: 0,
2966            resource: BindingResource::whole_buffer(shared.probes),
2967        });
2968        // Group records are present on both mesh paths, matching the layout.
2969        if shared.clusters.is_some() {
2970            entries.push(BindGroupEntry {
2971                binding: LEVEL_GROUP_TABLE_BINDING,
2972                array_index: 0,
2973                resource: BindingResource::whole_buffer(shared.tables),
2974            });
2975        }
2976        // The DFG texture is read by the fragment stage of every path.
2977        entries.push(BindGroupEntry {
2978            binding: SPECULAR_DFG_BINDING,
2979            array_index: 0,
2980            resource: BindingResource::ImageView(shared.specular_dfg),
2981        });
2982        // And §2's normal page above that, on the same ascending terms — see
2983        // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
2984        // binding 7's reason: one image, and the layer is chosen in the shader.
2985        entries.push(BindGroupEntry {
2986            binding: NORMAL_PAGE_BINDING,
2987            array_index: 0,
2988            resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
2989        });
2990        // And the area lights' table above that, on the same ascending terms —
2991        // see [`LTC_TABLE_BINDING`].
2992        entries.push(BindGroupEntry {
2993            binding: LTC_TABLE_BINDING,
2994            array_index: 0,
2995            resource: BindingResource::ImageView(shared.ltc_table),
2996        });
2997        // And the contact-shadow channel above that, last of the set and on the
2998        // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
2999        entries.push(BindGroupEntry {
3000            binding: CONTACT_SHADOW_BINDING,
3001            array_index: 0,
3002            resource: BindingResource::ImageView(self.contact_shadow),
3003        });
3004        // And the probe visibility maps above that, on the same ascending terms
3005        // — see [`PROBE_VISIBILITY_BINDING`].
3006        entries.push(BindGroupEntry {
3007            binding: PROBE_VISIBILITY_BINDING,
3008            array_index: 0,
3009            resource: BindingResource::ImageView(self.probe_visibility),
3010        });
3011        // And §2's other two pages above that, last of the set and on the same
3012        // ascending terms — see [`MRO_PAGE_BINDING`] and
3013        // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3014        // normal page's reason: one image apiece, and the layer is chosen in
3015        // the shader.
3016        entries.push(BindGroupEntry {
3017            binding: MRO_PAGE_BINDING,
3018            array_index: 0,
3019            resource: BindingResource::ImageView(
3020                shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3021            ),
3022        });
3023        entries.push(BindGroupEntry {
3024            binding: EMISSIVE_PAGE_BINDING,
3025            array_index: 0,
3026            resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3027        });
3028        entries.sort_by_key(|entry| entry.binding);
3029        entries
3030    }
3031}
3032
3033/// The two `ArrayPages` images every group of the mesh layout names, as the
3034/// graph knows them.
3035///
3036/// One value rather than two arguments because the two travel together
3037/// everywhere: every pass that declares one declares the other, and a pass
3038/// handed them the wrong way round would order a caller's copy into the wrong
3039/// image — which is a barrier bug, and therefore one that reproduces on one
3040/// backend and not the others.
3041#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3042struct MaterialPages {
3043    /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3044    base_color: ImageId,
3045    /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3046    normal: ImageId,
3047    /// §2's metallic-roughness-occlusion page —
3048    /// [`ForwardRenderer::mro_page_import`].
3049    mro: ImageId,
3050    /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3051    emissive: ImageId,
3052}
3053
3054/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3055/// as the graph knows it.
3056///
3057/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3058/// the list grew past what an argument list should be the moment the probe rows
3059/// joined it: each of these is in every cascade's bind group and read by no
3060/// cascade, so what the pass does with them is one thing — declare them, so the
3061/// graph can order whoever writes them against these draws.
3062#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3063struct ShadowReads {
3064    /// The occlusion placeholder every cascade's group stands the real channel
3065    /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3066    occlusion_placeholder: ImageId,
3067    /// §3.2's and §2's pages, which the cascades name and never sample.
3068    pages: MaterialPages,
3069    /// The skinned vertex region, where a frame has one — the cascades pull the
3070    /// same geometry the colour pass does.
3071    skinned: Option<BufferId>,
3072    /// This frame's slot of the probe ring — see [`crate::probe`].
3073    probes: BufferId,
3074}
3075
3076/// What the mesh pass's bind-group layout is called.
3077///
3078/// Named rather than written twice because a test asserts on it: the layout's
3079/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3080/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3081/// has to find this one layout among the recorder's.
3082const MESH_LAYOUT_LABEL: &str = "mesh frame";
3083
3084/// Imports a buffer a pass both reads and writes, carried from one frame on
3085/// its slot to the next: it arrives in the state the previous frame that used
3086/// the slot left it in, and that is the state it is declared to leave in.
3087///
3088/// A record of the cut or a statistics sink, which a pass writes and the next
3089/// frame on the same slot writes again — a barrier naming `Undefined` as its
3090/// source would carry no source scope and order this frame's write against
3091/// nothing.
3092fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3093    graph.import_buffer(
3094        label,
3095        ImportedBuffer {
3096            buffer,
3097            initial: ResourceState::ShaderReadWrite,
3098            final_state: ResourceState::ShaderReadWrite,
3099        },
3100    )
3101}
3102
3103/// Declares the buffers a geometry pass reads to find its draws.
3104///
3105/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3106/// struct is what the encoder is told. Three passes declare exactly this set, and
3107/// the seam calls the barrier it produces the single most important one in a
3108/// GPU-driven frame — its absence produces "sometimes nothing draws".
3109///
3110/// A caller with a cluster-selection buffer of its own appends it; that is the
3111/// one declaration that differs between the colour pass, a cascade and the depth
3112/// prepass.
3113fn read_draw_sources<'g, 'a>(
3114    pass: PassBuilder<'g, 'a>,
3115    draws: &GeneratedDraws,
3116    emit: EmitTail,
3117) -> PassBuilder<'g, 'a> {
3118    // The buffers the draws come out of. Declaring them is what makes the graph
3119    // transition them out of the compute pass's `ShaderReadWrite`.
3120    let pass = pass.read_buffer(draws.runs_id);
3121    if emit.is_mesh() {
3122        // **The same arguments, read as data rather than executed**, which is
3123        // what the stages use to bound the run of surviving instances they index.
3124        // The per-bucket draw *counts* are not read at all, because nothing here
3125        // is a draw whose count could come from memory.
3126        //
3127        // The dispatch *extents* are a real indirect read — one structure per
3128        // bucket, written by the same pass. They are in a **different buffer**
3129        // from the arguments above and that separation is load-bearing: a
3130        // resource is in exactly one state per pass and these two are in
3131        // different ones. They share a buffer with the counts instead, which
3132        // this path does not read at all — see [`GeneratedDraws::counts`].
3133        let pass = pass
3134            .read_buffer(draws.args_id)
3135            .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3136        // The amplification stage counts its survivors into the culling
3137        // statistics, which the draw-argument pass read a moment ago — so this
3138        // is a write-after-read the graph has to order, and declaring it is
3139        // the whole of how it learns to.
3140        //
3141        // Topic 25's hysteresis state is read here and written by
3142        // the draw-argument pass a moment ago. Declaring it is what orders the
3143        // two — and what puts it back into `ShaderReadWrite` at the end of the
3144        // graph, which is where the next frame's draw-argument pass expects to
3145        // find it.
3146        //
3147        // **Declared on the whole mesh path, not only where there is an
3148        // amplification stage**, because that is where the bind group now
3149        // names both — see the layout, which is where the Metal argument-table
3150        // arithmetic that forced it is argued. A buffer bound writable and
3151        // never transitioned is a descriptor in the wrong resource state, which
3152        // is what the graph exists to prevent.
3153        pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3154            .read_buffer(draws.group_state_id)
3155    } else {
3156        pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3157            .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3158    }
3159}
3160
3161/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3162///
3163/// One of these per description mesh, in description order — so a mesh's index
3164/// here is its index there, which is what lets the bucket table, the level
3165/// tables and the cluster pool all be filled in by walking one list.
3166struct ResidentMesh {
3167    /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3168    /// level for a DAG. Never empty.
3169    ///
3170    /// Every level is its own vertex range and so its own table entry. Level 0's
3171    /// id is the one the *instance* carries and the one the cull pass reads a
3172    /// bounding box out of; the coarser ones are named by the bucket table on a
3173    /// path that takes a uniform cut, and by nothing at all on the mesh path,
3174    /// where a cluster reaches its own level through
3175    /// [`vertex_bases`](Self::vertex_bases) instead.
3176    levels: Vec<u32>,
3177    /// Per level, how far that level's vertices start past level 0's — so a flat
3178    /// mesh's single entry is zero.
3179    ///
3180    /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3181    /// and the whole of what makes a DAG drawable from one instance: the mesh
3182    /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3183    /// three levels reads three different vertex ranges out of one pool.
3184    vertex_bases: Vec<u32>,
3185    /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3186    /// for a [`Geometry::Dag`].
3187    ///
3188    /// A DAG is refused because its coarser levels are separate vertex runs no
3189    /// skinning dispatch writes: an instance drawn out of a skinned region
3190    /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3191    /// to the region's base, which for anything but level 0 is memory the
3192    /// dispatch never touched.
3193    skinnable: Option<MeshHandle>,
3194}
3195
3196impl ResidentMesh {
3197    /// The table id an instance of this mesh carries: **level 0's**, whatever
3198    /// the geometry path, because it is the entry `cull.slang` reads a bounding
3199    /// box out of and the coarser levels approximate the same surface inside the
3200    /// same box.
3201    fn id(&self) -> u32 {
3202        self.levels[0]
3203    }
3204}
3205
3206/// One skinned object the renderer re-points every frame: the instance, and the
3207/// base vertex it draws out of under each parity.
3208///
3209/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3210/// so placing an object does not tie the renderer's lifetime to the caller's
3211/// reservation — the renderer never needs the region again, only the two
3212/// numbers.
3213#[derive(Clone, Copy, Debug)]
3214struct SkinnedInstance {
3215    handle: InstanceHandle,
3216    /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3217    /// indexing — so the half a frame of parity `p` draws out of is
3218    /// `bases[p & 1]` and the half the frame before it filled is
3219    /// `bases[(p ^ 1) & 1]`, which is
3220    /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3221    /// answer for the same `p`.
3222    bases: [u32; 2],
3223    /// Whether a frame has already pointed this entry at a half of the region
3224    /// it now names.
3225    ///
3226    /// **What makes the previous base meaningful.** The half a frame did not
3227    /// write holds whatever its reservation came with until a dispatch fills
3228    /// it, so an object's first frame out of a region has no previous
3229    /// deformation to point at — naming that half would give it a motion vector
3230    /// against undefined vertices. Such an entry is put at rest instead, which
3231    /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3232    /// applies to `previous_transform` for the same reason: a spawn did not
3233    /// travel from anywhere.
3234    pointed: bool,
3235}
3236
3237/// The two base vertices an object drawn out of `mesh` alternates between, in
3238/// [`SkinnedInstance::bases`]' indexing.
3239fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3240    [mesh.region().base(0), mesh.region().base(1)]
3241}
3242
3243/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3244/// generator is handed to the rollback.
3245struct TileBuffers {
3246    runs: Vec<BufferHandle>,
3247    args: Vec<BufferHandle>,
3248    cull_params: Vec<BufferHandle>,
3249    cull_stats: Vec<BufferHandle>,
3250    /// This cull's own hysteresis state, and not the camera's.
3251    ///
3252    /// A shadow view selects from the camera's eye at the camera's scale, like
3253    /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3254    /// it reaches a different answer for the same group, and an answer carried
3255    /// between frames needs somewhere of its own to be carried. Sharing the
3256    /// camera's buffer would be two rules writing one history and each undoing
3257    /// the other's band every frame.
3258    ///
3259    /// One per cull rather than one for the shadow pass, even though every one of
3260    /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3261    /// between them would be several dispatches writing one element with nothing
3262    /// ordering them.
3263    ///
3264    /// **This is what a cull costs that is not a dispatch.** It is
3265    /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3266    /// resident group count words of device-local
3267    /// memory, held for the renderer's whole life whether anything is drawn
3268    /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3269    /// budget rather than "however many lights the scene has" — and the reason a
3270    /// point light's six faces share one of these rather than owning six.
3271    group_state: BufferHandle,
3272}
3273
3274impl ForwardRenderer {
3275    /// Builds both pipelines and makes [`scene::demo`] resident.
3276    ///
3277    /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3278    /// nothing else — so the frame this draws is the one the golden suite has
3279    /// always compared, and every existing caller is untouched.
3280    ///
3281    /// `target_format` must be the format the tonemap pass will render into —
3282    /// dynamic rendering checks pipeline and attachment formats against each
3283    /// other at pass-begin time, not at creation.
3284    ///
3285    /// # Errors
3286    ///
3287    /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3288    pub fn new(
3289        device: &dyn Device,
3290        queue: QueueHandle,
3291        target_format: Format,
3292    ) -> Result<Self, HalError> {
3293        Self::with_scene(device, queue, target_format, &scene::demo())
3294    }
3295
3296    /// Builds both pipelines and makes `scene` resident.
3297    ///
3298    /// Everything in the description is created here and never grows: the
3299    /// geometry pools, the cluster pool, the material table, the page, the
3300    /// instance array and the bucket table are all sized and filled once. See
3301    /// [`crate::scene`] for why that split is where the seam is, and for the
3302    /// four places a description's *order* decides what the frame looks like.
3303    ///
3304    /// `target_format` must be the format the tonemap pass will render into —
3305    /// dynamic rendering checks pipeline and attachment formats against each
3306    /// other at pass-begin time, not at creation.
3307    ///
3308    /// # No description is too small
3309    ///
3310    /// One mesh and one material row is a scene, and so is
3311    /// [`scene::demo`]'s four and three. Nothing on this type names a
3312    /// description entry by position any more — the five `set_*` demo wrappers
3313    /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3314    /// and the row a caller wrote its **own** description in.
3315    ///
3316    /// # Errors
3317    ///
3318    /// [`HalError::InvalidDescriptor`] if the description cannot be made
3319    /// resident as written: a page layer that is not its kind's extent's worth of
3320    /// RGBA8, a page kind holding layers at no extent, a material row naming a
3321    /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3322    /// levels, a cluster array with a read outside itself in it (see
3323    /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3324    /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3325    /// capacity and what the description needs, because the answer to it is to
3326    /// raise the number. Every one of those is settled **before the first device
3327    /// object exists**, so a refusal leaks nothing.
3328    ///
3329    /// [`HalError`] otherwise, from any seam call — including the geometry a
3330    /// pool refuses for itself, such as vertex bytes that are not a whole number
3331    /// of vertices. A backend that cannot build a pipeline says so here rather
3332    /// than drawing nothing later, and a failure part-way through releases
3333    /// everything already created, so a caller that retries or exits leaves
3334    /// nothing behind.
3335    pub fn with_scene(
3336        device: &dyn Device,
3337        queue: QueueHandle,
3338        target_format: Format,
3339        scene: &SceneDesc<'_>,
3340    ) -> Result<Self, HalError> {
3341        Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3342    }
3343
3344    /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3345    /// the build so the thread running it can keep its window alive.
3346    ///
3347    /// # What it is for: a build on the thread that owns the window
3348    ///
3349    /// The build needs the device, so it runs on whichever thread holds it —
3350    /// for a game that is the loop thread, which also owns the window, and a
3351    /// desktop marks a window hung when its thread takes no message for a few
3352    /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3353    /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3354    /// whole build.
3355    ///
3356    /// # Where it is called
3357    ///
3358    /// Where the time is, which was measured rather than guessed. With a cold
3359    /// driver shader cache — a player's first launch, or the first after a
3360    /// driver update — **pipeline creation is most of the build**. Measured in
3361    /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3362    /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3363    /// mesh and page uploads took about 0.1 s either way. So `service` runs
3364    /// after every mesh upload (each level of a DAG), after every page layer's
3365    /// mip chain and each page's upload, after each of the camera's
3366    /// post-processing subsystems, before every mesh-pass and grass pipeline,
3367    /// and between the build's other phases.
3368    ///
3369    /// **The longest gap left is one pipeline**, and a pipeline cannot be
3370    /// split: on that scene, cold, it was the forward pass's colour pipeline
3371    /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3372    /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3373    /// eight times slower under contention still calls back inside the five
3374    /// seconds Windows allows.
3375    ///
3376    /// `service` sees nothing of the build and cannot touch the renderer or the
3377    /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3378    /// request — is the caller's to keep for later, as
3379    /// `crcbl_shell::Shell::keep_alive` does.
3380    ///
3381    /// # Errors
3382    ///
3383    /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3384    /// through releases everything already created.
3385    pub fn with_scene_serviced(
3386        device: &dyn Device,
3387        queue: QueueHandle,
3388        target_format: Format,
3389        scene: &SceneDesc<'_>,
3390        service: &mut dyn FnMut(),
3391    ) -> Result<Self, HalError> {
3392        Self::build_on_path(
3393            device,
3394            queue,
3395            target_format,
3396            scene,
3397            device.preferred_geometry_path(),
3398            service,
3399        )
3400    }
3401
3402    /// Builds exactly the requested geometry tail, independently of the device's
3403    /// performance preference. Capabilities remain available to other callers.
3404    ///
3405    /// # Errors
3406    ///
3407    /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3408    /// when the requested tail lacks its required feature. Other failures follow
3409    /// [`Self::with_scene`]'s rollback contract.
3410    pub fn with_scene_on_path(
3411        device: &dyn Device,
3412        queue: QueueHandle,
3413        target_format: Format,
3414        scene: &SceneDesc<'_>,
3415        geometry_path: GeometryPath,
3416    ) -> Result<Self, HalError> {
3417        Self::build_on_path(
3418            device,
3419            queue,
3420            target_format,
3421            scene,
3422            geometry_path,
3423            &mut || {},
3424        )
3425    }
3426
3427    /// The body of [`Self::with_scene_on_path`] and
3428    /// [`Self::with_scene_serviced`], calling `service` where the latter
3429    /// documents.
3430    fn build_on_path(
3431        device: &dyn Device,
3432        queue: QueueHandle,
3433        target_format: Format,
3434        scene: &SceneDesc<'_>,
3435        geometry_path: GeometryPath,
3436        service: &mut dyn FnMut(),
3437    ) -> Result<Self, HalError> {
3438        let required = match geometry_path {
3439            GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3440            GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3441            GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3442        };
3443        let missing = required.difference(device.caps().features);
3444        if !missing.is_empty() {
3445            return Err(HalError::UnsupportedFeatures { missing });
3446        }
3447        let mut rollback = Rollback::default();
3448        match Self::build(
3449            device,
3450            queue,
3451            target_format,
3452            scene,
3453            geometry_path,
3454            &mut rollback,
3455            service,
3456        ) {
3457            Ok(renderer) => Ok(renderer),
3458            Err(error) => {
3459                rollback.run(device);
3460                Err(error)
3461            }
3462        }
3463    }
3464
3465    /// Everything `build` needs to be true of a description, checked **before
3466    /// the first device object exists**.
3467    ///
3468    /// That placement is the whole design of this function. `build` hands the
3469    /// geometry pool and the material table to the rollback and creates a dozen
3470    /// objects with `?` between them; a check that ran part way down that list
3471    /// would be a new early exit on the wrong side of a handover, and a rejected
3472    /// description would leak two device-local buffers. Run from the top of
3473    /// `build`, a refusal costs nothing to unwind because nothing was made.
3474    ///
3475    /// # Errors
3476    ///
3477    /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3478    /// is wrong with it.
3479    fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3480        let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3481        // A renderer draws meshes, and every table below is sized from them:
3482        // with none, the mesh table's sizing has no level to take a maximum
3483        // of. A scene that draws only the sky is one with meshes and no
3484        // instances.
3485        if scene.meshes.is_empty() {
3486            return refuse(
3487                "a scene description needs at least one mesh; one with meshes and no \
3488                 instances draws only the sky"
3489                    .to_owned(),
3490            );
3491        }
3492        // Every layer's length against its own kind's extent, and layers at no
3493        // extent at all. Checked by the type that owns the page rather than
3494        // here, because that is where a page can be built wrong and where the
3495        // check can be made to fail; see `PageDesc::check`.
3496        scene.page.check()?;
3497        // The probe grid's counts against the rows it carries, which is what
3498        // bounds the shader's fetch. Checked by the type that owns the grid, on
3499        // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3500        scene.probes.check()?;
3501        // A row naming a layer the page does not have is an out-of-range sample,
3502        // which nothing below the seam reports.
3503        //
3504        // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3505        // value: it is a sentinel rather than an index — `0xFFFF`, one past
3506        // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3507        // fragment stage never reads a page for it. Exempting it here is what
3508        // lets a material name no texture without the page having to carry a
3509        // layer for it to point at — or, since row (d), having to exist at all.
3510        //
3511        // **Per kind**, because the kinds are separate images with separate
3512        // layer lists and separate extents: a row pointed at a base-colour layer
3513        // number would pass a check that only counted one of them and then
3514        // sample past the end of the other image.
3515        for (row, material) in scene.materials.iter().enumerate() {
3516            for kind in PageKind::ALL {
3517                let names = match kind {
3518                    PageKind::BaseColor => material.base_color_texture,
3519                    PageKind::Normal => material.normal_texture,
3520                    PageKind::MetallicRoughnessOcclusion => {
3521                        material.metallic_roughness_occlusion_texture
3522                    }
3523                    PageKind::Emissive => material.emissive_texture,
3524                };
3525                if names == mesh::GpuMaterial::NO_PAGE {
3526                    continue;
3527                }
3528                let have = scene.page.layers(kind).len();
3529                if names as usize >= have {
3530                    return refuse(format!(
3531                        "material row {row} samples {} page layer {names}, and that page \
3532                         has {have}",
3533                        kind.label()
3534                    ));
3535                }
3536            }
3537        }
3538
3539        for (index, desc) in scene.meshes.iter().enumerate() {
3540            let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3541                continue;
3542            };
3543            // Zipped together at upload and again at
3544            // `ClusterDag::selection_records`, so a short list would silently
3545            // leave a level's clusters reading the level below's vertices.
3546            if levels.len() != dag.levels.len() {
3547                return refuse(format!(
3548                    "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3549                    desc.label,
3550                    levels.len(),
3551                    dag.levels.len()
3552                ));
3553            }
3554            for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3555                let want = level.positions.len() * mesh::VERTEX_STRIDE;
3556                if bytes.len() != want {
3557                    return refuse(format!(
3558                        "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3559                         position(s), which is {want}",
3560                        desc.label,
3561                        bytes.len(),
3562                        level.positions.len()
3563                    ));
3564                }
3565            }
3566        }
3567
3568        // **Every read the mesh stage makes from a cluster array lands inside
3569        // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3570        // terms exactly — see `MeshClusters::check`, which is where the reason
3571        // it cannot be checked below the seam is argued. Both variants carry
3572        // the same type beside a vertex count, so both are checked the same way.
3573        for (index, desc) in scene.meshes.iter().enumerate() {
3574            let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3575                Geometry::Flat {
3576                    vertices, clusters, ..
3577                } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3578                Geometry::Dag { dag, .. } => dag
3579                    .levels
3580                    .iter()
3581                    .map(|level| (level.positions.len(), &level.clusters))
3582                    .collect(),
3583            };
3584            for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3585                if let Err(fault) = clusters.check(vertices) {
3586                    return refuse(format!(
3587                        "mesh {index} ({}) level {depth} {fault}",
3588                        desc.label
3589                    ));
3590                }
3591            }
3592        }
3593
3594        // **Capacity, summed over the whole description**, which is the one
3595        // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3596        // do refuse their own overflow, but they refuse it part way through
3597        // filling something that already exists, and the pair of numbers
3598        // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3599        // carries to tell fragmentation from a full pool says nothing *here*:
3600        // the pool was created empty a few lines below, nothing has been freed
3601        // in it, so its free list is one block and the largest block and the
3602        // total are the same number. At build the answer is always "raise this
3603        // capacity", so it is said by name and before anything is created.
3604        let mut vertices: u64 = 0;
3605        let mut indices: u64 = 0;
3606        for desc in &scene.meshes {
3607            match &desc.geometry {
3608                Geometry::Flat {
3609                    vertices: bytes,
3610                    indices: list,
3611                    ..
3612                } => {
3613                    // Bytes that are not a whole number of vertices are the
3614                    // pool's to refuse, and it refuses before it allocates.
3615                    vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3616                    indices += list.len() as u64;
3617                }
3618                Geometry::Dag { levels, dag, .. } => {
3619                    for bytes in levels {
3620                        vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3621                    }
3622                    for level in &dag.levels {
3623                        // The call the upload itself makes, so the two cannot
3624                        // disagree about what a level costs.
3625                        indices += level.indices().len() as u64;
3626                    }
3627                }
3628            }
3629        }
3630        let entries: u64 = scene
3631            .meshes
3632            .iter()
3633            .map(|desc| desc.geometry.levels() as u64)
3634            .sum();
3635        for (pool, needed, capacity) in [
3636            ("vertex pool", vertices, scene.capacities.vertices),
3637            ("index pool", indices, scene.capacities.indices),
3638            ("mesh table", entries, scene.capacities.meshes),
3639            (
3640                "material table",
3641                scene.materials.len() as u64,
3642                scene.capacities.materials,
3643            ),
3644            (
3645                "probe table",
3646                scene.probes.probes.len() as u64,
3647                scene.capacities.probes,
3648            ),
3649        ] {
3650            if needed > u64::from(capacity) {
3651                return refuse(format!(
3652                    "the {pool} holds {capacity} and the description needs {needed}"
3653                ));
3654            }
3655        }
3656        Ok(())
3657    }
3658
3659    /// The body of [`ForwardRenderer::with_scene`], recording what it has
3660    /// created into `rollback` as it goes and calling `service` where
3661    /// [`ForwardRenderer::with_scene_serviced`] documents.
3662    fn build(
3663        device: &dyn Device,
3664        queue: QueueHandle,
3665        target_format: Format,
3666        scene: &SceneDesc<'_>,
3667        geometry_path: GeometryPath,
3668        rollback: &mut Rollback,
3669        service: &mut dyn FnMut(),
3670    ) -> Result<Self, HalError> {
3671        // Before anything exists, so a refused description leaks nothing — see
3672        // `check_scene`, which is where that placement is argued.
3673        Self::check_scene(scene)?;
3674
3675        // Resolved before anything is created, because it decides the *shape*
3676        // of what is created — the bind group layout, which pipeline kind the
3677        // pass builds, and what a bucket's constant block says. A device on the
3678        // mesh path never builds the raster pipeline and a device on either
3679        // indirect tail never builds the mesh one, which is what makes "the
3680        // frame came out of the mesh stage" a fact about the object graph
3681        // rather than a claim about a branch.
3682        let emit = EmitTail::from_path(geometry_path);
3683        // And whether that tail draws a range of buckets per call, which only
3684        // changes what the passes record — the constant blocks carry the words
3685        // both shapes read — so it decides nothing about what is created.
3686        let range_limit = emit.range_limit(&device.caps());
3687        // **A second capability, asked separately.** `Features::TASK_SHADER` is
3688        // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3689        // amplification stage this renderer builds where the device has one and
3690        // leaves out where it does not — and a device without it keeps drawing
3691        // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3692        // nothing and emits every cluster. Same picture, more work.
3693        let culls_clusters = emit.is_mesh()
3694            && device
3695                .caps()
3696                .features
3697                .contains(crcbl_hal::Features::TASK_SHADER);
3698
3699        let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3700        // What an `InstanceDesc::mesh` index resolves through: one id per
3701        // description mesh, in description order, and each of them that mesh's
3702        // **level 0** whatever the path — because it is the entry the cull pass
3703        // reads a bounding box out of, and a DAG's coarser levels approximate
3704        // the same surface inside the same box.
3705        let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3706        // The scene's own triangles, kept for the probe-visibility capture and
3707        // for nothing else — and kept at all only when the description reserves
3708        // a probe, so a scene without one pays no memory for this rung. Taken
3709        // here because `scene` is the caller's and is read once.
3710        let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3711        // The same list one level down: what a caller reserving a skinned region
3712        // names its mesh with. Read here beside the ids rather than from
3713        // `residents` later, because the descriptions this came from are the
3714        // caller's and are read once.
3715        let skinnable_meshes: Vec<Option<MeshHandle>> =
3716            residents.iter().map(|mesh| mesh.skinnable).collect();
3717        // The handles are `Copy`, so they can be read out before the pool
3718        // becomes the rollback's — which it must be before the first `?` below,
3719        // or a failed pipeline would leak two device-local buffers. The index
3720        // pool is not named here at all: it is bound at draw time rather than
3721        // descriptor-written, so only the vertex pool and the mesh table reach a
3722        // bind group.
3723        let vertices = pool.vertex_buffer();
3724        let mesh_table = pool.table_buffer();
3725        rollback.pool = Some(pool);
3726
3727        // §3.2's texture side, before the table that indexes it: a material row
3728        // is written with a layer number, so the layer has to exist to be named.
3729        //
3730        // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3731        // three answers the kind itself owns — its format, its mip filter and
3732        // its device label — and everything else about creating a page is the
3733        // same code. Two hand-written copies were what let the normal page be
3734        // created through the colour page's filter for as long as nobody
3735        // compared the two, and rung 3 adds two more kinds to get wrong.
3736        //
3737        // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3738        // normal page, and that is the colour-space decision.** A base-colour
3739        // description's texels are sRGB-encoded, which is what glTF defines a
3740        // base-colour texture to be, so the format is what makes the sampler
3741        // decode them — and `mesh.slang` then multiplies a linear texel by a
3742        // linear `base_color` and lights in linear, exactly as it did before
3743        // there was a texture. A normal texel is a *number* and nothing decodes
3744        // it. See `PageKind::format`, and topic 44's rung 2.
3745        //
3746        // Every layer's length against its kind's extent was settled by
3747        // `check_scene` above, before this device object existed.
3748        //
3749        // **Every layer goes up with its mip chain**, built here on the host by
3750        // [`crate::mip`] — topic 43's filtering rung.
3751        // The chain is what a trilinear sampler needs to stop shimmering on a
3752        // minified surface, and it is built at upload rather than by a compute
3753        // pass because the page's format is what decodes it and a host chain is
3754        // the same bytes on every backend.
3755        //
3756        // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3757        // refuses a zero-layer image and every bind group has to fill both page
3758        // bindings, so a page nothing names is created 1×1 in its own format
3759        // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3760        // and which is magenta so that a frame says so if it ever does.
3761        //
3762        // The upload itself is [`upload_page`], shared with
3763        // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3764        // renderer is built exactly as this one was. A layer's chain is host
3765        // work proportional to its texels, so a page of many large layers is
3766        // serviced one layer at a time.
3767        let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3768        let mut page_extents = [(1, 1); PageKind::ALL.len()];
3769        let mut page_layers = [0; PageKind::ALL.len()];
3770        for kind in PageKind::ALL {
3771            let layers = scene.page.layers(kind);
3772            let (page, extent) = upload_page(
3773                device,
3774                queue,
3775                kind,
3776                scene.page.extent(kind),
3777                layers,
3778                service,
3779            )?;
3780            rollback.textures.push(page);
3781            page_extents[kind.index()] = (extent, extent);
3782            page_layers[kind.index()] = layers.len();
3783            pages[kind.index()] = Some(page);
3784            service();
3785        }
3786        let [
3787            Some(base_color_page),
3788            Some(normal_page),
3789            Some(mro_page),
3790            Some(emissive_page),
3791        ] = pages
3792        else {
3793            unreachable!("the loop above fills a slot for every PageKind::ALL entry");
3794        };
3795
3796        // The page's sampler at the device's default — see `create_page_sampler`
3797        // for what it filters, and `set_anisotropy` for how a caller moves it.
3798        let anisotropy = Self::anisotropy_for(&device.caps());
3799        let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
3800        rollback.samplers.push(base_color_sampler);
3801        // What every slot's groups are built naming, and what each moves off
3802        // only at its own frame — see `ForwardRenderer::adopt_pages`.
3803        let page_bindings = PageBindings {
3804            sampler: base_color_sampler,
3805            views: [
3806                base_color_page.view,
3807                normal_page.view,
3808                mro_page.view,
3809                emissive_page.view,
3810            ],
3811        };
3812
3813        // The material table, before the instances: an instance is written with
3814        // the material id it carries, so the row has to exist to be named.
3815        let (materials, material_ids) = Self::build_materials(device, scene)?;
3816        let material_buffer = materials.buffer();
3817        rollback.materials = Some(materials);
3818
3819        // Topic 50's irradiance grid: the table is created here once, and
3820        // `crate::probe_gather`'s compute pass rewrites its rows every frame —
3821        // see [`crate::probe`]. **Created even for a description with no probes**, because
3822        // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
3823        // honest filler for "no probes were authored" is the zeroed row the
3824        // shader's clamp lands on.
3825        let probe_table = ProbeTable::new(
3826            device,
3827            queue,
3828            &ProbeTableDesc {
3829                label: Some("forward"),
3830                capacity: scene.capacities.probes,
3831                frames: FRAMES_IN_FLIGHT,
3832            },
3833        )?;
3834        // Into the rollback before it is filled, so a copy that fails releases
3835        // the buffers rather than leaking them.
3836        rollback.probes = Some(probe_table);
3837        let probe_table = rollback.probes.as_ref().expect("just stored");
3838        probe_table.fill(device, queue, &scene.probes.probes)?;
3839        // Read out here, like the instance ring's below and for the same
3840        // reason: the handles are `Copy`, and the loop that builds the bind
3841        // groups mutates the rollback the table now lives in.
3842        let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3843            .map(|frame| probe_table.buffer(frame))
3844            .collect();
3845        // The irradiance probes' updater, built **only** for a
3846        // description that asked for it. A volume left at
3847        // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
3848        // the default really is the frame every scene drew before this landed.
3849        let probe_gather = match scene.probes.update {
3850            ProbeUpdate::Authored => None,
3851            ProbeUpdate::EveryFrame => Some(ProbeGather::new(
3852                device,
3853                &ProbeGatherDesc {
3854                    label: Some("forward probes"),
3855                    volume: scene.probes.volume,
3856                    probes: &probe_buffers,
3857                },
3858            )?),
3859        };
3860        rollback.probe_gather = probe_gather;
3861        let probe_gather = rollback.probe_gather.take();
3862        service();
3863
3864        // **Empty.** Every object in the scene arrives through
3865        // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
3866        // renderer that inserted one of its description's meshes here would put
3867        // an object in a caller's frame that the caller never asked for.
3868        let instances = InstancePool::new(
3869            device,
3870            &InstancePoolDesc {
3871                label: Some("forward instances"),
3872                capacity: scene.capacities.instances,
3873                frames_in_flight: FRAMES_IN_FLIGHT,
3874            },
3875        )?;
3876        // Same handle-then-hand-over dance as the geometry pool above: the
3877        // buffers are `Copy` and are read out before the pool becomes the
3878        // rollback's, which it must be before the first `?` below — after which
3879        // nothing needs the pool again until `begin_frame`.
3880        let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
3881        rollback.instances = Some(instances);
3882
3883        // The two compute passes, and the buffers the draws come out of. Built
3884        // here rather than beside the pipelines below because the mesh bind
3885        // group names one of its buffers, so it has to exist first.
3886        //
3887        // The bucket table, and the one place its order is decided.
3888        //
3889        // **Built by walking the description**, which is what makes a duplicate
3890        // structurally impossible rather than refused: every bucket's mesh id is
3891        // the id of the description mesh it came from, and two description
3892        // meshes are two uploads with two table entries however alike their
3893        // geometry is. That matters because `draw_gen.slang`'s scatter takes the
3894        // *first* bucket whose mesh id matches, so a second bucket naming one
3895        // mesh would never draw anything at all.
3896        //
3897        // One bucket per mesh, except for two things. A DAG is one bucket where
3898        // an amplification stage picks its cut per cluster and one per level
3899        // where the cull pass picks a uniform one — see [`buckets_for`]. And the
3900        // whole run is repeated once per **material mode** the scene holds, so
3901        // an instance's mode picks a bucket exactly as its mesh does; see
3902        // [`ForwardRenderer::bucket_modes`].
3903        //
3904        // **Mode-major: every mesh's run for one mode, then the next mode's.**
3905        // A mode picks the pipeline a pass binds, so this makes each pipeline's
3906        // partition — [`ForwardRenderer::depth_partitions`] and
3907        // [`ForwardRenderer::sided_partitions`] — one contiguous run of
3908        // buckets, which a device with a draw index records as one ranged call
3909        // rather than a call per bucket — and which the mesh tail behind a
3910        // task stage must have, because it draws each partition as one flat
3911        // call of its run. `DEPTH_MODES` order makes a sided partition one run
3912        // too: opaque sits beside masked, and double-sided beside both.
3913        //
3914        // **Once per mode the scene holds, not once per mode that exists.** A
3915        // scene whose materials are all opaque gets exactly the table it always
3916        // had — same length, same order, same bytes — so the twin costs nothing
3917        // where nothing is masked, which is every demo and every golden here. A
3918        // bucket is not free: every pass records one indirect call per bucket
3919        // per view, and every generator holds its run start.
3920        let scene_modes: Vec<u32> = {
3921            let held: Vec<u32> = DEPTH_MODES
3922                .into_iter()
3923                .filter(|mode| {
3924                    scene
3925                        .materials
3926                        .iter()
3927                        .any(|material| material.mode() == *mode)
3928                })
3929                .collect();
3930            // A description with no materials at all still needs a bucket per
3931            // mesh, or nothing it holds can be drawn.
3932            if held.is_empty() {
3933                vec![DEPTH_MODES[0]]
3934            } else {
3935                held
3936            }
3937        };
3938        // One mode's run: every description mesh's levels, in description
3939        // order. `bucket_bases` is where each mesh starts within it, so the
3940        // tables below can be filled in mesh by mesh rather than by re-deriving
3941        // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
3942        let mut mode_run: Vec<u32> = Vec::new();
3943        let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
3944        for resident in &residents {
3945            bucket_bases.push(mode_run.len());
3946            mode_run
3947                .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
3948        }
3949        let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
3950        // The mode each of those buckets draws, in step with it.
3951        let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
3952        for mode in &scene_modes {
3953            bucket_meshes.extend_from_slice(&mode_run);
3954            bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
3955        }
3956        let bucket_count = u32::try_from(bucket_meshes.len())
3957            .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
3958
3959        // Topic 25's selection tables, and the one thing that
3960        // decides whether `draw_gen.slang` takes a uniform cut at all.
3961        //
3962        // Every mesh id gets an entry, because the shader indexes this with
3963        // `GpuInstance::mesh` and an instance can name any of them; the default
3964        // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
3965        // so a mesh with no hierarchy resolves back to itself with no branch.
3966        // **A DAG keeps that default on the mesh path**, which is how a device
3967        // already descending it per cluster avoids a second, coarser cut on top
3968        // of it — the suppression is data rather than a branch in the shader.
3969        //
3970        // **Sized by the mesh table's capacity, not by the meshes resident in
3971        // it**, because that is the invariant `draw_gen.slang`'s
3972        // `mesh_levels_of` states and indexes on: "every entry an instance can
3973        // name is filled". The read is unbounded and an instance's mesh id is a
3974        // bare table index, so a table sized to the description alone is an
3975        // out-of-range read of whatever the packer laid down next for any id the
3976        // description did not fill. What it finds there decides the frame: zeros
3977        // resolve to mesh 0 and draw another mesh's geometry, and a live
3978        // `group_count` sends `select_level`'s loop over a count no allocation
3979        // backs, which on radv is a hard GPU recovery rather than a wrong
3980        // picture. That is not a hypothetical: it is what a skinned instance
3981        // naming an alias entry did until 2026-08, before it learned to name its
3982        // source mesh instead.
3983        let table_len = usize::try_from(scene.capacities.meshes)
3984            .unwrap_or(usize::MAX)
3985            .max(
3986                usize::try_from(
3987                    residents
3988                        .iter()
3989                        .flat_map(|resident| resident.levels.iter().copied())
3990                        .max()
3991                        .unwrap_or_else(|| {
3992                            unreachable!("check_scene refused an empty description")
3993                        })
3994                        + 1,
3995                )
3996                .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
3997            );
3998        let mut level_meshes: Vec<u32> = (0..table_len)
3999            .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4000            .collect();
4001        let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4002            .iter()
4003            .map(|&id| level_select::MeshLevels {
4004                first_level: id,
4005                ..level_select::MeshLevels::FLAT
4006            })
4007            .collect();
4008        // Every DAG's groups end to end, in description order, and where each
4009        // one's run starts. `ClusterSelect` records name a group by its index in
4010        // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4011        // several DAGs concatenate without `crcbl-shaders` knowing they did.
4012        let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4013        let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4014        for (index, desc) in scene.meshes.iter().enumerate() {
4015            first_groups.push(
4016                u32::try_from(level_groups.len())
4017                    .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4018            );
4019            let Geometry::Dag { dag, .. } = &desc.geometry else {
4020                continue;
4021            };
4022            let groups = dag.level_groups();
4023            let id = residents[index].id();
4024            mesh_levels[id as usize] = level_select::MeshLevels {
4025                first_group: first_groups[index],
4026                group_count: u32::try_from(groups.len())
4027                    .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4028                // **The mesh path suppresses the uniform cut with a top level of
4029                // zero, not with a group count of zero**, and the difference is
4030                // the hysteresis state: `draw_gen.slang` judges every group it is
4031                // given whatever level it answers, and the amplification stage
4032                // reads those answers. A record naming no groups would leave the
4033                // state untouched and every cluster of the patch collapsed. A
4034                // top level of zero makes the level loop's minimum unreachable,
4035                // so the instance routes to the mesh it already names — which is
4036                // level 0.
4037                first_level: if emit.is_mesh() {
4038                    id
4039                } else {
4040                    u32::try_from(level_meshes.len())
4041                        .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4042                },
4043                top_level: if emit.is_mesh() {
4044                    0
4045                } else {
4046                    u32::try_from(residents[index].levels.len() - 1)
4047                        .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4048                },
4049            };
4050            level_groups.extend(groups);
4051            if !emit.is_mesh() {
4052                level_meshes.extend_from_slice(&residents[index].levels);
4053            }
4054        }
4055
4056        // §3.5's clusters, on the path that reads them and on no other. The
4057        // records are `crcbl-shaders`' — cooked, because the builder is
4058        // `crcbl-scene`'s and the renderer must not depend on that crate — and
4059        // they arrive in bucket-mesh order so a bucket's range is its own
4060        // index. See `crate::cluster_pool`.
4061        //
4062        // Before the draw generation below rather than after it, because the
4063        // per-bucket cluster counts are the x extent of each bucket's mesh
4064        // dispatch and that pass writes the argument structure carrying them.
4065        let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4066        let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4067        let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4068        if emit.is_mesh() {
4069            // A flat mesh is one pool entry and its clusters carry
4070            // `ClusterSelect::ALWAYS`, so the descent draws them from every
4071            // camera; a DAG is **one entry per level**, laid end to end.
4072            let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4073            // Where each description mesh's entries start, on `bucket_bases`'
4074            // terms — the two differ exactly where a DAG's levels are one bucket
4075            // and several entries.
4076            let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4077            for (index, desc) in scene.meshes.iter().enumerate() {
4078                entry_bases.push(cooked.len());
4079                match &desc.geometry {
4080                    Geometry::Flat { clusters, .. } => {
4081                        cooked.push(PooledMesh::without_lod(clusters.clone()));
4082                    }
4083                    Geometry::Dag { dag, .. } => {
4084                        let selection = dag
4085                            .selection_records(&residents[index].vertex_bases, first_groups[index]);
4086                        for (level, records) in dag.levels.iter().zip(selection) {
4087                            cooked.push(PooledMesh {
4088                                clusters: level.clusters.clone(),
4089                                selection: records,
4090                            });
4091                        }
4092                    }
4093                }
4094            }
4095
4096            let clusters = ClusterPool::new(device, "forward", &cooked)?;
4097            let range = |entry: usize| {
4098                clusters
4099                    .range(entry)
4100                    .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4101            };
4102            // **A DAG's levels are one run, not one per bucket.** `concatenate`
4103            // lays the entries down in the order it was given them, so the
4104            // levels are contiguous: the bucket starts where level 0 does and
4105            // reaches to the end of the last level. That is what lets one
4106            // dispatch cover a cut spanning several of them — and it is why a
4107            // flat mesh, whose one entry is the whole sum, needs no second case.
4108            mesh_clusters.reserve(residents.len());
4109            for (index, resident) in residents.iter().enumerate() {
4110                let entry = entry_bases[index];
4111                let base = range(entry).base;
4112                let count: u32 = (entry..entry + resident.levels.len())
4113                    .map(|entry| range(entry).count)
4114                    .sum();
4115                // **Every one of this mesh's buckets, not only the first.** A
4116                // mode twin draws the same geometry, so it dispatches over the
4117                // same clusters; a twin left at zero launches no workgroup and
4118                // its instances vanish from the frame. One bucket per mode here,
4119                // because the mesh path takes `buckets_for` of one, each a whole
4120                // mode's run past the one before.
4121                for slot in 0..scene_modes.len() {
4122                    let bucket = slot * mode_run.len() + bucket_bases[index];
4123                    bucket_cluster_bases[bucket] = base;
4124                    bucket_clusters[bucket] = count;
4125                }
4126                mesh_clusters.push(ClusterRange { base, count });
4127            }
4128
4129            rollback.clusters = Some(clusters);
4130            service();
4131        }
4132
4133        // One ring per shadow view, indexed `[view][frame]`: topic 25's
4134        // observable, one word per resident cluster holding the cut the descent
4135        // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4136        // share the camera's, which [`View::build`] allocates beside its cull.
4137        //
4138        // Allocated on the whole mesh path rather than only where there is an
4139        // amplification stage to write them, because the layout declares
4140        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4141        let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4142        if emit.is_mesh() {
4143            let count = rollback
4144                .clusters
4145                .as_ref()
4146                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4147                .count();
4148            let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4149                let mut buffers = Vec::with_capacity(instance_buffers.len());
4150                for frame in 0..instance_buffers.len() {
4151                    let buffer = device.create_buffer(&BufferDesc {
4152                        label: Some(&format!("{label} {frame}")),
4153                        size: u64::from(count) * 4,
4154                        usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4155                        memory: MemoryLocation::DeviceLocal,
4156                    })?;
4157                    rollback.buffers.push(buffer);
4158                    buffers.push(buffer);
4159                }
4160                Ok(buffers)
4161            };
4162            for view in 0..SHADOW_VIEWS {
4163                tile_selection.push(ring(&format!("shadow selection {view}"))?);
4164            }
4165        }
4166
4167        // --- the mesh pass ---
4168        //
4169        // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4170        // because a lit mesh is not a Tier A feature. The bindless shape — a
4171        // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4172        // texture array — is topic 03's, at P3.
4173        // **Which stage pulls the geometry**, and the only thing the two shapes
4174        // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4175        // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4176        // and every backend refuses a layout carrying it on a device without
4177        // `Features::MESH_SHADER` — which is exactly the device that never
4178        // reaches this arm.
4179        //
4180        // **`TASK` joins it when there is an amplification stage**, and the
4181        // union is deliberately over every binding rather than the eight
4182        // `taskMain` actually reads. Slang's Metal backend materialises every
4183        // global in every entry point of a module — the argument bindings 6 to
4184        // 8 already carry — so a layout that named only the task stage's own
4185        // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4186        // runner this team cannot debug on.
4187        let geometry = match (emit.is_mesh(), culls_clusters) {
4188            (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4189            (true, false) => ShaderStages::MESH,
4190            (false, _) => ShaderStages::VERTEX,
4191        };
4192        let mut mesh_entries = vec![
4193            BindGroupLayoutEntry {
4194                binding: 0,
4195                visibility: geometry.union(ShaderStages::FRAGMENT),
4196                kind: BindingKind::UniformBuffer { dynamic: false },
4197                count: 1,
4198                flags: BindingFlags::empty(),
4199            },
4200            BindGroupLayoutEntry {
4201                binding: 1,
4202                // **Both stages, and here it is the FRAGMENT half that needs
4203                // saying** — binding 6 and 7 are the mirror image, where the
4204                // fragment stage plainly reads the row and the vertex half is
4205                // the one Slang forces. Slang's Metal backend materialises
4206                // every module global into every entry point, so
4207                // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4208                // its body dereferences it or not — and Metal's debug layer
4209                // answers a declared-but-unbound fragment argument with
4210                // `missing Buffer binding at index N`, once per draw. Vulkan,
4211                // D3D12 and WebGPU all accept a visibility wider than the
4212                // shader's reads, so naming FRAGMENT costs them nothing but the
4213                // entry itself.
4214                //
4215                // **It does not cost a redundant bind on Metal either**, and
4216                // that is what makes it safe rather than a trade: `crcbl-mtl`
4217                // consults `MTLPipelineOption::BindingInfo` reflection and
4218                // issues the fragment-stage bind only where `MTLBinding::isUsed`
4219                // says the compiled function kept the argument. This entry is
4220                // the permission; the reflection is the decision.
4221                visibility: geometry.union(ShaderStages::FRAGMENT),
4222                kind: BindingKind::StorageBuffer {
4223                    // The shader says `StructuredBuffer`, not
4224                    // `RWStructuredBuffer`, so this is the truth rather than a
4225                    // hint — and it is what lets the graph merge read-after-read.
4226                    read_only: true,
4227                    dynamic: false,
4228                    stride: size_of::<u32>() as u32,
4229                },
4230                count: 1,
4231                flags: BindingFlags::empty(),
4232            },
4233            BindGroupLayoutEntry {
4234                binding: 2,
4235                // Both stages, for binding 1's reason exactly.
4236                visibility: geometry.union(ShaderStages::FRAGMENT),
4237                kind: BindingKind::StorageBuffer {
4238                    // `StructuredBuffer` again: the vertex stage reads its
4239                    // instance and writes nothing. The *host* writes this one
4240                    // every frame, which is a mapped write rather than a shader
4241                    // one and does not make it read-write here.
4242                    read_only: true,
4243                    dynamic: false,
4244                    stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4245                },
4246                count: 1,
4247                flags: BindingFlags::empty(),
4248            },
4249            BindGroupLayoutEntry {
4250                binding: 3,
4251                // Both stages, for binding 1's reason exactly.
4252                visibility: geometry.union(ShaderStages::FRAGMENT),
4253                // `dynamic: true`, and it is the whole mechanism: it is what
4254                // lets a draw say where its run of instances starts without
4255                // `draw_indexed`'s own base instance, which the module docs and
4256                // `mesh.slang`'s header explain the targets disagree about.
4257                // Same shape, for the same reason, as `crate::sprite_pass`'s.
4258                kind: BindingKind::UniformBuffer { dynamic: true },
4259                count: 1,
4260                flags: BindingFlags::empty(),
4261            },
4262            BindGroupLayoutEntry {
4263                binding: 4,
4264                // Both stages, for binding 1's reason exactly.
4265                visibility: geometry.union(ShaderStages::FRAGMENT),
4266                kind: BindingKind::StorageBuffer {
4267                    // The mesh table. `StructuredBuffer` again — the vertex
4268                    // stage looks its mesh up and writes nothing — and one
4269                    // buffer shared by every frame's group, because unlike the
4270                    // instance array nothing rewrites it between frames.
4271                    read_only: true,
4272                    dynamic: false,
4273                    stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4274                },
4275                count: 1,
4276                flags: BindingFlags::empty(),
4277            },
4278            BindGroupLayoutEntry {
4279                binding: 5,
4280                // Both stages, for binding 1's reason exactly.
4281                visibility: geometry.union(ShaderStages::FRAGMENT),
4282                kind: BindingKind::StorageBuffer {
4283                    // The per-bucket runs of surviving instances. Read-only
4284                    // here and written by the draw-argument pass, which is a
4285                    // different bind group and a different pass — the graph is
4286                    // what orders the two.
4287                    read_only: true,
4288                    dynamic: false,
4289                    stride: size_of::<u32>() as u32,
4290                },
4291                count: 1,
4292                flags: BindingFlags::empty(),
4293            },
4294            BindGroupLayoutEntry {
4295                binding: 6,
4296                // **Both stages, and the union is not belt-and-braces.** The
4297                // fragment stage is where `mesh.slang` now reads the table, so
4298                // it plainly needs it — a pipeline layout that leaves it out is
4299                // refused outright by wgpu and reported as
4300                // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4301                // The vertex half has to stay because Slang's Metal backend
4302                // materialises every global in every entry point: `vertexMain`
4303                // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4304                // whether it reads it or not, so dropping VERTEX would break
4305                // Metal alone, on a runner this team cannot debug on.
4306                visibility: geometry.union(ShaderStages::FRAGMENT),
4307                kind: BindingKind::StorageBuffer {
4308                    // The material table. One buffer in every frame's group,
4309                    // like the mesh table above and unlike the instance ring:
4310                    // a material is written when it is created, not per frame.
4311                    read_only: true,
4312                    dynamic: false,
4313                    stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4314                },
4315                count: 1,
4316                flags: BindingFlags::empty(),
4317            },
4318            BindGroupLayoutEntry {
4319                binding: BASE_COLOR_PAGE_BINDING,
4320                // Both stages, for binding 6's reason exactly: the fragment
4321                // stage samples it, and Slang's Metal backend materialises
4322                // every global in every entry point — `vertexMain` in
4323                // `msl/mesh.metal` takes the texture whether it reads it or
4324                // not, so a layout without VERTEX would break Metal alone.
4325                visibility: geometry.union(ShaderStages::FRAGMENT),
4326                // **`D2Array`, and the layout is where wgpu wants to hear it.**
4327                // The other three backends read the dimension off the bound
4328                // view and never consult this; WebGPU compares the two at
4329                // pipeline creation and refuses the pair, which is what a
4330                // layout claiming `D2` over an array view got — "expects
4331                // dimension = D2, but given a view with dimension = D2Array".
4332                kind: BindingKind::SampledImage {
4333                    view_type: ImageViewType::D2Array,
4334                    sample_type: SampleType::Float,
4335                },
4336                // **`count: 1`, and this is the binding-model decision.** One
4337                // `D2Array` image whose *layers* the material rows index is
4338                // `BindingModel::ArrayPages`; an array of `count` descriptors
4339                // indexed per fragment would be `Bindless` and would need
4340                // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4341                // So this layout is legal on every device, exactly as the six
4342                // buffers above are, and no `BindingFlags` appear anywhere in
4343                // this file yet.
4344                count: 1,
4345                flags: BindingFlags::empty(),
4346            },
4347            BindGroupLayoutEntry {
4348                binding: PAGE_SAMPLER_BINDING,
4349                visibility: geometry.union(ShaderStages::FRAGMENT),
4350                kind: BindingKind::Sampler { comparison: false },
4351                count: 1,
4352                flags: BindingFlags::empty(),
4353            },
4354        ];
4355        if emit.is_mesh() {
4356            // §3.5's four extra reads, and only on the path that has them.
4357            // Adding them unconditionally would make every device declare four
4358            // buffers `mesh.slang` does not name — and WebGPU, which checks a
4359            // bind group against its layout entry for entry, would then need
4360            // four buffers created for a path that never reads them.
4361            //
4362            // `read_only: true` on all four, which is the truth rather than a
4363            // hint: the mesh stage indexes them and writes nothing, and it is
4364            // what lets the graph merge read-after-read.
4365            //
4366            // Four different element types, so four strides, in binding order:
4367            // the clusters (`Meshlet`), the cluster vertex and corner pools
4368            // (`uint` each), and the per-cluster draw arguments
4369            // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4370            let cluster_strides = [
4371                crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4372                size_of::<u32>() as u32,
4373                size_of::<u32>() as u32,
4374                crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4375            ];
4376            mesh_entries.extend(
4377                (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4378                    .zip(cluster_strides)
4379                    .map(|(binding, stride)| {
4380                        BindGroupLayoutEntry {
4381                            binding,
4382                            // **Not the fragment stage.** These four are the geometry
4383                            // stage's alone, and `mesh_cluster.slang` has no fragment entry
4384                            // point of its own to materialise them into — its fragment
4385                            // stage is `mesh.slang`'s, which does not declare mesh-only
4386                            // buffers.
4387                            visibility: geometry,
4388                            kind: BindingKind::StorageBuffer {
4389                                read_only: true,
4390                                dynamic: false,
4391                                stride,
4392                            },
4393                            count: 1,
4394                            flags: BindingFlags::empty(),
4395                        }
4396                    }),
4397            );
4398        }
4399        // Both mesh entry points retain these declarations. Omitting unused
4400        // task buffers would shift later native buffer indices on the plain
4401        // mesh path, so the layout includes them on both paths.
4402        if emit.is_mesh() {
4403            mesh_entries.push(BindGroupLayoutEntry {
4404                binding: CLUSTER_CULL_BINDING,
4405                visibility: geometry,
4406                // **The same block the instance cull reads**, not a copy: one
4407                // camera, one frustum, and no way for the two rejections to
4408                // disagree about which. `dynamic: false` because there is one
4409                // block per frame rather than one per bucket.
4410                kind: BindingKind::UniformBuffer { dynamic: false },
4411                count: 1,
4412                flags: BindingFlags::empty(),
4413            });
4414            mesh_entries.push(BindGroupLayoutEntry {
4415                binding: CLUSTER_CULL_STATS_BINDING,
4416                visibility: geometry,
4417                kind: BindingKind::StorageBuffer {
4418                    // **The one writable binding this pass has.** The stage adds
4419                    // to a counter, so `read_only: false` is the truth rather
4420                    // than a hint, and it is what makes the graph order this
4421                    // write after the draw-argument pass's read of the same
4422                    // buffer.
4423                    read_only: false,
4424                    dynamic: false,
4425                    stride: size_of::<u32>() as u32,
4426                },
4427                count: 1,
4428                flags: BindingFlags::empty(),
4429            });
4430        }
4431        // Topic 18's cascades, read by the fragment stage and declared last —
4432        // above `mesh_cluster.slang`'s range rather than inside it, for the
4433        // reason `SHADOW_ATLAS_BINDING` gives.
4434        //
4435        // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4436        // binding 7's reason exactly: Slang's Metal backend materialises every
4437        // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4438        // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4439        // [[sampler(1)]]` whether it reads them or not.
4440        mesh_entries.push(BindGroupLayoutEntry {
4441            binding: SHADOW_ATLAS_BINDING,
4442            visibility: geometry.union(ShaderStages::FRAGMENT),
4443            kind: BindingKind::SampledImage {
4444                view_type: ImageViewType::D2,
4445                // **`Depth`, and this is the field the seam grew for this
4446                // pass.** WebGPU will only bind a `D32Float` view through a
4447                // depth sample type, and its shader side agrees — the WGSL
4448                // artifact declares `texture_depth_2d`. The other three
4449                // backends take the interpretation off the view's format and
4450                // never read this.
4451                sample_type: SampleType::Depth,
4452            },
4453            count: 1,
4454            flags: BindingFlags::empty(),
4455        });
4456        mesh_entries.push(BindGroupLayoutEntry {
4457            binding: SHADOW_SAMPLER_BINDING,
4458            visibility: geometry.union(ShaderStages::FRAGMENT),
4459            // The sampler-side twin of the line above: `sampler_comparison` in
4460            // the WGSL, `SamplerComparisonState` in the HLSL, and a
4461            // `compareEnable` on the Vulkan sampler object. The layout has to
4462            // say so on WebGPU and cannot on the other three.
4463            kind: BindingKind::Sampler { comparison: true },
4464            count: 1,
4465            flags: BindingFlags::empty(),
4466        });
4467        // DAG geometry and selection state, in the mesh-only binding range.
4468        if emit.is_mesh() {
4469            mesh_entries.push(BindGroupLayoutEntry {
4470                binding: CLUSTER_SELECT_BINDING,
4471                visibility: geometry,
4472                // Read-only and read by **both** mesh entry points, unlike the
4473                // pair below: a cluster's `vertex_base` is which level of a DAG
4474                // its geometry lives in, which an un-amplified stage needs just
4475                // as much as an amplified one.
4476                kind: BindingKind::StorageBuffer {
4477                    read_only: true,
4478                    dynamic: false,
4479                    stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4480                },
4481                count: 1,
4482                flags: BindingFlags::empty(),
4483            });
4484        }
4485        // Both on the whole mesh path, for the two above's reason exactly: the
4486        // amplification stage is the only writer and the only reader, and the
4487        // Metal argument table counts entries rather than reading binding
4488        // numbers.
4489        if emit.is_mesh() {
4490            mesh_entries.push(BindGroupLayoutEntry {
4491                binding: CLUSTER_SELECTION_BINDING,
4492                visibility: geometry,
4493                kind: BindingKind::StorageBuffer {
4494                    // The second writable binding: the amplification stage
4495                    // records the cut it chose, one word per resident cluster.
4496                    read_only: false,
4497                    dynamic: false,
4498                    stride: size_of::<u32>() as u32,
4499                },
4500                count: 1,
4501                flags: BindingFlags::empty(),
4502            });
4503            mesh_entries.push(BindGroupLayoutEntry {
4504                binding: CLUSTER_GROUP_STATE_BINDING,
4505                visibility: geometry,
4506                kind: BindingKind::StorageBuffer {
4507                    // Topic 25's hysteresis state, and read-only
4508                    // here: the draw-argument pass is its only writer, which is
4509                    // what lets a stage with one workgroup per cluster use a
4510                    // decision that has to survive a frame.
4511                    read_only: true,
4512                    dynamic: false,
4513                    stride: size_of::<u32>() as u32,
4514                },
4515                count: 1,
4516                flags: BindingFlags::empty(),
4517            });
4518        }
4519
4520        // The shared fragment light list and froxel grid are bound on every
4521        // path and in every group, unlike the four
4522        // conditional ranges above: `mesh.slang`'s fragment stage reads them
4523        // whatever geometry produced the primitive, so there is no configuration
4524        // in which the layout can omit them.
4525        //
4526        // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4527        // exactly: Slang's Metal backend materialises every global into every
4528        // entry point, so the vertex and mesh stages take these buffers whether
4529        // they read them or not.
4530        mesh_entries.push(BindGroupLayoutEntry {
4531            binding: LIGHT_LIST_BINDING,
4532            visibility: geometry.union(ShaderStages::FRAGMENT),
4533            kind: BindingKind::StorageBuffer {
4534                read_only: true,
4535                dynamic: false,
4536                stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4537            },
4538            count: 1,
4539            flags: BindingFlags::empty(),
4540        });
4541        mesh_entries.push(BindGroupLayoutEntry {
4542            binding: LIGHT_GRID_BINDING,
4543            visibility: geometry.union(ShaderStages::FRAGMENT),
4544            kind: BindingKind::StorageBuffer {
4545                // **Read-only here**, and written by the clustering pass through
4546                // a layout of its own. The graph is what orders the two.
4547                read_only: true,
4548                dynamic: false,
4549                stride: size_of::<u32>() as u32,
4550            },
4551            count: 1,
4552            flags: BindingFlags::empty(),
4553        });
4554        // Topic 46's occlusion channel, last of the set
4555        // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4556        // than tidy.
4557        //
4558        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4559        // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4560        // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4561        mesh_entries.push(BindGroupLayoutEntry {
4562            binding: AMBIENT_OCCLUSION_BINDING,
4563            visibility: geometry.union(ShaderStages::FRAGMENT),
4564            kind: BindingKind::SampledImage {
4565                view_type: ImageViewType::D2,
4566                // **`Float`, unlike the shadow atlas above.** This one is an
4567                // ordinary `R8Unorm` colour image and the WGSL artifact declares
4568                // `texture_2d<f32>` for it; `Depth` here would be a layout
4569                // claiming a depth format the view does not have.
4570                sample_type: SampleType::Float,
4571            },
4572            count: 1,
4573            flags: BindingFlags::empty(),
4574        });
4575        // The irradiance grid, past the occlusion channel — see
4576        // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4577        //
4578        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4579        // `msl/mesh.metal` is again the proof rather than the theory: its
4580        // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4581        mesh_entries.push(BindGroupLayoutEntry {
4582            binding: PROBE_TABLE_BINDING,
4583            visibility: geometry.union(ShaderStages::FRAGMENT),
4584            kind: BindingKind::StorageBuffer {
4585                // **Read-only, and it stays read-only when the updater lands.**
4586                // The rows are device-local now — see [`crate::probe`], which is
4587                // where that is argued — so the seam no longer forces this;
4588                // what forces it is that the shading path does not write a
4589                // probe and this layout has no headroom to pretend otherwise.
4590                // The raster path is at the WebGPU per-stage storage-buffer
4591                // ceiling already, which the check at the end of the layout
4592                // holds it to, so `read_only: false` here would buy a write
4593                // nothing performs at the price of a binding budget there is
4594                // none of. The irradiance probes' gather is a
4595                // compute pass with a layout of its own, and that is where the
4596                // writable binding of these rows belongs.
4597                read_only: true,
4598                dynamic: false,
4599                stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4600            },
4601            count: 1,
4602            flags: BindingFlags::empty(),
4603        });
4604        if emit.is_mesh() {
4605            // DAG group records follow the common buffer prefix; the
4606            // remaining mesh-only buffers are sorted after them below.
4607            //
4608            // **Conditional like the mesh-only bindings**, and not for tidiness:
4609            // the raster path's layout is at the WebGPU storage-buffer ceiling
4610            // already, so a row bound unconditionally would be a renderer that
4611            // cannot be built in a browser. The mesh path's own reads sit outside
4612            // that count because `ShaderStages::MESH` is not one of the three
4613            // stages it sums.
4614            mesh_entries.push(BindGroupLayoutEntry {
4615                binding: LEVEL_GROUP_TABLE_BINDING,
4616                // Only the geometry stage reads this table: the
4617                // heatmap's colour is chosen where the cluster is known, and
4618                // `mesh.slang`'s fragment stage — which is this pipeline's —
4619                // does not declare this buffer.
4620                visibility: geometry,
4621                kind: BindingKind::StorageBuffer {
4622                    // Read-only and read by **both** mesh entry points, like
4623                    // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4624                    // `emit_cluster`, so a row present for one and absent for the
4625                    // other is a descriptor read out of an empty slot.
4626                    read_only: true,
4627                    dynamic: false,
4628                    stride: size_of::<u32>() as u32,
4629                },
4630                count: 1,
4631                flags: BindingFlags::empty(),
4632            });
4633        }
4634
4635        // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4636        //
4637        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4638        // Metal backend materialises every global into every entry point, so
4639        // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4640        // whether it reads it or not.
4641        mesh_entries.push(BindGroupLayoutEntry {
4642            binding: SPECULAR_DFG_BINDING,
4643            visibility: geometry.union(ShaderStages::FRAGMENT),
4644            kind: BindingKind::SampledImage {
4645                view_type: ImageViewType::D2,
4646                // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4647                // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4648                sample_type: SampleType::Float,
4649            },
4650            count: 1,
4651            flags: BindingFlags::empty(),
4652        });
4653
4654        // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4655        //
4656        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4657        // Metal backend materialises every global into every entry point, so
4658        // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4659        // or not. **A sampled image and not a storage buffer**, which costs this
4660        // layout nothing at the WebGPU ceiling checked below — that limit counts
4661        // storage buffers, and this row is a texture.
4662        mesh_entries.push(BindGroupLayoutEntry {
4663            binding: NORMAL_PAGE_BINDING,
4664            visibility: geometry.union(ShaderStages::FRAGMENT),
4665            kind: BindingKind::SampledImage {
4666                view_type: ImageViewType::D2Array,
4667                // `Float`: an `Rgba8Unorm` image, declared
4668                // `texture_2d_array<f32>` by the WGSL artifact — the same
4669                // sample type the sRGB base-colour page reports, since both
4670                // decode to floats.
4671                sample_type: SampleType::Float,
4672            },
4673            count: 1,
4674            flags: BindingFlags::empty(),
4675        });
4676        // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4677        //
4678        // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4679        // `Float` because `Rgba16Float` is a filterable sampled format on every
4680        // target this engine opens, and the WGSL artifact declares it
4681        // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4682        // has to say what the module declared.
4683        mesh_entries.push(BindGroupLayoutEntry {
4684            binding: LTC_TABLE_BINDING,
4685            visibility: geometry.union(ShaderStages::FRAGMENT),
4686            kind: BindingKind::SampledImage {
4687                view_type: ImageViewType::D2,
4688                sample_type: SampleType::Float,
4689            },
4690            count: 1,
4691            flags: BindingFlags::empty(),
4692        });
4693        // Topic 45's contact-shadow channel, last of the set —
4694        // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4695        // tidy.
4696        //
4697        // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4698        // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4699        // backend materialises every global into every entry point whether that
4700        // stage reads it or not.
4701        mesh_entries.push(BindGroupLayoutEntry {
4702            binding: CONTACT_SHADOW_BINDING,
4703            visibility: geometry.union(ShaderStages::FRAGMENT),
4704            kind: BindingKind::SampledImage {
4705                view_type: ImageViewType::D2,
4706                sample_type: SampleType::Float,
4707            },
4708            count: 1,
4709            flags: BindingFlags::empty(),
4710        });
4711        // The irradiance probes' per-probe visibility maps, last
4712        // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4713        // structural.
4714        //
4715        // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4716        // dimension a layout entry claims against the view handed to it at
4717        // pipeline creation, which is the normal page's own note.
4718        // `UnfilterableFloat` for the same reason and measured the same way: the
4719        // image is `Rg32Float`, which is unfilterable without WebGPU's
4720        // `float32-filterable`, and this slot declared `Float` made Chromium
4721        // refuse the whole mesh bind group — "None of the supported sample types
4722        // (UnfilterableFloat) ... match the expected sample types (Float)" —
4723        // which took every 3D demo's frame to black. Reading it only with `Load`
4724        // does not lift that: the check is on the layout against the view's
4725        // format, not on how the shader gets at it.
4726        mesh_entries.push(BindGroupLayoutEntry {
4727            binding: PROBE_VISIBILITY_BINDING,
4728            visibility: geometry.union(ShaderStages::FRAGMENT),
4729            kind: BindingKind::SampledImage {
4730                view_type: ImageViewType::D2Array,
4731                sample_type: SampleType::UnfilterableFloat,
4732            },
4733            count: 1,
4734            flags: BindingFlags::empty(),
4735        });
4736        // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4737        // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4738        //
4739        // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4740        // page's three answers exactly, and for its reasons: Slang's Metal
4741        // backend materialises every global into every entry point, WebGPU
4742        // compares the declared dimension against the bound view, and both
4743        // images are `Rgba8Unorm`-family formats that decode to filterable
4744        // floats.
4745        for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4746            mesh_entries.push(BindGroupLayoutEntry {
4747                binding,
4748                visibility: geometry.union(ShaderStages::FRAGMENT),
4749                kind: BindingKind::SampledImage {
4750                    view_type: ImageViewType::D2Array,
4751                    sample_type: SampleType::Float,
4752                },
4753                count: 1,
4754                flags: BindingFlags::empty(),
4755            });
4756        }
4757        mesh_entries.sort_by_key(|entry| entry.binding);
4758        let mesh_desc = BindGroupLayoutDesc {
4759            label: Some(MESH_LAYOUT_LABEL),
4760            entries: &mesh_entries,
4761        };
4762        // **This layout is at the guaranteed limit with no headroom on the
4763        // raster path, in both raster stages**: the vertex stage takes every
4764        // storage buffer a WebGPU device promises, and since bindings 1 to 5
4765        // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4766        // takes the same number. A ninth in either is a renderer that cannot be
4767        // built in a browser or on SwiftShader, so it fails here rather than at
4768        // somebody else's `createPipelineLayout` — see
4769        // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4770        // mesh path's extra reads are outside the count.
4771        // `Some("mesh")`, which is the *pipeline* layout's label, not
4772        // `mesh_desc.label` — the error text reads "pipeline layout {label}
4773        // binds …", so naming the bind group layout there sends the reader to
4774        // the wrong object.
4775        check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4776        let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4777        rollback.bind_group_layouts.push(mesh_layout);
4778
4779        // A dynamic offset must be a multiple of the device's alignment, and one
4780        // block has to fit inside one stride. Read from the device rather than
4781        // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
4782        // typical desktop Vulkan driver.
4783        //
4784        // One stride for both blocks, sized for the larger — see
4785        // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
4786        // decided below.
4787        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
4788        let draw_stride =
4789            u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
4790                HalError::InvalidDescriptor(format!(
4791                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
4792                         offset can express"
4793                ))
4794            })?;
4795        let draw_constants = device.create_buffer(&BufferDesc {
4796            label: Some("mesh draw constants"),
4797            // A block per bucket per draw region: a region's draws name their
4798            // own run starts, and the mesh path's block names the region's
4799            // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
4800            size: u64::from(draw_stride)
4801                * u64::from(bucket_count)
4802                * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
4803            usage: BufferUsage::UNIFORM,
4804            memory: MemoryLocation::HostUpload,
4805        })?;
4806        rollback.buffers.push(draw_constants);
4807        // --- the shadow map's own resources ---
4808        //
4809        // Before the bind groups, because every one of them names the atlas or
4810        // the placeholder standing in for it.
4811        let (atlas_width, atlas_height) = shadow::atlas_extent();
4812        let shadow_atlas = device.create_image(&ImageDesc {
4813            label: Some("shadow atlas"),
4814            image_type: ImageType::D2,
4815            format: Format::D32Float,
4816            extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
4817            mip_levels: 1,
4818            samples: 1,
4819            // `TRANSFER_SRC` so a test can copy the cascades back and check
4820            // that something was written into them. A shadow map that stayed at
4821            // its clear value produces a frame that looks entirely plausible —
4822            // everything is lit — so the readback is the only thing that can
4823            // tell a working pass from one that drew nothing.
4824            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
4825                .union(ImageUsage::SAMPLED)
4826                .union(ImageUsage::TRANSFER_SRC),
4827        })?;
4828        rollback.images.push(shadow_atlas);
4829        let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
4830            label: Some("shadow atlas"),
4831            image: shadow_atlas,
4832            view_type: ImageViewType::D2,
4833            format: Format::D32Float,
4834            range: ImageSubresourceRange::all(Format::D32Float),
4835        })?;
4836        rollback.image_views.push(shadow_atlas_view);
4837
4838        let shadow_placeholder = device.create_image(&ImageDesc {
4839            label: Some("shadow placeholder"),
4840            image_type: ImageType::D2,
4841            format: Format::D32Float,
4842            extent: crcbl_hal::Extent3d::d2(1, 1),
4843            mip_levels: 1,
4844            samples: 1,
4845            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
4846        })?;
4847        rollback.images.push(shadow_placeholder);
4848        let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
4849            label: Some("shadow placeholder"),
4850            image: shadow_placeholder,
4851            view_type: ImageViewType::D2,
4852            format: Format::D32Float,
4853            range: ImageSubresourceRange::all(Format::D32Float),
4854        })?;
4855        rollback.image_views.push(shadow_placeholder_view);
4856
4857        // The occlusion placeholder, beside the shadow one and for the same
4858        // reason: every group of this layout has to fill
4859        // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
4860        // graph has an occlusion image to name.
4861        //
4862        // **Uploaded rather than cleared**, unlike the depth placeholder above,
4863        // and the four bytes are the whole point — see
4864        // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
4865        // Left undefined this would be a random ambient scale *and* a random
4866        // direction to steer it along, on any frame that fell back to it.
4867        let ambient_occlusion_placeholder = upload_texture(
4868            device,
4869            queue,
4870            "ssao placeholder",
4871            Format::Rgba8Unorm,
4872            1,
4873            1,
4874            &AMBIENT_OCCLUSION_NONE,
4875        )?;
4876        rollback.textures.push(ambient_occlusion_placeholder);
4877
4878        // The contact-shadow placeholder, beside the occlusion one and on its
4879        // terms exactly: every group of this layout has to fill
4880        // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
4881        // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
4882        // so a fragment that reads this one is a fragment the sun reaches
4883        // unobstructed.
4884        let contact_shadow_placeholder = upload_texture(
4885            device,
4886            queue,
4887            "contact shadow placeholder",
4888            Format::R8Unorm,
4889            1,
4890            1,
4891            &[CONTACT_SHADOW_NONE],
4892        )?;
4893        rollback.textures.push(contact_shadow_placeholder);
4894
4895        // The probe-visibility placeholder, on the two above it's terms: every
4896        // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
4897        // nothing has been captured when they are built. One texel of
4898        // [`probe_visibility_none`], which no surface is further away than, so a
4899        // probe read through it keeps all of its weight.
4900        let probe_visibility_placeholder = upload_texture_layers(
4901            device,
4902            queue,
4903            "probe visibility placeholder",
4904            Format::Rg32Float,
4905            1,
4906            1,
4907            &[&probe_visibility_none()],
4908        )?;
4909        rollback.textures.push(probe_visibility_placeholder);
4910
4911        // The split-sum `DFG` table, uploaded once and read by every frame this
4912        // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
4913        // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
4914        //
4915        // **Cooked bytes rather than a computed image**: the integrator
4916        // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
4917        // engine's goldens are compared across four backends with no tolerance.
4918        // Baking here would be four slightly different tables.
4919        let specular_dfg = upload_texture(
4920            device,
4921            queue,
4922            "dfg table",
4923            // Two bytes of fixed point per channel, high byte first — see
4924            // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
4925            // not the `Rg16Float` the format's own doc anticipated.
4926            Format::Rgba8Unorm,
4927            DFG_SIZE_U32,
4928            DFG_SIZE_U32,
4929            &dfg::pair_texels(),
4930        )?;
4931        rollback.textures.push(specular_dfg);
4932
4933        // The area lights' fit, beside it and on its terms — cooked bytes for
4934        // the same reason, and `Rgba16Float` rather than fixed point because
4935        // these are matrix entries rather than shares of arriving light.
4936        // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
4937        let ltc_table = upload_texture(
4938            device,
4939            queue,
4940            "ltc table",
4941            Format::Rgba16Float,
4942            LTC_SIZE_U32,
4943            LTC_SIZE_U32,
4944            &ltc::texels(),
4945        )?;
4946        rollback.textures.push(ltc_table);
4947        service();
4948
4949        // **A comparison sampler, and that is the PCF.** Each
4950        // `SampleCmpLevelZero` returns the filtered fraction of four texels that
4951        // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
4952        // comparisons rather than nine raw fetches it averages itself.
4953        //
4954        // `Greater` for the engine's reversed-Z, exactly as the depth *test*
4955        // is: the receiver survives when it is nearer the light than whatever
4956        // the map stored. `SamplerDesc::compare` carries the same warning.
4957        //
4958        // Clamped on every axis so a receiver just outside a cascade's box
4959        // reads the edge rather than wrapping into the opposite corner — the
4960        // shader's own bounds check is what actually handles that case, and this
4961        // is the second line of defence one texel wide.
4962        let shadow_sampler = device.create_sampler(&SamplerDesc {
4963            label: Some("shadow comparison"),
4964            mag_filter: FilterMode::Linear,
4965            min_filter: FilterMode::Linear,
4966            mip_filter: FilterMode::Nearest,
4967            address_mode: [SamplerAddressMode::ClampToEdge; 3],
4968            compare: Some(crcbl_hal::CompareOp::Greater),
4969            ..SamplerDesc::default()
4970        })?;
4971        rollback.samplers.push(shadow_sampler);
4972
4973        // --- the camera ---
4974        //
4975        // Everything the camera's picture needs of its own, built against the
4976        // scene resources above — see [`view`], which is where the line between
4977        // the two is drawn. Into the rollback whole as soon as it exists, so a
4978        // failure further down releases it with everything else.
4979        let slot_pages = vec![page_bindings; instance_buffers.len()];
4980        rollback.primary = Some(View::build(
4981            device,
4982            queue,
4983            &ViewInputs {
4984                id: ViewId::PRIMARY,
4985                effects: RenderEffects::all(),
4986                background: ViewBackground::Scene,
4987                lighting: ViewLighting::Scene,
4988                target_format,
4989                emit,
4990                instances: &instance_buffers,
4991                mesh_table,
4992                bucket_meshes: &bucket_meshes,
4993                bucket_modes: &bucket_modes,
4994                bucket_clusters: &bucket_clusters,
4995                bucket_cluster_bases: &bucket_cluster_bases,
4996                mesh_levels: &mesh_levels,
4997                level_groups: &level_groups,
4998                level_meshes: &level_meshes,
4999                instance_capacity: scene.capacities.instances,
5000                light_capacity: scene.capacities.lights,
5001                clusters: rollback.clusters.as_ref(),
5002                task_lanes: view::task_lanes(culls_clusters),
5003                mesh_layout,
5004                vertices,
5005                draw_constants,
5006                materials: material_buffer,
5007                pages: &slot_pages,
5008                probes: &probe_buffers,
5009                specular_dfg: specular_dfg.view,
5010                ltc_table: ltc_table.view,
5011                shadow_map: shadow_atlas_view,
5012                shadow_sampler,
5013                ambient_occlusion: ambient_occlusion_placeholder.view,
5014                contact_shadow: contact_shadow_placeholder.view,
5015                probe_visibility: probe_visibility_placeholder.view,
5016            },
5017            service,
5018        )?);
5019        let primary = rollback.primary.as_ref().expect("just stored");
5020
5021        // Written here and never again: **which word holds** a bucket's run
5022        // start is fixed by the bucket table and the capacity, and both are
5023        // fixed at build. What varies per frame is where the run starts and how
5024        // much of it is filled, and the GPU writes both — the start into that
5025        // word, the count into the bucket's indirect arguments. See
5026        // `mesh.slang`'s header for why the block names a word rather than
5027        // carrying the start.
5028        //
5029        // Taken from the camera's generator and bound for every generator's
5030        // draws: the shadow culls and every secondary view are built from the
5031        // same table and the same capacity, so `bucket_start_word` answers the
5032        // same for all of them.
5033        let draws = &primary.draws;
5034        let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5035        // **Every draw region's copy**, region 0's at the offsets
5036        // `bucket_constants` records and each further region a bucket count of
5037        // strides behind the one before: a region's draw reads its own run
5038        // start and — on the mesh path — its own argument structure, and the
5039        // two are the only words a region changes. See
5040        // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5041        for (region, (bucket, index)) in
5042            (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5043                (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5044            })
5045        {
5046            let offset = (region * bucket_count + bucket) * draw_stride;
5047            if region == 0 {
5048                bucket_constants[index] = offset;
5049            }
5050            let start_at = draws.region_start_word(region, bucket);
5051            // The mesh path's block says three more things — where this
5052            // bucket's mesh's clusters are, how many it has, and which element
5053            // of the indirect arguments holds its instance count — because a
5054            // dispatch carries none of them and a `draw_indexed_indirect` does
5055            // not need them. All three are fixed when the bucket table is,
5056            // exactly like `start_at`.
5057            let block = if emit.is_mesh() {
5058                crcbl_shaders::meshlet::ClusterDrawConstants {
5059                    start_at,
5060                    cluster_base: bucket_cluster_bases[index],
5061                    cluster_count: bucket_clusters[index],
5062                    // The region's argument structure, which is where this
5063                    // region's instance count is.
5064                    bucket: region * bucket_count + bucket,
5065                    // The same number the draw-argument pass indexes the state
5066                    // with, taken from the object that owns the buffer rather
5067                    // than recomputed from the group table — the two indexing it
5068                    // differently is a cluster reading another instance's
5069                    // decision.
5070                    group_stride: draws.group_stride(),
5071                    // Where the group records are in the table buffer, from the
5072                    // object that packed it — the screen-error heatmap's one
5073                    // input that is not already in the frame block. Taken from
5074                    // `DrawGen` rather than recomputed here for `group_stride`'s
5075                    // reason: two spellings of one offset is an overlay reading
5076                    // another region's words as a group.
5077                    level_groups_at: draws.table_offsets().level_groups_at,
5078                    // The same two numbers again as words of that buffer,
5079                    // which is where a draw that is not the first of a ranged
5080                    // call reads them — `mesh_cluster.slang`'s "One call for
5081                    // a range of buckets". This bucket's, not the region's
5082                    // argument structure's: the tables hold one word a bucket.
5083                    cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5084                    cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5085                    // Where this bucket's task chunks start in this region,
5086                    // and where the region's end: what a flat call binding
5087                    // this block searches between — `mesh_cluster.slang`'s
5088                    // `taskMain`.
5089                    chunk_starts_at: draws.chunk_start_word(region, bucket),
5090                    chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5091                }
5092                .to_bytes()
5093                .to_vec()
5094            } else {
5095                // **The bucket's mesh, which is not always the drawn instance's.**
5096                // A uniform cut selects one of a DAG's levels and each level is
5097                // a mesh table entry of its own, so this is what says which
5098                // geometry the draw's index range belongs to; the instance goes
5099                // on naming level 0. See `mesh::DrawConstants::mesh`.
5100                mesh::DrawConstants {
5101                    start_at,
5102                    mesh: bucket_meshes[index],
5103                    mesh_at: draws.bucket_mesh_word(bucket),
5104                }
5105                .to_bytes()
5106                .to_vec()
5107            };
5108            device.write_buffer(draw_constants, u64::from(offset), &block)?;
5109        }
5110
5111        let region_step = RegionStep {
5112            constants: bucket_count * draw_stride,
5113            args: draws.args_region_offset(1),
5114            counts: draws.counts_region_offset(1),
5115        };
5116
5117        // §3.3's cull, once per cascade and once per shadowed light. Each gets
5118        // its own `DrawGen` and therefore its own frustum, survivor list and
5119        // indirect arguments — which is what "one cull dispatch per cascade
5120        // against the same instance/geometry pools" means, and why the instance
5121        // ring and the mesh table below are the same handles the camera's cull
5122        // was given.
5123        //
5124        // **One per light rather than one per tile**, which is topic 18's fourth
5125        // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5126        // against the light's sphere once and draw that one visible set through
5127        // six matrices.
5128        //
5129        // **Built for every slot, including the ones no light may ever hold.** A
5130        // generator's buffers are sized by the instance capacity rather than by
5131        // the scene, so building one on demand would mean allocating device
5132        // memory inside `begin_frame` — and a frame that cannot allocate is a
5133        // frame that cannot draw. The unused ones cost memory and no dispatch:
5134        // `add_shadow_pass` records passes for the occupied slots alone.
5135        for cull in 0..SHADOW_CULLS {
5136            // Into the rollback as each is built, on the same terms as the
5137            // camera's: a failure two culls in has to release the first one,
5138            // and the rollback is the only thing that knows about it.
5139            let label = if cull < shadow::CASCADES {
5140                format!("shadow cascade {cull}")
5141            } else {
5142                format!("shadow light {}", cull - shadow::CASCADES)
5143            };
5144            let draws = DrawGen::new(
5145                device,
5146                queue,
5147                &DrawGenDesc {
5148                    label: Some(&label),
5149                    instances: &instance_buffers,
5150                    mesh_table,
5151                    bucket_meshes: &bucket_meshes,
5152                    bucket_modes: &bucket_modes,
5153                    bucket_clusters: &bucket_clusters,
5154                    bucket_cluster_bases: &bucket_cluster_bases,
5155                    mesh_levels: &mesh_levels,
5156                    level_groups: &level_groups,
5157                    level_meshes: &level_meshes,
5158                    instance_capacity: scene.capacities.instances,
5159                    // No view's: a shadow map is drawn from everything resident
5160                    // that casts, so an instance a camera hides still casts its
5161                    // shadow and one `set_instance_casts_shadow` turned off does
5162                    // not — on every geometry path, since this is the cull they
5163                    // all draw from. The reflective shadow maps draw these same
5164                    // survivors, so such an instance bounces no light either.
5165                    hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5166                    // A light slot may hold a point light, whose six faces cull
5167                    // separately into six regions of the one generator; a
5168                    // cascade never does.
5169                    mode: if cull < shadow::CASCADES {
5170                        crcbl_shaders::draw_gen::DrawMode::Plain
5171                    } else {
5172                        crcbl_shaders::draw_gen::DrawMode::Faces
5173                    },
5174                    task_lanes: view::task_lanes(culls_clusters),
5175                },
5176            )?;
5177            rollback.shadow_draws.push(draws);
5178            service();
5179        }
5180        // The handles are `Copy` and are read out here for the same reason the
5181        // camera's are above: the pool they came from is the rollback's now.
5182        let tile_buffers: Vec<TileBuffers> = rollback
5183            .shadow_draws
5184            .iter()
5185            .map(|draws| TileBuffers {
5186                runs: (0..instance_buffers.len())
5187                    .map(|frame| draws.runs(frame))
5188                    .collect(),
5189                args: (0..instance_buffers.len())
5190                    .map(|frame| draws.args(frame))
5191                    .collect(),
5192                cull_params: (0..instance_buffers.len())
5193                    .map(|frame| draws.cull_params(frame))
5194                    .collect(),
5195                cull_stats: (0..instance_buffers.len())
5196                    .map(|frame| draws.visible_count(frame))
5197                    .collect(),
5198                group_state: draws.group_state(),
5199            })
5200            .collect();
5201
5202        let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5203        let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5204        let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5205        let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5206        for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5207            // Everything a group of this layout names that is the same in all of
5208            // this frame's — the camera's list and table buffers included, which
5209            // a shadow view binds because the layout declares them and reads
5210            // nothing of. The per-group half is what `MeshGroup` below varies,
5211            // and the two exist so the colour pass's group and the shadow pass's
5212            // are one description rather than two that agree today.
5213            let shared = SharedBindings {
5214                vertices,
5215                draw_constants,
5216                mesh_table,
5217                materials: material_buffer,
5218                pages: page_bindings,
5219                clusters: rollback.clusters.as_ref(),
5220                shadow_sampler,
5221                lights: primary.lights.lights(frame),
5222                light_grid: primary.lights.grid(frame),
5223                probes: probe_buffers[frame],
5224                tables: primary.draws.tables(),
5225                specular_dfg: specular_dfg.view,
5226                ltc_table: ltc_table.view,
5227            };
5228
5229            // The same layout again, once per shadow view, differing in exactly
5230            // the things a view is: which matrix, and which cull's survivors.
5231            //
5232            // **The view's own uniforms and the cull's shared buffers**, which
5233            // is the whole of what a point light's six faces are: one visible
5234            // set, six matrices. `shadow_cull` is the map from a view to the
5235            // generator behind it, and it is a compile-time one because a bind
5236            // group names its buffers when it is created — where a face's *tile*
5237            // is decided per frame and reaches the device as a viewport.
5238            let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5239            let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5240            let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5241            let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5242            for view in 0..SHADOW_VIEWS {
5243                let buffers = &tile_buffers[if view < shadow::CASCADES {
5244                    view
5245                } else {
5246                    shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5247                }];
5248                let tile_uniforms = device.create_buffer(&BufferDesc {
5249                    label: Some("shadow view uniforms"),
5250                    size: mesh::FRAME_UNIFORMS_SIZE as u64,
5251                    usage: BufferUsage::UNIFORM,
5252                    memory: MemoryLocation::HostUpload,
5253                })?;
5254                rollback.buffers.push(tile_uniforms);
5255                let entries = MeshGroup {
5256                    uniforms: tile_uniforms,
5257                    instances: slot_instances,
5258                    runs: buffers.runs[frame],
5259                    args: buffers.args[frame],
5260                    // The amplification stage culls clusters against whatever
5261                    // frustum is in this block, and against
5262                    // `frame.camera_position` — which in a view's copy is the
5263                    // *light*. So the per-cluster cull rejects what faces away
5264                    // from the light, which is the right question for a shadow
5265                    // map and the wrong one to have asked with the camera's
5266                    // frustum.
5267                    cull_params: buffers.cull_params[frame],
5268                    cull_stats: buffers.cull_stats[frame],
5269                    // **This view's own**, and not the colour pass's: that pass
5270                    // is recorded last and would write over it. See
5271                    // `ForwardRenderer::shadow_selection`.
5272                    cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5273                    // Its cull's — see `TileBuffers::group_state`, which is
5274                    // where that budget is argued.
5275                    group_state: emit.is_mesh().then_some(buffers.group_state),
5276                    shadow_map: shadow_placeholder_view,
5277                    // A cascade shades nothing — the pipeline has no fragment
5278                    // stage — so this slot exists only because Metal
5279                    // materialises every global into every entry point.
5280                    ambient_occlusion: ambient_occlusion_placeholder.view,
5281                    contact_shadow: contact_shadow_placeholder.view,
5282                    probe_visibility: probe_visibility_placeholder.view,
5283                }
5284                .entries(&shared);
5285                let group = device.create_bind_group(&BindGroupDesc {
5286                    label: Some("shadow view"),
5287                    layout: mesh_layout,
5288                    entries: &entries,
5289                    variable_count: None,
5290                })?;
5291                rollback.bind_groups.push(group);
5292                frame_shadow_uniforms.push(tile_uniforms);
5293                frame_shadow_groups.push(group);
5294                frame_shadow_entries.push(entries);
5295                frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5296            }
5297            shadow_uniforms.push(frame_shadow_uniforms);
5298            shadow_groups.push(frame_shadow_groups);
5299            shadow_group_entries.push(frame_shadow_entries);
5300            shadow_selection.push(frame_shadow_selection);
5301            service();
5302        }
5303
5304        let mesh_set_layouts = [mesh_layout];
5305        let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5306            label: Some("mesh"),
5307            bind_group_layouts: &mesh_set_layouts,
5308            // The camera goes in the uniform buffer above rather than here:
5309            // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5310            // explicit that the substitute is a data-layout decision. So this
5311            // file needs no tier branch at all — it has been on Tier B's shape
5312            // since P1, and `crate::ui_pass` is where the split actually bites.
5313            push_constants: None,
5314        })?;
5315        rollback.pipeline_layouts.push(mesh_pipeline_layout);
5316
5317        // The colour pass's pipeline and its depth-only twin, out of one set of
5318        // modules — see [`MeshModules`], which is where the two shapes and the
5319        // reasons for them live. Both are created before either is unwrapped and
5320        // the modules are released between, so a failing creation leaks nothing.
5321        //
5322        // **Each shape is built twice, once per material side** — see
5323        // [`SidedPipelines`], which is where the cull modes and the reason for a
5324        // pipeline rather than a per-draw state live. The shadow tile clear is
5325        // the one exception: its triangle comes out of `SV_VertexID` and it
5326        // already culls nothing.
5327        //
5328        // **`service` before every one of them**: on a cold driver cache each is
5329        // a shader compilation, and this batch is the build's longest run of
5330        // them — see [`ForwardRenderer::with_scene_serviced`].
5331        let modules = MeshModules::new(device, emit, culls_clusters)?;
5332        let mesh_results = MeshModules::sided(|cull| {
5333            service();
5334            modules.color_pipeline(
5335                device,
5336                mesh_pipeline_layout,
5337                PolygonMode::Fill,
5338                cull,
5339                "forward",
5340            )
5341        });
5342        let shadow_results = MeshModules::sided(|cull| {
5343            service();
5344            modules.depth_pipeline(device, mesh_pipeline_layout, cull)
5345        });
5346        // And its cutout twin, which a frame whose material table masks alpha is
5347        // recorded with instead — see [`MeshModules::depth_masked_pipeline`].
5348        let depth_masked_results = MeshModules::sided(|cull| {
5349            service();
5350            modules.depth_masked_pipeline(device, mesh_pipeline_layout, cull)
5351        });
5352        // And the one that resets a tile, which the cadence rung needs and the
5353        // attachment's load operation cannot express — see
5354        // [`MeshModules::depth_clear_pipeline`].
5355        service();
5356        let shadow_clear_result = modules.depth_clear_pipeline(device, mesh_pipeline_layout);
5357        // And the irradiance probes' reflective shadow map, built
5358        // from the same modules and the same layout — see
5359        // [`MeshModules::rsm_pipeline`]. Built on every scene rather than only
5360        // on one whose probes ask to be updated: the modules are released a line
5361        // below and a pipeline built later would need them back, which is a
5362        // second shader compilation for a field a `ProbeGrid` decides.
5363        let rsm_results = MeshModules::sided(|cull| {
5364            service();
5365            modules.rsm_pipeline(device, mesh_pipeline_layout, cull)
5366        });
5367        modules.destroy(device);
5368        // Register every successful creation before propagating any error.
5369        // Results later in this batch may own pipelines even when the first
5370        // result failed; dropping an unvisited Result does not release a HAL
5371        // handle. The outer rollback owns all of them until build succeeds.
5372        for pipeline in mesh_results
5373            .iter()
5374            .chain(&shadow_results)
5375            .chain(&depth_masked_results)
5376            .chain(std::iter::once(&shadow_clear_result))
5377            .chain(&rsm_results)
5378            .flatten()
5379        {
5380            rollback.pipelines.push(*pipeline);
5381        }
5382        let into_sided = |results: [Result<GraphicsPipelineHandle, HalError>; 2]|
5383         -> Result<SidedPipelines, HalError> {
5384            let [single, double] = results;
5385            Ok(SidedPipelines { single: single?, double: double? })
5386        };
5387        let mesh_pipeline = into_sided(mesh_results)?;
5388        let shadow_pipeline = into_sided(shadow_results)?;
5389        let depth_masked_pipeline = into_sided(depth_masked_results)?;
5390        let shadow_clear_pipeline = shadow_clear_result?;
5391        let rsm_pipeline = into_sided(rsm_results)?;
5392
5393        // --- the tonemap pass ---
5394        let tonemap_entries = [
5395            BindGroupLayoutEntry {
5396                binding: 0,
5397                visibility: ShaderStages::FRAGMENT,
5398                kind: BindingKind::SampledImage {
5399                    view_type: ImageViewType::D2,
5400                    sample_type: SampleType::Float,
5401                },
5402                count: 1,
5403                flags: BindingFlags::empty(),
5404            },
5405            BindGroupLayoutEntry {
5406                binding: 1,
5407                visibility: ShaderStages::FRAGMENT,
5408                kind: BindingKind::Sampler { comparison: false },
5409                count: 1,
5410                flags: BindingFlags::empty(),
5411            },
5412            // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5413            // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5414            // decision restated: WebGPU has no push constants at all, so a range
5415            // here would split this pass into a tier A and a tier B form —
5416            // two layouts, two buffers and, because one Slang entry point reads
5417            // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5418            // one and never both, a second copy of `tonemap.slang`. Four bytes
5419            // once a frame do not buy that.
5420            //
5421            // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5422            // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5423            // in the vertex one, because the vertex stage generates three
5424            // corners out of `SV_VertexID` and reads nothing.
5425            BindGroupLayoutEntry {
5426                binding: 2,
5427                visibility: ShaderStages::FRAGMENT,
5428                kind: BindingKind::UniformBuffer { dynamic: false },
5429                count: 1,
5430                flags: BindingFlags::empty(),
5431            },
5432            // The measured exposure — see [`crate::exposure`]. **Bound on every
5433            // frame, whether or not anything measured**, because a binding that
5434            // comes and goes is a second pipeline layout and a second group
5435            // cache keyed on which one is live, to save four bytes. The block
5436            // above carries the switch that decides whether the shader reads it.
5437            BindGroupLayoutEntry {
5438                binding: 3,
5439                visibility: ShaderStages::FRAGMENT,
5440                kind: BindingKind::StorageBuffer {
5441                    // Written by `exposure.slang`'s reduce and read here —
5442                    // `StructuredBuffer` in this shader, which is the truth
5443                    // rather than a hint.
5444                    read_only: true,
5445                    dynamic: false,
5446                    stride: size_of::<u32>() as u32,
5447                },
5448                count: 1,
5449                flags: BindingFlags::empty(),
5450            },
5451        ];
5452        let tonemap_desc = BindGroupLayoutDesc {
5453            label: Some("tonemap scene"),
5454            entries: &tonemap_entries,
5455        };
5456        check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5457        let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5458        rollback.bind_group_layouts.push(tonemap_layout);
5459        let tonemap_set_layouts = [tonemap_layout];
5460        let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5461            label: Some("tonemap"),
5462            bind_group_layouts: &tonemap_set_layouts,
5463            push_constants: None,
5464        })?;
5465        rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5466        let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5467        let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5468        let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5469            label: Some("tonemap.slang"),
5470            spirv: TONEMAP.spirv(),
5471            wgsl: TONEMAP.wgsl(),
5472            msl: TONEMAP.msl(),
5473            // A container per entry point, for the reason the mesh module above
5474            // gives.
5475            dxil: &TONEMAP.dxil_containers(),
5476        })?;
5477        let tonemap_targets = [ColorTargetState::opaque(target_format)];
5478        let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5479            label: Some("tonemap"),
5480            layout: tonemap_pipeline_layout,
5481            vertex: ShaderEntry {
5482                module: tonemap_module,
5483                entry_point: tonemap_vertex,
5484            },
5485            fragment: Some(ShaderEntry {
5486                module: tonemap_module,
5487                entry_point: tonemap_fragment,
5488            }),
5489            // The full-screen triangle is deliberately oversized, so two of its
5490            // vertices are outside the viewport and its winding is not worth
5491            // reasoning about. `CullMode::None` is the honest setting.
5492            primitive: PrimitiveState::default(),
5493            depth_stencil: None,
5494            multisample: MultisampleState::default(),
5495            color_targets: &tonemap_targets,
5496        });
5497        device.destroy_shader_module(tonemap_module);
5498        let tonemap_pipeline = tonemap_pipeline?;
5499        rollback.pipelines.push(tonemap_pipeline);
5500        service();
5501
5502        // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5503        // leave a golden image depending on two rasterisers agreeing about
5504        // texel-centre arithmetic.
5505        let sampler = device.create_sampler(&SamplerDesc {
5506            label: Some("tonemap scene"),
5507            mag_filter: FilterMode::Nearest,
5508            min_filter: FilterMode::Nearest,
5509            mip_filter: FilterMode::Nearest,
5510            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5511            ..SamplerDesc::default()
5512        })?;
5513        rollback.samplers.push(sampler);
5514
5515        // --- the shadow atlas viewer ---
5516        //
5517        // Built last, so `Rollback::run` releases it first. It writes the
5518        // caller's target rather than a transient — it replaces the picture the
5519        // tonemap put there, which is [`crate::atlas_view`]'s argument — and it
5520        // records on no frame but the one that resolved
5521        // [`DebugView::ShadowAtlas`].
5522        rollback.atlas_viewer = Some(AtlasView::new(
5523            device,
5524            instance_buffers.len(),
5525            target_format,
5526            Self::build_fullscreen,
5527        )?);
5528        service();
5529
5530        Ok(Self {
5531            pool: rollback
5532                .pool
5533                .take()
5534                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5535            bucket_constants,
5536            region_step,
5537            bucket_modes,
5538            instances: rollback
5539                .instances
5540                .take()
5541                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5542            mesh_ids,
5543            skinnable_meshes,
5544            skinned_instances: Vec::new(),
5545            materials: rollback
5546                .materials
5547                .take()
5548                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5549            material_ids,
5550            probes: rollback
5551                .probes
5552                .take()
5553                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5554            probe_volume: scene.probes.volume,
5555            base_color_page,
5556            normal_page,
5557            mro_page,
5558            emissive_page,
5559            page_extents,
5560            page_layers,
5561            base_color_sampler,
5562            anisotropy,
5563            // Every slot's groups were just built naming these.
5564            slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5565            retired_pages: Vec::new(),
5566            // No frame has been recorded yet, and the counters say so rather
5567            // than reporting the count a frame *would* have.
5568            recorded_draws: 0,
5569            emit,
5570            range_limit,
5571            clusters: rollback.clusters.take(),
5572            culls_clusters,
5573            draw_constants,
5574            mesh_clusters,
5575            // One entry per description mesh, each holding one bucket per level,
5576            // where the cull pass takes a uniform cut — and nothing at all where
5577            // the amplification stage takes a per-cluster one. Read off the
5578            // bucket table that was actually built rather than re-derived from
5579            // the path.
5580            mesh_level_buckets: if emit.is_mesh() {
5581                Vec::new()
5582            } else {
5583                residents
5584                    .iter()
5585                    .enumerate()
5586                    .map(|(index, resident)| {
5587                        let base = bucket_bases[index];
5588                        (base..base + resident.levels.len())
5589                            .map(|bucket| {
5590                                u32::try_from(bucket)
5591                                    .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5592                            })
5593                            .collect()
5594                    })
5595                    .collect()
5596            },
5597            lod_error_budget: LOD_ERROR_BUDGET,
5598            lod_hold_ratio: LOD_HOLD_RATIO,
5599            // Overwritten by the first `begin_frame`, which is the only thing
5600            // that can know the viewport.
5601            shadow_lod_params: [0.0, 0.0, 0.0],
5602            extra_lights: Vec::new(),
5603            primary: rollback
5604                .primary
5605                .take()
5606                .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5607            views: Vec::new(),
5608            draw_tables: DrawTables {
5609                bucket_meshes,
5610                bucket_clusters,
5611                bucket_cluster_bases,
5612                mesh_levels,
5613                level_groups,
5614                level_meshes,
5615                instance_capacity: scene.capacities.instances,
5616                light_capacity: scene.capacities.lights,
5617            },
5618            frame_serial: 0,
5619            frame_scene: None,
5620            frame: 0,
5621            mesh_layout,
5622            mesh_pipeline_layout,
5623            mesh_pipeline,
5624            // Off, and unbuilt, on the ground grid's terms below: the wireframe
5625            // view is opt-in, so a caller that never asks for one draws the
5626            // frame it drew before `set_wireframe` existed.
5627            wireframe_pipeline: None,
5628            wireframe_on: false,
5629            occlusion_culling: OcclusionCulling::OFF,
5630            point_face_culls: true,
5631            shadow_view_tamper: None,
5632            // Off, on the line above's terms: the normals view is opt-in, so a
5633            // caller that never asks for one draws the frame it drew before
5634            // `set_normals_view` existed. It builds nothing, so there is no
5635            // second field here.
5636            normals_view: false,
5637            // Off on the same terms, and "off" here is a density of zero: the
5638            // shader's composite is exactly the identity there, so a caller who
5639            // never calls `set_fog` gets the frame byte for byte.
5640            fog: Fog::NONE,
5641            sky: Sky::NONE,
5642            atmosphere: None,
5643            sky_view: None,
5644            sky_view_build: None,
5645            lod_view: false,
5646            heatmap: false,
5647            occlusion_view: false,
5648            motion_view: false,
5649            bent_normal_view: false,
5650            cascade_view: false,
5651            atlas_view: false,
5652            // Following the camera, on the line above's terms: the selection eye
5653            // is the camera's until a caller pins it, so a renderer nobody calls
5654            // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5655            // handed before this field existed.
5656            frozen_selection_eye: None,
5657            shadow_atlas,
5658            shadow_atlas_view,
5659            shadow_placeholder,
5660            shadow_placeholder_view,
5661            shadow_sampler,
5662            shadow_pipeline,
5663            depth_masked_pipeline,
5664            shadow_clear_pipeline,
5665            rsm_pipeline,
5666            probe_gather,
5667            probe_update: scene.probes.update,
5668            // Overwritten by the first `begin_frame`, which is the only reader's
5669            // only source. Zero is the honest placeholder: no cascade has been
5670            // fitted yet, and a gather recorded against it would scale by zero
5671            // rather than by a number nobody chose.
5672            cascade_reach: 0.0,
5673            // Nothing has been fitted before the first `begin_frame`.
5674            rsm_cull_ready: false,
5675            sun_color: Vec3::ZERO,
5676            shadow_draws: std::mem::take(&mut rollback.shadow_draws),
5677            shadow_uniforms,
5678            shadow_prepare_views: Vec::new(),
5679            shadow_prepare_culls: Vec::new(),
5680            shadow_groups,
5681            shadow_selection,
5682            shadow_lights: shadow::Selection::default(),
5683            // Nothing has drawn the atlas, so the first frame draws every group
5684            // whatever it is asked for — which is also what gives the image a
5685            // defined content before anything samples it. A record is never
5686            // empty, so the first frame's is a change and takes every id past
5687            // the zero below it.
5688            shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
5689            shadow_group_id: vec![0; SHADOW_CULLS],
5690            shadow_group_writes: vec![0; SHADOW_CULLS],
5691            shadow_footprints: Vec::new(),
5692            shadow_dag_elements: std::collections::BTreeSet::new(),
5693            shadow_written: Vec::new(),
5694            shadow_moved: Vec::new(),
5695            shadow_pass_id: 0,
5696            shadow_pass_ran: Arc::new(AtomicU64::new(0)),
5697            shadow_pending: None,
5698            // A reach of zero, so every centre on the first frame is further
5699            // from what the image holds than the nothing it holds reaches —
5700            // which is the reset that frame should be.
5701            shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
5702            shadow_group_redrawn: vec![false; SHADOW_CULLS],
5703            shadow_atlas_layout: None,
5704            shadow_atlas_cached: false,
5705            shadow_cadence_reset: false,
5706            shadow_faces_redrawn: 0,
5707            shadow_cadence_request: None,
5708            shadow_atlas_clears: true,
5709            shadow_frame: 0,
5710            frame_skins: false,
5711            // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
5712            // by, so a slot has been through the whole loop before it is read.
5713            // `culls_clusters` rather than the device's feature bits: what
5714            // decides whether the cluster word is a count is whether *this
5715            // renderer* built an amplification stage.
5716            cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
5717            tonemap_layout,
5718            tonemap_pipeline_layout,
5719            tonemap_pipeline,
5720            sampler,
5721            // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
5722            // renderer nobody has called `set_exposure` on writes the frame it
5723            // wrote before the block existed.
5724            exposure: tonemap::DEFAULT_EXPOSURE,
5725            exposure_adaptation: None,
5726            // And the filmic roll-off over it: this renderer shades in linear
5727            // HDR, so a view that has asked for nothing gets the operator that
5728            // range was shaded for.
5729            tonemap_curve: tonemap::TonemapCurve::Aces,
5730            target_format,
5731            ambient_occlusion_placeholder,
5732            contact_shadow_placeholder,
5733            probe_visibility_placeholder,
5734            // Nothing has been captured, so every frame drawn before
5735            // `capture_probe_visibility` reads the placeholder and weighs every
5736            // probe at one — which is the frame this renderer drew before the
5737            // maps existed.
5738            probe_visibility: None,
5739            probe_occluders,
5740            specular_dfg,
5741            ltc_table,
5742            shadow_group_entries,
5743            // Off, and unbuilt: the grid is opt-in, so a caller that never asks
5744            // for one draws the frame it drew before this module existed.
5745            ground_grid: None,
5746            ground_grid_on: false,
5747            // Empty, and unbuilt: nothing has appended a segment, so this
5748            // renderer records the frame it recorded before the layer existed.
5749            debug_draw: DebugDraw::default(),
5750            atlas_viewer: rollback
5751                .atlas_viewer
5752                .take()
5753                .unwrap_or_else(|| unreachable!("the viewer was placed in the rollback above")),
5754            // Full resolution, which is the frame every caller of this type drew
5755            // before there was a knob — see [`Self::set_render_scale`].
5756            render_scale: 1.0,
5757            // The default stack the view wants, no quality clamp and no
5758            // override, which resolves to every effect this device permits but
5759            // the lens one — the frame every caller of this type drew before
5760            // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
5761            effect_request: EffectRequest::default(),
5762            device_effects: RenderEffects::all(),
5763            frame_effects: RenderEffects::DEFAULT_STACK,
5764            // What the switch says today, so a renderer built and never opened
5765            // still describes the frame it would draw. `begin_frame` reads it
5766            // again for the frame it opens.
5767            frame_ssao_blurs: crate::ssao::blur_passes(),
5768            // No frame has been recorded yet, on `recorded_draws`' terms.
5769            recorded_fullscreen: 0,
5770            // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
5771            recorded_debug_draw: 0,
5772            recorded_tile_clears: 0,
5773            // No bodies, so no pass: the frame every caller of this type drew
5774            // before water existed. Nothing is allocated until a body is set.
5775            water: WaterBodies::new(FRAMES_IN_FLIGHT),
5776            recorded_water_draws: 0,
5777            // No field, so no pass: the frame every caller of this type drew
5778            // before grass existed. The two calm wind layers are one texel
5779            // each and are what makes a field with no weather set still.
5780            grass: GrassScene::new(device, queue, FRAMES_IN_FLIGHT)?,
5781            wind: crcbl_shaders::wind::WindParams::default(),
5782            recorded_grass_draws: 0,
5783        })
5784    }
5785
5786    /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
5787    /// fragment entry points.
5788    ///
5789    /// One helper because every post pass in this crate wants the same
5790    /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
5791    /// differing in the module, the layout and the target format alone. The
5792    /// tonemap's stays written out where it is: it is the one that carries the
5793    /// *why* of the shape, and this is the shape repeated.
5794    ///
5795    /// The module is destroyed before the pipeline result is unwrapped, so a
5796    /// failing creation leaks nothing.
5797    ///
5798    /// # Errors
5799    ///
5800    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5801    fn build_fullscreen(
5802        device: &dyn Device,
5803        label: &str,
5804        shader: &crcbl_shaders::Shader,
5805        layout: PipelineLayoutHandle,
5806        color_targets: &[ColorTargetState],
5807    ) -> Result<GraphicsPipelineHandle, HalError> {
5808        Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
5809    }
5810
5811    /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
5812    /// against an attachment it does not write.
5813    ///
5814    /// The state is [`DepthStencilState::equal_depth_read_only`], whose
5815    /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
5816    /// depth must equal what is already there". One caller, [`crate::sky_pass`],
5817    /// which emits its triangle at the far plane so that the test selects
5818    /// exactly the pixels no geometry covered — see that module.
5819    ///
5820    /// # Errors
5821    ///
5822    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5823    fn build_tested_fullscreen(
5824        device: &dyn Device,
5825        label: &str,
5826        shader: &crcbl_shaders::Shader,
5827        layout: PipelineLayoutHandle,
5828        color_targets: &[ColorTargetState],
5829        depth_format: Format,
5830    ) -> Result<GraphicsPipelineHandle, HalError> {
5831        Self::build_fullscreen_with(
5832            device,
5833            label,
5834            shader,
5835            layout,
5836            color_targets,
5837            Some(DepthStencilState::equal_depth_read_only(depth_format)),
5838        )
5839    }
5840
5841    /// The body of the two above, which differ in their depth state and in
5842    /// nothing else.
5843    ///
5844    /// # Errors
5845    ///
5846    /// [`HalError`] from the manifest lookup, the module or the pipeline.
5847    fn build_fullscreen_with(
5848        device: &dyn Device,
5849        label: &str,
5850        shader: &crcbl_shaders::Shader,
5851        layout: PipelineLayoutHandle,
5852        color_targets: &[ColorTargetState],
5853        depth_stencil: Option<DepthStencilState>,
5854    ) -> Result<GraphicsPipelineHandle, HalError> {
5855        let vertex = entry(shader, Stage::Vertex)?;
5856        let fragment = entry(shader, Stage::Fragment)?;
5857        let module = device.create_shader_module(&ShaderModuleDesc {
5858            label: Some(shader.source()),
5859            spirv: shader.spirv(),
5860            wgsl: shader.wgsl(),
5861            msl: shader.msl(),
5862            // A container per entry point, for the reason the mesh module gives.
5863            dxil: &shader.dxil_containers(),
5864        })?;
5865        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5866            label: Some(label),
5867            layout,
5868            vertex: ShaderEntry {
5869                module,
5870                entry_point: vertex,
5871            },
5872            fragment: Some(ShaderEntry {
5873                module,
5874                entry_point: fragment,
5875            }),
5876            // The triangle is deliberately oversized, so two of its vertices are
5877            // outside the viewport and its winding is not worth reasoning about.
5878            primitive: PrimitiveState::default(),
5879            depth_stencil,
5880            multisample: MultisampleState::default(),
5881            color_targets,
5882        });
5883        device.destroy_shader_module(module);
5884        pipeline
5885    }
5886
5887    /// Builds a full-screen-triangle pipeline that writes a **depth**
5888    /// attachment and no colour one.
5889    ///
5890    /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
5891    /// no colour target at all, and a depth state whose comparison always
5892    /// passes so every texel of the destination takes the value the fragment
5893    /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
5894    /// in this file uses would be wrong here — this pass is not depth-testing
5895    /// anything, it is writing a reduction, and a test against the target's
5896    /// undefined contents would drop texels at random.
5897    ///
5898    /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
5899    /// a method rather than moving there because the module and the
5900    /// destroy-before-unwrap above are this file's, and both take it in exactly
5901    /// as `crate::ssao` takes the sibling.
5902    ///
5903    /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
5904    /// fragment stage per pyramid, and a stage looked up by kind would be
5905    /// ambiguous.
5906    ///
5907    /// # Errors
5908    ///
5909    /// [`HalError`] from the module or the pipeline.
5910    fn build_depth_fullscreen(
5911        device: &dyn Device,
5912        label: &str,
5913        shader: &crcbl_shaders::Shader,
5914        vertex: &str,
5915        fragment: &str,
5916        layout: PipelineLayoutHandle,
5917        format: Format,
5918    ) -> Result<GraphicsPipelineHandle, HalError> {
5919        let module = device.create_shader_module(&ShaderModuleDesc {
5920            label: Some(shader.source()),
5921            spirv: shader.spirv(),
5922            wgsl: shader.wgsl(),
5923            msl: shader.msl(),
5924            dxil: &shader.dxil_containers(),
5925        })?;
5926        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5927            label: Some(label),
5928            layout,
5929            vertex: ShaderEntry {
5930                module,
5931                entry_point: vertex,
5932            },
5933            fragment: Some(ShaderEntry {
5934                module,
5935                entry_point: fragment,
5936            }),
5937            primitive: PrimitiveState::default(),
5938            depth_stencil: Some(DepthStencilState {
5939                format,
5940                depth_write: true,
5941                depth_compare: CompareOp::Always,
5942                stencil: None,
5943                bias: DepthBias::default(),
5944            }),
5945            multisample: MultisampleState::default(),
5946            color_targets: &[],
5947        });
5948        device.destroy_shader_module(module);
5949        pipeline
5950    }
5951
5952    /// Creates the geometry pool and makes every mesh of `scene` resident in it.
5953    ///
5954    /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
5955    /// the pool is not the rollback's until this has returned, so a failure
5956    /// between creating it and flushing the last upload releases it here.
5957    fn build_geometry(
5958        device: &dyn Device,
5959        queue: QueueHandle,
5960        scene: &SceneDesc<'_>,
5961        service: &mut dyn FnMut(),
5962    ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
5963        let mut pool = MeshPool::new(
5964            device,
5965            &MeshPoolDesc {
5966                label: Some("forward geometry"),
5967                vertex_capacity: scene.capacities.vertices,
5968                index_capacity: scene.capacities.indices,
5969                mesh_capacity: scene.capacities.meshes,
5970            },
5971        )?;
5972        match Self::residents(device, queue, &mut pool, scene, service) {
5973            Ok(residents) => Ok((pool, residents)),
5974            Err(error) => {
5975                pool.destroy(device);
5976                Err(error)
5977            }
5978        }
5979    }
5980
5981    /// Creates the material table and fills it with `scene`'s rows, returning it
5982    /// and the id of each.
5983    ///
5984    /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
5985    /// the table is not the rollback's until this has returned.
5986    fn build_materials(
5987        device: &dyn Device,
5988        scene: &SceneDesc<'_>,
5989    ) -> Result<(MaterialTable, Vec<u32>), HalError> {
5990        let mut materials = MaterialTable::new(
5991            device,
5992            &MaterialTableDesc {
5993                label: Some("forward"),
5994                capacity: scene.capacities.materials,
5995            },
5996        )?;
5997        match Self::material_rows(device, &mut materials, &scene.materials) {
5998            Ok(ids) => Ok((materials, ids)),
5999            Err(error) => {
6000                materials.destroy(device);
6001                Err(error)
6002            }
6003        }
6004    }
6005
6006    /// Inserts `rows` **in order** and returns the id of each.
6007    ///
6008    /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6009    /// be released on a failure without the borrow that filling it takes, which
6010    /// is the same shape [`ForwardRenderer::residents`] has.
6011    ///
6012    /// **In order, because row 0 is not this function's to choose**: it is what
6013    /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6014    /// without a material id shades with. Inserting a description's rows in any
6015    /// other order would move that row under every caller — see
6016    /// [`SceneDesc::materials`], which is where it is a caller's decision.
6017    fn material_rows(
6018        device: &dyn Device,
6019        materials: &mut MaterialTable,
6020        rows: &[mesh::GpuMaterial],
6021    ) -> Result<Vec<u32>, HalError> {
6022        let mut ids = Vec::with_capacity(rows.len());
6023        for row in rows {
6024            let handle = materials.insert(device, row)?;
6025            // The id is asked for rather than assumed, because the number an
6026            // instance carries is this one and nothing else knows it.
6027            ids.push(materials.index(handle).ok_or_else(|| {
6028                HalError::Backend(
6029                    "a material inserted into an empty table did not resolve".to_string(),
6030                )
6031            })?);
6032        }
6033        Ok(ids)
6034    }
6035
6036    /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6037    /// the transfers have completed.
6038    ///
6039    /// The calls are §3.1's upload path in order: the copies are recorded and
6040    /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6041    /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6042    /// before they have.
6043    ///
6044    /// **In description order**, which is what makes a mesh's table id a
6045    /// property of the description rather than of this loop — the second mesh
6046    /// uploaded is the pool's first resident at a non-zero base vertex, which is
6047    /// what the module docs call the one thing that can tell a working base
6048    /// vertex from a cancelled one.
6049    ///
6050    /// A DAG is **one upload per level**. Every level was decimated separately,
6051    /// so a coarser level's vertices are wherever the collapses put them and
6052    /// belong to no vertex of the level below — a DAG is several vertex ranges,
6053    /// and the pool suballocates in vertices, so several ranges means several
6054    /// uploads. Level 0 goes first, so every other level starts past it and the
6055    /// offsets a cluster carries are non-negative; that is checked rather than
6056    /// assumed, because the pool's free list makes no promise about where a mesh
6057    /// lands.
6058    fn residents(
6059        device: &dyn Device,
6060        queue: QueueHandle,
6061        pool: &mut MeshPool,
6062        scene: &SceneDesc<'_>,
6063        service: &mut dyn FnMut(),
6064    ) -> Result<Vec<ResidentMesh>, HalError> {
6065        let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6066            Vec::with_capacity(scene.meshes.len());
6067        for desc in &scene.meshes {
6068            match &desc.geometry {
6069                Geometry::Flat {
6070                    vertices,
6071                    indices,
6072                    uv_range,
6073                    flags,
6074                    ..
6075                } => {
6076                    uploaded.push(vec![pool.upload(
6077                        device,
6078                        queue,
6079                        &MeshUpload {
6080                            label: &desc.label,
6081                            vertices,
6082                            indices,
6083                            uv_range: *uv_range,
6084                            flags: *flags,
6085                        },
6086                    )?]);
6087                    service();
6088                }
6089                Geometry::Dag {
6090                    levels,
6091                    dag,
6092                    uv_range,
6093                    flags,
6094                } => {
6095                    let mut handles = Vec::with_capacity(levels.len());
6096                    for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6097                        handles.push(pool.upload(
6098                            device,
6099                            queue,
6100                            &MeshUpload {
6101                                label: &format!("{} level {depth}", desc.label),
6102                                vertices,
6103                                indices: &level.indices(),
6104                                // Level 0's range for every level, which is the
6105                                // one the mesh path reads whichever level it
6106                                // draws — see `Geometry::Dag::uv_range`.
6107                                uv_range: *uv_range,
6108                                // And the description's flags for every level,
6109                                // for the same reason: the levels are one
6110                                // surface, so a tangent frame either describes
6111                                // all of them or none.
6112                                flags: *flags,
6113                            },
6114                        )?);
6115                        service();
6116                    }
6117                    uploaded.push(handles);
6118                }
6119            }
6120        }
6121
6122        pool.flush(device)?;
6123        service();
6124        // The table index is the only number that leaves here — where the
6125        // geometry actually is reaches the GPU through the mesh table, and the
6126        // draw arguments are built from that table by a shader. `MeshPool::mesh`
6127        // is still asked, because it is the call that refuses a mesh whose
6128        // upload has not completed, and an id for a mesh that is not there yet
6129        // would be a draw of nothing.
6130        let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6131            (Some(_), Some(id)) => Ok(id),
6132            _ => Err(MeshPoolError::NotResident { handle }),
6133        };
6134        let base_vertex = |handle| match pool.mesh(handle) {
6135            Some(range) => Ok(range.base_vertex),
6136            None => Err(MeshPoolError::NotResident { handle }),
6137        };
6138
6139        let mut residents = Vec::with_capacity(uploaded.len());
6140        for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6141            // **Relative to level 0's base**, because that is the base the
6142            // instance resolves through its mesh id and the one the stage adds
6143            // this on top of. A level that landed *below* level 0 would make the
6144            // sum wrap, so it is refused here rather than drawn as another
6145            // mesh's vertices. A flat mesh is one level and reads zero.
6146            let level_zero = base_vertex(handles[0])?;
6147            let mut vertex_bases = Vec::with_capacity(handles.len());
6148            for (depth, &handle) in handles.iter().enumerate() {
6149                let base = base_vertex(handle)?;
6150                vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6151                    HalError::InvalidDescriptor(format!(
6152                        "{} level {depth} landed at vertex {base}, below level 0's \
6153                         {level_zero}, so its clusters cannot name their own geometry",
6154                        desc.label
6155                    ))
6156                })?);
6157            }
6158            residents.push(ResidentMesh {
6159                levels: handles
6160                    .iter()
6161                    .map(|&handle| resolve(handle))
6162                    .collect::<Result<_, _>>()?,
6163                vertex_bases,
6164                // Matched on the description rather than counted off `handles`,
6165                // so a DAG decimated to a single level is still refused: what
6166                // makes a mesh skinnable is that every draw of it reads one
6167                // vertex run, and that is a property of the geometry rather than
6168                // of how many levels it happened to arrive with.
6169                skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6170            });
6171        }
6172        Ok(residents)
6173    }
6174
6175    /// Rotates to the next frame's uniform buffer and instance buffer, writes
6176    /// this frame's camera and light into the first, and uploads whatever
6177    /// changed into the second.
6178    ///
6179    /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6180    /// Separate from `add_passes` because the write happens on the CPU and the
6181    /// passes are recorded on the GPU timeline: fusing them would hide the ring
6182    /// rotation inside a function whose name says nothing about it.
6183    ///
6184    /// **It moves nothing.** Every object's transform is the caller's, written
6185    /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6186    /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6187    /// frame in which nothing moved uploads no instance bytes at all. The
6188    /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6189    /// spins it; a still scene is free.
6190    ///
6191    /// It also writes this frame's **cull parameters** — the camera's frustum,
6192    /// extracted from the very same view-projection the uniform block carries,
6193    /// so the pass that decides what is on screen and the pass that draws it
6194    /// cannot be looking at two different cameras — and zeroes the counters the
6195    /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6196    /// zeroes come from the host.
6197    ///
6198    /// # Errors
6199    ///
6200    /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6201    /// draw-generation buffers could not be written.
6202    pub fn begin_frame(
6203        &mut self,
6204        device: &dyn Device,
6205        camera: &Camera,
6206        light: &DirectionalLight,
6207        extent: (u32, u32),
6208    ) -> Result<(), HalError> {
6209        // The instance pool owns the ring, so its slot is the frame index the
6210        // uniform buffer and the bind group below are picked with.
6211        self.frame = self.instances.rotate();
6212        self.frame_skins = false;
6213        self.instances.flush(device)?;
6214        self.begin_frame_body(device, camera, light, extent)
6215    }
6216
6217    /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6218    /// call with the skinning plan folded into it.
6219    ///
6220    /// It does four things in the one order that is correct, which is why it is
6221    /// a call and not a note in someone's docs:
6222    ///
6223    /// 1. rotates the instance ring, so the frame slot exists;
6224    /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6225    ///    uploads the palettes and **moves the ping-pong** — the only place the
6226    ///    parity ever moves;
6227    /// 3. points every object placed by
6228    ///    [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6229    ///    region the parity now names;
6230    /// 4. uploads the instance delta, so those bases are the ones this frame
6231    ///    draws.
6232    ///
6233    /// Do those three and four in the other order and the objects carry the
6234    /// previous frame's half — a character posed one frame late, every frame,
6235    /// with nothing to report it. A caller never sees a parity or a table id, and
6236    /// so cannot get that wrong.
6237    ///
6238    /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6239    /// this frame animates. A frame with **no** skinned object still calls this
6240    /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6241    /// otherwise re-dispatch whichever frame last used it.
6242    ///
6243    /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6244    /// the one that orders the dispatch before the draws.
6245    ///
6246    /// # Errors
6247    ///
6248    /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6249    /// palette, a binding count that is not the region's vertex count, more than
6250    /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6251    /// refused, this renderer's own uniform and instance writes included.
6252    ///
6253    /// # Panics
6254    ///
6255    /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6256    /// its rings are indexed by this renderer's frame slot, and
6257    /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6258    pub fn begin_skinned_frame(
6259        &mut self,
6260        device: &dyn Device,
6261        skinning: &mut Skinning,
6262        ranges: &[SkinRange<'_>],
6263        camera: &Camera,
6264        light: &DirectionalLight,
6265        extent: (u32, u32),
6266    ) -> Result<(), SkinningError> {
6267        self.frame = self.instances.rotate();
6268        // An empty plan dispatches nothing — see [`Skinning::begin_frame`] — so
6269        // it leaves the vertex pool where it was, and the shadow atlas with it.
6270        self.frame_skins = !ranges.is_empty();
6271        skinning.begin_frame(device, self.frame, ranges)?;
6272        self.point_skinned_instances(skinning.parity());
6273        self.instances.flush(device)?;
6274        self.begin_frame_body(device, camera, light, extent)?;
6275        Ok(())
6276    }
6277
6278    /// Whether this frame records the irradiance probes' two
6279    /// updater passes.
6280    ///
6281    /// The scene's own answer and the console's together: the volume decides
6282    /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6283    /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6284    /// on/off pair a pricing run reads the two passes' cost off with everything
6285    /// else held still.
6286    ///
6287    /// **It is not the whole condition.** The map is cascade 0's own draws, so
6288    /// the pass is recorded only where that cascade is being drawn too — see
6289    /// `add_shadow_pass`, which is where the rest of it is.
6290    fn probe_update_runs(&self) -> bool {
6291        self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6292    }
6293
6294    /// The six side-plane sets a point light's face culls test, or `None` for
6295    /// a light that is not a point — or with the face culls switched off, which
6296    /// is one cull against the light's box drawn into all six faces.
6297    ///
6298    /// `faces` are the light's face matrices in face order, the ones its tiles
6299    /// render through.
6300    fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6301        if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6302            return None;
6303        }
6304        let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6305        Some(crate::cull::face_planes(&matrices))
6306    }
6307
6308    /// Every punctual shadow face this frame draws into the punctual reflective
6309    /// shadow map, in the order the pass draws them and the producer table lists
6310    /// them.
6311    ///
6312    /// **One list for both halves of the updater**, and that is the point:
6313    /// `add_shadow_pass` sets a viewport from a face's
6314    /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6315    /// of the matching producer row, so a face the pass drew and a row the
6316    /// gather walked have to be the same face. Building the two from separate
6317    /// filters is two things that can drift, and the drift would be a light
6318    /// bouncing another light's map.
6319    ///
6320    /// **The occupied slots this frame redraws**, which is the same set
6321    /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6322    /// block and its draws are a shadow cull's, and
6323    /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6324    /// it is holding.
6325    ///
6326    /// # Every occupied tile, and no budget of its own
6327    ///
6328    /// The producers are exactly the atlas's occupied faces — up to
6329    /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6330    /// them — rather than the highest-ranked light or some smaller count.
6331    ///
6332    /// **Because the budget already exists and is spent.**
6333    /// [`shadow::Selection`] has ranked these lights by projected screen
6334    /// influence and handed out every tile there is; a second budget on top
6335    /// would rank the same lights again, differently, and produce a light that
6336    /// casts a shadow and lends no bounce. That is a difference no picture shows
6337    /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6338    /// and it is the kind of quiet inconsistency the two halves of one light are
6339    /// worst placed to have.
6340    ///
6341    /// It is affordable at the extent that was chosen for it:
6342    /// `apps/lantern` lights seven faces, and
6343    /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6344    /// carries the sweep that priced them.
6345    ///
6346    /// **Empty where shadows are off**, for that same reason — a punctual face
6347    /// *is* a shadow view. The sun's half is not, which is what
6348    /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6349    /// sun's bounce and loses every punctual one, rather than switching the
6350    /// whole updater off with them.
6351    fn punctual_faces(&self) -> Vec<PunctualFace> {
6352        if !self.probe_update_runs() {
6353            return Vec::new();
6354        }
6355        // A frame with the shadows switched off draws no atlas, so no group of
6356        // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6357        // branch has still written every one of these views and dispatched every
6358        // one of these culls, for this pass to draw through.
6359        let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6360        let mut faces = Vec::new();
6361        for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6362            let Some(held) = *held else {
6363                continue;
6364            };
6365            if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6366                continue;
6367            }
6368            let Some(light) = self.extra_lights.get(held.light) else {
6369                continue;
6370            };
6371            // A spot draws face 0 alone and a point light all six, each through
6372            // its own matrix into its own tile — `shadow::tile_span` is the same
6373            // function `Selection` allocated the run with, so a face here and a
6374            // tile there cannot disagree about how many there are.
6375            for face in 0..shadow::tile_span(light) {
6376                let tile = rsm::punctual_tile(held.base + face);
6377                faces.push(PunctualFace {
6378                    view: shadow_view(slot, face),
6379                    cull: shadow_cull(slot),
6380                    face,
6381                    tile,
6382                    producer: producer_row(light, tile),
6383                });
6384            }
6385        }
6386        faces
6387    }
6388
6389    /// Puts an object in the scene and returns the handle that names it.
6390    ///
6391    /// An instance in the pool **is** an object in the scene: the frame records
6392    /// a fixed number of draws and the cull pass decides which instances they
6393    /// walk, so adding one costs a slot in an array and not a command. It is
6394    /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6395    /// uploads it.
6396    ///
6397    /// # The index it lands at is not decoration
6398    ///
6399    /// `draw_gen.slang` keys topic 25's hysteresis state by the
6400    /// instance's **array index**, at `instance_index * group_stride`, and
6401    /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6402    /// record of which of a DAG's groups an object had expanded belongs to the
6403    /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6404    /// handed to the next `add_instance`, which inherits it. What that costs is
6405    /// one frame selected against a history that is not this object's, and the
6406    /// next frame's own judgement replaces it; it is never a wrong picture,
6407    /// because every group is judged afresh whatever the state said.
6408    ///
6409    /// That inheritance is inert while the scene holds **one** instance of a DAG
6410    /// mesh, which is every frame the engine has drawn so far — one instance's
6411    /// run has no previous occupant, and a flat mesh's
6412    /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6413    /// nothing indexes the state for it. It stops being inert the moment an
6414    /// application places a second.
6415    ///
6416    /// [`remove_instance`]: ForwardRenderer::remove_instance
6417    ///
6418    /// # A DAG mesh needs a device that can choose a level
6419    ///
6420    /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6421    /// **no** amplification stage in front of it emits every cluster of the
6422    /// bucket, which for a DAG is every level at once — several overlapping
6423    /// copies of one surface. This does not refuse it, because it has no
6424    /// vocabulary for that refusal; a caller placing a DAG asks
6425    /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6426    /// says yes. A flat mesh is unaffected on every path.
6427    ///
6428    /// # Errors
6429    ///
6430    /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6431    /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6432    /// what a caller sizes it with.
6433    ///
6434    /// # Panics
6435    ///
6436    /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6437    /// the description this renderer was built from. Both are indices a caller
6438    /// wrote against a description it holds, so an out-of-range one is a mistake
6439    /// in the calling code rather than a condition the frame can be in — and the
6440    /// alternative is an object silently drawn as some other mesh, in some other
6441    /// colour.
6442    pub fn add_instance(
6443        &mut self,
6444        desc: &InstanceDesc,
6445    ) -> Result<InstanceHandle, InstancePoolError> {
6446        let instance = self.gpu_instance(desc);
6447        self.instances.insert(&instance)
6448    }
6449
6450    /// Rewrites the object `handle` names — its mesh, its material and its
6451    /// transform, all three.
6452    ///
6453    /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6454    /// nothing, rather than overwriting whatever took its slot.
6455    ///
6456    /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6457    /// the element and nothing else: an object that did not move costs no
6458    /// transfer at all.
6459    ///
6460    /// # Panics
6461    ///
6462    /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6463    pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6464        let mut instance = self.gpu_instance(desc);
6465        instance.flags |= self.kept_flags(handle);
6466        self.instances.set(handle, &instance);
6467    }
6468
6469    /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6470    /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6471    /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6472    /// handle, whose rewrite writes nothing anyway.
6473    fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6474        self.instances.get(handle).map_or(0, |record| {
6475            record.flags
6476                & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6477        })
6478    }
6479
6480    /// Sets whether `handle` casts a shadow. Every instance starts casting.
6481    ///
6482    /// **Every shadow map and nothing else**: an instance that casts none is
6483    /// rejected by the cull of the sun's cascades and of every shadowed light,
6484    /// on every geometry path, so it lands in no tile of the atlas — and in no
6485    /// reflective shadow map, which draws those same culls' survivors, so it
6486    /// bounces no light into the probes either. Every camera still draws it,
6487    /// and it still receives the shadows the rest of the scene casts.
6488    ///
6489    /// What a model drawn for an icon wants, placed where the scene's sun can
6490    /// see it: see [`ViewBackground::Transparent`] and
6491    /// [`set_instance_views`](Self::set_instance_views).
6492    ///
6493    /// A change redraws every shadow map whose cull the instance could be kept
6494    /// by, because it is a write [`InstancePool::take_written`] names. Not a
6495    /// move, on
6496    /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6497    /// handle is ignored.
6498    pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6499        if let Some(record) = self.instances.get(handle) {
6500            let flags = if casts {
6501                record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6502            } else {
6503                record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6504            };
6505            self.instances.set_flags(handle, flags);
6506        }
6507    }
6508
6509    /// Whether `handle` casts a shadow, or `None` for a stale handle.
6510    #[must_use]
6511    pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6512        self.instances
6513            .get(handle)
6514            .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6515    }
6516
6517    /// Takes the object `handle` names back out of the scene, freeing its slot.
6518    ///
6519    /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6520    /// no longer records a draw per object: `cull.slang` asks whether an instance
6521    /// is live before it reads anything else, so removing an object and culling
6522    /// it off screen take the same path out of the frame. An instance left in the
6523    /// pool would be drawn wherever its transform put it.
6524    ///
6525    /// A stale handle removes nothing. Takes effect at the next
6526    /// [`ForwardRenderer::begin_frame`], on
6527    /// [`ForwardRenderer::set_instance`]'s terms.
6528    pub fn remove_instance(&mut self, handle: InstanceHandle) {
6529        self.instances.remove(handle);
6530    }
6531
6532    /// Captures a visibility map for every probe, from the static geometry
6533    /// standing in the scene right now.
6534    ///
6535    /// The probe visibility rung: each probe records how far
6536    /// away the nearest surface is in every direction, and `mesh.slang`'s
6537    /// `probe_irradiance` then weighs each of a fragment's eight probes by
6538    /// whether it can *see* that fragment — so a probe on the far side of a wall
6539    /// contributes nothing and a room stops lighting the room next door.
6540    /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6541    /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6542    /// format.
6543    ///
6544    /// # Call it once, after the scene's walls are placed
6545    ///
6546    /// **A description carries no instances** — [`SceneDesc`] is meshes,
6547    /// materials, a page and the probe rows, and the objects arrive afterwards
6548    /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6549    /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6550    /// call that has the room in it, and an application makes it once its static
6551    /// geometry is placed.
6552    ///
6553    /// A caller that never makes it draws exactly the frame this renderer drew
6554    /// before the maps existed: every group names the one-texel placeholder,
6555    /// which no surface is further away than, and every probe keeps all of its
6556    /// weight.
6557    ///
6558    /// **It is a capture of geometry and not a bake of light.** Nothing about
6559    /// the lights is recorded, every one of them still moves, and the rows the
6560    /// probes carry are untouched.
6561    ///
6562    /// # What it sees, and what it does not
6563    ///
6564    /// Every instance live in the pool when it is called, at the transform it
6565    /// then has, rasterised from its mesh's level-0 triangles into six 90°
6566    /// faces per probe. Objects that move
6567    /// afterwards keep the occlusion they had here, which is the accepted limit
6568    /// this technique has everywhere it is used — a probe volume is about the
6569    /// walls. Recapturing after a wall moves is this call again.
6570    ///
6571    /// **The device must be idle.** The previous capture's image is released
6572    /// here, and a frame in flight may still be reading it.
6573    ///
6574    /// # Errors
6575    ///
6576    /// [`HalError`] from the capture. The previous maps are kept on the failing
6577    /// path, so a renderer that has captured once and then failed goes on
6578    /// drawing with what it had.
6579    pub fn capture_probe_visibility(
6580        &mut self,
6581        device: &dyn Device,
6582        queue: QueueHandle,
6583    ) -> Result<(), HalError> {
6584        let placed: Vec<crate::probe_visibility::Occluder> = self
6585            .instances
6586            .live()
6587            .into_iter()
6588            .map(|record| crate::probe_visibility::Occluder {
6589                mesh: record.mesh,
6590                transform: Mat4::from_cols_array(&record.transform),
6591            })
6592            .collect();
6593        let Some(uploaded) = crate::probe_capture::capture(
6594            device,
6595            queue,
6596            &self.probe_volume,
6597            &self.probe_occluders,
6598            &placed,
6599        )?
6600        else {
6601            // No probes, or nothing placed for a map to be about. Leaving the
6602            // placeholder bound is the honest answer, and it is what a scene
6603            // with no probes has always read.
6604            return Ok(());
6605        };
6606        // The cached groups name the view this replaces, so they go before it
6607        // does — a bind group outliving the image it names is a validation
6608        // error on every backend that checks, and a use-after-free on the ones
6609        // that do not.
6610        for slot in &mut self.primary.screen_channel_groups {
6611            if let Some((_, stale)) = slot.take() {
6612                device.destroy_bind_group(stale);
6613            }
6614        }
6615        if let Some(previous) = self.probe_visibility.replace(uploaded) {
6616            previous.destroy(device);
6617        }
6618        Ok(())
6619    }
6620
6621    /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6622    /// captures the probes the step exposed.
6623    ///
6624    /// The irradiance probes' scrolling: each level moves a whole
6625    /// number of its own probe spacings towards `point`, so the probes that stay
6626    /// inside it stand exactly where they stood and go on being addressed at the
6627    /// rows they already had — and only the slabs the step brought in are
6628    /// captured. Answers how many rows that was, which is **zero for the
6629    /// ordinary frame**: the point has to travel half a probe spacing before the
6630    /// nearest whole step changes at all.
6631    ///
6632    /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6633    /// rule and `exposed` beside it is the invalidation; this is the two of them
6634    /// plus the device work they imply — the visibility maps of the exposed
6635    /// rows, and the position table the reflective-shadow-map gather reads.
6636    ///
6637    /// # A volume authored to cover its whole world does not move
6638    ///
6639    /// The steps are the ones that centre a level on `point`, and a caller whose
6640    /// volume is already the world it is in wants none of them — so a caller
6641    /// passes the point it wants the *centre* at rather than the camera outright
6642    /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6643    /// their own modules say so.
6644    ///
6645    /// # A step stalls, and a frame that does not step costs a comparison
6646    ///
6647    /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6648    /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6649    /// one does — so a step drains the device before it rewrites anything and
6650    /// leaves it drained. That is a stall, and it is why the probe records price a step
6651    /// separately from a frame. A call that steps nothing returns before the
6652    /// wait, so the ordinary frame pays a rounding per level and per axis and
6653    /// nothing else.
6654    ///
6655    /// It may therefore be called from a frame loop, but **not after**
6656    /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6657    /// recorded: the header it moves is the one that frame's uniform block has
6658    /// already been written from.
6659    ///
6660    /// A renderer that has never captured re-centres the header and captures
6661    /// nothing: there is no image to write slabs into, every group still names
6662    /// the placeholder, and the first
6663    /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6664    /// whole.
6665    ///
6666    /// # It moves the geometry and not the light
6667    ///
6668    /// What a step re-captures is the *visibility* of the probes it exposed,
6669    /// which is what the maps are about. The **rows** are not touched, so under
6670    /// [`ProbeUpdate::Authored`] a probe
6671    /// that a step brought in keeps the irradiance the probe that left had —
6672    /// authored for somewhere else. A volume that scrolls therefore wants
6673    /// [`ProbeUpdate::EveryFrame`], whose
6674    /// gather refills every row from the scene each frame and has no such gap;
6675    /// `docs/backlog.md` carries what an authored one would need instead.
6676    ///
6677    /// # Errors
6678    ///
6679    /// [`HalError`] from the recapture or from the position rewrite. The volume
6680    /// keeps the steps it had on either failing path, so a renderer that could
6681    /// not capture a slab does not go on drawing with rows about somewhere else.
6682    pub fn follow_probe_volume(
6683        &mut self,
6684        device: &dyn Device,
6685        queue: QueueHandle,
6686        point: [f32; 3],
6687    ) -> Result<u32, HalError> {
6688        let mut moved = self.probe_volume;
6689        let rows = moved.follow(point);
6690        if rows.is_empty() && moved.steps == self.probe_volume.steps {
6691            return Ok(0);
6692        }
6693        // **Before anything is written**, so a caller may make this call from
6694        // its frame loop: the layers the recapture rewrites and the position
6695        // table beside them are read by whatever frames are still in flight, and
6696        // neither is a ring. A frame that does not step never reaches this line,
6697        // which is what keeps the ordinary frame free of it.
6698        device.wait_idle()?;
6699        if let Some(captured) = &self.probe_visibility {
6700            let placed: Vec<crate::probe_visibility::Occluder> = self
6701                .instances
6702                .live()
6703                .into_iter()
6704                .map(|record| crate::probe_visibility::Occluder {
6705                    mesh: record.mesh,
6706                    transform: Mat4::from_cols_array(&record.transform),
6707                })
6708                .collect();
6709            crate::probe_capture::recapture(
6710                device,
6711                queue,
6712                &moved,
6713                &self.probe_occluders,
6714                &placed,
6715                &rows,
6716                captured.image,
6717            )?;
6718        }
6719        // After the capture, so a volume whose slabs could not be drawn keeps
6720        // the header its maps are about.
6721        if let Some(gather) = &self.probe_gather {
6722            gather.rewrite_positions(device, &moved)?;
6723        }
6724        self.probe_volume = moved;
6725        Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
6726    }
6727
6728    /// Where the irradiance clipmap stands right now — the header the frame
6729    /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
6730    /// included.
6731    #[must_use]
6732    pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
6733        self.probe_volume
6734    }
6735
6736    /// `draws` split by the **whole** material mode, each partition under the
6737    /// depth-only pipeline that honours it — what the depth prepass and every
6738    /// shadow view record instead of one call list under one pipeline.
6739    ///
6740    /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
6741    /// split total: the opaque buckets are drawn with
6742    /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
6743    /// fragment stage — the masked ones with
6744    /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
6745    /// `discard`, and each of those has a [`CullMode::None`] twin for the
6746    /// buckets whose material is double-sided. A scene with one cutout in it
6747    /// pays a fragment stage for that mesh's draws and for no others; before
6748    /// this it paid for the whole frame, which on lavapipe roughly doubled the
6749    /// prepass and added two thirds to the shadow pass.
6750    ///
6751    /// **Both depth passes and not just the atlas.** A double-sided plate whose
6752    /// back face the prepass culled writes no depth there, so the colour pass's
6753    /// `GreaterOrEqual` test against it rejects the fragment and the surface is
6754    /// missing from the frame; and a cascade that culled it casts no shadow.
6755    fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
6756        self.partitions(
6757            draws,
6758            mesh::GpuMaterial::MODE_MASK,
6759            &[
6760                (DEPTH_MODES[0], self.shadow_pipeline.single),
6761                (DEPTH_MODES[1], self.depth_masked_pipeline.single),
6762                (DEPTH_MODES[2], self.shadow_pipeline.double),
6763                (DEPTH_MODES[3], self.depth_masked_pipeline.double),
6764            ],
6765        )
6766    }
6767
6768    /// `draws` split by the material's **side** alone, each partition under the
6769    /// matching half of `pipelines` — what the colour pass and the two
6770    /// reflective shadow maps record.
6771    ///
6772    /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
6773    /// four, and the difference is the whole of what these passes do not care
6774    /// about: their pipelines carry a fragment stage either way and cut the
6775    /// alpha mask inside it, so a masked bucket and an opaque one are the same
6776    /// draw here. What they cannot express inside the stage is the cull mode.
6777    fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
6778        self.partitions(
6779            draws,
6780            mesh::GpuMaterial::DOUBLE_SIDED,
6781            &[
6782                (0, pipelines.single),
6783                (mesh::GpuMaterial::DOUBLE_SIDED, pipelines.double),
6784            ],
6785        )
6786    }
6787
6788    /// Resolves a description's mesh and material indices into the table ids the
6789    /// GPU reads.
6790    ///
6791    /// The whole record every time, because [`InstancePool::set`] writes the
6792    /// whole record: an instance that lost either id would name entry 0 of that
6793    /// table, which is a mesh and a material rather than an absence.
6794    fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
6795        mesh::GpuInstance {
6796            transform: desc.transform.to_cols_array(),
6797            mesh: self.mesh_ids[desc.mesh],
6798            material: self.material_ids[desc.material],
6799            flags: self.material_mode_bits(desc.material),
6800            ..mesh::GpuInstance::default()
6801        }
6802    }
6803
6804    /// The material mode of description material `material`, in the bits an
6805    /// instance record carries it in.
6806    ///
6807    /// **Read out of the table rather than out of the description**, because the
6808    /// table is what a `set` would move and the row is what the shader shades
6809    /// through. It is the other half of the record's routing key: `draw_gen`
6810    /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
6811    /// which is how a masked material costs a fragment stage in the depth passes
6812    /// for its own mesh alone.
6813    ///
6814    /// The mode is captured **here**, when the record is written — see
6815    /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
6816    /// for what that means for a material rewritten afterwards.
6817    fn material_mode_bits(&self, material: usize) -> u32 {
6818        self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
6819    }
6820
6821    // --- skinning: reserving the region, placing the object, ordering the
6822    // dispatch ---
6823
6824    /// The vertex pool every mesh here is resident in — what
6825    /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
6826    /// takes.
6827    ///
6828    /// The skinning pass reads a bind pose out of this buffer and writes the
6829    /// deformed vertices back into another run of it, which is what makes a
6830    /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
6831    /// [`Skinning`] built against any other writes vertices no draw here can
6832    /// reach.
6833    #[must_use]
6834    pub const fn vertex_buffer(&self) -> BufferHandle {
6835        self.pool.vertex_buffer()
6836    }
6837
6838    /// Where that pool's **attribute** region begins, in words — what
6839    /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
6840    /// takes.
6841    ///
6842    /// The buffer holds two streams, so a pass that writes it needs the
6843    /// boundary as well as the handle; a [`Skinning`] built with the wrong one
6844    /// writes a mesh's attributes over another mesh's positions. See
6845    /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
6846    #[must_use]
6847    pub const fn attribute_base(&self) -> u32 {
6848        self.pool.attribute_base()
6849    }
6850
6851    /// Reserves a skinned region for description mesh `mesh`.
6852    ///
6853    /// The whole of what a caller needs to skin something, in one value: hand
6854    /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
6855    /// frame's [`SkinRange`], hand the result to
6856    /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
6857    /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
6858    /// parity never have to be spelled by the caller at all — see
6859    /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
6860    ///
6861    /// **The mesh keeps its own entry and the region takes none**, so the same
6862    /// description mesh can be drawn skinned through this and in its bind pose
6863    /// through [`add_instance`](Self::add_instance) in the same frame, both
6864    /// resolving through the one table entry it already had.
6865    ///
6866    /// Give it back with [`release_skinned`](Self::release_skinned).
6867    ///
6868    /// # Errors
6869    ///
6870    /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
6871    /// both halves. **Two vertex runs per skinned primitive** is what a scene's
6872    /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
6873    ///
6874    /// # Panics
6875    ///
6876    /// If `mesh` is past the end of the description this renderer was built
6877    /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
6878    /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
6879    /// A DAG is refused rather than skinned wrongly: its coarser levels are
6880    /// separate vertex runs no dispatch writes, so a cut that descended past
6881    /// level 0 would draw whatever the pool happened to be holding there.
6882    pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
6883        let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
6884            panic!(
6885                "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
6886                 runs no skinning dispatch writes; only a flat mesh can be skinned"
6887            )
6888        });
6889        SkinnedMesh::reserve(&mut self.pool, source)
6890    }
6891
6892    /// Gives `skinned`'s region back to the vertex pool.
6893    ///
6894    /// The device must not still be drawing it: this records no barrier, on
6895    /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
6896    /// removed — [`remove_instance`](Self::remove_instance) is what does that,
6897    /// and an instance left behind goes on drawing its source mesh's geometry
6898    /// out of vertices the pool has handed back. Remove the objects first.
6899    pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
6900        skinned.release(&mut self.pool);
6901    }
6902
6903    /// Places a skinned object in the scene.
6904    ///
6905    /// [`add_instance`](Self::add_instance) with a reserved region in place of a
6906    /// description mesh. The renderer keeps the object in a list of its own and
6907    /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
6908    /// at the half of the region that frame's dispatch fills, so the parity is
6909    /// never something a caller writes.
6910    ///
6911    /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
6912    /// therefore left pointing wherever it last was, which after the first frame
6913    /// is the pose of the frame before — the reason the two entry points are
6914    /// separate calls rather than a flag.
6915    ///
6916    /// # Errors
6917    ///
6918    /// [`InstancePoolError::PoolFull`], on
6919    /// [`add_instance`](Self::add_instance)'s terms.
6920    ///
6921    /// # Panics
6922    ///
6923    /// If [`SkinnedInstanceDesc::material`] is past the end of the description
6924    /// this renderer was built from, on
6925    /// [`add_instance`](Self::add_instance)'s terms.
6926    pub fn add_skinned_instance(
6927        &mut self,
6928        desc: &SkinnedInstanceDesc<'_>,
6929    ) -> Result<InstanceHandle, InstancePoolError> {
6930        // Parity zero, and it never reaches the GPU as such: the instance pool
6931        // uploads by delta at `begin_skinned_frame`, which re-points every entry
6932        // of the list below before it flushes. What this writes is the rest of
6933        // the record.
6934        let instance = self.skinned_gpu_instance(desc, 0);
6935        let handle = self.instances.insert(&instance)?;
6936        self.skinned_instances.push(SkinnedInstance {
6937            handle,
6938            bases: skinned_bases(desc.mesh),
6939            pointed: false,
6940        });
6941        Ok(handle)
6942    }
6943
6944    /// Rewrites the skinned object `handle` names — its region, its material and
6945    /// its transform.
6946    ///
6947    /// [`set_instance`](Self::set_instance) for an object placed by
6948    /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
6949    /// character's transform changes through. A stale handle writes nothing.
6950    ///
6951    /// Passing a handle this renderer has never seen skinned adopts it: the
6952    /// object joins the re-pointed list from here on. That is what lets a caller
6953    /// swap a bind-pose instance over to a region without removing and replacing
6954    /// it.
6955    ///
6956    /// # Panics
6957    ///
6958    /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms.
6959    pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
6960        let mut instance = self.skinned_gpu_instance(desc, 0);
6961        instance.flags |= self.kept_flags(handle);
6962        if !self.instances.set(handle, &instance) {
6963            return;
6964        }
6965        let bases = skinned_bases(desc.mesh);
6966        match self
6967            .skinned_instances
6968            .iter_mut()
6969            .find(|entry| entry.handle == handle)
6970        {
6971            // **A different region is a fresh entry.** The half this object has
6972            // never been drawn out of holds whatever its reservation came with,
6973            // so the next pointing owes it rest rather than a previous
6974            // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
6975            // is what "different" means here: two calls naming one region give
6976            // the same two runs, so rewriting an object's material or transform
6977            // is not a change of region.
6978            Some(entry) => {
6979                entry.pointed &= entry.bases == bases;
6980                entry.bases = bases;
6981            }
6982            None => self.skinned_instances.push(SkinnedInstance {
6983                handle,
6984                bases,
6985                pointed: false,
6986            }),
6987        }
6988    }
6989
6990    /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
6991    /// with the region's base vertex carried in the record and the bit that says
6992    /// to read it.
6993    ///
6994    /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
6995    /// this instance is scattered into, the levels it selects through and the
6996    /// box it is culled against are the ones the undeformed mesh already had.
6997    fn skinned_gpu_instance(
6998        &self,
6999        desc: &SkinnedInstanceDesc<'_>,
7000        parity: u32,
7001    ) -> mesh::GpuInstance {
7002        let base_vertex = desc.mesh.region().base(parity);
7003        mesh::GpuInstance {
7004            transform: desc.transform.to_cols_array(),
7005            mesh: desc.mesh.mesh_id(),
7006            material: self.material_ids[desc.material],
7007            // The override bit **and** the material mode: a skinned instance is
7008            // routed by the same key as a rigid one, so a skinned cutout lands
7009            // in its mesh's masked bucket rather than in the opaque twin.
7010            flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE | self.material_mode_bits(desc.material),
7011            base_vertex,
7012            // At rest, which is what a record this call writes has to be: the
7013            // object has not been drawn out of this region yet, so the other
7014            // half holds whatever its reservation came with. A frame that runs
7015            // [`point_skinned_instances`](Self::point_skinned_instances) is
7016            // what starts pointing this at the half before.
7017            previous_base_vertex: base_vertex,
7018            ..mesh::GpuInstance::default()
7019        }
7020    }
7021
7022    /// Points every skinned object at the half of its region a frame of this
7023    /// parity fills **and at the half the frame before it filled**, and forgets
7024    /// the ones whose instance has gone.
7025    ///
7026    /// Called between the instance ring's rotation and its upload, which is the
7027    /// whole reason those two are separate calls — see
7028    /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7029    ///
7030    /// The second base is what a skinned fragment's motion vector is subtracted
7031    /// against — see
7032    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7033    /// **A region this frame's `ranges` left out was not skinned this frame**,
7034    /// so the half this points at as the current one already holds an earlier
7035    /// frame's pose. That is pre-existing — it is what a caller driving a
7036    /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7037    /// it predates this second base — and the previous half is then no worse off
7038    /// than the current one.
7039    fn point_skinned_instances(&mut self, parity: u32) {
7040        let Self {
7041            instances,
7042            skinned_instances,
7043            ..
7044        } = self;
7045        skinned_instances.retain_mut(|entry| {
7046            // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7047            // applied to the entry's own copy of the pair — see
7048            // [`SkinnedInstance::bases`].
7049            let base_vertex = entry.bases[(parity & 1) as usize];
7050            let previous_base_vertex = if entry.pointed {
7051                entry.bases[((parity ^ 1) & 1) as usize]
7052            } else {
7053                // Nothing has been written into the other half for this object,
7054                // so it is put at rest — see [`SkinnedInstance::pointed`].
7055                base_vertex
7056            };
7057            entry.pointed = true;
7058            // The two bases and nothing else: the transform, the material and
7059            // the mesh the caller last set survive, and so does the transform
7060            // the record moved *from* — which
7061            // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7062            // would overwrite with this frame's, leaving a skinned object's own
7063            // travel out of the motion target. See
7064            // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7065            // Its answer is also what says the instance is still there, so an
7066            // object a caller removed drops out of the list here.
7067            instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7068        });
7069    }
7070
7071    /// The lights in the frame **beside the sun**, which
7072    /// [`begin_frame`](Self::begin_frame) still takes on its own.
7073    ///
7074    /// Topic 44's light list, minus its first row: the
7075    /// sun is row 0 of every frame's list and the ones set here follow it, in
7076    /// the order given. That order is the one a froxel keeps a prefix of when it
7077    /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7078    /// overflow counter beside it — so it is a caller's lever and not an
7079    /// accident.
7080    ///
7081    /// The sun keeps a parameter of its own because it is the light that owns
7082    /// the ambient term and the shadow cascades, neither of which a [`Light`]
7083    /// has. What it stopped being is a special case in the *shader*, which is
7084    /// what the list bought.
7085    ///
7086    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7087    /// what uploads the rows.
7088    ///
7089    /// # Panics
7090    ///
7091    /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7092    /// room for once the sun has its row. Refused rather than truncated: a light
7093    /// missing from the list is missing from every froxel, and **no counter in
7094    /// the frame would report it** — the overflow counter counts what a froxel's
7095    /// budget refused, which is a different number.
7096    pub fn set_lights(&mut self, lights: &[Light]) {
7097        assert!(
7098            lights.len() < self.primary.lights.capacity() as usize,
7099            "{} lights beside the sun, in a list of {}",
7100            lights.len(),
7101            self.primary.lights.capacity()
7102        );
7103        self.extra_lights.clear();
7104        self.extra_lights.extend_from_slice(lights);
7105    }
7106
7107    /// Rows the light list holds, the sun's included.
7108    #[must_use]
7109    pub const fn light_capacity(&self) -> u32 {
7110        self.primary.lights.capacity()
7111    }
7112
7113    /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7114    /// from the viewport and the camera.
7115    ///
7116    /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7117    /// wants to know which froxel a point was shaded out of has to use the grid
7118    /// the frame really used, and re-deriving it would be a second copy of the
7119    /// arithmetic rather than a reading of the first.
7120    #[must_use]
7121    pub const fn grid(&self) -> Grid {
7122        self.primary.grid
7123    }
7124
7125    /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7126    /// pass decided.
7127    ///
7128    /// # Panics
7129    ///
7130    /// If `frame` is not a slot this was built with.
7131    #[must_use]
7132    pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7133        self.primary.lights.grid(frame)
7134    }
7135
7136    /// The pixel budget the descent compares a group's projected error against.
7137    ///
7138    /// One pixel until this is called — see the constant this crate keeps it
7139    /// in. Larger is coarser: a group
7140    /// projecting *over* the budget is expanded and its children are drawn, so
7141    /// raising it stops the descent higher up the DAG.
7142    ///
7143    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7144    /// what writes it into the frame block.
7145    pub const fn set_lod_error_budget(&mut self, budget: f32) {
7146        self.lod_error_budget = budget;
7147    }
7148
7149    /// The budget this renderer selects under unless
7150    /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7151    /// the ratio the hold budget sits at below whichever one is in force.
7152    ///
7153    /// Public because a test that drives a camera across a level boundary has to
7154    /// know where the boundary is, and where it is depends on both numbers —
7155    /// re-deriving either in the test would be a second copy to drift.
7156    pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7157    /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7158    pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7159
7160    /// How far below the budget an already-expanded group is held before it
7161    /// collapses again — topic 25's hysteresis, as a fraction of
7162    /// the budget.
7163    ///
7164    /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7165    /// of one removes the band**, which makes the two budgets equal and the
7166    /// previous frame's answer stop mattering — the setting a test uses to show
7167    /// that the band is what stops a drifting camera flickering, on the same
7168    /// code path and one number apart.
7169    ///
7170    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7171    /// what writes it into the two params blocks.
7172    pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7173        self.lod_hold_ratio = ratio;
7174    }
7175
7176    /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7177    /// pixels per unit at one unit from the eye, and the pixel budget.
7178    ///
7179    /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7180    /// starts expanding over, and the budget an expanded one is held down to.
7181    ///
7182    /// What `ClusterDag::expand` takes, so a caller reading
7183    /// [`cluster_selection`](Self::cluster_selection) back can run the same
7184    /// frames host-side rather than re-deriving the numbers from the camera and
7185    /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7186    #[must_use]
7187    pub const fn lod_params(&self) -> [f32; 3] {
7188        self.primary.lod_params
7189    }
7190
7191    /// The same three numbers the **shadow cascades** selected under, which is
7192    /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7193    /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7194    /// parameters it actually reaches the GPU as.
7195    ///
7196    /// The pixels-per-unit is the camera's, unchanged, because the cascades
7197    /// select from the camera's eye at the camera's scale; see
7198    /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7199    /// frame.
7200    #[must_use]
7201    pub const fn shadow_lod_params(&self) -> [f32; 3] {
7202        self.shadow_lod_params
7203    }
7204
7205    /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7206    /// level of it, as one run — or `None` off the mesh path, where there is no
7207    /// cluster pool at all.
7208    ///
7209    /// The base a reader adds a `(level, cluster)` to in order to index
7210    /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7211    /// finest first and contiguously, so level `d` cluster `c` is at
7212    /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7213    /// its run is its clusters and `c` indexes it directly.
7214    ///
7215    /// # Panics
7216    ///
7217    /// If `mesh` is past the end of the description this renderer was built
7218    /// from, on [`add_instance`](Self::add_instance)'s terms.
7219    #[must_use]
7220    pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7221        (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7222    }
7223
7224    /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7225    /// one `u32` per resident cluster, `1` where the cluster was drawn.
7226    ///
7227    /// `None` where there is no amplification stage, which is every device that
7228    /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7229    ///
7230    /// **This is topic 25's observable and nothing in the frame
7231    /// reads it.** A frame whose every cluster came from one level is a
7232    /// plausible picture and matches any golden blessed from it, so a golden
7233    /// cannot show per-cluster selection happening at all; this can. It is
7234    /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7235    ///
7236    /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7237    #[must_use]
7238    pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7239        self.primary.cluster_selection.get(frame).copied()
7240    }
7241
7242    /// The same, for `cascade`'s shadow pass: the cut that cascade's
7243    /// amplification stage chose this frame.
7244    ///
7245    /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7246    /// passed* is a parameter; the cut they reached under it is the behaviour,
7247    /// and this is the only thing that carries it out of a frame — the colour
7248    /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7249    /// cascades have run. Indexed and read exactly as that buffer is, through
7250    /// [`cluster_range`](Self::cluster_range).
7251    ///
7252    /// `None` where there is no amplification stage, and where `cascade` is not
7253    /// one of [`shadow::CASCADES`].
7254    #[must_use]
7255    pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7256        self.shadow_selection
7257            .get(frame)
7258            .and_then(|cascades| cascades.get(cascade))
7259            .copied()
7260    }
7261
7262    /// The buckets description mesh `mesh`'s levels draw through, finest first —
7263    /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7264    ///
7265    /// **This is the uniform cut's observable**, and it is the indirect
7266    /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7267    /// instance into the bucket for the level it selected, so exactly one of
7268    /// these buckets comes out of a frame with a non-zero instance count and
7269    /// which one it is *is* the chosen level. A reader takes
7270    /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7271    /// and looks at
7272    /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7273    ///
7274    /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7275    /// level is chosen per cluster instead — see
7276    /// [`cluster_selection`](Self::cluster_selection), which is that path's
7277    /// observable.
7278    ///
7279    /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7280    /// in any scene that has an opaque material, since the table is every
7281    /// mesh's levels once per mode the scene holds, mode by mode in
7282    /// `DEPTH_MODES` order. An instance of another mode selects the same level
7283    /// and lands in that level's bucket in its own mode's run, which this does
7284    /// not name; every scene in this tree that reads this accessor is all
7285    /// opaque, so "exactly one of these has a non-zero instance count" holds for
7286    /// them as it always did.
7287    ///
7288    /// # Panics
7289    ///
7290    /// If `mesh` is past the end of the description this renderer was built
7291    /// from, on [`add_instance`](Self::add_instance)'s terms.
7292    #[must_use]
7293    pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7294        if self.mesh_level_buckets.is_empty() {
7295            return &[];
7296        }
7297        &self.mesh_level_buckets[mesh]
7298    }
7299
7300    /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7301    /// bytes per bucket — what a reader of
7302    /// [`level_buckets`](Self::level_buckets) copies out.
7303    ///
7304    /// # Panics
7305    ///
7306    /// If `frame` is not a slot this renderer was built with.
7307    #[must_use]
7308    pub fn draw_args(&self, frame: usize) -> BufferHandle {
7309        self.primary.draws.args(frame)
7310    }
7311
7312    /// `frame`'s survivor list for the primary camera and the culling
7313    /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7314    /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7315    /// the first buffer, and their count in word
7316    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7317    /// of the second — for a test holding the GPU's occlusion verdicts against
7318    /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7319    /// behind the list; see [`crate::draw_gen`].
7320    ///
7321    /// # Panics
7322    ///
7323    /// If `frame` is not a slot this renderer was built with.
7324    #[must_use]
7325    pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7326        (
7327            self.primary.draws.visible(frame),
7328            self.primary.draws.visible_count(frame),
7329        )
7330    }
7331
7332    /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7333    /// takes it: every instance slot the pool has handed out, and the whole mesh
7334    /// table — both decoded from the host's own copies of what was uploaded.
7335    #[must_use]
7336    pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7337        (self.instances.records(), self.pool.table_entries())
7338    }
7339
7340    /// The generator behind shadow cull `cull` — a cascade's below
7341    /// [`shadow::CASCADES`], a light slot's after —
7342    /// for a test reading back what a point light's face culls kept.
7343    ///
7344    /// # Panics
7345    ///
7346    /// If `cull` is not one of the renderer's shadow culls.
7347    #[must_use]
7348    pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7349        &self.shadow_draws[cull]
7350    }
7351
7352    /// The primary camera's farthest-depth pyramid — every level's image, view
7353    /// and extent, level 1 first — or empty before a frame culled by occlusion.
7354    ///
7355    /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7356    /// exactly that, and they hold the last frame's early depth once that frame
7357    /// has finished.
7358    #[must_use]
7359    pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7360        self.primary.occlusion_pyramid.level_images()
7361    }
7362
7363    /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7364    ///
7365    /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7366    /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7367    /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7368    /// are not all filled runs fewer culls, which is what makes a free tile
7369    /// free.
7370    ///
7371    /// Derived rather than written down, because a number written down is one
7372    /// that stops matching the frame the day a pass is added — which is exactly
7373    /// how the samples' hand-picked `8` came to time the first eight passes of a
7374    /// fourteen-pass frame. A caller sizing
7375    /// [`PassTimers`](crate::timing::PassTimers) wants
7376    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7377    /// what the overlay renderers record.
7378    pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7379        + DrawGen::LATE_PASSES
7380        + LightGrid::MAX_PASSES
7381        + RENDER_PASSES;
7382
7383    /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7384    /// and returns the HDR scene target they went through.
7385    ///
7386    /// `target` is normally the imported swapchain image. Everything else — the
7387    /// HDR scene colour, the depth buffer, and every barrier between them — is
7388    /// the graph's.
7389    ///
7390    /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7391    /// the scene colour **with the screen-space reflections already added**, not
7392    /// the target the forward pass wrote. A caller that wants to add a pass of
7393    /// its own after the tonemap — a debug overlay, or a readback proving the
7394    /// HDR range is real — declares a read of it and the graph works out the
7395    /// transition, exactly as it does for the tonemap.
7396    ///
7397    /// The two are the same description and different images, which is the
7398    /// design's off-switch as data rather than as a branch: a frame with
7399    /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7400    /// pass's own id, and is bit-identical.
7401    ///
7402    /// # Which passes this adds is [`effects`](Self::effects)
7403    ///
7404    /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7405    /// and read here — see [`crate::effects`] for the four layers and for what
7406    /// each toggle removes. Every effect is on by default, which is the frame
7407    /// every caller drew before the toggles existed.
7408    ///
7409    /// A switched-off effect is **fewer passes and one different bound
7410    /// descriptor**, never a shader permutation: the shadow atlas keeps its
7411    /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7412    /// to the renderer's white 1×1, and the reflection pair simply is not there.
7413    ///
7414    /// # The ground grid comes last, and after the tonemap
7415    ///
7416    /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7417    /// and it is off by default. When it is on, its pass is added **after** the
7418    /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7419    /// against the scene depth: the grid is reference chrome, and a grid drawn
7420    /// before the tonemap would be exposed and tonemapped like geometry, so its
7421    /// colour would move with how bright the scene is. See [`crate::grid`].
7422    ///
7423    /// # `pool` is where the shadow atlas's incoming state comes from
7424    ///
7425    /// It must be the same pool the caller is about to
7426    /// [`compile`](RenderGraph::compile) and
7427    /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7428    /// its placeholder are imports this renderer owns across frames and the
7429    /// pool's ledger is the record of what the last executed graph left them in
7430    /// — [`TransientPool::imported_image_use`], with [`None`] read as
7431    /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7432    /// field of our own is what keeps the declaration and the audit
7433    /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7434    /// whose `compile` fails is a frame that never ran, and a field advanced at
7435    /// build time would already have moved on without it.
7436    pub fn add_passes<'a>(
7437        &'a mut self,
7438        graph: &mut RenderGraph<'a>,
7439        pool: &TransientPool,
7440        target: ImageId,
7441        extent: (u32, u32),
7442    ) -> ImageId {
7443        self.add_frame_passes(
7444            graph,
7445            pool,
7446            FrameTargets::primary(target, extent, None),
7447            |_, _| {},
7448        )
7449    }
7450
7451    /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7452    /// frame with `skinning`'s dispatch in front of every pass that draws.
7453    ///
7454    /// # This takes the pass rather than its [`BufferId`], and that is the point
7455    ///
7456    /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7457    /// mesh pass can declare a read of it and be ordered after the dispatch. The
7458    /// obvious seam is therefore an id parameter here — and it is the wrong one,
7459    /// because every way of getting it wrong is silent. A caller can pass the id
7460    /// of a *different* import, add the skinning pass after this one, or not add
7461    /// it at all, and in each case the graph orders nothing, the draws read the
7462    /// region before the compute write has been made visible, and what comes out
7463    /// is a mesh that flickers between two poses on hardware and looks perfect
7464    /// under a validation layer.
7465    ///
7466    /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7467    /// this renderer's own frame slot, and declares the read on the three passes
7468    /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7469    /// and the forward pass. There is no order for a caller to get right,
7470    /// because there is only one call.
7471    ///
7472    /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7473    /// handed no ranges adds no dispatch and no declarations, and is the frame
7474    /// [`add_passes`](Self::add_passes) would have built.
7475    ///
7476    /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7477    ///
7478    /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7479    /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7480    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7481    /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7482    pub fn add_skinned_passes<'a>(
7483        &'a mut self,
7484        graph: &mut RenderGraph<'a>,
7485        pool: &TransientPool,
7486        target: ImageId,
7487        extent: (u32, u32),
7488        skinning: &Skinning,
7489    ) -> ImageId {
7490        self.add_frame_passes(
7491            graph,
7492            pool,
7493            FrameTargets::primary(target, extent, Some(skinning)),
7494            |_, _| {},
7495        )
7496    }
7497
7498    /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7499    /// overlay inserted after the display-space frame is complete and before
7500    /// antialiasing or render-scale reconstruction.
7501    ///
7502    /// The callback receives the display target and its matching scene depth
7503    /// attachment at the internal render extent. It may add graph passes that
7504    /// sample `display` and attach `depth` read-only; it must leave both images
7505    /// in states its declarations name. The forward renderer continues with its
7506    /// existing resolve and upscale passes after the callback returns.
7507    pub fn add_skinned_passes_with_overlay<'a, F>(
7508        &'a mut self,
7509        graph: &mut RenderGraph<'a>,
7510        pool: &TransientPool,
7511        target: ImageId,
7512        extent: (u32, u32),
7513        skinning: &Skinning,
7514        overlay: F,
7515    ) -> ImageId
7516    where
7517        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7518    {
7519        self.add_frame_passes(
7520            graph,
7521            pool,
7522            FrameTargets::primary(target, extent, Some(skinning)),
7523            overlay,
7524        )
7525    }
7526
7527    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7528    /// for a frame that also draws secondary views — see
7529    /// [`create_view`](Self::create_view).
7530    ///
7531    /// **The scene's passes are recorded once**: one skinning dispatch (where
7532    /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7533    /// in `views` records its own cull, clustering and frame into its own
7534    /// target, and the primary camera's frame into `target` comes last — so
7535    /// `overlay` may read a view's target, which is already drawn by then.
7536    ///
7537    /// Every view named must have been begun this frame by
7538    /// [`begin_view`](Self::begin_view).
7539    ///
7540    /// # Panics
7541    ///
7542    /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7543    /// a view this renderer did not build, a view not begun this frame, or a
7544    /// view twice.
7545    pub fn add_passes_with_views<'a, F>(
7546        &'a mut self,
7547        graph: &mut RenderGraph<'a>,
7548        pool: &TransientPool,
7549        frame: FrameTargets<'_>,
7550        overlay: F,
7551    ) -> ImageId
7552    where
7553        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7554    {
7555        self.add_frame_passes(graph, pool, frame, overlay)
7556    }
7557
7558    /// The body of every `add_*passes` entry point, which differ in their
7559    /// arguments and in nothing else.
7560    fn add_frame_passes<'a, F>(
7561        &'a mut self,
7562        graph: &mut RenderGraph<'a>,
7563        pool: &TransientPool,
7564        frame: FrameTargets<'_>,
7565        overlay: F,
7566    ) -> ImageId
7567    where
7568        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7569    {
7570        let FrameTargets {
7571            target,
7572            extent,
7573            skinning,
7574            views,
7575        } = frame;
7576        // **From here down `extent` is the extent the frame is *drawn* at**,
7577        // which is the caller's at a render scale of `1.0` and smaller below it.
7578        // Every use of it in this function sizes a transient, and every one of
7579        // those transients belongs to the internal frame; `target` is the only
7580        // thing here at the caller's extent, and it is an id whose image already
7581        // knows how big it is. `begin_frame_body` shadows it the same way and
7582        // for the same reason, so the two halves of a frame cannot disagree.
7583        //
7584        // `upscaling` is derived from the two extents rather than from the scale
7585        // itself, which is what makes it exact: a target small enough that the
7586        // scaled extent rounds back onto it adds no pass, because there would be
7587        // nothing for the pass to do.
7588        let target_extent = extent;
7589        let extent = self.internal_extent(target_extent);
7590        let upscaling = extent != target_extent;
7591        let frame = self.frame;
7592        let instance_count = self.instances.slot_count();
7593        let emit = self.emit;
7594
7595        // Every secondary view the caller asked for, checked before anything of
7596        // theirs is recorded: a view that does not exist, or one nothing began
7597        // this frame, would draw out of blocks written for some other frame.
7598        let secondary: Vec<(ViewTarget, (u32, u32))> = views
7599            .iter()
7600            .map(|view| {
7601                assert!(
7602                    view.view != ViewId::PRIMARY,
7603                    "the primary camera draws into the target `add_passes_with_views` takes, \
7604                     not into a `ViewTarget`"
7605                );
7606                let built = self
7607                    .views
7608                    .get(view.view.index() - 1)
7609                    .and_then(Option::as_ref)
7610                    .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
7611                assert_eq!(
7612                    built.begun, self.frame_serial,
7613                    "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
7614                    view.view
7615                );
7616                assert!(
7617                    views.iter().filter(|other| other.view == view.view).count() == 1,
7618                    "{:?} was named twice in one frame",
7619                    view.view
7620                );
7621                (*view, self.view_extent(built.background, view.extent))
7622            })
7623            .collect();
7624
7625        // **The skinning dispatch, before anything else is added.** It imports
7626        // the vertex pool and hands back that node's id; every pass below that
7627        // pulls vertices declares a read of it, and the graph is what turns the
7628        // two declarations into the barrier between the compute write and the
7629        // draws. `None` is a frame with nothing to skin, which adds no pass and
7630        // declares nothing — see `Skinning::add_pass`.
7631        let skinned = skinning.and_then(|skinning| skinning.add_pass(graph, frame));
7632
7633        // The camera's cull dispatch and the draw-argument dispatch, and the
7634        // light clustering after them — before anything draws, and before the
7635        // shadow atlas, which is where they always ran. See [`View::add_cull`].
7636        let cull = self.primary.add_cull(graph, pool, frame, instance_count);
7637
7638        // Topic 25's record of each cascade's cut. Each is written by
7639        // exactly one mesh pass, so what the graph orders here is this frame's
7640        // write against the next frame's use of the same slot. Each arrives in
7641        // the state the previous frame left it in, which is the one declared as
7642        // final.
7643        let tile_selection: Vec<BufferId> = self
7644            .shadow_selection
7645            .get(self.frame)
7646            .into_iter()
7647            .flatten()
7648            .enumerate()
7649            .map(|(tile, &buffer)| {
7650                import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
7651            })
7652            .collect();
7653
7654        // **This frame's slot of the probe ring**, which is the buffer every
7655        // one of this frame's bind groups names — see [`crate::probe`] for why
7656        // there is more than one. Imported in `ShaderRead` and handed back in
7657        // it: the build's staging copy left it there and no pass in the frame
7658        // writes it yet.
7659        let probe_buffer = self.probes.buffer(frame);
7660        let probe_table = graph.import_buffer(
7661            "probes",
7662            ImportedBuffer {
7663                buffer: probe_buffer,
7664                initial: ResourceState::ShaderRead,
7665                final_state: ResourceState::ShaderRead,
7666            },
7667        );
7668
7669        // The occlusion placeholder, imported once and read by every pass whose
7670        // bind group names it: the shadow pass's views, the depth prepass's copy
7671        // of the camera's group, and — on a frame drawing without
7672        // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
7673        // uploaded at build, so it is already in `ShaderRead` and the graph has
7674        // nothing to transition; declaring it is what keeps that true if a later
7675        // pass wants it in some other state.
7676        let occlusion_placeholder = graph.import_image(
7677            "ssao-placeholder",
7678            ImportedImage {
7679                image: self.ambient_occlusion_placeholder.image,
7680                view: self.ambient_occlusion_placeholder.view,
7681                format: Format::R8Unorm,
7682                extent: (1, 1),
7683                initial: ResourceState::ShaderRead,
7684                claim: InitialClaim::Tracked,
7685                final_state: ResourceState::ShaderRead,
7686            },
7687        );
7688
7689        // The contact-shadow placeholder, imported beside the occlusion one and
7690        // on its terms exactly: every group of the mesh layout names this
7691        // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
7692        // it is what the forward pass binds.
7693        let contact_placeholder = graph.import_image(
7694            "contact-shadows-placeholder",
7695            ImportedImage {
7696                image: self.contact_shadow_placeholder.image,
7697                view: self.contact_shadow_placeholder.view,
7698                format: Format::R8Unorm,
7699                extent: (1, 1),
7700                initial: ResourceState::ShaderRead,
7701                claim: InitialClaim::Tracked,
7702                final_state: ResourceState::ShaderRead,
7703            },
7704        );
7705
7706        // §3.2's base-colour page, in every bind group of `mesh_layout` and so
7707        // read by all three of the passes that draw geometry. Like the
7708        // placeholder above it is already in `ShaderRead` and the graph has
7709        // nothing to transition on a frame nothing writes it — **the
7710        // declaration is for the frames something does**. A caller that copies a
7711        // render-to-texture view into one of its layers imports the same handle,
7712        // gets this same id back (`RenderGraph::import_image`), and the graph
7713        // then has an edge to order its write against these reads. Without the
7714        // declaration there is no such edge: the page is bound out of a
7715        // descriptor the graph never hears about, and a copy scheduled anywhere
7716        // but the tail of the frame leaves it in `TransferDst` for the passes
7717        // that sample it.
7718        let base_color_page =
7719            graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
7720        // §2's normal page beside it, declared for exactly the reason above: it
7721        // is in every group of `mesh_layout` too, so a caller copying into one
7722        // of its layers needs the same edge against these draws.
7723        let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
7724        // §2's other two pages beside them, declared for exactly the same
7725        // reason: both are in every group of `mesh_layout`, so a caller copying
7726        // into one of their layers needs the same edge against these draws.
7727        let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
7728        let emissive_page =
7729            graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
7730
7731        // What this frame draws, resolved by the `begin_frame` that opened it —
7732        // see [`crate::effects`]. Read once here so every conditional below is
7733        // about one value rather than about four reads of a field.
7734        let effects = self.frame_effects;
7735        // Read here for `effects`' reason and for one more: the passes below
7736        // borrow `self` field by field, and a `&self` method called between
7737        // them would borrow the whole of it.
7738        let draws_sky = self.draws_sky();
7739        // What the frame's water draws, or `None` for a frame with none — read
7740        // here for `draws_sky`'s reason, and the same value every view records
7741        // from.
7742        let water = self.water.frame(self.frame);
7743        // The same, for the grass field: read here for `draws_sky`'s reason,
7744        // and the same value every view records from.
7745        let grass = self.grass.frame();
7746        // Whether this frame ends by drawing the shadow atlas over itself — the
7747        // resolved view rather than the switch, so a caller who left the atlas
7748        // up and then asked for normals gets normals. Read here for
7749        // `draws_sky`'s reason exactly: `debug_view` takes `&self`.
7750        let draws_atlas_view = self.debug_view() == DebugView::ShadowAtlas;
7751
7752        let pages = MaterialPages {
7753            base_color: base_color_page,
7754            normal: normal_page,
7755            mro: mro_page,
7756            emissive: emissive_page,
7757        };
7758        let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
7759            graph,
7760            pool,
7761            &tile_selection,
7762            ShadowReads {
7763                occlusion_placeholder,
7764                pages,
7765                skinned,
7766                probes: probe_table,
7767            },
7768        );
7769
7770        // The wireframe twin where a caller switched the view on, and `None`
7771        // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
7772        // terms, and the `filter` is what keeps "switched on" from outrunning
7773        // "built": the field is only `Some` after a build that succeeded.
7774        //
7775        // The depth prepass below takes the depth-only pipeline and is untouched
7776        // by this, which is the half that makes a wireframe frame legible: the
7777        // occlusion pair still reads solid depth. **It is also what makes this
7778        // one variable rather than two**: the colour pass's depth attachment
7779        // branches on it as well, because a wireframe is not the geometry the
7780        // prepass drew — see `MeshModules::color_depth_stencil`.
7781        let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
7782        let bucket_draws = BucketDraws {
7783            // Replaced per partition below, in both passes that draw this list —
7784            // see [`ForwardRenderer::sided_partitions`] and
7785            // [`ForwardRenderer::depth_partitions`]. The field is what the
7786            // partitions inherit everything else from.
7787            pipeline: self.mesh_pipeline.single,
7788            layout: self.mesh_pipeline_layout,
7789            indices: self.pool.index_buffer(),
7790            emit,
7791            calls: self
7792                .bucket_constants
7793                .iter()
7794                .enumerate()
7795                .map(|(bucket, constant_offset)| {
7796                    let bucket = u32::try_from(bucket)
7797                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
7798                    (
7799                        *constant_offset,
7800                        self.primary.draws.args_offset(bucket),
7801                        self.primary.draws.count_offset(bucket),
7802                        self.primary.draws.mesh_args_offset(bucket),
7803                    )
7804                })
7805                .collect(),
7806            region_step: self.region_step,
7807            // Packed per partition, where the partition's buckets are known.
7808            ranges: None,
7809            flat: None,
7810        };
7811
7812        // Every draw this frame records: the shadow pass's, one per bucket — or
7813        // per range of buckets, or per partition behind a task stage — in
7814        // **each** of the depth prepass and the forward pass, and one full-screen
7815        // triangle per full-screen pass. Assigned before the passes below borrow
7816        // the fields they need, so it is the count for the frame being built
7817        // rather than the one before it — and off this frame's resolved effects
7818        // rather than off a constant, so a switched-off effect's triangle is not
7819        // counted as submitted.
7820        //
7821        // The ground grid is added on top rather than folded into
7822        // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
7823        // resolved by the toggle order — it is a caller's opt-in, off by
7824        // default — so what decides it is the field and not this frame's
7825        // effects.
7826        self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
7827                + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
7828                + if draws_sky { SkyPass::PASSES } else { 0 }
7829                // The composite on an atmosphere frame whose fog effect is off,
7830                // on the sky's terms: it is there for the air in front of the
7831                // scene, which the atmosphere decides and no effect bit does.
7832                // With the effect on, `fullscreen_passes` already counted it.
7833                + if self.primary.frame_aerial
7834                    && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
7835                {
7836                    u64::from(Volumetric::COMPOSITE_PASSES)
7837                } else {
7838                    0
7839                }
7840                // The water copy's triangle, on the sky's terms: content rather
7841                // than an effect bit, so the bodies decide it.
7842                + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
7843                // The atlas viewer, on the ground grid's terms: not an effect
7844                // bit and not resolved by the toggle order, so what decides it
7845                // is the debug view and not this frame's effects. It *replaces*
7846                // the tonemap `fullscreen_passes` counted and the grid above —
7847                // see `View::add_passes` — so its passes stand in for the one.
7848                + if draws_atlas_view {
7849                    u64::from(AtlasView::PASSES) - 1
7850                } else {
7851                    0
7852                };
7853        // The debug draw layer's own call, on the ground grid's terms: not an
7854        // effect bit, and decided by whether this frame's slot has a segment in
7855        // it. One direct draw of one instance covering every segment appended,
7856        // which is why it joins the full-screen triangles rather than the
7857        // indirect draws — `counters` counts both as submitted *and* drawn,
7858        // because the CPU knows what they cover.
7859        self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
7860        // The shadow pass's tile resets, on the same terms: one over-sized
7861        // triangle of one instance per tile it redrew, and none at all on a
7862        // frame that cleared the whole attachment — see
7863        // [`MeshModules::depth_clear_pipeline`].
7864        self.recorded_tile_clears = shadow_tile_clears;
7865        // One indexed draw per body the frame's water holds.
7866        self.recorded_water_draws = water
7867            .as_ref()
7868            .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
7869        // One indirect draw per tile slot the frame's field holds, per look it
7870        // draws.
7871        self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
7872            u64::from(grass.slots) * u64::from(grass.draws_per_slot())
7873        });
7874        // The late depth prepass is a third list of calls, on a frame whose
7875        // camera culls in two phases.
7876        let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
7877            == crcbl_shaders::draw_gen::DrawMode::Occlusion
7878        {
7879            3
7880        } else {
7881            2
7882        };
7883        let prepass_partitions = self.depth_partitions(&bucket_draws);
7884        // And the colour pass's own split, which is by **side** alone: its
7885        // pipeline has a fragment stage either way, so an alpha mask is nothing
7886        // it has to route around and a cull mode is. The wireframe twin pair
7887        // substitutes for the shaded one here exactly as the single pipeline
7888        // used to.
7889        let color_partitions =
7890            self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
7891        // Off the partitions the passes below record, because where a call
7892        // draws a range of buckets the two splits pack into different numbers
7893        // of ranges — see [`BucketDraws::call_count`].
7894        let calls = |partitions: &[BucketDraws]| -> u64 {
7895            partitions.iter().map(BucketDraws::call_count).sum()
7896        };
7897        self.recorded_draws = shadow_draws
7898            + (camera_passes - 1) * calls(&prepass_partitions)
7899            + calls(&color_partitions)
7900            + self.recorded_grass_draws
7901            + self.direct_draws();
7902
7903        // --- the probe gather ---
7904        //
7905        // The irradiance probes' updater, second half: the map
7906        // the pass above drew, read into every row of the table. **Here rather
7907        // than beside that pass** because the write is `&mut` — the group naming
7908        // the map's transient views is cached across frames, and a group naming a
7909        // transient cannot be built where the others are; see
7910        // [`crate::ssao::cached_group`].
7911        //
7912        // It is before the depth prepass and the forward pass, which is the
7913        // ordering that matters: both declare a read of these rows, so the graph
7914        // barriers this write against them.
7915        //
7916        // Which map layer a row is weighed against is the row's own index, so
7917        // the view is resolved exactly as the drawing passes resolve it — the
7918        // placeholder until `capture_probe_visibility` has run, and off entirely
7919        // where `r_probe_visibility` is off. A gather against the placeholder
7920        // occludes nothing, which is the honest answer for a scene that never
7921        // captured.
7922        let probe_visibility_view = match &self.probe_visibility {
7923            Some(captured) if crate::probe_visibility::enabled() => captured.view,
7924            _ => self.probe_visibility_placeholder.view,
7925        };
7926        let frame = self.frame;
7927        if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
7928            gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
7929        }
7930
7931        let passes = FramePasses {
7932            slot: frame,
7933            emit,
7934            target_format: self.target_format,
7935            ssao_blurs: self.frame_ssao_blurs,
7936            draws_sky,
7937            water,
7938            grass,
7939            skinned,
7940            probe_buffer,
7941            probe_table,
7942            occlusion_placeholder,
7943            contact_placeholder,
7944            pages,
7945            shadow_atlas,
7946            probe_visibility: probe_visibility_view,
7947            mesh_layout: self.mesh_layout,
7948            wireframe,
7949            prepass_partitions,
7950            color_partitions,
7951            tonemap: TonemapPipeline {
7952                sampler: self.sampler,
7953                layout: self.tonemap_layout,
7954                pipeline_layout: self.tonemap_pipeline_layout,
7955                pipeline: self.tonemap_pipeline,
7956            },
7957        };
7958        // From here the frame is borrowed field by field, because every view's
7959        // passes hold its own caches for the life of the graph.
7960        let Self {
7961            primary,
7962            views: built,
7963            debug_draw,
7964            ground_grid,
7965            ground_grid_on,
7966            atlas_viewer,
7967            cull_stats,
7968            ..
7969        } = self;
7970
7971        // **Every secondary view before the primary camera's frame**, so a pass
7972        // the primary records — an overlay compositing a scope's picture onto
7973        // the lens it is seen through — reads a view that is already drawn. Each
7974        // records its whole frame straight through: its own cull, its own
7975        // clustering, and every pass the primary records after them, against the
7976        // atlas and the probe rows the scene passes above left behind.
7977        for (index, slot) in built.iter_mut().enumerate() {
7978            let Some((view_target, view_extent)) = secondary
7979                .iter()
7980                .find(|(view, _)| view.view.index() == index + 1)
7981            else {
7982                continue;
7983            };
7984            let view = slot
7985                .as_mut()
7986                .unwrap_or_else(|| unreachable!("checked against the built views above"));
7987            let view_cull = view.add_cull(graph, pool, frame, instance_count);
7988            view.add_passes(
7989                graph,
7990                &passes,
7991                view_cull,
7992                ViewOutput {
7993                    target: view_target.target,
7994                    target_extent: view_target.extent,
7995                    extent: *view_extent,
7996                },
7997                Overlays::default(),
7998                |_, _| {},
7999            );
8000        }
8001
8002        // The statistics buffer's id, read before the cull moves into the pass
8003        // recording below: the copy that reads it is the frame's last pass.
8004        let stats_id = cull.generated.visible_count_id;
8005        let tonemapped = primary.add_passes(
8006            graph,
8007            &passes,
8008            cull,
8009            ViewOutput {
8010                target,
8011                target_extent,
8012                extent,
8013            },
8014            Overlays {
8015                debug_draw: Some(debug_draw),
8016                ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8017                atlas_viewer: draws_atlas_view.then_some(atlas_viewer),
8018            },
8019            overlay,
8020        );
8021
8022        // **Last, and that is the point.** Three passes add to the statistics
8023        // buffer — the cull dispatch, the light grid's overflow counter and the
8024        // amplification stage inside the forward pass — so a copy scheduled any
8025        // earlier would take a total the frame had not finished writing. The
8026        // graph puts it in `TransferSrc` for this and back into the state the
8027        // next frame on this slot imports it in; there is not a barrier written
8028        // here.
8029        if let Some(stats) = cull_stats.as_mut() {
8030            stats.add_copy_pass(graph, stats_id);
8031        }
8032
8033        tonemapped
8034    }
8035
8036    /// Adds the cull dispatches and the depth-only pass that fill the shadow
8037    /// atlas, and returns the atlas as the graph knows it.
8038    ///
8039    /// Every tile is one viewport of one render pass. A pass per tile would be
8040    /// one clear of the same image and one more barrier per tile, and the graph
8041    /// would have to be told each of them only touches part of it — where one
8042    /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8043    /// place.
8044    ///
8045    /// **Only the occupied tiles get a cull and a viewport.** The cascades
8046    /// always are; a light tile is occupied when
8047    /// [`shadow::Selection`] gave it to a light. A free one keeps the
8048    /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8049    /// away as depth goes" — so anything that did sample it would come back
8050    /// fully lit rather than fully shadowed.
8051    ///
8052    /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8053    ///
8054    /// That is the whole switch, and it is the same mechanism a free tile
8055    /// already had rather than a second one: no cull is dispatched and no
8056    /// viewport is drawn, the pass records its clear and nothing else, and every
8057    /// comparison against the atlas comes back fully lit. The pass itself stays
8058    /// on the frame that switches it off — it is what *writes* that clear, and a
8059    /// frame that skipped it would leave the atlas holding the last frame that
8060    /// did draw into it, or undefined memory on the first frame of all.
8061    ///
8062    /// # A cached atlas records nothing at all
8063    ///
8064    /// Topic 45's static-caching rung. When
8065    /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8066    /// what this frame would draw, this adds **no cull and no pass**: the atlas
8067    /// is imported so the passes that sample it have an edge to the resource,
8068    /// and it keeps the contents an earlier frame left in it. That is why the
8069    /// image is a persistent one with a tracked ledger entry rather than a
8070    /// transient — nothing else in the frame can alias it, so what it holds is
8071    /// what the last pass to write it wrote.
8072    ///
8073    /// # Per group, and what pays for the tiles it keeps
8074    ///
8075    /// Topic 45's cadence rung. A **group** — a cascade, or a
8076    /// light slot's whole run of tiles — is redrawn or held on its own, and
8077    /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8078    /// that holds nothing clears the whole attachment, which is the recording
8079    /// that shipped before the rung; a frame that holds something **loads** the
8080    /// attachment instead and resets each tile it redraws with
8081    /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8082    /// a clear bounded to one tile.
8083    ///
8084    /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8085    /// every tile including the ones being kept, and the region-bounded
8086    /// alternatives are not portable — Metal's load action and WebGPU's
8087    /// `loadOp` have no render area to bound them, so a clear that covered part
8088    /// of the image on Vulkan and all of it on Metal would be a held tile that
8089    /// survives on one backend and is erased on another.
8090    fn add_shadow_pass(
8091        &self,
8092        graph: &mut RenderGraph<'_>,
8093        pool: &TransientPool,
8094        selection: &[BufferId],
8095        reads: ShadowReads,
8096    ) -> (ImageId, u64, u64, Option<RsmImages>) {
8097        let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8098        let (atlas_width, atlas_height) = shadow::atlas_extent();
8099        let atlas = graph.import_image(
8100            "shadow-atlas",
8101            ImportedImage {
8102                image: self.shadow_atlas,
8103                view: self.shadow_atlas_view,
8104                format: Format::D32Float,
8105                extent: (atlas_width, atlas_height),
8106                // What the previous executed frame left it in — `Undefined` on
8107                // the first, which is what makes the graph give it a layout at
8108                // all.
8109                initial: imported_state(pool, self.shadow_atlas),
8110                // The renderer keeps this image across frames, so the pool's
8111                // ledger is the record of what happened to it and the line above
8112                // is that record read back rather than a second copy of it.
8113                claim: InitialClaim::Tracked,
8114                final_state: ResourceState::ShaderRead,
8115            },
8116        );
8117        // The cached frame's whole answer: the image above and nothing that
8118        // touches it. It is already in `ShaderRead` — the frame that drew it
8119        // handed it back that way — so the graph has no transition to make, and
8120        // the passes that sample it read the maps an earlier frame left there.
8121        if self.shadow_atlas_cached {
8122            // **And no reflective shadow map either**, which cannot happen while
8123            // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8124            // exactly that case, so a frame reaching here has nothing to draw
8125            // the map from. See `probe_update_runs`.
8126            return (atlas, 0, 0, None);
8127        }
8128        let placeholder = graph.import_image(
8129            "shadow-placeholder",
8130            ImportedImage {
8131                image: self.shadow_placeholder,
8132                view: self.shadow_placeholder_view,
8133                format: Format::D32Float,
8134                extent: (1, 1),
8135                // **Its own ledger entry, not the atlas's.** The two move
8136                // together today — both are imported by this function on every
8137                // frame and both are handed back in `ShaderRead` — so one lookup
8138                // would answer both, and that is exactly the coincidence a
8139                // second declared state here stops depending on.
8140                initial: imported_state(pool, self.shadow_placeholder),
8141                claim: InitialClaim::Tracked,
8142                final_state: ResourceState::ShaderRead,
8143            },
8144        );
8145
8146        // Which light slots have a light this frame, resolved once: a slot's
8147        // cull is dispatched and its faces are drawn together or not at all, and
8148        // `begin_frame` filled that generator's parameters under exactly this
8149        // condition.
8150        //
8151        // **And only the ones this frame redraws**, since the cadence rung: a
8152        // held slot keeps the texels it has, so recording its cull and its
8153        // draws would be the same picture at the full price.
8154        let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8155            .shadow_lights
8156            .slots()
8157            .iter()
8158            .enumerate()
8159            .filter(|_| shadows)
8160            .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8161            .filter_map(|(slot, held)| {
8162                let held = (*held)?;
8163                Some((slot, held, self.extra_lights.get(held.light)?))
8164            })
8165            .collect();
8166
8167        // One cull dispatch per cascade and per occupied slot, before the pass
8168        // that draws from them — **not one per tile**, which is topic 18's
8169        // fourth decision: a point light's six faces draw one visible set.
8170        let cascades: Vec<usize> = if shadows {
8171            (0..shadow::CASCADES)
8172                .filter(|cascade| self.shadow_group_redrawn[*cascade])
8173                .collect()
8174        } else {
8175            Vec::new()
8176        };
8177        // **Cascade 0's cull, on a frame that is not drawing it into the
8178        // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8179        // no shadows — see `rsm_cull_ready` — so this is the case where the map
8180        // is drawn and the atlas keeps its clear. Chained **last**, because the
8181        // occupied slots' entries are indexed by `cascades.len() + index` a few
8182        // lines below and an insertion before them would hand a light's draws to
8183        // the wrong viewport.
8184        let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8185        // The punctual producer's faces, which are also the light slots'
8186        // atlas views — see `punctual_faces`, the one list both halves of the
8187        // updater walk.
8188        let punctual = self.punctual_faces();
8189        // And their culls on a frame that is not drawing the atlas, which
8190        // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8191        // because a point light's six faces draw one visible set, and chained
8192        // **after** the entries `views` indexes positionally below.
8193        let punctual_only_culls: Vec<usize> = if shadows {
8194            Vec::new()
8195        } else {
8196            punctual
8197                .iter()
8198                .map(|face| face.cull)
8199                .collect::<std::collections::BTreeSet<_>>()
8200                .into_iter()
8201                .collect()
8202        };
8203        let generated: Vec<(usize, GeneratedDraws)> = cascades
8204            .iter()
8205            .copied()
8206            .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8207            .chain(rsm_only_cull.then_some(0))
8208            .chain(punctual_only_culls)
8209            .map(|cull| {
8210                (
8211                    cull,
8212                    self.shadow_draws[cull].add_passes(
8213                        graph,
8214                        self.frame,
8215                        self.instances.slot_count(),
8216                    ),
8217                )
8218            })
8219            .collect();
8220
8221        // What the pass body records, in order: which view's bind group, which
8222        // rectangle of the atlas its viewport covers, and which of the culls
8223        // above it draws from. Paired rather than positional, because the free
8224        // slots are missing from every one of these lists and a bare index into
8225        // one would hand a light's draws to the wrong viewport the moment one
8226        // slot is free and a later one is not.
8227        //
8228        // **The rectangle rather than the slot**, resolved here: the body runs
8229        // in a closure that outlives this borrow, and asking the selection for
8230        // it there would be a second reading of an allocation that has to be the
8231        // one the frame block was written from.
8232        //
8233        // **And which draw region of that cull**: region 0, every survivor, for
8234        // a cascade and a spot; and for a point light whose cull tagged its
8235        // casters by face, the region of the face being drawn — see
8236        // `set_point_face_culls`.
8237        let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8238            .iter()
8239            .enumerate()
8240            .map(|(position, cascade)| {
8241                (
8242                    *cascade,
8243                    self.shadow_lights.atlas_rect(*cascade),
8244                    position,
8245                    0,
8246                )
8247            })
8248            .collect();
8249        for (index, (slot, held, light)) in occupied.iter().enumerate() {
8250            // A spot draws face 0 alone; a point light draws all six, each
8251            // through its own matrix into its own tile. `shadow::tile_span` is
8252            // the same function `Selection` allocated the run with, so a face
8253            // here and a tile there cannot disagree about how many there are.
8254            let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8255                == crcbl_shaders::draw_gen::DrawMode::Faces;
8256            for face in 0..shadow::tile_span(light) {
8257                views.push((
8258                    shadow_view(*slot, face),
8259                    self.shadow_lights
8260                        .atlas_rect(shadow::light_tile(held.base + face)),
8261                    cascades.len() + index,
8262                    face_region(by_face, face),
8263                ));
8264            }
8265        }
8266
8267        let mut pass = graph
8268            .add_render_pass("shadow")
8269            // **Stored, unlike the scene's depth.** This is the one depth buffer
8270            // in the engine that something downstream reads, which is what
8271            // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8272            // day a prepass existed.
8273            .depth(
8274                atlas,
8275                // **Loaded on a frame that is keeping a tile**, which is the
8276                // cadence rung's whole seam: a clear here covers the image, so
8277                // the tiles this frame *does* redraw are reset one at a time by
8278                // the pipeline below instead. A frame keeping nothing clears,
8279                // which is what shipped.
8280                if self.shadow_atlas_clears {
8281                    LoadOp::Clear
8282                } else {
8283                    LoadOp::Load
8284                },
8285                StoreOp::Store,
8286                crcbl_hal::ClearValue {
8287                    depth: crcbl_hal::depth::CLEAR,
8288                    ..crcbl_hal::ClearValue::default()
8289                },
8290            )
8291            // Declared so the graph gives it a shader-read layout: it is in
8292            // every cascade's bind group, standing in for the atlas this pass is
8293            // writing. See `ForwardRenderer::shadow_placeholder`.
8294            .read_image(placeholder)
8295            // Likewise, and it is in every one of those groups too — see
8296            // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8297            // it here either: the depth-only pipeline has no fragment stage.
8298            .read_image(reads.occlusion_placeholder)
8299            // And §3.2's page, which `mesh_layout` names in every group — a
8300            // cascade's included. See `ForwardRenderer::base_color_page_import`
8301            // for what the declaration buys a caller that writes the page.
8302            .read_image(reads.pages.base_color)
8303            // And §2's other three pages beside it, in those same groups and
8304            // sampled by no cascade — see
8305            // `ForwardRenderer::normal_page_import`.
8306            .read_image(reads.pages.normal)
8307            .read_image(reads.pages.mro)
8308            .read_image(reads.pages.emissive)
8309            // And the probe rows, which are in those groups too and which no
8310            // cascade reads — declared on the placeholder's and the pages'
8311            // terms, plus one of their own: the rows are device-local and a copy
8312            // destination so the irradiance probes' gather can
8313            // write them, and a pass that binds a buffer it has not declared is
8314            // one the graph cannot order that write against.
8315            .read_buffer(reads.probes);
8316        // Each tile's mesh pass records the cut it descended to, into a buffer
8317        // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8318        // there is no amplification stage to descend anything.
8319        //
8320        // Declared for every tile rather than for the occupied ones: the state
8321        // is what the buffer is *in*, which does not depend on whether this
8322        // frame happened to write it, and a free tile's buffer still has to
8323        // arrive in the state the next frame's import claims.
8324        for &buffer in selection {
8325            pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8326        }
8327        // The skinned vertices this pass may pull, and the reason it is declared
8328        // here as well as on the colour passes: a cascade draws the same
8329        // geometry out of the same pool, so a shadow that fell before the
8330        // dispatch was visible would be cast by the previous pose — a shadow
8331        // that does not match its caster, on a frame whose picture is otherwise
8332        // right.
8333        if let Some(vertices) = reads.skinned {
8334            pass = pass.read_buffer(vertices);
8335        }
8336        for (_, draws) in &generated {
8337            pass = read_draw_sources(pass, draws, self.emit);
8338        }
8339
8340        let groups = self.shadow_groups[self.frame].clone();
8341        // **What the reflective shadow map is drawn from**, read out here rather
8342        // than reconstructed by the caller: cascade 0's bind group — whose
8343        // uniform block already holds that cascade's `view_proj`, which is what
8344        // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8345        // produced a moment ago. Both are `Copy`, so recording a second pass
8346        // from them costs no second cull and no second matrix.
8347        //
8348        // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8349        // or a `r_shadow_cadence` past one that held the group anyway. The rows
8350        // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8351        // which says so.
8352        let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8353            .rsm_cull_ready
8354            .then(|| {
8355                generated
8356                    .iter()
8357                    .find(|(cull, _)| *cull == 0)
8358                    .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8359            })
8360            .flatten();
8361        // **What the punctual reflective shadow map is drawn from**, resolved
8362        // here for `cascade_zero`'s reason and on its terms: each face's own
8363        // bind group — whose uniform block already holds that face's
8364        // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8365        // moment ago. Both are `Copy`, so the second pass costs no second cull
8366        // and no second matrix.
8367        //
8368        // Found by cull id rather than by position, so this list and the atlas's
8369        // cannot be knocked out of step by a slot the other one skipped.
8370        //
8371        // And the face's draw region, on the atlas's terms: a point light whose
8372        // cull tagged its casters draws each face from that face's region.
8373        let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8374            punctual
8375                .iter()
8376                .filter_map(|face| {
8377                    let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8378                    let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8379                        == crcbl_shaders::draw_gen::DrawMode::Faces;
8380                    Some((
8381                        groups[face.view],
8382                        face.tile,
8383                        *draws,
8384                        face_region(by_face, face.face),
8385                    ))
8386                })
8387                .collect();
8388        // The culls those faces draw from, **once each**: a point light's six
8389        // faces draw one visible set, so declaring a face's sources would
8390        // declare the same buffers six times in one pass.
8391        let punctual_sources: Vec<GeneratedDraws> = punctual
8392            .iter()
8393            .map(|face| face.cull)
8394            .collect::<std::collections::BTreeSet<_>>()
8395            .into_iter()
8396            .filter_map(|cull| {
8397                let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8398                Some(*draws)
8399            })
8400            .collect();
8401        let bucket_draws = BucketDraws {
8402            // Replaced per partition below; the field is what the tile clears
8403            // and the reflective shadow map inherit, and neither binds it.
8404            pipeline: self.shadow_pipeline.single,
8405            layout: self.mesh_pipeline_layout,
8406            indices: self.pool.index_buffer(),
8407            emit: self.emit,
8408            calls: self
8409                .bucket_constants
8410                .iter()
8411                .enumerate()
8412                .map(|(bucket, constant_offset)| {
8413                    let bucket = u32::try_from(bucket)
8414                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8415                    (
8416                        *constant_offset,
8417                        self.primary.draws.args_offset(bucket),
8418                        self.primary.draws.count_offset(bucket),
8419                        self.primary.draws.mesh_args_offset(bucket),
8420                    )
8421                })
8422                .collect(),
8423            region_step: self.region_step,
8424            // Packed per partition, where the partition's buckets are known.
8425            ranges: None,
8426            flat: None,
8427        };
8428        // Kept back for the reflective shadow map below, which is the same
8429        // per-bucket call list under a different pipeline — the depth prepass
8430        // plays exactly this trick with the camera's. Cloned before the pass
8431        // body takes the original.
8432        let bucket_calls = bucket_draws.clone();
8433        // The atlas's own split by material mode: an opaque bucket's tile is
8434        // drawn with no fragment stage in a scene that has a cutout in it. Every
8435        // view draws every partition — one call per bucket, per range of
8436        // buckets, or behind a task stage one flat call, per view, under a
8437        // pipeline per mode.
8438        let tile_partitions = self.depth_partitions(&bucket_draws);
8439
8440        // Counted off the two loops the body below runs, before it takes them:
8441        // every partition's calls per occupied view. `ForwardRenderer::counters`
8442        // is what reports it, and reading it back off the same `Vec`s is what
8443        // makes it move when the tile allocation does.
8444        let recorded = views.len() as u64
8445            * tile_partitions
8446                .iter()
8447                .map(BucketDraws::call_count)
8448                .sum::<u64>();
8449        // And the tile resets beside them, which are direct draws of one
8450        // instance rather than indirect ones: a frame that cleared the whole
8451        // attachment records none, and a frame that loaded it records one per
8452        // tile it redraws.
8453        let clears = if self.shadow_atlas_clears {
8454            0
8455        } else {
8456            views.len() as u64
8457        };
8458
8459        // What the image will hold once this body has run, carried into it so
8460        // that *recording* the pass is not what claims the atlas was drawn — see
8461        // [`ForwardRenderer::shadow_atlas_drawn`].
8462        let ran = Arc::clone(&self.shadow_pass_ran);
8463        let pass_id = self.shadow_pass_id;
8464        // The tiles this pass redraws have to be reset before anything is drawn
8465        // into them, and on a frame that loaded the attachment there is nothing
8466        // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8467        // that cleared has already had every tile reset by the attachment, so
8468        // this is `None` and the recording is the one that shipped.
8469        let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8470        // **The reset draw has to bind a group, and only a browser says so.**
8471        // `MeshModules::depth_clear_pipeline` builds this pipeline from
8472        // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8473        // the one triangle's vertex shader reads a byte of it — and WebGPU
8474        // refuses a draw with any group the *layout* declares left unset, where
8475        // Vulkan and the others only care about what the shader dereferences. An
8476        // unbound reset therefore fails no native run and rejects the whole
8477        // browser frame: `No bind group set at group index 0` arrives when the
8478        // encoder is finished, so every pass recorded after it is thrown away
8479        // with it and the canvas stays at the clear colour.
8480        //
8481        // Any bucket's offset does: the block is what the mesh draws index and
8482        // this draw reads none of it, so what matters is that the offset is one
8483        // the layout accepts rather than which bucket it names.
8484        let clear_layout = bucket_draws.layout;
8485        let clear_offset = bucket_draws
8486            .calls
8487            .first()
8488            .map_or(0, |(constant_offset, ..)| *constant_offset);
8489        pass.execute(move |ctx| {
8490            ran.store(pass_id, Ordering::Relaxed);
8491            let encoder = ctx.encoder();
8492            if let Some(clear) = clear {
8493                encoder.bind_graphics_pipeline(clear);
8494                for (view, tile, _, _) in &views {
8495                    set_shadow_tile(encoder, *tile);
8496                    encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8497                    encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8498                }
8499            }
8500            for partition in &tile_partitions {
8501                partition.open(encoder);
8502                for (view, tile, cull, region) in &views {
8503                    set_shadow_tile(encoder, *tile);
8504                    partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8505                }
8506            }
8507        });
8508
8509        // --- the reflective shadow map ---
8510        //
8511        // The irradiance probes' updater, first half, recorded
8512        // here because this is where cascade 0's bind group and its
8513        // already-generated draws are. **A pass of its own at its own extent**,
8514        // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8515        // one colour attachment there spans the whole 3072² image for data only
8516        // one 768² tile is read from, and it would give all fourteen light tiles
8517        // a fragment stage.
8518        //
8519        // No viewport is set: the graph opens a pass with a full-target viewport
8520        // and scissor already, and every attachment here is the map's own square.
8521        let Some((cascade_group, cascade_draws)) = cascade_zero else {
8522            return (atlas, recorded, clears, None);
8523        };
8524        let extent = rsm::extent();
8525        let sun = RsmTargets {
8526            albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8527            normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
8528            world: graph.create_image("rsm-world", rsm::world_target(extent)),
8529        };
8530        // Its own depth, cleared and discarded: it resolves which surface a
8531        // texel of the map holds and nothing reads it afterwards.
8532        let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
8533        let mut rsm = graph
8534            .add_render_pass("rsm")
8535            // **Cleared, and the world target's clear is load-bearing**: `w` is
8536            // the coverage flag `RsmOutput::world` writes, so a texel the pass
8537            // draws nothing into reads back zero there and the gather skips it.
8538            // Without the clear the world origin would stand in for every part
8539            // of the cascade the geometry does not cover.
8540            .clear_color(sun.albedo, [0.0; 4])
8541            .clear_color(sun.normal, [0.0; 4])
8542            .clear_color(sun.world, [0.0; 4])
8543            .clear_depth(rsm_depth)
8544            // The same declarations the cascade above makes, for the same
8545            // reason: every group of the mesh layout names these, and this pass
8546            // binds one of those groups. Unlike the cascade, this one has a
8547            // fragment stage — so the pages really are sampled here.
8548            .read_image(placeholder)
8549            .read_image(reads.occlusion_placeholder)
8550            .read_image(reads.pages.base_color)
8551            .read_image(reads.pages.normal)
8552            .read_image(reads.pages.mro)
8553            .read_image(reads.pages.emissive)
8554            .read_buffer(reads.probes);
8555        if let Some(vertices) = reads.skinned {
8556            rsm = rsm.read_buffer(vertices);
8557        }
8558        // Cascade 0's cluster-selection buffer, which the mesh path's stages
8559        // write — declared on the atlas pass's terms, and only for the one view
8560        // this pass draws.
8561        if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
8562            rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
8563        }
8564        rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
8565        // Split by side, on the colour pass's terms: this stage cuts the alpha
8566        // mask itself, so the only thing it cannot say inside the fragment stage
8567        // is which faces the rasteriser keeps.
8568        let rsm_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8569        let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
8570        rsm.execute(move |ctx| {
8571            let encoder = ctx.encoder();
8572            for partition in &rsm_partitions {
8573                partition.open(encoder);
8574                partition.record(encoder, cascade_group, &cascade_draws);
8575            }
8576        });
8577
8578        // --- the punctual reflective shadow map ---
8579        //
8580        // The irradiance probes' punctual producer: the same
8581        // pipeline and the same per-bucket call list as the pass above, under
8582        // one viewport per shadowed light face instead of one whole map. A spot
8583        // is a tile and a point light is six, which is `shadow::tile_span` — so
8584        // this is the atlas pass's own view loop drawn into a second, much
8585        // smaller set of targets.
8586        //
8587        // **Recorded whether or not the frame lights a punctual face**, unlike
8588        // the map above. The clear is a legitimate answer — a frame with no
8589        // shadowed punctual light has no punctual bounce, and the coverage flag
8590        // in `w` says so at every texel — and a pass that came and went with the
8591        // lights would be a pass list that changes shape with the scene, which
8592        // is what `RENDER_PASSES` and every timing reader are written against.
8593        let punctual_extent = rsm::punctual_extent();
8594        let punctual_targets = RsmTargets {
8595            albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
8596            normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
8597            world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
8598        };
8599        let punctual_depth =
8600            graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
8601        let mut punctual_pass = graph
8602            .add_render_pass("rsm-punctual")
8603            // Cleared on the map above's terms, and the world target's clear is
8604            // load-bearing for its reason as well as for one of this map's own:
8605            // the tiles the cascades would hold are drawn into by nothing at
8606            // all, and a coverage flag of zero is what keeps the gather out of
8607            // them.
8608            .clear_color(punctual_targets.albedo, [0.0; 4])
8609            .clear_color(punctual_targets.normal, [0.0; 4])
8610            .clear_color(punctual_targets.world, [0.0; 4])
8611            .clear_depth(punctual_depth)
8612            .read_image(placeholder)
8613            .read_image(reads.occlusion_placeholder)
8614            .read_image(reads.pages.base_color)
8615            .read_image(reads.pages.normal)
8616            .read_image(reads.pages.mro)
8617            .read_image(reads.pages.emissive)
8618            .read_buffer(reads.probes);
8619        if let Some(vertices) = reads.skinned {
8620            punctual_pass = punctual_pass.read_buffer(vertices);
8621        }
8622        // Each face's own cluster-selection buffer, which the mesh path's stages
8623        // write — declared on the atlas pass's terms, and only for the views
8624        // this pass draws.
8625        for face in &punctual {
8626            if let Some(&buffer) = selection.get(face.view) {
8627                punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8628            }
8629        }
8630        for draws in &punctual_sources {
8631            punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
8632        }
8633        let punctual_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8634        let punctual_recorded = punctual_views.len() as u64
8635            * punctual_partitions
8636                .iter()
8637                .map(BucketDraws::call_count)
8638                .sum::<u64>();
8639        punctual_pass.execute(move |ctx| {
8640            let encoder = ctx.encoder();
8641            // The partition is **outside** the view loop, on the shadow atlas's
8642            // terms: one pipeline bind covers every face of that side.
8643            for partition in &punctual_partitions {
8644                partition.open(encoder);
8645                for (group, tile, draws, region) in &punctual_views {
8646                    set_shadow_tile(encoder, *tile);
8647                    partition.record_region(encoder, *group, draws, *region);
8648                }
8649            }
8650        });
8651
8652        let images = RsmImages {
8653            sun,
8654            punctual: punctual_targets,
8655        };
8656        (
8657            atlas,
8658            recorded + rsm_recorded + punctual_recorded,
8659            clears,
8660            Some(images),
8661        )
8662    }
8663
8664    /// Which lights hold the atlas's light tiles this frame, and where each
8665    /// map was laid out.
8666    ///
8667    /// **The observable topic 45's priority rung otherwise has
8668    /// none for.** A map's *size* leaves no trace in the picture that a golden
8669    /// can hold anyone to: a light demoted to a quarter of a cell draws a
8670    /// slightly softer shadow, which is a perfectly plausible frame and one a
8671    /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
8672    /// off this is what says which level the allocator actually handed out, and
8673    /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
8674    ///
8675    /// Named for the selection's own subject rather than for its type, because
8676    /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
8677    /// descended to — and two accessors of one name is a caller reaching for
8678    /// the wrong one.
8679    ///
8680    /// It is this frame's answer, written by [`Self::begin_frame`]: before the
8681    /// first frame every slot is free.
8682    /// Whether this frame took the shadow atlas as an earlier frame left it,
8683    /// rather than drawing it again.
8684    ///
8685    /// Topic 45's static-caching rung, read back. True means
8686    /// this frame recorded **no** shadow cull and no shadow pass, and every map
8687    /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
8688    /// frame that did draw put there — so a caller comparing two frames' pass
8689    /// lists, draw counts or GPU timings has to know which of them redrew.
8690    ///
8691    /// Decided by [`Self::begin_frame`] out of everything each group of the
8692    /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
8693    /// and it answers `false` before the first frame, because no frame has been
8694    /// opened and so none of them has held anything.
8695    ///
8696    /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
8697    /// frame that redraws one map and holds another answers `false` here and
8698    /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
8699    /// together are what say which.
8700    #[must_use]
8701    pub const fn shadow_atlas_cached(&self) -> bool {
8702        self.shadow_atlas_cached
8703    }
8704
8705    /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
8706    /// the one an earlier frame put there.
8707    ///
8708    /// Topic 45's cadence rung, read back. **The observable
8709    /// that rung otherwise has none for**: a held map draws a shadow lagging its
8710    /// caster by a frame or two, which is a perfectly plausible picture and one
8711    /// a golden accepts — so nothing but this distinguishes a cadence that is
8712    /// working from one that is not running at all.
8713    ///
8714    /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
8715    /// frame, which is the same answer for the same reason: no map was drawn
8716    /// there.
8717    #[must_use]
8718    pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
8719        cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
8720    }
8721
8722    /// Whether this frame redrew the maps of light slot `slot` —
8723    /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
8724    /// earlier frame put there.
8725    ///
8726    /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
8727    /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
8728    /// once and draw one visible set, so they are redrawn or held as one.
8729    #[must_use]
8730    pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
8731        slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
8732    }
8733
8734    /// How many tiles of the atlas this frame redrew.
8735    ///
8736    /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
8737    /// say the budget bound rather than that it was configured. A cascade costs
8738    /// one and a point light's cube costs [`shadow::POINT_FACES`].
8739    #[must_use]
8740    pub const fn shadow_faces_redrawn(&self) -> u32 {
8741        self.shadow_faces_redrawn
8742    }
8743
8744    /// Pins the shadow cadence for this renderer, or hands it back to the
8745    /// console.
8746    ///
8747    /// [`Self::set_effect_request`]'s shape at this knob:
8748    /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
8749    /// process-global, so they are the *default* rather than the only answer —
8750    /// an application drawing two views at two qualities, or a test that needs a
8751    /// frame nothing else in the process can move, pins its own.
8752    ///
8753    /// [`None`] hands it back, which is what a renderer starts at.
8754    ///
8755    /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
8756    /// terms: this call decides it and `add_passes` acts on it.
8757    pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
8758        self.shadow_cadence_request = cadence;
8759    }
8760
8761    /// Whether this frame ignored the cadence for at least one map because the
8762    /// region that map covers had moved out from under it.
8763    ///
8764    /// Topic 45's "a moving light or camera cut resets it",
8765    /// made precise: a map is *reset* rather than merely out of date when the
8766    /// centre it is projected from has moved further than the map's own reach —
8767    /// a light further than its own radius, or a cascade's eye further than the
8768    /// sphere that cascade was fitted to. Holding such a map is not a shadow
8769    /// that lags; it is a shadow of somewhere else.
8770    ///
8771    /// A frame whose atlas was **relaid** — a light gained, lost or resized a
8772    /// tile, or shadows were switched on or off — answers `true` as well, and
8773    /// that frame redraws every map it has: the only clear this seam can make
8774    /// covers the whole image, so there is nothing left to hold.
8775    #[must_use]
8776    pub const fn shadow_cadence_reset(&self) -> bool {
8777        self.shadow_cadence_reset
8778    }
8779
8780    #[must_use]
8781    pub const fn shadow_lights(&self) -> &shadow::Selection {
8782        &self.shadow_lights
8783    }
8784
8785    /// The shadow atlas, for a caller that wants to read it back.
8786    ///
8787    /// **The observable this whole slice can otherwise hide behind.** A shadow
8788    /// pass that renders nothing leaves every texel at
8789    /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
8790    /// everything is lit — which is a perfectly plausible picture and matches
8791    /// any golden blessed from it. Copying this image back and finding a texel
8792    /// that is not the clear value is what distinguishes the two.
8793    ///
8794    /// It is created with
8795    /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
8796    /// exactly that, and its extent is [`shadow::atlas_extent`].
8797    #[must_use]
8798    pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
8799        self.shadow_atlas
8800    }
8801
8802    /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
8803    /// through, for a reader importing the atlas into a graph of its own.
8804    #[must_use]
8805    pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
8806        self.shadow_atlas_view
8807    }
8808
8809    /// The base-colour page every material row samples through
8810    /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
8811    /// as the image and the view [`crate::texture`] uploaded.
8812    ///
8813    /// **What a render-to-texture view copies into.** A second camera drawing
8814    /// into an image is only half of a monitor: the surface that *shows* it
8815    /// samples a page layer, and nothing above this crate can name the image
8816    /// that layer lives in.
8817    ///
8818    /// A caller that wants to *write* it wants
8819    /// [`base_color_page_import`](Self::base_color_page_import) instead: the
8820    /// graph can only order a copy against the draws that sample the page while
8821    /// both are declared, and the two declarations have to agree field for
8822    /// field. This one is the raw handles, for a caller that binds or reads them
8823    /// outside a graph.
8824    ///
8825    /// It is created with
8826    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
8827    /// because the upload that filled it is a copy, so a per-frame copy into it
8828    /// needs no new usage flag. Its extent is
8829    /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
8830    /// [`PageKind::BaseColor`] squared and it has one layer per
8831    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
8832    /// the description is the caller's, so the caller already knows both. A
8833    /// description naming no base-colour layer gets a 1×1 placeholder instead —
8834    /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
8835    #[must_use]
8836    pub const fn base_color_page(&self) -> UploadedTexture {
8837        self.base_color_page
8838    }
8839
8840    /// What [`add_passes`](Self::add_passes) names the base-colour page in the
8841    /// graph.
8842    ///
8843    /// [`RenderGraph::import_image`] keeps the label of whichever import ran
8844    /// first, so a caller importing the page too passes this rather than a
8845    /// string of its own — otherwise every barrier record and
8846    /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
8847    /// depending on which subsystem got there first.
8848    pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
8849
8850    /// The base-colour page **as this renderer declares it to a graph**.
8851    ///
8852    /// [`add_passes`](Self::add_passes) imports exactly this value under
8853    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
8854    /// of it on every pass whose bind group names the page, so a caller that
8855    /// writes the page — a render-to-texture view copied into one layer — gets
8856    /// the graph to order its write against those draws.
8857    ///
8858    /// **A caller that writes it imports this value rather than one of its
8859    /// own.** [`RenderGraph::import_image`] hands the second importer the id the
8860    /// first got, which is what puts the write and the reads on one state
8861    /// tracker, and it does that only while the two declarations agree in every
8862    /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
8863    /// [`compile`](RenderGraph::compile). Reading the declaration off the
8864    /// renderer that owns the page is what makes them one answer instead of two
8865    /// constants that have to be kept equal by hand.
8866    ///
8867    /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
8868    /// [`crate::texture`] leaves an uploaded page in that state, and the
8869    /// trailing barrier the `final_state` asks for puts it back there at the end
8870    /// of every frame — so the pool's ledger and this declaration are the same
8871    /// answer, which is what `Tracked` has the graph check.
8872    ///
8873    /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
8874    #[must_use]
8875    pub const fn base_color_page_import(&self) -> ImportedImage {
8876        ImportedImage {
8877            image: self.base_color_page.image,
8878            view: self.base_color_page.view,
8879            format: BASE_COLOR_PAGE_FORMAT,
8880            extent: self.page_extents[PageKind::BaseColor.index()],
8881            initial: ResourceState::ShaderRead,
8882            claim: InitialClaim::Tracked,
8883            final_state: ResourceState::ShaderRead,
8884        }
8885    }
8886
8887    /// Topic 43 §2's **normal** page, the raw handles.
8888    ///
8889    /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
8890    /// its terms: one `D2Array` image, one layer per
8891    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
8892    /// [`PageKind::Normal`], at **that kind's own extent**, and created with
8893    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
8894    /// per-frame copy into a layer needs no new usage flag. What it is *not* is
8895    /// the same format: it is `Rgba8Unorm`, where the base-colour page is
8896    /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
8897    /// is argued.
8898    #[must_use]
8899    pub const fn normal_page(&self) -> UploadedTexture {
8900        self.normal_page
8901    }
8902
8903    /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
8904    /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8905    pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
8906
8907    /// The normal page **as this renderer declares it to a graph**, on
8908    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
8909    /// — including that a caller writing a layer imports *this* value rather
8910    /// than one of its own, so the write and the draws land on one state
8911    /// tracker.
8912    #[must_use]
8913    pub const fn normal_page_import(&self) -> ImportedImage {
8914        ImportedImage {
8915            image: self.normal_page.image,
8916            view: self.normal_page.view,
8917            format: NORMAL_PAGE_FORMAT,
8918            extent: self.page_extents[PageKind::Normal.index()],
8919            initial: ResourceState::ShaderRead,
8920            claim: InitialClaim::Tracked,
8921            final_state: ResourceState::ShaderRead,
8922        }
8923    }
8924
8925    /// Topic 43 §2's packed
8926    /// **metallic-roughness-occlusion** page, the raw handles.
8927    ///
8928    /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
8929    /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
8930    /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
8931    /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
8932    #[must_use]
8933    pub const fn mro_page(&self) -> UploadedTexture {
8934        self.mro_page
8935    }
8936
8937    /// What [`add_passes`](Self::add_passes) names the
8938    /// metallic-roughness-occlusion page in the graph, on
8939    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8940    pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
8941
8942    /// The metallic-roughness-occlusion page **as this renderer declares it to a
8943    /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
8944    /// terms exactly.
8945    #[must_use]
8946    pub const fn mro_page_import(&self) -> ImportedImage {
8947        ImportedImage {
8948            image: self.mro_page.image,
8949            view: self.mro_page.view,
8950            format: MRO_PAGE_FORMAT,
8951            extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
8952            initial: ResourceState::ShaderRead,
8953            claim: InitialClaim::Tracked,
8954            final_state: ResourceState::ShaderRead,
8955        }
8956    }
8957
8958    /// Topic 43 §2's **emissive** page, the raw
8959    /// handles.
8960    ///
8961    /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
8962    /// format: an emissive texel is a colour, so this image is
8963    /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
8964    /// `EMISSIVE_PAGE_FORMAT`.
8965    #[must_use]
8966    pub const fn emissive_page(&self) -> UploadedTexture {
8967        self.emissive_page
8968    }
8969
8970    /// What [`add_passes`](Self::add_passes) names the emissive page in the
8971    /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8972    pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
8973
8974    /// The emissive page **as this renderer declares it to a graph**, on
8975    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
8976    #[must_use]
8977    pub const fn emissive_page_import(&self) -> ImportedImage {
8978        ImportedImage {
8979            image: self.emissive_page.image,
8980            view: self.emissive_page.view,
8981            format: EMISSIVE_PAGE_FORMAT,
8982            extent: self.page_extents[PageKind::Emissive.index()],
8983            initial: ResourceState::ShaderRead,
8984            claim: InitialClaim::Tracked,
8985            final_state: ResourceState::ShaderRead,
8986        }
8987    }
8988
8989    /// The model matrix for a cube spinning at `seconds` into the run.
8990    ///
8991    /// Two axes at incommensurable rates, so the animation never repeats and
8992    /// every face comes into view — which is what makes "the cube is spinning"
8993    /// observable rather than a claim about a matrix.
8994    #[must_use]
8995    pub fn spin(seconds: f32) -> Mat4 {
8996        Mat4::from_quat(
8997            Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
8998                * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
8999        )
9000    }
9001
9002    /// The format the tonemap pass renders into.
9003    #[must_use]
9004    pub const fn target_format(&self) -> Format {
9005        self.target_format
9006    }
9007
9008    /// Switches the infinite ground grid on with `style`, or off with [`None`].
9009    ///
9010    /// **Off by default.** Every sample and every golden image predates the
9011    /// grid, so a renderer nobody has called this on records exactly the passes
9012    /// it always did — see [`crate::grid`] for what the pass is and
9013    /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9014    ///
9015    /// The first `Some` builds the pipeline and the uniform ring; later calls
9016    /// only replace the style, and a `None` leaves both built. Releasing them
9017    /// here would mean releasing blocks the frames in flight may still be
9018    /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9019    /// one call that already requires an idle device.
9020    ///
9021    /// # Errors
9022    ///
9023    /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9024    /// Nothing is left switched on when that happens: the grid stays as it was.
9025    pub fn set_ground_grid(
9026        &mut self,
9027        device: &dyn Device,
9028        style: Option<GridStyle>,
9029    ) -> Result<(), HalError> {
9030        let Some(style) = style else {
9031            self.ground_grid_on = false;
9032            return Ok(());
9033        };
9034        let grid = match self.ground_grid.as_mut() {
9035            Some(grid) => grid,
9036            None => {
9037                // Built for the tonemap's target and the scene depth, because
9038                // those are the two attachments the pass is given — see
9039                // `add_passes`. Both are pipeline state, so a renderer whose
9040                // target format changed would need a new `Grid`; nothing in this
9041                // crate changes it after `build`, and `target_format` is kept
9042                // for exactly that reason.
9043                let grid = GroundGrid::new(
9044                    device,
9045                    self.primary.uniforms.len(),
9046                    self.target_format,
9047                    SCENE_DEPTH_FORMAT,
9048                )?;
9049                self.ground_grid.insert(grid)
9050            }
9051        };
9052        grid.set_style(style);
9053        self.ground_grid_on = true;
9054        Ok(())
9055    }
9056
9057    /// The debug draw layer's immediate-mode buffer, to append to.
9058    ///
9059    /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9060    /// spheres and frusta during the frame, and
9061    /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9062    /// a segment lives exactly the frame it was appended in and nothing has to
9063    /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9064    /// for the console switch that has to be on before anything is drawn.
9065    ///
9066    /// **Appending is free while the layer is off**, but building the geometry
9067    /// is the caller's: a system whose overlay costs something to compute asks
9068    /// [`DebugDraw::enabled`] first.
9069    pub fn debug_draw(&mut self) -> &mut DebugDraw {
9070        &mut self.debug_draw
9071    }
9072
9073    /// How the ground grid is drawn, or [`None`] where it is switched off.
9074    ///
9075    /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9076    /// observable a test asking "is the grid on" wants: a renderer that built
9077    /// the grid and then switched it off answers [`None`], because what it draws
9078    /// is what the question is about.
9079    #[must_use]
9080    pub fn ground_grid(&self) -> Option<&GridStyle> {
9081        self.ground_grid
9082            .as_ref()
9083            .filter(|_| self.ground_grid_on)
9084            .map(GroundGrid::style)
9085    }
9086
9087    /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9088    ///
9089    /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9090    /// [`set_sky`](Self::set_sky) or
9091    /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9092    /// here rather than left to the shader for the reason [`crate::sky_pass`]
9093    /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9094    /// frames, where adding no pass leaves them exactly as they were.
9095    fn draws_sky(&self) -> bool {
9096        self.sky != Sky::NONE || self.atmosphere.is_some()
9097    }
9098
9099    /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9100    /// per frame.
9101    ///
9102    /// Called once per [`Self::begin_frame`]. The comparison is on the
9103    /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9104    /// over, so re-setting the same sun spelled a different length is not a
9105    /// rebuild — and a caller that sets the same value every frame, which is
9106    /// the ordinary shape of a scene's update, pays the comparison and nothing
9107    /// else.
9108    ///
9109    /// # The first LUT is marched whole; every later one is marched in stripes
9110    ///
9111    /// A renderer that has no LUT has no sky to draw, so the first march after
9112    /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9113    /// call and a caller that draws a single frame gets that frame's sky. After
9114    /// that there is always a finished LUT to show, so a sun that moved starts
9115    /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9116    /// frame — the frames in between keep drawing the LUT the last completed
9117    /// march produced, and no frame pays the whole march.
9118    ///
9119    /// # A sun that moves again restarts the march rather than finishing it
9120    ///
9121    /// The build in flight is kept only while its own sun is still the one the
9122    /// caller wants; a sun that moved during it is a new build from row zero,
9123    /// because finishing the old one would swap in a LUT for a sun that is
9124    /// already wrong and then immediately start marching again. **A sun that
9125    /// moves every frame therefore never completes a build and goes on showing
9126    /// the last one it finished** — a sky frozen at the sun it last caught up
9127    /// with, rather than a sky that stutters at whatever the march last passed.
9128    /// That is the trade this makes: the frame cost is bounded and the sky
9129    /// lags, where the whole-march rebuild it replaced had the sky exact and
9130    /// the frame cost unbounded. A caller that wants the sky exact stops the
9131    /// sun on a value and leaves it there: the march then completes, and the
9132    /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9133    ///
9134    /// **The aerial-perspective LUT is marched in the same steps** — see
9135    /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9136    /// frame as the sky and lags the sun by the same frames, never a sun apart
9137    /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9138    /// on the same terms, since it is part of the parameters compared.
9139    fn refresh_sky_view(&mut self) {
9140        let Some(atmosphere) = self.atmosphere else {
9141            self.sky_view = None;
9142            self.sky_view_build = None;
9143            return;
9144        };
9145        let parameters = atmosphere.parameters();
9146        if self
9147            .sky_view
9148            .as_ref()
9149            .is_some_and(|presented| presented.parameters == parameters)
9150        {
9151            self.sky_view_build = None;
9152            return;
9153        }
9154        if self.sky_view.is_none() {
9155            self.sky_view_build = None;
9156            self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(&parameters)));
9157            return;
9158        }
9159        let mut build = match self.sky_view_build.take() {
9160            Some(build) if build.atmosphere() == parameters => build,
9161            _ => SkyViewBuild::start(&parameters),
9162        };
9163        if build.step(SKY_VIEW_BUILD_ROWS) {
9164            self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9165        } else {
9166            self.sky_view_build = Some(build);
9167        }
9168    }
9169
9170    /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9171    /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9172    ///
9173    /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9174    /// the value `tonemap.slang` held as a compile-time constant until this
9175    /// became a runtime one — so a renderer nobody calls this on draws the frame
9176    /// it always drew, and every golden image is untouched.
9177    ///
9178    /// It takes effect on the next
9179    /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9180    /// frame already recorded reads the value it was recorded with.
9181    ///
9182    /// **The clamp is here rather than at the call site** so that no caller can
9183    /// reach a picture it cannot get back from, and so that a control which
9184    /// steps by reading this back and setting a multiple of it — which is what
9185    /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9186    /// then need as many presses to come back.
9187    pub const fn set_exposure(&mut self, exposure: f32) {
9188        // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9189        // and a NaN reaching the block is a frame of NaN pixels with no key to
9190        // press to get out of it. `f32::max` returns the bound instead, so a NaN
9191        // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9192        self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9193    }
9194
9195    /// How far auto-exposure may travel toward its measurement in one frame.
9196    ///
9197    /// **[`None`] is the whole distance**, which is what a renderer nobody
9198    /// calls this on does and what the pass did before adaptation existed — so
9199    /// no golden moved when this arrived. A view that wants the roll asks, and
9200    /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9201    /// own delta: this crate has no clock, and the frame time lives where the
9202    /// frame loop is.
9203    ///
9204    /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9205    /// what writes the block, and it does nothing at all on a frame that did not
9206    /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9207    /// the ones that bit adds.
9208    pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9209        self.exposure_adaptation = adaptation;
9210    }
9211
9212    /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9213    /// handed.
9214    #[must_use]
9215    pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9216        self.exposure_adaptation
9217    }
9218
9219    /// Which operator the tonemap pass runs on the exposed scene colour.
9220    ///
9221    /// **The ACES fit by default**, because this renderer shades in linear HDR
9222    /// and the roll-off is what that range is for. What a caller asks *for* here
9223    /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9224    /// identity on `0..=1`, so display-referred content reaches the swapchain
9225    /// exactly, and a fixture that predicts a code value from a host model of
9226    /// the shading needs the frame to stay scene-referred. Every 2D sample in
9227    /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9228    /// instead, so none of them reaches this pass at all.
9229    ///
9230    /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9231    /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9232    /// there, and a frame already recorded reads the value it was recorded
9233    /// with.
9234    ///
9235    /// **There is nothing to refuse and no `supports_` probe beside it.** The
9236    /// selector is a lane of a uniform block read by a branch every device
9237    /// already runs, so unlike the wireframe there is no second pipeline for a
9238    /// device to decline to build.
9239    pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9240        self.tonemap_curve = curve;
9241    }
9242
9243    /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9244    /// value the next frame will be drawn with.
9245    #[must_use]
9246    pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9247        self.tonemap_curve
9248    }
9249
9250    /// How large the internal render target is as a fraction of the extent
9251    /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9252    /// `MIN_RENDER_SCALE..=1.0`.
9253    ///
9254    /// **This is the largest performance knob this renderer has.** Every pass
9255    /// before the upscale costs what its extent costs, so a scale of `0.7` is
9256    /// roughly half the shading work of `1.0`; the UI is composited onto the
9257    /// target afterwards at native resolution, so text stays sharp while the 3D
9258    /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9259    /// 48-post-processing plan left behind_) is where that trade is written down.
9260    ///
9261    /// **`1.0` is not a special case with a fast path, it is the absence of the
9262    /// feature.** At full scale the internal extent *is* the caller's, the post
9263    /// chain writes the target directly, and no upscale pass is recorded — which
9264    /// is what makes a renderer nobody has called this on draw the frame it drew
9265    /// before the knob existed, bit for bit.
9266    ///
9267    /// **Above `1.0` is clamped away rather than supported.** Supersampling
9268    /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9269    /// *reconstruction*; running it as a minification filter would alias, which
9270    /// is the opposite of what a caller asking for it wants. A non-finite scale
9271    /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9272    /// the failure it produces is a zero-sized target somewhere downstream.
9273    ///
9274    /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9275    /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9276    /// recorded is drawn at the scale it was recorded with.
9277    pub fn set_render_scale(&mut self, scale: f32) {
9278        self.render_scale = if scale.is_finite() {
9279            scale.clamp(MIN_RENDER_SCALE, 1.0)
9280        } else {
9281            1.0
9282        };
9283    }
9284
9285    /// The render scale in force, after the clamp
9286    /// [`set_render_scale`](Self::set_render_scale) applied.
9287    ///
9288    /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9289    #[must_use]
9290    pub const fn render_scale(&self) -> f32 {
9291        self.render_scale
9292    }
9293
9294    /// The anisotropy the base-colour page is sampled with, in force from the
9295    /// next [`begin_frame`](Self::begin_frame).
9296    ///
9297    /// Topic 43's filtering rung, the player's half:
9298    /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9299    /// called this on samples with, and this is what a settings row moves it
9300    /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9301    /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9302    /// was not — the row can turn the filter off or push it to the device's
9303    /// ceiling, and nothing it asks reaches a `create_sampler` that would
9304    /// refuse it. A value that is not a number is the default, on
9305    /// [`set_render_scale`](Self::set_render_scale)'s terms.
9306    ///
9307    /// **A sampler is a resource a bind group holds by handle**, so a new
9308    /// anisotropy is a new sampler, and every group of the mesh layout has to
9309    /// be rebuilt to name it. That happens per frame slot, at the slot's own
9310    /// `begin_frame`, which is the moment the ring guarantees the slot's
9311    /// previous submission has retired — the guarantee every host write in
9312    /// that call already leans on — so a frame in flight goes on naming the
9313    /// sampler it was recorded with, and the replaced sampler is destroyed once
9314    /// no slot names it. This call creates the sampler and nothing else, and
9315    /// asking for the anisotropy already in force creates nothing.
9316    ///
9317    /// # Errors
9318    ///
9319    /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9320    /// stays in force.
9321    pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9322        let caps = device.caps();
9323        let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9324            caps.limits.max_sampler_anisotropy
9325        } else {
9326            1.0
9327        };
9328        let wanted = if anisotropy.is_finite() {
9329            anisotropy.clamp(1.0, ceiling)
9330        } else {
9331            Self::anisotropy_for(&caps)
9332        };
9333        // Bit-equal rather than within an epsilon: both sides came out of the
9334        // same clamp, and a row that lands on the value in force must not
9335        // rebuild every group for it.
9336        if wanted.to_bits() == self.anisotropy.to_bits() {
9337            return Ok(());
9338        }
9339        let sampler = Self::create_page_sampler(device, wanted)?;
9340        self.retired_pages
9341            .push(RetiredPage::Sampler(std::mem::replace(
9342                &mut self.base_color_sampler,
9343                sampler,
9344            )));
9345        self.anisotropy = wanted;
9346        Ok(())
9347    }
9348
9349    /// The anisotropy in force, after the clamp
9350    /// [`set_anisotropy`](Self::set_anisotropy) applied.
9351    ///
9352    /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9353    #[must_use]
9354    pub const fn anisotropy(&self) -> f32 {
9355        self.anisotropy
9356    }
9357
9358    /// The anisotropy the base-colour page's sampler is created with on a
9359    /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9360    /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9361    /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9362    /// not.
9363    ///
9364    /// **Granted, not supported.** The feature is optional at every open site
9365    /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9366    /// without asking refuses a sampler above one even on hardware that has
9367    /// it, which is the shape every backend's `create_sampler` documents. So
9368    /// the question is what this device was opened *with*, and a caller that
9369    /// wants the plan's default has to name the feature beside the others it
9370    /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9371    /// one, so a browser samples isotropically until `docs/backlog.md`'s
9372    /// ceiling decision is taken.
9373    #[must_use]
9374    pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9375        if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9376            DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9377        } else {
9378            1.0
9379        }
9380    }
9381
9382    /// The base-colour page's sampler at `anisotropy`, which the caller has
9383    /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9384    /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9385    ///
9386    /// **Trilinear over the whole chain, anisotropic where the device is** —
9387    /// topic 43's filtering rung: a minified surface
9388    /// reads the level its footprint matches instead of shimmering through
9389    /// level 0, a magnified one blends four texels instead of stepping between
9390    /// them, and a surface at a grazing angle keeps its detail along the long
9391    /// axis of its footprint rather than blurring to the short one. A second
9392    /// sampler object rather than sharing the tonemap's, so a capture names
9393    /// each for what it filters.
9394    ///
9395    /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9396    /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9397    /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9398    /// wrapping address mode makes the page tile across it rather than
9399    /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9400    /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9401    /// clamped read return the same nearest texel for it.
9402    fn create_page_sampler(
9403        device: &dyn Device,
9404        anisotropy: f32,
9405    ) -> Result<SamplerHandle, HalError> {
9406        device.create_sampler(&SamplerDesc {
9407            label: Some("material base colour"),
9408            mag_filter: FilterMode::Linear,
9409            min_filter: FilterMode::Linear,
9410            mip_filter: FilterMode::Linear,
9411            address_mode: [SamplerAddressMode::Repeat; 3],
9412            anisotropy,
9413            ..SamplerDesc::default()
9414        })
9415    }
9416
9417    /// The extent a frame handed `target` is actually drawn at.
9418    ///
9419    /// Rounds rather than truncates, and floors at one texel in each dimension:
9420    /// a zero here would reach a transient image description, and an image of
9421    /// zero extent is a device error rather than a small frame. A caller who
9422    /// minimised the window already hands a zero extent through, and that path
9423    /// is unchanged — `max(1)` on a zero is one either way.
9424    fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9425        if self.render_scale >= 1.0 {
9426            return target;
9427        }
9428        let scale = f64::from(self.render_scale);
9429        (
9430            ((f64::from(target.0) * scale).round() as u32).max(1),
9431            ((f64::from(target.1) * scale).round() as u32).max(1),
9432        )
9433    }
9434
9435    /// The exposure in force, after the clamp
9436    /// [`set_exposure`](Self::set_exposure) applied.
9437    ///
9438    /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9439    /// caller wants is the number the frame is drawn with, not the one it asked
9440    /// for — which is also what makes a multiplicative step land on the end of
9441    /// the range rather than run past it.
9442    #[must_use]
9443    pub const fn exposure(&self) -> f32 {
9444        self.exposure
9445    }
9446
9447    /// Whether `device` can draw the wireframe view at all.
9448    ///
9449    /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9450    /// error, asked **before** anything is switched on — so an application can
9451    /// tell its user that this device has no wireframe rather than binding a key
9452    /// that fails, and can say so once at start-up instead of on every press.
9453    /// WebGPU has no line fill mode at all, so the browser is the case this
9454    /// exists for and not a hypothetical.
9455    ///
9456    /// An associated function rather than a method: it is a fact about the
9457    /// device, and a caller wants it before it has decided anything.
9458    #[must_use]
9459    pub fn supports_wireframe(device: &dyn Device) -> bool {
9460        device.caps().supports(Features::POLYGON_MODE_LINE)
9461    }
9462
9463    /// Asks every camera's cull to drop what is hidden or too small to see —
9464    /// topic 03 §3.3's occlusion cull and its
9465    /// small-feature test. See [`crate::occlusion_cull`].
9466    ///
9467    /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9468    /// guesses from the previous frame's depth, the second tests every rejected
9469    /// instance against this frame's, and only the second's rejections are
9470    /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9471    /// and is off unless a threshold is named.
9472    ///
9473    /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9474    /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9475    /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9476    /// alone, because a wireframe shows the edges a depth test would hide.
9477    pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9478        self.occlusion_culling = culling;
9479    }
9480
9481    /// Whether a point light's shadow cull tags each caster with the faces of
9482    /// its cube it reaches, so each face draws only those — **on** by default.
9483    ///
9484    /// Off is the cull this replaced: one test against the light's box, and
9485    /// every caster in it drawn into all six faces for the rasteriser to clip.
9486    /// The two write the same atlas, texel for texel — the six faces' pyramids
9487    /// tile the box, so a caster a face drops has no texel in that face's tile —
9488    /// and the switch exists so a test can hold them against each other and a
9489    /// price can be read off both.
9490    pub fn set_point_face_culls(&mut self, on: bool) {
9491        self.point_face_culls = on;
9492    }
9493
9494    /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
9495    /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
9496    /// on its way to the GPU, or stops doing so with [`None`] — the default,
9497    /// and the only value a frame outside a test runs under.
9498    ///
9499    /// Applied **after** the atlas cache has read the blocks, so the rewrite is
9500    /// invisible to the decision whether to redraw a map and visible only to the
9501    /// depth pass that draws it. That is what makes it a probe of the shaders:
9502    /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
9503    /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
9504    /// perturbed through here and holds the depth to the untampered frame's, bit
9505    /// for bit. It reaches the atlas's views alone — not the probe updater's
9506    /// shadows-off writes, which draw nothing into the atlas.
9507    pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
9508        self.shadow_view_tamper = tamper;
9509    }
9510
9511    /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
9512    /// for, before the console switches and the wireframe are applied.
9513    #[must_use]
9514    pub const fn occlusion_culling(&self) -> OcclusionCulling {
9515        self.occlusion_culling
9516    }
9517
9518    /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
9519    /// with the console switches applied, and nothing on a wireframe frame.
9520    #[must_use]
9521    pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
9522        if self.wireframe_on {
9523            return OcclusionCulling::OFF;
9524        }
9525        let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
9526        OcclusionCulling {
9527            occlusion: self.occlusion_culling.occlusion
9528                || crate::occlusion_cull::r_occlusion_cull.get_bool(),
9529            small_feature_pixels: self
9530                .occlusion_culling
9531                .small_feature_pixels
9532                .or((console_pixels > 0.0).then_some(console_pixels)),
9533        }
9534    }
9535
9536    /// Draws the scene's triangles as lines, or goes back to filling them.
9537    ///
9538    /// **Off by default.** Every sample and every golden image predates the
9539    /// view, so a renderer nobody has called this on records exactly the frame
9540    /// it always did.
9541    ///
9542    /// # What it is, and what it is not
9543    ///
9544    /// The **colour pass** alone changes fill mode. The depth prepass and the
9545    /// shadow cascades keep drawing filled triangles, because they are what the
9546    /// occlusion pair and the shadow lookups read and depth drawn as lines is
9547    /// depth with holes in it. So a wireframe frame is the same geometry, the
9548    /// same shading and the same lights, rasterised as edges: what was inside a
9549    /// triangle becomes the clear colour, and what was on its edge stays lit.
9550    ///
9551    /// # It is built on the first `true`
9552    ///
9553    /// The pipeline is compiled here rather than beside the filled one at
9554    /// [`with_scene`](Self::with_scene), and that is the trade this
9555    /// call makes: one pipeline compile on the first press — a hitch, in a view
9556    /// the user just asked for — against a second compile in the start-up of
9557    /// every sample, golden run and headless test that never asks for one. Later
9558    /// calls only flip the switch, and a `false` leaves the pipeline built, for
9559    /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
9560    /// the frames in flight may still be recording against is what
9561    /// [`destroy`](Self::destroy) — which already requires an idle device — is
9562    /// for.
9563    ///
9564    /// # Errors
9565    ///
9566    /// [`HalError::UnsupportedFeatures`] naming
9567    /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
9568    /// when `on` is `true` on a device that has not got it — ask
9569    /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
9570    /// than quietly filled: a caller who asked for a wireframe and got a solid
9571    /// frame back with no error has no way to tell that from a wireframe of a
9572    /// solid-looking model.
9573    ///
9574    /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
9575    /// when either happens**: the view stays as it was.
9576    pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
9577        if !on {
9578            self.wireframe_on = false;
9579            return Ok(());
9580        }
9581        if self.wireframe_pipeline.is_none() {
9582            if !Self::supports_wireframe(device) {
9583                return Err(HalError::UnsupportedFeatures {
9584                    missing: Features::POLYGON_MODE_LINE,
9585                });
9586            }
9587            let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
9588            let [single, double] = MeshModules::sided(|cull| {
9589                modules.color_pipeline(
9590                    device,
9591                    self.mesh_pipeline_layout,
9592                    PolygonMode::Line,
9593                    cull,
9594                    "wireframe",
9595                )
9596            });
9597            modules.destroy(device);
9598            // **Both or neither.** A caller that got one twin back would draw a
9599            // frame missing every double-sided surface and nothing would say
9600            // so; released here rather than kept, because `destroy` is what
9601            // releases what this field holds and it holds nothing yet.
9602            let pipelines = match (single, double) {
9603                (Ok(single), Ok(double)) => SidedPipelines { single, double },
9604                (Ok(built), Err(error)) | (Err(error), Ok(built)) => {
9605                    device.destroy_graphics_pipeline(built);
9606                    return Err(error);
9607                }
9608                (Err(error), Err(_)) => return Err(error),
9609            };
9610            self.wireframe_pipeline = Some(pipelines);
9611        }
9612        self.wireframe_on = true;
9613        Ok(())
9614    }
9615
9616    /// Whether the colour pass draws lines instead of filled triangles.
9617    ///
9618    /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
9619    /// observable a test asking "is this frame a wireframe" wants: a renderer
9620    /// that built the pipeline and then switched it off answers `false`, because
9621    /// what it draws is what the question is about.
9622    #[must_use]
9623    pub const fn wireframe(&self) -> bool {
9624        self.wireframe_on
9625    }
9626
9627    /// Draws each surface's **world-space** normal instead of shading it, so a
9628    /// modeller can see whether the normals a document carries are sane.
9629    ///
9630    /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
9631    /// is a tool's view of a document, and every sample and every golden image
9632    /// predates it. It takes effect on the next
9633    /// [`begin_frame`](Self::begin_frame), which is what writes the block.
9634    ///
9635    /// # What the colours mean
9636    ///
9637    /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
9638    /// green, +Z blue, and a face whose winding was inverted reads the
9639    /// **complement** of the colour it should have. A missing or degenerate
9640    /// normal reads as whatever the vertex data actually holds rather than as the
9641    /// plausible shading a light would have given it, which is the point.
9642    ///
9643    /// # World space, not view space
9644    ///
9645    /// The two diagnose different things and this one is world space, so a face
9646    /// keeps its colour while the camera orbits: "is this face inverted" is then
9647    /// something a modeller *sees*, instead of inferring it from a picture that
9648    /// re-colours whenever they move. View-space normals answer the other
9649    /// question — is this normal smooth, is this seam split — by re-colouring on
9650    /// purpose, and they are not a thing this block could express anyway: it
9651    /// carries `view_proj` and no separate view matrix, so there is no rotation in
9652    /// the shader to take a normal into eye space with.
9653    ///
9654    /// # It builds nothing and adds no pass
9655    ///
9656    /// Unlike the wireframe, which needs a second pipeline and so a device that
9657    /// can build one: this is one lane of the frame's uniform block — see
9658    /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
9659    /// stage every device already runs. There is nothing to refuse and nothing to
9660    /// release, which is why it cannot fail and there is no `supports_` probe
9661    /// beside it.
9662    ///
9663    /// The tonemap still applies: at
9664    /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
9665    /// is the identity on `0..=1` and the encoded normal reaches the swapchain
9666    /// exactly, and at any other exposure the picture is scaled per channel — so
9667    /// which channel dominates a face never changes, but a caller reading exact
9668    /// values wants [`set_exposure`](Self::set_exposure) left alone.
9669    ///
9670    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
9671    pub const fn set_normals_view(&mut self, on: bool) {
9672        self.normals_view = on;
9673    }
9674
9675    /// Sets the exponential height fog the colour pass composites over every
9676    /// shaded surface.
9677    ///
9678    /// Topic 43 §4's cheapest large win: distance
9679    /// reads as distance, a valley fills while a hilltop stays clear, and it
9680    /// costs four numbers in a block every pipeline already binds.
9681    ///
9682    /// # It adds no pass and cannot fail
9683    ///
9684    /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
9685    /// rows of the frame's uniform block, read by arithmetic in the fragment
9686    /// stage every device already runs. There is nothing to build, so there is
9687    /// nothing to refuse and no `supports_` probe beside it.
9688    ///
9689    /// # Off is exactly off
9690    ///
9691    /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
9692    /// not an approximate one: the optical depth is zero, its transmittance is
9693    /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
9694    /// rather than as a `lerp`, which at `t == 1` would return
9695    /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
9696    /// the fog colour. So this feature moves no frame it is not switched on
9697    /// for.
9698    ///
9699    /// # What it does not fog
9700    ///
9701    /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
9702    /// which arrive unfogged onto an already-fogged surface — see
9703    /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
9704    /// the reflection composite is one pass later.
9705    pub const fn set_fog(&mut self, fog: Fog) {
9706        self.fog = fog;
9707    }
9708
9709    /// Lights the scene with a gradient sky, on top of whatever ambient and
9710    /// irradiance grid it already has.
9711    ///
9712    /// Topic 43 §8's rung. [`Sky`] is three
9713    /// radiances — zenith, horizon, ground — and what reaches a surface is that
9714    /// gradient projected onto the L1 basis the probe grid already uses, so a
9715    /// surface facing up receives the sky and one facing down the ground's
9716    /// bounce. Three colours, no extra pass.
9717    ///
9718    /// # It adds no pass and cannot fail
9719    ///
9720    /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
9721    /// frame's uniform block and three dot products in a fragment stage every
9722    /// device already runs. Nothing to build, so nothing to refuse and no
9723    /// `supports_` probe beside it.
9724    ///
9725    /// # Off is exactly off
9726    ///
9727    /// [`Sky::NONE`] is the default and a black gradient projects to every
9728    /// coefficient zero — each is a product with a zero factor — so the
9729    /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
9730    /// before this existed, bit for bit.
9731    ///
9732    /// # What it does not do
9733    ///
9734    /// **Draw anything.** The background is still the scene target's clear
9735    /// colour, and a scene lit by a sky it cannot see is what this rung leaves
9736    /// behind until the pass that draws the gradient lands. The environment
9737    /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
9738    /// a mirror under a sky still reflects whatever the probes hold.
9739    pub const fn set_sky(&mut self, sky: Sky) {
9740        self.sky = sky;
9741    }
9742
9743    /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
9744    /// gradient back.
9745    ///
9746    /// Topic 43 §8. A frame with an atmosphere takes
9747    /// it for all three of the things a sky is: the background the sky pass
9748    /// draws, the L1 ambient term `mesh.slang` adds, and the environment
9749    /// `ssr.slang` falls back to when a ray hits nothing. The
9750    /// [`Sky`] a caller may also have set is not read on those frames.
9751    ///
9752    /// # What it costs
9753    ///
9754    /// **A march on the host, not on the device.** The first
9755    /// [`begin_frame`](Self::begin_frame) after this is called marches
9756    /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
9757    /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
9758    /// paid where it is asked for. Every later move of the sun is marched
9759    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
9760    /// drawn, so no frame after the first pays the whole march;
9761    /// `refresh_sky_view` is where that is written down, including what a sun
9762    /// that moves *every* frame gets. A frame whose
9763    /// sun has not moved costs the comparison that finds nothing to do and
9764    /// nothing else: the LUT's two projections are cached beside it. The device
9765    /// pays four buffer loads and a blend, which is what the gradient pays.
9766    ///
9767    /// # Off is exactly off
9768    ///
9769    /// `None` is the default, and a renderer nobody calls this on writes the
9770    /// same block, adds the same passes and draws the same frame it did before
9771    /// this existed — `sky.slang`'s arm is
9772    /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
9773    ///
9774    /// # What it does not do
9775    ///
9776    /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
9777    /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
9778    /// pass already shades with, and pointing the two the same way is the
9779    /// caller's job.
9780    ///
9781    /// **Put the air in front of a surface.** That is the paper's third LUT and
9782    /// this engine's froxel column, and neither reads this.
9783    pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
9784        self.atmosphere = atmosphere;
9785    }
9786
9787    /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
9788    /// and this crate's `water` module for how.
9789    ///
9790    /// Replaces whatever was set before. Each body is meshed here, by
9791    /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
9792    /// slot as that slot next begins, so the call touches no device and a frame
9793    /// still in flight keeps the buffers it was submitted with.
9794    ///
9795    /// # Off is exactly off
9796    ///
9797    /// An empty slice is the default, and a renderer with no bodies records no
9798    /// water pass at all: the frame it draws is the one it drew before this
9799    /// existed, bit for bit. Water is content, not a
9800    /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
9801    ///
9802    /// # Errors
9803    ///
9804    /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
9805    /// too few points, a non-finite coordinate, an outline that crosses itself,
9806    /// a negative coefficient — and then **nothing is replaced**: the bodies set
9807    /// before this call go on drawing.
9808    pub fn set_water(
9809        &mut self,
9810        bodies: &[crcbl_water::WaterBody],
9811    ) -> Result<(), crcbl_water::BodyError> {
9812        self.water.set(bodies)
9813    }
9814
9815    /// The bodies of water this renderer draws, as they were last set.
9816    #[must_use]
9817    pub fn water(&self) -> &[crcbl_water::WaterBody] {
9818        self.water.bodies()
9819    }
9820
9821    /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
9822    /// and G3, and this crate's `grass` module for how.
9823    ///
9824    /// Replaces whatever was set before. The field's ground, cover map, blade
9825    /// table and per-tile blocks are uploaded here, and the buffers a dispatch
9826    /// writes are created here; a field replaced while a frame is in flight
9827    /// leaves its resources alive until the ring has come round, so the call is
9828    /// safe at any point between frames.
9829    ///
9830    /// # Off is exactly off
9831    ///
9832    /// [`None`] is the default, and a renderer with no field records no grass
9833    /// pass at all: the frame it draws is the one it drew before this existed,
9834    /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
9835    /// [`set_water`](Self::set_water)'s terms.
9836    ///
9837    /// # Errors
9838    ///
9839    /// [`crate::grass::SetError::Field`] for a description the field itself
9840    /// refuses — no tiles, a zero texel scale, an empty blade table — and then
9841    /// **nothing is replaced**: the field set before this call goes on drawing.
9842    /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
9843    /// terms.
9844    pub fn set_grass(
9845        &mut self,
9846        device: &dyn Device,
9847        queue: QueueHandle,
9848        field: Option<&crate::grass::GrassField>,
9849    ) -> Result<(), crate::grass::SetError> {
9850        self.grass.set(device, queue, field)
9851    }
9852
9853    /// The field of grass this renderer draws, as it was last set.
9854    #[must_use]
9855    pub fn grass(&self) -> Option<&crate::grass::GrassField> {
9856        self.grass.field()
9857    }
9858
9859    /// The two buffers the grass generation pass writes, or [`None`] for a
9860    /// renderer with no field.
9861    ///
9862    /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
9863    /// blade and to read each slot's instance count, on
9864    /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
9865    /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
9866    /// last frame that generated left there, which for a field nobody has drawn
9867    /// yet is undefined rather than empty.
9868    #[must_use]
9869    pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
9870        self.grass.buffers()
9871    }
9872
9873    /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
9874    /// as the GPU copy of the field samples them.
9875    ///
9876    /// [`None`] restores the calm placeholder: one texel of no deflection and
9877    /// one of zero intensity, which is what makes a field with no weather set
9878    /// stand still. A replaced pair waits for the ring exactly as a replaced
9879    /// field does.
9880    ///
9881    /// # Errors
9882    ///
9883    /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
9884    /// texel of the grid it came with, or a seam call that failed.
9885    pub fn set_wind_layers(
9886        &mut self,
9887        device: &dyn Device,
9888        queue: QueueHandle,
9889        layers: Option<&crate::grass::WindLayers>,
9890    ) -> Result<(), crate::grass::WindLayerError> {
9891        self.grass.set_wind_layers(device, queue, layers)
9892    }
9893
9894    /// The wind's uniform block for the frames from here on —
9895    /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
9896    /// `f64` formula is narrowed to `f32`.
9897    ///
9898    /// Everything in it is camera-relative or already wrapped, so a caller
9899    /// writes it once per frame from the field's own state and never from a
9900    /// world-scale coordinate. The default is a base speed of zero, which is
9901    /// calm.
9902    pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
9903        self.wind = params;
9904    }
9905
9906    /// The wind block this renderer writes, as it was last set.
9907    #[must_use]
9908    pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
9909        self.wind
9910    }
9911
9912    /// The atmosphere this renderer draws, if it has one.
9913    #[must_use]
9914    pub const fn atmosphere(&self) -> Option<Atmosphere> {
9915        self.atmosphere
9916    }
9917
9918    /// Draws each cluster tinted by the DAG level it was decimated to, instead
9919    /// of shading it.
9920    ///
9921    /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
9922    /// several levels across its own surface is a statement a test can assert
9923    /// and nobody can see, and this is what makes it visible. The mesh path
9924    /// tints per cluster; the two indirect paths select one level per instance
9925    /// and have no per-cluster level at all, so they draw one flat grey — which
9926    /// is the comparison rather than a shortfall.
9927    ///
9928    /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
9929    /// of the frame's uniform block, read by a branch every device already runs.
9930    /// Nothing to build, nothing to refuse, nothing to release.
9931    ///
9932    /// **Wins over the normals view when both are on**, because the two share a
9933    /// lane and the fragment stage tests this one first.
9934    pub const fn set_lod_view(&mut self, on: bool) {
9935        self.lod_view = on;
9936    }
9937
9938    /// Whether the colour pass tints clusters by their DAG level.
9939    ///
9940    /// **What was asked for, not what is drawn.** The three debug views share
9941    /// one lane and resolve in one order, so a renderer with this and
9942    /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
9943    /// answers `true` here — the caller's setting is what a caller's toggle has
9944    /// to read back, and [`debug_view`](Self::debug_view) is what says which one
9945    /// the frame actually took.
9946    #[must_use]
9947    pub const fn lod_view(&self) -> bool {
9948        self.lod_view
9949    }
9950
9951    /// Shades each cluster by the **projected screen-space error** the LOD
9952    /// selection judged it on, instead of shading it.
9953    ///
9954    /// The LOD tint's sibling, and the other half of topic 25's
9955    /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
9956    /// looking at", and this answers "how close to the budget is this, and where
9957    /// is the selection about to switch". The number is the one
9958    /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
9959    /// cluster's *producing* group's error, projected from this frame's eye at
9960    /// this frame's pixels per unit.
9961    ///
9962    /// # What the colours mean
9963    ///
9964    /// A ramp that climbs in luminance from a cold floor to white, with a hue
9965    /// break at each of the two budgets: the hold budget where the hysteresis
9966    /// band starts, and the expand budget at the top, which is white. So the two
9967    /// budgets draw themselves as contour lines across the surface, and
9968    /// "brighter is closer to switching" reads even in a greyscale screenshot.
9969    /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
9970    /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
9971    /// to being readable as an ordering.
9972    ///
9973    /// A cluster nothing simplified — the original surface, at the bottom of the
9974    /// DAG — costs exactly zero and takes the ramp's floor.
9975    ///
9976    /// # Mesh path only, and that is the capability rather than a shortfall
9977    ///
9978    /// A per-cluster error exists only where selection is per cluster.
9979    /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
9980    /// choose one level per *instance*, so there is no per-cluster number for
9981    /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
9982    /// the LOD tint gets. Standing the two beside each other is the comparison.
9983    ///
9984    /// # It builds nothing and adds no pass
9985    ///
9986    /// One lane of the frame's uniform block, on
9987    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
9988    /// storage-buffer read in the mesh stage, which the mesh path's layout
9989    /// already carries. Nothing to build, nothing to refuse, nothing to release.
9990    ///
9991    /// **Wins over both the LOD tint and the normals view when several are on**;
9992    /// see [`debug_view`](Self::debug_view), which is that order stated once.
9993    ///
9994    /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
9995    /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
9996    pub const fn set_heatmap(&mut self, on: bool) {
9997        self.heatmap = on;
9998    }
9999
10000    /// Whether the colour pass shades clusters by their projected error.
10001    ///
10002    /// **What was asked for, not what is drawn**, on
10003    /// [`lod_view`](Self::lod_view)'s terms.
10004    #[must_use]
10005    pub const fn heatmap(&self) -> bool {
10006        self.heatmap
10007    }
10008
10009    /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10010    ///
10011    /// One is white and fully occluded is black — the buffer the forward pass
10012    /// multiplies its ambient term by, shown as itself. **This is how the AO
10013    /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10014    /// composited frame shows occlusion times albedo times ambient, and a
10015    /// difference in the first is not separable from a difference in the other
10016    /// two by looking at the result.
10017    ///
10018    /// # What it draws with occlusion switched off
10019    ///
10020    /// White, everywhere. A frame without
10021    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10022    /// a computed channel, and this view shows that image rather than pretending
10023    /// to a channel nothing computed — "no occlusion was computed" and "nothing
10024    /// occludes here" are the same value to the shading, and the view does not
10025    /// get to disagree with the shading about it.
10026    ///
10027    /// # It builds nothing and adds no pass
10028    ///
10029    /// One lane of the frame's uniform block, on
10030    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10031    /// tint and the heatmap it needs nothing from the geometry stage, so it
10032    /// draws on every [`GeometryPath`] rather than on
10033    /// the mesh-shader one alone.
10034    ///
10035    /// **Wins over every other view when several are on**; see
10036    /// [`debug_view`](Self::debug_view), which is that order stated once.
10037    pub const fn set_occlusion_view(&mut self, on: bool) {
10038        self.occlusion_view = on;
10039    }
10040
10041    /// Whether the colour pass draws the occlusion channel instead of shading.
10042    ///
10043    /// **What was asked for, not what is drawn**, on
10044    /// [`lod_view`](Self::lod_view)'s terms.
10045    #[must_use]
10046    pub const fn occlusion_view(&self) -> bool {
10047        self.occlusion_view
10048    }
10049
10050    /// Draws each fragment's motion vector instead of shading it.
10051    ///
10052    /// The two components are stretched by
10053    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10054    /// on grey, into red and green, with blue left at zero. A pixel at rest is
10055    /// grey in both channels to within one half-float step —
10056    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10057    /// not exactly — and a surface travelling right and down the screen
10058    /// brightens both.
10059    ///
10060    /// # It is the motion-vector target's only reader today
10061    ///
10062    /// The forward pass writes a motion vector into a third colour attachment on
10063    /// every frame — see [`crate::targets::motion`] — and no pass reads it
10064    /// yet; TAA (`docs/backlog.md`) is the first that will. This
10065    /// view is therefore what says the subtraction behind it is the right one,
10066    /// which is why it exists ahead of a consumer.
10067    ///
10068    /// # It builds nothing and adds no pass
10069    ///
10070    /// One lane of the frame's uniform block, on
10071    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10072    /// the occlusion view it needs nothing from the geometry stage that a
10073    /// shaded frame does not already produce — so it draws on every
10074    /// [`GeometryPath`].
10075    ///
10076    /// **Wins over every other view when several are on**; see
10077    /// [`debug_view`](Self::debug_view), which is that order stated once.
10078    pub const fn set_motion_view(&mut self, on: bool) {
10079        self.motion_view = on;
10080    }
10081
10082    /// Whether the colour pass draws the motion vector instead of shading.
10083    ///
10084    /// **What was asked for, not what is drawn**, on
10085    /// [`lod_view`](Self::lod_view)'s terms.
10086    #[must_use]
10087    pub const fn motion_view(&self) -> bool {
10088        self.motion_view
10089    }
10090
10091    /// Draws the occlusion channel's **bent direction** instead of shading.
10092    ///
10093    /// The three channels beside the visibility scalar, passed through as the
10094    /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10095    /// +Z blue, which is the mapping
10096    /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10097    /// normal. A fragment the occlusion pass had no direction for reads as the
10098    /// mid grey the zero sentinel encodes to.
10099    ///
10100    /// # What it is for
10101    ///
10102    /// The bent direction is what the ambient term is sampled *along*, and a
10103    /// composited frame cannot show it: ambient times albedo times a
10104    /// direction-dependent irradiance is one colour, and a direction that is
10105    /// subtly wrong looks like a lighting choice. This draws the direction
10106    /// alone, which is how a corner that leans the wrong way out of its own
10107    /// wall is a thing a reviewer sees rather than infers.
10108    ///
10109    /// # What it draws with occlusion switched off
10110    ///
10111    /// Mid grey, everywhere. A frame without
10112    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10113    /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10114    /// three channels, and this view shows that image rather than pretending to
10115    /// a direction nothing computed — which is the same answer the shading
10116    /// takes, since `mesh.slang` reads that sentinel as "use the shading
10117    /// normal".
10118    ///
10119    /// # It builds nothing and adds no pass
10120    ///
10121    /// One lane of the frame's uniform block, on
10122    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10123    /// the occlusion view it needs nothing from the geometry stage — so it
10124    /// draws on every [`GeometryPath`].
10125    ///
10126    /// **Wins over every other view when several are on**; see
10127    /// [`debug_view`](Self::debug_view), which is that order stated once.
10128    pub const fn set_bent_normal_view(&mut self, on: bool) {
10129        self.bent_normal_view = on;
10130    }
10131
10132    /// Whether the colour pass draws the bent direction instead of shading.
10133    ///
10134    /// **What was asked for, not what is drawn**, on
10135    /// [`lod_view`](Self::lod_view)'s terms.
10136    #[must_use]
10137    pub const fn bent_normal_view(&self) -> bool {
10138        self.bent_normal_view
10139    }
10140
10141    /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10142    /// shadow was sampled from.
10143    ///
10144    /// Topic 45's eighth decision made the cascade switch a
10145    /// band rather than a step, and this is the picture that band is judged in:
10146    /// each fragment's shading multiplied by
10147    /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10148    /// selected, and inside the band by the *blend* of the two — the same weight
10149    /// the visibility itself was mixed with. So the boundary reads as a
10150    /// gradient, and a seam where two cascades disagree shows up as a step in
10151    /// the gradient rather than as a ring somebody has to already suspect.
10152    ///
10153    /// # It keeps the shaded picture, which is why it loses to every other view
10154    ///
10155    /// Every other view replaces the frame; this one multiplies it, so the geometry
10156    /// stays readable underneath and the shadow the cascades produced is still
10157    /// in the picture being coloured. That is also what puts it last in
10158    /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10159    /// is no shading left for a tint to reach.
10160    ///
10161    /// # What it draws where no cascade covers a fragment
10162    ///
10163    /// Nothing at all —
10164    /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10165    /// A surface facing away from the sun and one past the last cascade's reach
10166    /// are both that, because neither was sampled through a cascade, and a
10167    /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10168    /// white everywhere for the same reason. Colouring those would be inventing
10169    /// a cascade for a pixel no map covers.
10170    ///
10171    /// # It builds nothing and adds no pass
10172    ///
10173    /// One lane of the frame's uniform block, on
10174    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10175    /// the occlusion view it needs nothing from the geometry stage — so it draws
10176    /// on every [`GeometryPath`].
10177    pub const fn set_cascade_view(&mut self, on: bool) {
10178        self.cascade_view = on;
10179    }
10180
10181    /// Whether the colour pass tints the picture by the sun's cascades.
10182    ///
10183    /// **What was asked for, not what is drawn**, on
10184    /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10185    /// case rather than the corner one: this view loses to every other one, so a
10186    /// renderer with any of them also on answers `true` here and draws that one.
10187    #[must_use]
10188    pub const fn cascade_view(&self) -> bool {
10189        self.cascade_view
10190    }
10191
10192    /// Draws the **shadow atlas itself** over the finished frame: the
10193    /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10194    /// each texel's stored depth as a grey and a border round every occupied
10195    /// slot.
10196    ///
10197    /// Sundial's atlas viewer, and the answer to a
10198    /// question no other view can be asked: which slot holds which map, and
10199    /// which slots hold nothing. A tile that was never rendered into, or
10200    /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10201    /// produces is plausible and every golden blessed from it passes. Here it is
10202    /// a rectangle that is visibly empty.
10203    ///
10204    /// # It is a pass, and it is the only debug view that is
10205    ///
10206    /// Every other view rides in one lane of the frame's uniform block and is a
10207    /// branch in `mesh.slang`, because every other view is a function of the
10208    /// fragment being shaded. The atlas is not: it is one image the whole frame
10209    /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10210    /// the frame instead — after the tonemap, in display space, for that
10211    /// module's reason — and the frame block is byte-identical either way.
10212    ///
10213    /// # Where it resolves, and what it costs when it is off
10214    ///
10215    /// Below every replacing view and above
10216    /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10217    /// [`debug_view`](Self::debug_view), which is that order stated once. A
10218    /// frame that resolved anything else records **no pass**, no pipeline bind
10219    /// and no block read, which is what makes the off position bit-identical on
10220    /// `crate::sky_pass`'s terms.
10221    pub const fn set_atlas_view(&mut self, on: bool) {
10222        self.atlas_view = on;
10223    }
10224
10225    /// Whether the frame draws the shadow atlas over the picture.
10226    ///
10227    /// **What was asked for, not what is drawn**, on
10228    /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10229    /// also on answers `true` here and draws that one.
10230    #[must_use]
10231    pub const fn atlas_view(&self) -> bool {
10232        self.atlas_view
10233    }
10234
10235    /// Pins the eye topic 25's selection is projected from, so the
10236    /// cut stops following the camera.
10237    ///
10238    /// [`None`] is the default and means "the camera's own eye", which is what
10239    /// every frame before this existed did. `Some(eye)` selects detail for a
10240    /// viewer standing at `eye` while the frame is still drawn, culled and lit
10241    /// from wherever the camera actually is.
10242    ///
10243    /// # What it is for
10244    ///
10245    /// Per-cluster LOD is only checkable from somewhere other than the point
10246    /// that chose it. Looked at from the selecting eye, a cut that is far too
10247    /// coarse and a cut that is exactly right produce the same silhouette —
10248    /// that is what a screen-space error budget *means* — so the one viewpoint
10249    /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10250    /// judged from. Pin the eye and fly away from it, and the boundaries between
10251    /// levels become geometry a reviewer can walk up to and look at edge-on.
10252    ///
10253    /// # Only the selection freezes
10254    ///
10255    /// The frame has three places a viewer position is read, and this moves
10256    /// exactly one of them:
10257    ///
10258    /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10259    ///   `DrawGenParams::camera_position` and is the only thing that decides the
10260    ///   cut. It writes the group hysteresis state that the mesh path's
10261    ///   amplification stage then descends, so freezing this one field freezes
10262    ///   the cut on the per-cluster path and the two indirect paths alike. This
10263    ///   is what moves.
10264    /// * **the frustum culls** — `cull.slang`'s instance test and
10265    ///   `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10266    ///   the frame's own view-projection and never read a camera position at
10267    ///   all. Unaffected, and it has to be: a frame culled against a frustum the
10268    ///   reviewer has flown out of would draw nothing.
10269    /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10270    ///   reads [`FrameUniforms::camera_position`] and asks which way a cluster
10271    ///   faces *relative to the viewer*. That question is about the eye the
10272    ///   picture is drawn from, not the eye it was selected for; frozen, a
10273    ///   reviewer who flew round to the other side of the face would have every
10274    ///   cluster now facing them rejected for facing away from a viewpoint
10275    ///   nobody is standing at. It stays live.
10276    ///
10277    /// The split is not new. `DrawGenParams::camera_position` and
10278    /// [`FrameUniforms::camera_position`] are already separate fields carrying
10279    /// different values on a shadow cascade — that one holds the sun while this
10280    /// one stays the camera, because detail is denominated in the camera's
10281    /// pixels and facing is asked about the light. This freezes the same seam
10282    /// from the other side, and needs no new binding, no new shader input and no
10283    /// shader change of any kind.
10284    ///
10285    /// # It freezes the cascades' selection too
10286    ///
10287    /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10288    /// cascade's draw generator, because a cascade selects detail for the
10289    /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10290    /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10291    /// is a difference in the picture that belongs to neither.
10292    ///
10293    /// # The heatmap reads the live eye, and says so
10294    ///
10295    /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10296    /// group's projected error, computed in the mesh stage from
10297    /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10298    /// frozen selection the two overlays answer different questions: the cut is
10299    /// the one chosen at the pinned eye, and the heat is what the error would be
10300    /// if it were chosen from here now. That is readable — flying towards the
10301    /// face brightens the clusters the frozen cut is not refining, which is the
10302    /// selection's sensitivity made visible — but it does mean the ramp's
10303    /// contours stop coinciding with the level boundaries while frozen.
10304    /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10305    /// unconditionally: a cluster's level is a property of the cut and of
10306    /// nothing else.
10307    ///
10308    /// Carrying the pinned eye into the mesh stage as well would need a second
10309    /// position in the frame block, which is a new shader input in every backend
10310    /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10311    ///
10312    /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10313    pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10314        self.frozen_selection_eye = eye;
10315    }
10316
10317    /// Where the selection is pinned, or [`None`] while it follows the camera.
10318    ///
10319    /// The read-back half of
10320    /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10321    /// debug panel says "frozen at" out of — "frozen" without the position is a
10322    /// row nobody can act on.
10323    #[must_use]
10324    pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10325        self.frozen_selection_eye
10326    }
10327
10328    /// Which of the debug views the next frame will actually draw.
10329    ///
10330    /// **The one place the precedence is decided**, and every other statement of
10331    /// it in this crate reads it back from here. The switches ride in one float
10332    /// lane of the frame block — see
10333    /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10334    /// — and the shaders test the outermost threshold first, so a sentinel for
10335    /// an outer view clears every threshold below it. Resolving here rather than
10336    /// letting each caller guess is what stops "which view is on" being answered
10337    /// differently by a menu row, a debug panel and the picture.
10338    #[must_use]
10339    pub const fn debug_view(&self) -> DebugView {
10340        if self.bent_normal_view {
10341            DebugView::BentNormal
10342        } else if self.motion_view {
10343            DebugView::Motion
10344        } else if self.occlusion_view {
10345            DebugView::AmbientOcclusion
10346        } else if self.heatmap {
10347            DebugView::Heatmap
10348        } else if self.lod_view {
10349            DebugView::LodTint
10350        } else if self.normals_view {
10351            DebugView::Normals
10352        } else if self.atlas_view {
10353            // **Below every view above it, and above the tint below.**
10354            //
10355            // Below, because every branch before this one is a question about
10356            // the *picture* — a cluster's error, a surface's normal, the
10357            // occlusion channel — and this one is not a picture of the scene at
10358            // all. A caller who left the atlas up and then asked for normals has
10359            // asked to look at the frame again, and the frame is what the branch
10360            // above draws; the atlas is one keystroke away and is not lost by
10361            // being deferred to.
10362            //
10363            // Above, because the cascade tint multiplies the shaded picture and
10364            // this replaces it: a tint on a frame the atlas overwrote would be a
10365            // tint on the atlas, which is a colour standing for nothing.
10366            DebugView::ShadowAtlas
10367        } else if self.cascade_view {
10368            // **Innermost, and the only view that sits below the others rather
10369            // than above them.** Every branch before this one draws something
10370            // *instead of* the shaded picture and returns before the shading; a
10371            // cascade tint is a multiply on that shading, so there is nothing
10372            // for it to modulate while one of them is showing and a caller with
10373            // both on has asked for the picture the outer one draws. The lane
10374            // says the same thing from the other end — the cascade sentinel is
10375            // negative, so it clears none of the shaders' thresholds — and
10376            // `crcbl_shaders`'
10377            // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10378            // what holds that half.
10379            DebugView::Cascades
10380        } else {
10381            DebugView::Shaded
10382        }
10383    }
10384
10385    /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10386    /// carries.
10387    const fn debug_view_lane(&self) -> f32 {
10388        match self.debug_view() {
10389            DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10390            DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10391            DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10392            DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10393            DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10394            DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10395            DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10396            // **The off sentinel, and it is not an omission.** This view is a
10397            // pass rather than a branch in `mesh.slang` — see
10398            // [`crate::atlas_view`] — so the colour pass draws exactly the
10399            // shaded picture it always drew and the pass afterwards replaces it.
10400            // A lane of its own would be a threshold no shader tests.
10401            DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10402        }
10403    }
10404
10405    /// Whether the colour pass draws world-space normals instead of shading.
10406    ///
10407    /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10408    /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10409    /// is about.
10410    #[must_use]
10411    pub const fn normals_view(&self) -> bool {
10412        self.normals_view
10413    }
10414
10415    /// The cull and draw-argument passes, and the buffers they produce.
10416    ///
10417    /// What a caller reads the culling statistics out of — topic 03 §3.6's
10418    /// delayed readback ring is [`DrawGen::visible_count`] — and what
10419    /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10420    /// arguments against the draws this pass used to record itself.
10421    #[must_use]
10422    pub const fn draws(&self) -> &DrawGen {
10423        &self.primary.draws
10424    }
10425
10426    /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
10427    /// and the exposure the reduce wrote out of them.
10428    ///
10429    /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
10430    /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
10431    /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
10432    /// there, so a frame drawn without
10433    /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
10434    /// hands back the frame before it rather than nothing.
10435    ///
10436    /// # Panics
10437    ///
10438    /// If `frame` is not a slot this renderer was built with.
10439    #[must_use]
10440    pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
10441        self.primary.auto_exposure.buffers(frame)
10442    }
10443
10444    /// `frame`'s froxel column: the buffers the froxel volume's
10445    /// three passes write, and the block they read.
10446    ///
10447    /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
10448    /// froxel against `crcbl_shaders::volumetric`, on
10449    /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
10450    ///
10451    /// # Panics
10452    ///
10453    /// If `frame` is not a slot this renderer was built with.
10454    #[must_use]
10455    pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
10456        self.primary.volumetric.buffers(frame)
10457    }
10458
10459    /// The three layers a caller supplies to the toggle resolution order — see
10460    /// [`crate::effects`].
10461    ///
10462    /// Read back rather than only written, so a caller changing one layer does
10463    /// not have to remember the other two: take this, edit the field it owns,
10464    /// hand it back to [`set_effect_request`](Self::set_effect_request).
10465    #[must_use]
10466    pub const fn effect_request(&self) -> EffectRequest {
10467        self.effect_request
10468    }
10469
10470    /// Replaces all three requested layers, and resolves them at the next
10471    /// [`begin_frame`](Self::begin_frame).
10472    ///
10473    /// **The frame in flight does not move.** `begin_frame` freezes what it
10474    /// resolved and [`add_passes`](Self::add_passes) records that, because the
10475    /// two halves of a frame have to agree about which culls were parametrised:
10476    /// `begin_frame` skips a shadow cull's parameter write when shadows are off
10477    /// and `add_passes` skips its dispatch, and a request landing between the two
10478    /// would dispatch a cull against numbers nothing zeroed.
10479    pub const fn set_effect_request(&mut self, request: EffectRequest) {
10480        self.effect_request = request;
10481    }
10482
10483    /// Replaces the **camera** layer with what `stack` asks for, and leaves the
10484    /// other three where they are.
10485    ///
10486    /// The file half of [`crate::stack`] reaching the renderer: a view that has
10487    /// a render stack writes it here, and the player's `[engine.video]` clamp,
10488    /// the antialiasing rung they picked and any programmatic override are
10489    /// untouched — which is the property that makes the four layers four rather
10490    /// than one. A caller that wants to move more than this layer builds an
10491    /// [`EffectRequest`] and uses
10492    /// [`set_effect_request`](Self::set_effect_request).
10493    ///
10494    /// **The frame in flight does not move**, on `set_effect_request`'s terms
10495    /// and for its reason: this writes the request and
10496    /// [`begin_frame`](Self::begin_frame) is what resolves it.
10497    pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
10498        self.effect_request.camera = stack.compile();
10499    }
10500
10501    /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
10502    ///
10503    /// The resolved set, not a layer: every effect in it has survived the
10504    /// camera's stack, the player's quality clamp, any programmatic override and
10505    /// the device — which is the one question a test asking "did this frame have
10506    /// shadows in it" wants answered.
10507    ///
10508    /// [`RenderEffects::all`] before the first frame, which is what a renderer
10509    /// nobody has changed would draw.
10510    #[must_use]
10511    pub const fn effects(&self) -> RenderEffects {
10512        self.frame_effects
10513    }
10514
10515    /// What a frame begun **now** would draw: the whole order applied to the
10516    /// current request.
10517    ///
10518    /// [`effects`](Self::effects)' question one frame earlier, and the one a
10519    /// caller reporting its own configuration wants — a debug panel built at
10520    /// startup has no frame behind it yet, and printing what the last one drew
10521    /// would print a default.
10522    ///
10523    /// **A debug view takes the antialiasing resolve off** — either tier of it
10524    /// — whatever the four layers said. Those views are readouts rather than
10525    /// pictures — a pixel's colour *is* the cluster's projected error or its
10526    /// DAG level, read back against a legend — and a filter that blends two
10527    /// clusters' shades invents a ramp position no cluster occupies.
10528    /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
10529    /// frame's distinct colours.
10530    #[must_use]
10531    pub fn resolved_effects(&self) -> RenderEffects {
10532        let resolved = self.effect_request.resolve(self.device_effects);
10533        if matches!(self.debug_view(), DebugView::Shaded) {
10534            resolved
10535        } else {
10536            // **Both tiers**, because the slot is what a readout cannot have
10537            // rather than one filter in particular.
10538            resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
10539        }
10540    }
10541
10542    /// Which tonemap operator the next frame runs:
10543    /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
10544    /// the clamp for a readout.
10545    ///
10546    /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
10547    /// operator instead of to the resolve.** A debug view's pixels *are* data —
10548    /// an encoded normal, an occlusion channel, a cascade's colour code — and a
10549    /// curve is a monotone remapping of every one of them. `apps/alcove`'s
10550    /// `--bent-view` reads a normal back and compares it against the geometry's
10551    /// own, which under ACES is 49 code values out; the clamp is the identity on
10552    /// `0..=1`, so it is the operator that leaves a readout readable. A caller
10553    /// that wants a curved readout has none, deliberately: there is no reading
10554    /// it would make easier.
10555    #[must_use]
10556    pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
10557        if matches!(self.debug_view(), DebugView::Shaded) {
10558            self.tonemap_curve
10559        } else {
10560            tonemap::TonemapCurve::Clamp
10561        }
10562    }
10563
10564    /// Which effects this **device** permits, which is the fourth layer and
10565    /// clamps last.
10566    ///
10567    /// Every one of them today — see [`ForwardRenderer::device_effects`], which
10568    /// is where that is argued per effect rather than asserted.
10569    #[must_use]
10570    pub const fn device_effects(&self) -> RenderEffects {
10571        self.device_effects
10572    }
10573
10574    /// Which [`GeometryPath`] this renderer was **built for** — not what the
10575    /// device reports, but what it actually built.
10576    ///
10577    /// The device may prefer a path below its capability ceiling when a higher
10578    /// one uses emulation. This reports the preference actually built, rather
10579    /// than the ceiling: [`GeometryPath::MeshShader`] here means
10580    /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
10581    /// cluster buffers, and created **no** raster pipeline for the pass to fall
10582    /// back to. So a frame this renderer drew came out of a mesh stage, and a
10583    /// silent degradation is not a state it has — which is the claim a golden
10584    /// image on its own could never make, because a fall-through draws the same
10585    /// picture.
10586    #[must_use]
10587    pub const fn geometry_path(&self) -> GeometryPath {
10588        match self.emit {
10589            EmitTail::Mesh => GeometryPath::MeshShader,
10590            EmitTail::Count => GeometryPath::IndirectCount,
10591            EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
10592        }
10593    }
10594
10595    /// Whether this renderer **built** §3.5's per-cluster cull — an
10596    /// amplification stage in front of the mesh stage, rejecting a surviving
10597    /// instance's back-facing and off-screen clusters.
10598    ///
10599    /// `false` on the two indirect tails, which draw index ranges and have no
10600    /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
10601    /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
10602    /// that device draws every cluster of every surviving instance and the
10603    /// picture is the same one.
10604    ///
10605    /// The instance cull runs on every path either way, and is unaffected by
10606    /// this.
10607    ///
10608    /// It is asked of the renderer rather than of the device for
10609    /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
10610    /// built, so `true` means
10611    /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
10612    /// cluster word is a number the frame produced rather than the zero the
10613    /// clearing pass left.
10614    #[must_use]
10615    pub const fn culls_clusters(&self) -> bool {
10616        self.culls_clusters
10617    }
10618
10619    /// Whether this renderer can choose **which level** of a
10620    /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
10621    /// [`ForwardRenderer::add_instance`] may be given one at all.
10622    ///
10623    /// Topic 25's selection happens in the amplification stage where
10624    /// there is one, and in the cull pass where the tail is indirect and a level
10625    /// is an ordinary index range. **One device shape has neither**: a mesh stage
10626    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10627    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
10628    /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
10629    /// of the bucket — and a DAG's bucket is every level end to end, so the frame
10630    /// is several overlapping copies of one surface. That is a real and supported
10631    /// device state rather than a degradation, so this reports it instead of
10632    /// refusing to build.
10633    ///
10634    /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
10635    /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
10636    /// which is why this is asked only before placing a DAG.
10637    ///
10638    /// Asked of the renderer rather than of the device for
10639    /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
10640    ///
10641    /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
10642    #[must_use]
10643    pub const fn selects_levels(&self) -> bool {
10644        !self.emit.is_mesh() || self.culls_clusters
10645    }
10646
10647    /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
10648    /// rotated to, which is the slot every per-frame buffer is indexed by.
10649    #[must_use]
10650    pub const fn frame(&self) -> usize {
10651        self.frame
10652    }
10653
10654    /// What the last [`add_passes`](Self::add_passes) recorded, and what it
10655    /// cannot know.
10656    ///
10657    /// Zero draws until a frame has been built: this reports what was recorded,
10658    /// not what a frame would record.
10659    ///
10660    /// # The triangles are [`None`] here, on every geometry path
10661    ///
10662    /// Every draw this renderer records except the full-screen passes' and the
10663    /// debug draw layer's is **indirect**:
10664    /// the instance count and the index range live in the argument buffer
10665    /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
10666    /// about what it covered. That is true of
10667    /// [`GeometryPath::MeshShader`] and of
10668    /// both indirect tails alike — the three differ in which call is recorded,
10669    /// not in who decides the counts — so
10670    /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
10671    /// is [`None`] whatever the device supports. Nothing counts a triangle on
10672    /// the GPU either, and a cluster count times a nominal triangles-per-cluster
10673    /// would read as authoritative and be neither.
10674    ///
10675    /// # The instances drawn come back off the GPU, a few frames late
10676    ///
10677    /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
10678    /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
10679    /// plus the frame's direct draws — the ones here whose instance the CPU
10680    /// knows about, and the ones that are also in
10681    /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
10682    /// comparable: the same quantity submitted and kept.
10683    ///
10684    /// **The camera's cull alone.** The shadow culls test other frustums and
10685    /// their survivors are counted into buffers of their own; adding them here
10686    /// would give a "drawn" larger than "submitted" on any frame with a shadow
10687    /// in it.
10688    ///
10689    /// It is [`None`] — the row says `indirect` — for the first few frames of a
10690    /// renderer's life, while the ring has not come round, and for good on a
10691    /// device that would not give out a readback.
10692    /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
10693    /// the number is about whenever there is one.
10694    ///
10695    /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
10696    /// is known and is the plan's "submitted" half: the live instances
10697    /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
10698    /// frame's direct draws — every full-screen pass's triangle and the debug
10699    /// draw layer's line list.
10700    #[must_use]
10701    pub fn counters(&self) -> FrameCounters {
10702        if self.recorded_draws == 0 {
10703            return FrameCounters::default();
10704        }
10705        let stats = self.cull_stats();
10706        let direct = self.direct_draws();
10707        FrameCounters {
10708            draws: self.recorded_draws,
10709            instances: self.instances.len() as u64 + direct,
10710            // Each direct draw is submitted and drawn, and none of them is in
10711            // the cull's count — they are draws of one instance, added on both
10712            // sides so the two halves of the row measure the same thing. Off the
10713            // frame that *was* recorded rather than off a constant, so a frame
10714            // with an effect switched off does not count a triangle it never
10715            // submitted.
10716            // Less what the occlusion cull's second phase rejected, which were
10717            // survivors of the frustum and were not drawn.
10718            drawn: stats
10719                .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
10720            triangles: None,
10721            // The survivors alone: the panel row is "clusters drawn", and the
10722            // frustum and cone rejection counts beside them are a different
10723            // question — `CullStats::clusters` carries all three for a caller
10724            // that wants the split, which `apps/quarry`'s own panel row is.
10725            clusters: stats
10726                .and_then(|stats| stats.clusters)
10727                .map(|cull| cull.survivors),
10728            cull_frame: stats.map(|stats| stats.frame),
10729        }
10730    }
10731
10732    /// The draws this renderer records **directly** — the ones whose instance
10733    /// the CPU knows about, as opposed to the indirect calls whose counts live
10734    /// in a buffer a shader wrote.
10735    ///
10736    /// Every full-screen pass's over-sized triangle, plus the debug draw
10737    /// layer's line list on a frame that has one. One instance each, which is
10738    /// why [`counters`](Self::counters) adds this to both halves of its
10739    /// submitted/drawn pair.
10740    fn direct_draws(&self) -> u64 {
10741        self.recorded_fullscreen * FULLSCREEN_DRAWS
10742            + self.recorded_debug_draw
10743            + self.recorded_tile_clears
10744            + self.recorded_water_draws
10745    }
10746
10747    /// What the camera's cull kept, on the frame the ring has reached.
10748    ///
10749    /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
10750    /// round — see [`crate::cull_stats`] for the latency and for what makes it
10751    /// free of any wait. [`counters`](Self::counters) is where this reaches the
10752    /// panel; it is exposed on its own because the frame number and the cluster
10753    /// word are both things a test asserts about directly.
10754    #[must_use]
10755    pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
10756        self.cull_stats.as_ref().and_then(CullStatsRing::latest)
10757    }
10758
10759    /// Describes the imported swapchain image the frame ends in.
10760    ///
10761    /// A helper rather than something every caller writes, because getting
10762    /// `initial`/`final_state` wrong is exactly the hand-written barrier this
10763    /// slice removed: an acquired image's contents are undefined, and the
10764    /// compositor may only be handed one in [`ResourceState::Present`].
10765    #[must_use]
10766    pub fn present_target(
10767        image: crcbl_hal::ImageHandle,
10768        view: ImageViewHandle,
10769        format: Format,
10770        extent: (u32, u32),
10771    ) -> ImportedImage {
10772        ImportedImage {
10773            image,
10774            view,
10775            format,
10776            extent,
10777            initial: ResourceState::Undefined,
10778            // The acquire's semaphore, not a barrier, is what orders this frame
10779            // after the last use of the image — which is what makes `Undefined`
10780            // honest here and what makes it uncheckable. See `InitialClaim`.
10781            claim: InitialClaim::Acquired,
10782            final_state: ResourceState::Present,
10783        }
10784    }
10785
10786    /// Releases everything, in dependency order. The device must be idle.
10787    pub fn destroy(self, device: &dyn Device) {
10788        if let Some(stats) = self.cull_stats {
10789            stats.destroy(device);
10790        }
10791        // The cameras first: their groups name the scene's buffers, pages and
10792        // atlas below, and they own nothing the scene's groups name.
10793        for view in self.views.into_iter().flatten() {
10794            view.destroy(device);
10795        }
10796        self.primary.destroy(device);
10797        // After every view, whose grass and water groups name these buffers.
10798        self.grass.destroy(device);
10799        self.water.destroy(device);
10800        device.destroy_sampler(self.sampler);
10801        device.destroy_graphics_pipeline(self.tonemap_pipeline);
10802        device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
10803        device.destroy_bind_group_layout(self.tonemap_layout);
10804
10805        for pipelines in [
10806            self.shadow_pipeline,
10807            self.depth_masked_pipeline,
10808            self.rsm_pipeline,
10809        ] {
10810            device.destroy_graphics_pipeline(pipelines.single);
10811            device.destroy_graphics_pipeline(pipelines.double);
10812        }
10813        device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
10814        for groups in self.shadow_groups {
10815            for group in groups {
10816                device.destroy_bind_group(group);
10817            }
10818        }
10819        for buffers in self.shadow_uniforms {
10820            for buffer in buffers {
10821                device.destroy_buffer(buffer);
10822            }
10823        }
10824        for buffers in self.shadow_selection {
10825            for buffer in buffers {
10826                device.destroy_buffer(buffer);
10827            }
10828        }
10829        for draws in self.shadow_draws {
10830            draws.destroy(device);
10831        }
10832        device.destroy_sampler(self.shadow_sampler);
10833        device.destroy_image_view(self.shadow_atlas_view);
10834        device.destroy_image(self.shadow_atlas);
10835        device.destroy_image_view(self.shadow_placeholder_view);
10836        device.destroy_image(self.shadow_placeholder);
10837
10838        if let Some(grid) = self.ground_grid {
10839            grid.destroy(device);
10840        }
10841        // Nothing to release on a renderer nobody drew a segment through — see
10842        // [`crate::debug_draw`], whose pipeline is built on first use.
10843        self.debug_draw.destroy(device);
10844        self.atlas_viewer.destroy(device);
10845        self.ambient_occlusion_placeholder.destroy(device);
10846        self.contact_shadow_placeholder.destroy(device);
10847        self.probe_visibility_placeholder.destroy(device);
10848        if let Some(captured) = self.probe_visibility {
10849            captured.destroy(device);
10850        }
10851        self.specular_dfg.destroy(device);
10852        self.ltc_table.destroy(device);
10853        self.normal_page.destroy(device);
10854        self.mro_page.destroy(device);
10855        self.emissive_page.destroy(device);
10856
10857        device.destroy_graphics_pipeline(self.mesh_pipeline.single);
10858        device.destroy_graphics_pipeline(self.mesh_pipeline.double);
10859        // The one place the wireframe pair is released — `set_wireframe(.., false)`
10860        // deliberately is not, because this call is the one that requires an
10861        // idle device.
10862        if let Some(pipelines) = self.wireframe_pipeline {
10863            device.destroy_graphics_pipeline(pipelines.single);
10864            device.destroy_graphics_pipeline(pipelines.double);
10865        }
10866        device.destroy_pipeline_layout(self.mesh_pipeline_layout);
10867        device.destroy_bind_group_layout(self.mesh_layout);
10868        self.base_color_page.destroy(device);
10869        device.destroy_sampler(self.base_color_sampler);
10870        for retired in self.retired_pages {
10871            retired.destroy(device);
10872        }
10873        device.destroy_buffer(self.draw_constants);
10874        if let Some(clusters) = self.clusters {
10875            clusters.destroy(device);
10876        }
10877        // Before the probe table, because its bind groups name that table's
10878        // rows — the same ordering the light grid is under above.
10879        if let Some(gather) = self.probe_gather {
10880            gather.destroy(device);
10881        }
10882        self.probes.destroy(device);
10883        self.materials.destroy(device);
10884        self.instances.destroy(device);
10885        self.pool.destroy(device);
10886    }
10887}
10888
10889/// What the shadow pass a frame recorded would leave the image holding, held
10890/// until the frame after can say whether its body ran.
10891///
10892/// Topic 45's static-caching rung, per group: recording a pass
10893/// is not drawing one, so nothing here is believed until
10894/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
10895/// out of the graph.
10896#[derive(Clone, Debug)]
10897struct ShadowCommit {
10898    /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
10899    id: u64,
10900    /// `[group]`: what the group's entry of
10901    /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
10902    /// redraws, and [`None`] for the groups it holds.
10903    groups: Vec<Option<(u64, Vec3, f32)>>,
10904    /// The layout the pass draws under, where it clears the whole attachment —
10905    /// and [`None`] where it loads, because a loading pass leaves every tile it
10906    /// does not redraw exactly as it found it.
10907    layout: Option<Vec<shadow::TileRect>>,
10908}
10909
10910/// The shader modules a mesh pipeline is built from, with its entry points
10911/// already resolved.
10912///
10913/// **A type rather than a run of locals in `build`** because there are now two
10914/// callers: `build`, which makes the colour pipeline and its depth-only twin,
10915/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
10916/// in [`PolygonMode::Line`] long after `build` released its modules. The
10917/// alternative was a second copy of a descriptor that names two modules, their
10918/// entry points, the colour targets and a depth state — the pair that drifts.
10919///
10920/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
10921/// in the same function. A module is not needed once the pipeline exists.
10922struct MeshModules {
10923    /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
10924    /// fragment stage on both.
10925    mesh: ShaderModuleHandle,
10926    /// `vertexMain`, unused on the mesh-shader path.
10927    vertex: &'static str,
10928    /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
10929    /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
10930    /// vertex pool and no attribute region at all. Unused on the mesh-shader
10931    /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
10932    depth_vertex: &'static str,
10933    /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
10934    /// builds the tile clear from: three corners off `SV_VertexID` and no input
10935    /// at all, so it resets one tile of the atlas without reading a vertex.
10936    ///
10937    /// **The same stage on every path**, unlike the two above: a device with a
10938    /// mesh stage still has a vertex stage, and a clear that produced no
10939    /// geometry is a primitive, not a cluster.
10940    depth_clear_vertex: &'static str,
10941    fragment: &'static str,
10942    /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
10943    /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
10944    /// all.
10945    ///
10946    /// **The same stage on both paths**, unlike the two vertex entry points
10947    /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
10948    /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
10949    /// mesh stage writes on the mesh one. So the cutout is one comparison in one
10950    /// place rather than one per geometry path.
10951    depth_masked_fragment: &'static str,
10952    /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
10953    /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
10954    /// describing the surface rather than shading it.
10955    ///
10956    /// **The reason the shaded stage above is looked up by name.** A module with
10957    /// two fragment entry points has no unambiguous one, which is what `entry`
10958    /// answers `None` for.
10959    rsm_fragment: &'static str,
10960    /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
10961    cluster: Option<ClusterStages>,
10962}
10963
10964/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
10965/// and the stages taken out of it.
10966struct ClusterStages {
10967    /// The module the mesh stage is built from, and the one the task stage is,
10968    /// which are **two modules rather than one**.
10969    ///
10970    /// `mesh_cluster.slang` compiles to a combined module carrying every entry
10971    /// point and to one module per stage, and these are the per-stage ones. A
10972    /// module holding a task entry point and its mesh partner carries two
10973    /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
10974    /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
10975    /// which draws cluster 0 of instance slot 0 of every bucket and nothing
10976    /// else. See `crcbl_shaders::EntryPoint`.
10977    mesh_module: ShaderModuleHandle,
10978    /// The task stage's own module, on the same terms. [`None`] exactly when
10979    /// [`task`](Self::task) is.
10980    task_module: Option<ShaderModuleHandle>,
10981    /// Which of the module's two mesh entry points this path builds — the
10982    /// amplified one where the device has a task stage to feed it.
10983    mesh: &'static str,
10984    /// §3.5's per-cluster cull, where the device has the stage to run it in.
10985    /// [`None`] is not a degradation: `meshMain` draws the same picture out of
10986    /// the same clusters, having rejected none of them, which is what a device
10987    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10988    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
10989    task: Option<&'static str>,
10990}
10991
10992impl MeshModules {
10993    /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
10994    /// writes the shaded colour, then topic 47's
10995    /// reflectivity channel, then topic 43 §9's motion
10996    /// vector — and both pipeline shapes name that same entry point, so each
10997    /// target is one more element of this array and not a second pipeline, a
10998    /// second entry point or a new interpolant. The refusal the AO section
10999    /// records was about the depth prepass, which has no fragment stage and no
11000    /// colour target at all; it does not reach this array.
11001    ///
11002    /// Element order is `SV_Target` order, and each format is the one the
11003    /// matching `TransientImageDesc` creates: a pipeline built for a format the
11004    /// attachment is not in is a validation error on WebGPU and a silent
11005    /// reinterpretation elsewhere.
11006    const COLOR_TARGETS: [ColorTargetState; 3] = [
11007        ColorTargetState::opaque(Format::Rgba16Float),
11008        ColorTargetState::opaque(Format::Rgba8Unorm),
11009        ColorTargetState::opaque(MOTION_FORMAT),
11010    ];
11011
11012    /// **Three targets again, and a different three.** `mesh.slang`'s
11013    /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11014    /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11015    /// which is what the irradiance probes' gather needs of a
11016    /// texel and nothing more.
11017    ///
11018    /// Element order is `SV_Target` order and each format is the one the
11019    /// matching description in [`crate::rsm`] creates: a pipeline built for a
11020    /// format the attachment is not in is a validation error on WebGPU and a
11021    /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11022    /// in that module is the other half of the pair.
11023    const RSM_TARGETS: [ColorTargetState; 3] = [
11024        ColorTargetState::opaque(Format::Rgba16Float),
11025        ColorTargetState::opaque(Format::Rgba8Unorm),
11026        ColorTargetState::opaque(Format::Rgba32Float),
11027    ];
11028
11029    /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11030    /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11031    /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11032    ///
11033    /// Taken from the crate that owns the shader source rather than written
11034    /// out, as
11035    /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11036    /// requires: only Metal reads this field, so a literal that disagreed with
11037    /// the shader would launch the wrong number of threads on one backend and
11038    /// nowhere else.
11039    const MESH_WORKGROUP_SIZE: [u32; 3] =
11040        [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11041
11042    /// Invocations per task workgroup: `taskMain` is
11043    /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11044    /// pair of its chunk. Taken from the crate that owns the shader, on
11045    /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11046    const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11047
11048    /// Loads whichever modules `emit` needs and resolves their entry points.
11049    ///
11050    /// # Errors
11051    ///
11052    /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11053    /// entry point, and [`HalError`] from either module. A failure after the
11054    /// first module was created releases it rather than leaking it.
11055    fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11056        // Entry points resolved before the module exists: a manifest that
11057        // disagreed with the SPIR-V would otherwise fail inside the descriptor
11058        // literal, with the module already created and nothing holding it.
11059        //
11060        // **The vertex stage is named rather than looked up by stage**, for
11061        // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11062        // this module has two vertex entry points, and a stage lookup answers
11063        // `None` for two matches. Which of the two a pipeline names is the whole
11064        // of what the split-stream vertex pool bought.
11065        let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11066        let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11067        let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11068        // **Named rather than looked up by stage, on the vertex entry points'
11069        // terms exactly.** Since the irradiance probes' updater
11070        // landed, this module has *two* fragment entry points — the shaded one
11071        // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11072        // a stage lookup here refuses the build outright with "exposes no
11073        // unambiguous Fragment entry point".
11074        let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11075        let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11076        let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11077        // **Named rather than looked up by stage**, because the module has two
11078        // mesh entry points and a stage lookup would refuse an ambiguous one —
11079        // see `named_entry`. Which of the two this names is the whole of the
11080        // amplification decision.
11081        let cluster_stages = emit
11082            .is_mesh()
11083            .then(|| {
11084                let mesh = named_entry(
11085                    &MESH_CLUSTER,
11086                    if culls_clusters {
11087                        "amplifiedMeshMain"
11088                    } else {
11089                        "meshMain"
11090                    },
11091                    Stage::Mesh,
11092                )?;
11093                let task = culls_clusters
11094                    .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11095                    .transpose()?;
11096                Ok::<_, HalError>((mesh, task))
11097            })
11098            .transpose()?;
11099
11100        let mesh = device.create_shader_module(&ShaderModuleDesc {
11101            label: Some("mesh.slang"),
11102            spirv: MESH.spirv(),
11103            wgsl: MESH.wgsl(),
11104            msl: MESH.msl(),
11105            // **Both containers, and still one module.** A DXIL container holds
11106            // exactly one entry point, so this is a list where its three
11107            // neighbours are single artifacts; the backend that consumes it
11108            // picks the container named by the stage it is building. Nothing
11109            // here branches on a backend, and the three that ignore DXIL see
11110            // the same module they always did.
11111            dxil: &MESH.dxil_containers(),
11112        })?;
11113        let cluster = match cluster_stages {
11114            None => None,
11115            Some((cluster_mesh, task)) => {
11116                // **The mesh stage's module is `mesh_cluster.slang`; the
11117                // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11118                // module per stage, so the shading — Lambert, the GGX lobe, the
11119                // material row, the page sample — is the same code both paths
11120                // run rather than a copy that agrees today.
11121                // `mesh_cluster.slang`'s header carries the argument, and its
11122                // `VertexOutput` is what the two agree through.
11123                // **One module per stage, each carrying that stage's own
11124                // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11125                // artifact per source whatever the stage, and a DXIL container
11126                // is already per entry point, so both are handed over unchanged
11127                // and the backends that read them see what they always did.
11128                let stage_module = |entry_point: &str| {
11129                    device.create_shader_module(&ShaderModuleDesc {
11130                        label: Some("mesh_cluster.slang"),
11131                        // The combined module where this stage has none of its
11132                        // own, which is every stage of every other shader.
11133                        spirv: MESH_CLUSTER
11134                            .spirv_for(entry_point)
11135                            .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11136                        // `None`, and it is the whole reason this is a second
11137                        // file: WGSL cannot express a mesh stage at all.
11138                        wgsl: MESH_CLUSTER.wgsl(),
11139                        msl: MESH_CLUSTER.msl(),
11140                        dxil: &MESH_CLUSTER.dxil_containers(),
11141                    })
11142                };
11143                let mesh_module = match stage_module(cluster_mesh) {
11144                    Ok(module) => module,
11145                    Err(error) => {
11146                        device.destroy_shader_module(mesh);
11147                        return Err(error);
11148                    }
11149                };
11150                let task_module = match task.map(stage_module).transpose() {
11151                    Ok(module) => module,
11152                    Err(error) => {
11153                        device.destroy_shader_module(mesh);
11154                        device.destroy_shader_module(mesh_module);
11155                        return Err(error);
11156                    }
11157                };
11158                Some(ClusterStages {
11159                    mesh_module,
11160                    task_module,
11161                    mesh: cluster_mesh,
11162                    task,
11163                })
11164            }
11165        };
11166        Ok(Self {
11167            mesh,
11168            vertex,
11169            depth_vertex,
11170            depth_clear_vertex,
11171            fragment,
11172            depth_masked_fragment,
11173            rsm_fragment,
11174            cluster,
11175        })
11176    }
11177
11178    /// The rasteriser state every pipeline shape here shares, because the only
11179    /// things that differ between them are which stage produces the geometry and
11180    /// which side of it survives.
11181    ///
11182    /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11183    /// been on from the first mesh. The cube's winding is asserted by
11184    /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11185    /// failure rather than a debugging session — and a mesh drawn without
11186    /// culling would let a winding mistake survive into P7's geometry pool. The
11187    /// mesh stage emits its corner triples in the index buffer's own order, so
11188    /// the winding it produces is the same one.
11189    ///
11190    /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11191    /// §3.9.6's first half — and the twin built with it is the only way a back
11192    /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11193    fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11194        PrimitiveState {
11195            cull_mode,
11196            polygon_mode,
11197            ..PrimitiveState::default()
11198        }
11199    }
11200
11201    /// What a pipeline built with `cull` adds to its label, so a capture and
11202    /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11203    /// the [`SidedPipelines::single`] it was built beside.
11204    ///
11205    /// Empty for the culling modes, because those pipelines' labels are the ones
11206    /// every existing capture and every test lookup already names.
11207    fn side_label(cull: CullMode) -> &'static str {
11208        match cull {
11209            CullMode::None => " double-sided",
11210            CullMode::Front | CullMode::Back => "",
11211        }
11212    }
11213
11214    /// Both sides of one pipeline shape, single-sided first, **created and not
11215    /// yet unwrapped**.
11216    ///
11217    /// The results rather than the pair, because that is the discipline `build`
11218    /// keeps for every pipeline it makes: everything is created while the
11219    /// modules are alive, the modules are released once, and only then is each
11220    /// successful result handed to rollback before any error is propagated. A
11221    /// helper that unwrapped here would have to drop a handle it had already
11222    /// created when its twin failed, and nothing would ever destroy it.
11223    fn sided(
11224        mut build: impl FnMut(CullMode) -> Result<GraphicsPipelineHandle, HalError>,
11225    ) -> [Result<GraphicsPipelineHandle, HalError>; 2] {
11226        [build(CullMode::Back), build(CullMode::None)]
11227    }
11228
11229    /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11230    /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11231    /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11232    /// matrix that agrees with **both** comes from [`crate::camera`].
11233    fn depth_stencil() -> Option<DepthStencilState> {
11234        Some(DepthStencilState::default())
11235    }
11236
11237    /// The colour pass's depth state, which is not the same shape as
11238    /// [`MeshModules::depth_stencil`] because the depth prepass has already
11239    /// drawn this geometry.
11240    ///
11241    /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11242    /// paid for once per pixel.** The prepass runs the same draws through
11243    /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11244    /// stage — so the depth already in the attachment is this pass's own answer,
11245    /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11246    /// that would have won the write. What it removes is the clustered-forward
11247    /// shading of every fragment a nearer one goes on to cover.
11248    ///
11249    /// **Lines: the writing default, because a wireframe is not the geometry the
11250    /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11251    /// and an edge pixel's depth is interpolated along the line rather than
11252    /// across the face, so testing it for equality against a filled prepass
11253    /// rejects most of the wireframe. That frame keeps the pass shape this pass
11254    /// had before the prepass existed — see the colour pass's depth attachment,
11255    /// which branches on the same condition.
11256    fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11257        match polygon_mode {
11258            PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11259            _ => Self::depth_stencil(),
11260        }
11261    }
11262
11263    /// The colour pass's pipeline, filled or wireframe, culling back faces or
11264    /// nothing.
11265    ///
11266    /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11267    /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11268    /// names the side, so a capture tells all four apart.
11269    fn color_pipeline(
11270        &self,
11271        device: &dyn Device,
11272        layout: PipelineLayoutHandle,
11273        polygon_mode: PolygonMode,
11274        cull: CullMode,
11275        label: &str,
11276    ) -> Result<GraphicsPipelineHandle, HalError> {
11277        let primitive = Self::primitive(polygon_mode, cull);
11278        let depth_stencil = Self::color_depth_stencil(polygon_mode);
11279        let side = Self::side_label(cull);
11280        let fragment = Some(ShaderEntry {
11281            module: self.mesh,
11282            entry_point: self.fragment,
11283        });
11284        match self.cluster.as_ref() {
11285            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11286                label: Some(&format!("{label}{side} mesh cluster")),
11287                layout,
11288                task: cluster
11289                    .task
11290                    .zip(cluster.task_module)
11291                    .map(|(entry_point, module)| ShaderEntry {
11292                        module,
11293                        entry_point,
11294                    }),
11295                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11296                mesh: ShaderEntry {
11297                    module: cluster.mesh_module,
11298                    entry_point: cluster.mesh,
11299                },
11300                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11301                fragment,
11302                primitive,
11303                depth_stencil,
11304                multisample: MultisampleState::default(),
11305                color_targets: &Self::COLOR_TARGETS,
11306            }),
11307            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11308                label: Some(&format!("{label}{side} mesh")),
11309                layout,
11310                vertex: ShaderEntry {
11311                    module: self.mesh,
11312                    entry_point: self.vertex,
11313                },
11314                fragment,
11315                primitive,
11316                depth_stencil,
11317                multisample: MultisampleState::default(),
11318                color_targets: &Self::COLOR_TARGETS,
11319            }),
11320        }
11321    }
11322
11323    /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11324    /// same modules and the same layout: no fragment stage, no colour target,
11325    /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11326    ///
11327    /// **The transform is identical and the fetch is not, which is the point.**
11328    /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11329    /// depth pass plus whatever emit tail the device selected", and what makes
11330    /// that work is a frame block whose `view_proj` is the cascade's matrix
11331    /// rather than a second transform path: a cascade that disagreed with the
11332    /// colour pass about where a vertex is would produce shadows that do not
11333    /// line up with their casters, which is indistinguishable from a bias
11334    /// problem. `depthVertexMain` is that same clip position written the same
11335    /// way, with everything the discarded varyings needed — the attribute
11336    /// region and the previous frame's position — left unread;
11337    /// topic 43 §2 split the pool for exactly this
11338    /// pass, and this is where it is spent.
11339    ///
11340    /// **The mesh-shader path still runs the colour pipeline's geometry
11341    /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11342    /// mesh stage is a second entry point in that module and its own rung; a
11343    /// device with a mesh stage goes on reading whole vertices here.
11344    ///
11345    /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11346    /// prepass, and depth drawn as lines is depth with holes in it — which the
11347    /// occlusion pair would read as geometry that is not there.
11348    fn depth_pipeline(
11349        &self,
11350        device: &dyn Device,
11351        layout: PipelineLayoutHandle,
11352        cull: CullMode,
11353    ) -> Result<GraphicsPipelineHandle, HalError> {
11354        let primitive = Self::primitive(PolygonMode::Fill, cull);
11355        let side = Self::side_label(cull);
11356        match self.cluster.as_ref() {
11357            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11358                label: Some(&format!("shadow cascade{side} mesh cluster")),
11359                layout,
11360                task: cluster
11361                    .task
11362                    .zip(cluster.task_module)
11363                    .map(|(entry_point, module)| ShaderEntry {
11364                        module,
11365                        entry_point,
11366                    }),
11367                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11368                mesh: ShaderEntry {
11369                    module: cluster.mesh_module,
11370                    entry_point: cluster.mesh,
11371                },
11372                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11373                fragment: None,
11374                primitive,
11375                depth_stencil: Self::depth_stencil(),
11376                multisample: MultisampleState::default(),
11377                color_targets: &[],
11378            }),
11379            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11380                label: Some(&format!("shadow cascade{side}")),
11381                layout,
11382                vertex: ShaderEntry {
11383                    module: self.mesh,
11384                    entry_point: self.depth_vertex,
11385                },
11386                fragment: None,
11387                primitive,
11388                depth_stencil: Self::depth_stencil(),
11389                multisample: MultisampleState::default(),
11390                color_targets: &[],
11391            }),
11392        }
11393    }
11394
11395    /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11396    /// state and the same absent colour targets, `depthMaskedFragmentMain`
11397    /// behind the geometry stage, and [`MeshModules::vertex`] in
11398    /// [`MeshModules::depth_vertex`]'s place.
11399    ///
11400    /// Topic 43 §3's cutout, in the two passes that
11401    /// write depth without shading. A masked instance drawn through the pipeline
11402    /// above writes its full silhouette: it occludes itself through the hole it
11403    /// can see through, and it casts the shadow of a leaf that has none.
11404    ///
11405    /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11406    /// needs the UV, which lives in the attribute region `depthVertexMain`
11407    /// exists not to read — so this stage reads a whole vertex, exactly as
11408    /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11409    /// What that buys is one fragment entry point for both geometry paths: the
11410    /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11411    /// compared in one place rather than once per path.
11412    ///
11413    /// **Which draws are recorded with it is the bucket's own material mode**,
11414    /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11415    /// masks nothing has no bucket in this partition, records through the
11416    /// pipeline above with no fragment stage anywhere, and costs exactly what it
11417    /// cost before this one existed; a scene that masks one mesh pays the
11418    /// fragment stage for that mesh's draws alone.
11419    fn depth_masked_pipeline(
11420        &self,
11421        device: &dyn Device,
11422        layout: PipelineLayoutHandle,
11423        cull: CullMode,
11424    ) -> Result<GraphicsPipelineHandle, HalError> {
11425        let primitive = Self::primitive(PolygonMode::Fill, cull);
11426        let side = Self::side_label(cull);
11427        let fragment = Some(ShaderEntry {
11428            module: self.mesh,
11429            entry_point: self.depth_masked_fragment,
11430        });
11431        match self.cluster.as_ref() {
11432            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11433                label: Some(&format!("shadow cascade masked{side} mesh cluster")),
11434                layout,
11435                task: cluster
11436                    .task
11437                    .zip(cluster.task_module)
11438                    .map(|(entry_point, module)| ShaderEntry {
11439                        module,
11440                        entry_point,
11441                    }),
11442                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11443                mesh: ShaderEntry {
11444                    module: cluster.mesh_module,
11445                    entry_point: cluster.mesh,
11446                },
11447                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11448                fragment,
11449                primitive,
11450                depth_stencil: Self::depth_stencil(),
11451                multisample: MultisampleState::default(),
11452                color_targets: &[],
11453            }),
11454            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11455                label: Some(&format!("shadow cascade masked{side}")),
11456                layout,
11457                vertex: ShaderEntry {
11458                    module: self.mesh,
11459                    entry_point: self.vertex,
11460                },
11461                fragment,
11462                primitive,
11463                depth_stencil: Self::depth_stencil(),
11464                multisample: MultisampleState::default(),
11465                color_targets: &[],
11466            }),
11467        }
11468    }
11469
11470    /// The reflective shadow map's pipeline: the colour pipeline's geometry
11471    /// stage, `rsmFragmentMain` in the shaded stage's place, and
11472    /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
11473    ///
11474    /// The irradiance probes' updater draws the sun's near
11475    /// cascade a second time through this — see [`crate::rsm`], which owns the
11476    /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
11477    /// pass out of that cascade's own bind group and its own already-generated
11478    /// draws.
11479    ///
11480    /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
11481    /// the cascade this rides beside: a fragment stage that writes a world
11482    /// position, a normal and an albedo needs the varyings `depthVertexMain`
11483    /// exists to leave unread. On the mesh path it is the very same geometry
11484    /// stage the colour pass runs, for the reason `depth_pipeline` gives.
11485    ///
11486    /// **Its own depth, written**, rather than the colour pass's read-only
11487    /// equality test: nothing has drawn this view's depth before it, and the
11488    /// pass is what decides which surface a texel of the map holds.
11489    fn rsm_pipeline(
11490        &self,
11491        device: &dyn Device,
11492        layout: PipelineLayoutHandle,
11493        cull: CullMode,
11494    ) -> Result<GraphicsPipelineHandle, HalError> {
11495        let primitive = Self::primitive(PolygonMode::Fill, cull);
11496        let side = Self::side_label(cull);
11497        let fragment = Some(ShaderEntry {
11498            module: self.mesh,
11499            entry_point: self.rsm_fragment,
11500        });
11501        match self.cluster.as_ref() {
11502            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11503                label: Some(&format!("rsm{side} mesh cluster")),
11504                layout,
11505                task: cluster
11506                    .task
11507                    .zip(cluster.task_module)
11508                    .map(|(entry_point, module)| ShaderEntry {
11509                        module,
11510                        entry_point,
11511                    }),
11512                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11513                mesh: ShaderEntry {
11514                    module: cluster.mesh_module,
11515                    entry_point: cluster.mesh,
11516                },
11517                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11518                fragment,
11519                primitive,
11520                depth_stencil: Self::depth_stencil(),
11521                multisample: MultisampleState::default(),
11522                color_targets: &Self::RSM_TARGETS,
11523            }),
11524            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11525                label: Some(&format!("rsm{side}")),
11526                layout,
11527                vertex: ShaderEntry {
11528                    module: self.mesh,
11529                    entry_point: self.vertex,
11530                },
11531                fragment,
11532                primitive,
11533                depth_stencil: Self::depth_stencil(),
11534                multisample: MultisampleState::default(),
11535                color_targets: &Self::RSM_TARGETS,
11536            }),
11537        }
11538    }
11539
11540    /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
11541    /// some tiles and redraw others.
11542    ///
11543    /// Topic 45's cadence rung needs a tile cleared on its own,
11544    /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
11545    /// whole image, and the region-bounded forms are not portable. This is the
11546    /// portable statement of the same thing: `mesh.slang`'s
11547    /// `depthClearVertexMain` covers the viewport the shadow pass has already
11548    /// set over the tile, and the depth state below writes
11549    /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
11550    ///
11551    /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
11552    /// clear rather than a draw: the tile holds the previous frame's depths, and
11553    /// under the engine's [`CompareOp::Greater`] a clear value of zero would
11554    /// fail against every one of them and leave the tile exactly as it was.
11555    ///
11556    /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
11557    /// is generated from `SV_VertexID` rather than wound by an artist, so a
11558    /// culling rule meant for scene geometry would decide whether the clear
11559    /// happens at all.
11560    ///
11561    /// **A vertex pipeline on every path**, including the mesh-shader one: a
11562    /// device with a mesh stage still has a vertex stage, and the clear has no
11563    /// clusters to descend.
11564    fn depth_clear_pipeline(
11565        &self,
11566        device: &dyn Device,
11567        layout: PipelineLayoutHandle,
11568    ) -> Result<GraphicsPipelineHandle, HalError> {
11569        device.create_graphics_pipeline(&GraphicsPipelineDesc {
11570            label: Some("shadow tile clear"),
11571            // The mesh layout, so binding this pipeline in the middle of the
11572            // shadow pass does not disturb the bind group the draws around it
11573            // are recorded with. The stage reads none of it.
11574            layout,
11575            vertex: ShaderEntry {
11576                module: self.mesh,
11577                entry_point: self.depth_clear_vertex,
11578            },
11579            fragment: None,
11580            primitive: PrimitiveState {
11581                cull_mode: CullMode::None,
11582                polygon_mode: PolygonMode::Fill,
11583                ..PrimitiveState::default()
11584            },
11585            depth_stencil: Some(DepthStencilState {
11586                depth_compare: CompareOp::Always,
11587                ..DepthStencilState::default()
11588            }),
11589            multisample: MultisampleState::default(),
11590            color_targets: &[],
11591        })
11592    }
11593
11594    /// Releases every module. The pipelines built from them stay valid.
11595    fn destroy(self, device: &dyn Device) {
11596        device.destroy_shader_module(self.mesh);
11597        if let Some(cluster) = self.cluster {
11598            device.destroy_shader_module(cluster.mesh_module);
11599            if let Some(task) = cluster.task_module {
11600                device.destroy_shader_module(task);
11601            }
11602        }
11603    }
11604}
11605
11606/// The entry point for `stage`, or an error naming the shader.
11607///
11608/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
11609/// expose both stages — but the alternative is an `expect` in engine code.
11610fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
11611    shader.entry_point(stage).ok_or_else(|| {
11612        HalError::ShaderCompilation(format!(
11613            "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
11614             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11615            shader.name()
11616        ))
11617    })
11618}
11619
11620/// The entry point called `name`, checked to be `stage`'s.
11621///
11622/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
11623/// points — one behind the amplification stage and one without it — and a
11624/// lookup by stage answers `None` for two matches rather than picking one, for
11625/// the good reason that picking one would draw the wrong geometry.
11626///
11627/// The stage is still checked rather than taken on trust: a name that resolved
11628/// to the wrong stage would be a pipeline built with an amplification stage in
11629/// its mesh slot, and the failure would arrive as a driver error rather than as
11630/// this sentence.
11631pub(crate) fn named_entry(
11632    shader: &crcbl_shaders::Shader,
11633    name: &'static str,
11634    stage: Stage,
11635) -> Result<&'static str, HalError> {
11636    let found = shader
11637        .entry_points()
11638        .iter()
11639        .find(|entry| entry.name() == name && entry.stage() == stage);
11640    found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
11641        HalError::ShaderCompilation(format!(
11642            "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
11643             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11644            shader.name()
11645        ))
11646    })
11647}
11648
11649// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
11650#[cfg(all(test, not(target_arch = "wasm32")))]
11651mod tests {
11652    mod instance_upload;
11653    mod load_service;
11654    mod page_reload;
11655    mod shadow_reach;
11656
11657    use super::*;
11658    use crate::effects::{Antialiasing, EffectOverride};
11659    use crate::scene::{
11660        DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
11661        DEMO_UNTINTED,
11662    };
11663    use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
11664    use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
11665
11666    #[test]
11667    fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
11668        let recorder = Recorder::new();
11669        let mut limits = crcbl_hal::Limits::desktop();
11670        limits.max_color_attachments = 2;
11671        let features = Features::COMPUTE | Features::MESH_SHADER;
11672        let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
11673            .with_recorder(recorder.clone());
11674        let device = instance
11675            .create_device(&DeviceDesc {
11676                label: None,
11677                adapter: crcbl_hal::AdapterId(0),
11678                required_features: features,
11679                optional_features: Features::empty(),
11680                compatible_surface: None,
11681            })
11682            .unwrap();
11683        let queue = device.queue(QueueKind::Graphics).unwrap();
11684        let before = recorder.total_live_objects();
11685        let error = ForwardRenderer::with_scene_on_path(
11686            device.as_ref(),
11687            queue,
11688            Format::Rgba8UnormSrgb,
11689            &scene::demo(),
11690            GeometryPath::MeshShader,
11691        )
11692        .expect_err("three-target color pipelines must be refused");
11693        assert!(
11694            error
11695                .to_string()
11696                .contains("3 colour targets exceeds max_color_attachments 2"),
11697            "{error}"
11698        );
11699        assert!(
11700            recorder.events().iter().any(|event| matches!(
11701                event,
11702                Event::Created {
11703                    kind: ObjectKind::GraphicsPipeline,
11704                    ..
11705                }
11706            )),
11707            "the refusal must exercise cleanup of successful pipelines"
11708        );
11709        assert_eq!(
11710            recorder.total_live_objects(),
11711            before,
11712            "partial pipeline construction leaked resources"
11713        );
11714        recorder.assert_valid();
11715    }
11716
11717    #[test]
11718    fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
11719        let recorder = Recorder::new();
11720        let instance = NullInstance::gpu_driven()
11721            .with_geometry_preference(GeometryPath::IndirectPerBatch)
11722            .with_recorder(recorder.clone());
11723        let device = instance
11724            .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
11725            .unwrap();
11726        let queue = device.queue(QueueKind::Graphics).unwrap();
11727        assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
11728        let default = ForwardRenderer::with_scene(
11729            device.as_ref(),
11730            queue,
11731            Format::Rgba8UnormSrgb,
11732            &scene::demo(),
11733        )
11734        .unwrap();
11735        assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
11736        default.destroy(device.as_ref());
11737        recorder.clear();
11738        let mut exact = ForwardRenderer::with_scene_on_path(
11739            device.as_ref(),
11740            queue,
11741            Format::Rgba8UnormSrgb,
11742            &scene::demo(),
11743            GeometryPath::IndirectCount,
11744        )
11745        .unwrap();
11746        assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
11747        let rendered = frame(device.as_ref(), &mut exact, queue);
11748        let commands = commands_in_pass(&recorder, "forward");
11749        assert!(commands.iter().any(|command| matches!(
11750            command,
11751            crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
11752        )));
11753        assert!(
11754            !commands
11755                .iter()
11756                .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
11757        );
11758        rendered.finish(device.as_ref(), exact);
11759    }
11760
11761    /// **A device with a draw index draws a range of buckets per call, and one
11762    /// without it a call per bucket** — both indirect tails, read off the
11763    /// recorded stream of a whole frame.
11764    ///
11765    /// The ranged frame records one bind and one multi-draw per range in the
11766    /// depth prepass, whose draws together cover every bucket exactly once,
11767    /// and no count draw anywhere; the per-bucket frame records the call per
11768    /// bucket it always did. Both frames' counters are what they recorded.
11769    #[test]
11770    fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
11771        use crcbl_hal::null::Command;
11772
11773        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11774            for ranged in [false, true] {
11775                let optional = if ranged {
11776                    Features::GPU_DRIVEN | Features::DRAW_INDEX
11777                } else {
11778                    DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
11779                };
11780                let (recorder, device, queue) = open_with(optional);
11781                let mut renderer = ForwardRenderer::with_scene_on_path(
11782                    device.as_ref(),
11783                    queue,
11784                    Format::Rgba8UnormSrgb,
11785                    &scene::demo(),
11786                    path,
11787                )
11788                .expect("the demo scene builds");
11789                assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
11790                let buckets = renderer.bucket_modes.len();
11791                assert!(buckets > 1, "one bucket packs into one call either way");
11792                let rendered = frame(device.as_ref(), &mut renderer, queue);
11793
11794                let commands = commands_in_pass(&recorder, "depth-prepass");
11795                let binds = commands
11796                    .iter()
11797                    .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
11798                    .count();
11799                let draws: Vec<u32> = commands
11800                    .iter()
11801                    .filter_map(|command| match command {
11802                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11803                        Command::DrawIndexedIndirectCount(draw) => {
11804                            assert!(!ranged, "{path:?}: a ranged pass records no count draw");
11805                            assert_eq!(draw.max_draw_count, 1);
11806                            Some(1)
11807                        }
11808                        _ => None,
11809                    })
11810                    .collect();
11811                assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
11812                assert_eq!(
11813                    draws.iter().sum::<u32>() as usize,
11814                    buckets,
11815                    "{path:?}: every bucket drawn once"
11816                );
11817                if ranged {
11818                    assert!(
11819                        draws.len() < buckets,
11820                        "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
11821                    );
11822                } else {
11823                    assert_eq!(draws, vec![1; buckets], "{path:?}");
11824                }
11825                assert!(
11826                    !recorder
11827                        .commands()
11828                        .iter()
11829                        .any(|command| ranged
11830                            && matches!(command, Command::DrawIndexedIndirectCount(_))),
11831                    "{path:?}: a ranged frame records no count draw"
11832                );
11833                assert_eq!(
11834                    renderer.counters().draws,
11835                    recorded_draws(&recorder) as u64,
11836                    "{path:?}, ranged {ranged}"
11837                );
11838                rendered.finish(device.as_ref(), renderer);
11839                recorder.assert_valid();
11840            }
11841        }
11842    }
11843
11844    /// **A scene holding every material mode draws each pipeline's buckets as
11845    /// one ranged call**, because the bucket table is numbered mode-major: the
11846    /// depth prepass records one call per depth pipeline and the colour pass
11847    /// one per sided pipeline, on both indirect tails.
11848    ///
11849    /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
11850    /// and every partition's runs are one bucket long, so the prepass would
11851    /// record a call per bucket — the counts below are what tell the two
11852    /// numberings apart, and the sums are what say every bucket still drew.
11853    #[test]
11854    fn every_mode_partition_of_a_ranged_frame_is_one_call() {
11855        use crcbl_hal::null::Command;
11856        use crcbl_shaders::mesh::GpuMaterial;
11857
11858        let scene = {
11859            let mut scene = crate::scene::demo();
11860            while scene.materials.len() < 4 {
11861                scene.materials.push(GpuMaterial::UNTINTED);
11862            }
11863            let rows = [
11864                0,
11865                GpuMaterial::ALPHA_MODE_MASK,
11866                GpuMaterial::DOUBLE_SIDED,
11867                GpuMaterial::MODE_MASK,
11868            ];
11869            for (row, flags) in scene.materials.iter_mut().zip(rows) {
11870                row.flags = flags;
11871            }
11872            scene
11873        };
11874        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11875            let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
11876            let mut renderer = ForwardRenderer::with_scene_on_path(
11877                device.as_ref(),
11878                queue,
11879                Format::Rgba8UnormSrgb,
11880                &scene,
11881                path,
11882            )
11883            .expect("the four-mode demo builds");
11884            assert!(renderer.range_limit.is_some(), "{path:?}");
11885            let buckets = renderer.bucket_modes.len();
11886            let per_mode = buckets / DEPTH_MODES.len();
11887            assert_eq!(
11888                per_mode * DEPTH_MODES.len(),
11889                buckets,
11890                "{path:?}: four twins"
11891            );
11892            assert!(
11893                per_mode > 1,
11894                "{path:?}: a mode of one bucket is one call under either numbering"
11895            );
11896            let rendered = frame(device.as_ref(), &mut renderer, queue);
11897
11898            let draws = |label: &str| -> Vec<u32> {
11899                commands_in_pass(&recorder, label)
11900                    .iter()
11901                    .filter_map(|command| match command {
11902                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11903                        _ => None,
11904                    })
11905                    .collect()
11906            };
11907            let prepass = draws("depth-prepass");
11908            assert_eq!(
11909                prepass,
11910                vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
11911                "{path:?}: one call per depth pipeline, each a whole mode"
11912            );
11913            let forward = draws("forward");
11914            assert_eq!(
11915                forward,
11916                vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
11917                "{path:?}: one call per sided pipeline, each two adjacent modes"
11918            );
11919            rendered.finish(device.as_ref(), renderer);
11920            recorder.assert_valid();
11921        }
11922    }
11923
11924    /// **Behind an amplification stage the mesh tail records one flat call per
11925    /// partition, and without one a range of buckets per call on a device with
11926    /// a draw index and a call per bucket without** — read off the recorded
11927    /// stream of a whole frame.
11928    ///
11929    /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
11930    /// colour pass's sided segments in region 0, under the segment's first
11931    /// bucket's block — whatever the bucket count, and whether or not the
11932    /// device granted a draw index, which the flat call does not read. Without
11933    /// the stage the colour pass's calls, unrolled a structure at a time, are
11934    /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
11935    /// bucket's own extents, each once. Either way the counters are what the
11936    /// frame recorded.
11937    #[test]
11938    fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
11939        use crcbl_hal::null::Command;
11940
11941        // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
11942        // bucket each, in one material mode — so one run of `n` buckets.
11943        for cubes in [None, Some(4), Some(33)] {
11944            for task in [Features::TASK_SHADER, Features::empty()] {
11945                for ranged in [false, true] {
11946                    let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
11947                    let recorder = Recorder::new();
11948                    let optional = if ranged {
11949                        task | Features::DRAW_INDEX
11950                    } else {
11951                        task
11952                    };
11953                    let (device, queue) = open_mesh_path(&recorder, optional);
11954                    let mut scene = scene::demo();
11955                    if let Some(cubes) = cubes {
11956                        scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
11957                        scene.capacities.meshes = cubes;
11958                        scene.capacities.vertices =
11959                            cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
11960                        scene.capacities.indices =
11961                            cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
11962                    }
11963                    let mut renderer = ForwardRenderer::with_scene_on_path(
11964                        device.as_ref(),
11965                        queue,
11966                        Format::Rgba8UnormSrgb,
11967                        &scene,
11968                        GeometryPath::MeshShader,
11969                    )
11970                    .expect("the mesh renderer builds");
11971                    assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
11972                    assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
11973                    let buckets = renderer.bucket_constants.len();
11974                    assert!(buckets > 1, "one bucket packs into one call either way");
11975                    let rendered = frame(device.as_ref(), &mut renderer, queue);
11976
11977                    let commands = commands_in_pass(&recorder, "forward");
11978                    let bound: Vec<u32> = commands
11979                        .iter()
11980                        .filter_map(|command| match command {
11981                            Command::BindGroup {
11982                                slot: 0,
11983                                dynamic_offsets,
11984                                ..
11985                            } => Some(dynamic_offsets[0]),
11986                            _ => None,
11987                        })
11988                        .collect();
11989                    let calls: Vec<DrawIndirect> = commands
11990                        .iter()
11991                        .filter_map(|command| match command {
11992                            Command::DrawMeshTasksIndirect(draw) => Some(*draw),
11993                            Command::DrawMeshTasks { .. }
11994                            | Command::DrawIndexedIndirect(_)
11995                            | Command::DrawIndexedIndirectCount(_) => {
11996                                panic!("{case}: the mesh tail recorded {command:?}")
11997                            }
11998                            _ => None,
11999                        })
12000                        .collect();
12001                    assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12002                    assert!(
12003                        calls
12004                            .iter()
12005                            .all(|call| call.stride
12006                                == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12007                        "{case}: one structure a bucket, or a flat call's one"
12008                    );
12009                    if task.is_empty() {
12010                        // Each call a structure at a time: what a call per
12011                        // bucket would have recorded for the buckets it
12012                        // stands for.
12013                        let mut unrolled: Vec<DrawIndirect> = calls
12014                            .iter()
12015                            .flat_map(|call| {
12016                                (0..call.draw_count).map(|draw| DrawIndirect {
12017                                    offset: call.offset + u64::from(draw) * u64::from(call.stride),
12018                                    draw_count: 1,
12019                                    ..*call
12020                                })
12021                            })
12022                            .collect();
12023                        unrolled.sort_by_key(|draw| draw.offset);
12024                        assert_eq!(
12025                            unrolled,
12026                            mesh_dispatch_calls(&renderer),
12027                            "{case}: every bucket's own extents, each once"
12028                        );
12029                        let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12030                        match (ranged, cubes) {
12031                            (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12032                            (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12033                            (true, None) => assert!(
12034                                calls.len() < buckets,
12035                                "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12036                            ),
12037                        }
12038                    } else {
12039                        let (expected, firsts) = flat_dispatch_calls(
12040                            &renderer,
12041                            crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12042                        );
12043                        assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12044                        assert_eq!(
12045                            bound,
12046                            firsts
12047                                .iter()
12048                                .map(|&bucket| renderer.bucket_constants[bucket as usize])
12049                                .collect::<Vec<_>>(),
12050                            "{case}: each under its segment's first bucket's block"
12051                        );
12052                    }
12053                    assert_eq!(
12054                        renderer.counters().draws,
12055                        recorded_draws(&recorder) as u64,
12056                        "{case}"
12057                    );
12058                    rendered.finish(device.as_ref(), renderer);
12059                    recorder.assert_valid();
12060                }
12061            }
12062        }
12063    }
12064
12065    /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12066    /// block carries**, in every draw region.
12067    ///
12068    /// The host half of `mesh_cluster.slang`'s "One call for a range of
12069    /// buckets": a ranged call binds its first bucket's block alone, and the
12070    /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12071    /// the two table words it names. So each bucket's block has to sit one word
12072    /// past the one before in all four, and the table words have to hold the
12073    /// bucket's own cluster base and count — read out of the bytes that reached
12074    /// the device, since a block written wrong leaves the renderer's fields
12075    /// right.
12076    #[test]
12077    fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12078        let recorder = Recorder::new();
12079        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12080        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12081            .expect("the mesh renderer builds");
12082        let blocks = recorder
12083            .buffer_bytes(renderer.draw_constants)
12084            .expect("the blocks are live");
12085        let tables = recorder
12086            .buffer_bytes(renderer.primary.draws.tables())
12087            .expect("the tables are live");
12088        let word = |bytes: &[u8], at: usize| {
12089            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12090        };
12091        let buckets = renderer.bucket_constants.len();
12092        assert!(buckets > 1, "a range needs two buckets to step between");
12093        let bucket_count = u32::try_from(buckets).expect("a few buckets");
12094        let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12095        let block = |region: u32, bucket: u32| {
12096            let at = ((region * bucket_count + bucket) * stride) as usize;
12097            let field = |index: usize| word(&blocks, at + index * 4);
12098            crcbl_shaders::meshlet::ClusterDrawConstants {
12099                start_at: field(0),
12100                cluster_base: field(1),
12101                cluster_count: field(2),
12102                bucket: field(3),
12103                group_stride: field(4),
12104                level_groups_at: field(5),
12105                cluster_base_at: field(6),
12106                cluster_count_at: field(7),
12107                chunk_starts_at: field(8),
12108                chunk_starts_end: field(9),
12109            }
12110        };
12111        let mut bases = Vec::new();
12112        for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12113            let first = block(region, 0);
12114            for bucket in 0..bucket_count {
12115                let own = block(region, bucket);
12116                assert_eq!(
12117                    word(&tables, own.cluster_base_at as usize * 4),
12118                    own.cluster_base,
12119                    "region {region} bucket {bucket}: the base word holds the base"
12120                );
12121                assert_eq!(
12122                    word(&tables, own.cluster_count_at as usize * 4),
12123                    own.cluster_count,
12124                    "region {region} bucket {bucket}: the count word holds the count"
12125                );
12126                // What draw `bucket` of a call bound at bucket 0's block reads
12127                // — and a flat call's workgroup that found bucket `bucket` by
12128                // searching the chunk starts from bucket 0's word to the
12129                // region's end.
12130                assert_eq!(
12131                    (
12132                        first.start_at + bucket,
12133                        first.bucket + bucket,
12134                        first.cluster_base_at + bucket,
12135                        first.cluster_count_at + bucket,
12136                        first.group_stride,
12137                        first.level_groups_at,
12138                        first.chunk_starts_at + bucket,
12139                        first.chunk_starts_end,
12140                    ),
12141                    (
12142                        own.start_at,
12143                        own.bucket,
12144                        own.cluster_base_at,
12145                        own.cluster_count_at,
12146                        own.group_stride,
12147                        own.level_groups_at,
12148                        own.chunk_starts_at,
12149                        own.chunk_starts_end,
12150                    ),
12151                    "region {region} bucket {bucket}"
12152                );
12153                assert_eq!(
12154                    own.chunk_starts_at,
12155                    crcbl_shaders::draw_gen::chunk_start_word(
12156                        renderer.primary.draws.visible_capacity(),
12157                        bucket_count,
12158                        region,
12159                        bucket,
12160                    ),
12161                    "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12162                );
12163                assert_eq!(
12164                    own.chunk_starts_end - own.chunk_starts_at,
12165                    bucket_count - bucket,
12166                    "region {region} bucket {bucket}: the search ends at the region's end word"
12167                );
12168                if region == 0 {
12169                    bases.push(own.cluster_base);
12170                }
12171            }
12172        }
12173        assert!(
12174            bases.windows(2).any(|pair| pair[0] != pair[1]),
12175            "the buckets' meshes start at different clusters, so a range reading its \
12176             first bucket's base for every draw would be seen: {bases:?}"
12177        );
12178        renderer.destroy(device.as_ref());
12179        recorder.assert_valid();
12180    }
12181
12182    #[test]
12183    fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12184    {
12185        for features in [
12186            Features::GPU_DRIVEN,
12187            Features::COMPUTE | Features::MESH_SHADER,
12188        ] {
12189            let recorder = Recorder::new();
12190            let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12191                features,
12192                limits: crcbl_hal::Limits::desktop(),
12193            })
12194            .with_recorder(recorder.clone());
12195            let device = instance
12196                .create_device(&DeviceDesc {
12197                    label: None,
12198                    adapter: crcbl_hal::AdapterId(0),
12199                    required_features: Features::COMPUTE,
12200                    optional_features: features,
12201                    compatible_surface: None,
12202                })
12203                .expect("null device opens");
12204            let queue = device.queue(QueueKind::Graphics).unwrap();
12205            for (path, required) in [
12206                (GeometryPath::IndirectPerBatch, Features::empty()),
12207                (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12208                (GeometryPath::MeshShader, Features::MESH_SHADER),
12209            ] {
12210                recorder.clear();
12211                let result = ForwardRenderer::with_scene_on_path(
12212                    device.as_ref(),
12213                    queue,
12214                    Format::Rgba8UnormSrgb,
12215                    &scene::demo(),
12216                    path,
12217                );
12218                if features.contains(required) {
12219                    let renderer = result.expect("supported exact tail builds");
12220                    assert_eq!(renderer.geometry_path(), path);
12221                    renderer.destroy(device.as_ref());
12222                } else {
12223                    assert!(
12224                        matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12225                    );
12226                    assert!(
12227                        recorder.events().is_empty(),
12228                        "unsupported selection must not touch device objects"
12229                    );
12230                }
12231                recorder.assert_valid();
12232            }
12233        }
12234    }
12235
12236    pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12237        open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12238    }
12239
12240    /// [`open`] asking for `optional_features` instead of
12241    /// [`DeviceDesc::for_adapter`]'s.
12242    ///
12243    /// The null preset *has* more than the default request asks for, and a
12244    /// granted feature set is the intersection of the two — so this is how a test
12245    /// reaches a device with something the ordinary one lacks. What it exists for
12246    /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12247    /// device has no line fill mode, which is the other half of the wireframe
12248    /// pair of tests below.
12249    fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12250        let recorder = Recorder::new();
12251        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12252        let adapter = instance.adapters().remove(0);
12253        let device = instance
12254            .create_device(&DeviceDesc {
12255                optional_features,
12256                ..DeviceDesc::for_adapter(adapter.id)
12257            })
12258            .expect("the null backend always opens");
12259        let queue = device.queue(QueueKind::Graphics).expect("always present");
12260        (recorder, device, queue)
12261    }
12262
12263    /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12264    ///
12265    /// **Insertion order is what the caller decides**, and it is load-bearing:
12266    /// the slot an object lands in is topic 25's hysteresis key. So
12267    /// every test below places its objects in the order the frame used to hold
12268    /// them — the cube first, wherever there is one.
12269    fn place_demo(
12270        renderer: &mut ForwardRenderer,
12271        mesh: usize,
12272        material: usize,
12273        transform: Mat4,
12274    ) -> InstanceHandle {
12275        renderer
12276            .add_instance(&InstanceDesc {
12277                mesh,
12278                material,
12279                transform,
12280            })
12281            .expect("a pool of thousands has room for a handful of objects")
12282    }
12283
12284    /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12285    /// always had.
12286    ///
12287    /// `begin_frame` used to write this object for every caller; the tests below
12288    /// that are about a frame with something in it place it themselves now.
12289    pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12290        place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12291    }
12292
12293    /// The whole renderer builds and tears down against a backend with no
12294    /// driver, which is what makes it testable on every CI leg.
12295    #[test]
12296    fn the_forward_renderer_builds_and_leaks_nothing() {
12297        let (recorder, device, queue) = open();
12298        let before = recorder.total_live_objects();
12299        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12300            .expect("the null backend accepts every descriptor");
12301        assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12302        assert!(recorder.total_live_objects() > before);
12303        renderer.destroy(device.as_ref());
12304        assert_eq!(
12305            recorder.total_live_objects(),
12306            before,
12307            "every object created must be destroyed"
12308        );
12309        recorder.assert_valid();
12310    }
12311
12312    /// The uniform ring really rotates, or a spinning cube is a
12313    /// read-after-write hazard across submissions.
12314    #[test]
12315    fn the_uniform_ring_rotates() {
12316        let (_, device, queue) = open();
12317        let mut renderer =
12318            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12319        let camera = Camera::default();
12320        let light = DirectionalLight::default();
12321
12322        let mut seen = Vec::new();
12323        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12324            renderer
12325                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12326                .expect("write");
12327            seen.push(renderer.primary.uniforms[renderer.frame]);
12328        }
12329        assert_ne!(
12330            seen[0], seen[1],
12331            "consecutive frames must not share a buffer"
12332        );
12333        assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12334        renderer.destroy(device.as_ref());
12335    }
12336
12337    /// **The tonemap's block is a ring too, and it carries the exposure the
12338    /// caller set.**
12339    ///
12340    /// The bytes are the observable rather than the field, because the field is
12341    /// what a renderer that never wired the block up would also have: the claim
12342    /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12343    /// null recorder's write log can say so.
12344    ///
12345    /// The default is checked first — a renderer nobody has called
12346    /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12347    /// `EXPOSURE` constant held, under
12348    /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12349    #[test]
12350    fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12351        let (recorder, device, queue) = open();
12352        let mut renderer =
12353            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12354        let camera = Camera::default();
12355        let light = DirectionalLight::default();
12356
12357        renderer
12358            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12359            .expect("write");
12360        assert_eq!(
12361            recorder
12362                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12363                .expect("begin_frame wrote the block"),
12364            crcbl_shaders::tonemap::TonemapParams {
12365                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12366                curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12367                auto_exposure: false,
12368                coverage_alpha: false,
12369            }
12370            .to_bytes(),
12371            "an untouched renderer must write the exposure the constant used to hold, \
12372             under the operator this renderer starts on",
12373        );
12374
12375        // A value that is neither the default nor a bound, so a block left at
12376        // either would fail.
12377        renderer.set_exposure(3.5);
12378        let mut slots = Vec::new();
12379        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12380            renderer
12381                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12382                .expect("write");
12383            slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
12384            assert_eq!(
12385                recorder
12386                    .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12387                    .expect("begin_frame wrote the block"),
12388                crcbl_shaders::tonemap::TonemapParams {
12389                    exposure: 3.5,
12390                    curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12391                    auto_exposure: false,
12392                    coverage_alpha: false,
12393                }
12394                .to_bytes(),
12395                "the frame's own block must carry the exposure in force",
12396            );
12397        }
12398        assert_ne!(
12399            slots[0], slots[1],
12400            "consecutive frames must not share a block"
12401        );
12402        assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
12403
12404        renderer.destroy(device.as_ref());
12405    }
12406
12407    /// **The curve reaches the block, and a caller can move it off the
12408    /// default.**
12409    ///
12410    /// The selector is a lane of the same ring the exposure rides in, and a lane
12411    /// nothing wrote would read as
12412    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
12413    /// whatever a caller asked for — a setter that compiles, a frame that looks
12414    /// right, and a curve that never runs. Since the renderer now *starts* on
12415    /// the fit, that failure would read as a working default, so the check runs
12416    /// in both directions: the untouched block carries the fit, and asking for
12417    /// the clamp changes the bytes on every frame of the ring.
12418    #[test]
12419    fn the_tonemap_block_carries_the_curve_a_caller_selected() {
12420        use crcbl_shaders::tonemap::TonemapCurve;
12421
12422        let (recorder, device, queue) = open();
12423        let mut renderer =
12424            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12425        let camera = Camera::default();
12426        let light = DirectionalLight::default();
12427
12428        assert_eq!(
12429            renderer.tonemap_curve(),
12430            TonemapCurve::Aces,
12431            "a renderer nobody configured must run the operator the goldens were blessed under",
12432        );
12433        renderer
12434            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12435            .expect("write");
12436        let by_default = recorder
12437            .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12438            .expect("begin_frame wrote the block");
12439
12440        renderer.set_tonemap_curve(TonemapCurve::Clamp);
12441        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
12442        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12443            renderer
12444                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12445                .expect("write");
12446            let written = recorder
12447                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12448                .expect("begin_frame wrote the block");
12449            assert_eq!(
12450                written,
12451                crcbl_shaders::tonemap::TonemapParams {
12452                    exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12453                    curve: TonemapCurve::Clamp,
12454                    auto_exposure: false,
12455                    coverage_alpha: false,
12456                }
12457                .to_bytes(),
12458                "every frame of the ring must carry the selected curve",
12459            );
12460            assert_ne!(
12461                written, by_default,
12462                "and it must differ from the block a default renderer writes",
12463            );
12464        }
12465
12466        // **A readout runs the clamp whatever was selected**, and the selection
12467        // survives it: the caller's curve is still the caller's, the frame's is
12468        // the identity, and the shaded frame after gets the curve back. Asked of
12469        // the fit, which is the selection a readout has something to lose under.
12470        renderer.set_tonemap_curve(TonemapCurve::Aces);
12471        renderer.set_normals_view(true);
12472        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
12473        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
12474        renderer
12475            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12476            .expect("write");
12477        assert_eq!(
12478            recorder
12479                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12480                .expect("begin_frame wrote the block"),
12481            crcbl_shaders::tonemap::TonemapParams {
12482                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12483                curve: TonemapCurve::Clamp,
12484                auto_exposure: false,
12485                coverage_alpha: false,
12486            }
12487            .to_bytes(),
12488            "a debug view's block must carry the clamp, since its pixels are data",
12489        );
12490        renderer.set_normals_view(false);
12491        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
12492
12493        renderer.destroy(device.as_ref());
12494    }
12495
12496    /// **The exposure is clamped where it is set**, so no caller can reach a
12497    /// frame it cannot get back from.
12498    ///
12499    /// Each case is a different way of leaving the range, and the NaN one is the
12500    /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
12501    /// propagates a NaN into the block, which is a frame of NaN pixels with no
12502    /// key to press to escape it.
12503    #[test]
12504    fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
12505        let (_, device, queue) = open();
12506        let mut renderer =
12507            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12508        assert!(
12509            (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
12510            "the default is {}",
12511            renderer.exposure(),
12512        );
12513
12514        for (asked, expected) in [
12515            (2.0, 2.0),
12516            (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
12517            (f32::INFINITY, EXPOSURE_MAX),
12518            (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
12519            (0.0, EXPOSURE_MIN),
12520            (-8.0, EXPOSURE_MIN),
12521            (f32::NEG_INFINITY, EXPOSURE_MIN),
12522            (f32::NAN, EXPOSURE_MIN),
12523        ] {
12524            renderer.set_exposure(asked);
12525            assert!(
12526                (renderer.exposure() - expected).abs() < f32::EPSILON,
12527                "{asked} was clamped to {}, not {expected}",
12528                renderer.exposure(),
12529            );
12530        }
12531
12532        renderer.destroy(device.as_ref());
12533    }
12534
12535    /// **The debug views resolve in one order, however they are set.**
12536    ///
12537    /// Every one of them rides in one float lane and the shaders test the
12538    /// outermost threshold first, so a renderer with two switches on draws
12539    /// exactly one picture — and which one has to be a rule rather than
12540    /// whichever branch a caller's setter happened to run last. Every
12541    /// combination of the switches is walked, because a precedence written as an
12542    /// `if` chain is right for most of them by accident: a chain in the wrong
12543    /// order agrees with this one on every combination where at most one switch
12544    /// is set.
12545    ///
12546    /// **The two innermost views are the exception the walk is worth most for.**
12547    /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
12548    /// it, so it resolves *last* and its sentinel runs the other way down the
12549    /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
12550    /// *off* sentinel, because it is a pass rather than a branch. Every
12551    /// combination where either is set beside a replacing view is a combination
12552    /// an order written any other way answers differently, and there is no
12553    /// single-switch case that could tell them apart.
12554    ///
12555    /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
12556    /// a panel reads back and the value the shader branches on cannot drift —
12557    /// they are the same function.
12558    #[test]
12559    fn the_debug_views_resolve_in_one_order_however_they_are_set() {
12560        // `w` of the second `float4` of the block — the lane
12561        // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
12562        // spells out, and for its reason.
12563        const AMBIENT_W: usize = 64 + 16 + 12;
12564
12565        let (recorder, device, queue) = open();
12566        let mut renderer =
12567            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12568        let camera = Camera::default();
12569        let light = DirectionalLight::default();
12570
12571        for bent in [false, true] {
12572            for motion in [false, true] {
12573                for occlusion in [false, true] {
12574                    for heatmap in [false, true] {
12575                        for lod in [false, true] {
12576                            for normals in [false, true] {
12577                                for (atlas, cascades) in
12578                                    [false, true].into_iter().flat_map(|atlas| {
12579                                        [false, true].map(|cascades| (atlas, cascades))
12580                                    })
12581                                {
12582                                    renderer.set_bent_normal_view(bent);
12583                                    renderer.set_motion_view(motion);
12584                                    renderer.set_occlusion_view(occlusion);
12585                                    renderer.set_heatmap(heatmap);
12586                                    renderer.set_lod_view(lod);
12587                                    renderer.set_normals_view(normals);
12588                                    renderer.set_atlas_view(atlas);
12589                                    renderer.set_cascade_view(cascades);
12590                                    let set = format!(
12591                                        "bent={bent} motion={motion} occlusion={occlusion} \
12592                                 heatmap={heatmap} lod={lod} normals={normals} \
12593                                 atlas={atlas} cascades={cascades}"
12594                                    );
12595                                    // Each switch reads back what it was set to, whatever
12596                                    // the others are: a caller's toggle is about the
12597                                    // caller's setting, and only `debug_view` is about the
12598                                    // picture.
12599                                    assert_eq!(renderer.bent_normal_view(), bent);
12600                                    assert_eq!(renderer.motion_view(), motion);
12601                                    assert_eq!(renderer.occlusion_view(), occlusion);
12602                                    assert_eq!(renderer.heatmap(), heatmap);
12603                                    assert_eq!(renderer.lod_view(), lod);
12604                                    assert_eq!(renderer.normals_view(), normals);
12605                                    assert_eq!(renderer.atlas_view(), atlas);
12606                                    assert_eq!(renderer.cascade_view(), cascades);
12607
12608                                    let expected = if bent {
12609                                        DebugView::BentNormal
12610                                    } else if motion {
12611                                        DebugView::Motion
12612                                    } else if occlusion {
12613                                        DebugView::AmbientOcclusion
12614                                    } else if heatmap {
12615                                        DebugView::Heatmap
12616                                    } else if lod {
12617                                        DebugView::LodTint
12618                                    } else if normals {
12619                                        DebugView::Normals
12620                                    } else if atlas {
12621                                        // **Below every replacing view above and
12622                                        // above the tint below**, which is the
12623                                        // half of this order no single-switch
12624                                        // case reaches: with a replacing view
12625                                        // also set the frame is that view's, and
12626                                        // with the tint also set the frame is the
12627                                        // atlas.
12628                                        DebugView::ShadowAtlas
12629                                    } else if cascades {
12630                                        // **Last, which is the half of this order a
12631                                        // chain in any other arrangement would get
12632                                        // right by accident.** The cascade tint is a
12633                                        // multiply on the shaded picture, so every
12634                                        // combination that also names a replacing
12635                                        // view has to resolve to *that* view — and
12636                                        // those are exactly the combinations an
12637                                        // `if cascades` written one line higher
12638                                        // would answer differently.
12639                                        DebugView::Cascades
12640                                    } else {
12641                                        DebugView::Shaded
12642                                    };
12643                                    assert_eq!(renderer.debug_view(), expected, "{set}");
12644
12645                                    renderer
12646                                        .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12647                                        .expect("write");
12648                                    let block = recorder
12649                                        .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12650                                        .expect("begin_frame wrote the block");
12651                                    let sentinel = match expected {
12652                                        DebugView::BentNormal => {
12653                                            mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
12654                                        }
12655                                        DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
12656                                        DebugView::AmbientOcclusion => {
12657                                            mesh::FrameUniforms::OCCLUSION_VIEW_ON
12658                                        }
12659                                        DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
12660                                        DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
12661                                        DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
12662                                        DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
12663                                        // **The atlas view carries the *off*
12664                                        // sentinel**, which is what makes this
12665                                        // assertion say something rather than
12666                                        // restate `debug_view_lane`: the colour
12667                                        // pass draws the shaded picture and
12668                                        // `crate::atlas_view`'s pass replaces
12669                                        // it, so a lane of its own here would be
12670                                        // a threshold no shader tests.
12671                                        DebugView::ShadowAtlas | DebugView::Shaded => {
12672                                            mesh::FrameUniforms::NORMALS_VIEW_OFF
12673                                        }
12674                                    };
12675                                    assert_eq!(
12676                                        &block[AMBIENT_W..AMBIENT_W + 4],
12677                                        &sentinel.to_le_bytes(),
12678                                        "{set} resolved to {expected:?}, and the lane says otherwise"
12679                                    );
12680                                    // And the resolve comes off for every one of them:
12681                                    // these frames are read back as data, so their colours
12682                                    // have to stay the ones the shader wrote — see
12683                                    // `resolved_effects`. The whole slot rather than one
12684                                    // tier of it, because which tier the default carries
12685                                    // is not what this is about.
12686                                    assert_eq!(
12687                                        renderer.effects().intersects(Antialiasing::SLOT),
12688                                        expected == DebugView::Shaded,
12689                                        "{set}"
12690                                    );
12691                                }
12692                            }
12693                        }
12694                    }
12695                }
12696            }
12697        }
12698
12699        renderer.destroy(device.as_ref());
12700    }
12701
12702    /// **The atlas viewer records one pass, and only on the frame it is the view
12703    /// showing.**
12704    ///
12705    /// The mechanism no other check in this file can see. Every other debug view
12706    /// is a lane of the frame block, so
12707    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
12708    /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
12709    /// is a claim about the command stream and about nothing else. A switch that
12710    /// resolved correctly and recorded nothing would satisfy every other
12711    /// assertion in this module and draw the frame unchanged.
12712    ///
12713    /// Three arms, and the third is the one that makes the first two mean
12714    /// something:
12715    ///
12716    /// * off — no pass at all, which is what makes the off position
12717    ///   bit-identical for every golden in this workspace;
12718    /// * on — the pass, with the full-screen triangle in it;
12719    /// * on **beside a replacing view** — no pass, because
12720    ///   [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
12721    ///   not what this frame draws. That is the half a `self.atlas_view` read at
12722    ///   the recording site would get wrong while passing both arms above.
12723    ///
12724    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
12725    /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
12726    /// the draw count follows.**
12727    ///
12728    /// The viewer fills every display pixel with a `DontCare` load, so a
12729    /// tonemapped frame or a grid recorded under it is stored and discarded.
12730    /// The pass counts go red if either comes back; the counter goes red if
12731    /// `counters` still charges the frame for the triangles it no longer
12732    /// records.
12733    #[test]
12734    fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
12735        let (recorder, device, queue) = open();
12736        let mut renderer =
12737            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12738        renderer
12739            .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
12740            .expect("the null backend builds every pipeline");
12741        renderer.set_atlas_view(true);
12742        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12743
12744        let viewing = frame(device.as_ref(), &mut renderer, queue);
12745        let opened = |label: &str| {
12746            recorder
12747                .commands()
12748                .iter()
12749                .filter(|command| {
12750                    matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
12751                })
12752                .count()
12753        };
12754        assert_eq!(opened(crate::atlas_view::LABEL), 1);
12755        assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
12756        assert_eq!(opened("grid"), 0, "and the grid drawn over it");
12757        assert_eq!(
12758            renderer.counters().draws,
12759            recorded_draws(&recorder) as u64,
12760            "the counter charges the frame for exactly the draws it recorded"
12761        );
12762        viewing.finish(device.as_ref(), renderer);
12763    }
12764
12765    #[test]
12766    fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
12767        use crcbl_hal::null::Command;
12768
12769        let (recorder, device, queue) = open();
12770        let device = device.as_ref();
12771        let mut renderer =
12772            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
12773        let (camera, sun) = (Camera::default(), DirectionalLight::default());
12774
12775        // How many times the viewer's pass was opened since `from`, which is
12776        // where the previous arm's commands ended.
12777        let opened = |from: usize| {
12778            recorder.commands()[from..]
12779                .iter()
12780                .filter(|command| {
12781                    matches!(
12782                        command.opens_pass(),
12783                        Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
12784                    )
12785                })
12786                .count()
12787        };
12788
12789        let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12790        assert_eq!(
12791            opened(0),
12792            0,
12793            "a frame drawing the shaded picture recorded the atlas viewer's pass"
12794        );
12795        let after_shaded = recorder.commands().len();
12796        shaded.release(device);
12797
12798        renderer.set_atlas_view(true);
12799        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12800        let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12801        assert_eq!(
12802            opened(after_shaded),
12803            1,
12804            "the atlas viewer is on and its pass was not recorded exactly once"
12805        );
12806        // And what it recorded is the over-sized triangle and nothing else: a
12807        // pass that bound a pipeline and drew no vertices would open above and
12808        // leave the frame the tonemap wrote.
12809        let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
12810            .into_iter()
12811            .filter_map(|command| match command {
12812                Command::Draw {
12813                    vertices,
12814                    instances,
12815                } => Some((
12816                    vertices.end - vertices.start,
12817                    instances.end - instances.start,
12818                )),
12819                _ => None,
12820            })
12821            .collect();
12822        assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
12823        let after_viewing = recorder.commands().len();
12824        viewing.release(device);
12825
12826        // The switch left on, and a replacing view asked for over the top of it.
12827        renderer.set_normals_view(true);
12828        assert_eq!(
12829            renderer.debug_view(),
12830            DebugView::Normals,
12831            "the atlas view does not lose to a replacing view, so the arm below asks nothing"
12832        );
12833        let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12834        assert_eq!(
12835            opened(after_viewing),
12836            0,
12837            "the frame resolved to the normals view and still recorded the atlas viewer's \
12838             pass over the top of it"
12839        );
12840        normals.release(device);
12841
12842        renderer.destroy(device);
12843    }
12844
12845    /// **The heatmap moves the ambient's last lane and no other byte**, and
12846    /// switching it off puts the block back.
12847    ///
12848    /// The normals view's assertion below, for the outermost of the three: the
12849    /// overlay costs one lane, so every golden image ever blessed is untouched
12850    /// by the feature existing. The `lod_params` row the heatmap reads is
12851    /// written every frame whether it is on or not — it is the numbers the
12852    /// selection used — so this compares two frames of the *same* camera and
12853    /// budget, where that row is equal on both sides and any byte outside the
12854    /// lane is a real difference.
12855    #[test]
12856    fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
12857        const AMBIENT_W: usize = 64 + 16 + 12;
12858
12859        // Held for the whole comparison, and it is not this check's own knob:
12860        // `r_shadow_filter` and `r_shadow_split` land in the block's
12861        // `shadow_filter` row on every `begin_frame`, and the filter checks in
12862        // this module move them under this lock while `cargo test` runs the
12863        // module's checks as threads of one process. Two frames read either side
12864        // of such a move differ at that row, which is outside every lane below —
12865        // one run in twelve, measured 2026-09-04.
12866        let _filter = shadow_filter_switch();
12867        let (recorder, device, queue) = open();
12868        let mut renderer =
12869            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12870        let camera = Camera::default();
12871        let light = DirectionalLight::default();
12872        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12873            renderer
12874                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12875                .expect("write");
12876            recorder
12877                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12878                .expect("begin_frame wrote the block")
12879        };
12880
12881        assert!(
12882            !renderer.heatmap(),
12883            "the heatmap has to be off in a renderer nobody has asked",
12884        );
12885        let shaded = block(&mut renderer);
12886        assert_eq!(
12887            &shaded[AMBIENT_W..AMBIENT_W + 4],
12888            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12889            "an untouched renderer must write the value every golden image was blessed with",
12890        );
12891
12892        renderer.set_heatmap(true);
12893        let heatmap = block(&mut renderer);
12894        assert_eq!(
12895            &heatmap[AMBIENT_W..AMBIENT_W + 4],
12896            &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
12897            "the switch has to reach the lane the mesh stage branches on",
12898        );
12899        let outside: Vec<usize> = shaded
12900            .iter()
12901            .zip(heatmap.iter())
12902            .enumerate()
12903            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
12904            .map(|(at, _)| at)
12905            .collect();
12906        assert!(
12907            outside.is_empty(),
12908            "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
12909        );
12910
12911        renderer.set_heatmap(false);
12912        assert_eq!(
12913            block(&mut renderer),
12914            shaded,
12915            "switching the view off has to put the block back, not just stop reporting it",
12916        );
12917
12918        renderer.destroy(device.as_ref());
12919    }
12920
12921    /// **The normals view moves one lane of the frame block and nothing else.**
12922    ///
12923    /// The mechanism, at the level a null device can observe it: which bytes of
12924    /// the buffer `mesh.slang` reads changed. A field on the renderer would say
12925    /// only that a flag moved; the block is what the shader actually branches on.
12926    ///
12927    /// Four claims, and each rules out a different way of passing wrongly:
12928    ///
12929    /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
12930    ///   is what makes every golden image untouched by this feature;
12931    /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
12932    ///   shader reads, at the offset `std140` puts it at rather than at one this
12933    ///   test picked;
12934    /// * **those four bytes are the only ones that moved**, so the switch did not
12935    ///   come at the cost of the ambient colour beside it or of any matrix;
12936    /// * and switching off puts the block back exactly, so the view is a toggle
12937    ///   rather than a one-way door.
12938    ///
12939    /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
12940    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
12941    #[test]
12942    fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
12943        // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
12944        // then three floats of ambient colour. Spelled as the sum rather than as
12945        // `92` so that a member arriving before it is a compile-time question
12946        // about `FrameUniforms`' own layout and not a silent read of a matrix.
12947        const AMBIENT_W: usize = 64 + 16 + 12;
12948
12949        // Held for the whole comparison, and it is not this check's own knob:
12950        // `r_shadow_filter` and `r_shadow_split` land in the block's
12951        // `shadow_filter` row on every `begin_frame`, and the filter checks in
12952        // this module move them under this lock while `cargo test` runs the
12953        // module's checks as threads of one process. Two frames read either side
12954        // of such a move differ at that row, which is outside every lane below —
12955        // one run in twelve, measured 2026-09-04.
12956        let _filter = shadow_filter_switch();
12957        let (recorder, device, queue) = open();
12958        let mut renderer =
12959            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12960        let camera = Camera::default();
12961        let light = DirectionalLight::default();
12962        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12963            renderer
12964                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12965                .expect("write");
12966            recorder
12967                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12968                .expect("begin_frame wrote the block")
12969        };
12970
12971        assert!(
12972            !renderer.normals_view(),
12973            "the normals view has to be off in a renderer nobody has asked",
12974        );
12975        let shaded = block(&mut renderer);
12976        assert_eq!(
12977            &shaded[AMBIENT_W..AMBIENT_W + 4],
12978            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12979            "an untouched renderer must write the value every golden image was blessed with",
12980        );
12981
12982        renderer.set_normals_view(true);
12983        assert!(renderer.normals_view());
12984        let normals = block(&mut renderer);
12985        assert_eq!(
12986            &normals[AMBIENT_W..AMBIENT_W + 4],
12987            &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
12988            "the switch has to reach the lane the fragment stage branches on",
12989        );
12990        // The bytes that moved, and they all have to be inside the lane — not
12991        // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
12992        // and an equality against the whole range would be a test about IEEE 754
12993        // rather than about the block.
12994        let outside: Vec<usize> = shaded
12995            .iter()
12996            .zip(normals.iter())
12997            .enumerate()
12998            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
12999            .map(|(at, _)| at)
13000            .collect();
13001        assert!(
13002            outside.is_empty(),
13003            "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13004        );
13005
13006        renderer.set_normals_view(false);
13007        assert!(!renderer.normals_view());
13008        assert_eq!(
13009            block(&mut renderer),
13010            shaded,
13011            "switching the view off has to put the block back, not just stop reporting it",
13012        );
13013
13014        renderer.destroy(device.as_ref());
13015    }
13016
13017    /// **A frame uploads the instances a caller moved, and a frame nobody moved
13018    /// anything in uploads nothing at all.**
13019    ///
13020    /// The second half is the stronger claim and it is the one that needed the
13021    /// cube to become an ordinary instance: `begin_frame` used to take the
13022    /// cube's transform as an argument and write it into the pool every frame,
13023    /// so that slot was dirty in every ring slot forever and a motionless scene
13024    /// paid a spinning one's transfer. The bytes were identical, so no golden
13025    /// image could ever have shown it — the recorder's write log is the only
13026    /// place the difference is visible.
13027    ///
13028    /// The pyramid is here so that "only the one that moved" is a claim about a
13029    /// choice: with one instance in the array, uploading it and uploading
13030    /// everything are the same event.
13031    #[test]
13032    fn only_the_instance_that_moved_is_uploaded() {
13033        let (recorder, device, queue) = open();
13034        let mut renderer =
13035            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13036        let instance_buffers = renderer.instances.buffers().to_vec();
13037        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13038        place_demo(
13039            &mut renderer,
13040            DEMO_PYRAMID,
13041            DEMO_UNTINTED,
13042            Mat4::from_translation(Vec3::X),
13043        );
13044
13045        // Both instances are dirty in *every* slot when they are inserted, so
13046        // the first frames upload both however well delta upload works. The ring
13047        // has to be walked right through before an upload is evidence about the
13048        // delta rather than about initialisation.
13049        let frame = |renderer: &mut ForwardRenderer| {
13050            renderer
13051                .begin_frame(
13052                    device.as_ref(),
13053                    &Camera::default(),
13054                    &DirectionalLight::default(),
13055                    (64, 48),
13056                )
13057                .expect("write");
13058        };
13059        for _ in 0..FRAMES_IN_FLIGHT {
13060            frame(&mut renderer);
13061        }
13062        let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13063            recorder
13064                .events()
13065                .into_iter()
13066                .skip(from)
13067                .filter_map(|event| match event {
13068                    crcbl_hal::null::Event::BufferWritten {
13069                        buffer,
13070                        offset,
13071                        len,
13072                    } if instance_buffers.contains(&buffer) => Some((offset, len)),
13073                    _ => None,
13074                })
13075                .collect()
13076        };
13077
13078        let before = recorder.events().len();
13079        frame(&mut renderer);
13080        assert_eq!(
13081            instance_writes(before),
13082            [],
13083            "a frame in which nothing moved must upload no instance bytes at all"
13084        );
13085
13086        let before = recorder.events().len();
13087        let model = ForwardRenderer::spin(1.25);
13088        renderer.set_instance(
13089            cube,
13090            &InstanceDesc {
13091                mesh: DEMO_CUBE,
13092                material: DEMO_UNTINTED,
13093                transform: model,
13094            },
13095        );
13096        frame(&mut renderer);
13097        assert_eq!(
13098            renderer
13099                .instances
13100                .get(cube)
13101                .expect("the cube is live")
13102                .transform,
13103            model.to_cols_array(),
13104            "the model matrix must land in the instance, not the uniform block"
13105        );
13106        let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13107            * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13108        assert_eq!(
13109            instance_writes(before),
13110            [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13111            "a steady-state frame must upload exactly the one instance that changed"
13112        );
13113
13114        renderer.destroy(device.as_ref());
13115        recorder.assert_valid();
13116    }
13117
13118    /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13119    /// it back for the next object to reuse.**
13120    ///
13121    /// The three-call bookkeeping every caller of the instance API depends on,
13122    /// checked on the pool rather than on the recorder. A `set_instance` that
13123    /// inserted instead would take a fresh slot per call — the pool exhausted in
13124    /// a few thousand frames of a caller that writes a transform per frame, which
13125    /// is what every sample does — and every slot it abandoned would stay
13126    /// **live**, so the frame would draw a copy of the object at each transform
13127    /// it had ever been given. Neither is something a golden image would show
13128    /// until the pool ran out.
13129    ///
13130    /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13131    /// reads the recorder; this is the bookkeeping half and reads the pool, which
13132    /// is where an abandoned slot would still be counted.
13133    ///
13134    /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13135    /// slot carries topic 25's hysteresis state — the reuse below is
13136    /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13137    /// previous occupant's expanded groups.
13138    #[test]
13139    fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13140        for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13141            let (recorder, device, queue) = open();
13142            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13143                .expect("built");
13144            // The null backend takes an indirect tail, so the DAG is placeable
13145            // here; the arm that cannot select a level refuses before an
13146            // application ever calls this.
13147            assert!(
13148                renderer.selects_levels(),
13149                "an indirect tail chooses a level for every mesh, DAG included"
13150            );
13151            // What the pool holds before anything is placed, which is nothing: a
13152            // renderer places no object of its own any more.
13153            let resident = renderer.instances.len();
13154            assert_eq!(resident, 0, "a fresh renderer holds no objects");
13155
13156            let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13157            let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13158            assert_eq!(
13159                renderer.instances.len(),
13160                resident + 1,
13161                "mesh {mesh}: add_instance takes one slot"
13162            );
13163
13164            // The rewrite is the whole test: the same handle, the same slot
13165            // count, and the new transform in it.
13166            let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13167            renderer.set_instance(
13168                handle,
13169                &InstanceDesc {
13170                    mesh,
13171                    material: DEMO_UNTINTED,
13172                    transform: second,
13173                },
13174            );
13175            assert_eq!(
13176                renderer.instances.len(),
13177                resident + 1,
13178                "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13179            );
13180            assert_eq!(
13181                renderer.instances.slot_count(),
13182                u32::try_from(resident + 1).expect("a handful of instances"),
13183                "mesh {mesh}: set_instance must not have reached past the slot it holds"
13184            );
13185            assert_eq!(
13186                renderer
13187                    .instances
13188                    .get(handle)
13189                    .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13190                    .transform,
13191                second.to_cols_array(),
13192                "mesh {mesh}: set_instance must have written the second transform"
13193            );
13194
13195            // And a removal gives the slot back, so a caller toggling an object
13196            // is not a leak either.
13197            renderer.remove_instance(handle);
13198            assert_eq!(
13199                renderer.instances.len(),
13200                resident,
13201                "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13202            );
13203            place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13204            assert_eq!(
13205                renderer.instances.slot_count(),
13206                u32::try_from(resident + 1).expect("a handful of instances"),
13207                "mesh {mesh}: the object after a removal must reuse the freed slot"
13208            );
13209
13210            renderer.destroy(device.as_ref());
13211            recorder.assert_valid();
13212        }
13213    }
13214
13215    /// **The description resolves to the ids the renderer used to hand itself**:
13216    /// one table entry per description mesh, in description order, with the DAG
13217    /// occupying one per level after them — and every level's vertex base
13218    /// measured from level 0's, which is zero.
13219    ///
13220    /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13221    /// box out of the entry the *instance* names. So a description walked in
13222    /// another order, or a DAG whose levels landed among the flat meshes, would
13223    /// leave every instance naming a mesh that is not its own: the cube culled
13224    /// against the pyramid's box, the dunes patch drawn as an open box. Every
13225    /// one of those is a frame that still looks like a frame.
13226    ///
13227    /// The bases are asserted against the table bytes rather than against
13228    /// `ResidentMesh`, because the table is what the GPU reads.
13229    #[test]
13230    fn the_description_resolves_to_the_ids_it_was_written_in() {
13231        let (recorder, device, queue) = open();
13232        let renderer =
13233            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13234
13235        assert_eq!(
13236            renderer.mesh_ids,
13237            [0, 1, 2, 3],
13238            "the four description meshes take the first four table entries, in order"
13239        );
13240
13241        // The DAG's coarser levels follow level 0, so a cut that spans them
13242        // reads entries the flat meshes never occupied.
13243        let scene = scene::demo();
13244        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13245            panic!("the demo description's fourth mesh is the DAG");
13246        };
13247        let level_ids: Vec<u32> = (0..dag.levels.len())
13248            .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13249            .collect();
13250        assert!(
13251            level_ids
13252                .iter()
13253                .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13254            "every dunes level is past the flat residents: {level_ids:?}"
13255        );
13256
13257        // **Level 0 is at the pool's own first vertex**, which is what makes
13258        // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13259        // sum the mesh stage forms with the instance's own base.
13260        let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13261            .iter()
13262            .map(|&id| mesh_entry(&recorder, &renderer, id))
13263            .collect();
13264        let level_zero = entries[0].base_vertex;
13265        assert_eq!(
13266            level_zero,
13267            mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13268                + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13269            "the DAG starts where the last flat resident ends"
13270        );
13271        let bases: Vec<u32> = entries
13272            .iter()
13273            .map(|entry| {
13274                entry
13275                    .base_vertex
13276                    .checked_sub(level_zero)
13277                    .expect("a level below level 0 would wrap the offset a cluster carries")
13278            })
13279            .collect();
13280        assert_eq!(
13281            bases[0], 0,
13282            "level 0 is the base every other is measured from"
13283        );
13284        assert!(
13285            bases.windows(2).all(|pair| pair[0] < pair[1]),
13286            "each level starts past the one below it: {bases:?}"
13287        );
13288
13289        renderer.destroy(device.as_ref());
13290        recorder.assert_valid();
13291    }
13292
13293    /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13294    ///
13295    /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13296    /// number of DAGs, and until this nothing had put either through it — every
13297    /// golden image and every end-to-end run is `scene::demo()`, whose four
13298    /// meshes hold one DAG between them.
13299    ///
13300    /// What only a second DAG exercises is the **concatenation**: `level_groups`
13301    /// is every DAG's groups laid end to end and a DAG reaches its own run
13302    /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13303    /// which is zero for the first one and therefore invisible while there is
13304    /// only one. A second DAG whose records still named the first's groups would
13305    /// descend a hierarchy belonging to another surface — a cut that is a
13306    /// plausible picture and matches no assertion the CPU makes about the frame.
13307    ///
13308    /// On the mesh path, because that is where the offset is *used*: an indirect
13309    /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13310    ///
13311    /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13312    #[test]
13313    fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13314        use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13315
13316        let recorder = Recorder::new();
13317        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13318
13319        // The engine has one DAG, so a second one is a second copy of it. That
13320        // is the whole point: two DAGs whose *groups* are alike is the case
13321        // where reaching the wrong run still produces a cut, and so the case a
13322        // frame comparison could never catch.
13323        let mut scene = scene::demo();
13324        let mut again = scene.meshes[DEMO_DUNES].clone();
13325        again.label = "dunes again".into();
13326        scene.meshes.push(again);
13327        // Room for the second copy. Doubling rather than measuring, because the
13328        // number that matters is that the description carries its own sizes at
13329        // all — see `Capacities`, which is the caller's to choose.
13330        scene.capacities.vertices *= 2;
13331        scene.capacities.indices *= 2;
13332        let second_dag = scene.meshes.len() - 1;
13333
13334        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13335            panic!("the demo description's fourth mesh is the DAG");
13336        };
13337        let levels = dag.levels.len();
13338        let groups = dag.level_groups().len();
13339        assert!(groups > 0, "a DAG with no groups would select nothing");
13340
13341        let mut renderer =
13342            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13343                .expect("a five-mesh description with two DAGs is one this can make resident");
13344
13345        // Every level of both is its own table entry, laid down in description
13346        // order, so the second DAG's level 0 is a whole hierarchy past the
13347        // first's.
13348        assert_eq!(
13349            renderer.mesh_ids.len(),
13350            scene.meshes.len(),
13351            "one id per description mesh, whatever the count"
13352        );
13353        assert_eq!(
13354            renderer.mesh_ids[second_dag],
13355            renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13356            "the second DAG's level 0 starts past every level of the first"
13357        );
13358
13359        // **The hysteresis state is per instance per resident group**, and
13360        // `group_stride` is what says how many groups that is. One DAG made this
13361        // number a single hierarchy's; two is what tells a stride that sums from
13362        // one that took the first answer it found.
13363        assert_eq!(
13364            renderer.primary.draws.group_stride(),
13365            u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13366            "every resident DAG's groups are in the stride, not just the first's"
13367        );
13368
13369        // The records themselves: which group each cluster produces and which
13370        // contains it, as the amplification stage reads them.
13371        let clusters = renderer
13372            .clusters
13373            .as_ref()
13374            .expect("the mesh path builds a cluster pool");
13375        let selection = recorder
13376            .buffer_bytes(clusters.selection())
13377            .expect("the selection records are live");
13378        // Entries are laid down in description order, a flat mesh taking one and
13379        // a DAG one per level — so the second DAG's start a hierarchy past the
13380        // first's, which start past the three flat residents.
13381        let first_entry = DEMO_DUNES;
13382        let record = |entry: usize| -> Vec<ClusterSelect> {
13383            let range = clusters.range(entry).expect("one range per entry");
13384            (range.base..range.base + range.count)
13385                .map(|cluster| {
13386                    let at = cluster as usize * CLUSTER_SELECT_STRIDE;
13387                    ClusterSelect::from_bytes(
13388                        selection[at..at + CLUSTER_SELECT_STRIDE]
13389                            .try_into()
13390                            .expect("one whole record"),
13391                    )
13392                })
13393                .collect()
13394        };
13395        // The named group of every record that has one, per DAG — and the count,
13396        // because a comparison over an empty set is a check that cannot fail.
13397        let named = |base: usize| -> Vec<u32> {
13398            (base..base + levels)
13399                .flat_map(record)
13400                .flat_map(|select| {
13401                    let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
13402                        .then_some(select.producer_group);
13403                    let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
13404                        .then_some(select.container_group);
13405                    producer.into_iter().chain(container)
13406                })
13407                .collect()
13408        };
13409        let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
13410        let first = named(first_entry);
13411        let second = named(first_entry + levels);
13412        assert!(
13413            !first.is_empty() && first.len() == second.len(),
13414            "the two copies must name the same number of groups: {} against {}",
13415            first.len(),
13416            second.len()
13417        );
13418        assert!(
13419            first.iter().all(|&group| group < boundary),
13420            "the first DAG's records stay inside its own run: {first:?}"
13421        );
13422        assert!(
13423            second
13424                .iter()
13425                .all(|&group| (boundary..boundary * 2).contains(&group)),
13426            "the second DAG's records must name the groups past the first's, and \
13427             `first_group` is the only thing that puts them there: {second:?}"
13428        );
13429
13430        // And both are placeable through the runtime API, which is what a
13431        // description of a shape no `set_*` method names is *for*.
13432        let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
13433            renderer
13434                .add_instance(&InstanceDesc {
13435                    mesh,
13436                    material: DEMO_UNTINTED,
13437                    transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
13438                })
13439                .expect("the pool has room")
13440        };
13441        let near = place(&mut renderer, DEMO_DUNES, -64.0);
13442        let far = place(&mut renderer, second_dag, 64.0);
13443        let index = |handle| {
13444            renderer
13445                .instances
13446                .index(handle)
13447                .expect("a just-added instance is live")
13448        };
13449        assert_ne!(
13450            index(near),
13451            index(far),
13452            "two instances take two slots, and the index is the hysteresis key"
13453        );
13454        assert_eq!(
13455            renderer.instances.get(far).expect("live").mesh,
13456            renderer.mesh_ids[second_dag],
13457            "an InstanceDesc's mesh index resolves through the description, not through \
13458             a table id the caller cannot know"
13459        );
13460
13461        renderer.destroy(device.as_ref());
13462        recorder.assert_valid();
13463    }
13464
13465    /// **A description the renderer cannot make resident is refused before the
13466    /// first device object exists**, so a rejection leaks nothing.
13467    ///
13468    /// `build` hands the geometry pool and the material table to the rollback
13469    /// and then creates a dozen objects with `?` between them. A check that ran
13470    /// part way down that list would be a new early exit on the wrong side of a
13471    /// handover, and the pool would go with it — which is exactly the leak
13472    /// `Rollback` exists to prevent and which
13473    /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
13474    /// only walks the happy path.
13475    ///
13476    /// Each arm below is a *different* refusal, so a check that stopped running
13477    /// would show up as one arm leaking rather than as all of them — and each
13478    /// names a fragment of the message it must be refused *with*, or an arm
13479    /// would pass on some other check's answer.
13480    /// **A description with no meshes is refused by name**, before anything
13481    /// is created, rather than reaching the mesh table's sizing with nothing
13482    /// to size it from.
13483    #[test]
13484    fn a_scene_with_no_meshes_is_refused_by_name() {
13485        let (recorder, device, queue) = open();
13486        let before = recorder.total_live_objects();
13487        let mut scene = scene::demo();
13488        scene.meshes.clear();
13489        let error =
13490            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13491                .expect_err("a scene of no meshes must be refused");
13492        assert!(
13493            error.to_string().contains("at least one mesh"),
13494            "the refusal says what is missing: {error}"
13495        );
13496        assert_eq!(
13497            recorder.total_live_objects(),
13498            before,
13499            "the refusal created something"
13500        );
13501    }
13502
13503    #[test]
13504    fn a_refused_description_creates_nothing_at_all() {
13505        /// One way of writing a description the renderer cannot build, and the
13506        /// words that say it was this refusal rather than another.
13507        type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
13508
13509        let cases: [Break; 9] = [
13510            (
13511                "a row naming a layer the page has not got",
13512                |scene| {
13513                    scene.materials[DEMO_TEXTURED].base_color_texture = 7;
13514                },
13515                "material row 2 samples base-colour page layer 7",
13516            ),
13517            // And the same on the two kinds rung 3 added, because `check_scene`
13518            // reads a different column of the row for each: a check written per
13519            // kind is only worth what its arms cover, and a column nobody broke
13520            // here could be read out of the wrong material field for ever.
13521            // `demo` names no layer of either, so any index at all is past the
13522            // end.
13523            (
13524                "a row naming a packed-page layer the page has not got",
13525                |scene| {
13526                    scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
13527                },
13528                "material row 2 samples metallic-roughness-occlusion page layer 3",
13529            ),
13530            (
13531                "a row naming an emissive layer the page has not got",
13532                |scene| {
13533                    scene.materials[DEMO_TEXTURED].emissive_texture = 3;
13534                },
13535                "material row 2 samples emissive page layer 3",
13536            ),
13537            // The one page refusal a caller can actually spell: `push_layer`
13538            // takes bytes it cannot measure against the extent.
13539            (
13540                "a page layer of the wrong length",
13541                |scene| {
13542                    scene.page = scene::PageDesc::empty();
13543                    scene
13544                        .page
13545                        .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
13546                    scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
13547                    scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
13548                },
13549                "base-colour page layer 0 carries 4 bytes",
13550            ),
13551            (
13552                "a DAG level with no vertices",
13553                |scene| {
13554                    let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
13555                    else {
13556                        panic!("the demo description's fourth mesh is the DAG");
13557                    };
13558                    levels.pop();
13559                },
13560                "vertex array(s) for a DAG of",
13561            ),
13562            // The four capacities, each of which is a pool a caller sized and
13563            // a description outgrew. Written as a capacity the description is
13564            // too large for rather than as a description too large for the
13565            // default, because that is the shape of the mistake: the numbers on
13566            // `Capacities` are the ones an application picks.
13567            (
13568                "more vertices than the pool holds",
13569                |scene| {
13570                    scene.capacities.vertices = 1;
13571                },
13572                "the vertex pool holds 1 and the description needs",
13573            ),
13574            (
13575                "more indices than the pool holds",
13576                |scene| {
13577                    scene.capacities.indices = 1;
13578                },
13579                "the index pool holds 1 and the description needs",
13580            ),
13581            (
13582                "more meshes than the table holds",
13583                |scene| {
13584                    scene.capacities.meshes = 1;
13585                },
13586                "the mesh table holds 1 and the description needs",
13587            ),
13588            (
13589                "more material rows than the table holds",
13590                |scene| {
13591                    scene.capacities.materials = 2;
13592                },
13593                "the material table holds 2 and the description needs 3",
13594            ),
13595        ];
13596
13597        for (what, break_it, says) in cases {
13598            let (recorder, device, queue) = open();
13599            let before = recorder.total_live_objects();
13600            let mut scene = scene::demo();
13601            break_it(&mut scene);
13602            let error =
13603                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13604                    .expect_err(&format!("{what} must be refused"));
13605            assert!(
13606                matches!(error, HalError::InvalidDescriptor(_)),
13607                "{what} must be refused as an invalid descriptor, not as {error:?}"
13608            );
13609            assert!(
13610                error.to_string().contains(says),
13611                "{what} must be refused with a message saying so, and this one says {error}"
13612            );
13613            assert_eq!(
13614                recorder.total_live_objects(),
13615                before,
13616                "{what} was refused after something had been created, and the rollback \
13617                 is the only thing that could have released it"
13618            );
13619            recorder.assert_valid();
13620        }
13621
13622        // **And the refusal that is not free**, which is the half of the
13623        // handover every arm above walks past: `check_scene` settles what the
13624        // whole description says, and what one mesh's *bytes* say is the pool's,
13625        // which only sees them one upload at a time. Vertex bytes that are not a
13626        // whole number of vertices reach `MeshPool::upload` — so the third of
13627        // the four meshes is refused with the pool created, two device-local
13628        // buffers in it and the first two meshes already staged into them.
13629        // `build_geometry` is what releases that, and it can only do so because
13630        // the pool is not the rollback's until it has returned.
13631        let (recorder, device, queue) = open();
13632        let before = recorder.total_live_objects();
13633        // So the count below is this build's and not `open`'s.
13634        recorder.clear();
13635        let mut scene = scene::demo();
13636        let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
13637            panic!("the demo description's third mesh is flat");
13638        };
13639        vertices.to_mut().push(0);
13640        let error =
13641            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13642                .expect_err("a mesh of part of a vertex must be refused");
13643        assert!(
13644            error.to_string().contains("is not a whole number of"),
13645            "the pool's own refusal reaches the caller with its numbers, and this \
13646             one says {error}"
13647        );
13648        assert!(
13649            recorder
13650                .events()
13651                .iter()
13652                .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
13653            "this arm is evidence about the rollback only if the refusal came after \
13654             something had been created"
13655        );
13656        assert_eq!(
13657            recorder.total_live_objects(),
13658            before,
13659            "a mesh refused part way through the list left the geometry pool behind, \
13660             which is exactly what `build_geometry` being self-cleaning is for"
13661        );
13662        recorder.assert_valid();
13663    }
13664
13665    /// **The one capacity a description cannot be checked against, and the one
13666    /// an application is expected to handle while it runs.**
13667    ///
13668    /// Every other number on [`scene::Capacities`] sizes something the
13669    /// description fills once, so `check_scene` refuses an over-large one before
13670    /// a device object exists. Objects are placed at any point in a renderer's
13671    /// life, so the only honest answer for that one is the error
13672    /// [`ForwardRenderer::add_instance`] returns — and it returns
13673    /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
13674    /// what is in it survive to the caller that chose them.
13675    ///
13676    /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
13677    /// value of its own rather than the default, which is what makes the pool
13678    /// fillable at all: a renderer that ignored the number the description
13679    /// carries and reserved the default would draw every frame in the tree
13680    /// identically and refuse nothing here.
13681    #[test]
13682    fn a_full_instance_pool_reaches_the_application_that_sized_it() {
13683        let (recorder, device, queue) = open();
13684        let mut scene = scene::demo();
13685        scene.capacities.instances = 2;
13686        let mut renderer =
13687            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13688                .expect("a scene with room for two objects builds");
13689        let place = |renderer: &mut ForwardRenderer| {
13690            renderer.add_instance(&InstanceDesc {
13691                mesh: DEMO_CUBE,
13692                material: DEMO_UNTINTED,
13693                transform: Mat4::IDENTITY,
13694            })
13695        };
13696        place(&mut renderer).expect("the first of two");
13697        place(&mut renderer).expect("the second of two");
13698        let error = place(&mut renderer).expect_err("a third object has no slot to go in");
13699        assert!(
13700            matches!(
13701                error,
13702                InstancePoolError::PoolFull {
13703                    capacity: 2,
13704                    in_use: 2
13705                }
13706            ),
13707            "a full pool must reach the caller as a full pool, with the capacity it \
13708             chose; this arrived as {error}"
13709        );
13710        renderer.destroy(device.as_ref());
13711        recorder.assert_valid();
13712    }
13713
13714    /// **One mesh and one material row is a scene, and it draws.**
13715    ///
13716    /// The floor is gone. `with_scene` used to refuse anything shorter than
13717    /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
13718    /// demo wrappers named those entries by position, and the renderer's own
13719    /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
13720    /// `DEMO_DUNES` besides. So an application's own description was not merely
13721    /// refused: with the check removed it would have panicked out of `build`.
13722    ///
13723    /// A frame is recorded rather than only a build, because that is where the
13724    /// positional indexing was: the bucket table, the cluster ranges and the
13725    /// draw-argument blocks are all one-per-description-mesh, and a renderer that
13726    /// still assumed four would come apart here rather than at `with_scene`.
13727    #[test]
13728    fn a_description_smaller_than_the_demo_is_a_scene() {
13729        use std::borrow::Cow;
13730
13731        let scene = SceneDesc {
13732            meshes: vec![scene::MeshDesc {
13733                label: Cow::Borrowed("the only mesh"),
13734                geometry: Geometry::Flat {
13735                    vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
13736                    uv_range: crcbl_shaders::mesh::demo_uv_range(),
13737                    indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
13738                    clusters: crcbl_shaders::meshlet::cube_clusters(),
13739                    flags: 0,
13740                },
13741            }],
13742            materials: vec![mesh::GpuMaterial::UNTINTED],
13743            page: scene::PageDesc::empty(),
13744            probes: scene::ProbeGrid::default(),
13745            capacities: scene::Capacities::default(),
13746        };
13747        assert!(
13748            scene.meshes.len() < scene::demo().meshes.len()
13749                && scene.materials.len() < scene::demo().materials.len(),
13750            "this description must be smaller than the demo's in both, or it says nothing \
13751             about the floor"
13752        );
13753
13754        let (recorder, device, queue) = open();
13755        let mut renderer =
13756            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13757                .expect("one mesh and one row is a description the renderer can hold");
13758        assert_eq!(
13759            renderer.mesh_ids,
13760            [0],
13761            "the one description mesh takes the one table entry"
13762        );
13763        assert_eq!(
13764            renderer.bucket_constants.len(),
13765            1,
13766            "one bucket per description mesh, and there is one"
13767        );
13768        renderer
13769            .add_instance(&InstanceDesc {
13770                mesh: 0,
13771                material: 0,
13772                transform: Mat4::IDENTITY,
13773            })
13774            .expect("an empty pool has room for the only object");
13775        let recorded = frame(device.as_ref(), &mut renderer, queue);
13776        assert_eq!(
13777            commands_in_pass(&recorder, "forward")
13778                .into_iter()
13779                .filter(|command| matches!(
13780                    command,
13781                    crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
13782                ))
13783                .count(),
13784            1,
13785            "a one-mesh scene records the one bucket's indirect call"
13786        );
13787        recorded.finish(device.as_ref(), renderer);
13788    }
13789
13790    /// **A description that exactly fills what it reserved is built, not
13791    /// refused.**
13792    ///
13793    /// The other side of the capacity check, and the side nothing else in the
13794    /// tree can fail on: every other scene reserves far more than it holds, so a
13795    /// comparison written `>=` instead of `>` would pass the whole suite and
13796    /// refuse only the application that had sized its pools exactly right.
13797    ///
13798    /// The two capacities asserted here are the two a caller can size without
13799    /// re-deriving anything the renderer knows: one mesh table entry per
13800    /// [`Geometry::levels`], which is what that method is documented to answer,
13801    /// and one row per material. The four rows share one comparison, so they
13802    /// stand or fall together.
13803    #[test]
13804    fn a_description_that_exactly_fits_its_capacities_is_built() {
13805        let (recorder, device, queue) = open();
13806        let mut scene = scene::demo();
13807        scene.capacities.meshes = scene
13808            .meshes
13809            .iter()
13810            .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
13811            .sum();
13812        scene.capacities.materials =
13813            u32::try_from(scene.materials.len()).expect("a few material rows");
13814        let renderer =
13815            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13816                .expect("a description that fits exactly is not too large for itself");
13817        renderer.destroy(device.as_ref());
13818        recorder.assert_valid();
13819    }
13820
13821    /// **The level tables cover every mesh-table slot an instance can name**,
13822    /// not only the slots the description filled.
13823    ///
13824    /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
13825    /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
13826    /// "every entry an instance can name is filled". An instance's mesh id is a
13827    /// bare table index, so a table sized to the description alone makes that
13828    /// read land in whatever the packer put next for any slot the description
13829    /// left empty.
13830    ///
13831    /// Growing the capacity by a known number of slots grows the tables buffer
13832    /// by exactly what those slots occupy: one `MeshLevels` record and one
13833    /// `level_meshes` word each. The arithmetic is the assertion, so nothing
13834    /// here is a number to keep in step by hand.
13835    #[test]
13836    fn the_level_tables_cover_every_slot_the_mesh_table_has() {
13837        const EXTRA: u32 = 4;
13838
13839        let sized = |extra: u32| {
13840            let (recorder, device, queue) = open();
13841            let mut scene = scene::demo();
13842            scene.capacities.meshes += extra;
13843            let renderer =
13844                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13845                    .expect("a description with room to spare");
13846            let size = recorder
13847                .buffer_bytes(renderer.primary.draws.tables())
13848                .expect("the table buffer is live")
13849                .len();
13850            renderer.destroy(device.as_ref());
13851            recorder.assert_valid();
13852            size
13853        };
13854
13855        let grown = sized(EXTRA) - sized(0);
13856        let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
13857        assert_eq!(
13858            grown, want,
13859            "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
13860             level words, and added {grown} bytes"
13861        );
13862    }
13863
13864    /// The property the whole arrangement exists for: the pool's second
13865    /// resident is **not** at base vertex zero, so a frame containing it is a
13866    /// frame that fails if the base is lost between the pool and the shader.
13867    ///
13868    /// Read out of the **mesh table** rather than out of a renderer field,
13869    /// because the table is where a generated draw's index range comes from:
13870    /// `draw_gen.slang` builds every argument structure out of these bytes and
13871    /// nothing on the CPU is consulted.
13872    ///
13873    /// Without this the pass is back where it started — one mesh, base 0, and a
13874    /// base-vertex bug that no picture can show.
13875    #[test]
13876    fn the_second_mesh_lands_past_the_first() {
13877        let (recorder, device, queue) = open();
13878        let renderer =
13879            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13880        let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
13881        let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
13882
13883        assert_eq!(cube.base_vertex, 0, "the cube is first");
13884        assert_eq!(
13885            pyramid.base_vertex as usize,
13886            crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
13887            "the pyramid must start where the cube ends, or the pools are not \
13888             suballocating at all"
13889        );
13890        assert_eq!(
13891            pyramid.index_count as usize,
13892            crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
13893            "and the entry carries the whole range, which is what the draw-argument \
13894             pass builds its arguments out of"
13895        );
13896        // And the two buckets read different constant blocks, or both would walk
13897        // the same run of instances.
13898        assert_ne!(
13899            renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
13900            "each bucket needs a block of its own"
13901        );
13902        renderer.destroy(device.as_ref());
13903    }
13904
13905    /// **Each bucket's block points at that bucket's own run**, and the runs do
13906    /// not overlap.
13907    ///
13908    /// This is what replaced "the block names an instance": a draw covers
13909    /// however many instances survived culling, so what it can say for itself is
13910    /// only where to find its slice of the survivors. Two buckets naming one
13911    /// start word would draw each other's objects — with the *right* geometry,
13912    /// because the index range comes from the arguments, which is exactly the
13913    /// kind of plausible wrong picture a golden image struggles with.
13914    ///
13915    /// Read out of the bytes that reached the device rather than out of the
13916    /// renderer's own fields, because the failure is a block written wrong and
13917    /// the field would still be right.
13918    #[test]
13919    fn each_bucket_walks_its_own_run_of_survivors() {
13920        let (recorder, device, queue) = open();
13921        let renderer =
13922            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13923        let blocks = recorder
13924            .buffer_bytes(renderer.draw_constants)
13925            .expect("the blocks are live");
13926        let start_word_at = |offset: u32| {
13927            let at = offset as usize;
13928            u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
13929        };
13930
13931        let draws = &renderer.primary.draws;
13932        let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
13933        let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
13934        // **Behind the survivors, their routes and the runs**, which share the
13935        // buffer: a block naming a word inside the runs would have the draw read
13936        // an instance index as its start, and one inside the survivor list or
13937        // the routes a start that is the same instances in a different order, or
13938        // a bucket number — both of which draw a plausible picture.
13939        assert_eq!(
13940            cube,
13941            draws.runs_at() + draws.visible_capacity(),
13942            "the first bucket's start word is the first word past one capacity of runs"
13943        );
13944        assert_eq!(
13945            pyramid,
13946            cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
13947            "and the second's is a word later — a start per bucket, not a run per bucket"
13948        );
13949        assert_eq!(
13950            cube,
13951            draws.bucket_start_word(DEMO_CUBE as u32),
13952            "the block carries what `DrawGen::bucket_start_word` says, because a reader \
13953             copying a run back uses that accessor and the shader uses this block"
13954        );
13955        renderer.destroy(device.as_ref());
13956    }
13957
13958    /// **An instance's record carries its material's mode**, in the bits
13959    /// `draw_gen.slang` routes by.
13960    ///
13961    /// The host half of the per-bucket split, and the half no picture and no
13962    /// pipeline bind can show: the bucket table can be perfectly twinned and
13963    /// every partition bound to the right pipeline while every instance still
13964    /// answers mode zero, in which case the masked twins are empty, the cutout
13965    /// partition draws nothing, and a cutout casts a solid shadow. The record is
13966    /// where that is decided.
13967    ///
13968    /// Both directions, so the check is shown to discriminate: the opaque
13969    /// instance's mode bits have to be **clear**, or a writer that set them
13970    /// unconditionally would satisfy a one-sided assertion. And the two records
13971    /// are asserted to differ in `flags` and nothing else, so this is about the
13972    /// mode rather than about two unrelated instances.
13973    #[test]
13974    fn an_instances_record_carries_its_materials_mode() {
13975        let masked_scene = {
13976            let mut scene = crate::scene::demo();
13977            scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
13978            scene
13979        };
13980        let (recorder, device, queue) = open();
13981        let device = device.as_ref();
13982        let mut renderer =
13983            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
13984                .expect("the null backend accepts the demo description");
13985        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
13986        let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
13987        let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
13988
13989        let record = |handle: InstanceHandle| {
13990            renderer
13991                .instances
13992                .get(handle)
13993                .expect("the instance was inserted and is live")
13994        };
13995        let opaque = record(opaque);
13996        let masked = record(masked);
13997        assert_eq!(
13998            opaque.material_mode(),
13999            0,
14000            "an opaque material's instance carries no mode bits, or every instance in the tree \
14001             routes to a cutout bucket"
14002        );
14003        assert_eq!(
14004            masked.material_mode(),
14005            crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14006            "and a masked material's instance carries its mode, or it scatters into the opaque \
14007             twin and the depth passes write its full silhouette"
14008        );
14009        assert_eq!(
14010            mesh::GpuInstance {
14011                flags: opaque.flags,
14012                material: opaque.material,
14013                ..masked
14014            },
14015            opaque,
14016            "the two records differ in the mode bits and the material id and in nothing else"
14017        );
14018
14019        renderer.destroy(device);
14020        recorder.assert_valid();
14021    }
14022
14023    /// **A scene whose materials are all opaque gets exactly the bucket table
14024    /// it had before material modes existed** — one bucket per (mesh, level),
14025    /// and no twin.
14026    ///
14027    /// The zero-cost half of the per-bucket split, and the one a null device can
14028    /// state exactly. A bucket is not free: every pass records one indirect call
14029    /// per bucket per view, and every generator holds a run start per bucket. So
14030    /// a table that twinned unconditionally would double the recorded draws of
14031    /// every demo and every golden in this tree, none of which mask anything.
14032    ///
14033    /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14034    /// built from a mesh's own level count rather than from the table's length —
14035    /// so a build that emitted a twin per mesh has more buckets than levels and
14036    /// this says so. And the twinned scenes below are asserted to be exactly as
14037    /// many times as long as they hold modes, or the comparison would pass on a
14038    /// renderer that had stopped twinning at all.
14039    ///
14040    /// # A twin per mode the scene **holds**, not per mode that exists
14041    ///
14042    /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14043    /// records one indirect call per bucket — so the rule that matters is which
14044    /// values the description's own materials carry. Two rows of two modes are
14045    /// two twins whichever two they are, and the pair below says so both ways:
14046    /// three modes across three rows is three, and three rows collapsed onto two
14047    /// *values* is two even though between them they set both mode bits.
14048    #[test]
14049    fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14050        use crcbl_shaders::mesh::GpuMaterial;
14051
14052        let (recorder, device, queue) = open();
14053        let device = device.as_ref();
14054        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14055        // The uniform-cut path, where a DAG is one bucket per level. The mesh
14056        // path folds a DAG into one bucket and reports no level buckets at all,
14057        // which would leave the oracle below empty.
14058        assert!(
14059            !renderer.emit.is_mesh(),
14060            "this preset built a mesh-shader path, whose level buckets are empty"
14061        );
14062        let levels: usize = (0..crate::scene::demo().meshes.len())
14063            .map(|mesh| renderer.level_buckets(mesh).len())
14064            .sum();
14065        assert!(levels > 0, "the demo has meshes, so it has levels");
14066        assert_eq!(
14067            renderer.bucket_constants.len(),
14068            levels,
14069            "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14070             twin: {levels} level(s) against {} bucket(s)",
14071            renderer.bucket_constants.len()
14072        );
14073        assert_eq!(
14074            renderer.bucket_modes,
14075            vec![0; levels],
14076            "and every one of them draws the OPAQUE mode"
14077        );
14078        let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14079        let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14080            .map(|mesh| renderer.level_buckets(mesh).to_vec())
14081            .collect();
14082        renderer.destroy(device);
14083        recorder.assert_valid();
14084
14085        // Every arrangement worth stating, as the modes its material rows carry
14086        // and the number of twins that has to produce. The demo has three rows;
14087        // a fourth is appended where four distinct modes are wanted, which
14088        // nothing instances and which therefore changes nothing but the mode
14089        // set.
14090        for (rows, modes, what) in [
14091            (
14092                vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14093                2,
14094                "one masked row beside two opaque ones",
14095            ),
14096            (
14097                vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14098                2,
14099                "one double-sided row beside two opaque ones",
14100            ),
14101            (
14102                vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14103                3,
14104                "a masked row, a double-sided one and an opaque one",
14105            ),
14106            (
14107                vec![
14108                    GpuMaterial::ALPHA_MODE_MASK,
14109                    GpuMaterial::DOUBLE_SIDED,
14110                    GpuMaterial::ALPHA_MODE_MASK,
14111                ],
14112                2,
14113                "three rows carrying two mode values between them — both mode bits are set \
14114                 somewhere and neither row is opaque, so a rule counting bits rather than \
14115                 values would say three",
14116            ),
14117            (
14118                vec![
14119                    0,
14120                    GpuMaterial::ALPHA_MODE_MASK,
14121                    GpuMaterial::DOUBLE_SIDED,
14122                    GpuMaterial::MODE_MASK,
14123                ],
14124                4,
14125                "one row of each mode, which is the only arrangement that pays for four",
14126            ),
14127        ] {
14128            let scene = {
14129                let mut scene = crate::scene::demo();
14130                while scene.materials.len() < rows.len() {
14131                    scene.materials.push(GpuMaterial::UNTINTED);
14132                }
14133                for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14134                    row.flags = *flags;
14135                }
14136                scene
14137            };
14138            let (recorder, device, queue) = open();
14139            let device = device.as_ref();
14140            let twinned =
14141                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14142                    .expect("the null backend accepts the demo description");
14143            assert_eq!(
14144                twinned.bucket_constants.len(),
14145                modes * levels,
14146                "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14147                 has {}",
14148                modes * levels,
14149                twinned.bucket_constants.len()
14150            );
14151            // The modes present, as a set — which is the claim, since the order
14152            // is `DEPTH_MODES`' and the count above already pins the length.
14153            let held: std::collections::BTreeSet<u32> =
14154                twinned.bucket_modes.iter().copied().collect();
14155            let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14156            assert_eq!(
14157                held, want,
14158                "{what}: the table twins the modes its materials carry and no others"
14159            );
14160            for mode in &held {
14161                assert_eq!(
14162                    twinned
14163                        .bucket_modes
14164                        .iter()
14165                        .filter(|held| *held == mode)
14166                        .count(),
14167                    levels,
14168                    "{what}: every mode present gets every mesh's levels once"
14169                );
14170            }
14171            // **Mode-major**: each held mode is one contiguous run of the
14172            // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14173            // partition is one range of buckets.
14174            let held_in_order: Vec<u32> = DEPTH_MODES
14175                .into_iter()
14176                .filter(|mode| held.contains(mode))
14177                .collect();
14178            assert_eq!(
14179                twinned.bucket_modes,
14180                held_in_order
14181                    .iter()
14182                    .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14183                    .collect::<Vec<_>>(),
14184                "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14185            );
14186            assert_eq!(
14187                twinned.draw_tables.bucket_meshes,
14188                opaque_meshes.repeat(held_in_order.len()),
14189                "{what}: each mode's run is the all-opaque table, mesh by mesh"
14190            );
14191            for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14192                assert_eq!(
14193                    twinned.level_buckets(mesh),
14194                    opaque.as_slice(),
14195                    "{what}: mesh {mesh}'s level buckets are the first mode's run"
14196                );
14197            }
14198            // And the `(mesh, mode) → bucket` lookup the scatter routes through
14199            // sends every key to its mode's run, at the mesh's own offset.
14200            let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14201                &twinned.draw_tables.bucket_meshes,
14202                &twinned.bucket_modes,
14203            )
14204            .expect("a small lookup");
14205            for (slot, mode) in held_in_order.iter().enumerate() {
14206                for (offset, mesh) in opaque_meshes.iter().enumerate() {
14207                    let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14208                    assert_eq!(
14209                        lookup[key as usize] as usize,
14210                        slot * levels + offset,
14211                        "{what}: mesh {mesh} in mode {mode}"
14212                    );
14213                }
14214            }
14215            twinned.destroy(device);
14216            recorder.assert_valid();
14217        }
14218    }
14219
14220    /// **The two pyramids differ in exactly one field, and it is the material
14221    /// id — which names a row holding a different colour and a different
14222    /// roughness.**
14223    ///
14224    /// The whole of what §3.2's table buys, stated as the two things that have
14225    /// to be true at once. Placed at the *same* transform, so "differ only in
14226    /// material" is literal rather than nearly: same mesh id, same matrix, same
14227    /// flags, and a `GpuInstance` comparison that would fail on any other
14228    /// field. And the ids they carry name rows the device actually holds —
14229    /// asserted on the bytes in the buffer, because a table the renderer agrees
14230    /// with itself about is not a table a shader can read.
14231    ///
14232    /// The two rows are asserted to differ, or the pair would be evidence of
14233    /// nothing: two instances naming two rows of the same colour draw the same
14234    /// picture whether or not either id was ever used.
14235    #[test]
14236    fn the_two_pyramids_differ_only_in_their_material() {
14237        let (recorder, device, queue) = open();
14238        let mut renderer =
14239            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14240        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14241        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14242        let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14243
14244        let instance = |handle: InstanceHandle| {
14245            renderer
14246                .instances
14247                .get(handle)
14248                .expect("the instance was inserted and is live")
14249        };
14250        let plain = instance(plain_handle);
14251        let tinted = instance(tinted_handle);
14252        assert_ne!(
14253            plain.material, tinted.material,
14254            "the two pyramids must not share a material row"
14255        );
14256        assert_eq!(
14257            mesh::GpuInstance {
14258                material: tinted.material,
14259                ..plain
14260            },
14261            tinted,
14262            "the two instances must differ in the material id and in nothing else"
14263        );
14264
14265        let bytes = recorder
14266            .buffer_bytes(renderer.materials.buffer())
14267            .expect("the table is live");
14268        let row = |index: u32| {
14269            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14270            mesh::GpuMaterial::from_bytes(
14271                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14272                    .try_into()
14273                    .expect("one row"),
14274            )
14275        };
14276        assert_eq!(
14277            row(plain.material),
14278            mesh::GpuMaterial::UNTINTED,
14279            "the plain pyramid's row must be the factor that changes nothing"
14280        );
14281        assert_eq!(
14282            row(tinted.material),
14283            mesh::GpuMaterial {
14284                base_color: scene::PYRAMID_TINT,
14285                roughness: scene::PYRAMID_ROUGHNESS,
14286                ..mesh::GpuMaterial::UNTINTED
14287            },
14288            "the tinted pyramid's row must be the tint and the tighter lobe"
14289        );
14290        // The shading half of that row, on its own: a roughness equal to the
14291        // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14292        // against itself, and that test would go green on a shader that had
14293        // never read the column.
14294        assert_ne!(
14295            row(plain.material).roughness,
14296            row(tinted.material).roughness,
14297            "the two rows must differ in roughness, or the highlight the render e2e measures \
14298             is not attributable to the material"
14299        );
14300        assert_ne!(
14301            row(plain.material),
14302            row(tinted.material),
14303            "two rows holding the same colour would make the pair prove nothing"
14304        );
14305        // And the tint is the *only* thing that differs between them: a row that
14306        // also changed its page layer would make this pair evidence about two
14307        // columns at once, which is what the third pyramid exists to avoid.
14308        assert_eq!(
14309            row(plain.material).base_color_texture,
14310            row(tinted.material).base_color_texture,
14311            "the factor pair must sample the same page layer"
14312        );
14313
14314        // And the second pyramid leaves the frame the way the first does: the
14315        // instance is removed, not a draw skipped.
14316        renderer.remove_instance(tinted_handle);
14317        assert!(
14318            renderer.instances.get(tinted_handle).is_none(),
14319            "the instance must be given back, or an object nobody asked for stays in the scene"
14320        );
14321
14322        renderer.destroy(device.as_ref());
14323    }
14324
14325    /// **The same claim one column along: the plain and textured pyramids
14326    /// differ in exactly one field, and the rows it names differ in exactly one
14327    /// column — the base-colour page layer.**
14328    ///
14329    /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14330    /// *texture indices* rather than its *factors*. The factors of the two rows
14331    /// are asserted **equal** here, which is the half that makes the pair
14332    /// evidence about the texture at all: a textured row that also carried a
14333    /// tint would draw a different picture for a reason the frame could not
14334    /// distinguish from the tinted pyramid's.
14335    ///
14336    /// The layer numbers are asserted against the page the renderer actually
14337    /// uploaded, so a row naming a layer that does not exist is caught here
14338    /// rather than as an out-of-range sample on a device.
14339    #[test]
14340    fn the_textured_pyramid_differs_only_in_its_page_layer() {
14341        let (recorder, device, queue) = open();
14342        let mut renderer =
14343            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14344        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14345        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14346        let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14347
14348        let instance = |handle: InstanceHandle| {
14349            renderer
14350                .instances
14351                .get(handle)
14352                .expect("the instance was inserted and is live")
14353        };
14354        let plain = instance(plain_handle);
14355        let textured = instance(textured_handle);
14356        assert_ne!(
14357            plain.material, textured.material,
14358            "the two pyramids must not share a material row"
14359        );
14360        assert_eq!(
14361            mesh::GpuInstance {
14362                material: textured.material,
14363                ..plain
14364            },
14365            textured,
14366            "the two instances must differ in the material id and in nothing else"
14367        );
14368
14369        let bytes = recorder
14370            .buffer_bytes(renderer.materials.buffer())
14371            .expect("the table is live");
14372        let row = |index: u32| {
14373            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14374            mesh::GpuMaterial::from_bytes(
14375                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14376                    .try_into()
14377                    .expect("one row"),
14378            )
14379        };
14380        assert_eq!(
14381            row(plain.material).base_color,
14382            row(textured.material).base_color,
14383            "the texture pair must share a factor, or the pair is evidence about both columns"
14384        );
14385        assert_eq!(
14386            row(plain.material).base_color_texture,
14387            mesh::GpuMaterial::NO_PAGE
14388        );
14389        assert_eq!(
14390            row(textured.material).base_color_texture,
14391            scene::CHECKER_LAYER
14392        );
14393        assert_ne!(
14394            row(plain.material),
14395            row(textured.material),
14396            "two rows naming the same layer would make the pair prove nothing"
14397        );
14398        // The layer that number names is a layer the page has, and it is not
14399        // one flat colour — a checker of one repeated texel would pass every
14400        // assertion above and draw the picture the untextured row draws.
14401        let page = scene::demo().page;
14402        let layers = page.layers(PageKind::BaseColor);
14403        assert!(
14404            (scene::CHECKER_LAYER as usize) < layers.len(),
14405            "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
14406             nothing below the seam would report",
14407            scene::CHECKER_LAYER,
14408            layers.len()
14409        );
14410        let checker = &layers[scene::CHECKER_LAYER as usize];
14411        assert!(
14412            checker
14413                .as_chunks::<4>()
14414                .0
14415                .iter()
14416                .any(|texel| texel != &checker[..4]),
14417            "a flat checker layer would shade the textured row exactly as the untextured \
14418             one shades, and the pair would prove nothing"
14419        );
14420
14421        renderer.remove_instance(textured_handle);
14422        assert!(
14423            renderer.instances.get(textured_handle).is_none(),
14424            "the instance must be given back, or an object nobody asked for stays in the scene"
14425        );
14426
14427        renderer.destroy(device.as_ref());
14428    }
14429
14430    /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
14431    /// and a third again for its chain.
14432    ///
14433    /// This is what row (d) bought, and it is the half of it no picture can
14434    /// show: the frame a scene with no normal map draws is byte-identical either
14435    /// way, because `mesh.slang` returns before it fetches. What changes is the
14436    /// image the renderer created, and the copies into it are where that is
14437    /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
14438    /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
14439    /// is the device-side half saying the frame did not move.
14440    ///
14441    /// [`scene::demo`] is the scene: every one of its rows carries
14442    /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
14443    /// the description every golden in this tree is a variation of.
14444    ///
14445    /// # Sabotage
14446    ///
14447    /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
14448    /// and its chain instead of the placeholder — the shape this replaced. Red
14449    /// on 2026-09-06 with `"a description with no normal map must upload the
14450    /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
14451    /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
14452    /// extent² × 4 bytes and a third again for its chain, on every scene in the
14453    /// tree"`.
14454    #[test]
14455    fn a_page_kind_nothing_names_costs_one_texel() {
14456        use crcbl_hal::null::Command;
14457
14458        let scene = scene::demo();
14459        assert!(
14460            scene
14461                .materials
14462                .iter()
14463                .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
14464            "a row naming a normal layer would make the description one that *does* name \
14465             the page, and this test would be about the other case"
14466        );
14467        assert!(
14468            scene.page.layers(PageKind::Normal).is_empty()
14469                && scene.page.extent(PageKind::BaseColor) > 1,
14470            "the description must name no normal layer while naming base-colour ones, or \
14471             a placeholder-sized copy says nothing about which page it landed in"
14472        );
14473
14474        let (recorder, device, queue) = open();
14475        let renderer =
14476            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14477                .expect("a description naming no normal page is one this can make resident");
14478
14479        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14480            .commands()
14481            .into_iter()
14482            .filter_map(|command| match command {
14483                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14484                    Some(copy)
14485                }
14486                _ => None,
14487            })
14488            .collect();
14489        let extents: Vec<crcbl_hal::Extent3d> =
14490            copies.iter().map(|copy| copy.image_extent).collect();
14491        assert_eq!(
14492            extents,
14493            vec![crcbl_hal::Extent3d::d2(1, 1)],
14494            "a description with no normal map must upload the one-texel placeholder, and \
14495             this copied {} level(s) at {extents:?} — a burned neutral layer costs \
14496             extent² × 4 bytes and a third again for its chain, on every scene in the tree",
14497            copies.len()
14498        );
14499
14500        // The placeholder is one layer, and the graph declaration says so: a
14501        // caller importing this page to write a layer of its own would get
14502        // `ImportDeclarationConflict` against an extent that was not 1×1.
14503        assert_eq!(
14504            renderer.normal_page_import().extent,
14505            (1, 1),
14506            "the declaration names the placeholder's extent, not the base-colour page's"
14507        );
14508        renderer.destroy(device.as_ref());
14509    }
14510
14511    /// **A page and a material table that are the caller's own, not
14512    /// [`scene::demo`]'s**: a different extent per kind, more layers than the
14513    /// demo page holds, a normal page the demo does not have at all, and rows
14514    /// past the three the demo writes.
14515    ///
14516    /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
14517    /// at most — so until this nothing had put an app-supplied *layer* or an
14518    /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
14519    /// build that uploaded the demo's two layers and stopped, or that inserted
14520    /// its three rows and stopped, would leave every golden byte-identical and
14521    /// pass every other assertion in this module: the demo scene cannot tell a
14522    /// table filled from the description from one filled up to the description's
14523    /// third row.
14524    ///
14525    /// Read off the recorder rather than off the description, because the
14526    /// description is the input. The copies are what reached the image and the
14527    /// table buffer is what the shader indexes, and neither is a restatement of
14528    /// what was handed in.
14529    #[test]
14530    fn an_app_page_and_table_reach_the_device_whole() {
14531        use crcbl_hal::null::Command;
14532
14533        /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
14534        /// rather than read off the page shows up as a copy of the wrong size.
14535        const APP_EXTENT: u32 = 4;
14536
14537        /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
14538        /// extent bought: a renderer that still sized the normal page from the
14539        /// base-colour page's number would copy this layer at 4² and the copy
14540        /// list below would say so.
14541        const APP_NORMAL_EXTENT: u32 = 2;
14542        let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
14543
14544        // Three base-colour layers, each flat and each a value of its own: a
14545        // build that uploaded one layer twice, or that stopped short, is a
14546        // different sequence of copies. Then one normal layer at the other
14547        // extent, which the demo scene has no page for at all.
14548        let mut page = scene::PageDesc::empty();
14549        page.set_extent(PageKind::BaseColor, APP_EXTENT);
14550        page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
14551        let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
14552            .into_iter()
14553            .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
14554            .collect();
14555        let app_normal = page.push_layer(
14556            PageKind::Normal,
14557            scene::PageDesc::NEUTRAL_NORMAL
14558                .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
14559        );
14560
14561        let mut scene = scene::demo();
14562        scene.page = page;
14563        // One row per appended layer, and each with a factor of its own as well,
14564        // so a row that landed at another row's id is not a row that happens to
14565        // look like it. The last of them names the normal layer too, so the
14566        // table carries a row through both pages.
14567        for (nth, &layer) in app_layers.iter().enumerate() {
14568            let shade = 0.25 * (nth as f32 + 1.0);
14569            let last = nth + 1 == app_layers.len();
14570            scene.materials.push(mesh::GpuMaterial {
14571                base_color: [shade, shade, shade, 1.0],
14572                base_color_texture: layer,
14573                normal_texture: if last {
14574                    app_normal
14575                } else {
14576                    mesh::GpuMaterial::NO_PAGE
14577                },
14578                ..mesh::GpuMaterial::UNTINTED
14579            });
14580        }
14581        assert!(
14582            scene.materials.len() > scene::demo().materials.len()
14583                && scene.page.layers(PageKind::BaseColor).len()
14584                    > scene::demo().page.layers(PageKind::BaseColor).len(),
14585            "the description under test must exceed the demo's in both, or this is a \
14586             demo test wearing another name"
14587        );
14588        assert_eq!(
14589            scene::demo().page.extent(PageKind::Normal),
14590            0,
14591            "the demo scene must name no normal page, or the normal copies below are \
14592             evidence about the demo's page rather than the caller's"
14593        );
14594
14595        let (recorder, device, queue) = open();
14596        let mut renderer =
14597            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14598                .expect("a page and a table of the caller's own are ones this can make resident");
14599
14600        // The page, layer by layer. Filtered by image because the build uploads
14601        // the ambient-occlusion placeholder through the same path.
14602        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14603            .commands()
14604            .into_iter()
14605            .filter_map(|command| match command {
14606                Command::CopyBufferToImage(copy)
14607                    if copy.image == renderer.base_color_page.image =>
14608                {
14609                    Some(copy)
14610                }
14611                _ => None,
14612            })
14613            .collect();
14614        // Every layer goes up with its chain — three levels for this extent —
14615        // so the copies are layer-major, level-minor, each at its level's own
14616        // extent.
14617        let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
14618            .full_mip_levels(crcbl_hal::ImageType::D2);
14619        assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
14620        let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
14621            .expect("a page of a few layers");
14622        assert_eq!(
14623            copies
14624                .iter()
14625                .map(|copy| (
14626                    copy.image_subresource.base_layer,
14627                    copy.image_subresource.mip
14628                ))
14629                .collect::<Vec<(u32, u32)>>(),
14630            (0..layer_count)
14631                .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
14632                .collect::<Vec<(u32, u32)>>(),
14633            "every level of every layer the description carries must be copied into the page, \
14634             in order"
14635        );
14636        assert!(
14637            copies.iter().all(|copy| {
14638                let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
14639                copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
14640            }),
14641            "the page is the extent the caller wrote, not the demo's, halved per level: \
14642             {copies:?}"
14643        );
14644
14645        // The normal page, at **its own** extent. One layer, two levels for a
14646        // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
14647        // that carried one extent for both kinds would put this layer up at 4².
14648        let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14649            .commands()
14650            .into_iter()
14651            .filter_map(|command| match command {
14652                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14653                    Some(copy)
14654                }
14655                _ => None,
14656            })
14657            .collect();
14658        let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
14659            .full_mip_levels(crcbl_hal::ImageType::D2);
14660        assert_eq!(
14661            normal_copies
14662                .iter()
14663                .map(|copy| (
14664                    copy.image_subresource.base_layer,
14665                    copy.image_subresource.mip,
14666                    copy.image_extent
14667                ))
14668                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14669            (0..normal_levels)
14670                .map(|level| {
14671                    let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
14672                    (0, level, crcbl_hal::Extent3d::d2(side, side))
14673                })
14674                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14675            "the normal page is the extent the caller wrote for *that* kind, halved per \
14676             level: {normal_copies:?}"
14677        );
14678        assert_eq!(
14679            renderer.normal_page_import().extent,
14680            (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
14681            "the graph declaration names the normal page's own extent, or a caller \
14682             importing it to write a layer gets ImportDeclarationConflict"
14683        );
14684        assert_eq!(
14685            renderer.base_color_page_import().extent,
14686            (APP_EXTENT, APP_EXTENT),
14687            "and the base-colour declaration names its own, which is a different number"
14688        );
14689
14690        // The table, row by row, out of the buffer `mesh.slang` indexes.
14691        let bytes = recorder
14692            .buffer_bytes(renderer.materials.buffer())
14693            .expect("the table is live");
14694        let row = |id: u32| {
14695            let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14696            mesh::GpuMaterial::from_bytes(
14697                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14698                    .try_into()
14699                    .expect("one row"),
14700            )
14701        };
14702        assert_eq!(
14703            renderer.material_ids.len(),
14704            scene.materials.len(),
14705            "one id per description row, whatever the count"
14706        );
14707        for (index, wrote) in scene.materials.iter().enumerate() {
14708            assert_eq!(
14709                &row(renderer.material_ids[index]),
14710                wrote,
14711                "description row {index} must be the row its id names"
14712            );
14713        }
14714
14715        // And a caller can place an object through a row only its own
14716        // description has, which is the whole point of the rows being the
14717        // caller's.
14718        let last = scene.materials.len() - 1;
14719        let handle = renderer
14720            .add_instance(&InstanceDesc {
14721                mesh: DEMO_CUBE,
14722                material: last,
14723                transform: Mat4::IDENTITY,
14724            })
14725            .expect("an empty pool of thousands has room for one object");
14726        assert_eq!(
14727            renderer
14728                .instances
14729                .get(handle)
14730                .expect("a just-added instance is live")
14731                .material,
14732            renderer.material_ids[last],
14733            "an InstanceDesc's material index resolves through the description, not \
14734             through a table id the caller cannot know"
14735        );
14736
14737        renderer.destroy(device.as_ref());
14738        recorder.assert_valid();
14739    }
14740
14741    /// **The frame records two compute dispatches and exactly one indirect draw
14742    /// per bucket — whatever is in the scene.**
14743    ///
14744    /// The property topic 03 opens with, checked on the recorded command stream:
14745    /// adding the pyramid adds an instance and changes no command. A pass that
14746    /// had kept a draw per object would record one command here and two there,
14747    /// which is what this used to assert and what the indirect path replaced.
14748    ///
14749    /// It also pins the arguments each call names: bucket `n` reads the `n`-th
14750    /// argument structure and the `n`-th count, at the stride every API fixed.
14751    /// Two calls pointing at one structure is a frame that draws one object
14752    /// twice.
14753    #[test]
14754    fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
14755        use crcbl_hal::null::Command;
14756
14757        for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
14758            let (recorder, device, queue) = open();
14759            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14760                .expect("built");
14761            // The cube in both scenes, so the difference between them is the
14762            // pyramid alone. It also keeps both frames non-empty, and an empty
14763            // one would be a weaker comparison than this claims: `cull`'s
14764            // dispatch covers no workgroups when the pool is empty, and the pass
14765            // records nothing rather than a dispatch of zero — see
14766            // [`DrawGen::add_passes`].
14767            place_cube(&mut renderer, Mat4::IDENTITY);
14768            if let Some(at) = pyramid {
14769                place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14770            }
14771            let frame = frame(device.as_ref(), &mut renderer, queue);
14772
14773            let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
14774            let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
14775                .map(|bucket| {
14776                    (
14777                        renderer.bucket_constants[bucket],
14778                        bucket as u64 * u64::from(stride),
14779                        bucket as u64 * 4,
14780                    )
14781                })
14782                .collect();
14783
14784            // The dynamic offset last bound before each draw, paired with the
14785            // offsets that draw read its arguments and its count from.
14786            let mut offset = None;
14787            let mut seen: Vec<(u32, u64, u64)> = Vec::new();
14788            let mut dispatches = 0;
14789            for command in recorder.commands() {
14790                if matches!(command, Command::Dispatch { .. }) {
14791                    dispatches += 1;
14792                }
14793            }
14794            for command in commands_in_pass(&recorder, "forward") {
14795                match command {
14796                    Command::BindGroup {
14797                        slot: 0,
14798                        dynamic_offsets,
14799                        ..
14800                    } => offset = dynamic_offsets.first().copied(),
14801                    Command::DrawIndexedIndirectCount(draw) => {
14802                        assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
14803                        assert_eq!(
14804                            draw.max_draw_count, 1,
14805                            "one argument structure per bucket, so one is the ceiling"
14806                        );
14807                        seen.push((
14808                            offset.expect("a draw is preceded by its constant block"),
14809                            draw.args_offset,
14810                            draw.count_offset,
14811                        ));
14812                    }
14813                    Command::DrawIndexed { .. } => {
14814                        panic!("the forward pass must not record a CPU-counted draw any more")
14815                    }
14816                    _ => {}
14817                }
14818            }
14819            assert_eq!(
14820                dispatches,
14821                DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
14822                "the clearing pass, the cull pass and the draw-argument pass's three, in \
14823                 front of the draws — once for the camera and once per shadow cascade — plus \
14824                 topic 18's one clustering dispatch, which is the camera's alone because a \
14825                 cascade shades nothing, plus the resolve's own"
14826            );
14827            assert_eq!(
14828                seen, expected,
14829                "with pyramid = {pyramid:?}, the pass must record one indirect call per \
14830                 bucket, each pointing at its own arguments, its own count and its own \
14831                 block"
14832            );
14833
14834            frame.finish(device.as_ref(), renderer);
14835        }
14836    }
14837
14838    /// **The two `GeometryPath` arms record different calls and nothing else
14839    /// differs.**
14840    ///
14841    /// A device with a GPU-side count takes it from GPU memory; one without —
14842    /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
14843    /// bucket's one argument structure unconditionally. Same buckets, same
14844    /// arguments, same block: the tail is the only thing that moves, which is
14845    /// what topic 03 means by "the lesser path is
14846    /// a constraint on data layout, not a separate renderer".
14847    ///
14848    /// Both presets are run here rather than only the one this machine has,
14849    /// because the arm a device never selects is the arm nothing tests.
14850    #[test]
14851    fn each_geometry_path_records_its_own_indirect_call() {
14852        use crcbl_hal::null::Command;
14853
14854        for (preset, path, counted) in [
14855            (
14856                NullInstance::gpu_driven(),
14857                GeometryPath::IndirectCount,
14858                true,
14859            ),
14860            (
14861                NullInstance::portable(),
14862                GeometryPath::IndirectPerBatch,
14863                false,
14864            ),
14865        ] {
14866            let recorder = Recorder::new();
14867            let instance = preset.with_recorder(recorder.clone());
14868            let adapter = instance.adapters().remove(0);
14869            assert_eq!(
14870                adapter.caps.geometry_path(),
14871                path,
14872                "the preset must select the path this arm is about"
14873            );
14874            // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
14875            // portable preset does not have; the forward pass does not need one
14876            // either, so this asks for what it uses. The optional set matters:
14877            // a device is opened with the features it *asked* for, and the path
14878            // is derived from those rather than from the adapter's.
14879            let device = instance
14880                .create_device(&DeviceDesc {
14881                    label: None,
14882                    adapter: adapter.id,
14883                    required_features: Features::COMPUTE,
14884                    optional_features: Features::GPU_DRIVEN,
14885                    compatible_surface: None,
14886                })
14887                .expect("the null backend always opens");
14888            assert_eq!(
14889                device.caps().geometry_path(),
14890                path,
14891                "and the opened device still selects it"
14892            );
14893            let queue = device.queue(QueueKind::Graphics).expect("always present");
14894            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14895                .expect("built");
14896            let frame = frame(device.as_ref(), &mut renderer, queue);
14897
14898            let mut counted_calls = 0;
14899            let mut per_batch_calls = 0;
14900            for command in commands_in_pass(&recorder, "forward") {
14901                match command {
14902                    Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
14903                    Command::DrawIndexedIndirect(draw) => {
14904                        assert_eq!(
14905                            draw.draw_count, 1,
14906                            "one argument structure per bucket, read unconditionally"
14907                        );
14908                        per_batch_calls += 1;
14909                    }
14910                    _ => {}
14911                }
14912            }
14913            let buckets = renderer.bucket_constants.len();
14914            let (expected_counted, expected_per_batch) =
14915                if counted { (buckets, 0) } else { (0, buckets) };
14916            assert_eq!(
14917                (counted_calls, per_batch_calls),
14918                (expected_counted, expected_per_batch),
14919                "{path:?} must record one call of its own kind per bucket and none of the other"
14920            );
14921
14922            frame.finish(device.as_ref(), renderer);
14923        }
14924    }
14925
14926    /// Serialises the two checks that move
14927    /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
14928    /// afterwards.
14929    ///
14930    /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
14931    /// `cargo test` runs a crate's tests as threads of *one* process: two checks
14932    /// that move the switch are then two writers to one cell, which shows up as
14933    /// a flake rather than as a failure anybody can read.
14934    /// `crcbl::debug_view::for_test` is the same shape one crate up and there
14935    /// for the same reason; this one is smaller because nothing outside these
14936    /// two tests ever writes the cell.
14937    fn debug_draw_switch() -> DebugDrawSwitch {
14938        let guard = DEBUG_DRAW_SWITCH
14939            .lock()
14940            .unwrap_or_else(std::sync::PoisonError::into_inner);
14941        let switch = DebugDrawSwitch { _guard: guard };
14942        switch.set(false);
14943        switch
14944    }
14945
14946    /// What [`debug_draw_switch`] hands back: the switch is this thread's until
14947    /// it drops, and it goes back off when it does.
14948    struct DebugDrawSwitch {
14949        _guard: std::sync::MutexGuard<'static, ()>,
14950    }
14951
14952    impl DebugDrawSwitch {
14953        /// Moves the switch.
14954        fn set(&self, on: bool) {
14955            crate::debug_draw::r_debug_draw
14956                .set(&crcbl_console::Value::Bool(on))
14957                .expect("`r_debug_draw` is a writable bool");
14958        }
14959    }
14960
14961    impl Drop for DebugDrawSwitch {
14962        fn drop(&mut self) {
14963            // Off at both ends, so a check that panicked mid-way does not hand
14964            // the next holder a switched-on layer.
14965            self.set(false);
14966        }
14967    }
14968
14969    /// [`debug_draw_switch`]'s lock.
14970    ///
14971    /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
14972    /// both — see that function for what the opposite order cost.
14973    static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
14974
14975    /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
14976    /// default when the guard drops.
14977    ///
14978    /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
14979    /// `cargo test` run shares one process between tests, and a variable this
14980    /// one left moved is a frame the next test did not ask for.
14981    ///
14982    /// **Every test whose assertion depends on the shape of a frame takes this,
14983    /// not only the one that moves the count.** The variable is a process
14984    /// global and `cargo test` runs this module's tests on threads that share
14985    /// it, so a frame built while
14986    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
14987    /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
14988    /// that the test building it never asked for. Taking the guard both
14989    /// serialises against that test and pins the count for the frames this one
14990    /// builds.
14991    ///
14992    /// Two shapes need it, and the second is easy to miss. A test comparing a
14993    /// frame against a **literal pass list** breaks whenever the count is two.
14994    /// A test comparing **two frames it built itself** — a difference in draws,
14995    /// an equality between pass lists, a "one pass longer" claim — breaks only
14996    /// when the count *moves between them*, which is a narrower window and why
14997    /// this reproduced at roughly one run in eight rather than every run.
14998    ///
14999    /// Both were established by experiment on 2026-09-01 rather than by
15000    /// reading: pinning the count at two reddens the first shape, and making
15001    /// `crate::ssao::blur_passes` alternate reddens the second.
15002    ///
15003    /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15004    /// These are two plain mutexes with no ordering between them, so two tests
15005    /// acquiring both in opposite orders deadlock — which is not a hazard this
15006    /// comment is guessing at: adding the guard to the two debug-draw tests
15007    /// above their existing one did exactly that on 2026-09-01, and turned a
15008    /// 0.2 second suite into one that had not finished in ten minutes. It is
15009    /// invisible in a single-threaded run, where the same suite passes in a
15010    /// second, so `--test-threads=1` is not a check for it.
15011    ///
15012    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15013    pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15014        let guard = SSAO_BLUR_SWITCH
15015            .lock()
15016            .unwrap_or_else(std::sync::PoisonError::into_inner);
15017        let switch = SsaoBlurSwitch { _guard: guard };
15018        switch.set(1);
15019        switch
15020    }
15021
15022    /// What [`ssao_blur_switch`] hands back.
15023    pub(super) struct SsaoBlurSwitch {
15024        _guard: std::sync::MutexGuard<'static, ()>,
15025    }
15026
15027    impl SsaoBlurSwitch {
15028        /// Asks for `passes` of them.
15029        fn set(&self, passes: i64) {
15030            crate::ssao::r_ssao_blur_passes
15031                .set(&crcbl_console::Value::Int(passes))
15032                .expect("`r_ssao_blur_passes` is a writable int in range");
15033        }
15034    }
15035
15036    impl Drop for SsaoBlurSwitch {
15037        fn drop(&mut self) {
15038            // Back to the shipping count at both ends, so a check that panicked
15039            // mid-way does not hand the next holder a three-pass frame.
15040            self.set(1);
15041        }
15042    }
15043
15044    /// [`ssao_blur_switch`]'s lock.
15045    static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15046
15047    /// Takes `r_ssao_split` for this thread and puts it back when the guard
15048    /// drops.
15049    ///
15050    /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15051    /// makes the occlusion chain record its second march, so a test about the
15052    /// widest frame a renderer can produce has to hold this as well as the blur
15053    /// count — see `crate::ssao`'s `r_ssao_split`.
15054    pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15055        let guard = SSAO_SPLIT_SWITCH
15056            .lock()
15057            .unwrap_or_else(std::sync::PoisonError::into_inner);
15058        let switch = SsaoSplitSwitch { _guard: guard };
15059        switch.set(0.0);
15060        switch
15061    }
15062
15063    /// What [`ssao_split_switch`] hands back.
15064    pub(super) struct SsaoSplitSwitch {
15065        _guard: std::sync::MutexGuard<'static, ()>,
15066    }
15067
15068    impl SsaoSplitSwitch {
15069        /// Asks for a seam at `at`, or for none at zero.
15070        fn set(&self, at: f32) {
15071            crate::ssao::r_ssao_split
15072                .set(&crcbl_console::Value::Float(at))
15073                .expect("`r_ssao_split` is a writable float in range");
15074        }
15075    }
15076
15077    impl Drop for SsaoSplitSwitch {
15078        fn drop(&mut self) {
15079            // Back to the default at both ends, so a check that panicked
15080            // mid-way does not hand the next holder a comparing frame.
15081            self.set(0.0);
15082        }
15083    }
15084
15085    /// [`ssao_split_switch`]'s lock.
15086    static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15087
15088    /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15089    /// them both back at their defaults when the guard drops.
15090    ///
15091    /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15092    /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15093    /// is where that is argued, and why the lock lives there rather than beside
15094    /// this function: `crate::shadow`'s own tests move the same two.
15095    fn shadow_filter_switch() -> ShadowFilterSwitch {
15096        let guard = crate::shadow::FILTER_SWITCH
15097            .lock()
15098            .unwrap_or_else(std::sync::PoisonError::into_inner);
15099        let switch = ShadowFilterSwitch { _guard: guard };
15100        switch.reset();
15101        switch
15102    }
15103
15104    /// What [`shadow_filter_switch`] hands back.
15105    struct ShadowFilterSwitch {
15106        _guard: std::sync::MutexGuard<'static, ()>,
15107    }
15108
15109    impl ShadowFilterSwitch {
15110        /// Asks for `filter` on the near side of the seam.
15111        fn filter(&self, filter: shadow::Filter) {
15112            crate::shadow::r_shadow_filter
15113                .set(&crcbl_console::Value::Enum(filter.label()))
15114                .expect("`r_shadow_filter` is a writable enum in the set");
15115        }
15116
15117        /// Asks for a seam at `at`, or for none at zero.
15118        fn seam(&self, at: f32) {
15119            crate::shadow::r_shadow_split
15120                .set(&crcbl_console::Value::Float(at))
15121                .expect("`r_shadow_split` is a writable float in range");
15122        }
15123
15124        /// Asks for `texels` of constant bias.
15125        fn bias(&self, texels: f32) {
15126            crate::shadow::r_shadow_bias
15127                .set(&crcbl_console::Value::Float(texels))
15128                .expect("`r_shadow_bias` is a writable float in range");
15129        }
15130
15131        /// Asks for `texels` of normal offset.
15132        fn offset(&self, texels: f32) {
15133            crate::shadow::r_shadow_normal_offset
15134                .set(&crcbl_console::Value::Float(texels))
15135                .expect("`r_shadow_normal_offset` is a writable float in range");
15136        }
15137
15138        /// Back to the frame every golden was blessed as.
15139        fn reset(&self) {
15140            self.filter(shadow::shipped_filter());
15141            self.seam(0.0);
15142            self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15143            self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15144        }
15145    }
15146
15147    /// The float `var` declares as its default — what a frame nobody typed at
15148    /// is drawn with, read off the variable rather than written down here.
15149    fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15150        match var.default() {
15151            crcbl_console::Value::Float(shipped) => *shipped,
15152            other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15153        }
15154    }
15155
15156    impl Drop for ShadowFilterSwitch {
15157        fn drop(&mut self) {
15158            // Back to the defaults at both ends, so a check that panicked
15159            // mid-way does not hand the next holder a comparing frame.
15160            self.reset();
15161        }
15162    }
15163
15164    /// Takes `r_ssao_slices` for this thread and puts it back at its default
15165    /// when the guard drops.
15166    ///
15167    /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15168    /// `cargo test` run shares one process between tests, and a variable this
15169    /// one left moved is a frame the next test did not ask for.
15170    fn ssao_slice_switch() -> SsaoSliceSwitch {
15171        let guard = SSAO_SLICE_SWITCH
15172            .lock()
15173            .unwrap_or_else(std::sync::PoisonError::into_inner);
15174        let switch = SsaoSliceSwitch { _guard: guard };
15175        switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15176        switch
15177    }
15178
15179    /// What [`ssao_slice_switch`] hands back.
15180    struct SsaoSliceSwitch {
15181        _guard: std::sync::MutexGuard<'static, ()>,
15182    }
15183
15184    impl SsaoSliceSwitch {
15185        /// Asks each pixel for `slices` of them.
15186        fn set(&self, slices: i64) {
15187            crate::ssao::r_ssao_slices
15188                .set(&crcbl_console::Value::Int(slices))
15189                .expect("`r_ssao_slices` is a writable int in range");
15190        }
15191    }
15192
15193    impl Drop for SsaoSliceSwitch {
15194        fn drop(&mut self) {
15195            // Back to the shipping count at both ends, so a check that panicked
15196            // mid-way does not hand the next holder a four-slice frame — which
15197            // is a frame every golden in this workspace was blessed without.
15198            self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15199        }
15200    }
15201
15202    /// [`ssao_slice_switch`]'s lock.
15203    static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15204
15205    /// Takes `r_ssao_technique` for this thread and puts it back at its default
15206    /// when the guard drops.
15207    ///
15208    /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15209    /// a **pipeline** rather than a lane of a uniform block, so a frame that
15210    /// picked it up from another thread's test gathers through a shader that
15211    /// test never selected.
15212    ///
15213    /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15214    /// it is the one switch here whose does: `ssao`'s own
15215    /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15216    /// variable, and a second mutex would serialise neither against the other.
15217    /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15218    fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15219        let guard = crate::ssao::TECHNIQUE_SWITCH
15220            .lock()
15221            .unwrap_or_else(std::sync::PoisonError::into_inner);
15222        let switch = SsaoTechniqueSwitch { _guard: guard };
15223        switch.set(shipped_technique_name());
15224        switch
15225    }
15226
15227    /// The technique name the chain ships, and the one
15228    /// [`ssao_technique_switch`] restores.
15229    ///
15230    /// **Read off the variable rather than written down**, which is
15231    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15232    /// rule about the slice count and for its reason: which value ships is a
15233    /// thing that moves, and a test naming the wrong one would be comparing the
15234    /// shipped configuration against itself.
15235    ///
15236    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15237    fn shipped_technique_name() -> &'static str {
15238        match crate::ssao::r_ssao_technique.default() {
15239            crcbl_console::Value::Enum(name) => name,
15240            other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15241        }
15242    }
15243
15244    /// A name from the variable's own set that is **not** the one it ships.
15245    ///
15246    /// [`shipped_technique_name`]'s clause from the other side: the tests below
15247    /// need a technique to move the console to, and picking it out of the
15248    /// declared set is what keeps them from naming one the variable does not
15249    /// offer — or, if a third arrived, from silently going on comparing the
15250    /// same two.
15251    fn other_technique_name() -> &'static str {
15252        let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15253            panic!("`r_ssao_technique` is an enum variable");
15254        };
15255        let ships = shipped_technique_name();
15256        names
15257            .iter()
15258            .copied()
15259            .find(|name| *name != ships)
15260            .expect("`r_ssao_technique` offers a technique other than the one it ships")
15261    }
15262
15263    /// What [`ssao_technique_switch`] hands back.
15264    struct SsaoTechniqueSwitch {
15265        _guard: std::sync::MutexGuard<'static, ()>,
15266    }
15267
15268    impl SsaoTechniqueSwitch {
15269        /// Asks for the gather `name` selects.
15270        fn set(&self, name: &'static str) {
15271            crate::ssao::r_ssao_technique
15272                .set(&crcbl_console::Value::Enum(name))
15273                .expect("`r_ssao_technique` is a writable enum in the set");
15274        }
15275    }
15276
15277    impl Drop for SsaoTechniqueSwitch {
15278        fn drop(&mut self) {
15279            // Back to what ships at both ends, so a check that panicked mid-way
15280            // does not hand the next holder a frame gathered through the cheap
15281            // tier — which is a frame no golden in this workspace was blessed
15282            // on.
15283            self.set(shipped_technique_name());
15284        }
15285    }
15286
15287    /// Every draw the recorded stream holds, whichever call recorded it.
15288    ///
15289    /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15290    /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15291    /// the thing to compare it against is the whole frame.
15292    fn recorded_draws(recorder: &Recorder) -> usize {
15293        use crcbl_hal::null::Command;
15294
15295        recorder
15296            .commands()
15297            .into_iter()
15298            .filter(|command| {
15299                matches!(
15300                    command,
15301                    Command::Draw { .. }
15302                        | Command::DrawIndexed { .. }
15303                        | Command::DrawIndirect(_)
15304                        | Command::DrawIndexedIndirect(_)
15305                        | Command::DrawIndirectCount(_)
15306                        | Command::DrawIndexedIndirectCount(_)
15307                        | Command::DrawMeshTasks { .. }
15308                        | Command::DrawMeshTasksIndirect(_)
15309                )
15310            })
15311            .count()
15312    }
15313
15314    /// **The draw count is what the frame recorded, and the two GPU-side
15315    /// counters are `None` rather than a guess.**
15316    ///
15317    /// Both halves matter and both are checked here against something that
15318    /// moves. The draws are compared with the recorded stream, so a count that
15319    /// forgot the shadow pass's share or the tonemap's triangle fails. The
15320    /// instances are read before and after a pyramid is put in the pool, so a
15321    /// counter wired to a constant — or to the pool's *capacity*, which does not
15322    /// move — fails too.
15323    ///
15324    /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15325    /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15326    /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15327    /// number invented before any readback landed. That is the assertion that
15328    /// catches the tempting version of this method: an instance count taken from
15329    /// the pool and reported as "drawn" would read as a culling win of exactly
15330    /// zero on every frame, which is the number the whole cull exists to change.
15331    /// What happens once the ring *has* come round is the test below.
15332    #[test]
15333    fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15334        let _blurs = ssao_blur_switch();
15335        let (recorder, device, queue) = open();
15336        let mut renderer =
15337            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15338
15339        // Before any frame: nothing recorded, and said as a known zero.
15340        assert_eq!(renderer.counters(), FrameCounters::default());
15341
15342        let first = frame(device.as_ref(), &mut renderer, queue);
15343        let counters = renderer.counters();
15344        assert_eq!(
15345            counters.draws,
15346            recorded_draws(&recorder) as u64,
15347            "the counter and the frame's recorded draws disagree",
15348        );
15349        // Derived from what the frame resolved rather than from a constant, so
15350        // this is still the every-effect frame's count and would follow a frame
15351        // that switched one off.
15352        let fullscreen = fullscreen_passes(
15353            renderer.effects(),
15354            TEST_EXTENT,
15355            false,
15356            renderer.frame_ssao_blurs,
15357        ) * FULLSCREEN_DRAWS;
15358        assert!(
15359            counters.draws > fullscreen,
15360            "a frame that recorded only its full-screen passes drew no scene",
15361        );
15362        assert_eq!(
15363            counters.instances,
15364            renderer.instances.len() as u64 + fullscreen,
15365        );
15366        assert_eq!(
15367            counters.drawn, None,
15368            "the ring has not come round, so there is no survivor count yet",
15369        );
15370        assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
15371        assert_eq!(counters.triangles, None);
15372        first.release(device.as_ref());
15373
15374        // A second scene: one more instance in the pool, and the counter moves
15375        // with it. The draws do not — one call per bucket whatever the scene
15376        // holds is what §3.3 is about, and this is where that shows.
15377        place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
15378        recorder.clear();
15379        let second = frame(device.as_ref(), &mut renderer, queue);
15380        let richer = renderer.counters();
15381        assert_eq!(
15382            richer.instances,
15383            counters.instances + 1,
15384            "an instance added to the pool must move the counter",
15385        );
15386        assert_eq!(
15387            richer.draws, counters.draws,
15388            "the recorded call count is independent of what the scene holds",
15389        );
15390        assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
15391
15392        second.finish(device.as_ref(), renderer);
15393    }
15394
15395    /// **Once the ring has come round, `drawn` is a number and it says which
15396    /// frame it is from.**
15397    ///
15398    /// The other half of the test above: `indirect` while the readback is in
15399    /// flight, a count afterwards, and a `cull_frame` naming a frame several
15400    /// behind the one just recorded. The null backend executes no copy, so the
15401    /// *value* here is the full-screen passes' own draws and nothing else — what the cull
15402    /// really kept is asserted against a real GPU, in the umbrella crate's
15403    /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
15404    ///
15405    /// The frame number is the assertion with teeth here: a ring that read the
15406    /// slot it had just written would report the frame it is on, and a
15407    /// `cull_frame` left at `None` would put a latent number on the panel with
15408    /// nothing to say how old it is.
15409    #[test]
15410    fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
15411        let (_recorder, device, queue) = open();
15412        let mut renderer =
15413            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15414
15415        let mut frames = Vec::new();
15416        for _ in 0..CULL_STATS_FLOOR {
15417            frames.push(frame(device.as_ref(), &mut renderer, queue));
15418            assert_eq!(
15419                renderer.counters().drawn,
15420                None,
15421                "no readback has even been polled yet, so there is nothing back",
15422            );
15423        }
15424
15425        frames.push(frame(device.as_ref(), &mut renderer, queue));
15426        let counters = renderer.counters();
15427        assert_eq!(
15428            counters.drawn,
15429            Some(
15430                fullscreen_passes(
15431                    renderer.effects(),
15432                    TEST_EXTENT,
15433                    false,
15434                    renderer.frame_ssao_blurs,
15435                ) * FULLSCREEN_DRAWS,
15436            ),
15437            "the survivor count the null backend produced is zero, plus one instance per \
15438             full-screen pass — which is on both sides of the row",
15439        );
15440        assert_eq!(
15441            counters.cull_frame,
15442            Some(1),
15443            "the report is the frame whose copy answered, not the frame just recorded",
15444        );
15445        assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
15446
15447        for frame in frames {
15448            frame.release(device.as_ref());
15449        }
15450        renderer.destroy(device.as_ref());
15451    }
15452
15453    /// The frames a culling counter cannot possibly have arrived in.
15454    ///
15455    /// Two: the copy is recorded on one frame and the readback for it requested
15456    /// on the next, so the earliest frame that can poll anything is the third.
15457    /// A device that answers its first poll — the null backend, and every native
15458    /// one — reports there; a browser answers later, which is why this is a
15459    /// floor rather than a latency. See [`crate::cull_stats`].
15460    const CULL_STATS_FLOOR: usize = 2;
15461
15462    /// **A light that takes a shadow tile moves the draw count**, because the
15463    /// shadow pass records one call per bucket per occupied view.
15464    ///
15465    /// The observable a `recorded_draws` comparison alone would miss: a
15466    /// `counters` that counted only the colour pass and the tonemap agrees with
15467    /// nothing here, and one that hard-coded the cascades agrees with the first
15468    /// frame and not the second.
15469    #[test]
15470    fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
15471        let (recorder, device, queue) = open();
15472        let mut renderer =
15473            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15474
15475        let dark = frame(device.as_ref(), &mut renderer, queue);
15476        let without = renderer.counters().draws;
15477        assert_eq!(without, recorded_draws(&recorder) as u64);
15478        dark.release(device.as_ref());
15479
15480        renderer.set_lights(&[shadowable_spot(0.0)]);
15481        recorder.clear();
15482        let lit = frame(device.as_ref(), &mut renderer, queue);
15483        let with = renderer.counters().draws;
15484        assert!(
15485            with > without,
15486            "a shadow-casting light adds a view and therefore draws: {with} against {without}",
15487        );
15488        assert_eq!(
15489            with,
15490            recorded_draws(&recorder) as u64,
15491            "and the counter still matches the stream",
15492        );
15493        lit.finish(device.as_ref(), renderer);
15494    }
15495
15496    /// Opens a null device offering `optional` on top of the mesh path, and
15497    /// asserts it really selected that path.
15498    ///
15499    /// Asked for rather than merely reported, because a device grants what it
15500    /// enabled: leaving mesh shaders out of the optional set opens a device on
15501    /// an indirect tail and tests nothing.
15502    ///
15503    /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
15504    /// only where `optional` asks for it — so a test that does not gets the
15505    /// mesh tail's call per bucket.
15506    fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
15507        let caps = crcbl_hal::DeviceCaps {
15508            features: Features::GPU_DRIVEN
15509                | Features::MESH_SHADER
15510                | Features::TASK_SHADER
15511                | Features::DRAW_INDEX,
15512            limits: crcbl_hal::Limits::desktop(),
15513        };
15514        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15515        let adapter = instance.adapters().remove(0);
15516        assert_eq!(
15517            adapter.caps.geometry_path(),
15518            GeometryPath::MeshShader,
15519            "a device with mesh shaders selects them, which is the case this is about"
15520        );
15521        let device = instance
15522            .create_device(&DeviceDesc {
15523                label: None,
15524                adapter: adapter.id,
15525                required_features: Features::COMPUTE,
15526                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
15527                compatible_surface: None,
15528            })
15529            .expect("the null backend always opens");
15530        assert_eq!(
15531            device.caps().geometry_path(),
15532            GeometryPath::MeshShader,
15533            "and the opened device still selects it"
15534        );
15535        let queue = device.queue(QueueKind::Graphics).expect("always present");
15536        (device, queue)
15537    }
15538
15539    /// **The four material pages are created with the format their contents
15540    /// call for, and it is only a *colour* that is sRGB.**
15541    ///
15542    /// Topic 44's rung 2 calls this the classic PBR bug and
15543    /// says why it survives review: a base-colour texel and an emissive one are
15544    /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
15545    /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
15546    /// decoding either of those through the sRGB curve is wrong by a gamma and
15547    /// looks merely like a surface bumpier or shinier than the author drew.
15548    /// Nothing in a frame reports it, no golden comparison can name it, and the
15549    /// four constants sit a few lines apart with the wrong one compiling.
15550    ///
15551    /// So this is the whole guard, and it is three claims rather than one: that
15552    /// each constant is the one it should be, that
15553    /// [`PageKind::format`] — which is what the upload loop actually calls —
15554    /// answers with it, and, the half that would otherwise be a check that
15555    /// cannot fail, that the format each page is *created* with is the format
15556    /// its `ImportedImage` declares. A declaration naming a format the image is
15557    /// not in picks the wrong aspects in a barrier.
15558    #[test]
15559    fn the_page_formats_split_colour_from_number() {
15560        assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15561        assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15562        assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
15563        assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
15564        // Through the dispatch the upload loop actually calls, rather than the
15565        // constants alone: one loop creates every image now, and a `format` arm
15566        // pointed at the wrong constant is the way that loop gets it wrong.
15567        assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
15568        assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
15569        assert_eq!(
15570            PageKind::MetallicRoughnessOcclusion.format(),
15571            MRO_PAGE_FORMAT
15572        );
15573        assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
15574        assert_ne!(
15575            BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
15576            "a normal page created sRGB decodes every texel through a gamma it never had"
15577        );
15578        assert_ne!(
15579            EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
15580            "a packed roughness page created sRGB shades every surface smoother than authored"
15581        );
15582
15583        let (recorder, device, queue) = open();
15584        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15585            .expect("the forward renderer builds on the null backend");
15586        assert_eq!(
15587            renderer.base_color_page_import().format,
15588            BASE_COLOR_PAGE_FORMAT
15589        );
15590        assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
15591        assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
15592        assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
15593        // And they really are four images, not one bound four times — which is
15594        // the other way a page could be "linear" and still be sampled through
15595        // the sRGB one.
15596        let created = [
15597            renderer.base_color_page(),
15598            renderer.normal_page(),
15599            renderer.mro_page(),
15600            renderer.emissive_page(),
15601        ];
15602        for (at, page) in created.iter().enumerate() {
15603            for other in &created[at + 1..] {
15604                assert_ne!(page.image, other.image, "two page kinds share one image");
15605                assert_ne!(page.view, other.view, "two page kinds share one view");
15606            }
15607        }
15608        // The labels come off the recorder rather than off the handles, so this
15609        // is evidence about what the device was asked to create.
15610        let images: Vec<String> = recorder
15611            .events()
15612            .into_iter()
15613            .filter_map(|event| match event {
15614                Event::Created {
15615                    kind: ObjectKind::Image,
15616                    label: Some(label),
15617                } => Some(label),
15618                _ => None,
15619            })
15620            .collect();
15621        for kind in PageKind::ALL {
15622            let page = kind.upload_label();
15623            assert!(
15624                images.iter().any(|label| label == page),
15625                "no image was created for the {page} page, and it is {images:?} that were"
15626            );
15627        }
15628        renderer.destroy(device.as_ref());
15629    }
15630
15631    /// Compare native argument indices from the shipped entry points with the
15632    /// actual renderer layout. A shared fragment buffer must have the same index
15633    /// even when geometry introduces additional resources in another module.
15634    #[test]
15635    fn mesh_pipeline_buffers_match_native_shader_arguments() {
15636        for optional in [Features::TASK_SHADER, Features::empty()] {
15637            let recorder = Recorder::new();
15638            let (device, queue) = open_mesh_path(&recorder, optional);
15639            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15640                .expect("the mesh renderer builds");
15641            let (_, entries) = recorder
15642                .bind_group_layouts_created()
15643                .into_iter()
15644                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15645                .expect("the actual mesh layout");
15646            let mut buffers: Vec<_> = entries
15647                .iter()
15648                .filter(|entry| {
15649                    matches!(
15650                        entry.kind,
15651                        BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
15652                    )
15653                })
15654                .collect();
15655            buffers.sort_by_key(|entry| entry.binding);
15656            assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
15657            for (source, shader, names) in [
15658                (
15659                    include_str!("../../crcbl-shaders/shaders/mesh.slang"),
15660                    &MESH,
15661                    &["fragmentMain"][..],
15662                ),
15663                (
15664                    include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
15665                    &MESH_CLUSTER,
15666                    &["meshMain", "taskMain", "amplifiedMeshMain"][..],
15667                ),
15668            ] {
15669                let declarations: Vec<_> = source.lines().collect();
15670                let bindings: Vec<_> = declarations
15671                    .windows(2)
15672                    .filter_map(|lines| {
15673                        let binding = lines[0]
15674                            .trim()
15675                            .strip_prefix("[[vk::binding(")?
15676                            .split(',')
15677                            .next()?
15678                            .parse::<u32>()
15679                            .ok()?;
15680                        // The name is the last word before the D3D12 register.
15681                        let name = lines[1]
15682                            .split(" D3D12_REGISTER(")
15683                            .next()?
15684                            .split_whitespace()
15685                            .last()?
15686                            .trim_end_matches(';');
15687                        Some((name, binding))
15688                    })
15689                    .collect();
15690                for name in names {
15691                    let signature = shader
15692                        .msl()
15693                        .expect("committed native shader")
15694                        .lines()
15695                        .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
15696                        .expect("native entry signature");
15697                    let mut checked = 0;
15698                    for argument in signature.split(", ") {
15699                        let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
15700                            continue;
15701                        };
15702                        let native: usize = tail.split(')').next().unwrap().parse().unwrap();
15703                        let variable = declaration.split_whitespace().last().unwrap();
15704                        let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
15705                        let binding = bindings
15706                            .iter()
15707                            .find(|(candidate, _)| *candidate == variable)
15708                            .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
15709                            .1;
15710                        let expected = buffers
15711                            .iter()
15712                            .position(|entry| entry.binding == binding)
15713                            .expect("shader binding exists in the renderer layout");
15714                        assert_eq!(
15715                            native, expected,
15716                            "{name}: {variable}, logical binding {binding}, native shader vs global layout"
15717                        );
15718                        checked += 1;
15719                    }
15720                    assert!(
15721                        checked >= 10,
15722                        "entry parsing must cover the complete buffer interface"
15723                    );
15724                }
15725            }
15726            renderer.destroy(device.as_ref());
15727        }
15728    }
15729
15730    #[test]
15731    fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
15732        let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
15733        for optional in [Features::TASK_SHADER, Features::empty()] {
15734            let recorder = Recorder::new();
15735            let (device, queue) = open_mesh_path(&recorder, optional);
15736            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15737                .expect("the forward renderer builds on both device shapes");
15738            assert_eq!(
15739                renderer.culls_clusters(),
15740                optional.contains(Features::TASK_SHADER),
15741                "the two arms must actually differ, or this compares a device with itself"
15742            );
15743            let (label, entries) = recorder
15744                .bind_group_layouts_created()
15745                .into_iter()
15746                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15747                .expect("the mesh pass declares its layout by name");
15748            assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
15749            declared.push(
15750                entries
15751                    .iter()
15752                    .map(|entry| (entry.binding, entry.kind))
15753                    .collect(),
15754            );
15755        }
15756
15757        let [amplified, plain] = declared
15758            .try_into()
15759            .unwrap_or_else(|_| unreachable!("two arms were run"));
15760        assert_eq!(
15761            amplified, plain,
15762            "the mesh layout's bindings changed with the task stage, which moves every Metal \
15763             argument-table index above the difference"
15764        );
15765        // These mesh declarations remain present without a task stage.
15766        for binding in [
15767            CLUSTER_CULL_BINDING,
15768            CLUSTER_CULL_STATS_BINDING,
15769            CLUSTER_SELECT_BINDING,
15770            CLUSTER_SELECTION_BINDING,
15771            CLUSTER_GROUP_STATE_BINDING,
15772        ] {
15773            assert!(
15774                plain.iter().any(|(number, _)| *number == binding),
15775                "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
15776            );
15777        }
15778        // Logical gaps consume no native slots. The complete shader union must
15779        // remain sorted, and every mesh-only buffer follows the fragment prefix.
15780        let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
15781        let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
15782        assert_eq!(
15783            numbers, expected,
15784            "the complete sparse shader binding union"
15785        );
15786    }
15787
15788    /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
15789    /// is built, and a device without it still draws.**
15790    ///
15791    /// The two capabilities are separate, and the adapter above offers both — so
15792    /// asking for one and not the other is a device state a real driver has and
15793    /// this can reach. Neither arm is a skip:
15794    ///
15795    /// * With the task stage, the renderer builds the amplification stage and
15796    ///   [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
15797    ///   task stage on a device without the flag, so an arm that computed this
15798    ///   wrongly would fail to build rather than pass quietly. It records one
15799    ///   flat call per partition — [`flat_dispatch_calls`].
15800    /// * Without it, the renderer builds `meshMain` — the un-amplified entry
15801    ///   point — and draws every cluster of every surviving instance, one
15802    ///   indirect dispatch per bucket reading its own extents.
15803    #[test]
15804    fn the_task_stage_is_built_only_where_the_device_has_one() {
15805        use crcbl_hal::null::Command;
15806
15807        for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
15808            let recorder = Recorder::new();
15809            let (device, queue) = open_mesh_path(&recorder, optional);
15810            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15811                .expect("the forward renderer builds on both device shapes");
15812            assert_eq!(
15813                device.caps().supports(Features::TASK_SHADER),
15814                expected,
15815                "the device must actually differ between the arms, or both test the same thing"
15816            );
15817            assert_eq!(
15818                renderer.culls_clusters(),
15819                expected,
15820                "the amplification stage is built exactly where the device has one"
15821            );
15822            assert_eq!(
15823                renderer.geometry_path(),
15824                GeometryPath::MeshShader,
15825                "both arms are the mesh path; only the stage in front of it differs"
15826            );
15827
15828            let frame = frame(device.as_ref(), &mut renderer, queue);
15829            // After the frame, because the buffer named is the slot the frame
15830            // rotated to — asking before it names the previous slot's ring
15831            // entry and the comparison is against a buffer nothing drew from.
15832            let expected = if expected {
15833                flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
15834            } else {
15835                mesh_dispatch_calls(&renderer)
15836            };
15837
15838            let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
15839                .into_iter()
15840                .filter_map(|command| match command {
15841                    Command::DrawMeshTasksIndirect(draw) => Some(draw),
15842                    _ => None,
15843                })
15844                .collect();
15845            assert_eq!(
15846                dispatched, expected,
15847                "a flat call per partition behind the stage, and a dispatch per bucket reading \
15848                 its own extents without it"
15849            );
15850
15851            frame.finish(device.as_ref(), renderer);
15852        }
15853    }
15854
15855    /// The flat calls a pass splitting the bucket table by the material-mode
15856    /// bits `key` records behind a task stage, in region 0, in partition order
15857    /// — one per segment the table holds buckets of — and each segment's first
15858    /// bucket, whose block the call binds.
15859    ///
15860    /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
15861    /// camera generator's own region count rather than from
15862    /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
15863    fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
15864        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15865        let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
15866        let regions = renderer.primary.draws.mode().regions();
15867        let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
15868        let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
15869            vec![0, key]
15870        } else {
15871            DEPTH_MODES.to_vec()
15872        };
15873        values
15874            .into_iter()
15875            .filter(|value| {
15876                renderer
15877                    .bucket_modes
15878                    .iter()
15879                    .any(|mode| mode & key == *value)
15880            })
15881            .map(|value| {
15882                let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
15883                    .expect("a split every pass makes");
15884                (
15885                    DrawIndirect {
15886                        args: renderer.primary.draws.mesh_args(renderer.frame),
15887                        offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
15888                            buckets, regions, 0, segment, 0,
15889                        )) * 4,
15890                        draw_count: 1,
15891                        stride,
15892                    },
15893                    segments[segment as usize].0,
15894                )
15895            })
15896            .unzip()
15897    }
15898
15899    /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
15900    /// order.
15901    ///
15902    /// Built from the buffer the draw-argument pass writes and the stride the
15903    /// APIs fixed, so a test comparing against it is asserting that the call
15904    /// reads *this frame's* arguments at *this bucket's* offset — the two ways
15905    /// an indirect dispatch goes wrong while still dispatching something.
15906    ///
15907    /// **The offsets are multiplied out here rather than asked of
15908    /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
15909    /// comparison and a tautology: an offset function that returned zero for
15910    /// every bucket would agree with itself, and three calls onto one structure
15911    /// is a frame that draws one bucket's geometry three times.
15912    fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
15913        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15914        // The extents share a buffer with the one draw count per bucket that
15915        // precedes them, so every offset is that far in. Written out from the
15916        // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
15917        // for the reason above: a base of zero is exactly the mistake this
15918        // comparison exists to catch, and it would agree with itself.
15919        let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
15920        (0..renderer.bucket_constants.len())
15921            .map(|bucket| DrawIndirect {
15922                args: renderer.primary.draws.mesh_args(renderer.frame),
15923                offset: counts_bytes + bucket as u64 * u64::from(stride),
15924                draw_count: 1,
15925                stride,
15926            })
15927            .collect()
15928    }
15929
15930    /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
15931    /// pipeline, and records no indirect draw and no index-buffer bind at all.**
15932    ///
15933    /// The three halves are one claim. That it dispatched says the path is
15934    /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
15935    /// did not quietly fall through to a tail that draws the same picture; and
15936    /// that it bound no index buffer says the geometry really came out of the
15937    /// cluster records rather than out of the index pool. Until 2026-08 this
15938    /// device degraded and logged that it had, which is exactly the shape —
15939    /// "not implemented" arriving as a passing frame — the three together rule
15940    /// out.
15941    ///
15942    /// **The extents are not here to be checked, and that is the point.** They
15943    /// are three words the draw-argument pass writes, so what this can pin is
15944    /// the call reading *this* bucket's structure out of *this* frame's buffer
15945    /// — and the CPU-side half of the x extent, the per-bucket cluster table
15946    /// the host uploaded, which the null backend keeps the bytes of. What the
15947    /// GPU then makes of it needs a GPU: `crcbl-vk`'s
15948    /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
15949    /// arguments back.
15950    #[test]
15951    fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
15952        use crcbl_hal::null::Command;
15953
15954        let recorder = Recorder::new();
15955        let caps = crcbl_hal::DeviceCaps {
15956            features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15957            limits: crcbl_hal::Limits::desktop(),
15958        };
15959        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15960        let adapter = instance.adapters().remove(0);
15961        assert_eq!(
15962            adapter.caps.geometry_path(),
15963            GeometryPath::MeshShader,
15964            "a device with mesh shaders selects them, which is the case this is about"
15965        );
15966        let device = instance
15967            .create_device(&DeviceDesc {
15968                label: None,
15969                adapter: adapter.id,
15970                required_features: Features::COMPUTE,
15971                // Asked for, because a device reports what it enabled: leaving
15972                // mesh shaders out of the optional set would open a device that
15973                // selects an indirect path outright and test nothing.
15974                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15975                compatible_surface: None,
15976            })
15977            .expect("the null backend always opens");
15978        assert_eq!(
15979            device.caps().geometry_path(),
15980            GeometryPath::MeshShader,
15981            "and the opened device still selects it"
15982        );
15983        let queue = device.queue(QueueKind::Graphics).expect("always present");
15984        let mut renderer =
15985            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15986        assert_eq!(
15987            renderer.geometry_path(),
15988            GeometryPath::MeshShader,
15989            "the renderer must have *built* the mesh path, not merely been offered it"
15990        );
15991        let frame = frame(device.as_ref(), &mut renderer, queue);
15992        let expected = mesh_dispatch_calls(&renderer);
15993        // The table is written once at build, into a host-visible buffer the
15994        // null backend keeps the bytes of — so it is readable whether or not a
15995        // shader ever ran. It shares that buffer with the four other tables the
15996        // draw-argument pass reads, so the region has to be cut out at the
15997        // offset the renderer told the shader about rather than at zero.
15998        let table_bytes = recorder
15999            .buffer_bytes(renderer.primary.draws.tables())
16000            .expect("the table buffer is one of this recorder's buffers");
16001        let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16002        let clusters: Vec<u32> = table_bytes[clusters_at..]
16003            .as_chunks::<4>()
16004            .0
16005            .iter()
16006            .take(renderer.bucket_constants.len())
16007            .map(|word| u32::from_le_bytes(*word))
16008            .collect();
16009
16010        let mut dispatched = Vec::new();
16011        let mut index_binds = 0;
16012        for command in commands_in_pass(&recorder, "forward") {
16013            match command {
16014                Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16015                Command::DrawMeshTasks { .. } => panic!(
16016                    "the mesh path recorded a CPU-sized dispatch, which is the extent \
16017                     the instance cull is supposed to have taken over"
16018                ),
16019                Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16020                    panic!(
16021                        "the mesh path recorded an indirect draw, which is the silent \
16022                         fall-through this test exists to rule out"
16023                    )
16024                }
16025                Command::BindIndexBuffer { .. } => index_binds += 1,
16026                _ => {}
16027            }
16028        }
16029        assert_eq!(
16030            dispatched, expected,
16031            "one indirect dispatch per bucket, each reading its own argument structure \
16032             out of this frame's buffer"
16033        );
16034        assert_eq!(
16035            clusters.len(),
16036            renderer.bucket_constants.len(),
16037            "one x extent per bucket: {clusters:?}"
16038        );
16039        assert!(
16040            clusters.iter().all(|&count| count > 0),
16041            "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16042             {clusters:?}"
16043        );
16044        // **The x extents are not all the same number**, which is what makes
16045        // the table a statement about each bucket's own mesh. Two
16046        // single-cluster meshes would let a table hard-coded to one cluster
16047        // pass; the open box is five, one per face.
16048        assert_eq!(
16049            clusters[DEMO_OPEN_BOX] as usize,
16050            crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16051            "the open box dispatches one workgroup per face, and that is the only \
16052             resident whose cluster count is not one: {clusters:?}"
16053        );
16054        assert_eq!(
16055            index_binds, 0,
16056            "a mesh pipeline has no index buffer; binding one would mean the geometry \
16057             came from the index pool after all"
16058        );
16059
16060        frame.finish(device.as_ref(), renderer);
16061    }
16062
16063    /// **The cull pass is told the camera the frame is drawn with**, and how
16064    /// many array elements to walk.
16065    ///
16066    /// Both halves fail silently: a frustum from a different aspect ratio culls
16067    /// geometry that is on screen, and an instance count short of the pool's
16068    /// high-water mark stops testing the instances above a freed slot. Neither
16069    /// is visible in a picture until something disappears from an edge.
16070    #[test]
16071    fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16072        let (recorder, device, queue) = open();
16073        let mut renderer =
16074            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16075        // The cube first and the pyramid above it, because the second half of
16076        // this test frees the lower slot and asks what the walk still covers.
16077        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16078        place_demo(
16079            &mut renderer,
16080            DEMO_PYRAMID,
16081            DEMO_UNTINTED,
16082            Mat4::from_translation(Vec3::X),
16083        );
16084
16085        let camera = Camera {
16086            eye: Vec3::new(1.6, 1.2, 2.2),
16087            ..Camera::default()
16088        };
16089        let extent = (256u32, 192u32);
16090        renderer
16091            .begin_frame(
16092                device.as_ref(),
16093                &camera,
16094                &DirectionalLight::default(),
16095                extent,
16096            )
16097            .expect("write");
16098
16099        let aspect = extent.0 as f32 / extent.1 as f32;
16100        let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16101        let written = recorder
16102            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16103            .expect("this frame's cull parameters are live");
16104        assert_eq!(
16105            &written[..crcbl_shaders::cull::PARAMS_SIZE],
16106            &crcbl_shaders::cull::Params {
16107                planes: expected.planes.map(|plane| plane.to_array()),
16108                instance_count: 2,
16109                capacity: scene::Capacities::default().instances,
16110                hidden_view: ViewId::PRIMARY.hidden_bit(),
16111                ..crcbl_shaders::cull::Params::default()
16112            }
16113            .to_bytes()[..],
16114            "the cull block must carry this frame's own frustum, the pool's whole \
16115             occupied range, and the visible list's capacity"
16116        );
16117
16118        // And the high-water mark is what is written, not the live count: remove
16119        // the cube and the pyramid above it still has to be tested.
16120        renderer.remove_instance(cube);
16121        renderer
16122            .begin_frame(
16123                device.as_ref(),
16124                &camera,
16125                &DirectionalLight::default(),
16126                extent,
16127            )
16128            .expect("write");
16129        let written = recorder
16130            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16131            .expect("live");
16132        assert_eq!(
16133            u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16134            2,
16135            "one live instance, two occupied slots — a walk of one would never \
16136             reach the pyramid"
16137        );
16138
16139        renderer.destroy(device.as_ref());
16140        recorder.assert_valid();
16141    }
16142
16143    /// **Every counter both compute passes add to is zeroed by a pass of its
16144    /// own, before either of them runs.**
16145    ///
16146    /// The two shaders only ever increment, so a counter carrying the previous
16147    /// frame's total makes a bucket's argument structure claim more instances
16148    /// than its run holds — which draws whatever the run's stale tail happens to
16149    /// name.
16150    ///
16151    /// # This once read the bytes back, and no longer can
16152    ///
16153    /// It used to poison every counter with `0xAB` and assert `begin_frame`
16154    /// had written zeroes over them — the poison being the whole test, because
16155    /// the null backend runs no shader and a counter nothing wrote reads as the
16156    /// zero it was created with. The counters are device-local now, so nothing
16157    /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16158    /// them: the zero is a dispatch inside the frame, and a backend that runs no
16159    /// shader cannot observe it at all.
16160    ///
16161    /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16162    /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16163    /// generated arguments — and what is checkable *here* is the schedule: that
16164    /// the frame contains the clearing pass, that it writes exactly those
16165    /// buffers, and that the graph orders the two accumulating passes after it.
16166    /// Each of the counts below goes red if a buffer is dropped from the
16167    /// clearing pass, and the pass list goes red if the pass leaves the frame.
16168    #[test]
16169    fn every_frame_starts_from_zeroed_counters() {
16170        let (recorder, device, queue) = open();
16171        let mut renderer =
16172            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16173        place_cube(&mut renderer, Mat4::IDENTITY);
16174        let imported = swapchain_image(device.as_ref());
16175        // Twice round the ring, because a slot cleared only on its first use is
16176        // exactly the failure this is about.
16177        for round in 0..FRAMES_IN_FLIGHT * 2 {
16178            renderer
16179                .begin_frame(
16180                    device.as_ref(),
16181                    &Camera::default(),
16182                    &DirectionalLight::default(),
16183                    (64, 48),
16184                )
16185                .expect("write");
16186            let mut graph = crate::RenderGraph::new(queue);
16187            let target = graph.import_image("target", imported);
16188            let pool = crate::TransientPool::new();
16189            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16190            let compiled = graph.compile(&pool).expect("a legal frame");
16191
16192            let clear = &compiled.passes()[0];
16193            assert_eq!(
16194                clear.label(),
16195                "clear-counters",
16196                "round {round}: the zero has to be written before anything adds to it"
16197            );
16198            let barriers = &clear.barriers().buffers;
16199            assert_eq!(
16200                barriers.len(),
16201                3,
16202                "round {round}: the survivor count, the draw arguments, and the buffer \
16203                 holding both the draw counts and the mesh-dispatch arguments, and \
16204                 nothing else: {barriers:?}"
16205            );
16206            assert!(
16207                barriers
16208                    .iter()
16209                    .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16210                "round {round}: every one of them is written by this pass: {barriers:?}"
16211            );
16212            // The ones the frame leaves as indirect arguments are the two a
16213            // driver reads; the survivor count rests in a shader read. That
16214            // split is what names them without a handle to compare.
16215            assert_eq!(
16216                barriers
16217                    .iter()
16218                    .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16219                    .count(),
16220                2,
16221                "round {round}: out of the state a draw read them in: {barriers:?}"
16222            );
16223
16224            let after = |label: &str| {
16225                compiled
16226                    .passes()
16227                    .iter()
16228                    .find(|pass| pass.label() == label)
16229                    .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16230                    .barriers()
16231                    .buffers
16232                    .iter()
16233                    .filter(|barrier| {
16234                        barrier.from == ResourceState::ShaderReadWrite
16235                            && barrier.to == ResourceState::ShaderReadWrite
16236                    })
16237                    .count()
16238            };
16239            assert_eq!(
16240                after("cull"),
16241                1,
16242                "round {round}: the survivor count reaches the cull pass's atomic behind a \
16243                 barrier on the write that zeroed it"
16244            );
16245            assert_eq!(
16246                after("draw-args"),
16247                4,
16248                "round {round}: and so do the draw arguments and the buffer holding the \
16249                 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16250                 which the cull pass has just written and this pass reads through the same \
16251                 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16252                 hysteresis state, which the clearing pass does *not* zero and which is \
16253                 behind the same kind of barrier for the opposite reason: it is the one \
16254                 buffer here carrying a value out of the previous frame, so what it needs \
16255                 ordering against is that frame rather than this one's clear"
16256            );
16257            // **And the prefix sum and the scatter behind barriers of their own**,
16258            // on every buffer the stage before them wrote. This is what orders
16259            // them on a device that runs undeclared commands in any order — see
16260            // `DrawGen::add_passes` — and what three dispatches in one pass
16261            // silently lacked.
16262            for label in ["draw-starts", "draw-scatter"] {
16263                assert_eq!(
16264                    after(label),
16265                    4,
16266                    "round {round}: `{label}` reads what the pass before it wrote, so every \
16267                     buffer they share is ordered behind a barrier"
16268                );
16269            }
16270
16271            // The compiled graph borrows the renderer's pass bodies, so it has
16272            // to go before the next frame borrows the renderer again.
16273            drop(compiled);
16274        }
16275        renderer.destroy(device.as_ref());
16276        device.destroy_image_view(imported.view);
16277        device.destroy_image(imported.image);
16278        recorder.assert_valid();
16279    }
16280
16281    /// **A frame with no instances leaves out every generator's cull and
16282    /// scatter passes**, and keeps the clear and the two stages that write each
16283    /// bucket's arguments.
16284    ///
16285    /// An empty pass is not a harmless no-op on Metal: the backend opens an
16286    /// encoder for every graph pass and strict validation rejects ending one
16287    /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16288    /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16289    #[test]
16290    fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16291        let (recorder, device, queue) = open();
16292        let mut renderer =
16293            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16294        renderer
16295            .begin_frame(
16296                device.as_ref(),
16297                &Camera::default(),
16298                &DirectionalLight::default(),
16299                (64, 48),
16300            )
16301            .expect("write");
16302        let imported = swapchain_image(device.as_ref());
16303        let mut graph = crate::RenderGraph::new(queue);
16304        let target = graph.import_image("target", imported);
16305        let pool = crate::TransientPool::new();
16306        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16307        let compiled = graph.compile(&pool).expect("a legal frame");
16308
16309        let count = |label: &str| {
16310            compiled
16311                .passes()
16312                .iter()
16313                .filter(|pass| pass.label() == label)
16314                .count()
16315        };
16316        // The camera's generator and one per shadow cascade.
16317        let generators = 1 + shadow::CASCADES;
16318        for label in ["clear-counters", "draw-args", "draw-starts"] {
16319            assert_eq!(
16320                count(label),
16321                generators,
16322                "`{label}` still has work with nothing to draw: the clear erases the \
16323                 previous frame's counts and the argument stages write zero draws"
16324            );
16325        }
16326        for label in ["cull", "draw-scatter"] {
16327            assert_eq!(
16328                count(label),
16329                0,
16330                "`{label}` has no workgroups to dispatch with no instances"
16331            );
16332        }
16333
16334        drop(compiled);
16335        renderer.destroy(device.as_ref());
16336        device.destroy_image_view(imported.view);
16337        device.destroy_image(imported.image);
16338        recorder.assert_valid();
16339    }
16340
16341    /// **The graph transitions the generated arguments into
16342    /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16343    /// runs into a shader read.
16344    ///
16345    /// The seam calls this the single most important barrier in a GPU-driven
16346    /// frame and says its absence produces "sometimes nothing draws" — which is
16347    /// exactly the failure a golden image on one driver would not catch. It is
16348    /// asserted on the compiled graph, which is pure and needs no device.
16349    #[test]
16350    fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
16351        let _blurs = ssao_blur_switch();
16352        let (recorder, device, queue) = open();
16353        let mut renderer =
16354            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16355        place_cube(&mut renderer, Mat4::IDENTITY);
16356        renderer
16357            .begin_frame(
16358                device.as_ref(),
16359                &Camera::default(),
16360                &DirectionalLight::default(),
16361                (64, 48),
16362            )
16363            .expect("write");
16364
16365        let imported = swapchain_image(device.as_ref());
16366        let mut graph = crate::RenderGraph::new(queue);
16367        let target = graph.import_image("target", imported);
16368        let pool = crate::TransientPool::new();
16369        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16370        let compiled = graph.compile(&pool).expect("a legal frame");
16371
16372        let passes: Vec<String> = compiled
16373            .passes()
16374            .iter()
16375            .map(|pass| pass.label().to_string())
16376            .collect();
16377        // The camera's five compute passes and topic 18's clustering dispatch,
16378        // then five per shadow cascade, then the depth-only pass they feed and
16379        // the colour pass that samples it.
16380        //
16381        // **The clustering pass is after the camera's clearing dispatch**, and
16382        // that is the ordering the overflow counter depends on: the clearing
16383        // pass zeroes the statistics word this one adds to, and both declare
16384        // the same buffer, so the graph is what puts the barrier between them.
16385        let mut expected: Vec<String> = Vec::new();
16386        for cascade in 0..=shadow::CASCADES {
16387            expected.extend(
16388                [
16389                    "clear-counters",
16390                    "cull",
16391                    "draw-args",
16392                    "draw-starts",
16393                    "draw-scatter",
16394                ]
16395                .into_iter()
16396                .map(str::to_string),
16397            );
16398            if cascade == 0 {
16399                expected.push("light-cluster".to_string());
16400            }
16401        }
16402        // And the culling-statistics copy **last**, after every pass that adds
16403        // to the buffer it reads — the cull dispatch, the clustering pass and
16404        // the amplification stage inside the colour pass.
16405        expected.extend(
16406            [
16407                "shadow",
16408                "depth-prepass",
16409                "ssao",
16410                "ssao-blur",
16411                // The reconstruction that ends the occlusion chain, between the
16412                // blur it reads and the pass that binds what it wrote — see
16413                // [`crate::ssao`]'s header on why the first two run smaller than
16414                // the frame and this one does not.
16415                "ssao-upsample",
16416                "forward",
16417                // The pyramid the march climbs, between the pass that wrote
16418                // level 0 and the pass that reads the chain. Two levels at this
16419                // extent, written out for the reason `crate::bloom`'s chain is
16420                // in the toggle test below: a table generated from
16421                // `crate::hiz::levels_for` could not fail.
16422                "hiz-1",
16423                "hiz-2",
16424                "ssr",
16425                "ssr-blur",
16426                "tonemap",
16427                // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
16428                // CMAA2's three rather than FXAA's one —
16429                // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
16430                // where the swap between the two tiers is pinned.
16431                "cmaa2-edges",
16432                "cmaa2-shapes",
16433                "cmaa2-apply",
16434                "cull-stats-readback",
16435            ]
16436            .into_iter()
16437            .map(str::to_string),
16438        );
16439        assert_eq!(
16440            passes, expected,
16441            "each cull's five compute passes come first, and in that order"
16442        );
16443
16444        // **The depth prepass, not the colour pass**, and that is what says the
16445        // prepass really is the first thing to draw from the camera's cull: it is
16446        // where the draw buffers leave the compute pass's writes. The colour pass
16447        // below then needs none of these, because they are already in the state it
16448        // wants — which is the assertion after it.
16449        let prepass = compiled
16450            .passes()
16451            .iter()
16452            .find(|pass| pass.label() == "depth-prepass")
16453            .expect("the pass list above");
16454        let into_indirect = prepass
16455            .barriers()
16456            .buffers
16457            .iter()
16458            .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
16459            .count();
16460        assert_eq!(
16461            into_indirect,
16462            2,
16463            "the arguments and the count, out of the compute pass's writes and into \
16464             the state a draw reads them in: {:?}",
16465            prepass.barriers().buffers
16466        );
16467        assert!(
16468            prepass.barriers().buffers.iter().any(|barrier| {
16469                barrier.from == ResourceState::ShaderReadWrite
16470                    && barrier.to == ResourceState::ShaderRead
16471            }),
16472            "and the runs, which the vertex stage reads: {:?}",
16473            prepass.barriers().buffers
16474        );
16475
16476        let forward = compiled
16477            .passes()
16478            .iter()
16479            .find(|pass| pass.label() == "forward")
16480            .expect("the pass list above");
16481        assert!(
16482            forward
16483                .barriers()
16484                .buffers
16485                .iter()
16486                .all(|barrier| barrier.to != ResourceState::IndirectArgument),
16487            "the prepass draws from the same arguments, so the colour pass finds them \
16488             already in the state it wants — a barrier here would mean something between \
16489             the two put them back: {:?}",
16490            forward.barriers().buffers
16491        );
16492        // What the colour pass *does* still have to be given: the froxel grid,
16493        // which no earlier pass reads.
16494        assert!(
16495            forward.barriers().buffers.iter().any(|barrier| {
16496                barrier.from == ResourceState::ShaderReadWrite
16497                    && barrier.to == ResourceState::ShaderRead
16498            }),
16499            "and the froxel grid, which its fragment stage reads: {:?}",
16500            forward.barriers().buffers
16501        );
16502
16503        let draw_args = compiled
16504            .passes()
16505            .iter()
16506            .find(|pass| pass.label() == "draw-args")
16507            .expect("the pass list above");
16508        assert!(
16509            draw_args.barriers().buffers.iter().any(|barrier| {
16510                barrier.from == ResourceState::ShaderReadWrite
16511                    && barrier.to == ResourceState::ShaderRead
16512            }),
16513            "and the visible list is ordered after the cull pass wrote it: {:?}",
16514            draw_args.barriers().buffers
16515        );
16516
16517        // The compiled graph borrows the renderer's pass bodies, so it has to go
16518        // before the renderer does.
16519        drop(compiled);
16520        renderer.destroy(device.as_ref());
16521        device.destroy_image_view(imported.view);
16522        device.destroy_image(imported.image);
16523        recorder.assert_valid();
16524    }
16525
16526    /// One more frame than the uniform ring is deep, so at least one lap both
16527    /// reuses a slot and follows a lap that already sampled the atlas.
16528    const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
16529
16530    /// **Every frame's first barrier on the shadow atlas names what the previous
16531    /// frame left it in**, and the same for its placeholder.
16532    ///
16533    /// # Why this cannot be read off one frame
16534    ///
16535    /// The atlas is neither a transient nor a swapchain image. The pool never
16536    /// hands one out and has no description to size it from, and no acquire
16537    /// semaphore sits between one frame's use of it and the next — so
16538    /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
16539    /// makes the transition true.
16540    ///
16541    /// What it declares is [`imported_state`], the pool's record of what the
16542    /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
16543    /// can only ever find the two agreeing for this one import — deliberately,
16544    /// because a declaration and an audit reading one value cannot drift apart
16545    /// the way a renderer-held copy of it could. The audit still has teeth
16546    /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
16547    /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
16548    /// what shows it fires on those.
16549    ///
16550    /// So neither mechanism says anything about the barriers on either side of
16551    /// the declaration — whether the frame that ran actually reached the state
16552    /// the ledger now claims, and whether the next frame's first barrier comes
16553    /// out of it — which is what the stream below is for.
16554    ///
16555    /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
16556    /// failure this catches. It expands to `srcStageMask = NONE,
16557    /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
16558    /// into the depth-only pass's attachment state orders against nothing — while
16559    /// the previous frame's colour pass is still sampling the very same image.
16560    /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
16561    /// `read_barriers: 0`; every other backend resolves it however the driver
16562    /// likes.
16563    ///
16564    /// # Why the command stream is the observable
16565    ///
16566    /// Nothing above the seam can see a wrong declaration: the frame still
16567    /// renders, the golden still matches, and no state is ever read back. So this
16568    /// replays the recorded stream with a tracker, which is the same check a
16569    /// validation layer performs and needs no GPU at all — the shape
16570    /// `crcbl::screenshot`'s
16571    /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
16572    /// One difference: `Undefined` is **not** waved through after the first
16573    /// touch. It is true for a swapchain image because the acquire's semaphore
16574    /// makes it true, and there is no such semaphore here.
16575    #[test]
16576    fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
16577        use crcbl_hal::null::Command;
16578
16579        let (recorder, device, queue) = open();
16580        let device = device.as_ref();
16581        let mut renderer =
16582            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16583        let atlas = renderer.shadow_atlas();
16584        let placeholder = renderer.shadow_placeholder;
16585        let mut pool = crate::TransientPool::new();
16586        let imported = swapchain_image(device);
16587        let mut recorded = Vec::with_capacity(SHADOW_LAPS);
16588
16589        for lap in 0..SHADOW_LAPS {
16590            renderer
16591                .begin_frame(
16592                    device,
16593                    &Camera::default(),
16594                    // **A different sun each lap**, so every lap redraws the
16595                    // atlas: this is a test about the barrier a frame that
16596                    // writes the image declares, and a lap that cached would
16597                    // record no pass and no transition at all. See
16598                    // [`moving_sun`].
16599                    &moving_sun(u32::try_from(lap).expect("a handful of laps")),
16600                    (64, 48),
16601                )
16602                .expect("write");
16603            let mut graph = crate::RenderGraph::new(queue);
16604            let target = graph.import_image("target", imported);
16605            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16606            let compiled = graph.compile(&pool).expect("a legal frame");
16607            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
16608                label: Some("shadow lap"),
16609                queue,
16610            });
16611            compiled
16612                .execute(device, &mut pool, encoder.as_mut(), None)
16613                .expect("the graph executed");
16614            recorded.push(encoder.finish().expect("recording succeeded"));
16615        }
16616
16617        // The two images the renderer owns across frames. A transient's state is
16618        // the pool's business and the fake swapchain image's is the acquire's, so
16619        // neither belongs in here.
16620        let mut tracked = [
16621            (atlas, ResourceState::Undefined),
16622            (placeholder, ResourceState::Undefined),
16623        ];
16624        let mut atlas_writes = 0usize;
16625        let mut named = 0usize;
16626        for command in recorder.commands() {
16627            let Command::Barrier { images, .. } = command else {
16628                continue;
16629            };
16630            for barrier in images {
16631                let Some((_, state)) = tracked
16632                    .iter_mut()
16633                    .find(|(handle, _)| *handle == barrier.image)
16634                else {
16635                    continue;
16636                };
16637                assert_eq!(
16638                    barrier.from, *state,
16639                    "a barrier declared {:?} -> {:?} on an image the frame before it left in \
16640                     {:?}. `Undefined` carries no source scope, so a transition declaring it \
16641                     orders against nothing and the previous frame's sampled read is still in \
16642                     flight underneath it.",
16643                    barrier.from, barrier.to, *state
16644                );
16645                if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
16646                    atlas_writes += 1;
16647                }
16648                *state = barrier.to;
16649                named += 1;
16650            }
16651        }
16652
16653        // Both halves of the loop above are silent on an empty stream, so the
16654        // shape it walked is asserted rather than assumed: one transition into
16655        // the depth-only pass's attachment state per lap, the last one included.
16656        assert_eq!(
16657            atlas_writes, SHADOW_LAPS,
16658            "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
16659             {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
16660             the sun, so every lap redraws the atlas, and anything else means the loop above \
16661             asserted on a stream that does not contain the transition it is about"
16662        );
16663        let (_, ended) = tracked[0];
16664        assert_eq!(
16665            ended,
16666            ResourceState::ShaderRead,
16667            "the import promises to hand the atlas back in the state the next frame declares"
16668        );
16669
16670        renderer.destroy(device);
16671        for commands in recorded {
16672            device.destroy_command_buffer(commands);
16673        }
16674        pool.destroy(device);
16675        device.destroy_image_view(imported.view);
16676        device.destroy_image(imported.image);
16677        recorder.assert_valid();
16678    }
16679
16680    /// A renderer with a shadowed spot beside the sun's cascades and a caster
16681    /// for both to draw, which is the smallest scene the atlas cache has
16682    /// anything to say about: without a light tile the only maps are the
16683    /// cascades, and without a caster every tile is a clear.
16684    fn shadow_cache_scene(
16685        device: &dyn Device,
16686        queue: QueueHandle,
16687    ) -> (ForwardRenderer, InstanceHandle) {
16688        let mut renderer =
16689            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16690        // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
16691        // are process-global and `the_console_moves_both_limits` holds them at
16692        // a four-frame hold and three faces a frame for the length of its
16693        // check. A cache test reading the console inside that window reports
16694        // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
16695        // holding both limits at those values inside the arm's own process,
16696        // which the pin makes harmless.
16697        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
16698        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16699        renderer.set_lights(&[shadowable_spot(-1.0)]);
16700        (renderer, cube)
16701    }
16702
16703    /// Draws one frame and answers whether it drew the shadow atlas, **read two
16704    /// ways that have to agree**.
16705    ///
16706    /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
16707    /// the recorded stream is what the device was actually told; either on its
16708    /// own would be satisfied by a renderer that reported one thing and did the
16709    /// other, which is precisely the failure a cache has. `seen` is the cursor
16710    /// into the cumulative recorder, so each call reads its own frame.
16711    fn drew_the_atlas(
16712        recorder: &Recorder,
16713        seen: &mut usize,
16714        device: &dyn Device,
16715        renderer: &mut ForwardRenderer,
16716        queue: QueueHandle,
16717        camera: &Camera,
16718        sun: &DirectionalLight,
16719    ) -> bool {
16720        let drawn = frame_seen_from(device, renderer, queue, camera, sun);
16721        let claimed = renderer.shadow_atlas_cached();
16722        let commands = recorder.commands();
16723        let opened = commands[*seen..].iter().any(|command| {
16724            command
16725                .opens_pass()
16726                .is_some_and(|(_, label)| label == Some("shadow"))
16727        });
16728        *seen = commands.len();
16729        drawn.release(device);
16730        assert_eq!(
16731            opened,
16732            !claimed,
16733            "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
16734            if opened { "opened" } else { "opened no" }
16735        );
16736        opened
16737    }
16738
16739    #[test]
16740    fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
16741        let (recorder, device, queue) = open();
16742        let device = device.as_ref();
16743        let (mut renderer, _) = shadow_cache_scene(device, queue);
16744        let camera = Camera::default();
16745        let sun = DirectionalLight::default();
16746        let mut seen = 0;
16747        assert!(drew_the_atlas(
16748            &recorder,
16749            &mut seen,
16750            device,
16751            &mut renderer,
16752            queue,
16753            &camera,
16754            &sun
16755        ));
16756        let capacity = (
16757            renderer.shadow_prepare_views.capacity(),
16758            renderer.shadow_prepare_culls.capacity(),
16759        );
16760        assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
16761        assert!(renderer.shadow_prepare_views.is_empty());
16762        assert!(renderer.shadow_prepare_culls.is_empty());
16763        for _ in 0..FRAMES_IN_FLIGHT {
16764            assert!(!drew_the_atlas(
16765                &recorder,
16766                &mut seen,
16767                device,
16768                &mut renderer,
16769                queue,
16770                &camera,
16771                &sun
16772            ));
16773            assert!(renderer.shadow_prepare_views.is_empty());
16774            assert!(renderer.shadow_prepare_culls.is_empty());
16775            assert_eq!(
16776                (
16777                    renderer.shadow_prepare_views.capacity(),
16778                    renderer.shadow_prepare_culls.capacity()
16779                ),
16780                capacity
16781            );
16782        }
16783        for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
16784            // The spot moves for its own view and the camera for the cascades',
16785            // which are fitted to it: a moved spot alone is no input of theirs.
16786            renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
16787            let camera = Camera {
16788                eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
16789                ..camera
16790            };
16791            let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
16792            let short = device
16793                .create_buffer(&BufferDesc {
16794                    label: Some("refused shadow scratch test upload"),
16795                    size: std::mem::size_of::<f32>() as u64,
16796                    usage: BufferUsage::UNIFORM,
16797                    memory: MemoryLocation::HostUpload,
16798                })
16799                .unwrap();
16800            let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
16801            let before = recorder.buffer_bytes(short).unwrap();
16802            let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
16803            renderer.shadow_uniforms[slot][view] = original;
16804            assert!(
16805                matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
16806                "observe a refused shadow uniform: {result:?}"
16807            );
16808            assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
16809            assert!(!recorder.events().iter().any(
16810                |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
16811            ));
16812            assert!(renderer.shadow_prepare_views.is_empty());
16813            assert!(renderer.shadow_prepare_culls.is_empty());
16814            assert_eq!(
16815                (
16816                    renderer.shadow_prepare_views.capacity(),
16817                    renderer.shadow_prepare_culls.capacity()
16818                ),
16819                capacity
16820            );
16821            let refused_inputs = renderer.shadow_group_inputs.clone();
16822            device.destroy_buffer(short);
16823            recorder.assert_valid();
16824            assert!(drew_the_atlas(
16825                &recorder,
16826                &mut seen,
16827                device,
16828                &mut renderer,
16829                queue,
16830                &camera,
16831                &sun
16832            ));
16833            assert_eq!(renderer.shadow_group_inputs, refused_inputs);
16834            assert!(renderer.shadow_prepare_views.is_empty());
16835            assert!(renderer.shadow_prepare_culls.is_empty());
16836            assert_eq!(
16837                (
16838                    renderer.shadow_prepare_views.capacity(),
16839                    renderer.shadow_prepare_culls.capacity()
16840                ),
16841                capacity
16842            );
16843            assert!(!drew_the_atlas(
16844                &recorder,
16845                &mut seen,
16846                device,
16847                &mut renderer,
16848                queue,
16849                &camera,
16850                &sun
16851            ));
16852        }
16853        renderer.destroy(device);
16854        recorder.assert_valid();
16855        assert_eq!(recorder.total_live_objects(), 0);
16856    }
16857
16858    /// **A frame over a scene nothing moved in does not draw the shadow atlas
16859    /// again**, and what it saves is the whole of the atlas's work.
16860    ///
16861    /// Topic 45's static-caching rung, and the observable it
16862    /// otherwise has none for: the map a cached frame samples is byte for byte
16863    /// the map the frame before it sampled, so no golden image and no readback
16864    /// can tell the two frames apart. The recorded command stream can — and the
16865    /// dispatch count is the half that says the *culls* went with the pass,
16866    /// rather than the frame still paying for the draws it decided not to
16867    /// record.
16868    #[test]
16869    fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
16870        use crcbl_hal::null::Command;
16871
16872        // The blur count is a process-global console variable, and the frame's
16873        // draw count below includes the full-screen triangle each blur records
16874        // — so a concurrent test holding `r_ssao_blur_passes` at two would move
16875        // it under this one. Held rather than merely read, which is the
16876        // convention that variable's own test set.
16877        let _blurs = ssao_blur_switch();
16878        let (recorder, device, queue) = open();
16879        let device = device.as_ref();
16880        let (mut renderer, _) = shadow_cache_scene(device, queue);
16881        let camera = Camera::default();
16882        let sun = DirectionalLight::default();
16883
16884        let mut seen = 0usize;
16885        let dispatches = |recorder: &Recorder, from: usize| {
16886            recorder.commands()[from..]
16887                .iter()
16888                .filter(|command| matches!(command, Command::Dispatch { .. }))
16889                .count()
16890        };
16891
16892        let at = seen;
16893        assert!(
16894            drew_the_atlas(
16895                &recorder,
16896                &mut seen,
16897                device,
16898                &mut renderer,
16899                queue,
16900                &camera,
16901                &sun
16902            ),
16903            "the first frame of all has to draw the atlas: nothing has put anything in it"
16904        );
16905        let first = dispatches(&recorder, at);
16906        let drawing_draws = renderer.counters().draws;
16907        let buckets = renderer.bucket_constants.len() as u64;
16908        assert!(
16909            renderer.shadow_lights().base_of(0).is_some(),
16910            "the spot must hold a run for the count below to include a light slot's cull"
16911        );
16912        // The camera's own draw generation and topic 18's clustering dispatch,
16913        // plus a generation per cascade and one for the spot's slot.
16914        assert_eq!(
16915            first,
16916            DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
16917            "the drawing frame did not record the culls this test is about skipping"
16918        );
16919
16920        for round in 0..3 {
16921            let at = seen;
16922            assert!(
16923                !drew_the_atlas(
16924                    &recorder,
16925                    &mut seen,
16926                    device,
16927                    &mut renderer,
16928                    queue,
16929                    &camera,
16930                    &sun
16931                ),
16932                "round {round} redrew an atlas nothing had changed"
16933            );
16934            assert_eq!(
16935                dispatches(&recorder, at),
16936                DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
16937                "round {round} kept a shadow cull it had no pass to feed"
16938            );
16939            assert_eq!(
16940                drawing_draws - renderer.counters().draws,
16941                (shadow::CASCADES + 1) as u64 * buckets,
16942                "round {round}: the frame's own draw count did not lose exactly the atlas's \
16943                 calls — one per bucket per cascade, and one per bucket for the spot's tile"
16944            );
16945        }
16946
16947        renderer.destroy(device);
16948        recorder.assert_valid();
16949    }
16950
16951    /// A cadence that holds every map one rung down for a frame, with the whole
16952    /// atlas's worth of tiles to spend.
16953    ///
16954    /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
16955    /// the console: [`shadow::r_shadow_cadence`] is process-global and the
16956    /// shadow pass is in every frame's pass list, so a test that moved it would
16957    /// change the frame every other test in this module draws.
16958    const HOLD_TWO: shadow::Cadence = shadow::Cadence {
16959        hold: 2,
16960        faces: shadow::TILES,
16961    };
16962
16963    /// How the shadow pass loaded its depth attachment, over the commands from
16964    /// `from` on, and [`None`] where the frame recorded no such pass.
16965    ///
16966    /// **The observable the tile clear otherwise has none for.** A frame that
16967    /// kept a tile and a frame that redrew every one of them sample maps that
16968    /// may be identical, so nothing in the picture separates them; this is the
16969    /// declaration that says which the device was told.
16970    fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
16971        use crcbl_hal::null::Command;
16972
16973        recorder.commands()[from..].iter().find_map(|command| {
16974            let Command::BeginRenderPass {
16975                label,
16976                depth_stencil_attachment,
16977                ..
16978            } = command
16979            else {
16980                return None;
16981            };
16982            if label.as_deref() != Some("shadow") {
16983                return None;
16984            }
16985            depth_stencil_attachment
16986                .as_ref()
16987                .map(|attachment| attachment.depth_load)
16988        })
16989    }
16990
16991    /// Direct draws recorded inside the shadow pass, over the commands from
16992    /// `from` on — which is one per tile the pass reset itself, the atlas's
16993    /// geometry being drawn indirectly.
16994    fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
16995        use crcbl_hal::null::Command;
16996
16997        let mut inside = false;
16998        let mut clears = 0;
16999        for command in &recorder.commands()[from..] {
17000            if let Some((_, label)) = command.opens_pass() {
17001                inside = label == Some("shadow");
17002                continue;
17003            }
17004            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17005                inside = false;
17006                continue;
17007            }
17008            if inside && matches!(command, Command::Draw { .. }) {
17009                clears += 1;
17010            }
17011        }
17012        clears
17013    }
17014
17015    /// **The far cascade is redrawn every second frame and the near one every
17016    /// frame**, on a scene where the eye moves and so every map is out of date.
17017    ///
17018    /// Topic 45's cadence rung, and the observable it otherwise
17019    /// has none for: a held map draws a shadow one frame behind its caster,
17020    /// which is a plausible picture and one a golden accepts.
17021    ///
17022    /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17023    /// reset — that is asserted rather than assumed, because a reset would make
17024    /// every frame redraw everything and this test would pass by having
17025    /// switched the cadence off.
17026    #[test]
17027    fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17028        let _blurs = ssao_blur_switch();
17029        let (recorder, device, queue) = open();
17030        let device = device.as_ref();
17031        let (mut renderer, _) = shadow_cache_scene(device, queue);
17032        let sun = DirectionalLight::default();
17033        renderer.set_shadow_cadence(Some(HOLD_TWO));
17034
17035        const FRAMES: usize = 8;
17036        let mut near = 0;
17037        let mut far = 0;
17038        for step in 0..FRAMES {
17039            #[expect(
17040                clippy::cast_precision_loss,
17041                reason = "a handful of frames, and the step is what is wanted"
17042            )]
17043            let camera = Camera {
17044                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17045                ..Camera::default()
17046            };
17047            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17048            assert_eq!(
17049                renderer.shadow_cadence_reset(),
17050                step == 0,
17051                "frame {step}: only the first frame has an atlas to lay out, and a reset \
17052                 after it would redraw everything and leave nothing for the cadence to hold"
17053            );
17054            near += usize::from(renderer.shadow_cascade_redrawn(0));
17055            far += usize::from(renderer.shadow_cascade_redrawn(1));
17056            drawn.release(device);
17057        }
17058        assert_eq!(
17059            near, FRAMES,
17060            "the near cascade is fitted to the eye and is on the top rung: every frame"
17061        );
17062        assert_eq!(
17063            far,
17064            FRAMES / 2,
17065            "the far cascade is one rung down, so every second frame"
17066        );
17067
17068        renderer.destroy(device);
17069        recorder.assert_valid();
17070    }
17071
17072    /// **A frame that keeps a tile loads the attachment and resets the tiles it
17073    /// redraws itself**, and a frame that keeps none clears it — which is what
17074    /// shipped.
17075    ///
17076    /// The half of the cadence a redraw count cannot see: holding a tile is only
17077    /// worth anything if the tile survives, and the one clear this seam has
17078    /// covers the whole image. A frame that loaded and reset nothing would draw
17079    /// into tiles still holding the last frame's depths, and under reversed-Z a
17080    /// caster that moved away would go on occluding.
17081    #[test]
17082    fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17083        let _blurs = ssao_blur_switch();
17084        let (recorder, device, queue) = open();
17085        let device = device.as_ref();
17086        let (mut renderer, _) = shadow_cache_scene(device, queue);
17087        let sun = DirectionalLight::default();
17088
17089        // The first frame lays the atlas out, so it clears and redraws
17090        // everything whatever the console says.
17091        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17092        first.release(device);
17093        assert_eq!(
17094            shadow_pass_depth_load(&recorder, 0),
17095            Some(LoadOp::Clear),
17096            "the frame that lays the atlas out has nothing to keep"
17097        );
17098        assert_eq!(
17099            tile_clears_in_the_shadow_pass(&recorder, 0),
17100            0,
17101            "and so resets no tile of its own"
17102        );
17103
17104        renderer.set_shadow_cadence(Some(HOLD_TWO));
17105        let mut seen = recorder.commands().len();
17106        let mut loaded = 0;
17107        for step in 1..4 {
17108            #[expect(
17109                clippy::cast_precision_loss,
17110                reason = "a handful of frames, and the step is what is wanted"
17111            )]
17112            let camera = Camera {
17113                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17114                ..Camera::default()
17115            };
17116            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17117            let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17118            let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17119            let faces = renderer.shadow_faces_redrawn() as usize;
17120            if load == LoadOp::Load {
17121                loaded += 1;
17122                assert_eq!(
17123                    clears, faces,
17124                    "frame {step} loaded the attachment and reset {clears} of the {faces} \
17125                     tiles it redrew"
17126                );
17127                assert!(
17128                    faces < shadow::TILES,
17129                    "frame {step} loaded an attachment while redrawing every tile"
17130                );
17131            } else {
17132                assert_eq!(
17133                    clears, 0,
17134                    "frame {step} cleared the attachment and reset {clears} tiles again"
17135                );
17136            }
17137            seen = recorder.commands().len();
17138            drawn.release(device);
17139        }
17140        assert!(
17141            loaded > 0,
17142            "no frame kept a tile, so nothing here is about the load path"
17143        );
17144
17145        renderer.destroy(device);
17146        recorder.assert_valid();
17147    }
17148
17149    /// A point light costs the budget every face it draws, not one.
17150    ///
17151    /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17152    /// a sum over the groups a frame redrew of the maps each of them owns, and
17153    /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17154    /// here is built on the sun and a spot, which own one map each — so a face
17155    /// count that answered `1` for every group would satisfy all of them, and
17156    /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17157    /// suite. This is what binds on the difference.
17158    #[test]
17159    fn a_point_light_costs_the_budget_every_face_it_draws() {
17160        let _blurs = ssao_blur_switch();
17161        let (_recorder, device, queue) = open();
17162        let device = device.as_ref();
17163        let mut renderer =
17164            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17165        let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17166        renderer.set_lights(&[shadowable_point(-1.0)]);
17167        let sun = DirectionalLight::default();
17168
17169        // Every group is forced on the first frame — the image has held none of
17170        // them — so this counts what a full redraw actually costs.
17171        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17172        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17173        first.release(device);
17174        let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17175        assert!(
17176            renderer.shadow_lights().base_of(0).is_some(),
17177            "the point must hold a run of tiles, or there is no multi-face group to count"
17178        );
17179        assert!(
17180            renderer.shadow_faces_redrawn() >= point_faces,
17181            "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17182             {point_faces} it owns — so the budget is counting groups rather than the maps they \
17183             draw, and a cube would slip past a budget of one",
17184            renderer.shadow_faces_redrawn()
17185        );
17186    }
17187
17188    /// **A frame never redraws more tiles than the budget allows**, and every
17189    /// map still gets its turn.
17190    ///
17191    /// The starvation half is what makes this more than an inequality: a
17192    /// schedule that spent the budget on the same maps every frame would satisfy
17193    /// the bound and never draw the rest at all.
17194    #[test]
17195    fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17196        let _blurs = ssao_blur_switch();
17197        let (recorder, device, queue) = open();
17198        let device = device.as_ref();
17199        let (mut renderer, _) = shadow_cache_scene(device, queue);
17200        let sun = DirectionalLight::default();
17201
17202        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17203        first.release(device);
17204        assert!(
17205            renderer.shadow_lights().base_of(0).is_some(),
17206            "the spot must hold a run, or the budget has only the cascades to bind on"
17207        );
17208
17209        // One tile a frame: the two cascades and the spot's map cannot all fit,
17210        // so something is held on every frame of the run below.
17211        const BUDGET: u32 = 1;
17212        renderer.set_shadow_cadence(Some(shadow::Cadence {
17213            hold: 1,
17214            faces: BUDGET as usize,
17215        }));
17216        const FRAMES: usize = 12;
17217        let mut drew = [0usize; 3];
17218        for step in 1..=FRAMES {
17219            #[expect(
17220                clippy::cast_precision_loss,
17221                reason = "a handful of frames, and the step is what is wanted"
17222            )]
17223            let camera = Camera {
17224                eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17225                ..Camera::default()
17226            };
17227            // The spot drifts too: its map is not fitted to the camera, so a
17228            // moving eye alone leaves it up to date and asking for nothing.
17229            #[expect(
17230                clippy::cast_precision_loss,
17231                reason = "a handful of frames, and the step is what is wanted"
17232            )]
17233            renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17234            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17235            assert!(
17236                renderer.shadow_faces_redrawn() <= BUDGET,
17237                "frame {step} redrew {} tiles against a budget of {BUDGET}",
17238                renderer.shadow_faces_redrawn()
17239            );
17240            drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17241            drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17242            drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17243            drawn.release(device);
17244        }
17245        for (map, count) in drew.iter().enumerate() {
17246            assert!(
17247                *count > 0,
17248                "map {map} was never redrawn in {FRAMES} frames under a budget of \
17249                 {BUDGET}: {drew:?}"
17250            );
17251        }
17252
17253        renderer.destroy(device);
17254        recorder.assert_valid();
17255    }
17256
17257    /// **A light that jumps further than its own radius resets the cadence**,
17258    /// and one that drifts inside it does not.
17259    ///
17260    /// Topic 45's "a moving light or camera cut resets it",
17261    /// made precise: a map whose centre has moved past the map's own reach is
17262    /// not a frame out of date, it is about somewhere else — so it is redrawn on
17263    /// the frame that notices rather than when its turn comes round. Both arms,
17264    /// because a reset that fired on every move would be the cadence switched
17265    /// off.
17266    #[test]
17267    fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17268        let _blurs = ssao_blur_switch();
17269        let (recorder, device, queue) = open();
17270        let device = device.as_ref();
17271        let (mut renderer, _) = shadow_cache_scene(device, queue);
17272        let sun = DirectionalLight::default();
17273        let camera = Camera::default();
17274        // The coarsest hold there is, so a redraw of the spot's map on the
17275        // frames below is the reset and not its turn.
17276        renderer.set_shadow_cadence(Some(shadow::Cadence {
17277            hold: 8,
17278            faces: shadow::TILES,
17279        }));
17280
17281        let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17282        settle.release(device);
17283        for _ in 0..2 {
17284            settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17285            settle.release(device);
17286        }
17287        assert!(
17288            !renderer.shadow_cadence_reset(),
17289            "the scene has settled, so nothing is about somewhere else"
17290        );
17291
17292        // A drift well inside the light's own radius: out of date, not moved.
17293        renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17294        let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17295        drifted.release(device);
17296        assert!(
17297            !renderer.shadow_cadence_reset(),
17298            "a light that moved a sixteenth of its radius is a map a frame out of date"
17299        );
17300
17301        // And a jump past it. `shadowable_spot`'s radius is what the reach is
17302        // taken from, so this is a light standing where its own map says
17303        // nothing.
17304        renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17305        let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17306        jumped.release(device);
17307        assert!(
17308            renderer.shadow_cadence_reset(),
17309            "a light that jumped five times its own radius must not hold its map"
17310        );
17311        assert!(
17312            renderer.shadow_slot_redrawn(0),
17313            "and the reset is only a reset if the map is actually redrawn"
17314        );
17315
17316        renderer.destroy(device);
17317        recorder.assert_valid();
17318    }
17319
17320    /// **A console knob about *sampling* the atlas does not redraw it.**
17321    ///
17322    /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17323    /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17324    /// receiver it reads — and not one byte of what the depth pass writes into
17325    /// it is any of theirs. Yet the
17326    /// shadow views' blocks are the frame's block spread, and the cache record
17327    /// is those blocks' bytes — so until the views zeroed the row, a person
17328    /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17329    /// and in this crate's own test process the filter tests moving that cell
17330    /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17331    /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17332    /// here is what makes the move below the only one in flight.
17333    #[test]
17334    fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17335        let switch = shadow_filter_switch();
17336        let (recorder, device, queue) = open();
17337        let device = device.as_ref();
17338        let (mut renderer, _) = shadow_cache_scene(device, queue);
17339        let camera = Camera::default();
17340        let sun = DirectionalLight::default();
17341        let mut seen = 0usize;
17342        assert!(
17343            drew_the_atlas(
17344                &recorder,
17345                &mut seen,
17346                device,
17347                &mut renderer,
17348                queue,
17349                &camera,
17350                &sun
17351            ),
17352            "the first frame of all draws the atlas"
17353        );
17354        assert!(
17355            !drew_the_atlas(
17356                &recorder,
17357                &mut seen,
17358                device,
17359                &mut renderer,
17360                queue,
17361                &camera,
17362                &sun
17363            ),
17364            "a still second frame has to hold it, or the move below proves nothing"
17365        );
17366
17367        switch.filter(shadow::Filter::Box);
17368        switch.seam(0.5);
17369        assert!(
17370            !drew_the_atlas(
17371                &recorder,
17372                &mut seen,
17373                device,
17374                &mut renderer,
17375                queue,
17376                &camera,
17377                &sun
17378            ),
17379            "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
17380             sampling knob reached the record of what the maps were drawn from"
17381        );
17382
17383        // The bias pair sits in a different row of the same block, and the
17384        // second row it reaches is `Cascades::params`, which is rebuilt every
17385        // frame — so this is the arm that says the *whole* row is kept out of
17386        // the record rather than the one lane the filter is in.
17387        switch.bias(8.0);
17388        switch.offset(8.0);
17389        assert!(
17390            !drew_the_atlas(
17391                &recorder,
17392                &mut seen,
17393                device,
17394                &mut renderer,
17395                queue,
17396                &camera,
17397                &sun
17398            ),
17399            "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
17400             the bias row reached the record of what the maps were drawn from"
17401        );
17402
17403        renderer.destroy(device);
17404        recorder.assert_valid();
17405    }
17406
17407    /// **Every input the atlas is drawn from redraws it**, one at a time.
17408    ///
17409    /// The half that stops "cached everything, for ever" from passing every
17410    /// assertion above. Each arm moves exactly one thing and asserts the next
17411    /// frame draws again — and then holds still and asserts it stops, so an arm
17412    /// cannot pass by having broken the cache outright.
17413    ///
17414    /// The camera is in here because it is not obvious: a shadow map is drawn
17415    /// from a light, not from the eye. But a cascade is fitted to the camera's
17416    /// own frustum, and every shadow cull selects a DAG's detail at the camera's
17417    /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
17418    /// different light map wherever a DAG is in the light's cull.
17419    /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
17420    /// caster must *not* redraw.
17421    ///
17422    /// `settles` is how many still frames it takes to go quiet again, and it is
17423    /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
17424    /// instance's `previous_transform` back at rest on the frame *after* the
17425    /// move, and that is a write, which is a change this record cannot tell
17426    /// from any other. See `InstancePool::take_written`, which says so.
17427    #[test]
17428    fn each_thing_the_atlas_is_drawn_from_redraws_it() {
17429        let camera = Camera::default();
17430        let sun = DirectionalLight::default();
17431        let moved_camera = Camera {
17432            eye: camera.eye + Vec3::X * 4.0,
17433            ..camera
17434        };
17435        type Change = fn(&mut ForwardRenderer, InstanceHandle);
17436        let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
17437            (
17438                "a caster moved",
17439                |renderer, cube| {
17440                    renderer.set_instance(
17441                        cube,
17442                        &InstanceDesc {
17443                            mesh: DEMO_CUBE,
17444                            material: DEMO_UNTINTED,
17445                            transform: Mat4::from_translation(Vec3::X),
17446                        },
17447                    );
17448                },
17449                &camera,
17450                &sun,
17451                2,
17452            ),
17453            (
17454                "a caster removed",
17455                |renderer, cube| renderer.remove_instance(cube),
17456                &camera,
17457                &sun,
17458                1,
17459            ),
17460            (
17461                "the light moved",
17462                |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
17463                &camera,
17464                &sun,
17465                1,
17466            ),
17467            ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
17468        ];
17469
17470        for (what, change, camera, sun, settles) in arms {
17471            let (recorder, device, queue) = open();
17472            let device = device.as_ref();
17473            let (mut renderer, cube) = shadow_cache_scene(device, queue);
17474            let mut seen = 0usize;
17475            // Two frames, so the atlas is drawn and then held: the arm's own
17476            // assertion is about a frame that would otherwise have cached.
17477            for round in 0..2 {
17478                let drew = drew_the_atlas(
17479                    &recorder,
17480                    &mut seen,
17481                    device,
17482                    &mut renderer,
17483                    queue,
17484                    &Camera::default(),
17485                    &DirectionalLight::default(),
17486                );
17487                assert_eq!(
17488                    drew,
17489                    round == 0,
17490                    "{what}: the still frames before the change did not settle"
17491                );
17492            }
17493
17494            change(&mut renderer, cube);
17495            assert!(
17496                drew_the_atlas(
17497                    &recorder,
17498                    &mut seen,
17499                    device,
17500                    &mut renderer,
17501                    queue,
17502                    camera,
17503                    sun
17504                ),
17505                "{what} and the atlas was not drawn again"
17506            );
17507            // And it goes quiet again in exactly `settles` frames, so the arm
17508            // cannot pass by having broken the cache rather than by having
17509            // invalidated it — and a change that started redrawing for ever
17510            // fails here rather than going unnoticed.
17511            for round in 0..settles {
17512                assert_eq!(
17513                    drew_the_atlas(
17514                        &recorder,
17515                        &mut seen,
17516                        device,
17517                        &mut renderer,
17518                        queue,
17519                        camera,
17520                        sun
17521                    ),
17522                    round + 1 < settles,
17523                    "{what}: the still frames after the change did not settle in {settles}"
17524                );
17525            }
17526
17527            renderer.destroy(device);
17528            recorder.assert_valid();
17529        }
17530    }
17531
17532    /// **A frame with a skinned object in it always redraws the atlas**, and
17533    /// that is a limit written down rather than a gap.
17534    ///
17535    /// A skinned caster's vertices are produced by a compute dispatch into the
17536    /// pool, so there is nothing on the host to compare: the palette a caller
17537    /// hands over is not the geometry, and the geometry is never read back. The
17538    /// honest answer is to redraw, and the dishonest one is a map of a pose the
17539    /// character has left.
17540    #[test]
17541    fn a_frame_with_a_skinned_object_never_caches_the_atlas() {
17542        let (recorder, device, queue) = open();
17543        let device = device.as_ref();
17544        let mut fixture = SkinnedFixture::build(device, queue);
17545        fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
17546        let imported = swapchain_image_at(device, TEST_EXTENT);
17547        let mut pool = crate::TransientPool::new();
17548
17549        // The same palette and the same plan every lap, so nothing a host-side
17550        // comparison could see has moved.
17551        for lap in 0..3 {
17552            fixture.begin(device);
17553            let mut graph = crate::RenderGraph::new(queue);
17554            let target = graph.import_image("target", imported);
17555            fixture.renderer.add_skinned_passes(
17556                &mut graph,
17557                &pool,
17558                target,
17559                TEST_EXTENT,
17560                &fixture.skinning,
17561            );
17562            let compiled = graph.compile(&pool).expect("a legal frame");
17563            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17564                label: Some("skinned lap"),
17565                queue,
17566            });
17567            compiled
17568                .execute(device, &mut pool, encoder.as_mut(), None)
17569                .expect("the graph executed");
17570            device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
17571            assert!(
17572                !fixture.renderer.shadow_atlas_cached(),
17573                "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
17574            );
17575        }
17576
17577        fixture.destroy(device);
17578        pool.destroy(device);
17579        device.destroy_image_view(imported.view);
17580        device.destroy_image(imported.image);
17581        recorder.assert_valid();
17582    }
17583
17584    /// **Switching the shadows off clears the atlas once, and then holds the
17585    /// clear**, which is the same cache answering a frame that draws nothing.
17586    ///
17587    /// The switched-off frame is not itself a cached frame: the pass has to run
17588    /// to write the reversed-Z clear that makes every comparison come back lit,
17589    /// and the image holds the last drawn maps until it does. What *is* cached
17590    /// is every frame after it, and the record for a switched-off frame is
17591    /// deliberately blind to the camera and the casters, because nothing about
17592    /// them reaches an atlas nothing draws into.
17593    #[test]
17594    fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
17595        let (recorder, device, queue) = open();
17596        let device = device.as_ref();
17597        let (mut renderer, cube) = shadow_cache_scene(device, queue);
17598        let camera = Camera::default();
17599        let sun = DirectionalLight::default();
17600        let mut seen = 0usize;
17601
17602        assert!(
17603            drew_the_atlas(
17604                &recorder,
17605                &mut seen,
17606                device,
17607                &mut renderer,
17608                queue,
17609                &camera,
17610                &sun
17611            ),
17612            "the first frame draws the maps"
17613        );
17614        renderer.set_effect_request(EffectRequest {
17615            programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
17616            ..EffectRequest::default()
17617        });
17618        assert!(
17619            drew_the_atlas(
17620                &recorder,
17621                &mut seen,
17622                device,
17623                &mut renderer,
17624                queue,
17625                &camera,
17626                &sun
17627            ),
17628            "the frame that switched the shadows off has to run the pass that clears the maps \
17629             out of the image"
17630        );
17631        assert!(
17632            !drew_the_atlas(
17633                &recorder,
17634                &mut seen,
17635                device,
17636                &mut renderer,
17637                queue,
17638                &camera,
17639                &sun
17640            ),
17641            "a second switched-off frame cleared an atlas that was already clear"
17642        );
17643        // And nothing about the scene reaches a frame that draws no map: the
17644        // caster moves and the atlas is still the clear it was.
17645        renderer.set_instance(
17646            cube,
17647            &InstanceDesc {
17648                mesh: DEMO_CUBE,
17649                material: DEMO_UNTINTED,
17650                transform: Mat4::from_translation(Vec3::X),
17651            },
17652        );
17653        assert!(
17654            !drew_the_atlas(
17655                &recorder,
17656                &mut seen,
17657                device,
17658                &mut renderer,
17659                queue,
17660                &camera,
17661                &sun
17662            ),
17663            "a caster moved with the shadows off, and the frame cleared the atlas over again"
17664        );
17665
17666        renderer.set_effect_request(EffectRequest::default());
17667        assert!(
17668            drew_the_atlas(
17669                &recorder,
17670                &mut seen,
17671                device,
17672                &mut renderer,
17673                queue,
17674                &camera,
17675                &sun
17676            ),
17677            "switching the shadows back on has to draw the maps the clear replaced"
17678        );
17679
17680        renderer.destroy(device);
17681        recorder.assert_valid();
17682    }
17683
17684    /// **A frame the graph refuses leaves the shadow atlas where it was.**
17685    ///
17686    /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
17687    /// described in full and then thrown away, and
17688    /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
17689    /// thing that writes the pool's ledger — never runs. That is the case a
17690    /// renderer-held `ResourceState`, stepped forward while the passes were
17691    /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
17692    /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
17693    /// object, because with nothing recorded there is nothing to contradict. The
17694    /// guard would be silent on precisely the drift it exists to find, which is
17695    /// why [`imported_state`] reads the ledger instead of a second copy of it.
17696    ///
17697    /// The observable is the first barrier the *next* frame records on the
17698    /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
17699    /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
17700    /// layout the image was never in, which is a layout mismatch on every
17701    /// backend and a discarded image on some.
17702    #[test]
17703    fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
17704        use crcbl_hal::null::Command;
17705
17706        let (recorder, device, queue) = open();
17707        let device = device.as_ref();
17708        let mut renderer =
17709            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17710        let atlas = renderer.shadow_atlas();
17711        let placeholder = renderer.shadow_placeholder;
17712        let mut pool = crate::TransientPool::new();
17713        let imported = swapchain_image(device);
17714
17715        // The refused frame: every pass a real frame declares, and beside them
17716        // one transient nothing reads or writes. `compile` answers
17717        // `UnusedTransient` and the whole description — the shadow atlas's
17718        // import included — is dropped without a command being recorded.
17719        renderer
17720            .begin_frame(
17721                device,
17722                &Camera::default(),
17723                &DirectionalLight::default(),
17724                (64, 48),
17725            )
17726            .expect("write");
17727        {
17728            let mut graph = crate::RenderGraph::new(queue);
17729            let target = graph.import_image("target", imported);
17730            renderer.add_passes(&mut graph, &pool, target, (64, 48));
17731            graph.create_image("orphan", crate::targets::scene_color((64, 48)));
17732            let refused = graph
17733                .compile(&pool)
17734                .expect_err("a transient no pass declares");
17735            assert!(
17736                matches!(refused, crate::GraphError::UnusedTransient { .. }),
17737                "the frame has to be refused for the reason this test is about — a graph that \
17738                 compiled would go on to execute and the ledger would be written after all: \
17739                 {refused:?}"
17740            );
17741        }
17742        assert_eq!(
17743            pool.imported_image_use(atlas),
17744            None,
17745            "nothing executed, so the ledger has nothing to say about the atlas — this is the \
17746             emptiness `InitialClaim::Tracked` cannot check against"
17747        );
17748
17749        // And the frame after it, which does run.
17750        renderer
17751            .begin_frame(
17752                device,
17753                &Camera::default(),
17754                &DirectionalLight::default(),
17755                (64, 48),
17756            )
17757            .expect("write");
17758        let mut graph = crate::RenderGraph::new(queue);
17759        let target = graph.import_image("target", imported);
17760        renderer.add_passes(&mut graph, &pool, target, (64, 48));
17761        let compiled = graph.compile(&pool).expect("a legal frame");
17762        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17763            label: Some("frame after a refusal"),
17764            queue,
17765        });
17766        compiled
17767            .execute(device, &mut pool, encoder.as_mut(), None)
17768            .expect("the graph executed");
17769        let commands = encoder.finish().expect("recording succeeded");
17770
17771        // The first barrier each of the two images gets. Only the refused frame
17772        // ran before this one and it recorded nothing, so these are the frame's
17773        // opening transitions.
17774        let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
17775        for command in recorder.commands() {
17776            let Command::Barrier { images, .. } = command else {
17777                continue;
17778            };
17779            for barrier in images {
17780                if barrier.image != atlas && barrier.image != placeholder {
17781                    continue;
17782                }
17783                if opened.iter().any(|(image, _, _)| *image == barrier.image) {
17784                    continue;
17785                }
17786                opened.push((barrier.image, barrier.from, barrier.to));
17787            }
17788        }
17789        for (image, from, to) in &opened {
17790            assert_eq!(
17791                *from,
17792                ResourceState::Undefined,
17793                "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
17794                 layout to. The declaration is what makes the transition true, so one that has \
17795                 moved on without an executed frame behind it names a source scope and an old \
17796                 layout the image was never in — and the ledger is empty, so nothing refuses it \
17797                 either. Image {image:?}"
17798            );
17799        }
17800        // The loop above is silent on an empty list and on a short one, and a
17801        // wrong declaration shortens it: an image declared in the state it is
17802        // wanted in needs no transition, so it drops out of the stream
17803        // altogether rather than appearing with the wrong source.
17804        assert_eq!(
17805            opened.len(),
17806            2,
17807            "the atlas and its placeholder are both imported every frame and both are wanted in a \
17808             state they are not in, so both have to be barriered: {opened:?}"
17809        );
17810        assert!(
17811            opened
17812                .iter()
17813                .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
17814            "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
17815        );
17816
17817        renderer.destroy(device);
17818        device.destroy_command_buffer(commands);
17819        pool.destroy(device);
17820        device.destroy_image_view(imported.view);
17821        device.destroy_image(imported.image);
17822        recorder.assert_valid();
17823    }
17824
17825    /// **The import audit still refuses an engine site whose declaration is
17826    /// wrong**, now that the shadow atlas's is read out of the same ledger it is
17827    /// checked against.
17828    ///
17829    /// That pair is deliberately circular and this test is what keeps it from
17830    /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
17831    /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
17832    /// ever find them agreeing — their safety comes from there being one answer
17833    /// rather than from the check. Every *other* import in the frame declares a
17834    /// constant, and `ssao-placeholder` is the one this drives a ledger entry
17835    /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
17836    /// declared so on every frame, so a graph that leaves it somewhere else is a
17837    /// declaration the next `compile` has to refuse.
17838    #[test]
17839    fn the_guard_still_catches_an_engine_import_that_lies() {
17840        let (recorder, device, queue) = open();
17841        let device = device.as_ref();
17842        let mut renderer =
17843            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17844        let mut pool = crate::TransientPool::new();
17845        let imported = swapchain_image(device);
17846        let occlusion = renderer.ambient_occlusion_placeholder.image;
17847
17848        // A graph of this test's own, which moves the renderer's occlusion
17849        // placeholder somewhere `add_passes` does not expect. Same image handle,
17850        // so the entry it leaves in the ledger is the one the next `compile`
17851        // reads for `ssao-placeholder`.
17852        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17853            label: Some("move the placeholder"),
17854            queue,
17855        });
17856        {
17857            let mut graph = crate::RenderGraph::new(queue);
17858            let moved = graph.import_image(
17859                "moved-placeholder",
17860                ImportedImage {
17861                    image: occlusion,
17862                    view: renderer.ambient_occlusion_placeholder.view,
17863                    format: Format::Rgba8Unorm,
17864                    extent: (1, 1),
17865                    initial: ResourceState::ShaderRead,
17866                    claim: InitialClaim::Tracked,
17867                    final_state: ResourceState::TransferSrc,
17868                },
17869            );
17870            graph
17871                .add_copy_pass("read the placeholder")
17872                .use_image(moved, ResourceState::TransferSrc)
17873                .execute(|_| {});
17874            graph
17875                .compile(&pool)
17876                .expect("a legal frame")
17877                .execute(device, &mut pool, encoder.as_mut(), None)
17878                .expect("the graph executed");
17879        }
17880        let commands = encoder.finish().expect("recording succeeded");
17881        assert_eq!(
17882            pool.imported_image_use(occlusion),
17883            Some(ResourceState::TransferSrc),
17884            "the ledger has to have moved for the frame below to have anything to disagree with"
17885        );
17886
17887        renderer
17888            .begin_frame(
17889                device,
17890                &Camera::default(),
17891                &DirectionalLight::default(),
17892                (64, 48),
17893            )
17894            .expect("write");
17895        let mut graph = crate::RenderGraph::new(queue);
17896        let target = graph.import_image("target", imported);
17897        renderer.add_passes(&mut graph, &pool, target, (64, 48));
17898        let refused = graph
17899            .compile(&pool)
17900            .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
17901        let crate::GraphError::ImportStateMismatch {
17902            resource,
17903            declared,
17904            left,
17905        } = &refused
17906        else {
17907            panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
17908        };
17909        assert_eq!(resource, "ssao-placeholder");
17910        assert_eq!(*declared, ResourceState::ShaderRead);
17911        assert_eq!(*left, ResourceState::TransferSrc);
17912
17913        renderer.destroy(device);
17914        device.destroy_command_buffer(commands);
17915        pool.destroy(device);
17916        device.destroy_image_view(imported.view);
17917        device.destroy_image(imported.image);
17918        recorder.assert_valid();
17919    }
17920
17921    /// Compiles one frame and names the passes it turned out to be, in order.
17922    ///
17923    /// Compiled and not executed: what a pass costs is not the question here,
17924    /// only which of them the frame declared. Names rather than a count since
17925    /// the toggles landed — a count says a frame lost two passes and a list says
17926    /// *which* two, which is the difference between "the switch did something"
17927    /// and "the switch did the thing it is for".
17928    fn passes_in_a_frame(
17929        device: &dyn Device,
17930        queue: QueueHandle,
17931        renderer: &mut ForwardRenderer,
17932        imported: ImportedImage,
17933        pool: &crate::TransientPool,
17934        extent: (u32, u32),
17935    ) -> Vec<String> {
17936        renderer
17937            .begin_frame(
17938                device,
17939                &Camera::default(),
17940                &DirectionalLight::default(),
17941                extent,
17942            )
17943            .expect("write");
17944        let mut graph = crate::RenderGraph::new(queue);
17945        let target = graph.import_image("target", imported);
17946        renderer.add_passes(&mut graph, pool, target, extent);
17947        graph
17948            .compile(pool)
17949            .expect("a legal frame")
17950            .passes()
17951            .iter()
17952            .map(|pass| pass.label().to_string())
17953            .collect()
17954    }
17955
17956    /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
17957    /// radius, a direction and a cone well inside the widest one allowed.
17958    /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
17959    /// than one.
17960    ///
17961    /// The spot beside it is one tile and one face, so a scene built only from
17962    /// spots cannot tell a budget counting **faces** from one counting groups —
17963    /// which is what this exists to give a check something to bind on.
17964    fn shadowable_point(x: f32) -> Light {
17965        Light::Point(crate::light::PointLight {
17966            position: Vec3::new(x, 2.0, 0.0),
17967            radius: 8.0,
17968            color: Vec3::ONE,
17969            fill: false,
17970        })
17971    }
17972
17973    fn shadowable_spot(x: f32) -> Light {
17974        Light::Spot(crate::light::SpotLight {
17975            position: Vec3::new(x, 2.0, 0.0),
17976            radius: 8.0,
17977            color: Vec3::ONE,
17978            direction: -Vec3::Y,
17979            inner_angle: 0.3,
17980            outer_angle: 0.6,
17981            fill: false,
17982        })
17983    }
17984
17985    /// The page's anisotropy is the plan's default clamped to the device, and
17986    /// one on a device that was not granted the feature — whatever its limit
17987    /// says.
17988    ///
17989    /// The last arm is the one worth having: `gate_limits_on_features` narrows
17990    /// a declined feature's limit on `crcbl-vk`, but a backend that did not
17991    /// would report sixteen beside an absent feature, and a clamp that read the
17992    /// limit alone would ask for a sampler the device refuses.
17993    #[test]
17994    fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
17995        let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
17996            features,
17997            limits: crcbl_hal::Limits {
17998                max_sampler_anisotropy,
17999                ..crcbl_hal::Limits::desktop()
18000            },
18001        };
18002        let granted = Features::SAMPLER_ANISOTROPY;
18003        assert!(
18004            (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18005                < f32::EPSILON,
18006            "a device above the default gets the default"
18007        );
18008        assert!(
18009            (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18010            "a device below the default gets its own limit"
18011        );
18012        assert!(
18013            (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18014                < f32::EPSILON,
18015            "a device that was not granted the feature gets one, whatever its limit says"
18016        );
18017    }
18018
18019    /// A new anisotropy is a new sampler, and every slot moves onto it at its
18020    /// own frame — the old one living until the last slot has left it.
18021    ///
18022    /// Counted on the null recorder rather than looked at: the sampler count
18023    /// rises by one at the call, holds through every slot's frame but the
18024    /// last, and falls back there, while the live group count never moves at
18025    /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18026    /// destroyed a group a slot in flight still held, and one that never
18027    /// happened each move one of those counts; a second lap of the ring
18028    /// creating any group at all would be a rebuild that did not know it was
18029    /// done.
18030    #[test]
18031    fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18032        let (recorder, device, queue) =
18033            open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18034        let device = device.as_ref();
18035        let mut renderer =
18036            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18037        assert!(
18038            (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18039            "a renderer nobody has called the setter on samples at the default"
18040        );
18041        let samplers = recorder.live_objects(ObjectKind::Sampler);
18042        let groups = recorder.live_objects(ObjectKind::BindGroup);
18043        let groups_created = || {
18044            recorder
18045                .events()
18046                .iter()
18047                .filter(|event| {
18048                    matches!(
18049                        event,
18050                        Event::Created {
18051                            kind: ObjectKind::BindGroup,
18052                            ..
18053                        }
18054                    )
18055                })
18056                .count()
18057        };
18058
18059        renderer
18060            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18061            .expect("the device allows it");
18062        assert_eq!(
18063            recorder.live_objects(ObjectKind::Sampler),
18064            samplers,
18065            "the value in force creates nothing"
18066        );
18067
18068        renderer
18069            .set_anisotropy(device, 4.0)
18070            .expect("the device allows it");
18071        assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18072        assert_eq!(
18073            recorder.live_objects(ObjectKind::Sampler),
18074            samplers + 1,
18075            "the new sampler stands beside the one every slot still names"
18076        );
18077        assert_eq!(
18078            recorder.live_objects(ObjectKind::BindGroup),
18079            groups,
18080            "no group moves until its slot's frame"
18081        );
18082
18083        for round in 0..FRAMES_IN_FLIGHT {
18084            renderer
18085                .begin_frame(
18086                    device,
18087                    &Camera::default(),
18088                    &DirectionalLight::default(),
18089                    (64, 48),
18090                )
18091                .expect("write");
18092            let expected = if round + 1 < FRAMES_IN_FLIGHT {
18093                samplers + 1
18094            } else {
18095                samplers
18096            };
18097            assert_eq!(
18098                recorder.live_objects(ObjectKind::Sampler),
18099                expected,
18100                "round {round}: the replaced sampler lives until the last slot has left it"
18101            );
18102            assert_eq!(
18103                recorder.live_objects(ObjectKind::BindGroup),
18104                groups,
18105                "round {round}: every rebuilt group replaced one"
18106            );
18107        }
18108        let created = groups_created();
18109        for _ in 0..FRAMES_IN_FLIGHT {
18110            renderer
18111                .begin_frame(
18112                    device,
18113                    &Camera::default(),
18114                    &DirectionalLight::default(),
18115                    (64, 48),
18116                )
18117                .expect("write");
18118        }
18119        assert_eq!(
18120            groups_created(),
18121            created,
18122            "a slot already on the sampler in force rebuilds nothing"
18123        );
18124
18125        // The clamp: the device's ceiling above it, off below one, the default
18126        // for a value that is not a number.
18127        let ceiling = device.caps().limits.max_sampler_anisotropy;
18128        renderer
18129            .set_anisotropy(device, ceiling * 4.0)
18130            .expect("clamped to what the device allows");
18131        assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18132        renderer
18133            .set_anisotropy(device, 0.0)
18134            .expect("one is the value that turns it off");
18135        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18136        renderer
18137            .set_anisotropy(device, f32::NAN)
18138            .expect("the default is a sampler the device allows");
18139        assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18140
18141        recorder.assert_valid();
18142        renderer.destroy(device);
18143        assert_eq!(
18144            recorder.live_objects(ObjectKind::Sampler),
18145            0,
18146            "the samplers no slot ever adopted went with the renderer"
18147        );
18148    }
18149
18150    /// A device without the feature samples isotropically whatever is asked:
18151    /// the ceiling is one, so the clamp lands on the value already in force and
18152    /// no sampler is created that `create_sampler` would refuse.
18153    #[test]
18154    fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18155        let (recorder, device, queue) = open();
18156        let device = device.as_ref();
18157        assert!(
18158            !device
18159                .caps()
18160                .features
18161                .contains(Features::SAMPLER_ANISOTROPY),
18162            "the default request does not name the feature"
18163        );
18164        let mut renderer =
18165            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18166        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18167        let samplers = recorder.live_objects(ObjectKind::Sampler);
18168
18169        renderer
18170            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18171            .expect("asks for nothing the device lacks");
18172        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18173        assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18174        renderer.destroy(device);
18175    }
18176
18177    /// The knob clamps to the range it documents, in both directions and on a
18178    /// value that is neither.
18179    ///
18180    /// **The `NaN` arm is the one worth having.** A slider that divided by a
18181    /// zero, or a settings file that carried a nonsense string, reaches this
18182    /// with a value that fails every comparison it is put through — so a naive
18183    /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18184    /// `as u32` below would produce a zero extent and a device error a long way
18185    /// from here.
18186    #[test]
18187    fn the_render_scale_is_clamped_to_the_range_it_documents() {
18188        let (recorder, device, queue) = open();
18189        let device = device.as_ref();
18190        let mut renderer =
18191            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18192
18193        assert!(
18194            (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18195            "a renderer nobody has called the setter on draws at full scale"
18196        );
18197
18198        renderer.set_render_scale(0.5);
18199        assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18200
18201        // Above one is supersampling, which this filter is the wrong one for.
18202        renderer.set_render_scale(2.0);
18203        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18204
18205        renderer.set_render_scale(0.01);
18206        assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18207
18208        renderer.set_render_scale(f32::NAN);
18209        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18210        renderer.set_render_scale(f32::INFINITY);
18211        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18212
18213        renderer.destroy(device);
18214        recorder.assert_valid();
18215    }
18216
18217    /// The internal extent is the target rounded, never zero, and is the target
18218    /// itself at full scale.
18219    ///
18220    /// **The floor is not decoration.** A transient image of zero extent is a
18221    /// device error rather than a small frame, and a 4×3 target at the minimum
18222    /// scale is exactly the arithmetic that would produce one.
18223    #[test]
18224    fn the_internal_extent_rounds_and_never_reaches_zero() {
18225        let (recorder, device, queue) = open();
18226        let device = device.as_ref();
18227        let mut renderer =
18228            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18229
18230        assert_eq!(
18231            renderer.internal_extent((1920, 1080)),
18232            (1920, 1080),
18233            "full scale is the absence of the feature, not a resize by one"
18234        );
18235
18236        renderer.set_render_scale(0.5);
18237        assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18238
18239        // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18240        // 756 — both exact — so a target that does *not* divide evenly is what
18241        // shows the rounding. 1281 * 0.7 = 896.7.
18242        renderer.set_render_scale(0.7);
18243        assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18244
18245        renderer.set_render_scale(MIN_RENDER_SCALE);
18246        assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18247        assert_eq!(
18248            renderer.internal_extent((0, 0)),
18249            (1, 1),
18250            "a minimised window is the caller's zero extent, and this may not \
18251             pass it through as one"
18252        );
18253
18254        renderer.destroy(device);
18255        recorder.assert_valid();
18256    }
18257
18258    /// **The upscale is a pass below full scale and is not there above it**, and
18259    /// the frame is otherwise the same list.
18260    ///
18261    /// This is the observable the knob is: everything else about it — the
18262    /// clamps, the rounding — is arithmetic that could be right while the frame
18263    /// went on being drawn at the caller's extent. What says the feature works
18264    /// is that the pass appears, that it appears **last**, and that switching it
18265    /// off leaves the frame that was there before it existed.
18266    #[test]
18267    fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18268        let _blurs = ssao_blur_switch();
18269        let (recorder, device, queue) = open();
18270        let device = device.as_ref();
18271        let mut renderer =
18272            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18273        let imported = swapchain_image_at(device, TEST_EXTENT);
18274        let pool = crate::TransientPool::new();
18275
18276        let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18277        assert!(
18278            !full.contains(&"upscale".to_string()),
18279            "a frame at full scale has no upscale in it: {full:?}"
18280        );
18281
18282        renderer.set_render_scale(0.5);
18283        let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18284        assert_eq!(
18285            scaled.iter().filter(|label| *label == "upscale").count(),
18286            1,
18287            "a scaled frame records exactly one upscale: {scaled:?}"
18288        );
18289        // Last of the passes that draw. The statistics copy is genuinely after
18290        // it and says so — see the comment on `add_copy_pass`'s placement.
18291        let upscale = scaled
18292            .iter()
18293            .position(|label| label == "upscale")
18294            .expect("the assertion above");
18295        let tonemap = scaled
18296            .iter()
18297            .position(|label| label == "tonemap")
18298            .expect("every frame tonemaps");
18299        assert!(
18300            upscale > tonemap,
18301            "the upscale carries what the post chain ended with: {scaled:?}"
18302        );
18303
18304        // **The pyramid gets shorter, and that is the evidence the rest of the
18305        // frame really is smaller.** Everything above this is about the last
18306        // pass; a knob that added an upscale while going on rendering at the
18307        // caller's extent would pass every one of those assertions and save
18308        // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18309        // level count is a number read out of the frame that can only be the
18310        // internal extent's.
18311        let levels = |passes: &[String]| {
18312            passes
18313                .iter()
18314                .filter(|label| label.starts_with("hiz-"))
18315                .count()
18316        };
18317        let internal = renderer.internal_extent(TEST_EXTENT);
18318        assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18319        assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18320        assert!(
18321            levels(&scaled) < levels(&full),
18322            "at this extent the halved frame has to lose a level, or this \
18323             assertion is not looking at anything: {scaled:?}"
18324        );
18325
18326        // And nothing else moved: an upscale is a pass added to the frame, not a
18327        // frame rebuilt around one. The pyramid is the one part that is a
18328        // function of the extent, so it is compared by the count above and
18329        // dropped from the list here.
18330        let without_hiz = |passes: &[String]| -> Vec<String> {
18331            passes
18332                .iter()
18333                .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
18334                .cloned()
18335                .collect()
18336        };
18337        assert_eq!(
18338            without_hiz(&scaled),
18339            without_hiz(&full),
18340            "the scaled frame is the full-scale frame, one pass longer and one \
18341             pyramid shorter"
18342        );
18343
18344        renderer.set_render_scale(1.0);
18345        let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18346        assert_eq!(
18347            back, full,
18348            "the knob goes back, which is what a settings slider does"
18349        );
18350
18351        renderer.destroy(device);
18352        device.destroy_image_view(imported.view);
18353        device.destroy_image(imported.image);
18354        recorder.assert_valid();
18355    }
18356
18357    /// **A skinned-frame overlay receives the display and depth images at the
18358    /// internal extent, before either resolve reconstructs the target.**
18359    ///
18360    /// The callback's own pass attaches the display and depth it received. That
18361    /// makes matching dimensions a graph invariant rather than a comparison of
18362    /// numbers the callback could have been handed without ever using the
18363    /// images; changing either id to a target-sized image makes compilation
18364    /// refuse the mismatched attachments.
18365    #[test]
18366    fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
18367        let (recorder, device, queue) = open();
18368        let device = device.as_ref();
18369        let mut fixture = SkinnedFixture::build(device, queue);
18370        fixture.renderer.set_render_scale(0.5);
18371        fixture.renderer.set_effect_request(EffectRequest {
18372            antialiasing: Some(Antialiasing::Fxaa),
18373            ..EffectRequest::default()
18374        });
18375        fixture.begin(device);
18376        let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
18377
18378        let imported = swapchain_image_at(device, TEST_EXTENT);
18379        let mut pool = crate::TransientPool::new();
18380        {
18381            let mut graph = crate::RenderGraph::new(queue);
18382            let target = graph.import_image("target", imported);
18383            let mut received = None;
18384            fixture.renderer.add_skinned_passes_with_overlay(
18385                &mut graph,
18386                &pool,
18387                target,
18388                TEST_EXTENT,
18389                &fixture.skinning,
18390                |graph, targets| {
18391                    received = Some(targets);
18392                    graph
18393                        .add_render_pass("overlay-probe")
18394                        .color(
18395                            targets.display,
18396                            LoadOp::Load,
18397                            StoreOp::Store,
18398                            crcbl_hal::ClearValue::default(),
18399                        )
18400                        .depth_read(targets.depth)
18401                        .execute(|_| {});
18402                },
18403            );
18404            let received = received.expect("the overlay callback runs while the frame is built");
18405            assert_eq!(
18406                received.internal_extent, internal_extent,
18407                "the overlay receives the extent its display and depth attachments have"
18408            );
18409
18410            let compiled = graph.compile(&pool).expect("the shared attachments match");
18411            let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
18412            let overlay = labels
18413                .iter()
18414                .position(|label| *label == "overlay-probe")
18415                .expect("the callback's pass is part of the frame");
18416            let fxaa = labels
18417                .iter()
18418                .position(|label| *label == "fxaa")
18419                .expect("the requested resolve is part of the frame");
18420            let upscale = labels
18421                .iter()
18422                .position(|label| *label == "upscale")
18423                .expect("the half-scale frame reconstructs its target");
18424            assert!(
18425                overlay < fxaa && overlay < upscale,
18426                "the overlay must write display before its resolve and upscale: {labels:?}"
18427            );
18428        }
18429
18430        fixture.destroy(device);
18431        pool.destroy(device);
18432        device.destroy_image_view(imported.view);
18433        device.destroy_image(imported.image);
18434        recorder.assert_valid();
18435    }
18436
18437    /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
18438    ///
18439    /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
18440    /// halves matter: a bound under the widest frame times part of it and drops
18441    /// the rest, and a bound well over it buys query sets nothing ever writes.
18442    /// A shadowable spot per light slot fills every one of them, which is the
18443    /// most culls a frame can run and so the widest frame there is — it must land
18444    /// exactly on the constant, and the frame with no shadowed light at all must
18445    /// be short of it by exactly the culls those slots would have added.
18446    ///
18447    /// The ground grid is switched on for **both** frames, because the widest
18448    /// frame is the one that has it: it is off by default and not a
18449    /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
18450    /// debug draw layer is on for both frames for the same reason, and it needs
18451    /// a segment appended before each rather than one switch, because
18452    /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
18453    ///
18454    /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
18455    /// [`TEST_EXTENT`], with every effect forced on and the render scale off
18456    /// full.** The bloom chain's length is a function of the extent the frame is
18457    /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
18458    /// records is a *large* one, and a bound checked against a 64×48 frame would
18459    /// sit six passes above what that frame runs and this assertion would have
18460    /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
18461    /// frame buys query sets nothing writes, and only an exact comparison
18462    /// notices.
18463    ///
18464    /// **The render scale is what makes those two requirements compose.** The
18465    /// upscale is a pass only below full scale, and below full scale the chain
18466    /// runs at the *internal* extent — so a frame with both is one whose
18467    /// internal extent is the longest chain's, and whose target is larger than
18468    /// that. Halving a target of 2048×1024 is what arranges it, and the two
18469    /// assertions below check the arrangement rather than trusting it.
18470    ///
18471    /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
18472    #[test]
18473    fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
18474        /// The extent whose bloom chain is the longest [`crate::bloom`] will
18475        /// build: six halvings of 512 leave sixteen by eight, which is still at
18476        /// or above that module's floor. The widest frame is drawn at this,
18477        /// which is why it is the internal one and not the target.
18478        const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
18479        /// Half, so the frame records an upscale and draws at
18480        /// [`WIDEST_INTERNAL`].
18481        const WIDEST_SCALE: f32 = 0.5;
18482        /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
18483        const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
18484
18485        let (recorder, device, queue) = open();
18486        let device = device.as_ref();
18487        // **A scene whose probes ask to be updated**, because the widest frame
18488        // is the one with every pass in it and
18489        // the irradiance probes' two are recorded by a volume
18490        // rather than by an effect bit — the ground grid's argument exactly. A
18491        // renderer built on the demo's empty grid records neither, and the bound
18492        // would then be checked against a frame that could not reach it.
18493        let mut scene = scene::demo();
18494        scene.capacities.probes = 1;
18495        scene.probes = scene::ProbeGrid {
18496            volume: crcbl_shaders::probe::ProbeVolume {
18497                origin: [0.0; 3],
18498                inv_spacing: [1.0; 3],
18499                counts: [1, 1, 1],
18500                levels: 1,
18501                steps: crcbl_shaders::probe::ProbeSteps::default(),
18502            },
18503            probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
18504            update: ProbeUpdate::EveryFrame,
18505        };
18506        let mut renderer =
18507            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
18508                .expect("built");
18509        // A maximum-width graph must include actual instances to cull.
18510        place_cube(&mut renderer, Mat4::IDENTITY);
18511        renderer
18512            .set_ground_grid(device, Some(GridStyle::default()))
18513            .expect("the null backend builds every pipeline");
18514        // **And the occlusion cull**, whose late prepass, farthest pyramid and
18515        // three late compute passes are the ground grid's kind of pass: off
18516        // unless a caller asks, and in the widest frame when one does.
18517        renderer.set_occlusion_culling(OcclusionCulling {
18518            occlusion: true,
18519            small_feature_pixels: None,
18520        });
18521        // **A body of water**, on the ground grid's terms: content rather than
18522        // an effect bit, so the widest frame is one a caller gave water to, and
18523        // `Water::PASSES` is in the bound for it.
18524        renderer
18525            .set_water(&[crcbl_water::WaterBody {
18526                outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
18527                level: 0.0,
18528                medium: crcbl_water::Medium {
18529                    absorption: [0.4, 0.1, 0.05],
18530                    scattering: [0.01, 0.01, 0.01],
18531                },
18532            }])
18533            .expect("a square meshes");
18534        // **A field of grass**, on the water body's terms exactly: content
18535        // rather than an effect bit, so the widest frame is one a caller gave a
18536        // field to and `Grass::PASSES` is in the bound for it.
18537        renderer
18538            .set_grass(
18539                device,
18540                queue,
18541                Some(
18542                    &crate::grass::GrassField::new(
18543                        [1, 1],
18544                        4.0,
18545                        [-2.0, -2.0],
18546                        50.0,
18547                        crate::grass::Heightfield {
18548                            texels: [4, 4],
18549                            metres_per_texel: 1.0,
18550                            origin: [-2.0, -2.0],
18551                            heights: vec![0.0; 16],
18552                        },
18553                        crate::grass::CoverMap {
18554                            texels: [4, 4],
18555                            metres_per_texel: 1.0,
18556                            origin: [-2.0, -2.0],
18557                            cover: vec![[255, 0]; 16],
18558                        },
18559                        // A shell row and a mesh blade row, so the widest
18560                        // frame records every look's draw the grass pass has.
18561                        [
18562                            crate::grass::BladeLook::Shells,
18563                            crate::grass::BladeLook::Blades,
18564                        ]
18565                        .map(|look| crate::grass::BladeType {
18566                            root_color: [0.05, 0.1, 0.02],
18567                            tip_color: [0.3, 0.5, 0.1],
18568                            height: 0.3,
18569                            half_width: 0.03,
18570                            height_spread: 0.3,
18571                            width_spread: 0.2,
18572                            look,
18573                            style: crate::grass::BladeStyle::PLAIN,
18574                            shape: crate::grass::BladeShape::STRAIGHT,
18575                            clumping: crate::grass::Clumping::NONE,
18576                        })
18577                        .to_vec(),
18578                    )
18579                    .expect("a real field"),
18580                ),
18581            )
18582            .expect("the null backend uploads every map");
18583        renderer.set_render_scale(WIDEST_SCALE);
18584        assert_eq!(
18585            renderer.internal_extent(WIDEST_EXTENT),
18586            WIDEST_INTERNAL,
18587            "the scale has to take the target to the extent whose chain is the \
18588             longest one, or the bound below is checked against a frame that \
18589             could not reach it"
18590        );
18591        // **Both post effects forced on.** Neither is in the default camera
18592        // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
18593        // for one reason and the resolve out for another — and the widest frame
18594        // is the one that has every effect in it, the ground grid's argument
18595        // exactly.
18596        renderer.set_effect_request(EffectRequest {
18597            programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
18598            ..EffectRequest::default()
18599        });
18600        let imported = swapchain_image_at(device, WIDEST_EXTENT);
18601        let mut pool = crate::TransientPool::new();
18602
18603        // The debug draw layer on for both frames below, because it is a pass
18604        // the bound counts and no effect bit switches on — the ground grid's
18605        // argument again. A segment before each, since `begin_frame` clears the
18606        // buffer: the layer is immediate mode.
18607        let switch = debug_draw_switch();
18608        switch.set(true);
18609        // And the occlusion pair's second blur, for exactly that reason: it is a
18610        // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
18611        // frame at the shipping count comes one short of the bound and this test
18612        // would be asserting the bound against a frame that could not reach it.
18613        let blurs = ssao_blur_switch();
18614        blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
18615        // And the comparison seam, which is the occlusion chain's other
18616        // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
18617        // same reason the blur count is: the bound counts a frame that compares,
18618        // so a frame that does not could never reach it.
18619        let split = ssao_split_switch();
18620        split.set(0.5);
18621        renderer
18622            .debug_draw()
18623            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18624        let bare =
18625            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18626        assert_eq!(
18627            crate::bloom::mips_for(WIDEST_INTERNAL),
18628            crate::bloom::MAX_MIPS,
18629            "the widest frame has to be one whose chain is the longest one there \
18630             is, or the bound below is checked against a frame that could not \
18631             reach it"
18632        );
18633        assert!(
18634            bare < ForwardRenderer::MAX_PASSES as usize,
18635            "a frame with no shadowed light runs {bare} passes, which is already the \
18636             bound of {} — then the bound does not cover the slots this scene left free",
18637            ForwardRenderer::MAX_PASSES
18638        );
18639
18640        // One spot per slot, spaced so no two of them share an influence — the
18641        // list has to fill every slot or the bound below is checked against a
18642        // frame that could not reach it.
18643        #[expect(
18644            clippy::cast_precision_loss,
18645            reason = "a handful of slots, and the value is only a position"
18646        )]
18647        let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
18648            .map(|slot| shadowable_spot(1.0 + slot as f32))
18649            .collect();
18650        renderer.set_lights(&spots);
18651        renderer
18652            .debug_draw()
18653            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18654        let widest =
18655            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18656        assert_eq!(
18657            renderer.shadow_lights.slots().iter().flatten().count(),
18658            shadow::LIGHT_SLOTS,
18659            "the spots must actually hold every slot, or this is the bare frame again \
18660             under another name"
18661        );
18662        assert_eq!(
18663            widest,
18664            ForwardRenderer::MAX_PASSES as usize,
18665            "the widest frame is what the bound is for"
18666        );
18667        assert_eq!(
18668            widest - bare,
18669            DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
18670            "a filled slot costs a cull's passes and nothing else"
18671        );
18672
18673        renderer.destroy(device);
18674        pool.destroy(device);
18675        device.destroy_image_view(imported.view);
18676        device.destroy_image(imported.image);
18677        recorder.assert_valid();
18678    }
18679
18680    /// **A toggle reaches the recorded frame, and takes exactly its own passes
18681    /// with it.**
18682    ///
18683    /// The observable is the compiled pass list, because the thing that could
18684    /// otherwise be true is that the switch is stored and read by nothing: a
18685    /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
18686    /// draws a frame that looks right, reports the right effect set, and has not
18687    /// switched anything off.
18688    ///
18689    /// So each arm compares the whole list rather than its length. Two passes
18690    /// fewer is satisfied by removing the wrong two, and it is satisfied by a
18691    /// frame that lost its tonemap.
18692    ///
18693    /// The shadow arm is the one that cannot be written by name — a cascade's
18694    /// cull passes are labelled exactly as the camera's are — so it is written as
18695    /// its two halves instead: the count moves by a cull's worth per cascade and
18696    /// per filled light slot, and everything from the `shadow` pass onwards is
18697    /// unchanged. The `shadow` pass itself **stays**, because it is what writes
18698    /// the clear that reads as "fully lit".
18699    #[test]
18700    fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
18701        let _blurs = ssao_blur_switch();
18702        let (recorder, device, queue) = open();
18703        let device = device.as_ref();
18704        let mut renderer =
18705            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18706        place_cube(&mut renderer, Mat4::IDENTITY);
18707        // One shadowed light beside the cascades, so the shadow arm below covers
18708        // a light slot's cull as well as a cascade's.
18709        renderer.set_lights(&[shadowable_spot(-1.0)]);
18710        let imported = swapchain_image(device);
18711        let mut pool = crate::TransientPool::new();
18712
18713        // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
18714        // [`frame_switching_off`]'s terms exactly: the default camera stack
18715        // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
18716        // control built on the default alone would have nothing for their arms
18717        // to remove. `force` clears the other side, so an arm whose `off` is one
18718        // of them still resolves to off.
18719        //
18720        // [`frame_switching_off`]: fn@frame_switching_off
18721        let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
18722            renderer.set_effect_request(EffectRequest {
18723                programmatic: EffectOverride::none()
18724                    .force(OUTSIDE_THE_DEFAULT, Some(true))
18725                    .force(off, Some(false)),
18726                ..EffectRequest::default()
18727            });
18728            passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
18729        };
18730
18731        let all_on = without(&mut renderer, RenderEffects::empty());
18732        assert_eq!(
18733            renderer.effects(),
18734            RenderEffects::all(),
18735            "the control frame has to be the every-effect one"
18736        );
18737        assert_eq!(
18738            renderer.shadow_lights.slots().iter().flatten().count(),
18739            1,
18740            "the spot must actually hold a slot, or the shadow arm below is only about cascades"
18741        );
18742
18743        // **None of the three leaves anything behind it**, and for the same
18744        // reason: nothing reads what it would have written. The occlusion pair's
18745        // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
18746        // its `Load` into it — and the reflection pair's and the chain's readers
18747        // both tonemap whatever image they would have read anyway.
18748        //
18749        // The chain's labels are written out rather than built from
18750        // `crate::bloom`'s arithmetic, because a table generated from the code
18751        // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
18752        // downsamples, the one upsample between them, and the composite — and if
18753        // that extent moves this is the assertion that says so.
18754        for (off, gone) in [
18755            (
18756                RenderEffects::AMBIENT_OCCLUSION,
18757                ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
18758            ),
18759            (
18760                RenderEffects::CONTACT_SHADOWS,
18761                // One pass and no blur — `crate::contact_shadows`'s header says
18762                // why the occlusion pair's second pass has no counterpart here.
18763                ["contact-shadows"].as_slice(),
18764            ),
18765            (
18766                RenderEffects::REFLECTIONS,
18767                // **The pyramid goes with the march**, which is the whole of
18768                // what makes it an optimisation rather than a resource: it is
18769                // recorded on the frames that reflect and on no others. Two
18770                // levels at `TEST_EXTENT`, written out on the chain's terms
18771                // above.
18772                ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
18773            ),
18774            (
18775                RenderEffects::BLOOM,
18776                [
18777                    "bloom-down-1",
18778                    "bloom-down-2",
18779                    "bloom-up-1",
18780                    "bloom-composite",
18781                ]
18782                .as_slice(),
18783            ),
18784            (
18785                RenderEffects::AUTO_EXPOSURE,
18786                // All three go together and the tonemap stays: the pass reads
18787                // the measurement only when the block says to, and the block
18788                // says so on exactly the frames these three ran on.
18789                ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
18790            ),
18791        ] {
18792            let labels = without(&mut renderer, off);
18793            assert_eq!(
18794                renderer.effects(),
18795                RenderEffects::all().difference(off),
18796                "{off:?}: the frame must have resolved to the set the request asked for"
18797            );
18798            // **The control frame has to contain what this arm removes**, and
18799            // that is not a restatement of the comparison below: the comparison
18800            // builds `expected` by filtering `gone` out of `all_on`, so an arm
18801            // naming a pass the control never recorded filters nothing, matches,
18802            // and passes whether the effect draws anything or not. Removing the
18803            // resolve pass entirely left this loop green until this assertion
18804            // existed.
18805            for label in gone {
18806                assert!(
18807                    all_on.iter().any(|recorded| recorded == label),
18808                    "{off:?}: the every-effect frame does not record `{label}`, so removing it \
18809                     below proves nothing: {all_on:#?}"
18810                );
18811            }
18812            let expected: Vec<String> = all_on
18813                .iter()
18814                .filter(|label| !gone.contains(&label.as_str()))
18815                .cloned()
18816                .collect();
18817            assert_eq!(
18818                labels, expected,
18819                "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
18820                 every other pass"
18821            );
18822        }
18823
18824        // **The two antialiasing tiers share one resolve slot**, so neither is
18825        // a plain removal and neither belongs in the loop above: switching
18826        // CMAA2 off while FXAA stays on swaps three passes for one rather than
18827        // losing three, and the loop's "gain nothing in their place" comparison
18828        // is exactly what that violates. Three frames say it instead.
18829        let both = all_on.clone();
18830        let cheap = without(&mut renderer, RenderEffects::CMAA2);
18831        let neither = without(
18832            &mut renderer,
18833            RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
18834        );
18835        const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
18836        let resolve_of = |labels: &[String]| -> Vec<String> {
18837            labels
18838                .iter()
18839                .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
18840                .cloned()
18841                .collect()
18842        };
18843        let without_resolve = |labels: &[String]| -> Vec<String> {
18844            labels
18845                .iter()
18846                .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
18847                .cloned()
18848                .collect()
18849        };
18850        assert_eq!(
18851            resolve_of(&both),
18852            CMAA2_PASSES.map(str::to_string).to_vec(),
18853            "with both bits set the higher tier takes the slot and the cheap one \
18854             records nothing"
18855        );
18856        assert_eq!(
18857            resolve_of(&cheap),
18858            vec!["fxaa".to_string()],
18859            "with only the cheap bit set the slot is FXAA's"
18860        );
18861        assert!(
18862            resolve_of(&neither).is_empty(),
18863            "with neither bit set the frame has no resolve at all: {neither:#?}"
18864        );
18865        // And nothing else moved: the tiers swap in one slot rather than
18866        // rebuilding the frame around themselves.
18867        assert_eq!(without_resolve(&both), without_resolve(&cheap));
18868        assert_eq!(without_resolve(&both), without_resolve(&neither));
18869        // The slot is where the ordering argument puts it — directly after the
18870        // last pass that writes the display image, which at this extent is the
18871        // tonemap.
18872        for labels in [&both, &cheap] {
18873            let at = labels
18874                .iter()
18875                .position(|label| label == "tonemap")
18876                .expect("a frame has to reach the swapchain");
18877            assert_eq!(
18878                &labels[at + 1..=at + resolve_of(labels).len()],
18879                resolve_of(labels).as_slice(),
18880                "the resolve must follow the tonemap: {labels:#?}"
18881            );
18882        }
18883
18884        let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
18885        assert_eq!(
18886            renderer.effects(),
18887            RenderEffects::all().difference(RenderEffects::SHADOWS),
18888        );
18889        assert_eq!(
18890            all_on.len() - no_shadows.len(),
18891            DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
18892            "shadows off must drop a cull's passes per cascade and per filled slot"
18893        );
18894        let from_the_atlas = |labels: &[String]| {
18895            let at = labels
18896                .iter()
18897                .position(|label| label == "shadow")
18898                .expect("the atlas pass is recorded whether or not anything draws into it");
18899            labels[at..].to_vec()
18900        };
18901        assert_eq!(
18902            from_the_atlas(&no_shadows),
18903            from_the_atlas(&all_on),
18904            "only the culls go: the atlas pass and everything after it are unchanged"
18905        );
18906
18907        renderer.destroy(device);
18908        pool.destroy(device);
18909        device.destroy_image_view(imported.view);
18910        device.destroy_image(imported.image);
18911        recorder.assert_valid();
18912    }
18913
18914    /// **The contact march is a pass a frame records only when it was asked
18915    /// for, and the mask it writes is what the forward pass then reads.**
18916    ///
18917    /// Two observables, because either alone is satisfied by a mistake the other
18918    /// one catches:
18919    ///
18920    /// * **The compiled pass list.** `contact-shadows` appears between the
18921    ///   prepass whose depth it marches and the forward pass that binds it, and
18922    ///   appears at all only on the frame that asked. The toggle test above
18923    ///   already says a frame loses this pass and nothing else; what is added
18924    ///   here is *where* it sits, which is the half a set comparison cannot see
18925    ///   — a march recorded after the pass that reads it compiles and draws a
18926    ///   mask nothing ever looks at.
18927    /// * **The forward pass's own barriers.** On the frame that marched, one
18928    ///   more image is transitioned into [`ResourceState::ShaderRead`] before
18929    ///   the forward pass opens than on the frame that did not — which is the
18930    ///   mask leaving the colour attachment it was written as. That is what says
18931    ///   the pass's output reaches the shading, rather than being written into a
18932    ///   transient and dropped while the shader goes on reading the 1×1
18933    ///   placeholder. The placeholder is imported in `ShaderRead` already and
18934    ///   needs no transition, so it contributes nothing to this count and the
18935    ///   difference is exactly the mask.
18936    ///
18937    /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
18938    /// while its re-bless is pending — see that constant — so the `on` frame has
18939    /// to force it and the `off` frame is what a view saying nothing draws.
18940    #[test]
18941    fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
18942        let (recorder, device, queue) = open();
18943        let device = device.as_ref();
18944        let mut renderer =
18945            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18946        let imported = swapchain_image(device);
18947        let mut pool = crate::TransientPool::new();
18948
18949        let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
18950            renderer.set_effect_request(EffectRequest {
18951                programmatic: EffectOverride::none()
18952                    .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
18953                ..EffectRequest::default()
18954            });
18955            renderer
18956                .begin_frame(
18957                    device,
18958                    &Camera::default(),
18959                    &DirectionalLight::default(),
18960                    TEST_EXTENT,
18961                )
18962                .expect("write");
18963            let mut graph = crate::RenderGraph::new(queue);
18964            let target = graph.import_image("target", imported);
18965            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
18966            let compiled = graph.compile(&pool).expect("a legal frame");
18967            let labels: Vec<String> = compiled
18968                .passes()
18969                .iter()
18970                .map(|pass| pass.label().to_string())
18971                .collect();
18972            let readable = compiled
18973                .passes()
18974                .iter()
18975                .find(|pass| pass.label() == "forward")
18976                .expect("every frame draws its geometry")
18977                .barriers()
18978                .images
18979                .iter()
18980                .filter(|barrier| barrier.to == ResourceState::ShaderRead)
18981                .count();
18982            (labels, readable)
18983        };
18984
18985        let (marched, marched_reads) = frame(&mut renderer, true);
18986        assert!(
18987            renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
18988            "the forced frame has to have resolved with the bit set"
18989        );
18990        let (bare, bare_reads) = frame(&mut renderer, false);
18991        assert!(
18992            !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
18993            "and the control frame without it"
18994        );
18995
18996        assert!(
18997            !bare.iter().any(|label| label == "contact-shadows"),
18998            "a frame that did not ask must record no march at all: {bare:#?}"
18999        );
19000        let at = |labels: &[String], wanted: &str| {
19001            labels
19002                .iter()
19003                .position(|label| label == wanted)
19004                .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19005        };
19006        let march = at(&marched, "contact-shadows");
19007        assert!(
19008            march > at(&marched, "depth-prepass"),
19009            "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19010        );
19011        assert!(
19012            march < at(&marched, "forward"),
19013            "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19014        );
19015
19016        assert_eq!(
19017            marched_reads,
19018            bare_reads + 1,
19019            "the forward pass has to take one more image into `ShaderRead` on the frame that \
19020             marched — the mask. Equal counts mean the pass wrote a transient the shading \
19021             never reads."
19022        );
19023
19024        renderer.destroy(device);
19025        pool.destroy(device);
19026        device.destroy_image_view(imported.view);
19027        device.destroy_image(imported.image);
19028        recorder.assert_valid();
19029    }
19030
19031    /// **The ground grid is off until a caller asks, and then it is the last
19032    /// pass of the frame — after the tonemap.**
19033    ///
19034    /// Three claims and each is a separate way to get this wrong. Off by default
19035    /// is what keeps every sample and every golden image where they were. *After
19036    /// the tonemap* is the placement decision: added a line earlier it would
19037    /// draw into the HDR scene colour and be tonemapped like geometry, which
19038    /// compiles, draws a grid, and gives it a colour that moves with the
19039    /// exposure. And switching it off again has to remove the pass, not merely
19040    /// stop reporting it.
19041    ///
19042    /// The whole list is compared rather than its length, for the reason the
19043    /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19044    /// one.
19045    #[test]
19046    fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19047        let _blurs = ssao_blur_switch();
19048        let (recorder, device, queue) = open();
19049        let device = device.as_ref();
19050        let mut renderer =
19051            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19052        let imported = swapchain_image(device);
19053        let mut pool = crate::TransientPool::new();
19054
19055        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19056        assert!(
19057            renderer.ground_grid().is_none(),
19058            "a renderer nobody asked has no grid"
19059        );
19060        assert!(
19061            !off.contains(&"grid".to_string()),
19062            "the grid must not be in a frame nobody asked for it in: {off:#?}"
19063        );
19064
19065        renderer
19066            .set_ground_grid(device, Some(GridStyle::default()))
19067            .expect("the null backend builds every pipeline");
19068        assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19069        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19070
19071        let mut expected = off.clone();
19072        // The statistics copy is added after every render pass and stays last —
19073        // see `add_passes`. So the grid goes in front of it, which is directly
19074        // after the tonemap.
19075        let tonemap = expected
19076            .iter()
19077            .position(|label| label == "tonemap")
19078            .expect("a frame has to reach the swapchain");
19079        expected.insert(tonemap + 1, "grid".to_string());
19080        assert_eq!(
19081            on, expected,
19082            "the grid must be the one pass gained, and it must sit after the tonemap"
19083        );
19084
19085        renderer
19086            .set_ground_grid(device, None)
19087            .expect("switching off builds nothing");
19088        assert!(renderer.ground_grid().is_none());
19089        assert_eq!(
19090            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19091            off,
19092            "switching the grid off has to remove its pass, not just stop reporting it"
19093        );
19094
19095        renderer.destroy(device);
19096        pool.destroy(device);
19097        device.destroy_image_view(imported.view);
19098        device.destroy_image(imported.image);
19099        recorder.assert_valid();
19100    }
19101
19102    /// **A second occlusion blur is a pass the frame records, an image it takes
19103    /// out of the pool, and a triangle its counter reports** — or it is a switch
19104    /// that does nothing.
19105    ///
19106    /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19107    /// by driving the pipelines itself, so nothing there would notice that a
19108    /// real frame never records it. The three things below are what a frame has
19109    /// to do differently, and each of them fails silently on its own: a missing
19110    /// pass draws a slightly rougher picture, a missing image is a bind of the
19111    /// wrong one, and a counter short by one is a number nobody reads until it
19112    /// is quoted.
19113    ///
19114    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19115    /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19116    /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19117    /// whichever blur ran into it.
19118    ///
19119    /// **The one thing about that chain no other check can see.** The pass list
19120    /// is identical either way, the graph accepts a written-and-never-read
19121    /// transient without complaint, and every golden is at one blur where the
19122    /// two blur answers coincide — so a frame bound to the wrong image draws
19123    /// something nobody would question, which is exactly what the function's
19124    /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19125    /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19126    /// suites and lantern's golden all stayed green.
19127    ///
19128    /// **Since the halving it is a second silent failure and a louder one.**
19129    /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19130    /// returned working id is not merely a rougher channel — it is an image a
19131    /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19132    /// which its clamp turns into occlusion smeared over the top-left quarter of
19133    /// the frame rather than into an error.
19134    #[test]
19135    fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19136        let (_recorder, device, queue) = open();
19137        let device = device.as_ref();
19138        let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19139        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19140
19141        let one = {
19142            let mut graph = crate::RenderGraph::new(queue);
19143            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19144            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19145            let blurred =
19146                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19147            let upsampled = graph.create_image(
19148                "ssao-upsampled",
19149                crate::targets::ambient_occlusion(TEST_EXTENT),
19150            );
19151            let got = ssao.add_passes(
19152                &mut graph,
19153                0,
19154                TEST_EXTENT,
19155                depth,
19156                crate::ssao::OcclusionImages {
19157                    raw,
19158                    blurred,
19159                    again: None,
19160                    upsampled,
19161                },
19162            );
19163            (got == upsampled, got == blurred || got == raw)
19164        };
19165        assert!(one.0, "one blur finishes in the reconstruction's image");
19166        assert!(
19167            !one.1,
19168            "and never in one of the half-extent images the chain worked in"
19169        );
19170
19171        let two = {
19172            let mut graph = crate::RenderGraph::new(queue);
19173            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19174            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19175            let blurred =
19176                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19177            let again = graph.create_image(
19178                "ssao-blurred-2",
19179                crate::targets::ambient_occlusion(gathered),
19180            );
19181            let upsampled = graph.create_image(
19182                "ssao-upsampled",
19183                crate::targets::ambient_occlusion(TEST_EXTENT),
19184            );
19185            let got = ssao.add_passes(
19186                &mut graph,
19187                0,
19188                TEST_EXTENT,
19189                depth,
19190                crate::ssao::OcclusionImages {
19191                    raw,
19192                    blurred,
19193                    again: Some(again),
19194                    upsampled,
19195                },
19196            );
19197            (got == upsampled, got == again || got == blurred)
19198        };
19199        assert!(
19200            two.0,
19201            "two blurs finish in the reconstruction's image as well, which is the id the forward \
19202             pass binds"
19203        );
19204        assert!(
19205            !two.1,
19206            "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19207             would question"
19208        );
19209    }
19210
19211    /// **The gather runs at half the frame and the reconstruction runs at all
19212    /// of it** — or the halving is a description nobody rendered into.
19213    ///
19214    /// The pass list cannot see this: three passes with the right labels in the
19215    /// right order is exactly what a chain that halved nothing would record. The
19216    /// **render area** is where the halving is observable, and the graph derives
19217    /// it from each pass's colour attachment — so this is the check that the
19218    /// transients [`ForwardRenderer::add_passes`] created are the ones
19219    /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19220    /// the frame-sized one.
19221    ///
19222    /// Neither mistake is an error anywhere else. Working images at the frame's
19223    /// extent are four times the march and a reconstruction reading the corner
19224    /// of its input; a frame-sized image handed to the march and a half-sized
19225    /// one to the forward pass is occlusion smeared over a quarter of the
19226    /// picture by `mesh.slang`'s clamp. Both are pictures.
19227    ///
19228    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19229    /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19230    /// occlusion chain's passes up by name, and a second blur arriving from
19231    /// another thread's switch is a pass this frame did not ask for.
19232    #[test]
19233    fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19234        let _switch = ssao_blur_switch();
19235
19236        let (recorder, device, queue) = open();
19237        let device = device.as_ref();
19238        let mut renderer =
19239            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19240        let imported = swapchain_image(device);
19241        let mut pool = crate::TransientPool::new();
19242        renderer
19243            .begin_frame(
19244                device,
19245                &Camera::default(),
19246                &DirectionalLight::default(),
19247                TEST_EXTENT,
19248            )
19249            .expect("write");
19250        let mut graph = crate::RenderGraph::new(queue);
19251        let target = graph.import_image("target", imported);
19252        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19253        let compiled = graph.compile(&pool).expect("a legal frame");
19254        let area_of = |label: &str| {
19255            let pass = compiled
19256                .passes()
19257                .iter()
19258                .find(|pass| pass.label() == label)
19259                .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19260            let area = pass.render_area();
19261            (area.width, area.height)
19262        };
19263
19264        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19265        assert_ne!(
19266            gathered, TEST_EXTENT,
19267            "the fixture extent has to halve to something else, or every assertion below holds \
19268             of a chain that halved nothing"
19269        );
19270        assert_eq!(
19271            area_of("ssao"),
19272            gathered,
19273            "the march has to run over the gather extent"
19274        );
19275        assert_eq!(
19276            area_of("ssao-blur"),
19277            gathered,
19278            "and so does the blur over what the march wrote"
19279        );
19280        assert_eq!(
19281            area_of("ssao-upsample"),
19282            TEST_EXTENT,
19283            "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19284             runs at the frame's own extent"
19285        );
19286
19287        drop(compiled);
19288        renderer.destroy(device);
19289        pool.destroy(device);
19290        device.destroy_image_view(imported.view);
19291        device.destroy_image(imported.image);
19292        recorder.assert_valid();
19293    }
19294
19295    /// **The comparison seam records a second march, scissored to the columns
19296    /// the first one was kept off.**
19297    ///
19298    /// `crate::split`'s geometry, read off the encoder rather than off the code
19299    /// that drove it: two passes, and two `SetScissor` rectangles that tile the
19300    /// gather extent between them.
19301    ///
19302    /// **What this cannot see is which block each march bound.** The reference
19303    /// backend records a bind group as a handle and a layout, not as the
19304    /// resources behind it, so pointing both marches at one buffer leaves this
19305    /// test green — measured, by doing exactly that. The group inequality below
19306    /// is kept because it is free and would catch the two marches sharing a
19307    /// cache, which is a different fault; what covers the blocks is
19308    /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
19309    /// is not covered at all is the wiring between them. `docs/backlog.md`
19310    /// carries that gap.
19311    ///
19312    /// **The control is the same frame without a seam**, and it is what makes
19313    /// the assertions mean anything: a chain that scissored unconditionally
19314    /// would satisfy every claim below and change every golden in the workspace,
19315    /// so the frame nobody asked to compare has to record one march and set no
19316    /// rectangle at all.
19317    ///
19318    /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
19319    /// is process-wide state and a frame that picked one up from another
19320    /// thread's test is a frame with a pass this one did not ask for.
19321    #[test]
19322    fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
19323        use crcbl_hal::null::Command;
19324
19325        let _blurs = ssao_blur_switch();
19326        let split = ssao_split_switch();
19327        // Third, after the two above: the only other test that takes this one
19328        // takes it alone, so this is the whole order and there is no cycle in
19329        // it. Moved below, because two blocks holding the same scalars are
19330        // equal whatever the seam did.
19331        let slices = ssao_slice_switch();
19332        // The count the seam's far side reads, and one that is not it. Read off
19333        // the variable rather than written down: which end of the range ships
19334        // has changed once already, and a test naming the wrong end would be
19335        // comparing the shipped configuration against itself.
19336        let ships = match crate::ssao::r_ssao_slices.default() {
19337            crcbl_console::Value::Int(count) => *count,
19338            other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
19339        };
19340        let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
19341            i64::from(ssao::SLICE_COUNT_DEFAULT)
19342        } else {
19343            i64::from(ssao::SLICE_COUNT_MAX)
19344        };
19345        assert_ne!(
19346            ships, moved,
19347            "the two slice counts this compares are one count, so the blocks below would differ \
19348             by nothing whatever the seam did"
19349        );
19350        slices.set(ships);
19351
19352        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19353        // One entry per march the frame recorded: the last rectangle that pass
19354        // left the scissor at, and the group it bound.
19355        //
19356        // **The last and not the only one.** The graph opens every pass with a
19357        // scissor over the whole render area, so a march that sets none of its
19358        // own still records one — which is why "did it scissor at all" is not
19359        // the question and "what did it end up cropped to" is.
19360        let marches = |recorder: &Recorder, from: usize| {
19361            let mut inside = false;
19362            let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
19363            let mut rect = None;
19364            let mut group = None;
19365            for command in &recorder.commands()[from..] {
19366                if let Some((_, label)) = command.opens_pass() {
19367                    inside = matches!(label, Some("ssao" | "ssao-shipped"));
19368                    (rect, group) = (None, None);
19369                    continue;
19370                }
19371                if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19372                    if let (true, Some(rect), Some(group)) = (inside, rect, group) {
19373                        found.push((rect, group));
19374                    }
19375                    inside = false;
19376                    continue;
19377                }
19378                if !inside {
19379                    continue;
19380                }
19381                match command {
19382                    Command::SetScissor(at) => rect = Some(*at),
19383                    Command::BindGroup { group: bound, .. } => group = Some(*bound),
19384                    _ => {}
19385                }
19386            }
19387            found
19388        };
19389
19390        let (recorder, device, queue) = open();
19391        let device = device.as_ref();
19392        let mut renderer =
19393            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19394
19395        split.set(0.0);
19396        let alone = frame_seen_from(
19397            device,
19398            &mut renderer,
19399            queue,
19400            &Camera::default(),
19401            &DirectionalLight::default(),
19402        );
19403        let plain = marches(&recorder, 0);
19404        let after = recorder.commands().len();
19405        let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19406        let (uncompared_console, uncompared_shipped) = (
19407            recorder.buffer_bytes(console).expect("the console's block"),
19408            recorder.buffer_bytes(shipped).expect("the seam's block"),
19409        );
19410        alone.release(device);
19411
19412        split.set(0.5);
19413        slices.set(moved);
19414        let frame = frame_seen_from(
19415            device,
19416            &mut renderer,
19417            queue,
19418            &Camera::default(),
19419            &DirectionalLight::default(),
19420        );
19421        let compared = marches(&recorder, after);
19422        let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19423        let (compared_console, compared_shipped) = (
19424            recorder.buffer_bytes(console).expect("the console's block"),
19425            recorder.buffer_bytes(shipped).expect("the seam's block"),
19426        );
19427        frame.finish(device, renderer);
19428
19429        assert_eq!(
19430            plain.len(),
19431            1,
19432            "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
19433            plain.len()
19434        );
19435        assert_eq!(
19436            (
19437                plain[0].0.x,
19438                plain[0].0.y,
19439                plain[0].0.width,
19440                plain[0].0.height
19441            ),
19442            (0, 0, gathered.0, gathered.1),
19443            "a frame comparing nothing left its march cropped to something other than the whole \
19444             gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
19445             and every golden in this workspace was blessed on a frame that does not"
19446        );
19447
19448        assert_eq!(
19449            compared.len(),
19450            2,
19451            "a frame comparing two configurations recorded {} march(es)",
19452            compared.len()
19453        );
19454        let (left, right) = (compared[0].0, compared[1].0);
19455        assert_eq!(
19456            (left.x, left.y, right.y),
19457            (0, 0, 0),
19458            "both halves start at the top and the left one at the edge"
19459        );
19460        assert_eq!(
19461            i64::from(right.x),
19462            i64::from(left.width),
19463            "the second march starts where the first one ended, or a column is drawn twice"
19464        );
19465        assert_eq!(
19466            (left.width + right.width, left.height, right.height),
19467            (gathered.0, gathered.1, gathered.1),
19468            "the two rectangles have to cover the gather extent {gathered:?} exactly"
19469        );
19470        assert!(
19471            left.width < gathered.0 && right.width < gathered.0,
19472            "one half covers the whole extent, so the other draws over it and the seam is a \
19473             rectangle that crops nothing"
19474        );
19475        assert_ne!(
19476            compared[0].1, compared[1].1,
19477            "the two marches bound one group, so they cannot be reading two blocks"
19478        );
19479
19480        // How far the reference backend can follow the far side. It will say
19481        // what bytes a buffer holds and it will not say which buffer a group
19482        // names, so the two together are "there are two blocks, and they differ
19483        // by the knob that was moved" — not "the right march read the right
19484        // one". Pointing both marches at one buffer still passes; see this
19485        // module's entry in `docs/backlog.md`.
19486        assert_eq!(
19487            uncompared_console, uncompared_shipped,
19488            "the console sat at its defaults and the two blocks still differ, so the seam's far \
19489             side is not this frame with the shipped scalars — it is another frame"
19490        );
19491        assert_ne!(
19492            compared_console, compared_shipped,
19493            "one slice count was moved off the shipped one and both blocks still hold the same \
19494             bytes, so a comparison shows the same picture twice"
19495        );
19496
19497        recorder.assert_valid();
19498    }
19499
19500    /// Every gather pipeline the frame bound, in the order the marches ran.
19501    ///
19502    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
19503    /// `marches` closure asking the other question of the same stream: that one
19504    /// reads the scissor and the group, and this one reads the pipeline. Only
19505    /// the `ssao` and `ssao-shipped` passes are looked at, because every other
19506    /// pass in the chain binds a pipeline too and a filter over the whole stream
19507    /// would be counting blurs.
19508    ///
19509    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
19510    fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
19511        use crcbl_hal::null::Command;
19512
19513        let mut inside = false;
19514        let mut found = Vec::new();
19515        for command in &recorder.commands()[from..] {
19516            if let Some((_, label)) = command.opens_pass() {
19517                inside = matches!(label, Some("ssao" | "ssao-shipped"));
19518                continue;
19519            }
19520            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19521                inside = false;
19522                continue;
19523            }
19524            if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
19525                found.push(*pipeline);
19526            }
19527        }
19528        found
19529    }
19530
19531    /// **`r_ssao_technique` decides which shader the gather runs**, read off the
19532    /// pipeline the `ssao` pass bound.
19533    ///
19534    /// The observable `docs/backlog.md` says the uniform block cannot have. The
19535    /// reference backend records a bind group as a handle and a layout rather
19536    /// than as the resources behind it, so nothing can ask which *block* a march
19537    /// read — but a pipeline is recorded as itself, so which *technique* a march
19538    /// ran is a question this backend answers. `Ssao::gathers` is what names the
19539    /// two, so this is an equality against the pipeline built from each shader
19540    /// rather than an inequality that any two handles would satisfy.
19541    ///
19542    /// **The default arm is the load-bearing half.** A selector that read the
19543    /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
19544    /// change the frame when the console moved; what would go with it is every
19545    /// golden in this workspace, which is blessed on the technique that ships.
19546    ///
19547    /// Holds [`ssao_blur_switch`] for its own reason and
19548    /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
19549    /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
19550    #[test]
19551    fn the_occlusion_technique_picks_the_gathers_pipeline() {
19552        let _blurs = ssao_blur_switch();
19553        let _seam = ssao_split_switch();
19554        let technique = ssao_technique_switch();
19555        // The name to move to, taken out of the variable's own set — see
19556        // `other_technique_name`.
19557        let other = other_technique_name();
19558
19559        let (recorder, device, queue) = open();
19560        let device = device.as_ref();
19561        let mut renderer =
19562            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19563        let (ships, cheap) = renderer.primary.ssao.gathers();
19564        assert_ne!(
19565            ships, cheap,
19566            "the renderer built one gather pipeline for both techniques, so nothing below can \
19567             tell them apart"
19568        );
19569
19570        let shipped = frame_seen_from(
19571            device,
19572            &mut renderer,
19573            queue,
19574            &Camera::default(),
19575            &DirectionalLight::default(),
19576        );
19577        let by_default = gathers_bound(&recorder, 0);
19578        let after = recorder.commands().len();
19579        shipped.release(device);
19580
19581        technique.set(other);
19582        let moved_frame = frame_seen_from(
19583            device,
19584            &mut renderer,
19585            queue,
19586            &Camera::default(),
19587            &DirectionalLight::default(),
19588        );
19589        let moved = gathers_bound(&recorder, after);
19590        moved_frame.finish(device, renderer);
19591
19592        assert_eq!(
19593            by_default,
19594            vec![ships],
19595            "a frame nobody has touched the console on gathered through something other than \
19596             `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
19597        );
19598        assert_eq!(
19599            moved,
19600            vec![cheap],
19601            "`r_ssao_technique {other}` left the frame gathering through the pipeline \
19602             it gathered through before, so the selector reaches nothing"
19603        );
19604        recorder.assert_valid();
19605    }
19606
19607    /// **The comparison seam's two marches run two techniques**, which is what
19608    /// the seam was built for.
19609    ///
19610    /// Alcove's second milestone is SSAO and GTAO in
19611    /// one frame, and this is that claim as a pair of pipeline handles: with the
19612    /// technique moved the near side runs the cheap tier and the far side the
19613    /// one that ships, and with it at its default both marches run the same
19614    /// shader and the seam separates nothing.
19615    ///
19616    /// **The control is the frame at the default**, and it is what makes the
19617    /// first half mean anything: a far side that always ran `ssao.slang` would
19618    /// satisfy the inequality below whatever `shipped_technique` did, and a
19619    /// chain that had simply forgotten to pass the far side a pipeline of its
19620    /// own would too.
19621    #[test]
19622    fn the_comparison_seam_marches_through_two_techniques() {
19623        let _blurs = ssao_blur_switch();
19624        let seam = ssao_split_switch();
19625        let technique = ssao_technique_switch();
19626        let other = other_technique_name();
19627
19628        let (recorder, device, queue) = open();
19629        let device = device.as_ref();
19630        let mut renderer =
19631            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19632        let (ships, cheap) = renderer.primary.ssao.gathers();
19633
19634        seam.set(0.5);
19635        let compared = frame_seen_from(
19636            device,
19637            &mut renderer,
19638            queue,
19639            &Camera::default(),
19640            &DirectionalLight::default(),
19641        );
19642        let one_technique = gathers_bound(&recorder, 0);
19643        let after = recorder.commands().len();
19644        compared.release(device);
19645
19646        technique.set(other);
19647        let frame = frame_seen_from(
19648            device,
19649            &mut renderer,
19650            queue,
19651            &Camera::default(),
19652            &DirectionalLight::default(),
19653        );
19654        let two_techniques = gathers_bound(&recorder, after);
19655        frame.finish(device, renderer);
19656
19657        assert_eq!(
19658            one_technique,
19659            vec![ships, ships],
19660            "a seam with the technique at its default has to march the shipped gather twice — \
19661             both sides read `shipped`'s configuration, and the picture is one technique either \
19662             side of a line"
19663        );
19664        assert_eq!(
19665            two_techniques,
19666            vec![cheap, ships],
19667            "with `r_ssao_technique {other}` the near side has to run the cheap tier \
19668             and the far side what ships; the far side follows the variable's *default*, exactly \
19669             as the four scalars do"
19670        );
19671        recorder.assert_valid();
19672    }
19673
19674    /// **The frame block carries the console's shadow filter on the near side
19675    /// of the seam, the shipped one on the far side, and the column
19676    /// [`crate::split::halves`] counted.**
19677    ///
19678    /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
19679    /// other seam, and it has to be a claim about *bytes* rather than about
19680    /// pass handles: the occlusion chain compares two pipelines and this
19681    /// compares two arms of one, so there is nothing in the pass list to look
19682    /// at. What a person sees is decided entirely by the row this asserts.
19683    ///
19684    /// **The frame at the default is the control**, and it is what makes the
19685    /// rest mean anything: a block that always wrote the shipped filter into
19686    /// both lanes would satisfy the third case's far side whatever
19687    /// `shipped_filter` did, and one that copied the near lane into the far one
19688    /// would satisfy the first two.
19689    ///
19690    /// The column is compared against `halves`' own answer rather than against
19691    /// a number written here, which is the seam module's whole point: a test
19692    /// that multiplied the fraction by the width itself would be a second
19693    /// opinion about the rounding, and the floor is exactly what that module's
19694    /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
19695    ///
19696    /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
19697    #[test]
19698    fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
19699        let switch = shadow_filter_switch();
19700
19701        let (recorder, device, queue) = open();
19702        let device = device.as_ref();
19703        let mut renderer =
19704            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19705
19706        // The seam is counted over the extent the scene is *drawn* at, which is
19707        // what `SV_Position.x` is denominated in — not the caller's window.
19708        let internal = renderer.internal_extent(TEST_EXTENT);
19709        let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
19710        assert!(
19711            left.width > 0,
19712            "a seam with no columns on one side would make every assertion below hold of a \
19713             frame that compares nothing"
19714        );
19715
19716        let ships = shadow::shipped_filter();
19717        let other = shadow::Filter::Box;
19718        assert_ne!(
19719            other.mode(),
19720            ships.mode(),
19721            "the filter this test moves the console to is the one that ships, so the seam it \
19722             asks for compares one kernel against itself"
19723        );
19724
19725        let draw = |renderer: &mut ForwardRenderer| {
19726            renderer
19727                .begin_frame(
19728                    device,
19729                    &Camera::default(),
19730                    &DirectionalLight::default(),
19731                    TEST_EXTENT,
19732                )
19733                .expect("write");
19734            let bytes = recorder
19735                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
19736                .expect("this frame's uniform block is live");
19737            let at = mesh::FRAME_UNIFORMS_SIZE - 16;
19738            core::array::from_fn(|lane| {
19739                u32::from_le_bytes(
19740                    bytes[at + lane * 4..at + lane * 4 + 4]
19741                        .try_into()
19742                        .expect("four bytes"),
19743                )
19744            })
19745        };
19746
19747        let shipped: [u32; 4] = draw(&mut renderer);
19748        assert_eq!(
19749            shipped,
19750            [ships.mode(), ships.mode(), 0, 0],
19751            "a frame nobody has touched the console on must carry the shipped filter in both \
19752             lanes and no column, which is the row every golden in this workspace was blessed \
19753             under"
19754        );
19755
19756        switch.filter(other);
19757        let unsplit: [u32; 4] = draw(&mut renderer);
19758        assert_eq!(
19759            unsplit,
19760            [other.mode(), other.mode(), 0, 0],
19761            "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
19762            other.label()
19763        );
19764
19765        switch.seam(0.5);
19766        let compared: [u32; 4] = draw(&mut renderer);
19767        assert_eq!(
19768            compared,
19769            [other.mode(), ships.mode(), left.width, 0],
19770            "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
19771             shipped one right of it; the far side follows the variable's *default*, exactly \
19772             as the occlusion chain's does"
19773        );
19774
19775        renderer.destroy(device);
19776        recorder.assert_valid();
19777    }
19778
19779    #[test]
19780    fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
19781        let switch = ssao_blur_switch();
19782
19783        let (recorder, device, queue) = open();
19784        let device = device.as_ref();
19785        let mut renderer =
19786            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19787        let imported = swapchain_image(device);
19788        let pool = crate::TransientPool::new();
19789
19790        let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19791        let counted_once = renderer.counters().instances;
19792        assert!(
19793            once.contains(&"ssao-blur".to_string()),
19794            "the shipping frame has to blur once, or the arm below is about a frame with no \
19795             occlusion in it at all: {once:#?}"
19796        );
19797        assert!(
19798            !once.contains(&"ssao-blur-2".to_string()),
19799            "a frame nobody moved the switch for must record one blur: {once:#?}"
19800        );
19801
19802        switch.set(2);
19803        let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19804        let counted_twice = renderer.counters().instances;
19805        assert!(
19806            twice.contains(&"ssao-blur-2".to_string()),
19807            "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
19808        );
19809        assert_eq!(
19810            twice.len(),
19811            once.len() + 1,
19812            "the second blur is the only pass that may join the frame: {twice:#?}"
19813        );
19814        assert_eq!(
19815            counted_twice,
19816            counted_once + FULLSCREEN_DRAWS,
19817            "the frame recorded a full-screen triangle its counter did not report"
19818        );
19819
19820        // The pass has to write somewhere the forward pass then reads, and the
19821        // graph is what would refuse a frame that bound an image nothing wrote.
19822        // `passes_in_a_frame` compiles rather than executes, so this is the
19823        // check that the third transient was requested at all.
19824        assert!(
19825            twice.iter().any(|pass| pass == "forward"),
19826            "the frame still has to reach its forward pass: {twice:#?}"
19827        );
19828        recorder.assert_valid();
19829    }
19830
19831    /// Every host-written buffer at the end of a whole ring of frames, keyed by
19832    /// the handle written and holding what that handle last held.
19833    ///
19834    /// A whole ring rather than one frame, because the blocks a frame writes are
19835    /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
19836    /// so one frame touches one slot of each and two single-frame batches would
19837    /// be comparing different buffers. A ring writes every slot, so two batches'
19838    /// keys line up and a difference between them is a difference in *bytes*.
19839    ///
19840    /// Only the events this call appends are read, so a caller can take one
19841    /// batch after another off the same recorder.
19842    fn host_buffers_over_a_ring(
19843        recorder: &Recorder,
19844        device: &dyn Device,
19845        renderer: &mut ForwardRenderer,
19846        queue: QueueHandle,
19847    ) -> std::collections::BTreeMap<u64, Vec<u8>> {
19848        let from = recorder.events().len();
19849        for _ in 0..FRAMES_IN_FLIGHT {
19850            frame(device, renderer, queue).release(device);
19851        }
19852        recorder.events()[from..]
19853            .iter()
19854            .filter_map(|event| match event {
19855                Event::BufferWritten { buffer, .. } => Some(*buffer),
19856                _ => None,
19857            })
19858            .map(|buffer| {
19859                let bytes = recorder
19860                    .buffer_bytes(buffer)
19861                    .expect("the stream only names buffers this recorder created");
19862                (buffer.to_bits(), bytes)
19863            })
19864            .collect()
19865    }
19866
19867    /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
19868    /// the ring, and moves nothing else in the frame.**
19869    ///
19870    /// The device test drives the two occlusion pipelines directly and
19871    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
19872    /// count, so until this the slice count was a variable with a `get_i64` and
19873    /// no evidence that a rendered frame ever carried it: `slice_count` could
19874    /// have returned its default unconditionally and every check in this
19875    /// workspace would still be green.
19876    ///
19877    /// So the observable is the bytes, taken off the null recorder's write log
19878    /// after a whole ring of frames at each setting and compared **by handle**.
19879    /// Two claims come out of that comparison and both are load-bearing:
19880    ///
19881    /// * **Some block moved** — every ring slot, in fact, which is what says the
19882    ///   count reaches the frame at all rather than only the slot the last frame
19883    ///   happened to land in.
19884    /// * **Every block that moved, moved only there.** A frame is a few dozen
19885    ///   host writes and the slice count has business with exactly one word of
19886    ///   one of them; a setting that perturbed a matrix, an instance or a shadow
19887    ///   view would be drawing a different frame for a reason nobody asked for,
19888    ///   and the "at least one differs" half alone would pass on it happily.
19889    ///
19890    /// **Holds every switch whose row is in a block it compares**, in the lock
19891    /// order: the two batches are compared byte for byte over every host
19892    /// buffer the frame writes, so any console row another test moves between
19893    /// them — the blur count, the seam, the technique, the shadow filter, or
19894    /// `crate::ssao`'s own mover of the params block — reads here as "some
19895    /// other write moving". [`ssao_technique_switch`] is the one that
19896    /// serialises against that mover.
19897    #[test]
19898    fn four_slices_reach_the_frame_the_shader_reads() {
19899        let _blurs = ssao_blur_switch();
19900        let _seam = ssao_split_switch();
19901        let switch = ssao_slice_switch();
19902        let _technique = ssao_technique_switch();
19903        let _filter = shadow_filter_switch();
19904
19905        let (recorder, device, queue) = open();
19906        let device = device.as_ref();
19907        let mut renderer =
19908            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19909
19910        // A ring rendered before either batch is taken, because the two below
19911        // are compared by handle and the renderer's opening frame writes blocks
19912        // no later frame writes again: it fills a cold shadow atlas, so the
19913        // shadow views' uniform blocks and the draw-generation blocks of the
19914        // cascades that were drawn are written once and never again while the
19915        // cache holds. Those would be in the first batch and missing from the
19916        // second, and a key that is only in one of them is a difference this
19917        // test cannot say anything about.
19918        for _ in 0..FRAMES_IN_FLIGHT {
19919            frame(device, &mut renderer, queue).release(device);
19920        }
19921        let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
19922        switch.set(i64::from(ssao::SLICE_COUNT_MAX));
19923        let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
19924        assert_eq!(
19925            shipping.keys().collect::<Vec<_>>(),
19926            asked.keys().collect::<Vec<_>>(),
19927            "the two batches must write the same buffers, or they are not comparable",
19928        );
19929
19930        // Which bytes moving the count alone is allowed to move, asked of
19931        // `SsaoParams::to_bytes` rather than written here as an offset: the
19932        // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
19933        // of the count would leave a number spelled here pointing at the radius.
19934        let block_of = |slices| {
19935            ssao::SsaoParams {
19936                inv_proj: [0.0; 16],
19937                proj: [0.0; 16],
19938                inv_view: [0.0; 16],
19939                radius: 0.0,
19940                slices,
19941                intensity: ssao::INTENSITY_DEFAULT,
19942                bent_normals: crate::ssao::bent_normals(),
19943            }
19944            .to_bytes()
19945        };
19946        let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
19947        let at_max = block_of(ssao::SLICE_COUNT_MAX);
19948        let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
19949            .filter(|at| at_shipping[*at] != at_max[*at])
19950            .collect();
19951
19952        let mut moved = 0;
19953        for (handle, before) in &shipping {
19954            let after = &asked[handle];
19955            if before == after {
19956                continue;
19957            }
19958            moved += 1;
19959            let mut only_the_count = before.clone();
19960            for at in &count_word {
19961                assert_eq!(
19962                    before[*at], at_shipping[*at],
19963                    "buffer {handle} differs between the batches but did not go in holding the \
19964                     shipping slice count, so this is some other write moving",
19965                );
19966                only_the_count[*at] = at_max[*at];
19967            }
19968            assert_eq!(
19969                after, &only_the_count,
19970                "buffer {handle} moved somewhere other than the slice count's word: the setting \
19971                 is perturbing a block it has no business in",
19972            );
19973        }
19974        assert_eq!(
19975            moved, FRAMES_IN_FLIGHT,
19976            "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
19977             none of them is a console variable no rendered frame reads",
19978        );
19979
19980        renderer.destroy(device);
19981        recorder.assert_valid();
19982    }
19983
19984    /// **The debug draw layer costs a frame nothing until something is appended
19985    /// *and* the console switch is on, and then it is the pass immediately
19986    /// before the tonemap.**
19987    ///
19988    /// Four claims, and each is a separate way to get this wrong.
19989    ///
19990    /// * **Off by default** is what keeps every golden image in the workspace
19991    ///   where it was blessed.
19992    /// * **A segment appended while the switch is off records nothing**, so a
19993    ///   system may append unconditionally.
19994    /// * **The switch on with an empty buffer records nothing either** — this is
19995    ///   the "costs nothing when empty" claim as a check rather than a sentence:
19996    ///   the compiled pass list is compared whole against the frame drawn before
19997    ///   the layer was switched on, so a pass that clears, blits or barriers
19998    ///   anything would show up here.
19999    /// * **Before the tonemap**, which is
20000    ///   `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20001    ///   the ground grid above. Recorded a line later it would draw into the
20002    ///   display-space target and be free of the exposure, which compiles and
20003    ///   draws lines and is the wrong picture.
20004    ///
20005    /// And the fifth, which is what "immediate mode" means: the frame *after*
20006    /// the one that appended records nothing again, because
20007    /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20008    ///
20009    /// The whole list is compared rather than its length, for the ground grid
20010    /// test's reason: one more pass is satisfied by gaining the wrong one.
20011    ///
20012    /// **This test owns `r_debug_draw` for its duration**, through
20013    /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20014    /// between tests, so the two checks here that move it have to take turns.
20015    /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20016    /// none of it.
20017    #[test]
20018    fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20019        let switch = debug_draw_switch();
20020        let _blurs = ssao_blur_switch();
20021
20022        let (recorder, device, queue) = open();
20023        let device = device.as_ref();
20024        let mut renderer =
20025            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20026        let imported = swapchain_image(device);
20027        let mut pool = crate::TransientPool::new();
20028
20029        assert!(
20030            !crate::DebugDraw::enabled(),
20031            "the layer must be off before anything switches it on, or every claim below is \
20032             about a different default"
20033        );
20034        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20035        assert!(
20036            !off.contains(&"debug-draw".to_string()),
20037            "the layer must not be in a frame nobody switched it on for: {off:#?}"
20038        );
20039
20040        renderer
20041            .debug_draw()
20042            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20043        assert_eq!(
20044            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20045            off,
20046            "a segment appended while the switch is off must record no pass"
20047        );
20048
20049        switch.set(true);
20050        assert_eq!(
20051            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20052            off,
20053            "the switch on with an empty buffer must record the frame the layer's absence would"
20054        );
20055
20056        renderer
20057            .debug_draw()
20058            .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20059        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20060        let mut expected = off.clone();
20061        let tonemap = expected
20062            .iter()
20063            .position(|label| label == "tonemap")
20064            .expect("a frame has to reach the swapchain");
20065        expected.insert(tonemap, "debug-draw".to_string());
20066        assert_eq!(
20067            on, expected,
20068            "the layer must be the one pass gained, and it must sit before the tonemap"
20069        );
20070
20071        assert_eq!(
20072            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20073            off,
20074            "the buffer is immediate mode: the frame after the one that appended must record \
20075             nothing"
20076        );
20077
20078        switch.set(false);
20079        renderer.destroy(device);
20080        pool.destroy(device);
20081        device.destroy_image_view(imported.view);
20082        device.destroy_image(imported.image);
20083        recorder.assert_valid();
20084    }
20085
20086    /// **The debug draw layer's own call is counted in the frame's draws.**
20087    ///
20088    /// [`ForwardRenderer::counters`]' draw count is compared against the
20089    /// commands the null backend actually recorded, which is the same instrument
20090    /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20091    /// uses — so a layer whose line list was recorded and not counted fails here
20092    /// rather than quietly making every panel's draw row one short.
20093    ///
20094    /// Both directions are asserted: the frame that drew a segment records one
20095    /// more draw than the frame before it, *and* the counter moved by the same
20096    /// one. A count wired to a constant satisfies neither.
20097    ///
20098    /// It owns `r_debug_draw` for its duration, on
20099    /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20100    /// terms.
20101    #[test]
20102    fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20103        let switch = debug_draw_switch();
20104        let _blurs = ssao_blur_switch();
20105
20106        let (recorder, device, queue) = open();
20107        let device = device.as_ref();
20108        let mut renderer =
20109            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20110
20111        // A different sun in each of the two frames, so both of them redraw the
20112        // shadow atlas: the claim below is that the layer's own call is the one
20113        // draw the second frame gained, and a second frame that cached its
20114        // atlas would have lost the atlas's draws at the same time. See
20115        // [`moving_sun`].
20116        let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20117        let without = renderer.counters().draws;
20118        assert_eq!(
20119            without,
20120            recorded_draws(&recorder) as u64,
20121            "the counter and the frame's recorded draws disagree before the layer draws at all"
20122        );
20123        quiet.release(device);
20124
20125        switch.set(true);
20126        renderer
20127            .debug_draw()
20128            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20129        let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20130        let with = renderer.counters().draws;
20131        assert_eq!(
20132            with,
20133            without + 1,
20134            "the layer records one draw, so the count has to move by one"
20135        );
20136        assert_eq!(
20137            recorded_draws(&recorder) as u64,
20138            without + with,
20139            "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20140             counted somewhere it was not recorded or recorded somewhere it was not counted"
20141        );
20142
20143        switch.set(false);
20144        drawn.finish(device, renderer);
20145        recorder.assert_valid();
20146    }
20147
20148    /// **The depth-only passes run the depth-only entry point, and the colour
20149    /// pass does not.**
20150    ///
20151    /// Topic 43 §2 split the vertex pool so a pass
20152    /// that wants a clip position and no more could fetch stream 0 alone, and
20153    /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20154    /// is the whole of how that split is spent. **Nothing else in the tree sees
20155    /// it.** `crcbl_shaders::mesh`'s
20156    /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20157    /// compiled artifact and would pass with the entry point built and unused;
20158    /// no golden moves, because the two stages compute the same clip position on
20159    /// purpose; the render graph records a legal frame either way; and the
20160    /// measured price says nothing — pointing this pipeline back at `vertexMain`
20161    /// cost the depth prepass about a tenth more on lavapipe and nothing to
20162    /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20163    /// asserted here, against the reference backend, which records the entry
20164    /// point a pipeline names precisely so this question has an answer.
20165    ///
20166    /// **Both halves, so the check is shown to discriminate.** A lookup that
20167    /// answered `depthVertexMain` for every pipeline would satisfy the first
20168    /// assertion alone, and the colour pipeline is the one that must *not* have
20169    /// moved. The labels are the descriptors' own and are what the two are told
20170    /// apart by, so a renamed pipeline fails at the `expect` rather than
20171    /// silently matching nothing.
20172    #[test]
20173    fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20174        let (recorder, device, queue) = open();
20175        let device = device.as_ref();
20176        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20177        // A mesh stage has no vertex entry point to name, and this whole rung is
20178        // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20179        // preset reports no `Features::MESH_SHADER`, so this is what it built;
20180        // asserted rather than assumed, because a preset that grew the feature
20181        // would leave every assertion below looking for pipelines that do not
20182        // exist.
20183        assert_ne!(
20184            renderer.geometry_path(),
20185            crcbl_hal::GeometryPath::MeshShader,
20186            "this device built a mesh-shader path, whose geometry stage names no vertex \
20187             entry point at all"
20188        );
20189
20190        let pipelines = recorder.graphics_pipeline_vertex_entries();
20191        let entry_of = |label: &str| -> String {
20192            let found: Vec<&str> = pipelines
20193                .iter()
20194                .filter(|(name, _)| name.as_deref() == Some(label))
20195                .map(|(_, entry)| entry.as_str())
20196                .collect();
20197            assert_eq!(
20198                found.len(),
20199                1,
20200                "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20201                found.len()
20202            );
20203            found[0].to_owned()
20204        };
20205
20206        assert_eq!(
20207            entry_of("shadow cascade"),
20208            "depthVertexMain",
20209            "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20210             that reads the position stream alone"
20211        );
20212        assert_eq!(
20213            entry_of("forward mesh"),
20214            "vertexMain",
20215            "the colour pass needs every attribute the depth pass skips, so it is the entry \
20216             point that reads a whole vertex"
20217        );
20218        assert_eq!(
20219            entry_of("shadow cascade masked"),
20220            "vertexMain",
20221            "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
20222             in the attribute region `depthVertexMain` exists not to read"
20223        );
20224
20225        renderer.destroy(device);
20226        recorder.assert_valid();
20227    }
20228
20229    /// **A masked material moves that mesh's depth draws onto the cutout
20230    /// pipeline, and moves nothing else.**
20231    ///
20232    /// The mechanism is which pipeline handle the recorded stream binds and
20233    /// which buckets' indirect calls follow each bind — the wireframe test's
20234    /// observable, for the same reason: a field saying a mode was read would
20235    /// prove the flag was read, not that the frame changed.
20236    ///
20237    /// Four claims, and each rules out a different way of passing wrongly:
20238    ///
20239    /// * a scene with nothing masked binds the vertex-only pipeline and
20240    ///   **never** the cutout one, which is the "an opaque frame costs what it
20241    ///   always did" claim at the level a null device can see it;
20242    /// * a scene with one masked row binds **both** in the depth prepass and
20243    ///   both in the shadow atlas — a per-frame choice binds one or the other,
20244    ///   never the pair;
20245    /// * the calls following each bind are exactly that mode's buckets, in
20246    ///   bucket order, read off the argument offsets the draws name. A split
20247    ///   that bound both pipelines and drew every bucket under each would
20248    ///   satisfy the claim above and double the frame's draws;
20249    /// * and folding the two handles together — then collapsing the runs of
20250    ///   equal binds the fold creates — leaves the two frames' bind streams
20251    ///   **equal**, so the colour pass, the tile clears and the reflective
20252    ///   shadow map are all where they were. A change that had also moved the
20253    ///   colour pass would satisfy the first three and fail this.
20254    ///
20255    /// The two scenes differ in one flags word and nothing else.
20256    #[test]
20257    fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
20258        use crcbl_hal::null::Command;
20259
20260        // The occlusion blur count is a process-global console variable and a
20261        // frame binds one pipeline per blur, so a concurrent test moving it
20262        // would put a bind in one of these frames and not the other — the
20263        // wireframe test's hazard exactly.
20264        let _blurs = ssao_blur_switch();
20265
20266        let masked_scene = {
20267            let mut scene = crate::scene::demo();
20268            scene.materials[DEMO_UNTINTED].flags =
20269                crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
20270            scene
20271        };
20272
20273        /// What one scene's frame reveals: the bucket count and each bucket's
20274        /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
20275        /// pairs the depth prepass and the shadow atlas recorded, and the whole
20276        /// bind stream with the two depth handles folded into one.
20277        struct Recorded {
20278            modes: Vec<u32>,
20279            cutouts: usize,
20280            plains: usize,
20281            prepass: Vec<(bool, u32)>,
20282            atlas: Vec<(bool, u32)>,
20283            folded: Vec<GraphicsPipelineHandle>,
20284        }
20285
20286        // One frame each, from two renderers rather than two frames from one:
20287        // a bucket table is fixed at build, and two builds keep the frames'
20288        // shadow-atlas state identical — both are a first frame.
20289        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20290            let (recorder, device, queue) = open();
20291            let device = device.as_ref();
20292            let mut renderer =
20293                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20294                    .expect("the null backend accepts the demo description");
20295            place_cube(&mut renderer, Mat4::IDENTITY);
20296            let imported = swapchain_image(device);
20297            let mut pool = crate::TransientPool::new();
20298            renderer
20299                .begin_frame(
20300                    device,
20301                    &Camera::default(),
20302                    &DirectionalLight::default(),
20303                    (64, 48),
20304                )
20305                .expect("write");
20306            let mut graph = crate::RenderGraph::new(queue);
20307            let target = graph.import_image("target", imported);
20308            renderer.add_passes(&mut graph, &pool, target, (64, 48));
20309            let compiled = graph.compile(&pool).expect("a legal frame");
20310            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20311                label: Some("alpha mask lap"),
20312                queue,
20313            });
20314            compiled
20315                .execute(device, &mut pool, encoder.as_mut(), None)
20316                .expect("the graph executed");
20317            encoder.finish().expect("recording succeeded");
20318            let plain = renderer.shadow_pipeline.single;
20319            let cutout = renderer.depth_masked_pipeline.single;
20320            assert_ne!(
20321                plain, cutout,
20322                "the two depth pipelines have to be two objects, or nothing below discriminates"
20323            );
20324            // Which bucket a draw is, recovered from the argument offset it
20325            // names — the offsets are the renderer's own accessor, so a call
20326            // pointing at the wrong bucket has no entry here at all.
20327            let bucket_of = |args_offset: u64| -> u32 {
20328                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20329                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20330                    .unwrap_or_else(|| {
20331                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20332                    })
20333            };
20334            // Per depth pass: the pipeline in force at each indirect call and
20335            // the bucket that call drew, in the order they were recorded.
20336            let pass_calls = |label: &str| -> Vec<(bool, u32)> {
20337                let mut current = None;
20338                let mut out = Vec::new();
20339                for command in commands_in_pass(&recorder, label) {
20340                    match command {
20341                        Command::BindGraphicsPipeline(handle) => current = Some(handle),
20342                        Command::DrawIndexedIndirectCount(draw) => {
20343                            let handle = current.expect("a draw follows a pipeline bind");
20344                            assert!(
20345                                handle == plain || handle == cutout,
20346                                "a depth pass drew under a pipeline that is neither depth one"
20347                            );
20348                            out.push((handle == cutout, bucket_of(draw.args_offset)));
20349                        }
20350                        _ => {}
20351                    }
20352                }
20353                out
20354            };
20355            let prepass = pass_calls("depth-prepass");
20356            let atlas = pass_calls("shadow");
20357            let binds: Vec<GraphicsPipelineHandle> = recorder
20358                .commands()
20359                .iter()
20360                .filter_map(|command| match command {
20361                    Command::BindGraphicsPipeline(handle) => Some(*handle),
20362                    _ => None,
20363                })
20364                .collect();
20365            let cutouts = binds.iter().filter(|handle| **handle == cutout).count();
20366            let plains = binds.iter().filter(|handle| **handle == plain).count();
20367            let mut folded: Vec<GraphicsPipelineHandle> = Vec::with_capacity(binds.len());
20368            for handle in binds {
20369                let handle = if handle == cutout { plain } else { handle };
20370                // The fold turns the masked frame's `plain, cutout` pair into
20371                // `plain, plain`; collapsing a run of equal binds is what makes
20372                // the two streams comparable without hiding a bind of anything
20373                // else, since no pass in either frame binds two *different*
20374                // pipelines that the fold could bring together.
20375                if folded.last() != Some(&handle) {
20376                    folded.push(handle);
20377                }
20378            }
20379            let modes = renderer.bucket_modes.clone();
20380            renderer.destroy(device);
20381            recorder.assert_valid();
20382            Recorded {
20383                modes,
20384                cutouts,
20385                plains,
20386                prepass,
20387                atlas,
20388                folded,
20389            }
20390        };
20391
20392        let opaque = bound(&crate::scene::demo());
20393        let masked = bound(&masked_scene);
20394
20395        assert_eq!(
20396            opaque.cutouts, 0,
20397            "a scene with nothing masked must never bind the cutout pipeline"
20398        );
20399        assert!(
20400            opaque.plains > 0,
20401            "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
20402             above is about a frame with no depth pass in it"
20403        );
20404        assert!(
20405            opaque.modes.iter().all(|mode| *mode == 0),
20406            "and every one of its buckets is opaque: {:?}",
20407            opaque.modes
20408        );
20409        assert_eq!(
20410            opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
20411            0,
20412            "so no opaque draw is recorded under the cutout pipeline"
20413        );
20414
20415        assert!(
20416            masked.cutouts > 0 && masked.plains > 0,
20417            "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
20418             the choice is still per frame",
20419            masked.cutouts,
20420            masked.plains
20421        );
20422        // What each depth pass should have recorded: every opaque bucket under
20423        // the plain pipeline in bucket order, then every masked one under the
20424        // cutout, which is the partition order `depth_partitions` lays down.
20425        let want: Vec<(bool, u32)> = [false, true]
20426            .into_iter()
20427            .flat_map(|cutout| {
20428                masked
20429                    .modes
20430                    .iter()
20431                    .enumerate()
20432                    .filter(move |(_, mode)| {
20433                        (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
20434                    })
20435                    .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
20436            })
20437            .collect();
20438        assert!(
20439            want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
20440            "the masked demo has to hold buckets of both modes, or this compares one partition \
20441             against itself: {:?}",
20442            masked.modes
20443        );
20444        assert_eq!(
20445            masked.prepass, want,
20446            "the depth prepass must record each bucket once, under the pipeline its own mode \
20447             asked for"
20448        );
20449        // The atlas draws every bucket once per occupied view, and the
20450        // partition is **outside** the view loop — one pipeline bind covers
20451        // every view of that mode — so its stream is each partition's bucket
20452        // list repeated once per view.
20453        let views = masked.atlas.len() / want.len();
20454        assert!(
20455            views > 0 && masked.atlas.len() % want.len() == 0,
20456            "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
20457             of views",
20458            masked.atlas.len(),
20459            want.len()
20460        );
20461        let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
20462        for cutout in [false, true] {
20463            let partition: Vec<(bool, u32)> = want
20464                .iter()
20465                .copied()
20466                .filter(|(mode, _)| *mode == cutout)
20467                .collect();
20468            for _ in 0..views {
20469                atlas_want.extend_from_slice(&partition);
20470            }
20471        }
20472        assert_eq!(
20473            masked.atlas, atlas_want,
20474            "and every shadow view draws both partitions, each under its own pipeline"
20475        );
20476
20477        assert_eq!(
20478            masked.folded, opaque.folded,
20479            "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
20480        );
20481    }
20482
20483    /// **A double-sided material moves every pass's draws for its own buckets
20484    /// onto the `CullMode::None` twins, and moves nothing else.**
20485    ///
20486    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
20487    /// claim for glTF's other mode, and it is wider by construction: an alpha
20488    /// mask is cut inside a fragment stage, so only the two depth-only passes
20489    /// route around it, while a cull mode is a pipeline state and **every** pass
20490    /// that draws the surface has to route around it — the colour pass, both
20491    /// depth passes and the two reflective shadow maps.
20492    ///
20493    /// So this walks the whole recorded stream rather than two named passes:
20494    /// every render pass that recorded an indirect draw is read back as the
20495    /// (side, bucket) pairs it recorded, and each of the four claims below is
20496    /// about all of them at once.
20497    ///
20498    /// * a scene with nothing double-sided binds **no** cull-none twin
20499    ///   anywhere, which is the "an all-single-sided frame costs what it always
20500    ///   did" claim at the level a null device can see it;
20501    /// * a scene with one double-sided row binds a twin in every pass that
20502    ///   draws — a frame that had only routed the colour pass would satisfy
20503    ///   nothing below, and one that had only routed the depth passes would
20504    ///   draw a surface the prepass wrote no depth for;
20505    /// * the calls following each bind are exactly that side's buckets, in
20506    ///   bucket order. A split that bound both pipelines and drew every bucket
20507    ///   under each would satisfy the claim above and double the frame's draws;
20508    /// * and folding each twin onto the pipeline it is a twin of — then
20509    ///   collapsing the runs of equal binds the fold creates — leaves the two
20510    ///   frames' bind streams **equal**, so nothing else in the frame moved.
20511    ///
20512    /// The two scenes differ in one flags word and nothing else.
20513    ///
20514    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]: fn@a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline
20515    #[test]
20516    fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
20517        use crcbl_hal::null::Command;
20518
20519        // The occlusion blur count is a process-global console variable and a
20520        // frame binds one pipeline per blur — the masked test's hazard exactly.
20521        let _blurs = ssao_blur_switch();
20522
20523        // **A scene whose probes ask to be updated**, because the reflective
20524        // shadow maps are recorded by a volume rather than by an effect bit —
20525        // and they are two of the five passes this claim is about. The demo's
20526        // empty grid records neither, which would leave the widest half of the
20527        // routing unchecked.
20528        let scene_with_probes = || {
20529            let mut scene = crate::scene::demo();
20530            scene.capacities.probes = 1;
20531            scene.probes = crate::scene::ProbeGrid {
20532                volume: crcbl_shaders::probe::ProbeVolume {
20533                    origin: [0.0; 3],
20534                    inv_spacing: [1.0; 3],
20535                    counts: [1, 1, 1],
20536                    levels: 1,
20537                    steps: crcbl_shaders::probe::ProbeSteps::default(),
20538                },
20539                probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
20540                update: ProbeUpdate::EveryFrame,
20541            };
20542            scene
20543        };
20544        let single_scene = scene_with_probes();
20545        let double_scene = {
20546            let mut scene = scene_with_probes();
20547            scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
20548            scene
20549        };
20550
20551        /// What one scene's frame reveals: each bucket's mode, how often a
20552        /// cull-none twin was bound at all, every drawing pass's (side, bucket)
20553        /// pairs in record order, and the whole bind stream with each twin
20554        /// folded onto the pipeline it twins.
20555        struct Recorded {
20556            modes: Vec<u32>,
20557            twins_bound: usize,
20558            passes: Vec<(String, Vec<(bool, u32)>)>,
20559            folded: Vec<GraphicsPipelineHandle>,
20560        }
20561
20562        // One frame each, from two renderers rather than two frames from one, on
20563        // the masked test's terms: a bucket table is fixed at build, and two
20564        // builds keep both frames a first frame.
20565        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20566            let (recorder, device, queue) = open();
20567            let device = device.as_ref();
20568            let mut renderer =
20569                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20570                    .expect("the null backend accepts the demo description");
20571            assert!(
20572                !renderer.emit.is_mesh(),
20573                "this preset built a mesh-shader path, whose draws carry no argument offset to \
20574                 recover a bucket from"
20575            );
20576            place_cube(&mut renderer, Mat4::IDENTITY);
20577            // **One shadowed spot**, so the punctual reflective shadow map has a
20578            // face to draw into: the pass is recorded on every frame but its
20579            // view loop is empty without one, and an empty loop records no draw
20580            // for the claim below to be about.
20581            renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
20582                position: Vec3::new(0.0, 2.0, 0.0),
20583                radius: 8.0,
20584                color: Vec3::splat(4.0),
20585                direction: Vec3::NEG_Y,
20586                inner_angle: 0.3,
20587                outer_angle: 0.6,
20588                fill: false,
20589            })]);
20590            let imported = swapchain_image(device);
20591            let mut pool = crate::TransientPool::new();
20592            renderer
20593                .begin_frame(
20594                    device,
20595                    &Camera::default(),
20596                    &DirectionalLight::default(),
20597                    (64, 48),
20598                )
20599                .expect("write");
20600            let mut graph = crate::RenderGraph::new(queue);
20601            let target = graph.import_image("target", imported);
20602            renderer.add_passes(&mut graph, &pool, target, (64, 48));
20603            let compiled = graph.compile(&pool).expect("a legal frame");
20604            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20605                label: Some("double sided lap"),
20606                queue,
20607            });
20608            compiled
20609                .execute(device, &mut pool, encoder.as_mut(), None)
20610                .expect("the graph executed");
20611            encoder.finish().expect("recording succeeded");
20612
20613            // Every twin and the pipeline it twins, so a bind can be reported as
20614            // a side and folded back. Asserted distinct, or nothing here
20615            // discriminates.
20616            let sided = [
20617                renderer.mesh_pipeline,
20618                renderer.shadow_pipeline,
20619                renderer.depth_masked_pipeline,
20620                renderer.rsm_pipeline,
20621            ];
20622            for pair in sided {
20623                assert_ne!(
20624                    pair.single, pair.double,
20625                    "a pipeline and its cull-none twin have to be two objects"
20626                );
20627            }
20628            let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
20629                sided
20630                    .iter()
20631                    .find(|pair| pair.double == handle)
20632                    .map(|pair| pair.single)
20633            };
20634            let bucket_of = |args_offset: u64| -> u32 {
20635                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20636                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20637                    .unwrap_or_else(|| {
20638                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20639                    })
20640            };
20641
20642            let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
20643            let mut folded: Vec<GraphicsPipelineHandle> = Vec::new();
20644            let mut twins_bound = 0usize;
20645            let mut current: Option<GraphicsPipelineHandle> = None;
20646            let mut label: Option<String> = None;
20647            let mut calls: Vec<(bool, u32)> = Vec::new();
20648            let commands = recorder.commands();
20649            for command in &commands {
20650                match command {
20651                    Command::BeginRenderPass { label: name, .. } => {
20652                        label = name.clone();
20653                        calls = Vec::new();
20654                    }
20655                    Command::EndRenderPass => {
20656                        if !calls.is_empty() {
20657                            passes.push((
20658                                label.clone().expect("every pass here is labelled"),
20659                                std::mem::take(&mut calls),
20660                            ));
20661                        }
20662                    }
20663                    Command::BindGraphicsPipeline(handle) => {
20664                        current = Some(*handle);
20665                        if twin_of(*handle).is_some() {
20666                            twins_bound += 1;
20667                        }
20668                        // The fold turns a `single, double` pair into
20669                        // `single, single`; collapsing a run of equal binds is
20670                        // what makes the two streams comparable without hiding
20671                        // a bind of anything else.
20672                        let folded_handle = twin_of(*handle).unwrap_or(*handle);
20673                        if folded.last() != Some(&folded_handle) {
20674                            folded.push(folded_handle);
20675                        }
20676                    }
20677                    Command::DrawIndexedIndirectCount(draw) => {
20678                        let handle = current.expect("a draw follows a pipeline bind");
20679                        calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
20680                    }
20681                    Command::DrawIndexedIndirect(draw) => {
20682                        let handle = current.expect("a draw follows a pipeline bind");
20683                        calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
20684                    }
20685                    _ => {}
20686                }
20687            }
20688            let modes = renderer.bucket_modes.clone();
20689            renderer.destroy(device);
20690            pool.destroy(device);
20691            device.destroy_image_view(imported.view);
20692            device.destroy_image(imported.image);
20693            recorder.assert_valid();
20694            Recorded {
20695                modes,
20696                twins_bound,
20697                passes,
20698                folded,
20699            }
20700        };
20701
20702        let single = bound(&single_scene);
20703        let double = bound(&double_scene);
20704
20705        assert_eq!(
20706            single.twins_bound, 0,
20707            "a scene with nothing double-sided must never bind a cull-none twin"
20708        );
20709        // Named rather than counted, because the claim is that **every** pass
20710        // that draws the surface routes: a frame that had quietly stopped
20711        // recording one of them would satisfy a count and leave that pass's
20712        // routing unchecked for ever.
20713        let drawing: Vec<&str> = single
20714            .passes
20715            .iter()
20716            .map(|(name, _)| name.as_str())
20717            .collect();
20718        for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
20719            assert!(
20720                drawing.contains(&pass),
20721                "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
20722            );
20723        }
20724        assert!(
20725            double.twins_bound > 0,
20726            "a double-sided scene must bind the cull-none twins"
20727        );
20728        assert_eq!(
20729            double
20730                .passes
20731                .iter()
20732                .map(|(name, _)| name)
20733                .collect::<Vec<_>>(),
20734            single
20735                .passes
20736                .iter()
20737                .map(|(name, _)| name)
20738                .collect::<Vec<_>>(),
20739            "the two frames must draw in the same passes, or they are not comparable"
20740        );
20741
20742        // What each drawing pass should have recorded: every single-sided bucket
20743        // under the plain pipeline in bucket order, then every double-sided one
20744        // under the twin — the partition order `sided_partitions` lays down —
20745        // repeated once per view for a pass that draws several.
20746        let want: Vec<(bool, u32)> = [false, true]
20747            .into_iter()
20748            .flat_map(|twin| {
20749                double
20750                    .modes
20751                    .iter()
20752                    .enumerate()
20753                    .filter(move |(_, mode)| {
20754                        (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
20755                    })
20756                    .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
20757            })
20758            .collect();
20759        assert!(
20760            want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
20761            "the double-sided demo has to hold buckets of both sides, or this compares one \
20762             partition against itself: {:?}",
20763            double.modes
20764        );
20765        for (name, calls) in &double.passes {
20766            let views = calls.len() / want.len();
20767            assert!(
20768                views > 0 && calls.len() % want.len() == 0,
20769                "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
20770                 views",
20771                calls.len(),
20772                want.len()
20773            );
20774            // The partition is **outside** any view loop — one pipeline bind
20775            // covers every view of that side — so the stream is each partition's
20776            // bucket list repeated once per view.
20777            let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
20778            for twin in [false, true] {
20779                let partition: Vec<(bool, u32)> = want
20780                    .iter()
20781                    .copied()
20782                    .filter(|(side, _)| *side == twin)
20783                    .collect();
20784                for _ in 0..views {
20785                    expected.extend_from_slice(&partition);
20786                }
20787            }
20788            assert_eq!(
20789                *calls, expected,
20790                "`{name}` must record each bucket once per view, under the pipeline its own \
20791                 side asked for"
20792            );
20793        }
20794
20795        assert_eq!(
20796            double.folded, single.folded,
20797            "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
20798             pipeline it twins"
20799        );
20800    }
20801
20802    /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
20803    ///
20804    /// The mechanism, at the level a null device can observe it: which pipeline
20805    /// handle each pass of the recorded stream binds. A field on the renderer
20806    /// would say only that a flag moved — this says the *frame* moved, and says
20807    /// which part of it did.
20808    ///
20809    /// Four claims, and each rules out a different way of passing wrongly:
20810    ///
20811    /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
20812    ///   one does not exist;
20813    /// * switching on **removes** the filled pipeline from the stream — a second
20814    ///   pipeline that was built and never bound would still leave it there;
20815    /// * every other pipeline the frame binds is unchanged, so the depth prepass
20816    ///   and the shadow cascades are still filling triangles;
20817    /// * and switching off puts the stream back exactly, so the view is a toggle
20818    ///   rather than a one-way door.
20819    #[test]
20820    fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
20821        use crcbl_hal::null::Command;
20822
20823        // The pipelines a frame binds include one per occlusion blur, and the
20824        // blur count is a process-global console variable — so a concurrent
20825        // test holding `r_ssao_blur_passes` at two adds a bind to one of the
20826        // frames below and not to the others. It reddened this assertion on
20827        // 2026-08-31 under a workspace `cargo test`.
20828        let _blurs = ssao_blur_switch();
20829        let (recorder, device, queue) =
20830            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20831        let device = device.as_ref();
20832        assert!(
20833            ForwardRenderer::supports_wireframe(device),
20834            "this test needs the line fill mode, and asked the device for it",
20835        );
20836        let mut renderer =
20837            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20838        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20839        let imported = swapchain_image(device);
20840        let mut pool = crate::TransientPool::new();
20841
20842        // The pipelines one frame binds, in record order. Cumulative recorder,
20843        // so each call takes the tail its own frame added.
20844        let mut seen = 0usize;
20845        // A different sun each lap, so the shadow atlas is redrawn in every one
20846        // of them: the comparison below is "which pipelines did this frame
20847        // bind", and a lap that cached its atlas would bind the depth-only
20848        // pipeline one fewer time for a reason that has nothing to do with the
20849        // wireframe. See [`moving_sun`].
20850        let mut lap = 0u32;
20851        let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
20852            lap += 1;
20853            renderer
20854                .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
20855                .expect("write");
20856            let mut graph = crate::RenderGraph::new(queue);
20857            let target = graph.import_image("target", imported);
20858            renderer.add_passes(&mut graph, pool, target, (64, 48));
20859            let compiled = graph.compile(pool).expect("a legal frame");
20860            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20861                label: Some("wireframe lap"),
20862                queue,
20863            });
20864            compiled
20865                .execute(device, pool, encoder.as_mut(), None)
20866                .expect("the graph executed");
20867            encoder.finish().expect("recording succeeded");
20868            let commands = recorder.commands();
20869            let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
20870                .iter()
20871                .filter_map(|command| match command {
20872                    Command::BindGraphicsPipeline(handle) => Some(*handle),
20873                    _ => None,
20874                })
20875                .collect();
20876            seen = commands.len();
20877            bound
20878        };
20879
20880        let filled = renderer.mesh_pipeline.single;
20881        let off = pipelines_in_a_frame(&mut renderer, &mut pool);
20882        assert!(
20883            off.contains(&filled),
20884            "a frame nobody asked has to bind the filled pipeline: {off:?}",
20885        );
20886        assert!(!renderer.wireframe());
20887        assert!(
20888            renderer.wireframe_pipeline.is_none(),
20889            "the wireframe pipeline must not be built until it is asked for",
20890        );
20891
20892        renderer
20893            .set_wireframe(device, true)
20894            .expect("a device with the line fill mode builds it");
20895        assert!(renderer.wireframe());
20896        let lines = renderer
20897            .wireframe_pipeline
20898            .expect("switching on is what builds it")
20899            .single;
20900        let on = pipelines_in_a_frame(&mut renderer, &mut pool);
20901        assert!(
20902            !on.contains(&filled),
20903            "the colour pass still bound the filled pipeline: {on:?}",
20904        );
20905        assert_eq!(
20906            on.iter().filter(|handle| **handle == lines).count(),
20907            1,
20908            "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
20909        );
20910        let substituted: Vec<GraphicsPipelineHandle> = on
20911            .iter()
20912            .map(|handle| if *handle == lines { filled } else { *handle })
20913            .collect();
20914        assert_eq!(
20915            substituted, off,
20916            "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
20917             {off:?}",
20918        );
20919
20920        renderer
20921            .set_wireframe(device, false)
20922            .expect("switching off builds nothing");
20923        assert!(!renderer.wireframe());
20924        assert_eq!(
20925            pipelines_in_a_frame(&mut renderer, &mut pool),
20926            off,
20927            "switching the view off has to put the filled pipeline back, not just stop reporting \
20928             it",
20929        );
20930
20931        renderer.destroy(device);
20932        pool.destroy(device);
20933        device.destroy_image_view(imported.view);
20934        device.destroy_image(imported.image);
20935        recorder.assert_valid();
20936    }
20937
20938    /// **The colour pass tests against the prepass's depth instead of clearing
20939    /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
20940    /// does the opposite, because lines do not reproduce a filled prepass.
20941    ///
20942    /// Both halves have to hold together or the frame is wrong in one of two
20943    /// ways, so both are asserted here. The attachment alone read-only while the
20944    /// pipeline still wrote would be a pipeline writing to a read-only
20945    /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
20946    /// this pass had just *cleared* would reject every fragment and draw a black
20947    /// frame. Neither shows up as an error — the first is a validation message
20948    /// on one backend and undefined behaviour on the rest, the second is a
20949    /// picture — which is why the observable is read off the compiled graph and
20950    /// off the pipeline state rather than off a screenshot.
20951    #[test]
20952    fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
20953        let (recorder, device, queue) =
20954            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20955        let device = device.as_ref();
20956        let mut renderer =
20957            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20958        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20959        let imported = swapchain_image(device);
20960        let mut pool = crate::TransientPool::new();
20961
20962        // Each pass's depth attachment, off the graph's own dump: the label it
20963        // was declared under, and the `load`/`store`/`write` triple the backend
20964        // is handed. A pass with no depth attachment contributes nothing, which
20965        // is what makes the lookup below a search rather than an index.
20966        let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
20967            renderer
20968                .begin_frame(
20969                    device,
20970                    &Camera::default(),
20971                    &DirectionalLight::default(),
20972                    (64, 48),
20973                )
20974                .expect("write");
20975            let mut graph = crate::RenderGraph::new(queue);
20976            let target = graph.import_image("target", imported);
20977            renderer.add_passes(&mut graph, pool, target, (64, 48));
20978            let dump = graph.compile(pool).expect("a legal frame").dump();
20979            let mut pass = String::new();
20980            let mut found = None;
20981            for line in dump.lines() {
20982                if let Some(rest) = line.split(" pass \"").nth(1) {
20983                    pass = rest.trim_end_matches('"').to_string();
20984                    if let Some((name, _)) = pass.split_once('"') {
20985                        pass = name.to_string();
20986                    }
20987                }
20988                if pass == label
20989                    && let Some(at) = line.find("depth load=")
20990                {
20991                    // Without the slot note the dump appends: which physical
20992                    // image the transient landed on is aliasing's business, not
20993                    // this assertion's.
20994                    let role = &line[at..];
20995                    let role = role.split_once(" [").map_or(role, |(head, _)| head);
20996                    found = Some(role.trim().to_string());
20997                }
20998            }
20999            found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21000        };
21001
21002        assert_eq!(
21003            depth_of(&mut renderer, &mut pool, "depth-prepass"),
21004            "depth load=Clear store=Store write=yes",
21005            "the prepass is what puts the depth there, so it clears, writes and keeps it",
21006        );
21007        assert_eq!(
21008            depth_of(&mut renderer, &mut pool, "forward"),
21009            "depth load=Load store=Store write=no",
21010            "and the colour pass reads it: a clear here would throw away the prepass and \
21011             pay for the overdraw again, and a write would be a second pass writing the \
21012             same values",
21013        );
21014        assert_eq!(
21015            MeshModules::color_depth_stencil(PolygonMode::Fill),
21016            Some(DepthStencilState {
21017                format: Format::D32Float,
21018                depth_write: false,
21019                depth_compare: CompareOp::GreaterOrEqual,
21020                stencil: None,
21021                bias: DepthBias::default(),
21022            }),
21023            "and the pipeline agrees with the attachment: equality against the prepass, \
21024             reachable only through the `OrEqual` under reversed-Z",
21025        );
21026
21027        renderer
21028            .set_wireframe(device, true)
21029            .expect("this device was asked for the line fill mode");
21030        assert_eq!(
21031            depth_of(&mut renderer, &mut pool, "forward"),
21032            "depth load=Clear store=Store write=yes",
21033            "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21034             along the edge rather than across the face, so testing it against a filled \
21035             prepass rejects most of the wireframe — and *loading* that depth under the \
21036             writing default's `Greater` would reject all of it",
21037        );
21038        assert_eq!(
21039            MeshModules::color_depth_stencil(PolygonMode::Line),
21040            MeshModules::depth_stencil(),
21041            "which is the writing default, the same state the depth-only twin uses",
21042        );
21043
21044        renderer.destroy(device);
21045        pool.destroy(device);
21046        device.destroy_image_view(imported.view);
21047        device.destroy_image(imported.image);
21048        recorder.assert_valid();
21049    }
21050
21051    /// **A device with no line fill mode is refused, not quietly filled.**
21052    ///
21053    /// The failure this rules out is the silent one: a caller who binds a key to
21054    /// this, presses it, and gets the solid frame back with nothing anywhere
21055    /// saying why — which on a model whose silhouette hides its interior is
21056    /// indistinguishable from a wireframe that worked. WebGPU is the real device
21057    /// this happens on; `open`'s null device stands in for it, because
21058    /// [`DeviceDesc::for_adapter`] asks for
21059    /// [`Features::GPU_DRIVEN`] and nothing else.
21060    #[test]
21061    fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21062        let (recorder, device, queue) = open();
21063        let device = device.as_ref();
21064        assert!(
21065            !ForwardRenderer::supports_wireframe(device),
21066            "this device was not asked for the line fill mode, so it must not report it",
21067        );
21068        let mut renderer =
21069            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21070
21071        let refused = renderer
21072            .set_wireframe(device, true)
21073            .expect_err("a device without the feature has to say so");
21074        assert!(
21075            matches!(
21076                refused,
21077                HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21078            ),
21079            "the refusal has to name the feature to go and look up, and is {refused:?}",
21080        );
21081        assert!(
21082            !renderer.wireframe(),
21083            "a refused request must leave the view off rather than half on",
21084        );
21085        assert!(
21086            renderer.wireframe_pipeline.is_none(),
21087            "nothing may be left behind by a refusal",
21088        );
21089        // And switching *off* is still fine on such a device: it builds nothing.
21090        renderer
21091            .set_wireframe(device, false)
21092            .expect("switching off asks the device for nothing");
21093
21094        renderer.destroy(device);
21095        recorder.assert_valid();
21096    }
21097
21098    /// The grid's own full-screen triangle is counted as submitted, and only
21099    /// while it is on.
21100    ///
21101    /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21102    /// row, and every full-screen pass in the frame contributes one — so a grid
21103    /// that drew and was not counted makes that row disagree with the frame by
21104    /// exactly one triangle, silently.
21105    #[test]
21106    fn the_grids_triangle_is_counted_only_while_it_is_on() {
21107        let _blurs = ssao_blur_switch();
21108        let (recorder, device, queue) = open();
21109        let device = device.as_ref();
21110        let mut renderer =
21111            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21112        let imported = swapchain_image(device);
21113        let mut pool = crate::TransientPool::new();
21114
21115        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21116        let off = renderer.counters();
21117
21118        renderer
21119            .set_ground_grid(device, Some(GridStyle::default()))
21120            .expect("the null backend builds every pipeline");
21121        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21122        let on = renderer.counters();
21123
21124        assert_eq!(
21125            on.draws - off.draws,
21126            FULLSCREEN_DRAWS,
21127            "the grid records exactly one draw"
21128        );
21129        assert_eq!(
21130            on.instances - off.instances,
21131            FULLSCREEN_DRAWS,
21132            "and exactly one submitted instance"
21133        );
21134
21135        renderer.destroy(device);
21136        pool.destroy(device);
21137        device.destroy_image_view(imported.view);
21138        device.destroy_image(imported.image);
21139        recorder.assert_valid();
21140    }
21141
21142    /// One frame on a device of its own, under an override switching `off`.
21143    ///
21144    /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21145    /// device's whole life: asking "did the atlas pass draw" of a recorder that
21146    /// has seen two frames answers about both of them, and the arm that matters
21147    /// most here is the one whose answer must be zero.
21148    ///
21149    /// Returns what the frame reported and what its atlas pass actually drew.
21150    fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21151        use crcbl_hal::null::Command;
21152
21153        let recorder = Recorder::new();
21154        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21155        let adapter = instance.adapters().remove(0);
21156        let opened = instance
21157            .create_device(&DeviceDesc::for_adapter(adapter.id))
21158            .expect("the null backend always opens");
21159        let device = opened.as_ref();
21160        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21161        let mut renderer =
21162            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21163        // A shadowed light beside the cascades, so the atlas pass has draws to
21164        // lose rather than being empty either way.
21165        renderer.set_lights(&[shadowable_spot(-1.0)]);
21166        // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21167        // camera stack leaves both of them out — see
21168        // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21169        // default alone would be measuring three effects and calling it five,
21170        // and their arms below would be switching off something already off.
21171        // `force` clears the other side, so an arm whose `off` is one of them
21172        // still resolves to off.
21173        renderer.set_effect_request(EffectRequest {
21174            programmatic: EffectOverride::none()
21175                .force(OUTSIDE_THE_DEFAULT, Some(true))
21176                .force(off, Some(false)),
21177            ..EffectRequest::default()
21178        });
21179
21180        let recorded = frame(device, &mut renderer, queue);
21181        assert_eq!(
21182            renderer.effects(),
21183            RenderEffects::all().difference(off),
21184            "the frame must have resolved to the set the request asked for"
21185        );
21186        let counters = renderer.counters();
21187        let instances = renderer.instances.len() as u64;
21188        let atlas_draws = commands_in_pass(&recorder, "shadow")
21189            .into_iter()
21190            .filter(|command| {
21191                matches!(
21192                    command,
21193                    Command::DrawIndexedIndirect(_)
21194                        | Command::DrawIndexedIndirectCount(_)
21195                        | Command::DrawMeshTasksIndirect(_)
21196                )
21197            })
21198            .count();
21199        assert_eq!(
21200            counters.draws,
21201            recorded_draws(&recorder) as u64,
21202            "the counter and the frame's own recorded stream must agree, whatever is switched off"
21203        );
21204        recorded.finish(device, renderer);
21205        recorder.assert_valid();
21206        (counters, instances, atlas_draws)
21207    }
21208
21209    /// **A switched-off effect is work the frame did not record**, and a frame
21210    /// that still executes with the placeholder bound in place of what it lost.
21211    ///
21212    /// The other half of the pass-list test above, and the half a pass list
21213    /// cannot make: the `shadow` pass is still *there* with shadows off, so the
21214    /// question is whether it drew. That answer comes off the recorded command
21215    /// stream, which is a different instrument from `recorded_draws` — the number
21216    /// under test.
21217    ///
21218    /// Executed rather than only compiled, because the occlusion switch changes
21219    /// which image the forward pass has bound. A frame that declared a read of a
21220    /// transient it never created, or bound a view the graph never realised,
21221    /// fails here and compiles perfectly.
21222    #[test]
21223    fn a_switched_off_effect_is_work_the_frame_did_not_record() {
21224        let _blurs = ssao_blur_switch();
21225        let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
21226        assert!(
21227            atlas_draws > 0,
21228            "with shadows on the atlas pass has to draw something, or turning it off means \
21229             nothing"
21230        );
21231        assert_eq!(
21232            control.instances,
21233            instances
21234                + fullscreen_passes(
21235                    RenderEffects::all(),
21236                    TEST_EXTENT,
21237                    false,
21238                    crate::ssao::blur_passes(),
21239                ) * FULLSCREEN_DRAWS,
21240            "the control frame submits one triangle per full-screen pass"
21241        );
21242
21243        // Each pair is one full-screen triangle per pass, and the atlas is
21244        // untouched by either.
21245        for (off, fewer) in [
21246            (
21247                RenderEffects::AMBIENT_OCCLUSION,
21248                u64::from(Ssao::passes(crate::ssao::blur_passes())),
21249            ),
21250            // The contact march's one pass, and a constant rather than a
21251            // function of anything: it has no blur behind it and no chain.
21252            (
21253                RenderEffects::CONTACT_SHADOWS,
21254                u64::from(ContactShadows::PASSES),
21255            ),
21256            // The march's two passes and the reductions that feed them, which
21257            // is what makes this arm's number a function of the extent the way
21258            // the chain's below is.
21259            (
21260                RenderEffects::REFLECTIONS,
21261                u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
21262            ),
21263            // Not a constant, unlike the occlusion pair above: the chain's
21264            // length is a function of the extent, and this is what it is at
21265            // `TEST_EXTENT`.
21266            (
21267                RenderEffects::BLOOM,
21268                u64::from(Bloom::passes_for(TEST_EXTENT)),
21269            ),
21270        ] {
21271            let (counters, instances, atlas) = frame_switching_off(off);
21272            assert_eq!(
21273                counters.draws,
21274                control.draws - fewer * FULLSCREEN_DRAWS,
21275                "{off:?}: the frame must record one draw fewer per pass it did not add"
21276            );
21277            assert_eq!(
21278                counters.instances,
21279                instances
21280                    + fullscreen_passes(
21281                        RenderEffects::all().difference(off),
21282                        TEST_EXTENT,
21283                        false,
21284                        crate::ssao::blur_passes(),
21285                    ) * FULLSCREEN_DRAWS,
21286                "{off:?}: and must not report as submitted a triangle it never submitted"
21287            );
21288            assert_eq!(
21289                atlas, atlas_draws,
21290                "{off:?}: a screen-space effect must not touch the shadow atlas"
21291            );
21292        }
21293
21294        // Shadows: the atlas pass survives and draws nothing at all, which is
21295        // the mechanism — a cleared reversed-Z atlas reads as fully lit.
21296        let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
21297        assert_eq!(
21298            atlas, 0,
21299            "with shadows off the atlas pass must record its clear and no draw"
21300        );
21301        assert_eq!(
21302            counters.draws,
21303            control.draws - atlas_draws as u64,
21304            "and the frame must record exactly the atlas pass's draws fewer"
21305        );
21306    }
21307
21308    /// **Every pass the frame records gets a row in the report, except the ones
21309    /// that open no scope.**
21310    ///
21311    /// The observable the bound exists for: the samples' hand-picked capacity
21312    /// timed the first eight passes of a fourteen-pass frame and reported eight
21313    /// rows, which reads exactly like a frame that has eight passes. Sized from
21314    /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
21315    /// pass the graph compiled, in order — so a bound one short of the frame
21316    /// makes this list short too.
21317    ///
21318    /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
21319    /// expectation rather than expected to be missing by accident. The seam
21320    /// takes a timestamp only where a pass opens and closes and a copy opens
21321    /// nothing, so `PassTimers` gives it no query pair and no row — a row
21322    /// reading 0.000 ms would be a measurement nobody made.
21323    #[test]
21324    fn every_pass_of_the_frame_gets_a_timing_row() {
21325        let _blurs = ssao_blur_switch();
21326        // And the comparison seam, so the frame this checks carries the
21327        // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
21328        // for a *per-technique* cost, and what makes that true is this test's
21329        // own claim — every pass that opens a scope gets a row — applied to a
21330        // frame that compares. See `crate::ssao`'s `r_ssao_split`.
21331        let split = ssao_split_switch();
21332        split.set(0.5);
21333        let recorder = Recorder::new();
21334        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21335        let adapter = instance.adapters().remove(0);
21336        // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
21337        // may lack it — so a device that wants timers has to ask for it, and
21338        // `open` above, which uses `DeviceDesc::for_adapter`, does not.
21339        let opened = instance
21340            .create_device(&DeviceDesc {
21341                label: Some("timed frame"),
21342                adapter: adapter.id,
21343                required_features: Features::GPU_DRIVEN,
21344                optional_features: Features::TIMESTAMP_QUERY,
21345                compatible_surface: None,
21346            })
21347            .expect("the null backend always opens");
21348        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21349        let device = opened.as_ref();
21350        let mut renderer =
21351            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21352        renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
21353        let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
21354            .expect("the tier A null adapter has timestamp queries");
21355        let imported = swapchain_image(device);
21356        let mut pool = crate::TransientPool::new();
21357        let mut recorded = Vec::new();
21358        let mut compiled_labels = Vec::new();
21359
21360        // The ring is one slot longer than the frames in flight and resolves a
21361        // slot only when it comes round again, so the first frame's report is
21362        // that many frames behind it — see the [`timing`](crate::timing) docs.
21363        for _ in 0..FRAMES_IN_FLIGHT + 2 {
21364            renderer
21365                .begin_frame(
21366                    device,
21367                    &Camera::default(),
21368                    &DirectionalLight::default(),
21369                    (64, 48),
21370                )
21371                .expect("write");
21372            let mut graph = crate::RenderGraph::new(queue);
21373            let target = graph.import_image("target", imported);
21374            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21375            let compiled = graph.compile(&pool).expect("a legal frame");
21376            if compiled_labels.is_empty() {
21377                compiled_labels = compiled
21378                    .passes()
21379                    .iter()
21380                    .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
21381                    .map(|pass| pass.label().to_string())
21382                    .collect();
21383            }
21384            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21385                label: Some("timed frame"),
21386                queue,
21387            });
21388            compiled
21389                .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
21390                .expect("the graph executed");
21391            recorded.push(encoder.finish().expect("recording succeeded"));
21392        }
21393
21394        let reported: Vec<&str> = timers
21395            .latest()
21396            .passes
21397            .iter()
21398            .map(|timing| timing.label.as_str())
21399            .collect();
21400        // Anti-vacuity for the seam held above: a frame that did not compare
21401        // would satisfy the equality below and say nothing about a
21402        // per-technique cost, because there would be one technique in it.
21403        for label in ["ssao", "ssao-shipped"] {
21404            assert!(
21405                compiled_labels.iter().any(|pass| pass == label),
21406                "the frame compiled no `{label}` pass, so the seam did not reach it and this \
21407                 test says nothing about a comparison having a cost per side. Its passes: \
21408                 {compiled_labels:?}"
21409            );
21410        }
21411        assert_eq!(
21412            reported,
21413            compiled_labels,
21414            "the report must name every pass the frame compiled that opens a scope, in order \
21415             — {} of {} timed with a capacity of {}",
21416            reported.len(),
21417            compiled_labels.len(),
21418            timers.capacity()
21419        );
21420
21421        timers.destroy(device);
21422        renderer.destroy(device);
21423        for commands in recorded {
21424            device.destroy_command_buffer(commands);
21425        }
21426        pool.destroy(device);
21427        device.destroy_image_view(imported.view);
21428        device.destroy_image(imported.image);
21429        recorder.assert_valid();
21430    }
21431
21432    /// One mesh-table entry, decoded from the bytes that reached the device.
21433    fn mesh_entry(
21434        recorder: &Recorder,
21435        renderer: &ForwardRenderer,
21436        id: u32,
21437    ) -> crcbl_shaders::mesh::GpuMesh {
21438        let table = recorder
21439            .buffer_bytes(renderer.pool.table_buffer())
21440            .expect("the table is live");
21441        let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
21442        crcbl_shaders::mesh::GpuMesh::from_bytes(
21443            table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
21444                .try_into()
21445                .expect("one whole entry"),
21446        )
21447    }
21448
21449    // --- skinning: the seam a caller draws a skinned mesh through -----------
21450
21451    /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
21452    /// [`Skinning`] built against that renderer's own vertex pool.
21453    struct SkinnedFixture {
21454        renderer: ForwardRenderer,
21455        skinning: Skinning,
21456        skinned: SkinnedMesh,
21457        palette: Vec<Mat4>,
21458        bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
21459    }
21460
21461    impl SkinnedFixture {
21462        fn build(device: &dyn Device, queue: QueueHandle) -> Self {
21463            let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
21464                .expect("the null backend accepts every descriptor");
21465            let skinned = renderer
21466                .reserve_skinned(DEMO_CUBE)
21467                .expect("a default pool has room for two halves of a cube");
21468            let skinning = Skinning::new(
21469                device,
21470                &crate::skinning::SkinningDesc {
21471                    label: Some("skinned fixture"),
21472                    frames: FRAMES_IN_FLIGHT,
21473                    ranges: 1,
21474                    joints: 1,
21475                    bindings: skinned.vertex_count(),
21476                    // The renderer's own pool, which is the whole of what makes
21477                    // the dispatch's output reachable by its draws.
21478                    vertices: renderer.vertex_buffer(),
21479                    attribute_base: renderer.attribute_base(),
21480                },
21481            )
21482            .expect("the null backend accepts every descriptor");
21483            let bindings = vec![
21484                crcbl_shaders::skinning::SkinBinding {
21485                    joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
21486                    weights: [1.0, 0.0, 0.0, 0.0],
21487                };
21488                skinned.vertex_count() as usize
21489            ];
21490            Self {
21491                renderer,
21492                skinning,
21493                skinned,
21494                palette: vec![Mat4::IDENTITY],
21495                bindings,
21496            }
21497        }
21498
21499        /// One skinned frame's `begin_skinned_frame`, with this fixture's single
21500        /// range.
21501        fn begin(&mut self, device: &dyn Device) {
21502            let range = self.skinned.skin_range(&self.palette, &self.bindings);
21503            self.renderer
21504                .begin_skinned_frame(
21505                    device,
21506                    &mut self.skinning,
21507                    &[range],
21508                    &Camera::default(),
21509                    &DirectionalLight::default(),
21510                    TEST_EXTENT,
21511                )
21512                .expect("a legal skinning plan");
21513        }
21514
21515        fn destroy(mut self, device: &dyn Device) {
21516            self.renderer.release_skinned(self.skinned);
21517            self.skinning.destroy(device);
21518            self.renderer.destroy(device);
21519        }
21520    }
21521
21522    /// How many times the host wrote the mesh-table entry `id` names.
21523    fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
21524        let table = renderer.pool.table_buffer();
21525        let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
21526        recorder
21527            .events()
21528            .into_iter()
21529            .filter(|event| {
21530                matches!(
21531                    event,
21532                    crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
21533                        if *buffer == table && *offset == at
21534                )
21535            })
21536            .count()
21537    }
21538
21539    /// The record `handle` names, out of the ring buffer **this frame draws
21540    /// from** rather than out of the pool's host mirror.
21541    ///
21542    /// A mirror and a buffer that disagree is exactly the defect a re-pointing
21543    /// design can have, so every claim about a skinned instance's bases is read
21544    /// off the bytes a shader would.
21545    fn instance_record(
21546        recorder: &Recorder,
21547        renderer: &ForwardRenderer,
21548        handle: InstanceHandle,
21549    ) -> mesh::GpuInstance {
21550        let buffer = renderer.instances.buffers()[renderer.frame()];
21551        let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
21552        let index = renderer
21553            .instances
21554            .index(handle)
21555            .expect("the object is live") as usize;
21556        let at = index * mesh::INSTANCE_STRIDE;
21557        mesh::GpuInstance::from_bytes(
21558            bytes[at..at + mesh::INSTANCE_STRIDE]
21559                .try_into()
21560                .expect("one whole instance"),
21561        )
21562    }
21563
21564    /// **A skinned primitive takes no mesh-table entry of its own, and nothing
21565    /// rewrites the one it draws through.**
21566    ///
21567    /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
21568    /// precisely because nothing rewrites an entry between frames, so a design
21569    /// that re-pointed an entry at the half a frame writes would be wrong only
21570    /// on the frames that overlap — which is to say invisibly. What alternates
21571    /// instead is a field of the *instance*, and instances go through a ring.
21572    ///
21573    /// So a skinned object draws through the source mesh's own entry: the same
21574    /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
21575    /// carrying the bind pose's base vertex, still written exactly once after
21576    /// four skinned frames. That shared entry is also what lets one mesh be
21577    /// drawn skinned and unskinned in the same frame.
21578    #[test]
21579    fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
21580        let (recorder, device, queue) = open();
21581        let device = device.as_ref();
21582        let mut fixture = SkinnedFixture::build(device, queue);
21583
21584        let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
21585        assert_eq!(
21586            fixture.skinned.mesh_id(),
21587            bind_pose_id,
21588            "a skinned instance names the mesh it was deformed from, so the bucket, the level \
21589             tables and the bounding box all resolve as the bind pose's"
21590        );
21591
21592        let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
21593        assert_eq!(
21594            bind_pose.base_vertex,
21595            fixture.skinned.input_base(),
21596            "the entry goes on naming the bind pose the dispatch reads, not either half it \
21597             writes"
21598        );
21599        for parity in 0..2 {
21600            assert_ne!(
21601                fixture.skinned.region().base(parity),
21602                bind_pose.base_vertex,
21603                "half {parity} must not be the bind pose, which the kernel reads while it \
21604                 writes them"
21605            );
21606        }
21607        assert_ne!(
21608            fixture.skinned.region().base(0),
21609            fixture.skinned.region().base(1),
21610            "the two halves are separate reservations, or the ping-pong is one buffer"
21611        );
21612
21613        // Counted before the frames rather than compared against a literal:
21614        // `MeshPool::new` clears the whole table with one write at offset zero,
21615        // which lands on this entry too, so the number here is the pool's
21616        // start-up and not this test's business. What the loop below has to
21617        // leave alone is whatever it is.
21618        let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
21619        assert!(
21620            writes_before > 0,
21621            "the entry was written at least once before any frame ran, or the counter below \
21622             is counting nothing and the comparison after the frames is vacuous"
21623        );
21624
21625        // Four frames, which is two of each parity: enough that a design
21626        // rewriting an entry per frame would have written four more times.
21627        let imported = swapchain_image_at(device, TEST_EXTENT);
21628        let mut pool = crate::TransientPool::new();
21629        for _ in 0..4 {
21630            fixture.begin(device);
21631            let mut graph = crate::RenderGraph::new(queue);
21632            let target = graph.import_image("target", imported);
21633            fixture.renderer.add_skinned_passes(
21634                &mut graph,
21635                &pool,
21636                target,
21637                TEST_EXTENT,
21638                &fixture.skinning,
21639            );
21640            graph.compile(&pool).expect("a legal frame");
21641        }
21642
21643        assert_eq!(
21644            table_writes(&recorder, &fixture.renderer, bind_pose_id),
21645            writes_before,
21646            "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
21647             table is one buffer rather than a ring is that nothing rewrites an entry between \
21648             frames"
21649        );
21650
21651        fixture.destroy(device);
21652        pool.destroy(device);
21653        device.destroy_image_view(imported.view);
21654        device.destroy_image(imported.image);
21655        recorder.assert_valid();
21656    }
21657
21658    /// **A skinned object's recorded base vertex follows the parity of the frame
21659    /// it is drawn in**, and it carries the bit that makes a shader read it.
21660    ///
21661    /// The other half of the design: the table entry never moves, so what has to
21662    /// alternate is a field of the *instance* — and it has to alternate in the
21663    /// buffer the frame actually draws from, which is why this reads the
21664    /// instance ring's bytes rather than the host's mirror.
21665    ///
21666    /// Three claims, and the last two are what stop the first being vacuous. The
21667    /// base must be the one this frame's parity names; the record must carry
21668    /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
21669    /// without which the raster stages read the mesh entry and the field is
21670    /// decoration; and two consecutive frames must have named **different**
21671    /// halves, without which a renderer ignoring the parity entirely would pass.
21672    #[test]
21673    fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
21674        let (recorder, device, queue) = open();
21675        let device = device.as_ref();
21676        let mut fixture = SkinnedFixture::build(device, queue);
21677        let handle = fixture
21678            .renderer
21679            .add_skinned_instance(&SkinnedInstanceDesc {
21680                mesh: &fixture.skinned,
21681                material: DEMO_UNTINTED,
21682                transform: Mat4::IDENTITY,
21683            })
21684            .expect("a pool of thousands has room for one object");
21685
21686        let mut carried = Vec::new();
21687        for _ in 0..2 {
21688            fixture.begin(device);
21689            let parity = fixture.skinning.parity();
21690            let instance = instance_record(&recorder, &fixture.renderer, handle);
21691            assert_eq!(
21692                instance.base_vertex,
21693                fixture.skinned.region().base(parity),
21694                "the buffer this frame draws from must carry the base parity {parity} writes"
21695            );
21696            assert_eq!(
21697                instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21698                mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21699                "without the bit the raster stages resolve the mesh entry's base and this \
21700                 field is never read"
21701            );
21702            assert_eq!(
21703                instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
21704                "and the record still names the source mesh, which is what its bucket, its \
21705                 levels and its bounding box resolve through"
21706            );
21707            carried.push(instance.base_vertex);
21708        }
21709        assert_ne!(
21710            carried[0], carried[1],
21711            "two consecutive frames must have drawn different halves, or a renderer that \
21712             ignored the parity entirely would pass this"
21713        );
21714
21715        fixture.destroy(device);
21716        recorder.assert_valid();
21717    }
21718
21719    /// **A skinned object's record names the half the frame before it filled**,
21720    /// and it starts at rest.
21721    ///
21722    /// The other half of a skinned motion vector. The base above is where a
21723    /// fragment *is*; this is where it *was*, and without it the geometry stages
21724    /// put the previous transform through this frame's deformed vertex — so a
21725    /// limb that swung reports the motion of the body it hangs off. See
21726    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
21727    ///
21728    /// Four claims, and the first and last are what stop the middle two being a
21729    /// restatement of the parity:
21730    ///
21731    /// * the **first** frame of a fresh object writes the base it draws out of,
21732    ///   because the other half holds whatever its reservation came with and a
21733    ///   motion vector against undefined vertices is worse than no motion;
21734    /// * the frames after it write
21735    ///   [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
21736    ///   which must also **differ** from the base they draw out of — a renderer
21737    ///   that wrote the current base into both lanes would satisfy every "it is
21738    ///   a legal base" reading of this and leave every skinned instance at rest;
21739    /// * and moving the object onto a **different region** puts it back at rest
21740    ///   for one frame, because the halves it now names are two runs it has
21741    ///   never been drawn out of.
21742    #[test]
21743    fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
21744        let (recorder, device, queue) = open();
21745        let device = device.as_ref();
21746        let mut fixture = SkinnedFixture::build(device, queue);
21747        let handle = fixture
21748            .renderer
21749            .add_skinned_instance(&SkinnedInstanceDesc {
21750                mesh: &fixture.skinned,
21751                material: DEMO_UNTINTED,
21752                transform: Mat4::IDENTITY,
21753            })
21754            .expect("a pool of thousands has room for one object");
21755
21756        for frame in 1..=3u32 {
21757            fixture.begin(device);
21758            let parity = fixture.skinning.parity();
21759            let instance = instance_record(&recorder, &fixture.renderer, handle);
21760            assert_eq!(
21761                instance.base_vertex,
21762                fixture.skinned.region().base(parity),
21763                "frame {frame} must draw out of the half parity {parity} fills"
21764            );
21765            if frame == 1 {
21766                assert_eq!(
21767                    instance.previous_base_vertex, instance.base_vertex,
21768                    "a fresh object has no previous deformation, so its first frame owes rest \
21769                     rather than a half no dispatch has written"
21770                );
21771            } else {
21772                assert_eq!(
21773                    instance.previous_base_vertex,
21774                    fixture.skinned.region().previous_base(parity),
21775                    "frame {frame} must subtract against the half the frame before it filled"
21776                );
21777                assert_ne!(
21778                    instance.previous_base_vertex, instance.base_vertex,
21779                    "frame {frame} named one half twice, which is every skinned fragment at \
21780                     rest however far its surface moved"
21781                );
21782            }
21783        }
21784
21785        // The same object, moved onto a region it has never been drawn out of:
21786        // both halves are runs no dispatch of this object's has filled, so the
21787        // rule that put the first frame at rest applies again.
21788        let second = fixture
21789            .renderer
21790            .reserve_skinned(DEMO_CUBE)
21791            .expect("a default pool has room for two more halves of a cube");
21792        assert_ne!(
21793            second.region().base(0),
21794            fixture.skinned.region().base(0),
21795            "the second reservation is the same two runs as the first, so nothing below is \
21796             about a change of region at all"
21797        );
21798        fixture.renderer.set_skinned_instance(
21799            handle,
21800            &SkinnedInstanceDesc {
21801                mesh: &second,
21802                material: DEMO_UNTINTED,
21803                transform: Mat4::IDENTITY,
21804            },
21805        );
21806
21807        for frame in 1..=2u32 {
21808            fixture.begin(device);
21809            let parity = fixture.skinning.parity();
21810            let instance = instance_record(&recorder, &fixture.renderer, handle);
21811            assert_eq!(
21812                instance.base_vertex,
21813                second.region().base(parity),
21814                "frame {frame} after the move must draw out of the new region"
21815            );
21816            if frame == 1 {
21817                assert_eq!(
21818                    instance.previous_base_vertex, instance.base_vertex,
21819                    "the first frame on a new region owes rest, exactly as a fresh object does"
21820                );
21821            } else {
21822                assert_eq!(
21823                    instance.previous_base_vertex,
21824                    second.region().previous_base(parity),
21825                    "and the frame after it is subtracting against the new region's other half"
21826                );
21827            }
21828        }
21829
21830        fixture.renderer.release_skinned(second);
21831        fixture.destroy(device);
21832        recorder.assert_valid();
21833    }
21834
21835    /// **A skinned object that moves carries the transform it moved from**, and
21836    /// the frame after it is back at rest.
21837    ///
21838    /// The transform half of a skinned motion vector, and the half the
21839    /// per-frame re-point used to erase: it rewrote the record through
21840    /// [`InstancePool::set`], which fills the previous transform out of the
21841    /// record it overwrites — and that record already held this frame's
21842    /// transform, because
21843    /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
21844    /// it there. Every skinned instance then read `previous_transform ==
21845    /// transform` on every frame, so a character that walked contributed
21846    /// nothing to the motion target from the walk, only from its deformation.
21847    /// [`InstancePool::set_bases`] is what the re-point goes through instead.
21848    ///
21849    /// Both frames are the claim. Without the second, a re-point that wrote
21850    /// some *other* stale transform into the field would pass; and the second
21851    /// is the pool's own rest rule reaching a skinned object at all, which a
21852    /// re-point that kept enrolling the element every frame would suppress
21853    /// for ever.
21854    ///
21855    /// Read out of the ring buffer the frame draws from, on
21856    /// [`instance_record`]'s terms.
21857    #[test]
21858    fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
21859        let (recorder, device, queue) = open();
21860        let device = device.as_ref();
21861        let mut fixture = SkinnedFixture::build(device, queue);
21862        let handle = fixture
21863            .renderer
21864            .add_skinned_instance(&SkinnedInstanceDesc {
21865                mesh: &fixture.skinned,
21866                material: DEMO_UNTINTED,
21867                transform: Mat4::IDENTITY,
21868            })
21869            .expect("a pool of thousands has room for one object");
21870
21871        // Two frames standing still, so the history the move is measured
21872        // against is a settled record rather than a fresh one.
21873        fixture.begin(device);
21874        fixture.begin(device);
21875
21876        let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
21877        fixture.renderer.set_skinned_instance(
21878            handle,
21879            &SkinnedInstanceDesc {
21880                mesh: &fixture.skinned,
21881                material: DEMO_UNTINTED,
21882                transform: moved,
21883            },
21884        );
21885        fixture.begin(device);
21886        let instance = instance_record(&recorder, &fixture.renderer, handle);
21887        assert_eq!(
21888            instance.transform,
21889            moved.to_cols_array(),
21890            "the frame that moved the object must draw it where it arrived"
21891        );
21892        assert_eq!(
21893            instance.previous_transform,
21894            Mat4::IDENTITY.to_cols_array(),
21895            "and it must say where from — a previous transform equal to the current one is \
21896             the re-point having overwritten the move"
21897        );
21898
21899        fixture.begin(device);
21900        let settled = instance_record(&recorder, &fixture.renderer, handle);
21901        assert_eq!(
21902            settled.transform,
21903            moved.to_cols_array(),
21904            "nothing moved it again"
21905        );
21906        assert_eq!(
21907            settled.previous_transform, settled.transform,
21908            "so the frame after the move owes rest; a re-point that enrolled the element \
21909             every frame would keep it reporting the move for ever"
21910        );
21911
21912        fixture.destroy(device);
21913        recorder.assert_valid();
21914    }
21915
21916    /// **The graph barriers the skinning dispatch's write before every pass that
21917    /// pulls vertices**, and it does so because `add_skinned_passes` added the
21918    /// dispatch itself rather than trusting a caller to.
21919    ///
21920    /// Pass order alone would not settle it — a dispatch that ran first and was
21921    /// never barriered is the exact defect, and it produces a correct-looking
21922    /// frame on a desktop driver. So the transition out of
21923    /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
21924    /// it must sit after the dispatch, and it must sit at or before the first of
21925    /// the three passes that draw.
21926    #[test]
21927    fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
21928        let (recorder, device, queue) = open();
21929        let device = device.as_ref();
21930        let mut fixture = SkinnedFixture::build(device, queue);
21931        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
21932        fixture
21933            .renderer
21934            .add_skinned_instance(&SkinnedInstanceDesc {
21935                mesh: &fixture.skinned,
21936                material: DEMO_UNTINTED,
21937                transform: Mat4::IDENTITY,
21938            })
21939            .expect("room for one object");
21940        fixture.begin(device);
21941
21942        let imported = swapchain_image_at(device, TEST_EXTENT);
21943        let mut pool = crate::TransientPool::new();
21944        let mut graph = crate::RenderGraph::new(queue);
21945        let target = graph.import_image("target", imported);
21946        // The same node `Skinning::add_pass` imports — one handle is one node —
21947        // so the barriers below can be named rather than guessed at.
21948        let vertices = graph.import_buffer(
21949            "vertex-pool",
21950            ImportedBuffer {
21951                buffer: fixture.renderer.vertex_buffer(),
21952                initial: ResourceState::ShaderRead,
21953                final_state: ResourceState::ShaderRead,
21954            },
21955        );
21956        fixture.renderer.add_skinned_passes(
21957            &mut graph,
21958            &pool,
21959            target,
21960            TEST_EXTENT,
21961            &fixture.skinning,
21962        );
21963        let compiled = graph.compile(&pool).expect("a legal frame");
21964        let labels: Vec<&str> = compiled
21965            .passes()
21966            .iter()
21967            .map(crate::graph::CompiledPass::label)
21968            .collect();
21969
21970        let dispatch = labels
21971            .iter()
21972            .position(|label| *label == "skinning")
21973            .expect("add_skinned_passes adds the dispatch itself");
21974        let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
21975            .into_iter()
21976            .map(|wanted| {
21977                labels
21978                    .iter()
21979                    .position(|label| *label == wanted)
21980                    .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
21981            })
21982            .collect();
21983        for (label, at) in ["shadow", "depth-prepass", "forward"]
21984            .into_iter()
21985            .zip(&drawing)
21986        {
21987            assert!(
21988                dispatch < *at,
21989                "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
21990            );
21991        }
21992
21993        // Each drawing pass declares the read for itself, and this is asserted
21994        // per pass rather than left to the single barrier below. The graph
21995        // transitions the region once, before the first reader, and a later
21996        // pass that never declared the read finds it already in the state it
21997        // wanted — so dropping the declaration from `forward` alone changes no
21998        // barrier and moves no label, and every assertion in this test still
21999        // passes. What it does drop is that pass's *dependency* on the
22000        // dispatch, which is the only thing keeping the two in this order.
22001        for (label, at) in ["shadow", "depth-prepass", "forward"]
22002            .into_iter()
22003            .zip(&drawing)
22004        {
22005            assert!(
22006                compiled.passes()[*at].reads_buffer(vertices),
22007                "{label} draws skinned vertices and must declare that it reads them, or \
22008                 nothing but declaration order keeps it after the dispatch"
22009            );
22010        }
22011
22012        let released: Vec<usize> = compiled
22013            .passes()
22014            .iter()
22015            .enumerate()
22016            .filter(|(_, pass)| {
22017                pass.barriers().buffers.iter().any(|barrier| {
22018                    barrier.buffer == vertices
22019                        && barrier.from == ResourceState::ShaderReadWrite
22020                        && barrier.to == ResourceState::ShaderRead
22021                })
22022            })
22023            .map(|(at, _)| at)
22024            .collect();
22025        assert_eq!(
22026            released.len(),
22027            1,
22028            "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
22029        );
22030        let barrier = released[0];
22031        let first_draw = *drawing.iter().min().expect("three passes");
22032        assert!(
22033            dispatch < barrier && barrier <= first_draw,
22034            "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
22035             draws at {first_draw} — a draw that reads the region before the write is made \
22036             visible is the whole defect this seam exists to prevent"
22037        );
22038
22039        drop(compiled);
22040        fixture.destroy(device);
22041        pool.destroy(device);
22042        device.destroy_image_view(imported.view);
22043        device.destroy_image(imported.image);
22044        recorder.assert_valid();
22045    }
22046
22047    /// A frame with nothing to skin adds no dispatch and declares no read, and
22048    /// is the frame [`ForwardRenderer::add_passes`] would have built.
22049    #[test]
22050    fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
22051        let _blurs = ssao_blur_switch();
22052        let (recorder, device, queue) = open();
22053        let device = device.as_ref();
22054        let mut fixture = SkinnedFixture::build(device, queue);
22055        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22056
22057        let imported = swapchain_image_at(device, TEST_EXTENT);
22058        let pool = crate::TransientPool::new();
22059        let mut skinned_labels = Vec::new();
22060        for _ in 0..1 {
22061            fixture
22062                .renderer
22063                .begin_skinned_frame(
22064                    device,
22065                    &mut fixture.skinning,
22066                    &[],
22067                    &Camera::default(),
22068                    &DirectionalLight::default(),
22069                    TEST_EXTENT,
22070                )
22071                .expect("an empty plan is a legal one");
22072            let mut graph = crate::RenderGraph::new(queue);
22073            let target = graph.import_image("target", imported);
22074            fixture.renderer.add_skinned_passes(
22075                &mut graph,
22076                &pool,
22077                target,
22078                TEST_EXTENT,
22079                &fixture.skinning,
22080            );
22081            skinned_labels = graph
22082                .compile(&pool)
22083                .expect("a legal frame")
22084                .passes()
22085                .iter()
22086                .map(|pass| pass.label().to_string())
22087                .collect();
22088        }
22089        let plain = passes_in_a_frame(
22090            device,
22091            queue,
22092            &mut fixture.renderer,
22093            imported,
22094            &pool,
22095            TEST_EXTENT,
22096        );
22097        assert_eq!(
22098            skinned_labels, plain,
22099            "a frame with nothing to skin must cost the vertex pool no barrier at all"
22100        );
22101
22102        fixture.destroy(device);
22103        let mut pool = pool;
22104        pool.destroy(device);
22105        device.destroy_image_view(imported.view);
22106        device.destroy_image(imported.image);
22107        recorder.assert_valid();
22108    }
22109
22110    /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
22111    /// the commands land in.
22112    ///
22113    /// Returned rather than cleaned up here because the caller reads the
22114    /// recorder afterwards, and everything below must outlive that.
22115    struct Frame {
22116        imported: ImportedImage,
22117        pool: crate::TransientPool,
22118        commands: crcbl_hal::CommandBufferHandle,
22119    }
22120
22121    impl Frame {
22122        /// Releases the frame and the image it drew into, leaving the renderer
22123        /// alive for another one.
22124        fn release(self, device: &dyn Device) {
22125            device.destroy_command_buffer(self.commands);
22126            let mut pool = self.pool;
22127            pool.destroy(device);
22128            device.destroy_image_view(self.imported.view);
22129            device.destroy_image(self.imported.image);
22130        }
22131
22132        /// Releases the frame, the renderer and the image it drew into.
22133        fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
22134            self.release(device);
22135            renderer.destroy(device);
22136        }
22137    }
22138
22139    /// Everything one labelled pass recorded, and nothing any other pass did.
22140    ///
22141    /// **Every draw assertion below is scoped through this**, and the reason is
22142    /// topic 18: the frame now records the same indirect call the colour pass
22143    /// records once per shadow cascade as well, out of that cascade's own
22144    /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
22145    /// would see one per cascade as well as the colour pass's, and could not
22146    /// say which pass any of them belonged to — so "the forward pass records one
22147    /// call per bucket" would become a claim about a total, which a shadow pass
22148    /// recording the wrong thing could satisfy.
22149    /// The compute dispatches a default frame's **resolve** records, which
22150    /// every dispatch count in this module sees and none of them is about.
22151    ///
22152    /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
22153    /// shape classification are dispatches; its apply is a draw and does not
22154    /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
22155    /// what pins the resolve's pass list itself, so a tier that grew a dispatch
22156    /// fails there first and arrives here as a second red rather than as a
22157    /// silent skew.
22158    const RESOLVE_DISPATCHES: usize = 2;
22159
22160    fn commands_in_pass(
22161        recorder: &crcbl_hal::null::Recorder,
22162        label: &str,
22163    ) -> Vec<crcbl_hal::null::Command> {
22164        use crcbl_hal::null::Command;
22165
22166        let mut inside = false;
22167        let mut out = Vec::new();
22168        for command in recorder.commands() {
22169            if let Some((_, recorded)) = command.opens_pass() {
22170                inside = recorded == Some(label);
22171                continue;
22172            }
22173            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
22174                inside = false;
22175                continue;
22176            }
22177            if inside {
22178                out.push(command);
22179            }
22180        }
22181        assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
22182        out
22183    }
22184
22185    /// The extent every helper frame in this module is drawn at.
22186    ///
22187    /// Named since the bloom chain, whose length is a function of it — see
22188    /// [`crate::bloom`] — so a test comparing a pass count against
22189    /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
22190    /// at. Small on purpose: two chain levels is enough for every arm here, and
22191    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
22192    /// test that needs a frame large enough for six.
22193    ///
22194    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
22195    const TEST_EXTENT: (u32, u32) = (64, 48);
22196
22197    /// The effects a caller has to ask for, because the default stack leaves
22198    /// them out — see [`RenderEffects::DEFAULT_STACK`].
22199    ///
22200    /// Named rather than written out at each of the three sites that force them
22201    /// on, because the point of those sites is "every effect there is" and the
22202    /// bug they exist to catch is a new effect joining the set and one site
22203    /// still measuring the old one while calling it the whole stack. They are
22204    /// held out of the default for different reasons — [`crate::effects`] gives
22205    /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
22206    /// pending re-bless rather than a decision — and share only that a test
22207    /// wanting the widest frame must ask.
22208    ///
22209    /// **Named for what it is rather than for what most of it is**: the set held
22210    /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
22211    /// march is neither.
22212    const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
22213        .union(RenderEffects::ANTIALIASING)
22214        .union(RenderEffects::VOLUMETRIC_FOG)
22215        .union(RenderEffects::AUTO_EXPOSURE)
22216        .union(RenderEffects::CMAA2)
22217        .union(RenderEffects::CONTACT_SHADOWS);
22218
22219    /// Every effect this renderer draws is either in the default stack or in
22220    /// [`OUTSIDE_THE_DEFAULT`].
22221    ///
22222    /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
22223    /// call the result "every effect", which is only true while nothing else is
22224    /// held out. An effect added outside the default stack and not added
22225    /// here makes this red before it makes a pass-list assertion red — which is
22226    /// the useful order, since a pass list going red says a label moved and this
22227    /// says what actually happened.
22228    #[test]
22229    fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
22230        assert_eq!(
22231            RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
22232            RenderEffects::all(),
22233            "an effect outside the default stack that no test forces on is an effect \
22234             the every-effect frames below have never drawn"
22235        );
22236    }
22237
22238    /// The default sun, turned a little further round for each `lap`.
22239    ///
22240    /// Topic 45's static-caching rung means a second frame over
22241    /// a scene nothing moved in records **no shadow pass at all** — see
22242    /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
22243    /// a difference that every A/B drawing two frames from one renderer would
22244    /// otherwise be measuring on top of the one it is about. Turning the sun is
22245    /// the smallest input the atlas depends on: the cascades are refitted, so
22246    /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
22247    /// with it.
22248    ///
22249    /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
22250    /// frame is the ordinary one keeps the frame every other test draws.
22251    fn moving_sun(lap: u32) -> DirectionalLight {
22252        let sun = DirectionalLight::default();
22253        // A degree a lap, about the axis the default direction is not parallel
22254        // to. Small enough that every cascade still sees the scene, and large
22255        // enough that the snapped cascade origin actually moves.
22256        let turn = Mat4::from_rotation_y(
22257            f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
22258                / 180.0,
22259        );
22260        DirectionalLight {
22261            direction: turn.transform_vector3(sun.direction).normalize(),
22262            ..sun
22263        }
22264    }
22265
22266    /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
22267    /// not the one the lap before it left in the image.
22268    fn frame_moving_the_sun(
22269        device: &dyn Device,
22270        renderer: &mut ForwardRenderer,
22271        queue: QueueHandle,
22272        lap: u32,
22273    ) -> Frame {
22274        frame_lit_by(device, renderer, queue, &moving_sun(lap))
22275    }
22276
22277    fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
22278        frame_lit_by(device, renderer, queue, &DirectionalLight::default())
22279    }
22280
22281    fn frame_lit_by(
22282        device: &dyn Device,
22283        renderer: &mut ForwardRenderer,
22284        queue: QueueHandle,
22285        sun: &DirectionalLight,
22286    ) -> Frame {
22287        frame_seen_from(device, renderer, queue, &Camera::default(), sun)
22288    }
22289
22290    fn frame_seen_from(
22291        device: &dyn Device,
22292        renderer: &mut ForwardRenderer,
22293        queue: QueueHandle,
22294        camera: &Camera,
22295        sun: &DirectionalLight,
22296    ) -> Frame {
22297        renderer
22298            .begin_frame(device, camera, sun, TEST_EXTENT)
22299            .expect("write");
22300        let imported = swapchain_image(device);
22301        let mut graph = crate::RenderGraph::new(queue);
22302        let target = graph.import_image("target", imported);
22303        let mut pool = crate::TransientPool::new();
22304        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
22305        let compiled = graph.compile(&pool).expect("a legal frame");
22306        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22307            label: Some("forward frame"),
22308            queue,
22309        });
22310        compiled
22311            .execute(device, &mut pool, encoder.as_mut(), None)
22312            .expect("the graph executed");
22313        let commands = encoder.finish().expect("recording succeeded");
22314        Frame {
22315            imported,
22316            pool,
22317            commands,
22318        }
22319    }
22320
22321    /// A stand-in for the acquired swapchain image the frame normally ends in,
22322    /// at [`TEST_EXTENT`].
22323    fn swapchain_image(device: &dyn Device) -> ImportedImage {
22324        swapchain_image_at(device, TEST_EXTENT)
22325    }
22326
22327    /// The same, at an extent of the caller's choosing.
22328    ///
22329    /// A frame's attachments must all be one size — the graph refuses a pass
22330    /// whose colour target and depth disagree — so a test drawing at anything
22331    /// but [`TEST_EXTENT`] has to import a target of that size too.
22332    pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
22333        let format = Format::Rgba8UnormSrgb;
22334        let image = device
22335            .create_image(&crcbl_hal::ImageDesc {
22336                label: Some("fake swapchain image"),
22337                image_type: crcbl_hal::ImageType::D2,
22338                extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
22339                format,
22340                mip_levels: 1,
22341                samples: 1,
22342                usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
22343            })
22344            .expect("an image");
22345        let view = device
22346            .create_image_view(&crcbl_hal::ImageViewDesc {
22347                label: Some("fake swapchain view"),
22348                image,
22349                view_type: crcbl_hal::ImageViewType::D2,
22350                format,
22351                range: crcbl_hal::ImageSubresourceRange::all(format),
22352            })
22353            .expect("a view");
22354        ForwardRenderer::present_target(image, view, format, extent)
22355    }
22356
22357    /// The spin is a rotation: no scale, no shear, so the cube neither grows
22358    /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
22359    /// picture of one cube.
22360    ///
22361    /// That is also what keeps those goldens insensitive to `mesh.slang`'s
22362    /// `normal_basis`. A matrix with orthonormal rows and a positive
22363    /// determinant is its own cofactor matrix, to within a rounding step, so
22364    /// the vertex stage writes the normals it wrote when it multiplied by the
22365    /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
22366    /// longer requires a caller to be rigid at all.
22367    #[test]
22368    fn the_spin_matrix_stays_rigid() {
22369        for seconds in [0.0f32, 0.5, 3.25, 100.0] {
22370            let model = ForwardRenderer::spin(seconds);
22371            let basis = glam::Mat3::from_mat4(model);
22372            let product = basis * basis.transpose();
22373            for (row, expected) in [
22374                (product.x_axis, Vec3::X),
22375                (product.y_axis, Vec3::Y),
22376                (product.z_axis, Vec3::Z),
22377            ] {
22378                assert!(
22379                    (row - expected).length() < 1e-5,
22380                    "the spin at {seconds}s is not orthonormal: {product:?}"
22381                );
22382            }
22383            assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
22384        }
22385        // And it actually moves.
22386        assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
22387    }
22388
22389    /// The swapchain import says what a swapchain image actually needs, which is
22390    /// the knowledge the hand-written barriers used to carry.
22391    #[test]
22392    fn the_present_target_starts_undefined_and_ends_presentable() {
22393        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
22394        let image = pool.insert(0).cast();
22395        let view = pool.insert(0).cast();
22396        let imported =
22397            ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
22398        assert_eq!(imported.initial, ResourceState::Undefined);
22399        assert_eq!(imported.final_state, ResourceState::Present);
22400        assert_eq!(imported.extent, (1280, 720));
22401    }
22402
22403    /// The scene target is `Rgba16Float`, and the depth target is the
22404    /// reversed-Z format. Both are locked decisions and both are cheap to pin.
22405    #[test]
22406    fn the_scene_targets_are_hdr_and_reversed_z() {
22407        let color = crate::targets::scene_color((64, 48));
22408        assert_eq!(color.format, Format::Rgba16Float);
22409        assert!(color.format.is_hdr_capable());
22410        assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
22411
22412        let depth = crate::targets::scene_depth((64, 48));
22413        assert_eq!(depth.format, Format::D32Float);
22414        assert_eq!(
22415            DepthStencilState::default().depth_compare,
22416            crcbl_hal::CompareOp::Greater
22417        );
22418    }
22419
22420    /// A sun ten degrees or so above the horizon, and one further round: two
22421    /// atmospheres whose LUTs are nowhere near each other, so a comparison
22422    /// between them cannot pass by the two skies being alike.
22423    ///
22424    /// Spelled as directions rather than as angles for
22425    /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
22426    /// own — and normalised by `Atmosphere::parameters` on the way in.
22427    const MOVED_SUN: Atmosphere = Atmosphere {
22428        sun_direction: Vec3::new(1.0, 0.2, 0.0),
22429        ..Atmosphere::NOON
22430    };
22431
22432    /// [`MOVED_SUN`] again, further round and lower.
22433    const MOVED_AGAIN: Atmosphere = Atmosphere {
22434        sun_direction: Vec3::new(1.0, 0.05, 0.5),
22435        ..Atmosphere::NOON
22436    };
22437
22438    /// Frames the striped march takes to cross the LUT.
22439    const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
22440
22441    /// The bytes the most recent sky-view LUT upload put on the device.
22442    ///
22443    /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
22444    /// that has an atmosphere, into the slot that frame is using — so the last
22445    /// write to any of the ring's buffers is the LUT the frame just recorded
22446    /// would draw. That is the only place the presented LUT is observable: the
22447    /// renderer's own copy is what a test could assert about instead, and it
22448    /// would then be asserting about the thing rather than about what reached
22449    /// the device.
22450    fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
22451        recorder
22452            .events()
22453            .into_iter()
22454            .rev()
22455            .find_map(|event| match event {
22456                crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
22457                    recorder.buffer_bytes(buffer)
22458                }
22459                _ => None,
22460            })
22461            .expect("a frame with an atmosphere uploads a sky-view LUT")
22462    }
22463
22464    /// A renderer with an atmosphere set and its first LUT marched, and the
22465    /// buffers that LUT reaches the device through.
22466    ///
22467    /// The three tests below all start here: the first march is synchronous, so
22468    /// one frame is what it takes to have a sky to be stale about.
22469    fn with_marched_atmosphere(
22470        device: &dyn Device,
22471        queue: QueueHandle,
22472        atmosphere: Atmosphere,
22473    ) -> (ForwardRenderer, Vec<BufferHandle>) {
22474        let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
22475            .expect("the null backend builds a renderer");
22476        let luts = renderer.primary.sky_pass.luts().to_vec();
22477        renderer.set_atmosphere(Some(atmosphere));
22478        atmosphere_frame(&mut renderer, device);
22479        (renderer, luts)
22480    }
22481
22482    /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
22483    /// is what writes the blocks and steps the march.
22484    fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
22485        renderer
22486            .begin_frame(
22487                device,
22488                &Camera::default(),
22489                &DirectionalLight::default(),
22490                (64, 48),
22491            )
22492            .expect("the frame's blocks are written");
22493    }
22494
22495    /// A sun that moved is marched a stripe per frame, and every frame until it
22496    /// is finished still uploads the LUT of the sun before it.
22497    ///
22498    /// **The amortisation, from the device's side.** Before this, one
22499    /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
22500    /// tens of milliseconds of CPU in every frame. The claim now is three
22501    /// things at once, and only the middle one is about performance: the march
22502    /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
22503    /// device meanwhile are the *previous* sun's rather than a half-marched
22504    /// sky, and the new sun's LUT arrives whole on the frame the march ends.
22505    ///
22506    /// **And the aerial-perspective LUT keeps the same pace**: it rides the
22507    /// same stripes, so it too uploads the previous sun's air on every frame
22508    /// of the march and the new sun's on the frame that ends it — the lag
22509    /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
22510    /// reach the device a sun apart.
22511    #[test]
22512    fn a_moving_sun_is_marched_a_stripe_per_frame() {
22513        let (recorder, device, queue) = open();
22514        let (mut renderer, luts) =
22515            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22516        let aerials = renderer.primary.sky_pass.aerials().to_vec();
22517
22518        let before_view = SkyView::build(&Atmosphere::NOON.parameters());
22519        let after_view = SkyView::build(&MOVED_SUN.parameters());
22520        let before = before_view.rows();
22521        let after = after_view.rows();
22522        let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
22523        assert_ne!(
22524            before, after,
22525            "the two suns march to the same LUT, so nothing below distinguishes them"
22526        );
22527        assert_ne!(
22528            air_before, air_after,
22529            "the two suns march to the same air, so nothing below distinguishes them"
22530        );
22531        assert!(
22532            renderer.sky_view_build.is_none(),
22533            "the first march is synchronous, so no build is left in flight"
22534        );
22535        assert_eq!(
22536            presented_lut(&recorder, &luts),
22537            before,
22538            "the frame after `set_atmosphere` did not upload that sun's LUT"
22539        );
22540        assert_eq!(
22541            presented_lut(&recorder, &aerials),
22542            air_before,
22543            "the frame after `set_atmosphere` did not upload that sun's air"
22544        );
22545
22546        renderer.set_atmosphere(Some(MOVED_SUN));
22547        for step in 1..MARCH_FRAMES {
22548            atmosphere_frame(&mut renderer, device.as_ref());
22549            assert_eq!(
22550                renderer
22551                    .sky_view_build
22552                    .as_ref()
22553                    .map(SkyViewBuild::rows_done),
22554                Some(step * SKY_VIEW_BUILD_ROWS),
22555                "frame {step} of the march is not a stripe further along than frame {} was",
22556                step - 1
22557            );
22558            assert_eq!(
22559                presented_lut(&recorder, &luts),
22560                before,
22561                "frame {step} of the march uploaded something other than the sky it is still \
22562                 drawing"
22563            );
22564            assert_eq!(
22565                presented_lut(&recorder, &aerials),
22566                air_before,
22567                "frame {step} of the march uploaded air other than the sky it is still drawing's"
22568            );
22569        }
22570
22571        atmosphere_frame(&mut renderer, device.as_ref());
22572        assert!(
22573            renderer.sky_view_build.is_none(),
22574            "the march did not finish in the frames its own stripe says it takes"
22575        );
22576        assert_eq!(
22577            presented_lut(&recorder, &luts),
22578            after,
22579            "the frame that finished the march did not upload the new sun's LUT"
22580        );
22581        assert_eq!(
22582            presented_lut(&recorder, &aerials),
22583            air_after,
22584            "the frame that finished the march did not upload the new sun's air"
22585        );
22586    }
22587
22588    /// An atmosphere adds the composite for its air whether or not the fog
22589    /// effect is on, and the block tells the composite which halves to read.
22590    ///
22591    /// **The seam between the two volumes, on the renderer's side.** Three
22592    /// frames of one renderer: no atmosphere and the default stack, which has
22593    /// no fog effect in it — no composite at all, the frame drawn before the
22594    /// air existed; an atmosphere and the same stack — the composite and
22595    /// nothing of the column, and a block saying so; and an atmosphere with
22596    /// the fog effect forced on — all three passes, and a block saying both.
22597    /// The counters are held to the frame on the second: the composite is a
22598    /// full-screen triangle, and a frame that drew it and did not count it
22599    /// makes the debug panel's row disagree with the frame by one.
22600    #[test]
22601    fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
22602        let _blurs = ssao_blur_switch();
22603        let (recorder, device, queue) = open();
22604        let device = device.as_ref();
22605        let mut renderer =
22606            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
22607        let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
22608            .map(|frame| renderer.primary.volumetric.buffers(frame).params)
22609            .collect();
22610        let imported = swapchain_image(device);
22611        let mut pool = crate::TransientPool::new();
22612        let block = |recorder: &Recorder| {
22613            let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
22614                presented_lut(recorder, &blocks)
22615                    .try_into()
22616                    .expect("the block is its own size");
22617            crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
22618        };
22619        let column = ["volumetric-scatter", "volumetric-integrate"];
22620
22621        let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22622        let before = renderer.counters();
22623        assert!(
22624            !bare.iter().any(|pass| pass.starts_with("volumetric")),
22625            "a frame with neither fog nor an atmosphere records {bare:?}"
22626        );
22627        let off = block(&recorder);
22628        assert_eq!(
22629            off.aerial_params,
22630            [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
22631            "a frame with no atmosphere writes something into the aerial row"
22632        );
22633
22634        renderer.set_atmosphere(Some(Atmosphere::NOON));
22635        let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22636        assert!(
22637            air.iter().any(|pass| pass == "volumetric-composite")
22638                && !air.iter().any(|pass| column.contains(&pass.as_str())),
22639            "an atmosphere with the fog effect off records {air:?}, where it should composite its \
22640             air and run nothing of the column"
22641        );
22642        let after = renderer.counters();
22643        assert_eq!(
22644            after.draws - before.draws,
22645            (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
22646            "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
22647        );
22648        let aerial_only = block(&recorder);
22649        let sun = Atmosphere::NOON.parameters().sun_direction;
22650        assert_eq!(
22651            aerial_only.aerial_params,
22652            [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
22653            "the aerial row does not carry the atmosphere's sun and its switch"
22654        );
22655        assert_eq!(
22656            aerial_only.fog_params[3],
22657            crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
22658            "the block tells the composite to read a column no pass filled"
22659        );
22660
22661        renderer.set_effect_request(EffectRequest {
22662            programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
22663            ..EffectRequest::default()
22664        });
22665        let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22666        assert!(
22667            column
22668                .iter()
22669                .chain(&["volumetric-composite"])
22670                .all(|name| both.iter().any(|pass| pass == name)),
22671            "an atmosphere with the fog effect on records {both:?}"
22672        );
22673        assert_eq!(
22674            block(&recorder).fog_params[3],
22675            crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
22676            "the block tells the composite to skip a column the frame filled"
22677        );
22678
22679        renderer.destroy(device);
22680        pool.destroy(device);
22681        device.destroy_image_view(imported.view);
22682        device.destroy_image(imported.image);
22683        recorder.assert_valid();
22684    }
22685
22686    /// A sun that moves while a march is in flight restarts it from row zero.
22687    ///
22688    /// **The decision `refresh_sky_view` writes down**, and the reason a sun
22689    /// that moves every frame shows a frozen sky rather than a stuttering one:
22690    /// finishing a march for a sun that has already moved would swap in a LUT
22691    /// that is wrong on arrival. What is observable is the progress counter —
22692    /// a build that kept its rows would be two stripes along here rather than
22693    /// one — and the sun the build in flight names.
22694    #[test]
22695    fn a_sun_that_moves_mid_march_restarts_it() {
22696        let (recorder, device, queue) = open();
22697        let (mut renderer, luts) =
22698            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22699        let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
22700
22701        renderer.set_atmosphere(Some(MOVED_SUN));
22702        atmosphere_frame(&mut renderer, device.as_ref());
22703        atmosphere_frame(&mut renderer, device.as_ref());
22704        assert_eq!(
22705            renderer
22706                .sky_view_build
22707                .as_ref()
22708                .map(SkyViewBuild::rows_done),
22709            Some(2 * SKY_VIEW_BUILD_ROWS),
22710            "two frames of marching did not leave two stripes marched"
22711        );
22712
22713        renderer.set_atmosphere(Some(MOVED_AGAIN));
22714        atmosphere_frame(&mut renderer, device.as_ref());
22715        assert_eq!(
22716            renderer
22717                .sky_view_build
22718                .as_ref()
22719                .map(SkyViewBuild::rows_done),
22720            Some(SKY_VIEW_BUILD_ROWS),
22721            "the march kept the rows it had marched for a sun that has since moved"
22722        );
22723        assert_eq!(
22724            renderer
22725                .sky_view_build
22726                .as_ref()
22727                .map(SkyViewBuild::atmosphere),
22728            Some(MOVED_AGAIN.parameters()),
22729            "the build in flight is marching a sun the caller has moved away from"
22730        );
22731        assert_eq!(
22732            presented_lut(&recorder, &luts),
22733            before,
22734            "a restart uploaded something other than the last LUT that finished"
22735        );
22736    }
22737
22738    /// A frame whose sun has not moved marches nothing and re-takes neither
22739    /// projection.
22740    ///
22741    /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
22742    /// be taken from the LUT in every `begin_frame`, which is host work a still
22743    /// sun has no reason to pay. Both are now taken once, where the march
22744    /// finishes — so a sentinel written over the cached gradient survives a
22745    /// frame if and only if that frame took neither the march nor the
22746    /// projection again, and the same sentinel's bytes turn up in what the
22747    /// frame wrote, which is what says the cache is the thing being read.
22748    #[test]
22749    fn a_still_sun_marches_nothing_and_reprojects_nothing() {
22750        let (recorder, device, queue) = open();
22751        let (mut renderer, _luts) =
22752            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22753
22754        let sentinel = crcbl_shaders::sky::SkyGradient {
22755            zenith: [0.125, 0.25, 0.375],
22756            horizon: [0.5, 0.625, 0.75],
22757            ground: [0.875, 1.125, 1.375],
22758        };
22759        let presented = renderer
22760            .sky_view
22761            .as_mut()
22762            .expect("the first frame marched a LUT");
22763        assert_ne!(
22764            presented.gradient, sentinel,
22765            "the sentinel is what the real projection already returns, so it proves nothing"
22766        );
22767        presented.gradient = sentinel;
22768
22769        let before = recorder.events().len();
22770        atmosphere_frame(&mut renderer, device.as_ref());
22771        assert_eq!(
22772            renderer
22773                .sky_view
22774                .as_ref()
22775                .map(|presented| presented.gradient),
22776            Some(sentinel),
22777            "a frame under a sun that has not moved re-took the projections"
22778        );
22779        assert!(
22780            renderer.sky_view_build.is_none(),
22781            "a frame under a sun that has not moved started a march"
22782        );
22783
22784        let wanted: Vec<u8> = sentinel
22785            .rows()
22786            .iter()
22787            .flatten()
22788            .flat_map(|value| value.to_le_bytes())
22789            .collect();
22790        let used = recorder
22791            .events()
22792            .into_iter()
22793            .skip(before)
22794            .filter_map(|event| match event {
22795                crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
22796                    recorder.buffer_bytes(buffer)
22797                }
22798                _ => None,
22799            })
22800            .any(|bytes| {
22801                bytes
22802                    .windows(wanted.len())
22803                    .any(|window| window == wanted.as_slice())
22804            });
22805        assert!(
22806            used,
22807            "the cached gradient reached no block this frame wrote, so the frame is not reading \
22808             the cache at all"
22809        );
22810    }
22811
22812    /// **The frame block's ambient rows carry the marched LUT's own L1
22813    /// projection**, and not the three-band fit's.
22814    ///
22815    /// `begin_frame` writes [`PresentedSky::irradiance`] into
22816    /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
22817    /// test nothing read them back. The only reader of those rows is arithmetic
22818    /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
22819    /// surface under an atmosphere — `crcbl`'s
22820    /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
22821    /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
22822    /// instead, the three-band fit's projection rather than the LUT's, was a
22823    /// swap `docs/backlog.md` recorded passing every suite in the tree on
22824    /// 2026-09-06.
22825    ///
22826    /// **Both halves are needed and the second is the sabotage's.** The rows
22827    /// equalling the LUT's projection is the wiring; the rows *differing* from
22828    /// the fit's is what makes the equality a claim about which projection
22829    /// arrived rather than about two numbers that happen to agree. The
22830    /// `assert_ne` above them is the anti-vacuity: a sun for which the two
22831    /// projections coincide would make this test pass under the swap.
22832    ///
22833    /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
22834    #[test]
22835    fn an_atmosphere_writes_the_luts_own_ambient_term() {
22836        /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
22837        /// puts in the block.
22838        fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
22839            [probe.sh_r, probe.sh_g, probe.sh_b]
22840                .iter()
22841                .flatten()
22842                .flat_map(|value| value.to_le_bytes())
22843                .collect()
22844        }
22845
22846        let (recorder, device, queue) = open();
22847        let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
22848
22849        let view = SkyView::build(&MOVED_SUN.parameters());
22850        let marched = rows(&view.irradiance());
22851        let fitted = rows(&view.gradient_fit().irradiance());
22852        assert_ne!(
22853            marched, fitted,
22854            "this sun's LUT and its three-band fit project to the same rows, so a block \
22855             carrying either would satisfy the check below and the swap it exists for would \
22856             pass"
22857        );
22858
22859        let block = recorder
22860            .buffer_bytes(renderer.primary.uniforms[renderer.frame])
22861            .expect("a frame with an atmosphere writes its uniform block");
22862        let at = mesh::SKY_SH_R_OFFSET;
22863        assert_eq!(
22864            &block[at..at + marched.len()],
22865            marched.as_slice(),
22866            "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
22867             marched, so the ambient term the fragment stage evaluates comes from somewhere \
22868             else"
22869        );
22870        assert_ne!(
22871            &block[at..at + fitted.len()],
22872            fitted.as_slice(),
22873            "the frame block's sky rows are the gradient fit's projection — the LUT was \
22874             marched and then thrown away for the three-band approximation of it"
22875        );
22876
22877        renderer.destroy(device.as_ref());
22878    }
22879}