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::{Aabb, Frustum};
167use crate::cull_stats::CullStatsRing;
168use crate::debug_draw::DebugDraw;
169use crate::draw_gen::{DrawGen, DrawGenDesc, DrawGenPipelines, 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, GrassLayouts, GrassPipelines, 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::partial::Partial;
192use crate::pipeline_batch::{self, Pipeline};
193use crate::probe::{ProbeTable, ProbeTableDesc};
194use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
195use crate::rsm;
196use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
197use crate::shadow::{self, Cascades};
198use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
199use crate::sky_pass::SkyPass;
200use crate::ssao::{Ssao, cached_group};
201use crate::ssr::{Ssr, SsrEnvironment, SsrImages, SsrLayouts, SsrPipelines};
202use crate::stack::CameraStack;
203use crate::texture::{PendingUpload, UploadBatch, UploadedTexture, upload_texture_mip_layers};
204use crate::transient::TransientPool;
205use crate::upscale::Upscale;
206use crate::volumetric::{
207    FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricLayouts, VolumetricPipelines,
208    VolumetricReads,
209};
210use crate::water::{
211    Water, WaterBodies, WaterFrame, WaterImages, WaterInputs, WaterLayouts, WaterPipelines,
212};
213use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};
214
215mod bucket_draws;
216mod frame_prepare;
217mod pages;
218mod shadow_inputs;
219mod skin_cull;
220mod view;
221
222use pages::{PageBindings, RetiredPage, upload_page};
223
224pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};
225
226use bucket_draws::{BucketDraws, EmitTail, RegionStep};
227
228use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput, ViewPipelines};
229pub use view::{
230    FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
231};
232
233/// The clear behind the mesh, in **linear** light.
234///
235/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
236/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
237/// display-referred colour here would come out visibly paler, which is the
238/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
239pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
240
241/// How many frames of uniform buffers to keep. Matches the frame loop's
242/// frames-in-flight.
243pub const FRAMES_IN_FLIGHT: usize = 2;
244
245// The UI pass this renderer draws its HUD through keeps a ring of its own,
246// built at `crcbl_frame`'s default depth; held equal here, where both are in
247// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
248const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);
249
250/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
251/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
252///
253/// The floor exists so that the control cannot be driven somewhere it cannot be
254/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
255/// unclamped input has two dead ends: far enough down and every pixel rounds to
256/// the same black byte, far enough up and every pixel saturates to white — and
257/// in both the picture stops carrying the information a user would need to see
258/// which way to go. Five stops is well inside either: it is a sixteenth of the
259/// scene's brightness, dark but plainly still a picture, and it is the range a
260/// camera's exposure-compensation dial covers.
261pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
262
263/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
264/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
265/// [`EXPOSURE_MIN`]'s reason.
266pub const EXPOSURE_MAX: f32 = 32.0;
267
268/// The default has to be reachable from both ends of the range, or a control
269/// that steps by a ratio starts somewhere it can only leave in one direction.
270const _: () = assert!(
271    EXPOSURE_MIN > 0.0
272        && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
273        && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
274);
275
276/// The format the frame's depth buffer is created with, taken from the
277/// description that creates it rather than written down a second time.
278///
279/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
280/// depth attachment before there is a frame to ask. The extent is irrelevant to
281/// a format, which is why any is passed.
282pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
283
284/// The format the frame's HDR scene target is created with, taken from the
285/// description that creates it rather than written down a second time.
286///
287/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
288/// chain of HDR passes ended with — every one of them is a
289/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
290/// which is why any is passed.
291pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
292
293/// The format §3.2's base-colour page is created with.
294///
295/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
296/// for it is at the `upload_texture_mip_layers` call inside
297/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
298/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
299/// the image was created with, and a barrier naming a format the image is not in
300/// picks the wrong aspects.
301const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
302
303/// The format topic 43 §2's **normal** page is
304/// created with.
305///
306/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
307/// Topic 44's rung 2 argues it: a base-colour texel is a
308/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
309/// the sampler decode it; a normal texel is a *number* — three components of a
310/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
311/// transfer curve is wrong by a gamma. What that looks like is not an error but
312/// a surface that leans further off vertical than the author drew, which is why
313/// the mistake survives review everywhere it is made.
314///
315/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
316/// worth having because the four constants sit a few lines apart and the wrong
317/// one compiles.
318const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
319
320/// The format topic 43 §2's **metallic-roughness-
321/// occlusion** page is created with.
322///
323/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
324/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
325/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
326/// linear factors — and a surface shaded through an sRGB decode of them is
327/// smoother and shinier than the author drew, which is a failure that survives
328/// review because it looks like a choice.
329///
330/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
331/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
332/// one of them wanted a different format should be an edit here rather than a
333/// search for which callers of a shared name meant which page.
334const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
335
336/// The format topic 43 §2's **emissive** page is
337/// created with.
338///
339/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
340/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
341/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
342/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
343/// what puts the two in one space before they are multiplied.
344///
345/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
346/// and `the_page_formats_split_colour_from_number` is the guard that the four
347/// do not drift into one another.
348const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
349
350/// What the renderer needs of a [`PageKind`] to create and fill its image.
351///
352/// Written here rather than in [`crate::scene`] because the two answers are the
353/// device's: the format is the one [`base_color_page_import`] and
354/// [`normal_page_import`] have to declare, and the filter is the one
355/// [`crate::mip`] builds the chain with. A kind added by
356/// topic 43 §2's rung 3 is a new arm in each.
357///
358/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
359/// [`normal_page_import`]: ForwardRenderer::normal_page_import
360impl PageKind {
361    /// The format this kind's image is created with.
362    ///
363    /// The sRGB in one and its absence in the other is the whole colour-space
364    /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
365    /// which is where each is argued.
366    const fn format(self) -> Format {
367        match self {
368            Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
369            Self::Normal => NORMAL_PAGE_FORMAT,
370            Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
371            Self::Emissive => EMISSIVE_PAGE_FORMAT,
372        }
373    }
374
375    /// Every mip level below `level0`, built on the host with this kind's own
376    /// filter.
377    ///
378    /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
379    /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
380    /// weights by alpha. A normal map mipped through the colour filter leans
381    /// further off vertical at every level than the map it was built from, and
382    /// nothing in a frame reports it.
383    fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
384        match self {
385            Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
386            Self::Normal => crate::mip::normal_chain(level0, extent),
387            Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
388        }
389    }
390
391    /// The device label this kind's image is created under.
392    const fn upload_label(self) -> &'static str {
393        match self {
394            Self::BaseColor => "material base colour",
395            Self::Normal => "material normals",
396            Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
397            Self::Emissive => "material emissive",
398        }
399    }
400}
401
402/// The one texel a page **nothing names** is created with.
403///
404/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
405/// every bind group of the mesh layout has to fill both page bindings whether or
406/// not the description carried either page — so a [`PageKind`] with no layers
407/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
408/// nobody samples. That is the whole of what row (d) bought back:
409/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
410/// every scene in the tree that has no normal map used to carry a full neutral
411/// layer and a third again for its chain.
412///
413/// **Magenta, and it is never sampled for its value.** A material naming no page
414/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
415/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
416/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
417/// at all. So nothing should ever read this — and the value is chosen so that if
418/// something does, the frame says so in a colour no lit surface in this engine
419/// produces. White would blend into every untextured surface and black would
420/// read as a shadow; both are failures a golden could pass.
421const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
422
423/// The format the motion-vector target is created with: two channels of half
424/// float, topic 43 §9's third colour attachment.
425///
426/// **Named here rather than in [`crate::targets::motion`]**, on
427/// [`crate::graph`]'s other format-owning descriptions' terms: the description
428/// and
429/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
430/// pipeline is the one that owns the answer.
431///
432/// # The convention the target holds, so a consumer never has to guess it
433///
434/// **Current minus previous, in texture coordinates, `+y` down.** A pass
435/// holding the previous frame reads its history at `uv - motion`, and a surface
436/// travelling right and down the screen has both components positive.
437/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
438/// is the same sentence on the host side, because the first consumer will read
439/// one of the two and not both.
440///
441/// # Two channels and half float
442///
443/// A motion vector is a screen-space offset and has no third component. Half
444/// float rather than a normalised integer because the value is signed and
445/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
446/// — and because the interesting magnitudes are small: a surface moving a
447/// tenth of a pixel is the case a temporal filter is most sensitive to, and
448/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
449/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
450/// names motion vectors as the use for.
451pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
452
453/// Which picture the colour pass draws instead of the shaded one.
454///
455/// The engine's debug views, as one value rather than as independent booleans,
456/// because they are not independent: every one of them rides in a single lane of
457/// the frame's uniform block and the shaders test the thresholds outermost
458/// first, so a renderer with two of them set draws exactly one.
459/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
460/// answers with — so a menu row, a debug panel and the picture cannot disagree
461/// about which view is on.
462///
463/// **The declaration order is not the precedence** — each view was appended as
464/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
465/// decided. The sentinels in
466/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
467/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
468/// first.
469#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
470pub enum DebugView {
471    /// The lit picture. What every frame draws unless a caller asked otherwise.
472    #[default]
473    Shaded,
474    /// Each cluster shaded by the projected screen-space error the LOD
475    /// selection judged it on — [`ForwardRenderer::set_heatmap`].
476    Heatmap,
477    /// Each cluster tinted by the DAG level it was decimated to —
478    /// [`ForwardRenderer::set_lod_view`].
479    LodTint,
480    /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
481    Normals,
482    /// The ambient-occlusion channel alone, as grey —
483    /// [`ForwardRenderer::set_occlusion_view`].
484    AmbientOcclusion,
485    /// The motion vector each fragment wrote, stretched and centred on grey —
486    /// [`ForwardRenderer::set_motion_view`].
487    Motion,
488    /// The bent direction the occlusion channel carries beside its scalar, as
489    /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
490    /// every other view.**
491    BentNormal,
492    /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
493    /// atlas itself, letterboxed over the finished frame with a border round
494    /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
495    ///
496    /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
497    /// therefore the one whose lane is the off sentinel: the colour pass draws
498    /// the shaded picture exactly as it always did and `crate::atlas_view`
499    /// replaces it afterwards. That module's header is where the placement is
500    /// argued.
501    ///
502    /// It resolves **below every view above and above [`Self::Cascades`]** — see
503    /// [`ForwardRenderer::debug_view`].
504    ShadowAtlas,
505    /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
506    /// was sampled from, with the cross-fade band drawn as the blend of the two
507    /// — [`ForwardRenderer::set_cascade_view`].
508    ///
509    /// **Loses to every other view**, and it is the only one that does. The views
510    /// above draw something *instead of* the shaded picture; this one draws the
511    /// shaded picture and multiplies it, so there is nothing left for it to
512    /// modulate as soon as one of them is on. See
513    /// [`ForwardRenderer::debug_view`].
514    Cascades,
515}
516
517impl DebugView {
518    /// What a panel row or a summary line calls it.
519    #[must_use]
520    pub const fn label(self) -> &'static str {
521        match self {
522            Self::Shaded => "shaded",
523            Self::Heatmap => "heatmap",
524            Self::LodTint => "lod tint",
525            Self::Normals => "normals",
526            Self::AmbientOcclusion => "ambient occlusion",
527            Self::Motion => "motion",
528            Self::BentNormal => "bent normal",
529            Self::ShadowAtlas => "shadow atlas",
530            Self::Cascades => "cascades",
531        }
532    }
533}
534
535// Mesh-only resources follow the complete common fragment binding range.
536// Metal assigns dense native indices by resource-table order, so inserting a
537// mesh-only buffer before lights/probes would shift the layout away from the
538// independently compiled fragment stage. Sparse logical bindings cost no slots.
539const CLUSTERS_BINDING: u32 = 32;
540const CLUSTER_VERTICES_BINDING: u32 = 33;
541const CLUSTER_CORNERS_BINDING: u32 = 34;
542const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
543const CLUSTER_CULL_BINDING: u32 = 36;
544const CLUSTER_CULL_STATS_BINDING: u32 = 37;
545const CLUSTER_SELECT_BINDING: u32 = 38;
546const CLUSTER_SELECTION_BINDING: u32 = 39;
547const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
548
549/// The shared fragment shader's shadow atlas slot. Historical logical gaps
550/// remain reserved so the raster shader bindings stay unchanged.
551const SHADOW_ATLAS_BINDING: u32 = 15;
552
553/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
554const SHADOW_SAMPLER_BINDING: u32 = 16;
555
556/// The bind-group slot the base-colour page is bound to.
557///
558/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
559/// of the mesh layout, as it does each page's binding — see
560/// `pages::page_binding`.
561const BASE_COLOR_PAGE_BINDING: u32 = 7;
562
563/// The bind-group slot the base-colour page's sampler is bound to.
564///
565/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
566/// in every group of the mesh layout: a sampler is a resource a group holds by
567/// handle, so a new sampler is a new group, and the rebuild finds the entry by
568/// this number.
569const PAGE_SAMPLER_BINDING: u32 = 8;
570
571/// The shared fragment shader's light list. Both shader modules declare it
572/// before mesh-only buffers so native buffer index 7 is common to both stages.
573const LIGHT_LIST_BINDING: u32 = 20;
574
575/// The bind-group slot the froxel grid is read through.
576const LIGHT_GRID_BINDING: u32 = 21;
577
578/// The fragment shader's screen-space occlusion texture. Mesh-only additions
579/// are buffers, so this resource does not shift their native argument table.
580const AMBIENT_OCCLUSION_BINDING: u32 = 22;
581
582/// The shared irradiance probe table, native buffer 9 in both shader modules.
583/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
584const PROBE_TABLE_BINDING: u32 = 23;
585
586/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
587/// Its logical binding stays 24; after the shared fragment buffer prefix it is
588/// native buffer 10. The raster path does not declare this storage buffer.
589const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
590
591/// The bind-group slot the split-sum `DFG` table is fetched through — how much
592/// of the light arriving at a GGX lobe that lobe hands back.
593///
594/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
595/// after the shared prefix. The fragment shader's `specular_dfg` remains at
596/// native texture 3, following `ambient_occlusion` at texture 2.
597///
598/// **An image rather than a storage buffer, and that is forced.** The table is
599/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
600/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
601/// Metal backend materialises every global into every entry point — so a row
602/// bound to the fragment stage alone would be a global the vertex stage names
603/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
604/// binding 7's `geometry` visibility.
605const SPECULAR_DFG_BINDING: u32 = 25;
606
607/// The bind-group slot §2's normal page is sampled through.
608///
609/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
610/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
611/// next index in its Metal argument table by counting the same-table entries of
612/// this layout, and Slang numbers a stage's arguments by declaration order, so
613/// the two agree only while both ascend. No mirror is needed in
614/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
615///
616/// **No sampler of its own.** The page is read through
617/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
618/// base-colour page uses, because it is sampled at the same UV over an image of
619/// the same extent. A second sampler would be a second layout entry, a second
620/// index in Metal's sampler argument table, and a second thing
621/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
622/// be identical.
623const NORMAL_PAGE_BINDING: u32 = 26;
624
625/// The bind-group slot topic 44's rung 5 reads its linearly
626/// transformed cosine table through.
627///
628/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
629/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
630/// Metal argument table by counting the same-table entries of this layout, and
631/// Slang numbers a stage's arguments by declaration order, so the two agree only
632/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
633/// needs no mirror there and no index anything already owns moves.
634///
635/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
636/// blend written out in the shader, because a hardware filter's weights are
637/// fixed-function arithmetic four rasterisers compute independently and these
638/// goldens are compared across all four.
639const LTC_TABLE_BINDING: u32 = 27;
640
641/// The bind-group slot topic 45's contact-shadow channel is
642/// read through.
643///
644/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
645/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
646/// argument table by counting the same-table entries of this layout, and Slang
647/// numbers a stage's arguments by declaration order, so the two agree only while
648/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
649/// no mirror there and no index anything already owns moves.
650///
651/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
652/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
653/// the frame on every pass that computed one.
654const CONTACT_SHADOW_BINDING: u32 = 28;
655
656/// The bind-group slot the irradiance probes' per-probe
657/// visibility maps are read through: one `Rg32Float` layer per probe.
658///
659/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
660/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
661/// Metal argument table by counting the same-table entries of this layout, and
662/// Slang numbers a stage's arguments by declaration order, so the two agree only
663/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
664/// needs no mirror there and no index anything already owns moves —
665/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
666///
667/// **A texture rather than a storage buffer, and that is forced**: the raster
668/// path's vertex stage is already at every storage buffer a WebGPU device
669/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
670///
671/// **No sampler**, like the occlusion channel and both cooked tables:
672/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
673/// out, because a hardware filter's weights are fixed-function arithmetic four
674/// rasterisers compute independently — and because `Rg32Float` is not a
675/// filterable format on WebGPU without an optional feature.
676const PROBE_VISIBILITY_BINDING: u32 = 29;
677
678/// The bind-group slot topic 43 §2's packed
679/// **metallic-roughness-occlusion** page is sampled through.
680///
681/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
682/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
683/// next index in its Metal argument table by counting the same-table entries of
684/// this layout, and Slang numbers a stage's arguments by declaration order, so
685/// the two agree only while both ascend. No mirror is needed in
686/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
687///
688/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
689/// read at the same UV over an image of the same shape as the base-colour one,
690/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
691/// Metal's sampler argument table.
692const MRO_PAGE_BINDING: u32 = 30;
693
694/// The bind-group slot topic 43 §2's **emissive**
695/// page is sampled through.
696///
697/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
698/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
699/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
700/// mirror there and no index anything already owns moves.
701const EMISSIVE_PAGE_BINDING: u32 = 31;
702
703/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
704///
705/// The table is square, and its size is a compile-time constant, so the
706/// conversion belongs here rather than as a fallible one at the upload.
707const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
708
709/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
710///
711/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
712/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
713/// what says the two tables are the same square, and each upload naming its own
714/// module is what would make a day they were not into a compile error here
715/// rather than a stretched image.
716const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
717
718/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
719///
720/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
721/// what `mesh.slang` reads on a frame drawing without
722/// [`RenderEffects::AMBIENT_OCCLUSION`].
723///
724/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
725/// this and the term is untouched. Any other value would be a silent global
726/// ambient scale.
727///
728/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
729/// direction** — the sentinel the occlusion chain writes wherever it has no
730/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
731/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
732/// direction at this pixel" are one case with one answer, and a frame drawn
733/// with the effect off is the frame this renderer drew before the channel was
734/// widened. Encoding a direction here instead would tilt every ambient term in
735/// such a frame towards one world axis.
736const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
737    0xFF,
738    ssao::BENT_NORMAL_NONE,
739    ssao::BENT_NORMAL_NONE,
740    ssao::BENT_NORMAL_NONE,
741];
742
743/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
744///
745/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
746/// what `mesh.slang` reads on a frame drawing without
747/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
748/// and the cascades have the last word alone. Any other value would be a silent
749/// global scale on the sun.
750///
751/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
752/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
753/// placeholders stand for different facts, and a day one of them wanted a
754/// different value should be an edit here rather than a search for which
755/// callers of a shared name meant which thing.
756const CONTACT_SHADOW_NONE: u8 = 0xFF;
757
758/// The one `Rg32Float` texel that occludes nothing: a mean distance of
759/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
760/// square.
761///
762/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
763/// what `mesh.slang` reads on a frame drawn before anything was captured or with
764/// `r_probe_visibility` off. No surface in any scene is further away than that,
765/// so `probe_weight` answers one for every probe and every fragment, and the
766/// grid is the unweighted trilinear blend it was before this rung — which is
767/// what makes the off position bit-identical rather than merely close.
768///
769/// Any *smaller* value would be a silent occluder: every probe in every scene
770/// would read as being behind a wall, and the whole grid would collapse onto
771/// `PROBE_OCCLUDED_WEIGHT`.
772fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
773    let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
774    let far = crcbl_shaders::probe_visibility::FAR;
775    texel[..4].copy_from_slice(&far.to_le_bytes());
776    texel[4..].copy_from_slice(&(far * far).to_le_bytes());
777    texel
778}
779
780/// The reversed-Z far plane, in the two places that have to agree about it.
781///
782/// `ssao.slang` leaves early at exactly this depth because the unprojection there
783/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
784/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
785/// the mirror is checked here — which is the only place both names are in scope.
786const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
787
788/// How many buckets a resident mesh occupies, which is **not the same on every
789/// geometry path** — the one place in this renderer the two differ in shape
790/// rather than in the call they record.
791///
792/// A flat mesh is one bucket either way. A DAG is one bucket on
793/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
794/// topic 25's per-cluster selection is that one dispatch covers
795/// several levels at once, so the run is every level's clusters end to end and
796/// the bucket's mesh id is level 0's.
797///
798/// On the two indirect tails a DAG is one bucket **per level**, because there
799/// the same plan takes a uniform cut and a level is drawn as an ordinary index
800/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
801/// selects one per instance, and a bucket is what an indexed draw of one index
802/// range *is*. See [`ForwardRenderer::level_buckets`].
803const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
804    if emit.is_mesh() { 1 } else { levels }
805}
806
807/// Every material mode this renderer routes a draw by, and the order the bucket
808/// table lays its per-mode runs of every mesh's levels down in.
809///
810/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
811/// the routing is total rather than checked: a row's mode is
812/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
813/// double-sided one, and the four combinations of them are these — so no
814/// material can carry a mode that is not in this list and no instance can
815/// scatter into a bucket that does not exist. Widening the mask means adding the
816/// mode here **and** giving it a depth pipeline in
817/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
818/// producer and the consumer of one list.
819///
820/// **A scene emits a twin per mode its own materials carry**, not one per
821/// entry here: two materials of two modes are two twins whichever two they are,
822/// and only a scene actually holding all four pays for four. The build below is
823/// where that filter is, and this module's
824/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
825const DEPTH_MODES: [u32; 4] = [
826    0,
827    mesh::GpuMaterial::ALPHA_MODE_MASK,
828    mesh::GpuMaterial::DOUBLE_SIDED,
829    mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
830];
831
832/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
833/// draw single-sided and double-sided buckets of one frame.
834///
835/// **A pipeline rather than a per-draw state, because no backend seam exposes
836/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
837/// is the precedent for why one would not be added: a raster state a recorded
838/// stream carried per draw is a state every backend has to be able to change
839/// between two indirect calls, and the portable answer to "this draw rasterises
840/// differently" is a second pipeline. Which draws take which is
841/// [`ForwardRenderer::sided_partitions`].
842///
843/// Four passes need the pair — the colour pass, the two depth-only ones and the
844/// reflective shadow map — so it is a type rather than eight fields.
845///
846/// **The twin exists only where the scene can draw with it.** A bucket table is
847/// fixed at build, from the modes the description's materials carry (see
848/// [`ForwardRenderer::bucket_modes`]), and nothing adds a material afterwards;
849/// so `build` knows then whether any bucket will ever be double-sided, and
850/// compiles the twin for that scene alone. Each twin is a cold compile as long
851/// as the pipeline it twins.
852///
853/// [`ForwardRenderer::partitions`] is what makes an unbuilt twin unbindable:
854/// it takes each pipeline as an [`Option`], so there is no handle to record
855/// for one that was never compiled, and a partition with draws in it and no
856/// pipeline is a panic rather than a bind.
857#[derive(Clone, Copy, Debug, PartialEq, Eq)]
858struct SidedPipelines {
859    /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
860    /// every bucket of every scene that does not use `doubleSided`.
861    single: GraphicsPipelineHandle,
862    /// [`CullMode::None`]: the buckets whose material carries
863    /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED), and
864    /// [`None`] for a scene with no such bucket.
865    double: Option<GraphicsPipelineHandle>,
866}
867
868impl SidedPipelines {
869    /// Both halves, single-sided first, for a pass to hand
870    /// [`ForwardRenderer::partitions`] — keyed by the
871    /// [`DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED) bit.
872    fn by_side(self) -> [(u32, Option<GraphicsPipelineHandle>); 2] {
873        [
874            (0, Some(self.single)),
875            (mesh::GpuMaterial::DOUBLE_SIDED, self.double),
876        ]
877    }
878
879    /// Every pipeline this holds, for a release.
880    fn handles(self) -> impl Iterator<Item = GraphicsPipelineHandle> {
881        std::iter::once(self.single).chain(self.double)
882    }
883}
884
885/// The pixel budget topic 25's descent compares a group's projected
886/// error against, unless a caller sets another with
887/// [`ForwardRenderer::set_lod_error_budget`].
888///
889/// One pixel, because that is what the metric is *for*: a level's error is how
890/// far its simplification may have moved the surface, so a budget of a pixel is
891/// the point at which a level change stops being something a viewer can see.
892/// The plan's "correct thresholds make pops sub-pixel by definition" is this
893/// number.
894const LOD_ERROR_BUDGET: f32 = 1.0;
895
896/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
897/// it holds.
898///
899/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
900/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
901/// because which one a bucket holds is the geometry path's decision and the
902/// buffer, its dynamic stride and the range the bind group names are all fixed
903/// before that decision reaches them.
904///
905/// **The bound range is the half that bites.** A range sized for the smaller
906/// block leaves the larger one's tail outside it, and a uniform read past the
907/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
908/// path's `group_stride` read back as zero and every instance descended against
909/// instance zero's LOD state.
910const DRAW_CONSTANTS_BLOCK: u64 =
911    if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
912        mesh::DRAW_CONSTANTS_SIZE as u64
913    } else {
914        crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
915    };
916
917/// How far below the budget an already-expanded group is held before it
918/// collapses again — topic 25's "switch-up and switch-down differ",
919/// as a fraction of [`LOD_ERROR_BUDGET`].
920///
921/// A ratio and not an offset because the band has to scale with the budget: a
922/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
923/// one. A fifth of the budget is a deadband a camera has to move decisively out
924/// of, and one a camera drifting along a boundary never leaves — which is the
925/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
926/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
927/// the setting that shows the band is what stops the flicker.
928const LOD_HOLD_RATIO: f32 = 0.8;
929
930/// How much larger than the camera's the pixel budget a shadow cascade selects
931/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
932/// selects +1/+2 coarser levels — casters are cheap where it never shows".
933///
934/// # A budget factor, because a level is not a parameter of the rule
935///
936/// The descent compares a group's projected error to a pixel budget; it never
937/// names a level. So "one or two levels coarser" is an *intent*, and the budget
938/// that produces it is the setting — and the two do not convert, because how far
939/// apart two levels' errors are is a property of the mesh. The committed dunes
940/// DAG is the demonstration: the step from one level's error to the next is
941/// several times larger in the middle of that hierarchy than at its base, and
942/// across its top levels there is no step at all — they report one error and are
943/// never separately selected by any budget. A bias expressed in levels would
944/// mean something different at each of those. `cook-clusters` prints the per
945/// level errors it built.
946///
947/// Four, then, is two doublings of the budget: enough that a caster is drawn
948/// coarser than the same object is in the colour pass, and small enough to stay
949/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
950/// the atlas is read through a comparison sampler with linear filtering, so an
951/// edge arrives already spread over neighbouring texels — and that the atlas
952/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
953/// samples it.
954///
955/// # Why one number, applied to the whole pass
956///
957/// **A cut is a cover only while expansion is monotone up the DAG**, and this
958/// scaling is what keeps it so. Multiplying both budgets by one positive
959/// constant leaves the rule in
960/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
961/// that module's induction turns on the projected error being monotone up the
962/// DAG rather than on what the constants are — so the shadow pass's cut is a
963/// cover for exactly the reason the camera's is. A bias that varied by cluster,
964/// by group, by level or by cascade would not be: two groups on one branch would
965/// be judged against different budgets, and a child expanding under an
966/// unexpanded parent is a hole.
967///
968/// Being larger than one also makes the shadow pass's expanded set a **subset**
969/// of the colour pass's, since the two now select from one eye at one scale: a
970/// group over `k` times the budget is over the budget. So the shadow cut is
971/// never finer than the camera's anywhere, which is the property
972/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
973/// and asserts.
974pub const SHADOW_LOD_BIAS: f32 = 4.0;
975
976/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
977/// light**, whatever kind of light it is.
978///
979/// Topic 18's fourth decision, as a number. A point light's six faces share the
980/// light's sphere — which is what a cull tests against — so they share one
981/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
982/// viewport. Six generators per light would be six copies of
983/// [`TileBuffers::group_state`], which is where the cost of one is written down.
984const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
985
986/// How many shadow *views* there are: one per cascade, and one per face of every
987/// light slot.
988///
989/// A view is what has a matrix, so it is what has a frame-block copy, a bind
990/// group and a cut of its own — while a *tile* is where a view lands in the
991/// atlas and a *cull* is which visible set it draws. The three were one number
992/// until a light could own six tiles.
993///
994/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
995/// point or a spot, because a bind group names its buffers when it is created
996/// and the kind of light holding a slot changes per frame. A spot uses face 0's
997/// view and the other five are never recorded — they cost a uniform buffer and a
998/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
999/// would cost.
1000const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
1001
1002/// Cascade 0's view, which is the one the irradiance probes'
1003/// reflective shadow map is drawn through.
1004///
1005/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
1006/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
1007/// [`shadow::CASCADES`], so it is not the function to reach for here.
1008const CASCADE_ZERO_VIEW: usize = 0;
1009
1010const _: () = assert!(
1011    CASCADE_ZERO_VIEW < shadow::CASCADES,
1012    "cascade 0's view has to be one of the cascades' own, not a light slot's"
1013);
1014
1015/// Which view is face `face` of light slot `slot`.
1016const fn shadow_view(slot: usize, face: usize) -> usize {
1017    shadow::CASCADES + slot * shadow::POINT_FACES + face
1018}
1019
1020/// Which cull light slot `slot` draws from.
1021const fn shadow_cull(slot: usize) -> usize {
1022    shadow::CASCADES + slot
1023}
1024
1025/// One punctual shadow face this frame draws into the punctual reflective
1026/// shadow map, and everything both halves of the updater need of it.
1027///
1028/// The irradiance probes' punctual producer. It carries no
1029/// matrix and no visible set: a face's transform is already in the uniform block
1030/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
1031/// slot's cull generated for the atlas — which is what makes this rung cost no
1032/// second cull and no second matrix.
1033#[derive(Clone, Copy, Debug)]
1034struct PunctualFace {
1035    /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1036    /// of the bind group whose block holds that face's own `view_proj`.
1037    view: usize,
1038    /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1039    /// answer for the slot this face belongs to.
1040    cull: usize,
1041    /// Which face of its light this is, and so — where the light's cull tagged
1042    /// its casters by face — which draw region it draws.
1043    face: usize,
1044    /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1045    /// rectangle the pass sets its viewport to *and* the one the gather reads
1046    /// this face's texels out of.
1047    tile: shadow::TileRect,
1048    /// The light this is a face of, as the gather weighs its texels.
1049    producer: PunctualProducer,
1050}
1051
1052/// The draw region face `face` of a light draws: its own region where the
1053/// light's cull tagged casters by face, and region 0 — every survivor — where it
1054/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1055fn face_region(by_face: bool, face: usize) -> u32 {
1056    if by_face {
1057        crcbl_shaders::draw_gen::FACE_REGION_BASE
1058            + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1059    } else {
1060        0
1061    }
1062}
1063
1064/// One light's row in the gather's producer table, for the face standing at
1065/// `tile`.
1066///
1067/// **Built out of the light's own row**, which is the one place a light becomes
1068/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1069/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1070/// than a second reading of the same fields that could round or widen
1071/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1072/// because a producer occludes through nothing: the gather gates a texel with
1073/// the probe's own visibility map, not with the light's.
1074fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1075    let row = light.row(None);
1076    PunctualProducer {
1077        position: [row.position[0], row.position[1], row.position[2]],
1078        radius: row.position[3],
1079        color: [row.color[0], row.color[1], row.color[2]],
1080        cos_outer: row.direction[3],
1081        axis: [row.direction[0], row.direction[1], row.direction[2]],
1082        cos_inner: row.cos_inner,
1083        origin: [tile.x, tile.y],
1084        side: tile.side,
1085        kind: row.kind,
1086    }
1087}
1088
1089const _: () = assert!(
1090    SHADOW_CULLS == shadow::GROUPS,
1091    "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1092     dispatches, and two different counts would schedule a group nothing draws"
1093);
1094
1095/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1096/// generates from `SV_VertexID`. No geometry is bound.
1097const TILE_CLEAR_VERTICES: u32 = 3;
1098
1099const _: () = assert!(
1100    crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1101    "the stage that resets one tile writes a depth the attachment's own clear \
1102     does not, so a held tile and a cleared one would answer differently where \
1103     nothing was drawn"
1104);
1105
1106/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1107///
1108/// The rectangle the allocator handed out — the same one the fragment stage
1109/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1110/// the whole atlas before the pass body ran, and this is what narrows it: the
1111/// same clip-space matrix mapped into a different part of the image, and for a
1112/// point light six different matrices into six of them off one visible set.
1113///
1114/// A function rather than the two calls inline, because the tile clear and the
1115/// draws that follow it walk the same tiles and a viewport set one way for one
1116/// of them would clear a rectangle nothing draws into.
1117fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1118    let rect = Rect2d {
1119        x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1120        y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1121        width: tile.side,
1122        height: tile.side,
1123    };
1124    encoder.set_viewport(&Viewport {
1125        x: rect.x as f32,
1126        y: rect.y as f32,
1127        width: rect.width as f32,
1128        height: rect.height as f32,
1129        ..Viewport::from_size(rect.width, rect.height)
1130    });
1131    encoder.set_scissor(&rect);
1132}
1133
1134/// What the last executed graph left the renderer-owned import `image` in, as an
1135/// [`ImportedImage::initial`].
1136///
1137/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1138/// fallback around one.** The ledger records what a graph *executed*, so nothing
1139/// recorded means nothing has run against this image on this pool — a freshly
1140/// created image before its first frame, and an image whose pool has been
1141/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1142/// barrier has moved is in. It is also the only declaration that lets the
1143/// incoming barrier hand the image a layout at all: every other state names an
1144/// old layout the image is not in.
1145///
1146/// The reason this is a lookup and not a field the renderer advances: a graph is
1147/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1148/// stepped forward while the passes were declared would have moved for a frame
1149/// that never reached the GPU, and the next frame's declaration — now wrong —
1150/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1151/// it through. One source of truth is what removes that gap rather than
1152/// narrowing it.
1153fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1154    pool.imported_image_use(image)
1155        .unwrap_or(ResourceState::Undefined)
1156}
1157
1158/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1159/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1160/// the debug draw layer, the tonemap, the ground grid and the
1161/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1162/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1163/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1164///
1165/// [`AtlasView::PASSES`] has no term of its own and is inside
1166/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1167/// viewer and the resolve are never both recorded.
1168///
1169/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1170/// ground grid's terms: all three are off unless a scene's
1171/// [`ProbeUpdate`] asks for them, and a bound short
1172/// of the frame that does ask would silently stop timing its last pass. The
1173/// punctual map is a pass whether or not the frame has a punctual light to draw
1174/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1175/// gather reads on a frame that lights none.
1176///
1177/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1178/// [`LightGrid`], which is why this is the only count written here rather than
1179/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1180/// though a device that refused the readback records one fewer: this is a
1181/// ceiling, and one that came up short would silently stop timing the last pass
1182/// of every frame. It is the **all-effects-on** count for the same reason: a
1183/// frame that switched one off records fewer, and a bound that tracked the
1184/// toggles would have to be re-sized whenever they moved.
1185///
1186/// The ground grid is counted on the same terms, even though it is off by
1187/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1188/// records one more pass, and a bound short of that would silently stop timing
1189/// the last pass of every frame it drew. The render-scale upscale is the second
1190/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1191/// therefore absent until a caller moves it. The debug draw layer is the third,
1192/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1193///
1194/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1195/// counts**: a chain's length is a function of the target's extent — see
1196/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1197/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1198/// either an extent or a console is known. The frame that lands on
1199/// it is a large one with bloom switched on; every smaller frame records fewer,
1200/// exactly as a frame with a free shadow slot does.
1201const RENDER_PASSES: u32 = 8
1202    // The occlusion cull's late depth prepass and its farthest pyramid, on the
1203    // ground grid's terms: off unless a caller switches the cull on.
1204    + 1
1205    + OcclusionPyramid::PASSES
1206    + DebugDraw::MAX_PASSES
1207    + ProbeGather::PASSES
1208    + Ssao::MAX_PASSES
1209    + ContactShadows::PASSES
1210    + Hiz::PASSES
1211    + Ssr::PASSES
1212    + Volumetric::PASSES
1213    + Water::PASSES
1214    + Grass::PASSES
1215    + Exposure::PASSES
1216    + Bloom::MAX_PASSES
1217    + POST_TONEMAP_PASSES
1218    + Upscale::PASSES;
1219
1220/// What the frame's one resolve slot costs at its widest: the larger of the two
1221/// antialiasing tiers.
1222///
1223/// **The larger and not the sum**, because the two are never both recorded —
1224/// [`RenderEffects::CMAA2`] carries that in writing and
1225/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1226/// all-effects-on count as well as the ceiling, which is the property
1227/// [`RENDER_PASSES`] needs from every term it adds up.
1228///
1229/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1230const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1231    Fxaa::PASSES
1232} else {
1233    Cmaa2::PASSES
1234};
1235
1236/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1237/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1238/// filtering it.
1239///
1240/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1241/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1242/// antialiasing tiers off for every debug view, and the atlas viewer records
1243/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1244/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1245/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1246/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1247/// is what holds the arithmetic to a frame that was actually recorded.
1248const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1249    RESOLVE_PASSES
1250} else {
1251    AtlasView::PASSES
1252};
1253
1254/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1255///
1256/// The smallest fraction of the target extent a frame may be drawn at.
1257///
1258/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1259/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1260/// stops being a picture of the scene and starts being a picture of the filter,
1261/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1262/// engine's resolution slider bottoms out somewhere; this is where this one
1263/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1264/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1265/// draw.
1266pub const MIN_RENDER_SCALE: f32 = 0.25;
1267
1268/// The anisotropy the base-colour page is sampled with where the device grants
1269/// [`Features::SAMPLER_ANISOTROPY`].
1270///
1271/// Eight, which is topic 43's filtering rung's
1272/// default and the figure current engines default their own slider to: past it
1273/// the footprint's long axis is already sampled finely enough that sixteen is
1274/// invisible at a grazing angle and costs the same again in fetches. A device
1275/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1276/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1277/// device without the feature gets one, which is the value that turns it off.
1278pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1279
1280/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1281/// because these are the only draws in this file whose instance and triangle
1282/// counts the CPU knows exactly — everything else here goes through an indirect
1283/// call.
1284const FULLSCREEN_DRAWS: u64 = 1;
1285
1286/// How many full-screen passes a frame drawing `effects` at `extent` records:
1287/// the tonemap, always, and each switched-on effect's passes beside it.
1288///
1289/// **A function of the frame rather than a constant**, since
1290/// topic 48's toggles: it was the tonemap alone, then
1291/// five, and either written down is a number that stops matching the frame. The
1292/// tonemap is the one that is not conditional — a frame has to reach the
1293/// swapchain.
1294///
1295/// **`extent` is here because the bloom chain's length depends on it** — see
1296/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1297/// size. A frame too small for even one chain level records none of them, which
1298/// is the same arithmetic as the toggle being off. It is the **internal** render
1299/// extent for the same reason: that is the extent every one of these passes runs
1300/// at.
1301///
1302/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1303/// resolution, not an effect — so it arrives as its own argument, on the ground
1304/// grid's terms. It is false on every frame at full render scale, which is the
1305/// frame this function counted before the knob existed.
1306///
1307/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1308/// variable rather than an effect bit, and it is the caller's job to read it
1309/// **once** for the frame. Reading it here as well would be a second read that
1310/// a command landing between the two could disagree with, and the disagreement
1311/// would be a counter describing a frame that was not recorded.
1312fn fullscreen_passes(
1313    effects: RenderEffects,
1314    extent: (u32, u32),
1315    upscaling: bool,
1316    ssao_blurs: u32,
1317) -> u64 {
1318    let mut passes = 1;
1319    if upscaling {
1320        passes += Upscale::PASSES as u64;
1321    }
1322    if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1323        passes += u64::from(Ssao::passes(ssao_blurs));
1324    }
1325    if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1326        passes += u64::from(ContactShadows::PASSES);
1327    }
1328    if effects.contains(RenderEffects::REFLECTIONS) {
1329        // The march's pair, and the pyramid it climbs — which is as long as the
1330        // extent allows and is zero on a frame too small to halve once, so this
1331        // term is the only one here that is not a constant per effect.
1332        passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1333    }
1334    if effects.contains(RenderEffects::BLOOM) {
1335        passes += u64::from(Bloom::passes_for(extent));
1336    }
1337    // **One resolve slot, and the higher tier takes it.** Both bits set is a
1338    // frame with CMAA2's passes and no FXAA pass at all, which is what
1339    // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1340    // an `else if` rather than two independent terms.
1341    //
1342    // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1343    // function counts is full-screen *draws*, and two of that tier's three
1344    // passes are compute dispatches. [`crate::exposure`]'s three are left out
1345    // of this arithmetic for the same reason.
1346    if effects.contains(RenderEffects::CMAA2) {
1347        passes += Cmaa2::FULLSCREEN_PASSES;
1348    } else if effects.contains(RenderEffects::ANTIALIASING) {
1349        passes += Fxaa::PASSES as u64;
1350    }
1351    if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1352        // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1353        // scatter and the column scan are compute dispatches; what this
1354        // function counts is full-screen *draws*, and only the composite is
1355        // one. An atmosphere runs the composite without the effect, and the
1356        // caller adds that one — it is not an effect bit.
1357        passes += u64::from(Volumetric::COMPOSITE_PASSES);
1358    }
1359    // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1360    // entry here: all three of its passes are compute dispatches, and the
1361    // exposure they measure reaches the picture through the tonemap's own draw.
1362    passes
1363}
1364
1365/// The budget an **orthographic** camera selects under: one no group satisfies,
1366/// so every group expands and the base level is drawn whole.
1367///
1368/// The metric divides a projected error by the distance to the group's sphere,
1369/// and an orthographic projection has no such falloff — see
1370/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1371/// Drawing the finest level is the conservative answer and the honest one; a
1372/// distance term invented for a projection that has none would be neither.
1373///
1374/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1375const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1376
1377/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1378/// [`SkinnedMesh`] where the description's mesh index would be.
1379///
1380/// The mesh is a reservation rather than an index because a skinned draw is not
1381/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1382/// fills, and which of the reservation's two runs that is changes every frame.
1383/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1384/// here carries a parity.
1385#[derive(Clone, Copy, Debug)]
1386pub struct SkinnedInstanceDesc<'a> {
1387    /// The region this object is drawn out of, from
1388    /// [`ForwardRenderer::reserve_skinned`].
1389    pub mesh: &'a SkinnedMesh,
1390    /// Which [`SceneDesc::materials`] row it shades through, exactly as
1391    /// [`InstanceDesc::material`].
1392    pub material: usize,
1393    /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1394    ///
1395    /// The joints are **not** in it — a palette carries each joint's global
1396    /// transform times its inverse bind matrix, and this is what puts the
1397    /// deformed mesh in the world. See
1398    /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1399    pub transform: Mat4,
1400    /// A **model-space** box around every pose this object will be drawn in
1401    /// until it is next set, in the space [`transform`](Self::transform)
1402    /// carries into the world — or `None`, which keeps it in every cull.
1403    ///
1404    /// **`None` is the safe default and the costly one.** The region's source
1405    /// mesh's box is its bind pose, which says nothing about where a skinning
1406    /// dispatch moves the vertices, so an object without a box of its own is
1407    /// drawn by every camera and every shadow map wherever it is. With one, the
1408    /// frustum culls, the occlusion culls and the shadow cache's footprints
1409    /// test it exactly as they test a rigid mesh's box. **The box has to
1410    /// contain every vertex the palette can put anywhere**: a cull that finds
1411    /// it outside drops the whole object, so a box that misses part of a pose
1412    /// can make an object vanish while that part is on screen.
1413    /// [`ForwardRenderer::set_skinned_bounds`] moves it each frame, for a pose
1414    /// — a ragdoll — that travels far from the object's origin.
1415    ///
1416    /// Every corner must be finite and `min` must not exceed `max` on any
1417    /// axis. An inverted or non-finite box is refused rather than written,
1418    /// because the culls would read it as a box nothing reaches and drop the
1419    /// object everywhere — see [`InstancePoolError::InvalidBounds`].
1420    pub bounds: Option<Aabb>,
1421}
1422
1423/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1424///
1425/// **The two projections are cached beside the LUT rather than taken per
1426/// frame**, which is what makes a frame under a sun that has not moved do no
1427/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1428/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1429/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1430/// rows per frame, because those are writes into the frame's own ring slots
1431/// rather than projections.
1432#[derive(Clone, Debug)]
1433struct PresentedSky {
1434    /// The normalised sun and viewpoint the LUT was marched for, which is what
1435    /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1436    /// against.
1437    parameters: crcbl_shaders::atmosphere::Atmosphere,
1438    /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1439    /// samples.
1440    view: SkyView,
1441    /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1442    /// pass's block carries.
1443    gradient: crcbl_shaders::sky::SkyGradient,
1444    /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1445    irradiance: crcbl_shaders::probe::GpuProbe,
1446}
1447
1448impl PresentedSky {
1449    /// Takes both projections from a LUT that has just been marched.
1450    fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1451        Self {
1452            parameters,
1453            gradient: view.gradient_fit(),
1454            irradiance: view.irradiance(),
1455            view,
1456        }
1457    }
1458}
1459
1460/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1461/// secondary view begun after it writes its blocks against the same sun, light
1462/// rows and shadow matrices the primary camera's were written against.
1463///
1464/// Everything here is decided by the primary camera and drawn once: the rows
1465/// carry the shadow tiles the primary camera's selection handed out, and the
1466/// cascades are fitted to its frustum. A secondary view samples the maps those
1467/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1468#[derive(Clone, Debug)]
1469struct FrameScene {
1470    light: DirectionalLight,
1471    rows: Vec<crcbl_shaders::light::GpuLight>,
1472    cascades: Cascades,
1473    shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1474    light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1475    atlas_rects: [[f32; 4]; shadow::TILES],
1476}
1477
1478/// The bucket and level tables a scene's generators are all built from, kept
1479/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1480/// returned.
1481#[derive(Debug)]
1482struct DrawTables {
1483    bucket_meshes: Vec<u32>,
1484    bucket_clusters: Vec<u32>,
1485    bucket_cluster_bases: Vec<u32>,
1486    mesh_levels: Vec<level_select::MeshLevels>,
1487    level_groups: Vec<level_select::LevelGroup>,
1488    level_meshes: Vec<u32>,
1489    instance_capacity: u32,
1490    light_capacity: u32,
1491}
1492
1493/// The primary frame attachments an overlay may use before antialiasing and
1494/// render-scale reconstruction.
1495///
1496/// `display` is the display-space image the tonemap and post-tonemap overlays
1497/// have written. `depth` is the matching internal scene depth image, retained
1498/// as a read-only attachment for depth-tested overlays. Both have
1499/// `internal_extent` dimensions.
1500#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1501pub struct ForwardOverlayTargets {
1502    pub display: ImageId,
1503    pub depth: ImageId,
1504    pub internal_extent: (u32, u32),
1505}
1506
1507/// Everything the forward frame owns, created once.
1508#[derive(Debug)]
1509pub struct ForwardRenderer {
1510    // Geometry: the global pools, and the meshes resident in them. Each
1511    // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1512    // for a mesh whose upload has completed — so there is no way to reach a
1513    // draw below with a mesh the GPU has not received.
1514    pool: MeshPool,
1515    /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1516    /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1517    /// [`buckets_for`] says is a property of the path as well as of the scene.
1518    ///
1519    /// **The whole of what the CPU still says per draw.** Everything else a
1520    /// draw needs — how many instances, which indices, which vertices — is in
1521    /// the arguments the GPU wrote or in a table it resolves them through.
1522    bucket_constants: Vec<u32>,
1523    /// What one draw region adds to a bucket's offsets — the same for every
1524    /// generator this renderer built, because they share one bucket table.
1525    region_step: RegionStep,
1526    /// The material mode of each bucket, in the same order — the copy the
1527    /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1528    /// against.
1529    ///
1530    /// What it is for: the depth prepass and the shadow atlas partition their
1531    /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1532    /// scene with a cutout in it keeps the vertex-only stage. See
1533    /// [`ForwardRenderer::depth_partitions`].
1534    ///
1535    /// All zeroes for a scene whose materials are all opaque — every demo and
1536    /// every golden in this tree — which is exactly one bucket per mesh and one
1537    /// partition, byte for byte the stream they recorded before modes existed.
1538    bucket_modes: Vec<u32>,
1539
1540    // The instance array, and the objects' places in it. Nothing here is
1541    // rewritten per frame: the pool uploads what a caller changed and nothing
1542    // else, so a scene nobody moved costs no transfer at all.
1543    instances: InstancePool,
1544    /// The mesh table id of each description mesh's **level 0**, in
1545    /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1546    /// resolves through.
1547    ///
1548    /// Level 0's and not the whole run, because that is the entry an instance
1549    /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1550    /// levels approximate the same surface inside the same box. The coarser
1551    /// entries are resident and no instance names one — a cluster reaches its
1552    /// own level's vertices through
1553    /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1554    /// uniform cut reaches them through the bucket table.
1555    ///
1556    /// Kept rather than resolved per call because every write of an instance
1557    /// writes the whole record, and an instance that lost its mesh id would
1558    /// resolve to entry 0 — which is a mesh, and the wrong one.
1559    mesh_ids: Vec<u32>,
1560    /// Level 0's pool handle for each description mesh that can be skinned, in
1561    /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1562    /// [`ResidentMesh::skinnable`].
1563    ///
1564    /// What [`ForwardRenderer::reserve_skinned`] resolves an
1565    /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1566    /// there is no way back from a table id to the handle that owns it: an id is
1567    /// a bare index and a [`MeshHandle`] is generational.
1568    skinnable_meshes: Vec<Option<MeshHandle>>,
1569    /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1570    /// two base vertices it alternates between.
1571    ///
1572    /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1573    /// at the half of its region *this* frame's dispatch fills. Entries whose
1574    /// instance has gone stale are dropped as it walks, so
1575    /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1576    /// skinning.
1577    skinned_instances: Vec<SkinnedInstance>,
1578
1579    /// §3.2's material table, and the rows in it.
1580    ///
1581    /// One buffer shared by every frame's bind group, not a ring — see
1582    /// [`crate::material_table`], which is where that decision lives.
1583    materials: MaterialTable,
1584    /// The table row of each description material, in [`SceneDesc::materials`]
1585    /// order — what an [`InstanceDesc::material`] index resolves through.
1586    ///
1587    /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1588    /// whole record, and an instance that lost its material id would name row 0
1589    /// by accident, which is a material and only *happens* to be the untinted
1590    /// one.
1591    material_ids: Vec<u32>,
1592    /// Topic 50's irradiance grid, row by row.
1593    ///
1594    /// One buffer shared by every frame's bind group, like the material table
1595    /// and for a stronger version of its reason: a probe is written when the
1596    /// scene is made resident and there is no call that rewrites one. See
1597    /// [`crate::probe`].
1598    probes: ProbeTable,
1599    /// Where those rows are, which rides in the frame block rather than in a
1600    /// buffer of its own — a fragment needs it before it knows which row to
1601    /// fetch.
1602    ///
1603    /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1604    /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1605    /// grid of nothing, which is what a description with no probes leaves here
1606    /// and what makes the whole feature add zero.
1607    probe_volume: crcbl_shaders::probe::ProbeVolume,
1608    /// §3.2's texture side: one `D2Array` image whose layers the material rows
1609    /// index. One page, bound once, for every material — see the module docs on
1610    /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1611    /// a bindless descriptor array.
1612    base_color_page: UploadedTexture,
1613    /// §2's second page: one `D2Array` image of tangent-space normals, whose
1614    /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1615    /// indexes.
1616    ///
1617    /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1618    /// through the same UV and the same sampler, and **created linear** — see
1619    /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1620    /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1621    /// base-colour one is what the caller wrote and what this holds.
1622    normal_page: UploadedTexture,
1623    /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1624    /// roughness and metallic, whose layers
1625    /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1626    /// indexes.
1627    ///
1628    /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1629    /// same UV and the same sampler, and **created linear** — see
1630    /// [`MRO_PAGE_FORMAT`].
1631    mro_page: UploadedTexture,
1632    /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1633    /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1634    ///
1635    /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1636    /// **created sRGB** rather than linear, because an emissive texel is a
1637    /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1638    emissive_page: UploadedTexture,
1639    /// Each [`PageKind`]'s image size in texels, as a width and a height,
1640    /// indexed by [`PageKind::index`].
1641    ///
1642    /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1643    /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1644    /// named no layer of, which is the placeholder's extent and not the
1645    /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1646    /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1647    /// to the graph and an [`ImportedImage`] names an extent, and the
1648    /// description they came from is the caller's, read once at build.
1649    page_extents: [(u32, u32); PageKind::ALL.len()],
1650    /// The sampler the page is read through.
1651    base_color_sampler: SamplerHandle,
1652    /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1653    /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1654    anisotropy: f32,
1655    /// How many layers each [`PageKind`]'s page holds, indexed by
1656    /// [`PageKind::index`] — zero for a kind the description named none of.
1657    ///
1658    /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1659    /// replacement to, so every material row's layer number goes on naming the
1660    /// same texture.
1661    page_layers: [usize; PageKind::ALL.len()],
1662    /// `[frame]`: the page sampler and the four page views that slot's
1663    /// mesh-layout groups name.
1664    ///
1665    /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1666    /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1667    /// so this is what says which slots still name a sampler
1668    /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1669    /// [`replace_page`](ForwardRenderer::replace_page) did.
1670    slot_pages: Vec<PageBindings>,
1671    /// Page samplers and pages replaced while some slot may still name them.
1672    /// Each is destroyed as the last slot naming it moves off, or at
1673    /// [`destroy`](ForwardRenderer::destroy).
1674    retired_pages: Vec<RetiredPage>,
1675
1676    /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1677    /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1678    ///
1679    /// Kept rather than recomputed because the shadow pass's share is the number
1680    /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1681    /// out from topic 45's tile allocation and nothing outside
1682    /// it can restate without becoming the second copy that drifts.
1683    recorded_draws: u64,
1684    /// Which call the forward pass records — the device's [`GeometryPath`],
1685    /// resolved once.
1686    emit: EmitTail,
1687    /// The most buckets one call of the geometry passes draws, or `None` where
1688    /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1689    /// build with [`emit`](Self::emit) and for its reason.
1690    range_limit: Option<u32>,
1691    /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1692    /// tails draw the same geometry out of the index pool and read none of
1693    /// this. `None` is therefore the ordinary state on most devices rather than
1694    /// a failure, and it is also what makes a fall-through impossible — see
1695    /// [`ForwardRenderer::geometry_path`].
1696    clusters: Option<ClusterPool>,
1697    /// Whether the mesh pipeline was built with §3.5's amplification stage in
1698    /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1699    /// what it means is written down.
1700    culls_clusters: bool,
1701    /// Where each description mesh's clusters are in
1702    /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1703    /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1704    /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1705    mesh_clusters: Vec<ClusterRange>,
1706    /// The bucket each level of each description mesh draws through, finest
1707    /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1708    /// [`ForwardRenderer::level_buckets`].
1709    ///
1710    /// **The run for the scene's first material mode**, which is `OPAQUE`
1711    /// wherever the scene has an opaque material at all: the table is every
1712    /// mesh's levels once per mode the scene holds, mode by mode, and this
1713    /// names a mesh's levels in the first of those runs. See
1714    /// [`ForwardRenderer::bucket_modes`].
1715    mesh_level_buckets: Vec<Vec<u32>>,
1716    /// The pixel budget topic 25's descent compares a group's
1717    /// projected error against. [`LOD_ERROR_BUDGET`] until
1718    /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1719    lod_error_budget: f32,
1720    /// How far below that an expanded group is held before it collapses again.
1721    /// [`LOD_HOLD_RATIO`] until
1722    /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1723    lod_hold_ratio: f32,
1724    /// The same three numbers the shadow cascades selected under, which is
1725    /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1726    /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1727    ///
1728    /// Kept beside the camera's for its reason: a reader comparing the two cuts
1729    /// takes both pairs from here rather than re-deriving the bias, which would
1730    /// be comparing two copies of one arithmetic instead of two selections.
1731    shadow_lod_params: [f32; 3],
1732
1733    /// The lights a caller set beside the sun, as
1734    /// [`ForwardRenderer::set_lights`] was handed them.
1735    ///
1736    /// Kept rather than converted on the way in, because a row is the *frame's*
1737    /// artefact: the sun arrives per frame at
1738    /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1739    /// frame uploads cannot be assembled until then.
1740    extra_lights: Vec<Light>,
1741
1742    /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1743    /// alignment apart. Shared by every frame's bind group rather than ringed,
1744    /// because nothing rewrites it after `build`: a mesh's base vertex and an
1745    /// object's instance index are decided when the pools allocate them.
1746    draw_constants: BufferHandle,
1747    /// The camera's resources and history — see [`view`], which is where the
1748    /// line between a camera's state and the scene's is drawn.
1749    primary: View,
1750    /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1751    /// [`ViewId::index`] less one — a free id is `None`.
1752    views: Vec<Option<View>>,
1753    /// The tables a view's generator is built from — see [`DrawTables`].
1754    draw_tables: DrawTables,
1755    /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1756    /// say which frame it was last begun for — see [`View::begun`].
1757    frame_serial: u64,
1758    /// The frame the last `begin_frame` opened, for
1759    /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1760    frame_scene: Option<FrameScene>,
1761    /// Which frame-in-flight slot is current. Set from
1762    /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1763    /// uniform ring and the instance ring cannot drift apart.
1764    frame: usize,
1765
1766    mesh_layout: BindGroupLayoutHandle,
1767    mesh_pipeline_layout: PipelineLayoutHandle,
1768    mesh_pipeline: SidedPipelines,
1769    /// [`ForwardRenderer::mesh_pipeline`] again in
1770    /// [`PolygonMode::Line`], for
1771    /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1772    ///
1773    /// [`None`] until a caller first switches the view on — the ground grid's
1774    /// arrangement exactly, and for its reason: a second pipeline compiled at
1775    /// build would be paid for by every sample, golden and headless run that
1776    /// never asks for a wireframe, which is all of them. Once built it is kept,
1777    /// because switching the view off is
1778    /// [`ForwardRenderer::wireframe_on`] and not a release.
1779    ///
1780    /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1781    /// does not disable culling: a single-sided wireframe drawn over a
1782    /// double-sided bucket would leave a surface out of the debug view that the
1783    /// shaded frame beside it draws, which is a view of the document that
1784    /// disagrees with the document.
1785    wireframe_pipeline: Option<SidedPipelines>,
1786    /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1787    /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1788    /// default**: a wireframe is a tool's view of a document, and every sample
1789    /// and every golden image predates it.
1790    wireframe_on: bool,
1791    /// The occlusion and small-feature culls a caller asked for — see
1792    /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1793    occlusion_culling: OcclusionCulling,
1794    /// Whether the skinning dispatch skips a region no view and no shadow
1795    /// cull can draw this frame — see
1796    /// [`set_skinning_culls`](ForwardRenderer::set_skinning_culls).
1797    skinning_culls: bool,
1798    /// Every shadow cull this frame redraws, and the probe updater's on a
1799    /// frame with shadows off: the shadow half of what
1800    /// [`ForwardRenderer::cull_skinned_regions`] tests a skinned object's
1801    /// footprint against. Written by `begin_frame_body`.
1802    skin_shadow_reach: Vec<Frustum>,
1803    /// The skinning cull's storage and its last answer — see
1804    /// [`ForwardRenderer::cull_skinned_regions`].
1805    skin_cull: skin_cull::SkinCull,
1806    /// Regions the last recorded skinned frame planned and did not dispatch —
1807    /// see [`skinned_regions_skipped`](ForwardRenderer::skinned_regions_skipped).
1808    skinned_skipped: u32,
1809    /// Whether a point light's six faces cull separately — see
1810    /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1811    point_face_culls: bool,
1812    /// What a test asked every shadow view's uploaded block to be rewritten
1813    /// with — see
1814    /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1815    /// [`None`] outside a test.
1816    shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1817    /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1818    /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1819    /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1820    /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1821    ///
1822    /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1823    /// exactly: it is a tool's view of a document, and every sample and every
1824    /// golden image predates it.
1825    ///
1826    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1827    normals_view: bool,
1828
1829    /// The exponential height fog the colour pass composites over its
1830    /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1831    ///
1832    /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1833    /// terms: a caller who never asks for fog draws the frame this renderer
1834    /// drew before the feature existed, and exactly that frame — the shader's
1835    /// composite is an identity at zero density rather than an interpolation
1836    /// that nearly is.
1837    fog: Fog,
1838
1839    /// The gradient sky whose irradiance the colour pass adds to the ambient
1840    /// term — see [`set_sky`](ForwardRenderer::set_sky).
1841    ///
1842    /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1843    /// gradient projects to coefficients that are all zero, so the three dot
1844    /// products the fragment stage adds are zero and no frame drawn before a
1845    /// sky existed moves.
1846    sky: Sky,
1847    /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1848    /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1849    ///
1850    /// `None` by default, so a renderer nobody calls that on is the renderer it
1851    /// was.
1852    atmosphere: Option<Atmosphere>,
1853    /// The marched sky-view LUT this renderer is drawing, with the parameters
1854    /// it was marched for and the projections taken from it.
1855    ///
1856    /// **Cached against the parameters rather than rebuilt per frame**, because
1857    /// the march is tens of milliseconds of CPU and the sun in most frames has
1858    /// not moved. The stored parameters are the *normalised* ones the shader
1859    /// crate takes, so a caller handing over the same sun spelled two lengths
1860    /// does not force a rebuild.
1861    ///
1862    /// This is the LUT a frame is **drawn from**, which is not the one being
1863    /// marched: see [`Self::sky_view_build`].
1864    sky_view: Option<PresentedSky>,
1865    /// The march in flight, when the sun has moved away from
1866    /// [`Self::sky_view`]'s.
1867    ///
1868    /// [`ForwardRenderer::refresh_sky_view`] steps it
1869    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1870    /// [`Self::sky_view`] when it finishes.
1871    ///
1872    /// **The host side is where the double buffer is**: the LUT being drawn and
1873    /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1874    /// device ring is untouched. Putting the stripe on the device instead would
1875    /// mean writing part of a ring slot per frame, and that ring's slots are
1876    /// written whole precisely because each is a frame in flight — a partial
1877    /// write would have to track, per slot, which rows of *which* sun that slot
1878    /// already holds, which is bookkeeping the host copy does not need at all.
1879    sky_view_build: Option<SkyViewBuild>,
1880
1881    /// Whether the colour pass tints each cluster by its DAG level instead of
1882    /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1883    ///
1884    /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1885    /// because one uniform lane carries both switches and the fragment stage
1886    /// tests the LOD threshold first. `crcbl_shaders`'
1887    /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1888    /// order true.
1889    lod_view: bool,
1890
1891    /// Whether the colour pass shades each cluster by the projected error the
1892    /// LOD selection judged it on, instead of shading it or tinting it — see
1893    /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1894    ///
1895    /// **Wins over both [`lod_view`](Self::lod_view) and
1896    /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1897    /// reason: one uniform lane carries all three switches and the shaders test
1898    /// the outermost threshold first. `crcbl_shaders`'
1899    /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1900    /// order true, and
1901    /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1902    /// holds this side to it.
1903    heatmap: bool,
1904
1905    /// Whether the colour pass draws the ambient-occlusion channel as grey
1906    /// instead of shading — see
1907    /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1908    ///
1909    /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1910    /// for its reason: one uniform lane, outermost threshold first.
1911    /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1912    /// what keeps that order true, and
1913    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1914    /// this side to it.
1915    occlusion_view: bool,
1916
1917    /// Whether the colour pass draws the motion vector instead of shading — see
1918    /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1919    ///
1920    /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1921    /// terms and for its reason: one uniform lane, outermost threshold first.
1922    /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1923    /// is what keeps that order true, and
1924    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1925    /// this side to it.
1926    motion_view: bool,
1927    /// Whether the colour pass draws the occlusion channel's bent direction
1928    /// instead of shading — see
1929    /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1930    ///
1931    /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1932    /// terms: it is the outermost sentinel in the lane, and
1933    /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1934    /// is what holds the shader's branch order to it.
1935    bent_normal_view: bool,
1936
1937    /// Whether the colour pass tints the shaded picture by the cascade each
1938    /// sun-lit fragment's shadow was sampled from — see
1939    /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1940    ///
1941    /// **Loses to every other view**, which is the opposite of every field
1942    /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1943    /// replaces the shaded picture and this one multiplies it, so a frame drawing
1944    /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1945    /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1946    /// holds the shader to the same order, from the other end of the lane.
1947    cascade_view: bool,
1948
1949    /// Whether the frame draws the shadow atlas over the finished picture — see
1950    /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1951    ///
1952    /// **Not a lane of the frame block**, unlike every field above: this view is
1953    /// a pass rather than a branch in `mesh.slang`, so what reads this is
1954    /// [`ForwardRenderer::add_passes`] deciding whether to record
1955    /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1956    /// [`cascade_view`](Self::cascade_view) — see
1957    /// [`ForwardRenderer::debug_view`].
1958    atlas_view: bool,
1959
1960    /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1961    /// topic 25's selection from, when that is not the camera's own
1962    /// eye — see
1963    /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1964    ///
1965    /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1966    /// every frame the engine has drawn so far did: the eye handed to
1967    /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1968    /// never sets this writes the parameter block it wrote before this field
1969    /// existed.
1970    ///
1971    /// **Not a [`DebugView`]**, and deliberately: the three views are one
1972    /// picture chosen between, while this is a change to what the *selection*
1973    /// answers and leaves the picture's choice alone. A reviewer freezing the
1974    /// cut and then reading it off the LOD tint is the combination the feature
1975    /// exists for, so the two cannot be alternatives.
1976    frozen_selection_eye: Option<Vec3>,
1977
1978    /// Topic 18's shadow atlas: one `D32Float` image holding
1979    /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1980    /// first, then one per shadowed light.
1981    ///
1982    /// Owned here rather than created by the graph per frame, because its
1983    /// extent is a **quality setting and not a window size** — nothing about it
1984    /// changes on a resize, so a transient would be re-created for no reason
1985    /// and could not be read back by a test that does not own the graph.
1986    shadow_atlas: ImageHandle,
1987    shadow_atlas_view: ImageViewHandle,
1988    /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1989    /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1990    ///
1991    /// Both halves of that sentence are forced:
1992    ///
1993    /// * **The slot has to be filled.** Slang's Metal backend materialises every
1994    ///   global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
1995    ///   `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
1996    ///   depth-only pipeline sharing this layout still declares the argument. A
1997    ///   layout with the slot removed would break Metal alone, on a runner this
1998    ///   team cannot debug on, which is the trap binding 6's comment already
1999    ///   records.
2000    /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
2001    ///   attachment and a bind-group resource in the same pass, and the shadow
2002    ///   pass is exactly that pass.
2003    ///
2004    /// Nothing samples it: the shadow pipeline has no fragment stage. It is
2005    /// brought into the graph beside the atlas so its layout transition is the
2006    /// graph's like every other, rather than a hand-written barrier.
2007    shadow_placeholder: ImageHandle,
2008    shadow_placeholder_view: ImageViewHandle,
2009    /// The **comparison** sampler the atlas is read through — hardware PCF.
2010    shadow_sampler: SamplerHandle,
2011    /// The depth-only pipeline every tile is rendered with — and, driven with
2012    /// the camera's own draws, the depth prepass's: `mesh.slang`'s
2013    /// `depthVertexMain` where the geometry comes from a vertex stage, the same
2014    /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
2015    /// a mesh one, and no fragment stage in either case.
2016    shadow_pipeline: SidedPipelines,
2017    /// The same two passes' pipeline for the buckets whose material mode cuts
2018    /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
2019    /// [`MeshModules::depth_masked_pipeline`].
2020    ///
2021    /// [`None`] for a scene whose materials mask nothing, such as the demo
2022    /// scene: the bucket table is fixed at build, so a scene
2023    /// without a masked bucket then never has one — see [`SidedPipelines`] for
2024    /// the twin's same argument. Which buckets are drawn with it is
2025    /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
2026    /// frame's draws** rather than a choice for the whole frame.
2027    depth_masked_pipeline: Option<SidedPipelines>,
2028    /// The pipeline that resets one tile of the atlas before it is redrawn, on a
2029    /// frame that is keeping some of the others — see
2030    /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
2031    /// for it lives.
2032    shadow_clear_pipeline: GraphicsPipelineHandle,
2033    /// The irradiance probes' reflective shadow map — see
2034    /// [`MeshModules::rsm_pipeline`]. Built only for a volume that asked for
2035    /// [`ProbeUpdate::EveryFrame`], beside [`ForwardRenderer::probe_gather`] and
2036    /// for its reason, and [`None`] everywhere else; the pass that draws the
2037    /// map is recorded only where this is `Some`.
2038    rsm_pipeline: Option<SidedPipelines>,
2039    /// The compute pass that reads that map into the probe rows, and [`None`]
2040    /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
2041    /// whole of what the default costs such a scene: no pipeline, no buffers, no
2042    /// pass and no frame time.
2043    probe_gather: Option<ProbeGather>,
2044    /// Whether cascade 0's view block and cull parameters were written for the
2045    /// frame being recorded, so the reflective shadow map can be drawn from
2046    /// them.
2047    ///
2048    /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
2049    /// *atlas*: a frame drawing without
2050    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
2051    /// cascade 0 for the map and writes no tile, and overloading that flag would
2052    /// report a cascade as redrawn when nothing drew it.
2053    rsm_cull_ready: bool,
2054    /// What the scene said fills the probe rows.
2055    ///
2056    /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
2057    /// shadow atlas's static-cache hold when the updater is on, because the map
2058    /// is that cascade's own draws — and by the pass recording below.
2059    probe_update: ProbeUpdate,
2060    /// How far cascade 0 reached on the frame being recorded, which is the
2061    /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
2062    /// reads it.
2063    ///
2064    /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
2065    /// themselves, rather than recomputed at pass-record time: a frame that
2066    /// scaled its gather by one cascade's footprint while drawing the map
2067    /// through another's would be a bounce that is uniformly wrong, and nothing
2068    /// in the frame could see it.
2069    cascade_reach: f32,
2070    /// The sun's colour premultiplied by its intensity, this frame.
2071    ///
2072    /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2073    /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2074    /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2075    /// The sun's *direction* is not carried beside it: the gather needs none, on
2076    /// `probe_gather.slang`'s own derivation.
2077    sun_color: Vec3,
2078    /// One cull and draw-argument pass **per cascade and per shadowed light**,
2079    /// which is topic 18's "one cull dispatch per cascade against the same
2080    /// instance/geometry pools" with a shadowed light counting as a cascade does.
2081    ///
2082    /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2083    /// the same indirect call the colour pass does, so it needs the same
2084    /// arguments, and there is no "cull only" constructor to reach for. The cost
2085    /// is [`DrawGen`]'s own buffers and per-instance state — see
2086    /// [`TileBuffers::group_state`], which is where that price is written down,
2087    /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2088    /// than six.
2089    ///
2090    /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2091    /// [`shadow_cull`] is where a light slot's is.
2092    shadow_draws: Vec<DrawGen>,
2093    /// The layouts and pipelines every [`DrawGen`] above and in each view
2094    /// dispatches, compiled once and shared rather than once per generator.
2095    ///
2096    /// This reference is the renderer's own, held so [`create_view`] can hand
2097    /// the set to a view built later; [`destroy`](Self::destroy) gives it back
2098    /// after every generator, and whichever reference goes last destroys it.
2099    ///
2100    /// [`create_view`]: Self::create_view
2101    draw_pipelines: Arc<DrawGenPipelines>,
2102    /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2103    /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2104    /// mesh stages rather than a second transform path.
2105    shadow_uniforms: Vec<Vec<BufferHandle>>,
2106    /// Empty between frame preparations, with capacity retained for assembly.
2107    shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2108    /// Empty between frame preparations, with capacity retained for frusta.
2109    shadow_prepare_culls: Vec<(usize, Frustum)>,
2110    /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2111    /// the survivors of the cull its slot owns.
2112    shadow_groups: Vec<Vec<BindGroupHandle>>,
2113    /// `[frame][view]`: the cut that view's amplification stage chose, one word
2114    /// per resident cluster — and empty where there is no such stage.
2115    ///
2116    /// **A buffer per view rather than the camera's**, unlike every other
2117    /// resource these passes share: the colour pass is recorded last and writes
2118    /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2119    /// so a view writing there leaves nothing behind to read. Without one of
2120    /// these the shadow pass's descent is unobservable — which is the state
2121    /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2122    /// would have stayed in.
2123    shadow_selection: Vec<Vec<BufferHandle>>,
2124    /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2125    /// in the atlas's light region its tiles are, and the memory that keeps that
2126    /// answer from flickering.
2127    ///
2128    /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2129    /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2130    /// occupied slot and a viewport per face it has, and nothing at all for the
2131    /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2132    /// "nothing stored, fully lit" wherever anything did sample it.
2133    shadow_lights: shadow::Selection,
2134    /// `[group]`: everything that group's maps would be drawn from, as
2135    /// [`ForwardRenderer::shadow_group_record`] spells it.
2136    ///
2137    /// Kept only to tell one frame's answer from the last one's: it is compared
2138    /// and then replaced, and what travels from there is the number below.
2139    ///
2140    /// **Per group rather than per atlas**, since the cadence rung: a group is a
2141    /// cascade or a light slot's whole run of tiles, and holding one map while
2142    /// redrawing another is the whole of what that rung buys.
2143    shadow_group_inputs: Vec<Vec<u8>>,
2144    /// `[group]`: a number that moves whenever that group's entry of
2145    /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2146    /// value it has had.
2147    ///
2148    /// So "the image already holds this" is one integer comparison, which is
2149    /// what lets the pass body below carry the answer out of the graph.
2150    shadow_group_id: Vec<u64>,
2151    /// `[group]`: how many instance writes that group's cull could have seen,
2152    /// over the renderer's life — the per-group stand-in for
2153    /// [`InstancePool::revision`] in
2154    /// [`ForwardRenderer::shadow_group_record`], moved by
2155    /// [`ForwardRenderer::note_caster_writes`].
2156    shadow_group_writes: Vec<u64>,
2157    /// `[element]`: where each element of the instance array could draw into a
2158    /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2159    /// which is what a write's *before* is read from. Grows to the highest
2160    /// element written; an element past its end has never been written and is
2161    /// [`shadow_inputs::CasterFootprint::Nowhere`].
2162    shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2163    /// The live elements whose mesh has a DAG, and so whose level the selection
2164    /// eye chooses — the ones that put the eye into a light group's record.
2165    shadow_dag_elements: std::collections::BTreeSet<u32>,
2166    /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2167    /// an instance does not allocate its list.
2168    shadow_written: Vec<u32>,
2169    /// This frame's written elements' footprints, before and after the write,
2170    /// from [`ForwardRenderer::note_caster_writes`] for
2171    /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2172    /// written in.
2173    shadow_moved: Vec<(
2174        shadow_inputs::CasterFootprint,
2175        shadow_inputs::CasterFootprint,
2176    )>,
2177    /// The number given to the shadow pass this renderer recorded last.
2178    ///
2179    /// Moves once per recorded pass, so the body below can say *which* pass ran
2180    /// with one integer.
2181    shadow_pass_id: u64,
2182    /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2183    /// **ran**, written by that pass's own body.
2184    ///
2185    /// By the body rather than by the call that recorded it, and that is the
2186    /// whole of why this is shared state rather than a plain field: a frame
2187    /// whose graph was refused — or built and dropped — recorded a pass that
2188    /// never executed, so the image still holds whatever the frame before it
2189    /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2190    /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2191    /// imported images uses for the same reason.
2192    ///
2193    /// Zero until a pass has run, and the ids start above it, so the first frame
2194    /// of all draws.
2195    shadow_pass_ran: Arc<AtomicU64>,
2196    /// What the shadow pass recorded last would leave the image holding, if its
2197    /// body ran.
2198    ///
2199    /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2200    /// the only place that can tell whether it did — see
2201    /// [`ForwardRenderer::shadow_pass_ran`].
2202    shadow_pending: Option<ShadowCommit>,
2203    /// `[group]`: the id, the centre that group's maps were projected from and
2204    /// how far they reach, as the record the **image** holds describes them.
2205    ///
2206    /// The id is what says a map is out of date. The centre and reach are what
2207    /// say it is about somewhere else: a map whose own centre has moved further
2208    /// than its own reach covers ground it was never drawn for, and holding
2209    /// that is worse than a shadow that lags — see
2210    /// [`ForwardRenderer::shadow_cadence_reset`].
2211    shadow_group_held: Vec<(u64, Vec3, f32)>,
2212    /// `[group]`: whether this frame redraws that group's maps.
2213    ///
2214    /// Frozen by [`ForwardRenderer::begin_frame`] for
2215    /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2216    /// `add_passes` acts on it, and a value that moved between them would skip
2217    /// a cull whose draws were recorded, or the other way about.
2218    shadow_group_redrawn: Vec<bool>,
2219    /// Where every atlas slot's map was laid out on the frame the **image** was
2220    /// drawn from, so a frame can tell whether the texels it is keeping still
2221    /// describe the layout it is about to sample through.
2222    ///
2223    /// A layout that has moved is what makes a frame clear the whole attachment
2224    /// and redraw every group: a tile left over from a different layout is
2225    /// texels nothing this frame can account for. Promoted beside
2226    /// [`ForwardRenderer::shadow_group_held`].
2227    ///
2228    /// [`None`] until a pass has drawn, which is **not** the layout a frame
2229    /// with shadows off produces: an image no pass has touched holds undefined
2230    /// memory rather than a clear, so the first frame of all has to write one
2231    /// whatever it is asked for.
2232    shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2233    /// Whether any map this frame samples is one an earlier frame drew, rather
2234    /// than one this frame did.
2235    ///
2236    /// The cadence's own readback — see
2237    /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2238    /// atlas.
2239    shadow_atlas_cached: bool,
2240    /// Whether this frame ignored the cadence because some map's region moved
2241    /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2242    shadow_cadence_reset: bool,
2243    /// How many tiles this frame redraws — see
2244    /// [`ForwardRenderer::shadow_faces_redrawn`].
2245    shadow_faces_redrawn: u32,
2246    /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2247    ///
2248    /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2249    /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2250    /// process-global, and an application that wants a tier's own pair — or a
2251    /// test that wants a frame nothing else in the process can move — needs one
2252    /// that is not.
2253    shadow_cadence_request: Option<shadow::Cadence>,
2254    /// Whether this frame's shadow pass clears the whole attachment, rather
2255    /// than loading it and resetting only the tiles it redraws.
2256    ///
2257    /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2258    /// reason: the decision is `begin_frame`'s and the recording is
2259    /// `add_shadow_pass`'s, and a value that moved between them would load an
2260    /// attachment whose tiles nothing had reset.
2261    shadow_atlas_clears: bool,
2262    /// How many frames have been opened, which is what the cadence is keyed to.
2263    ///
2264    /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2265    /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2266    /// keyed to that would repeat every few frames and bound nothing.
2267    shadow_frame: u64,
2268
2269    /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2270    /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2271    /// the latency are argued.
2272    ///
2273    /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2274    /// statistics buffer of their own and none of them is read: a cascade's
2275    /// survivor count is a different question about a different frustum, and
2276    /// added into this one it would produce a number larger than the pool holds.
2277    ///
2278    /// [`None`] on a device that would not give out the buffers, which is what
2279    /// makes the counters row degrade to `indirect` rather than fail.
2280    cull_stats: Option<CullStatsRing>,
2281
2282    tonemap_layout: BindGroupLayoutHandle,
2283    tonemap_pipeline_layout: PipelineLayoutHandle,
2284    tonemap_pipeline: GraphicsPipelineHandle,
2285    sampler: SamplerHandle,
2286    /// The multiplier the tonemap pass applies before its clamp — see
2287    /// [`set_exposure`](ForwardRenderer::set_exposure).
2288    ///
2289    /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2290    /// the only thing that writes it and it clamps.
2291    exposure: f32,
2292    /// How far auto-exposure may move in one frame — see
2293    /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2294    ///
2295    /// [`None`] until a caller says otherwise, and that is the whole distance in
2296    /// one frame: the picture the pass drew before adaptation existed.
2297    exposure_adaptation: Option<ExposureAdaptation>,
2298    /// Which operator the tonemap pass runs — see
2299    /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2300    ///
2301    /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2302    /// a caller says otherwise: this renderer shades in linear HDR, so the
2303    /// filmic roll-off is what a view that has said nothing wants. A
2304    /// display-referred view — a 2D sample, or a fixture whose assertions
2305    /// predict a code value — asks for
2306    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2307    /// which is the identity on `0..=1`.
2308    tonemap_curve: tonemap::TonemapCurve,
2309
2310    /// The format the tonemap pipeline was built for. A swapchain format change
2311    /// needs a new pipeline, which is why it is remembered rather than assumed.
2312    target_format: Format,
2313
2314    /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2315    /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2316    /// occlusion image that does not exist yet.
2317    ///
2318    /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2319    /// The shadow pass and the depth prepass name it and never sample it — a
2320    /// depth-only pipeline has no fragment stage — and **the forward pass names
2321    /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2322    /// where it is the whole of that effect's off-switch. An AO-on frame binds
2323    /// the occlusion pair's blurred output instead.
2324    ///
2325    /// **It is white because that is the value that occludes nothing**, which is
2326    /// what makes it an honest stand-in for "no occlusion was computed" rather
2327    /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2328    /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2329    /// texel is zero on every backend, so the shader clamps the coordinate to the
2330    /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2331    ///
2332    /// It is uploaded rather than cleared, so it is in
2333    /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2334    /// declare it to give it a layout.
2335    ambient_occlusion_placeholder: UploadedTexture,
2336    /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2337    /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2338    /// contact-shadow image that does not exist yet.
2339    ///
2340    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2341    /// binding along and with one difference worth stating: an unclamped `Load`
2342    /// past this one's single texel would cost the frame its **sun**, not its
2343    /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2344    contact_shadow_placeholder: UploadedTexture,
2345    /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2346    /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2347    /// has been captured — and so the console switch has something to name when
2348    /// the maps are turned off.
2349    ///
2350    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2351    /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2352    /// against `GetDimensions`, so all four of its taps land on this image's one
2353    /// texel and every probe reads as unobstructed.
2354    probe_visibility_placeholder: UploadedTexture,
2355    /// The captured maps, one `Rg32Float` layer per probe — `None` until
2356    /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2357    /// frame drawn by a caller that never calls it.
2358    probe_visibility: Option<UploadedTexture>,
2359    /// The scene's static triangles, kept for that capture and for nothing else.
2360    ///
2361    /// Empty for a description that reserved no probes, which is what makes the
2362    /// retention cost of this rung zero for every caller that does not use it —
2363    /// see [`crate::probe_visibility`].
2364    probe_occluders: crate::probe_visibility::Occluders,
2365    /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2366    /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2367    /// by every area light's specular term.
2368    ///
2369    /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2370    /// again: it is a property of the GGX lobe rather than of a scene, a view or
2371    /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2372    /// it this is not a stand-in for anything — there is no path on which the
2373    /// table is absent, because there is no path on which the lobe is.
2374    specular_dfg: UploadedTexture,
2375    /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2376    /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2377    ///
2378    /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2379    /// terms exactly and for the same reason: it is a property of the lobe, and
2380    /// it is bound on every path because Slang's Metal backend materialises
2381    /// every global into every entry point.
2382    ltc_table: UploadedTexture,
2383    /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2384    /// from.
2385    ///
2386    /// Kept for one rebuild only: the pages' and their sampler's, which
2387    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2388    /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2389    shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2390
2391    /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2392    ///
2393    /// [`None`] until a caller first switches it on with
2394    /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2395    /// keeps a sample that never asks for a grid from building a pipeline and a
2396    /// ring of blocks for a pass it does not record. Once built it is kept —
2397    /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2398    /// release, because releasing a uniform ring the frames in flight may still
2399    /// be reading is exactly what the ring exists to prevent.
2400    ground_grid: Option<GroundGrid>,
2401    /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2402    /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2403    /// every sample and every golden image predates it.
2404    ground_grid_on: bool,
2405
2406    /// The debug draw layer's immediate-mode buffer and its pass — see
2407    /// [`crate::debug_draw`].
2408    ///
2409    /// Always present and empty by default, because appending to it is what a
2410    /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2411    /// it are what stay unbuilt until a frame has both a segment and
2412    /// [`crate::debug_draw::r_debug_draw`] switched on.
2413    debug_draw: DebugDraw,
2414
2415    /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2416    /// but the one [`debug_view`](Self::debug_view) resolved to
2417    /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2418    /// [`set_atlas_view`](Self::set_atlas_view) — and that frame's
2419    /// [`begin_frame`](Self::begin_frame) is what builds it, so a renderer
2420    /// whose atlas nobody looks at holds no pipeline for it.
2421    atlas_viewer: Option<AtlasView>,
2422    /// Whether the frame [`begin_frame`](Self::begin_frame) opened draws the
2423    /// shadow atlas viewer: [`debug_view`](Self::debug_view) as that call
2424    /// resolved it, frozen on [`frame_effects`](Self::frame_effects)' terms —
2425    /// the viewer's block is written and its pipeline built there, so
2426    /// [`add_passes`](Self::add_passes) has to agree with that call.
2427    frame_atlas_view: bool,
2428    /// How large the internal render target is as a fraction of the extent a
2429    /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2430    render_scale: f32,
2431    /// [`render_scale`](Self::render_scale) as the frame
2432    /// [`begin_frame`](Self::begin_frame) opened froze it, on
2433    /// [`frame_effects`](Self::frame_effects)' terms: every view's internal
2434    /// extent this frame is taken at it, so a scale moved before
2435    /// [`add_passes`](Self::add_passes) waits for the next frame, as
2436    /// [`set_render_scale`](Self::set_render_scale) says it does.
2437    frame_render_scale: f32,
2438
2439    /// The three layers a caller supplies — see [`crate::effects`].
2440    effect_request: EffectRequest,
2441    /// The fourth layer: what this device can draw, which clamps last and
2442    /// absolutely.
2443    ///
2444    /// **Every effect, and that is a fact about the effects rather than an
2445    /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2446    /// words — "there is no device fact to gate on … inventing a capability that
2447    /// is really a performance opinion is what topic 39 exists to prevent" — and
2448    /// the reflection pair's module says it of itself. The shadow atlas is a
2449    /// `D32Float` image and a depth-only pass, which is not something a device
2450    /// that got this far can be missing either: one too small for the atlas
2451    /// fails to *build* this renderer rather than degrading past it.
2452    ///
2453    /// So the clamp is real and its rule set is empty. The first rule arrives
2454    /// with the ray-traced variants of these same three effects, which
2455    /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2456    /// builds yet.
2457    device_effects: RenderEffects,
2458    /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2459    /// draws, resolved once there.
2460    ///
2461    /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2462    /// parameter write when shadows are off and
2463    /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2464    /// changed between the two would dispatch a cull whose counters nothing
2465    /// zeroed, which is a plausible frame drawn off last frame's numbers.
2466    frame_effects: RenderEffects,
2467    /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2468    /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2469    /// read once there.
2470    ///
2471    /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2472    /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2473    /// full-screen triangles and records its passes, and a console command
2474    /// landing between the two reads would leave `counters` describing a frame
2475    /// that was never submitted.
2476    frame_ssao_blurs: u32,
2477    /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2478    /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2479    /// as submitted beside the pool's instances.
2480    ///
2481    /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2482    /// `counters` describes the frame that *was* recorded, and a request set
2483    /// after it would otherwise change the count of a frame already submitted.
2484    recorded_fullscreen: u64,
2485
2486    /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2487    /// debug draw layer's pass, as the one direct draw it costs.
2488    ///
2489    /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2490    /// a full-screen triangle: it is one line-list draw of every segment this
2491    /// frame appended. Both are direct draws of one instance, which is what
2492    /// [`ForwardRenderer::direct_draws`] adds up.
2493    recorded_debug_draw: u64,
2494    /// How many tiles of the shadow atlas the last
2495    /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2496    /// than with the attachment's own clear.
2497    ///
2498    /// Zero on every frame that clears the whole attachment, which is every
2499    /// frame until the cadence is switched on — see
2500    /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2501    /// instance each, so it joins the full-screen draws rather than the
2502    /// indirect ones.
2503    recorded_tile_clears: u64,
2504    /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2505    /// buffers every view draws them from — see [`crate::water`]. Empty until
2506    /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2507    /// pass.
2508    water: WaterBodies,
2509    /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2510    /// recorded for the primary camera: one indexed draw per body, each of one
2511    /// instance, so they join the direct draws on the debug draw layer's terms.
2512    recorded_water_draws: u64,
2513    /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2514    /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2515    /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2516    /// pass.
2517    grass: GrassScene,
2518    /// What [`ForwardRenderer::grass`]'s field draws this frame, or [`None`]
2519    /// for a frame with none, frozen by `begin_frame` so that every view's
2520    /// blocks, the grass passes it builds and the passes
2521    /// [`add_passes`](ForwardRenderer::add_passes) records are one field's —
2522    /// a field set between the two is drawn from the next frame on, as a
2523    /// body of water is.
2524    frame_grass: Option<GrassFrame>,
2525    /// The wind block every view writes into its own ring — see
2526    /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2527    wind: crcbl_shaders::wind::WindParams,
2528    /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2529    /// recorded for the primary camera: one per tile slot per look the field
2530    /// draws.
2531    ///
2532    /// **Not among the direct draws**, unlike the water surface's: every one of
2533    /// them is an indirect call whose instance count lives in a buffer a
2534    /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2535    /// nothing about how many blades came out of them.
2536    recorded_grass_draws: u64,
2537    /// Start-up uploads submitted without a wait — the build's batch, and one
2538    /// for each [`create_view`](ForwardRenderer::create_view) and
2539    /// [`set_wind_layers`](ForwardRenderer::set_wind_layers) since — whose
2540    /// staging the GPU may still be reading.
2541    ///
2542    /// Each is retired by the first `begin_frame` that finds its semaphore
2543    /// signalled, and waited for by [`destroy`](ForwardRenderer::destroy) and
2544    /// [`destroy_view`](ForwardRenderer::destroy_view) before they release
2545    /// anything the copies write. Queue order is what lets a frame read the
2546    /// uploaded resources without waiting first — see [`PendingUpload`] — so
2547    /// every one of them was submitted to the device's graphics queue.
2548    uploads_in_flight: Vec<PendingUpload>,
2549}
2550
2551/// What a partly-built [`ForwardRenderer`] has to give back.
2552///
2553/// `new` creates a dozen objects with `?` between them, and the seam's
2554/// `destroy_*` is explicit — so a failure half way through used to leak
2555/// everything created before it. The recorder's leak assertions cover the happy
2556/// path; this covers the other one.
2557#[derive(Debug, Default)]
2558struct Rollback {
2559    buffers: Vec<BufferHandle>,
2560    bind_groups: Vec<BindGroupHandle>,
2561    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2562    pipeline_layouts: Vec<PipelineLayoutHandle>,
2563    pipelines: Vec<GraphicsPipelineHandle>,
2564    samplers: Vec<SamplerHandle>,
2565    /// The shadow atlas and its placeholder, which are created here rather than
2566    /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2567    /// with their views beside them.
2568    images: Vec<ImageHandle>,
2569    image_views: Vec<ImageViewHandle>,
2570    /// Uploaded images, which own a view each and so cannot be rolled back as
2571    /// one list of handles.
2572    textures: Vec<UploadedTexture>,
2573    /// The geometry pool, which owns two buffers, a semaphore and anything
2574    /// still staged — so it cannot be rolled back as a list of handles.
2575    pool: Option<MeshPool>,
2576    /// The instance pool, which owns one buffer per frame in flight.
2577    instances: Option<InstancePool>,
2578    /// The material table, which owns one buffer.
2579    materials: Option<MaterialTable>,
2580    /// The irradiance probe table, which owns one buffer.
2581    probes: Option<ProbeTable>,
2582    /// The irradiance probes' updater, which owns one pipeline,
2583    /// one layout and a ring of blocks — and only exists for a scene whose
2584    /// volume asked to be updated.
2585    probe_gather: Option<ProbeGather>,
2586    /// A view's cull and draw-argument passes, while [`View::build`] — which
2587    /// keeps a rollback of this type of its own — is still building the rest of
2588    /// that view. Only a view's rollback holds this one; the renderer's keeps
2589    /// its shadow culls' in [`shadow_draws`](Self::shadow_draws). They
2590    /// own a ring of buffers and dispatch
2591    /// [`draw_pipelines`](Self::draw_pipelines), and clean themselves up on
2592    /// their own failure path, so this only carries one that was built.
2593    draws: Option<DrawGen>,
2594    /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2595    /// `Option`, because a failure part way through the tiles has to release the
2596    /// ones already built.
2597    shadow_draws: Vec<DrawGen>,
2598    /// The draw-generation pipelines every generator shares, released after
2599    /// all of them — see [`ForwardRenderer::draw_pipelines`].
2600    draw_pipelines: Option<Arc<DrawGenPipelines>>,
2601    /// The cluster buffers, which own three buffers and are built on the
2602    /// mesh-shader path alone.
2603    clusters: Option<ClusterPool>,
2604    /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2605    /// three buffers — and which clean themselves up on their own failure path,
2606    /// so this only carries one that was built.
2607    lights: Option<LightGrid>,
2608    /// Topic 03 §3.3's farthest-depth pyramid,
2609    /// which owns one pipeline, one layout and — once a frame culled — a chain
2610    /// of level images.
2611    occlusion_pyramid: Option<OcclusionPyramid>,
2612    /// Topic 47's reflection march, which owns one
2613    /// pipeline, one layout and a ring of blocks.
2614    ssr: Option<Ssr>,
2615    /// The march's layouts and pipelines while nothing else owns them — see
2616    /// [`SsrPipelines`]. In the renderer's rollback, from the mesh batch that
2617    /// compiled them until [`View::build`] takes them; in a view's, from
2618    /// [`View::build`]'s start — the set came from that batch or from
2619    /// [`ViewPipelines::new`] — until [`Ssr::new`] takes it.
2620    ssr_pipelines: Option<SsrPipelines>,
2621    /// The froxel volume, which owns three
2622    /// pipelines, two layouts and two rings of buffers.
2623    volumetric: Option<Volumetric>,
2624    /// The volume's layouts and pipelines, on [`Rollback::ssr_pipelines`]'
2625    /// terms.
2626    volumetric_pipelines: Option<VolumetricPipelines>,
2627    /// Topic 43 §6's auto-exposure, which owns three
2628    /// pipelines, one layout and three rings of buffers.
2629    exposure: Option<Exposure>,
2630    /// The background pass, which owns one pipeline, one layout and a ring of
2631    /// blocks and groups.
2632    sky_pass: Option<SkyPass>,
2633    /// The camera, once [`View::build`] has made it whole — released as one,
2634    /// by [`View::destroy`].
2635    primary: Option<View>,
2636}
2637
2638impl Rollback {
2639    /// Releases everything, in the same dependency order as
2640    /// [`ForwardRenderer::destroy`].
2641    fn run(self, device: &dyn Device) {
2642        if let Some(view) = self.primary {
2643            view.destroy(device);
2644        }
2645        for texture in self.textures {
2646            texture.destroy(device);
2647        }
2648        for handle in self.samplers {
2649            device.destroy_sampler(handle);
2650        }
2651        for handle in self.image_views {
2652            device.destroy_image_view(handle);
2653        }
2654        for handle in self.images {
2655            device.destroy_image(handle);
2656        }
2657        for handle in self.pipelines {
2658            device.destroy_graphics_pipeline(handle);
2659        }
2660        for handle in self.pipeline_layouts {
2661            device.destroy_pipeline_layout(handle);
2662        }
2663        for handle in self.bind_groups {
2664            device.destroy_bind_group(handle);
2665        }
2666        for handle in self.bind_group_layouts {
2667            device.destroy_bind_group_layout(handle);
2668        }
2669        for handle in self.buffers {
2670            device.destroy_buffer(handle);
2671        }
2672        if let Some(clusters) = self.clusters {
2673            clusters.destroy(device);
2674        }
2675        for draws in self.shadow_draws {
2676            draws.destroy(device);
2677        }
2678        if let Some(lights) = self.lights {
2679            lights.destroy(device);
2680        }
2681        if let Some(sky_pass) = self.sky_pass {
2682            sky_pass.destroy(device);
2683        }
2684        if let Some(exposure) = self.exposure {
2685            exposure.destroy(device);
2686        }
2687        if let Some(volumetric) = self.volumetric {
2688            volumetric.destroy(device);
2689        }
2690        if let Some(pipelines) = self.volumetric_pipelines {
2691            pipelines.destroy(device);
2692        }
2693        if let Some(ssr) = self.ssr {
2694            ssr.destroy(device);
2695        }
2696        if let Some(pipelines) = self.ssr_pipelines {
2697            pipelines.destroy(device);
2698        }
2699        if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2700            occlusion_pyramid.destroy(device);
2701        }
2702        if let Some(draws) = self.draws {
2703            draws.destroy(device);
2704        }
2705        // After every generator — the camera's above and each shadow cull's —
2706        // although the reference count would hold it until the last of them
2707        // anyway.
2708        if let Some(pipelines) = self.draw_pipelines {
2709            DrawGenPipelines::release(pipelines, device);
2710        }
2711        // Before the table, because its bind groups name that table's rows.
2712        if let Some(gather) = self.probe_gather {
2713            gather.destroy(device);
2714        }
2715        if let Some(table) = self.probes {
2716            table.destroy(device);
2717        }
2718        if let Some(table) = self.materials {
2719            table.destroy(device);
2720        }
2721        if let Some(pool) = self.instances {
2722            pool.destroy(device);
2723        }
2724        if let Some(pool) = self.pool {
2725            pool.destroy(device);
2726        }
2727    }
2728}
2729
2730/// What every bind group of the mesh layout names identically.
2731///
2732/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2733/// the claim: a resource here cannot differ between the colour pass's group and
2734/// a cascade's, and one there must be looked at.
2735struct SharedBindings<'a> {
2736    vertices: BufferHandle,
2737    draw_constants: BufferHandle,
2738    mesh_table: BufferHandle,
2739    materials: BufferHandle,
2740    /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2741    /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2742    /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2743    /// beside them — as this frame slot names them, which is what
2744    /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2745    pages: PageBindings,
2746    /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2747    /// what decides whether the mesh-only bindings exist at all.
2748    clusters: Option<&'a ClusterPool>,
2749    shadow_sampler: SamplerHandle,
2750    /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2751    /// slots of the light ring.
2752    ///
2753    /// Shared rather than per-group, unlike the instance array beside them, and
2754    /// that is the claim: **a cascade shades nothing**, so it reads the same
2755    /// list and the same grid the colour pass does — the depth-only pipeline
2756    /// simply never looks. Two buffers per pass would be two clustering
2757    /// dispatches for one camera.
2758    lights: BufferHandle,
2759    light_grid: BufferHandle,
2760    /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2761    /// grid's ring.
2762    ///
2763    /// Shared across the *groups of one frame* rather than across frames, which
2764    /// is the light list's arrangement exactly: a cascade shades nothing, so it
2765    /// reads the same rows the colour pass does and the depth-only pipeline
2766    /// simply never looks. What it is not is shared across the ring — see
2767    /// [`crate::probe`] for why the table is per-frame at all.
2768    probes: BufferHandle,
2769    /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2770    ///
2771    /// Shared rather than per-group for the probe grid's reason exactly: the
2772    /// regions are written when a mesh becomes resident and never per frame, so
2773    /// a cascade and the colour pass read the same words. What varies between
2774    /// them is the *budget* the mesh stage projects against, and that rides in
2775    /// each pass's own frame block.
2776    tables: BufferHandle,
2777    /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2778    /// [`ForwardRenderer::specular_dfg`].
2779    ///
2780    /// Shared rather than per-group for the probe grid's reason and more
2781    /// strongly: it is cooked into the binary, uploaded once at build and
2782    /// identical for every view this engine will ever draw. A cascade names it
2783    /// and never looks.
2784    specular_dfg: ImageViewHandle,
2785    /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2786    /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2787    ltc_table: ImageViewHandle,
2788}
2789
2790/// The half of a mesh-layout bind group that differs between the colour pass and
2791/// each shadow cascade.
2792///
2793/// One description for both, so the two cannot drift: a cascade's group is the
2794/// colour pass's with six resources swapped, and swapping the wrong five of them
2795/// is a shadow map rendered from the camera — which looks like a shadow map.
2796struct MeshGroup {
2797    /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2798    /// `view_proj` is that cascade's matrix.
2799    uniforms: BufferHandle,
2800    /// Binding 2. This frame's slot of the instance ring.
2801    instances: BufferHandle,
2802    /// Binding 5. Whose survivors this group draws.
2803    runs: BufferHandle,
2804    /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2805    /// read as data.
2806    args: BufferHandle,
2807    /// Binding 13, where there is an amplification stage: the frustum it culls
2808    /// clusters against.
2809    cull_params: BufferHandle,
2810    /// Binding 14, likewise: what it counts survivors into.
2811    cull_stats: BufferHandle,
2812    /// Binding 18, likewise: the cut the descent chose, one word per resident
2813    /// cluster. `None` exactly where there is no amplification stage, which is
2814    /// where the layout has no CLUSTER_SELECTION_BINDING either.
2815    ///
2816    /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2817    /// so a cascade writing the camera's would leave nothing of its own to read.
2818    /// See [`ForwardRenderer::shadow_selection`].
2819    cluster_selection: Option<BufferHandle>,
2820    /// Binding 19, likewise: topic 25's hysteresis state, which the
2821    /// draw-argument pass wrote this frame and this one only reads.
2822    ///
2823    /// **A buffer per pass** as well, because the colour pass and a cascade
2824    /// judge the same groups under different budgets — see
2825    /// [`TileBuffers::group_state`].
2826    group_state: Option<BufferHandle>,
2827    /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2828    /// and the placeholder for the pass that writes it — see
2829    /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2830    shadow_map: ImageViewHandle,
2831    /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2832    /// a forward pass that computed one, and the white placeholder everywhere
2833    /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2834    ///
2835    /// **Every group built at `build` names the placeholder**, including the
2836    /// camera's: the occlusion image may be a graph transient whose view exists
2837    /// only at execute time, so the camera's group is rebuilt against whatever
2838    /// the frame bound inside the forward pass and cached — the shape
2839    /// [`View::tonemap_groups`] already has.
2840    ambient_occlusion: ImageViewHandle,
2841    /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2842    /// forward pass that marched one, and the white placeholder everywhere else
2843    /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2844    ///
2845    /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2846    /// group built at `build` names the placeholder.
2847    contact_shadow: ImageViewHandle,
2848    /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2849    /// maps for the camera's pass, and the one-texel placeholder everywhere
2850    /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2851    ///
2852    /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2853    /// is not a graph transient but an ordinary uploaded texture, so what makes
2854    /// this a per-frame swap is the console switch and whether a capture has
2855    /// happened yet — neither of which is known at `build`.
2856    probe_visibility: ImageViewHandle,
2857}
2858
2859impl MeshGroup {
2860    fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2861        let mut entries = vec![
2862            BindGroupEntry {
2863                binding: 0,
2864                array_index: 0,
2865                resource: BindingResource::whole_buffer(self.uniforms),
2866            },
2867            BindGroupEntry {
2868                binding: 1,
2869                array_index: 0,
2870                resource: BindingResource::whole_buffer(shared.vertices),
2871            },
2872            BindGroupEntry {
2873                binding: 2,
2874                array_index: 0,
2875                // **This frame's slot of the instance ring, not a shared
2876                // buffer.** Binding one buffer here for every group would undo
2877                // the ring and reintroduce the cross-submission
2878                // read-after-write hazard it exists to prevent.
2879                resource: BindingResource::whole_buffer(self.instances),
2880            },
2881            BindGroupEntry {
2882                binding: 3,
2883                array_index: 0,
2884                // **One block, not the whole buffer.** The binding is dynamic,
2885                // so the bind's offset is added on top of this one and both
2886                // Vulkan and WebGPU require `offset + dynamic + size` to stay
2887                // inside the buffer — bound whole, the very first non-zero
2888                // dynamic offset would be out of range.
2889                resource: BindingResource::Buffer {
2890                    buffer: shared.draw_constants,
2891                    offset: 0,
2892                    size: DRAW_CONSTANTS_BLOCK,
2893                },
2894            },
2895            BindGroupEntry {
2896                binding: 4,
2897                array_index: 0,
2898                // The same table in every group, unlike the instance array
2899                // above it: the pool writes an entry when a mesh is uploaded or
2900                // freed, neither of which happens between frames here.
2901                resource: BindingResource::whole_buffer(shared.mesh_table),
2902            },
2903            BindGroupEntry {
2904                binding: 5,
2905                array_index: 0,
2906                // Whose cull this group draws from. This is the binding a
2907                // cascade's group differs in most consequentially: it is what
2908                // makes the shadow pass draw what the *light* can see rather
2909                // than what the camera can.
2910                resource: BindingResource::whole_buffer(self.runs),
2911            },
2912            BindGroupEntry {
2913                binding: 6,
2914                array_index: 0,
2915                resource: BindingResource::whole_buffer(shared.materials),
2916            },
2917            BindGroupEntry {
2918                binding: BASE_COLOR_PAGE_BINDING,
2919                array_index: 0,
2920                // **One entry, `array_index: 0`**, because the page is one
2921                // image and the layer is chosen in the shader. A bindless array
2922                // would be one entry per texture at ascending array indices,
2923                // which is the write path `BindGroupEntry`'s own docs describe
2924                // and the one this pass does not take.
2925                resource: BindingResource::ImageView(
2926                    shared.pages.views[PageKind::BaseColor.index()],
2927                ),
2928            },
2929            BindGroupEntry {
2930                binding: PAGE_SAMPLER_BINDING,
2931                array_index: 0,
2932                resource: BindingResource::Sampler(shared.pages.sampler),
2933            },
2934        ];
2935        if let Some(clusters) = shared.clusters {
2936            entries.extend([
2937                BindGroupEntry {
2938                    binding: CLUSTERS_BINDING,
2939                    array_index: 0,
2940                    // The same three buffers in every group, on the mesh table's
2941                    // terms: clusters are written when the pool is built and
2942                    // never again.
2943                    resource: BindingResource::whole_buffer(clusters.clusters()),
2944                },
2945                BindGroupEntry {
2946                    binding: CLUSTER_VERTICES_BINDING,
2947                    array_index: 0,
2948                    resource: BindingResource::whole_buffer(clusters.vertices()),
2949                },
2950                BindGroupEntry {
2951                    binding: CLUSTER_CORNERS_BINDING,
2952                    array_index: 0,
2953                    resource: BindingResource::whole_buffer(clusters.corners()),
2954                },
2955                BindGroupEntry {
2956                    binding: CLUSTER_DRAW_ARGS_BINDING,
2957                    array_index: 0,
2958                    // **Arguments read as data.** The mesh path records no
2959                    // indirect draw at all; what it wants out of this buffer is
2960                    // the one word only the GPU knows — how many instances
2961                    // survived into each bucket.
2962                    resource: BindingResource::whole_buffer(self.args),
2963                },
2964            ]);
2965        }
2966        // Both mesh entry points retain these native buffer arguments even
2967        // when no amplification stage reads them.
2968        if shared.clusters.is_some() {
2969            entries.extend([
2970                BindGroupEntry {
2971                    binding: CLUSTER_CULL_BINDING,
2972                    array_index: 0,
2973                    resource: BindingResource::whole_buffer(self.cull_params),
2974                },
2975                BindGroupEntry {
2976                    binding: CLUSTER_CULL_STATS_BINDING,
2977                    array_index: 0,
2978                    resource: BindingResource::whole_buffer(self.cull_stats),
2979                },
2980            ]);
2981        }
2982        entries.push(BindGroupEntry {
2983            binding: SHADOW_ATLAS_BINDING,
2984            array_index: 0,
2985            resource: BindingResource::ImageView(self.shadow_map),
2986        });
2987        entries.push(BindGroupEntry {
2988            binding: SHADOW_SAMPLER_BINDING,
2989            array_index: 0,
2990            resource: BindingResource::Sampler(shared.shadow_sampler),
2991        });
2992        // Mesh-only buffers are sorted after the common fragment prefix below.
2993        if let Some(clusters) = shared.clusters {
2994            entries.push(BindGroupEntry {
2995                binding: CLUSTER_SELECT_BINDING,
2996                array_index: 0,
2997                // Bound with the geometry rather than with the cull, because
2998                // `vertex_base` *is* geometry: it is which level of a DAG a
2999                // cluster's vertices live in, and both mesh entry points resolve
3000                // a vertex through it.
3001                resource: BindingResource::whole_buffer(clusters.selection()),
3002            });
3003        }
3004        if let Some(selection) = self.cluster_selection {
3005            entries.push(BindGroupEntry {
3006                binding: CLUSTER_SELECTION_BINDING,
3007                array_index: 0,
3008                resource: BindingResource::whole_buffer(selection),
3009            });
3010        }
3011        if let Some(state) = self.group_state {
3012            entries.push(BindGroupEntry {
3013                binding: CLUSTER_GROUP_STATE_BINDING,
3014                array_index: 0,
3015                resource: BindingResource::whole_buffer(state),
3016            });
3017        }
3018        // Topic 18's pair, on every path and in every group — see the layout,
3019        // which has no configuration that omits them either.
3020        entries.push(BindGroupEntry {
3021            binding: LIGHT_LIST_BINDING,
3022            array_index: 0,
3023            resource: BindingResource::whole_buffer(shared.lights),
3024        });
3025        entries.push(BindGroupEntry {
3026            binding: LIGHT_GRID_BINDING,
3027            array_index: 0,
3028            resource: BindingResource::whole_buffer(shared.light_grid),
3029        });
3030        // Shared fragment textures and probes retain their raster bindings.
3031        entries.push(BindGroupEntry {
3032            binding: AMBIENT_OCCLUSION_BINDING,
3033            array_index: 0,
3034            resource: BindingResource::ImageView(self.ambient_occlusion),
3035        });
3036        // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
3037        entries.push(BindGroupEntry {
3038            binding: PROBE_TABLE_BINDING,
3039            array_index: 0,
3040            resource: BindingResource::whole_buffer(shared.probes),
3041        });
3042        // Group records are present on both mesh paths, matching the layout.
3043        if shared.clusters.is_some() {
3044            entries.push(BindGroupEntry {
3045                binding: LEVEL_GROUP_TABLE_BINDING,
3046                array_index: 0,
3047                resource: BindingResource::whole_buffer(shared.tables),
3048            });
3049        }
3050        // The DFG texture is read by the fragment stage of every path.
3051        entries.push(BindGroupEntry {
3052            binding: SPECULAR_DFG_BINDING,
3053            array_index: 0,
3054            resource: BindingResource::ImageView(shared.specular_dfg),
3055        });
3056        // And §2's normal page above that, on the same ascending terms — see
3057        // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
3058        // binding 7's reason: one image, and the layer is chosen in the shader.
3059        entries.push(BindGroupEntry {
3060            binding: NORMAL_PAGE_BINDING,
3061            array_index: 0,
3062            resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
3063        });
3064        // And the area lights' table above that, on the same ascending terms —
3065        // see [`LTC_TABLE_BINDING`].
3066        entries.push(BindGroupEntry {
3067            binding: LTC_TABLE_BINDING,
3068            array_index: 0,
3069            resource: BindingResource::ImageView(shared.ltc_table),
3070        });
3071        // And the contact-shadow channel above that, last of the set and on the
3072        // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
3073        entries.push(BindGroupEntry {
3074            binding: CONTACT_SHADOW_BINDING,
3075            array_index: 0,
3076            resource: BindingResource::ImageView(self.contact_shadow),
3077        });
3078        // And the probe visibility maps above that, on the same ascending terms
3079        // — see [`PROBE_VISIBILITY_BINDING`].
3080        entries.push(BindGroupEntry {
3081            binding: PROBE_VISIBILITY_BINDING,
3082            array_index: 0,
3083            resource: BindingResource::ImageView(self.probe_visibility),
3084        });
3085        // And §2's other two pages above that, last of the set and on the same
3086        // ascending terms — see [`MRO_PAGE_BINDING`] and
3087        // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3088        // normal page's reason: one image apiece, and the layer is chosen in
3089        // the shader.
3090        entries.push(BindGroupEntry {
3091            binding: MRO_PAGE_BINDING,
3092            array_index: 0,
3093            resource: BindingResource::ImageView(
3094                shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3095            ),
3096        });
3097        entries.push(BindGroupEntry {
3098            binding: EMISSIVE_PAGE_BINDING,
3099            array_index: 0,
3100            resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3101        });
3102        entries.sort_by_key(|entry| entry.binding);
3103        entries
3104    }
3105}
3106
3107/// The two `ArrayPages` images every group of the mesh layout names, as the
3108/// graph knows them.
3109///
3110/// One value rather than two arguments because the two travel together
3111/// everywhere: every pass that declares one declares the other, and a pass
3112/// handed them the wrong way round would order a caller's copy into the wrong
3113/// image — which is a barrier bug, and therefore one that reproduces on one
3114/// backend and not the others.
3115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3116struct MaterialPages {
3117    /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3118    base_color: ImageId,
3119    /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3120    normal: ImageId,
3121    /// §2's metallic-roughness-occlusion page —
3122    /// [`ForwardRenderer::mro_page_import`].
3123    mro: ImageId,
3124    /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3125    emissive: ImageId,
3126}
3127
3128/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3129/// as the graph knows it.
3130///
3131/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3132/// the list grew past what an argument list should be the moment the probe rows
3133/// joined it: each of these is in every cascade's bind group and read by no
3134/// cascade, so what the pass does with them is one thing — declare them, so the
3135/// graph can order whoever writes them against these draws.
3136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3137struct ShadowReads {
3138    /// The occlusion placeholder every cascade's group stands the real channel
3139    /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3140    occlusion_placeholder: ImageId,
3141    /// §3.2's and §2's pages, which the cascades name and never sample.
3142    pages: MaterialPages,
3143    /// The skinned vertex region, where a frame has one — the cascades pull the
3144    /// same geometry the colour pass does.
3145    skinned: Option<BufferId>,
3146    /// This frame's slot of the probe ring — see [`crate::probe`].
3147    probes: BufferId,
3148}
3149
3150/// What the mesh pass's bind-group layout is called.
3151///
3152/// Named rather than written twice because a test asserts on it: the layout's
3153/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3154/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3155/// has to find this one layout among the recorder's.
3156const MESH_LAYOUT_LABEL: &str = "mesh frame";
3157
3158/// Imports a buffer a pass both reads and writes, carried from one frame on
3159/// its slot to the next: it arrives in the state the previous frame that used
3160/// the slot left it in, and that is the state it is declared to leave in.
3161///
3162/// A record of the cut or a statistics sink, which a pass writes and the next
3163/// frame on the same slot writes again — a barrier naming `Undefined` as its
3164/// source would carry no source scope and order this frame's write against
3165/// nothing.
3166fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3167    graph.import_buffer(
3168        label,
3169        ImportedBuffer {
3170            buffer,
3171            initial: ResourceState::ShaderReadWrite,
3172            final_state: ResourceState::ShaderReadWrite,
3173        },
3174    )
3175}
3176
3177/// Declares the buffers a geometry pass reads to find its draws.
3178///
3179/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3180/// struct is what the encoder is told. Three passes declare exactly this set, and
3181/// the seam calls the barrier it produces the single most important one in a
3182/// GPU-driven frame — its absence produces "sometimes nothing draws".
3183///
3184/// A caller with a cluster-selection buffer of its own appends it; that is the
3185/// one declaration that differs between the colour pass, a cascade and the depth
3186/// prepass.
3187fn read_draw_sources<'g, 'a>(
3188    pass: PassBuilder<'g, 'a>,
3189    draws: &GeneratedDraws,
3190    emit: EmitTail,
3191) -> PassBuilder<'g, 'a> {
3192    // The buffers the draws come out of. Declaring them is what makes the graph
3193    // transition them out of the compute pass's `ShaderReadWrite`.
3194    let pass = pass.read_buffer(draws.runs_id);
3195    if emit.is_mesh() {
3196        // **The same arguments, read as data rather than executed**, which is
3197        // what the stages use to bound the run of surviving instances they index.
3198        // The per-bucket draw *counts* are not read at all, because nothing here
3199        // is a draw whose count could come from memory.
3200        //
3201        // The dispatch *extents* are a real indirect read — one structure per
3202        // bucket, written by the same pass. They are in a **different buffer**
3203        // from the arguments above and that separation is load-bearing: a
3204        // resource is in exactly one state per pass and these two are in
3205        // different ones. They share a buffer with the counts instead, which
3206        // this path does not read at all — see [`GeneratedDraws::counts`].
3207        let pass = pass
3208            .read_buffer(draws.args_id)
3209            .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3210        // The amplification stage counts its survivors into the culling
3211        // statistics, which the draw-argument pass read a moment ago — so this
3212        // is a write-after-read the graph has to order, and declaring it is
3213        // the whole of how it learns to.
3214        //
3215        // Topic 25's hysteresis state is read here and written by
3216        // the draw-argument pass a moment ago. Declaring it is what orders the
3217        // two — and what puts it back into `ShaderReadWrite` at the end of the
3218        // graph, which is where the next frame's draw-argument pass expects to
3219        // find it.
3220        //
3221        // **Declared on the whole mesh path, not only where there is an
3222        // amplification stage**, because that is where the bind group now
3223        // names both — see the layout, which is where the Metal argument-table
3224        // arithmetic that forced it is argued. A buffer bound writable and
3225        // never transitioned is a descriptor in the wrong resource state, which
3226        // is what the graph exists to prevent.
3227        pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3228            .read_buffer(draws.group_state_id)
3229    } else {
3230        pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3231            .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3232    }
3233}
3234
3235/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3236///
3237/// One of these per description mesh, in description order — so a mesh's index
3238/// here is its index there, which is what lets the bucket table, the level
3239/// tables and the cluster pool all be filled in by walking one list.
3240struct ResidentMesh {
3241    /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3242    /// level for a DAG. Never empty.
3243    ///
3244    /// Every level is its own vertex range and so its own table entry. Level 0's
3245    /// id is the one the *instance* carries and the one the cull pass reads a
3246    /// bounding box out of; the coarser ones are named by the bucket table on a
3247    /// path that takes a uniform cut, and by nothing at all on the mesh path,
3248    /// where a cluster reaches its own level through
3249    /// [`vertex_bases`](Self::vertex_bases) instead.
3250    levels: Vec<u32>,
3251    /// Per level, how far that level's vertices start past level 0's — so a flat
3252    /// mesh's single entry is zero.
3253    ///
3254    /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3255    /// and the whole of what makes a DAG drawable from one instance: the mesh
3256    /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3257    /// three levels reads three different vertex ranges out of one pool.
3258    vertex_bases: Vec<u32>,
3259    /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3260    /// for a [`Geometry::Dag`].
3261    ///
3262    /// A DAG is refused because its coarser levels are separate vertex runs no
3263    /// skinning dispatch writes: an instance drawn out of a skinned region
3264    /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3265    /// to the region's base, which for anything but level 0 is memory the
3266    /// dispatch never touched.
3267    skinnable: Option<MeshHandle>,
3268}
3269
3270impl ResidentMesh {
3271    /// The table id an instance of this mesh carries: **level 0's**, whatever
3272    /// the geometry path, because it is the entry `cull.slang` reads a bounding
3273    /// box out of and the coarser levels approximate the same surface inside the
3274    /// same box.
3275    fn id(&self) -> u32 {
3276        self.levels[0]
3277    }
3278}
3279
3280/// One skinned object the renderer re-points every frame: the instance, and the
3281/// base vertex it draws out of under each parity.
3282///
3283/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3284/// so placing an object does not tie the renderer's lifetime to the caller's
3285/// reservation — the renderer never needs the region again, only the two
3286/// numbers.
3287#[derive(Clone, Copy, Debug)]
3288struct SkinnedInstance {
3289    handle: InstanceHandle,
3290    /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3291    /// indexing — so the half a frame of parity `p` draws out of is
3292    /// `bases[p & 1]` and the half the frame before it filled is
3293    /// `bases[(p ^ 1) & 1]`, which is
3294    /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3295    /// answer for the same `p`.
3296    bases: [u32; 2],
3297    /// Whether a frame has already pointed this entry at a half of the region
3298    /// it now names.
3299    ///
3300    /// **What makes the previous base meaningful.** The half a frame did not
3301    /// write holds whatever its reservation came with until a dispatch fills
3302    /// it, so an object's first frame out of a region has no previous
3303    /// deformation to point at — naming that half would give it a motion vector
3304    /// against undefined vertices. Such an entry is put at rest instead, which
3305    /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3306    /// applies to `previous_transform` for the same reason: a spawn did not
3307    /// travel from anywhere.
3308    ///
3309    /// **Cleared again by a frame whose skinning cull skipped its region**,
3310    /// whose halves then hold poses from before the skip — see
3311    /// [`ForwardRenderer::cull_skinned_regions`]. So an object coming back
3312    /// into view is at rest for one frame, exactly as a fresh one is.
3313    pointed: bool,
3314}
3315
3316/// [`SkinnedInstanceDesc::bounds`] as the record carries it: the
3317/// [`OWNS_BOUNDS`](mesh::GpuInstance::OWNS_BOUNDS) bit and the box's two
3318/// corners, or no bit and a zeroed box the culls do not read.
3319///
3320/// # Errors
3321///
3322/// [`InstancePoolError::InvalidBounds`] for a box with a non-finite corner or
3323/// with `min` past `max` on any axis — see [`SkinnedInstanceDesc::bounds`].
3324fn bounds_fields(bounds: Option<Aabb>) -> Result<(u32, [f32; 3], [f32; 3]), InstancePoolError> {
3325    let Some(bounds) = bounds else {
3326        return Ok((0, [0.0; 3], [0.0; 3]));
3327    };
3328    // `min <= max` is false for a NaN lane as well as for an inverted one, and
3329    // `is_finite` is what refuses an infinity, which orders but cannot be
3330    // carried through a transform without becoming one.
3331    if !(bounds.min.is_finite() && bounds.max.is_finite() && bounds.min.cmple(bounds.max).all()) {
3332        return Err(InstancePoolError::InvalidBounds {
3333            min: bounds.min.to_array(),
3334            max: bounds.max.to_array(),
3335        });
3336    }
3337    Ok((
3338        mesh::GpuInstance::OWNS_BOUNDS,
3339        bounds.min.to_array(),
3340        bounds.max.to_array(),
3341    ))
3342}
3343
3344/// [`bounds_fields`] for [`ForwardRenderer::set_skinned_instance`], which has
3345/// no `Result` to return it through: the renderer's answer to a description it
3346/// cannot use is a panic naming it, as for a material index past the end of the
3347/// scene.
3348fn bounds_fields_or_panic(bounds: Option<Aabb>) -> (u32, [f32; 3], [f32; 3]) {
3349    bounds_fields(bounds).unwrap_or_else(|error| panic!("{error}"))
3350}
3351
3352/// The two base vertices an object drawn out of `mesh` alternates between, in
3353/// [`SkinnedInstance::bases`]' indexing.
3354fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3355    mesh.region().halves()
3356}
3357
3358/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3359/// generator is handed to the rollback.
3360struct TileBuffers {
3361    runs: Vec<BufferHandle>,
3362    args: Vec<BufferHandle>,
3363    cull_params: Vec<BufferHandle>,
3364    cull_stats: Vec<BufferHandle>,
3365    /// This cull's own hysteresis state, and not the camera's.
3366    ///
3367    /// A shadow view selects from the camera's eye at the camera's scale, like
3368    /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3369    /// it reaches a different answer for the same group, and an answer carried
3370    /// between frames needs somewhere of its own to be carried. Sharing the
3371    /// camera's buffer would be two rules writing one history and each undoing
3372    /// the other's band every frame.
3373    ///
3374    /// One per cull rather than one for the shadow pass, even though every one of
3375    /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3376    /// between them would be several dispatches writing one element with nothing
3377    /// ordering them.
3378    ///
3379    /// **This is what a cull costs that is not a dispatch.** It is
3380    /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3381    /// resident group count words of device-local
3382    /// memory, held for the renderer's whole life whether anything is drawn
3383    /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3384    /// budget rather than "however many lights the scene has" — and the reason a
3385    /// point light's six faces share one of these rather than owning six.
3386    group_state: BufferHandle,
3387}
3388
3389impl ForwardRenderer {
3390    /// Builds both pipelines and makes [`scene::demo`] resident.
3391    ///
3392    /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3393    /// nothing else — so the frame this draws is the one the golden suite has
3394    /// always compared, and every existing caller is untouched.
3395    ///
3396    /// `target_format` must be the format the tonemap pass will render into —
3397    /// dynamic rendering checks pipeline and attachment formats against each
3398    /// other at pass-begin time, not at creation.
3399    ///
3400    /// # Errors
3401    ///
3402    /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3403    pub fn new(
3404        device: &dyn Device,
3405        queue: QueueHandle,
3406        target_format: Format,
3407    ) -> Result<Self, HalError> {
3408        Self::with_scene(device, queue, target_format, &scene::demo())
3409    }
3410
3411    /// Builds both pipelines and makes `scene` resident.
3412    ///
3413    /// Everything in the description is created here and never grows: the
3414    /// geometry pools, the cluster pool, the material table, the page, the
3415    /// instance array and the bucket table are all sized and filled once. See
3416    /// [`crate::scene`] for why that split is where the seam is, and for the
3417    /// four places a description's *order* decides what the frame looks like.
3418    ///
3419    /// `target_format` must be the format the tonemap pass will render into —
3420    /// dynamic rendering checks pipeline and attachment formats against each
3421    /// other at pass-begin time, not at creation.
3422    ///
3423    /// # No description is too small
3424    ///
3425    /// One mesh and one material row is a scene, and so is
3426    /// [`scene::demo`]'s four and three. Nothing on this type names a
3427    /// description entry by position any more — the five `set_*` demo wrappers
3428    /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3429    /// and the row a caller wrote its **own** description in.
3430    ///
3431    /// # Errors
3432    ///
3433    /// [`HalError::InvalidDescriptor`] if the description cannot be made
3434    /// resident as written: a page layer that is not its kind's extent's worth of
3435    /// RGBA8, a page kind holding layers at no extent, a material row naming a
3436    /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3437    /// levels, a cluster array with a read outside itself in it (see
3438    /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3439    /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3440    /// capacity and what the description needs, because the answer to it is to
3441    /// raise the number. Every one of those is settled **before the first device
3442    /// object exists**, so a refusal leaks nothing.
3443    ///
3444    /// [`HalError`] otherwise, from any seam call — including the geometry a
3445    /// pool refuses for itself, such as vertex bytes that are not a whole number
3446    /// of vertices. A backend that cannot build a pipeline says so here rather
3447    /// than drawing nothing later, and a failure part-way through releases
3448    /// everything already created, so a caller that retries or exits leaves
3449    /// nothing behind.
3450    pub fn with_scene(
3451        device: &dyn Device,
3452        queue: QueueHandle,
3453        target_format: Format,
3454        scene: &SceneDesc<'_>,
3455    ) -> Result<Self, HalError> {
3456        Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3457    }
3458
3459    /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3460    /// the build so the thread running it can keep its window alive.
3461    ///
3462    /// # What it is for: a build on the thread that owns the window
3463    ///
3464    /// The build needs the device, so it runs on whichever thread holds it —
3465    /// for a game that is the loop thread, which also owns the window, and a
3466    /// desktop marks a window hung when its thread takes no message for a few
3467    /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3468    /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3469    /// whole build.
3470    ///
3471    /// # Where it is called
3472    ///
3473    /// Where the time is, which was measured rather than guessed. With a cold
3474    /// driver shader cache — a player's first launch, or the first after a
3475    /// driver update — **pipeline creation is most of the build**. Measured in
3476    /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3477    /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3478    /// mesh and page uploads took about 0.1 s either way. So `service` runs
3479    /// after every mesh upload (each level of a DAG), after every page layer's
3480    /// mip chain and each page's upload, after each of the camera's
3481    /// post-processing subsystems, before every round of the mesh-pass
3482    /// pipelines, and between the build's other phases. The water and grass
3483    /// passes are not built here: the first frame with a body or a field
3484    /// builds them, unless the caller builds them first under the same kind of
3485    /// `service` with [`prepare_content`](Self::prepare_content).
3486    ///
3487    /// **The longest gap left is about one pipeline**, and a pipeline cannot be
3488    /// split: on that scene, cold, it was the forward pass's colour pipeline
3489    /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3490    /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3491    /// eight times slower under contention still calls back inside the five
3492    /// seconds Windows allows.
3493    ///
3494    /// **One condition on that bound.** The mesh-pass pipelines are compiled
3495    /// as one batch on a device that can take them from several
3496    /// threads, in rounds of a small fixed number of pipelines with `service`
3497    /// on this thread before each — see `crate::pipeline_batch`. A driver that
3498    /// compiles side by side finishes a round in about its slowest compile, so
3499    /// the bound holds. One that serialises its compiles internally takes a
3500    /// whole round's worth between two calls, which is still bounded — the
3501    /// round is capped — but leaves about a quarter of the headroom above: a
3502    /// machine twice as slow rather than eight times. On a device that cannot take
3503    /// pipelines from several threads, `service` runs before each pipeline as
3504    /// it always did.
3505    ///
3506    /// `service` sees nothing of the build and cannot touch the renderer or the
3507    /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3508    /// request — is the caller's to keep for later, as
3509    /// `crcbl_shell::Shell::keep_alive` does.
3510    ///
3511    /// # Errors
3512    ///
3513    /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3514    /// through releases everything already created.
3515    pub fn with_scene_serviced(
3516        device: &dyn Device,
3517        queue: QueueHandle,
3518        target_format: Format,
3519        scene: &SceneDesc<'_>,
3520        service: &mut dyn FnMut(),
3521    ) -> Result<Self, HalError> {
3522        Self::build_on_path(
3523            device,
3524            queue,
3525            target_format,
3526            scene,
3527            device.preferred_geometry_path(),
3528            service,
3529        )
3530    }
3531
3532    /// Builds exactly the requested geometry tail, independently of the device's
3533    /// performance preference. Capabilities remain available to other callers.
3534    ///
3535    /// # Errors
3536    ///
3537    /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3538    /// when the requested tail lacks its required feature. Other failures follow
3539    /// [`Self::with_scene`]'s rollback contract.
3540    pub fn with_scene_on_path(
3541        device: &dyn Device,
3542        queue: QueueHandle,
3543        target_format: Format,
3544        scene: &SceneDesc<'_>,
3545        geometry_path: GeometryPath,
3546    ) -> Result<Self, HalError> {
3547        Self::build_on_path(
3548            device,
3549            queue,
3550            target_format,
3551            scene,
3552            geometry_path,
3553            &mut || {},
3554        )
3555    }
3556
3557    /// The body of [`Self::with_scene_on_path`] and
3558    /// [`Self::with_scene_serviced`], calling `service` where the latter
3559    /// documents.
3560    fn build_on_path(
3561        device: &dyn Device,
3562        queue: QueueHandle,
3563        target_format: Format,
3564        scene: &SceneDesc<'_>,
3565        geometry_path: GeometryPath,
3566        service: &mut dyn FnMut(),
3567    ) -> Result<Self, HalError> {
3568        let required = match geometry_path {
3569            GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3570            GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3571            GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3572        };
3573        let missing = required.difference(device.caps().features);
3574        if !missing.is_empty() {
3575            return Err(HalError::UnsupportedFeatures { missing });
3576        }
3577        crcbl_frame::require_frame_queue(device, queue, "a forward renderer")?;
3578        let mut rollback = Rollback::default();
3579        // **One submission and no wait for the build's small uploads**: the
3580        // placeholders, the split-sum and area-light tables, and every view's
3581        // and shadow cull's start-up fills are recorded into this batch as they
3582        // are created, and submitted once the renderer is whole. Each used to
3583        // be its own submit and `wait_idle`, and on Mesa's ANV the first submit
3584        // on a fresh device costs several milliseconds and every later round
3585        // trip about half of one. The geometry pools, the pages and the probe
3586        // table still submit for themselves, all of them before this batch's
3587        // submission, and none of them reads anything it writes.
3588        //
3589        // The batch is submitted without a wait: every reader of what it
3590        // writes is a frame on this same queue, after it, which is all the
3591        // ordering the copies need — see `PendingUpload`. Its staging is
3592        // retired by the first `begin_frame` that finds its semaphore
3593        // signalled, or waited for by `destroy`.
3594        let mut uploads = UploadBatch::new(device, queue, "forward");
3595        match Self::build(
3596            device,
3597            &mut uploads,
3598            target_format,
3599            scene,
3600            geometry_path,
3601            &mut rollback,
3602            service,
3603        ) {
3604            // The submit is the build's last fallible step, so nothing can
3605            // fail between it and the renderer owning the upload: a failed
3606            // submit leaves nothing pending, and `destroy` finds an empty list.
3607            Ok(mut renderer) => match uploads.submit_deferred() {
3608                Ok(pending) => {
3609                    renderer.uploads_in_flight.push(pending);
3610                    Ok(renderer)
3611                }
3612                Err(error) => {
3613                    renderer.destroy(device);
3614                    Err(error)
3615                }
3616            },
3617            Err(error) => {
3618                // The batch first, so nothing it recorded is still pending when
3619                // the rollback destroys what it recorded into.
3620                drop(uploads);
3621                rollback.run(device);
3622                Err(error)
3623            }
3624        }
3625    }
3626
3627    /// Releases every start-up upload the GPU is known to be past, without
3628    /// blocking — the first thing each `begin_frame` does.
3629    ///
3630    /// # Errors
3631    ///
3632    /// [`HalError`] from reading a semaphore — a lost device. What was not
3633    /// released stays in the list.
3634    fn retire_uploads(&mut self, device: &dyn Device) -> Result<(), HalError> {
3635        let mut index = 0;
3636        while index < self.uploads_in_flight.len() {
3637            if self.uploads_in_flight[index].poll(device)? {
3638                // Retired, so dropping it releases nothing and logs nothing.
3639                drop(self.uploads_in_flight.swap_remove(index));
3640            } else {
3641                index += 1;
3642            }
3643        }
3644        Ok(())
3645    }
3646
3647    /// Blocks until every start-up upload has landed and releases them, before
3648    /// `caller` destroys anything their copies write.
3649    ///
3650    /// A failed wait is a lost device. What it would have released is leaked
3651    /// rather than freed under the GPU, and said so in the log; the caller goes
3652    /// on, as a destroy has nothing to hand an error to.
3653    fn wait_for_uploads(&mut self, device: &dyn Device, caller: &str) {
3654        for mut pending in self.uploads_in_flight.drain(..) {
3655            if let Err(error) = pending.wait(device) {
3656                crcbl_core::log::warn!(
3657                    "ForwardRenderer::{caller}: a start-up upload's wait failed ({error}); its \
3658                     staging buffers are leaked rather than freed under the GPU"
3659                );
3660                // Dropping it is the leak, and it logs one of its own.
3661            }
3662        }
3663    }
3664
3665    /// Everything `build` needs to be true of a description, checked **before
3666    /// the first device object exists**.
3667    ///
3668    /// That placement is the whole design of this function. `build` hands the
3669    /// geometry pool and the material table to the rollback and creates a dozen
3670    /// objects with `?` between them; a check that ran part way down that list
3671    /// would be a new early exit on the wrong side of a handover, and a rejected
3672    /// description would leak two device-local buffers. Run from the top of
3673    /// `build`, a refusal costs nothing to unwind because nothing was made.
3674    ///
3675    /// # Errors
3676    ///
3677    /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3678    /// is wrong with it.
3679    fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3680        let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3681        // A renderer draws meshes, and every table below is sized from them:
3682        // with none, the mesh table's sizing has no level to take a maximum
3683        // of. A scene that draws only the sky is one with meshes and no
3684        // instances.
3685        if scene.meshes.is_empty() {
3686            return refuse(
3687                "a scene description needs at least one mesh; one with meshes and no \
3688                 instances draws only the sky"
3689                    .to_owned(),
3690            );
3691        }
3692        // Every layer's length against its own kind's extent, and layers at no
3693        // extent at all. Checked by the type that owns the page rather than
3694        // here, because that is where a page can be built wrong and where the
3695        // check can be made to fail; see `PageDesc::check`.
3696        scene.page.check()?;
3697        // The probe grid's counts against the rows it carries, which is what
3698        // bounds the shader's fetch. Checked by the type that owns the grid, on
3699        // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3700        scene.probes.check()?;
3701        // A row naming a layer the page does not have is an out-of-range sample,
3702        // which nothing below the seam reports.
3703        //
3704        // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3705        // value: it is a sentinel rather than an index — `0xFFFF`, one past
3706        // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3707        // fragment stage never reads a page for it. Exempting it here is what
3708        // lets a material name no texture without the page having to carry a
3709        // layer for it to point at — or, since row (d), having to exist at all.
3710        //
3711        // **Per kind**, because the kinds are separate images with separate
3712        // layer lists and separate extents: a row pointed at a base-colour layer
3713        // number would pass a check that only counted one of them and then
3714        // sample past the end of the other image.
3715        for (row, material) in scene.materials.iter().enumerate() {
3716            for kind in PageKind::ALL {
3717                let names = match kind {
3718                    PageKind::BaseColor => material.base_color_texture,
3719                    PageKind::Normal => material.normal_texture,
3720                    PageKind::MetallicRoughnessOcclusion => {
3721                        material.metallic_roughness_occlusion_texture
3722                    }
3723                    PageKind::Emissive => material.emissive_texture,
3724                };
3725                if names == mesh::GpuMaterial::NO_PAGE {
3726                    continue;
3727                }
3728                let have = scene.page.layers(kind).len();
3729                if names as usize >= have {
3730                    return refuse(format!(
3731                        "material row {row} samples {} page layer {names}, and that page \
3732                         has {have}",
3733                        kind.label()
3734                    ));
3735                }
3736            }
3737        }
3738
3739        for (index, desc) in scene.meshes.iter().enumerate() {
3740            let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3741                continue;
3742            };
3743            // Zipped together at upload and again at
3744            // `ClusterDag::selection_records`, so a short list would silently
3745            // leave a level's clusters reading the level below's vertices.
3746            if levels.len() != dag.levels.len() {
3747                return refuse(format!(
3748                    "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3749                    desc.label,
3750                    levels.len(),
3751                    dag.levels.len()
3752                ));
3753            }
3754            for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3755                let want = level.positions.len() * mesh::VERTEX_STRIDE;
3756                if bytes.len() != want {
3757                    return refuse(format!(
3758                        "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3759                         position(s), which is {want}",
3760                        desc.label,
3761                        bytes.len(),
3762                        level.positions.len()
3763                    ));
3764                }
3765            }
3766        }
3767
3768        // **Every read the mesh stage makes from a cluster array lands inside
3769        // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3770        // terms exactly — see `MeshClusters::check`, which is where the reason
3771        // it cannot be checked below the seam is argued. Both variants carry
3772        // the same type beside a vertex count, so both are checked the same way.
3773        for (index, desc) in scene.meshes.iter().enumerate() {
3774            let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3775                Geometry::Flat {
3776                    vertices, clusters, ..
3777                } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3778                Geometry::Dag { dag, .. } => dag
3779                    .levels
3780                    .iter()
3781                    .map(|level| (level.positions.len(), &level.clusters))
3782                    .collect(),
3783            };
3784            for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3785                if let Err(fault) = clusters.check(vertices) {
3786                    return refuse(format!(
3787                        "mesh {index} ({}) level {depth} {fault}",
3788                        desc.label
3789                    ));
3790                }
3791            }
3792        }
3793
3794        // **Capacity, summed over the whole description**, which is the one
3795        // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3796        // do refuse their own overflow, but they refuse it part way through
3797        // filling something that already exists, and the pair of numbers
3798        // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3799        // carries to tell fragmentation from a full pool says nothing *here*:
3800        // the pool was created empty a few lines below, nothing has been freed
3801        // in it, so its free list is one block and the largest block and the
3802        // total are the same number. At build the answer is always "raise this
3803        // capacity", so it is said by name and before anything is created.
3804        let mut vertices: u64 = 0;
3805        let mut indices: u64 = 0;
3806        for desc in &scene.meshes {
3807            match &desc.geometry {
3808                Geometry::Flat {
3809                    vertices: bytes,
3810                    indices: list,
3811                    ..
3812                } => {
3813                    // Bytes that are not a whole number of vertices are the
3814                    // pool's to refuse, and it refuses before it allocates.
3815                    vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3816                    indices += list.len() as u64;
3817                }
3818                Geometry::Dag { levels, dag, .. } => {
3819                    for bytes in levels {
3820                        vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3821                    }
3822                    for level in &dag.levels {
3823                        // The call the upload itself makes, so the two cannot
3824                        // disagree about what a level costs.
3825                        indices += level.indices().len() as u64;
3826                    }
3827                }
3828            }
3829        }
3830        let entries: u64 = scene
3831            .meshes
3832            .iter()
3833            .map(|desc| desc.geometry.levels() as u64)
3834            .sum();
3835        for (pool, needed, capacity) in [
3836            ("vertex pool", vertices, scene.capacities.vertices),
3837            ("index pool", indices, scene.capacities.indices),
3838            ("mesh table", entries, scene.capacities.meshes),
3839            (
3840                "material table",
3841                scene.materials.len() as u64,
3842                scene.capacities.materials,
3843            ),
3844            (
3845                "probe table",
3846                scene.probes.probes.len() as u64,
3847                scene.capacities.probes,
3848            ),
3849        ] {
3850            if needed > u64::from(capacity) {
3851                return refuse(format!(
3852                    "the {pool} holds {capacity} and the description needs {needed}"
3853                ));
3854            }
3855        }
3856        Ok(())
3857    }
3858
3859    /// The body of [`ForwardRenderer::with_scene`], recording what it has
3860    /// created into `rollback` as it goes and calling `service` where
3861    /// [`ForwardRenderer::with_scene_serviced`] documents.
3862    ///
3863    /// The small start-up uploads go into `uploads`, which the caller submits
3864    /// once this has returned the renderer — nothing here may read them on the
3865    /// GPU first. What still submits for itself takes the batch's queue.
3866    fn build(
3867        device: &dyn Device,
3868        uploads: &mut UploadBatch<'_>,
3869        target_format: Format,
3870        scene: &SceneDesc<'_>,
3871        geometry_path: GeometryPath,
3872        rollback: &mut Rollback,
3873        service: &mut dyn FnMut(),
3874    ) -> Result<Self, HalError> {
3875        // Before anything exists, so a refused description leaks nothing — see
3876        // `check_scene`, which is where that placement is argued.
3877        Self::check_scene(scene)?;
3878        let queue = uploads.queue();
3879
3880        // Resolved before anything is created, because it decides the *shape*
3881        // of what is created — the bind group layout, which pipeline kind the
3882        // pass builds, and what a bucket's constant block says. A device on the
3883        // mesh path never builds the raster pipeline and a device on either
3884        // indirect tail never builds the mesh one, which is what makes "the
3885        // frame came out of the mesh stage" a fact about the object graph
3886        // rather than a claim about a branch.
3887        let emit = EmitTail::from_path(geometry_path);
3888        // And whether that tail draws a range of buckets per call, which only
3889        // changes what the passes record — the constant blocks carry the words
3890        // both shapes read — so it decides nothing about what is created.
3891        let range_limit = emit.range_limit(&device.caps());
3892        // **A second capability, asked separately.** `Features::TASK_SHADER` is
3893        // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3894        // amplification stage this renderer builds where the device has one and
3895        // leaves out where it does not — and a device without it keeps drawing
3896        // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3897        // nothing and emits every cluster. Same picture, more work.
3898        let culls_clusters = emit.is_mesh()
3899            && device
3900                .caps()
3901                .features
3902                .contains(crcbl_hal::Features::TASK_SHADER);
3903
3904        let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3905        // What an `InstanceDesc::mesh` index resolves through: one id per
3906        // description mesh, in description order, and each of them that mesh's
3907        // **level 0** whatever the path — because it is the entry the cull pass
3908        // reads a bounding box out of, and a DAG's coarser levels approximate
3909        // the same surface inside the same box.
3910        let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3911        // The scene's own triangles, kept for the probe-visibility capture and
3912        // for nothing else — and kept at all only when the description reserves
3913        // a probe, so a scene without one pays no memory for this rung. Taken
3914        // here because `scene` is the caller's and is read once.
3915        let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3916        // The same list one level down: what a caller reserving a skinned region
3917        // names its mesh with. Read here beside the ids rather than from
3918        // `residents` later, because the descriptions this came from are the
3919        // caller's and are read once.
3920        let skinnable_meshes: Vec<Option<MeshHandle>> =
3921            residents.iter().map(|mesh| mesh.skinnable).collect();
3922        // The handles are `Copy`, so they can be read out before the pool
3923        // becomes the rollback's — which it must be before the first `?` below,
3924        // or a failed pipeline would leak two device-local buffers. The index
3925        // pool is not named here at all: it is bound at draw time rather than
3926        // descriptor-written, so only the vertex pool and the mesh table reach a
3927        // bind group.
3928        let vertices = pool.vertex_buffer();
3929        let mesh_table = pool.table_buffer();
3930        rollback.pool = Some(pool);
3931
3932        // §3.2's texture side, before the table that indexes it: a material row
3933        // is written with a layer number, so the layer has to exist to be named.
3934        //
3935        // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3936        // three answers the kind itself owns — its format, its mip filter and
3937        // its device label — and everything else about creating a page is the
3938        // same code. Two hand-written copies were what let the normal page be
3939        // created through the colour page's filter for as long as nobody
3940        // compared the two, and rung 3 adds two more kinds to get wrong.
3941        //
3942        // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3943        // normal page, and that is the colour-space decision.** A base-colour
3944        // description's texels are sRGB-encoded, which is what glTF defines a
3945        // base-colour texture to be, so the format is what makes the sampler
3946        // decode them — and `mesh.slang` then multiplies a linear texel by a
3947        // linear `base_color` and lights in linear, exactly as it did before
3948        // there was a texture. A normal texel is a *number* and nothing decodes
3949        // it. See `PageKind::format`, and topic 44's rung 2.
3950        //
3951        // Every layer's length against its kind's extent was settled by
3952        // `check_scene` above, before this device object existed.
3953        //
3954        // **Every layer goes up with its mip chain**, built here on the host by
3955        // [`crate::mip`] — topic 43's filtering rung.
3956        // The chain is what a trilinear sampler needs to stop shimmering on a
3957        // minified surface, and it is built at upload rather than by a compute
3958        // pass because the page's format is what decodes it and a host chain is
3959        // the same bytes on every backend.
3960        //
3961        // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3962        // refuses a zero-layer image and every bind group has to fill both page
3963        // bindings, so a page nothing names is created 1×1 in its own format
3964        // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3965        // and which is magenta so that a frame says so if it ever does.
3966        //
3967        // The upload itself is [`upload_page`], shared with
3968        // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3969        // renderer is built exactly as this one was. A layer's chain is host
3970        // work proportional to its texels, so a page of many large layers is
3971        // serviced one layer at a time.
3972        let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3973        let mut page_extents = [(1, 1); PageKind::ALL.len()];
3974        let mut page_layers = [0; PageKind::ALL.len()];
3975        for kind in PageKind::ALL {
3976            let layers = scene.page.layers(kind);
3977            let (page, extent) = upload_page(
3978                device,
3979                queue,
3980                kind,
3981                scene.page.extent(kind),
3982                layers,
3983                service,
3984            )?;
3985            rollback.textures.push(page);
3986            page_extents[kind.index()] = (extent, extent);
3987            page_layers[kind.index()] = layers.len();
3988            pages[kind.index()] = Some(page);
3989            service();
3990        }
3991        let [
3992            Some(base_color_page),
3993            Some(normal_page),
3994            Some(mro_page),
3995            Some(emissive_page),
3996        ] = pages
3997        else {
3998            unreachable!("the loop above fills a slot for every PageKind::ALL entry");
3999        };
4000
4001        // The page's sampler at the device's default — see `create_page_sampler`
4002        // for what it filters, and `set_anisotropy` for how a caller moves it.
4003        let anisotropy = Self::anisotropy_for(&device.caps());
4004        let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
4005        rollback.samplers.push(base_color_sampler);
4006        // What every slot's groups are built naming, and what each moves off
4007        // only at its own frame — see `ForwardRenderer::adopt_pages`.
4008        let page_bindings = PageBindings {
4009            sampler: base_color_sampler,
4010            views: [
4011                base_color_page.view,
4012                normal_page.view,
4013                mro_page.view,
4014                emissive_page.view,
4015            ],
4016        };
4017
4018        // The material table, before the instances: an instance is written with
4019        // the material id it carries, so the row has to exist to be named.
4020        let (materials, material_ids) = Self::build_materials(device, scene)?;
4021        let material_buffer = materials.buffer();
4022        rollback.materials = Some(materials);
4023
4024        // Topic 50's irradiance grid: the table is created here once, and
4025        // `crate::probe_gather`'s compute pass rewrites its rows every frame —
4026        // see [`crate::probe`]. **Created even for a description with no probes**, because
4027        // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
4028        // honest filler for "no probes were authored" is the zeroed row the
4029        // shader's clamp lands on.
4030        let probe_table = ProbeTable::new(
4031            device,
4032            queue,
4033            &ProbeTableDesc {
4034                label: Some("forward"),
4035                capacity: scene.capacities.probes,
4036                frames: FRAMES_IN_FLIGHT,
4037            },
4038        )?;
4039        // Into the rollback before it is filled, so a copy that fails releases
4040        // the buffers rather than leaking them.
4041        rollback.probes = Some(probe_table);
4042        let probe_table = rollback.probes.as_ref().expect("just stored");
4043        probe_table.fill(device, queue, &scene.probes.probes)?;
4044        // Read out here, like the instance ring's below and for the same
4045        // reason: the handles are `Copy`, and the loop that builds the bind
4046        // groups mutates the rollback the table now lives in.
4047        let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
4048            .map(|frame| probe_table.buffer(frame))
4049            .collect();
4050        // The irradiance probes' updater, built **only** for a
4051        // description that asked for it. A volume left at
4052        // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
4053        // the default really is the frame every scene drew before this landed.
4054        let probe_gather = match scene.probes.update {
4055            ProbeUpdate::Authored => None,
4056            ProbeUpdate::EveryFrame => Some(ProbeGather::new(
4057                device,
4058                &ProbeGatherDesc {
4059                    label: Some("forward probes"),
4060                    volume: scene.probes.volume,
4061                    probes: &probe_buffers,
4062                },
4063            )?),
4064        };
4065        rollback.probe_gather = probe_gather;
4066        let probe_gather = rollback.probe_gather.take();
4067        service();
4068
4069        // **Empty.** Every object in the scene arrives through
4070        // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
4071        // renderer that inserted one of its description's meshes here would put
4072        // an object in a caller's frame that the caller never asked for.
4073        let instances = InstancePool::new(
4074            device,
4075            &InstancePoolDesc {
4076                label: Some("forward instances"),
4077                capacity: scene.capacities.instances,
4078                frames_in_flight: FRAMES_IN_FLIGHT,
4079            },
4080        )?;
4081        // Same handle-then-hand-over dance as the geometry pool above: the
4082        // buffers are `Copy` and are read out before the pool becomes the
4083        // rollback's, which it must be before the first `?` below — after which
4084        // nothing needs the pool again until `begin_frame`.
4085        let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
4086        rollback.instances = Some(instances);
4087
4088        // The two compute passes, and the buffers the draws come out of. Built
4089        // here rather than beside the pipelines below because the mesh bind
4090        // group names one of its buffers, so it has to exist first.
4091        //
4092        // The bucket table, and the one place its order is decided.
4093        //
4094        // **Built by walking the description**, which is what makes a duplicate
4095        // structurally impossible rather than refused: every bucket's mesh id is
4096        // the id of the description mesh it came from, and two description
4097        // meshes are two uploads with two table entries however alike their
4098        // geometry is. That matters because `draw_gen.slang`'s scatter takes the
4099        // *first* bucket whose mesh id matches, so a second bucket naming one
4100        // mesh would never draw anything at all.
4101        //
4102        // One bucket per mesh, except for two things. A DAG is one bucket where
4103        // an amplification stage picks its cut per cluster and one per level
4104        // where the cull pass picks a uniform one — see [`buckets_for`]. And the
4105        // whole run is repeated once per **material mode** the scene holds, so
4106        // an instance's mode picks a bucket exactly as its mesh does; see
4107        // [`ForwardRenderer::bucket_modes`].
4108        //
4109        // **Mode-major: every mesh's run for one mode, then the next mode's.**
4110        // A mode picks the pipeline a pass binds, so this makes each pipeline's
4111        // partition — [`ForwardRenderer::depth_partitions`] and
4112        // [`ForwardRenderer::sided_partitions`] — one contiguous run of
4113        // buckets, which a device with a draw index records as one ranged call
4114        // rather than a call per bucket — and which the mesh tail behind a
4115        // task stage must have, because it draws each partition as one flat
4116        // call of its run. `DEPTH_MODES` order makes a sided partition one run
4117        // too: opaque sits beside masked, and double-sided beside both.
4118        //
4119        // **Once per mode the scene holds, not once per mode that exists.** A
4120        // scene whose materials are all opaque gets exactly the table it always
4121        // had — same length, same order, same bytes — so the twin costs nothing
4122        // where nothing is masked, which is every demo and every golden here. A
4123        // bucket is not free: every pass records one indirect call per bucket
4124        // per view, and every generator holds its run start.
4125        let scene_modes: Vec<u32> = {
4126            let held: Vec<u32> = DEPTH_MODES
4127                .into_iter()
4128                .filter(|mode| {
4129                    scene
4130                        .materials
4131                        .iter()
4132                        .any(|material| material.mode() == *mode)
4133                })
4134                .collect();
4135            // A description with no materials at all still needs a bucket per
4136            // mesh, or nothing it holds can be drawn.
4137            if held.is_empty() {
4138                vec![DEPTH_MODES[0]]
4139            } else {
4140                held
4141            }
4142        };
4143        // One mode's run: every description mesh's levels, in description
4144        // order. `bucket_bases` is where each mesh starts within it, so the
4145        // tables below can be filled in mesh by mesh rather than by re-deriving
4146        // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
4147        let mut mode_run: Vec<u32> = Vec::new();
4148        let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
4149        for resident in &residents {
4150            bucket_bases.push(mode_run.len());
4151            mode_run
4152                .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
4153        }
4154        let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
4155        // The mode each of those buckets draws, in step with it.
4156        let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
4157        for mode in &scene_modes {
4158            bucket_meshes.extend_from_slice(&mode_run);
4159            bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
4160        }
4161        let bucket_count = u32::try_from(bucket_meshes.len())
4162            .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
4163
4164        // Topic 25's selection tables, and the one thing that
4165        // decides whether `draw_gen.slang` takes a uniform cut at all.
4166        //
4167        // Every mesh id gets an entry, because the shader indexes this with
4168        // `GpuInstance::mesh` and an instance can name any of them; the default
4169        // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
4170        // so a mesh with no hierarchy resolves back to itself with no branch.
4171        // **A DAG keeps that default on the mesh path**, which is how a device
4172        // already descending it per cluster avoids a second, coarser cut on top
4173        // of it — the suppression is data rather than a branch in the shader.
4174        //
4175        // **Sized by the mesh table's capacity, not by the meshes resident in
4176        // it**, because that is the invariant `draw_gen.slang`'s
4177        // `mesh_levels_of` states and indexes on: "every entry an instance can
4178        // name is filled". The read is unbounded and an instance's mesh id is a
4179        // bare table index, so a table sized to the description alone is an
4180        // out-of-range read of whatever the packer laid down next for any id the
4181        // description did not fill. What it finds there decides the frame: zeros
4182        // resolve to mesh 0 and draw another mesh's geometry, and a live
4183        // `group_count` sends `select_level`'s loop over a count no allocation
4184        // backs, which on radv is a hard GPU recovery rather than a wrong
4185        // picture. That is not a hypothetical: it is what a skinned instance
4186        // naming an alias entry did until 2026-08, before it learned to name its
4187        // source mesh instead.
4188        let table_len = usize::try_from(scene.capacities.meshes)
4189            .unwrap_or(usize::MAX)
4190            .max(
4191                usize::try_from(
4192                    residents
4193                        .iter()
4194                        .flat_map(|resident| resident.levels.iter().copied())
4195                        .max()
4196                        .unwrap_or_else(|| {
4197                            unreachable!("check_scene refused an empty description")
4198                        })
4199                        + 1,
4200                )
4201                .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
4202            );
4203        let mut level_meshes: Vec<u32> = (0..table_len)
4204            .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4205            .collect();
4206        let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4207            .iter()
4208            .map(|&id| level_select::MeshLevels {
4209                first_level: id,
4210                ..level_select::MeshLevels::FLAT
4211            })
4212            .collect();
4213        // Every DAG's groups end to end, in description order, and where each
4214        // one's run starts. `ClusterSelect` records name a group by its index in
4215        // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4216        // several DAGs concatenate without `crcbl-shaders` knowing they did.
4217        let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4218        let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4219        for (index, desc) in scene.meshes.iter().enumerate() {
4220            first_groups.push(
4221                u32::try_from(level_groups.len())
4222                    .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4223            );
4224            let Geometry::Dag { dag, .. } = &desc.geometry else {
4225                continue;
4226            };
4227            let groups = dag.level_groups();
4228            let id = residents[index].id();
4229            mesh_levels[id as usize] = level_select::MeshLevels {
4230                first_group: first_groups[index],
4231                group_count: u32::try_from(groups.len())
4232                    .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4233                // **The mesh path suppresses the uniform cut with a top level of
4234                // zero, not with a group count of zero**, and the difference is
4235                // the hysteresis state: `draw_gen.slang` judges every group it is
4236                // given whatever level it answers, and the amplification stage
4237                // reads those answers. A record naming no groups would leave the
4238                // state untouched and every cluster of the patch collapsed. A
4239                // top level of zero makes the level loop's minimum unreachable,
4240                // so the instance routes to the mesh it already names — which is
4241                // level 0.
4242                first_level: if emit.is_mesh() {
4243                    id
4244                } else {
4245                    u32::try_from(level_meshes.len())
4246                        .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4247                },
4248                top_level: if emit.is_mesh() {
4249                    0
4250                } else {
4251                    u32::try_from(residents[index].levels.len() - 1)
4252                        .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4253                },
4254            };
4255            level_groups.extend(groups);
4256            if !emit.is_mesh() {
4257                level_meshes.extend_from_slice(&residents[index].levels);
4258            }
4259        }
4260
4261        // §3.5's clusters, on the path that reads them and on no other. The
4262        // records are `crcbl-shaders`' — cooked, because the builder is
4263        // `crcbl-scene`'s and the renderer must not depend on that crate — and
4264        // they arrive in bucket-mesh order so a bucket's range is its own
4265        // index. See `crate::cluster_pool`.
4266        //
4267        // Before the draw generation below rather than after it, because the
4268        // per-bucket cluster counts are the x extent of each bucket's mesh
4269        // dispatch and that pass writes the argument structure carrying them.
4270        let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4271        let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4272        let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4273        if emit.is_mesh() {
4274            // A flat mesh is one pool entry and its clusters carry
4275            // `ClusterSelect::ALWAYS`, so the descent draws them from every
4276            // camera; a DAG is **one entry per level**, laid end to end.
4277            let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4278            // Where each description mesh's entries start, on `bucket_bases`'
4279            // terms — the two differ exactly where a DAG's levels are one bucket
4280            // and several entries.
4281            let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4282            for (index, desc) in scene.meshes.iter().enumerate() {
4283                entry_bases.push(cooked.len());
4284                match &desc.geometry {
4285                    Geometry::Flat { clusters, .. } => {
4286                        cooked.push(PooledMesh::without_lod(clusters.clone()));
4287                    }
4288                    Geometry::Dag { dag, .. } => {
4289                        let selection = dag
4290                            .selection_records(&residents[index].vertex_bases, first_groups[index]);
4291                        for (level, records) in dag.levels.iter().zip(selection) {
4292                            cooked.push(PooledMesh {
4293                                clusters: level.clusters.clone(),
4294                                selection: records,
4295                            });
4296                        }
4297                    }
4298                }
4299            }
4300
4301            let clusters = ClusterPool::new(device, "forward", &cooked)?;
4302            let range = |entry: usize| {
4303                clusters
4304                    .range(entry)
4305                    .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4306            };
4307            // **A DAG's levels are one run, not one per bucket.** `concatenate`
4308            // lays the entries down in the order it was given them, so the
4309            // levels are contiguous: the bucket starts where level 0 does and
4310            // reaches to the end of the last level. That is what lets one
4311            // dispatch cover a cut spanning several of them — and it is why a
4312            // flat mesh, whose one entry is the whole sum, needs no second case.
4313            mesh_clusters.reserve(residents.len());
4314            for (index, resident) in residents.iter().enumerate() {
4315                let entry = entry_bases[index];
4316                let base = range(entry).base;
4317                let count: u32 = (entry..entry + resident.levels.len())
4318                    .map(|entry| range(entry).count)
4319                    .sum();
4320                // **Every one of this mesh's buckets, not only the first.** A
4321                // mode twin draws the same geometry, so it dispatches over the
4322                // same clusters; a twin left at zero launches no workgroup and
4323                // its instances vanish from the frame. One bucket per mode here,
4324                // because the mesh path takes `buckets_for` of one, each a whole
4325                // mode's run past the one before.
4326                for slot in 0..scene_modes.len() {
4327                    let bucket = slot * mode_run.len() + bucket_bases[index];
4328                    bucket_cluster_bases[bucket] = base;
4329                    bucket_clusters[bucket] = count;
4330                }
4331                mesh_clusters.push(ClusterRange { base, count });
4332            }
4333
4334            rollback.clusters = Some(clusters);
4335            service();
4336        }
4337
4338        // One ring per shadow view, indexed `[view][frame]`: topic 25's
4339        // observable, one word per resident cluster holding the cut the descent
4340        // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4341        // share the camera's, which [`View::build`] allocates beside its cull.
4342        //
4343        // Allocated on the whole mesh path rather than only where there is an
4344        // amplification stage to write them, because the layout declares
4345        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4346        let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4347        if emit.is_mesh() {
4348            let count = rollback
4349                .clusters
4350                .as_ref()
4351                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4352                .count();
4353            let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4354                let mut buffers = Vec::with_capacity(instance_buffers.len());
4355                for frame in 0..instance_buffers.len() {
4356                    let buffer = device.create_buffer(&BufferDesc {
4357                        label: Some(&format!("{label} {frame}")),
4358                        size: u64::from(count) * 4,
4359                        usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4360                        memory: MemoryLocation::DeviceLocal,
4361                    })?;
4362                    rollback.buffers.push(buffer);
4363                    buffers.push(buffer);
4364                }
4365                Ok(buffers)
4366            };
4367            for view in 0..SHADOW_VIEWS {
4368                tile_selection.push(ring(&format!("shadow selection {view}"))?);
4369            }
4370        }
4371
4372        // --- the mesh pass ---
4373        //
4374        // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4375        // because a lit mesh is not a Tier A feature. The bindless shape — a
4376        // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4377        // texture array — is topic 03's, at P3.
4378        // **Which stage pulls the geometry**, and the only thing the two shapes
4379        // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4380        // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4381        // and every backend refuses a layout carrying it on a device without
4382        // `Features::MESH_SHADER` — which is exactly the device that never
4383        // reaches this arm.
4384        //
4385        // **`TASK` joins it when there is an amplification stage**, and the
4386        // union is deliberately over every binding rather than the eight
4387        // `taskMain` actually reads. Slang's Metal backend materialises every
4388        // global in every entry point of a module — the argument bindings 6 to
4389        // 8 already carry — so a layout that named only the task stage's own
4390        // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4391        // runner this team cannot debug on.
4392        let geometry = match (emit.is_mesh(), culls_clusters) {
4393            (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4394            (true, false) => ShaderStages::MESH,
4395            (false, _) => ShaderStages::VERTEX,
4396        };
4397        let mut mesh_entries = vec![
4398            BindGroupLayoutEntry {
4399                binding: 0,
4400                visibility: geometry.union(ShaderStages::FRAGMENT),
4401                kind: BindingKind::UniformBuffer { dynamic: false },
4402                count: 1,
4403                flags: BindingFlags::empty(),
4404            },
4405            BindGroupLayoutEntry {
4406                binding: 1,
4407                // **Both stages, and here it is the FRAGMENT half that needs
4408                // saying** — binding 6 and 7 are the mirror image, where the
4409                // fragment stage plainly reads the row and the vertex half is
4410                // the one Slang forces. Slang's Metal backend materialises
4411                // every module global into every entry point, so
4412                // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4413                // its body dereferences it or not — and Metal's debug layer
4414                // answers a declared-but-unbound fragment argument with
4415                // `missing Buffer binding at index N`, once per draw. Vulkan,
4416                // D3D12 and WebGPU all accept a visibility wider than the
4417                // shader's reads, so naming FRAGMENT costs them nothing but the
4418                // entry itself.
4419                //
4420                // **It does not cost a redundant bind on Metal either**, and
4421                // that is what makes it safe rather than a trade: `crcbl-mtl`
4422                // consults `MTLPipelineOption::BindingInfo` reflection and
4423                // issues the fragment-stage bind only where `MTLBinding::isUsed`
4424                // says the compiled function kept the argument. This entry is
4425                // the permission; the reflection is the decision.
4426                visibility: geometry.union(ShaderStages::FRAGMENT),
4427                kind: BindingKind::StorageBuffer {
4428                    // The shader says `StructuredBuffer`, not
4429                    // `RWStructuredBuffer`, so this is the truth rather than a
4430                    // hint — and it is what lets the graph merge read-after-read.
4431                    read_only: true,
4432                    dynamic: false,
4433                    stride: size_of::<u32>() as u32,
4434                },
4435                count: 1,
4436                flags: BindingFlags::empty(),
4437            },
4438            BindGroupLayoutEntry {
4439                binding: 2,
4440                // Both stages, for binding 1's reason exactly.
4441                visibility: geometry.union(ShaderStages::FRAGMENT),
4442                kind: BindingKind::StorageBuffer {
4443                    // `StructuredBuffer` again: the vertex stage reads its
4444                    // instance and writes nothing. The *host* writes this one
4445                    // every frame, which is a mapped write rather than a shader
4446                    // one and does not make it read-write here.
4447                    read_only: true,
4448                    dynamic: false,
4449                    stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4450                },
4451                count: 1,
4452                flags: BindingFlags::empty(),
4453            },
4454            BindGroupLayoutEntry {
4455                binding: 3,
4456                // Both stages, for binding 1's reason exactly.
4457                visibility: geometry.union(ShaderStages::FRAGMENT),
4458                // `dynamic: true`, and it is the whole mechanism: it is what
4459                // lets a draw say where its run of instances starts without
4460                // `draw_indexed`'s own base instance, which the module docs and
4461                // `mesh.slang`'s header explain the targets disagree about.
4462                // Same shape, for the same reason, as `crate::sprite_pass`'s.
4463                kind: BindingKind::UniformBuffer { dynamic: true },
4464                count: 1,
4465                flags: BindingFlags::empty(),
4466            },
4467            BindGroupLayoutEntry {
4468                binding: 4,
4469                // Both stages, for binding 1's reason exactly.
4470                visibility: geometry.union(ShaderStages::FRAGMENT),
4471                kind: BindingKind::StorageBuffer {
4472                    // The mesh table. `StructuredBuffer` again — the vertex
4473                    // stage looks its mesh up and writes nothing — and one
4474                    // buffer shared by every frame's group, because unlike the
4475                    // instance array nothing rewrites it between frames.
4476                    read_only: true,
4477                    dynamic: false,
4478                    stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4479                },
4480                count: 1,
4481                flags: BindingFlags::empty(),
4482            },
4483            BindGroupLayoutEntry {
4484                binding: 5,
4485                // Both stages, for binding 1's reason exactly.
4486                visibility: geometry.union(ShaderStages::FRAGMENT),
4487                kind: BindingKind::StorageBuffer {
4488                    // The per-bucket runs of surviving instances. Read-only
4489                    // here and written by the draw-argument pass, which is a
4490                    // different bind group and a different pass — the graph is
4491                    // what orders the two.
4492                    read_only: true,
4493                    dynamic: false,
4494                    stride: size_of::<u32>() as u32,
4495                },
4496                count: 1,
4497                flags: BindingFlags::empty(),
4498            },
4499            BindGroupLayoutEntry {
4500                binding: 6,
4501                // **Both stages, and the union is not belt-and-braces.** The
4502                // fragment stage is where `mesh.slang` now reads the table, so
4503                // it plainly needs it — a pipeline layout that leaves it out is
4504                // refused outright by wgpu and reported as
4505                // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4506                // The vertex half has to stay because Slang's Metal backend
4507                // materialises every global in every entry point: `vertexMain`
4508                // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4509                // whether it reads it or not, so dropping VERTEX would break
4510                // Metal alone, on a runner this team cannot debug on.
4511                visibility: geometry.union(ShaderStages::FRAGMENT),
4512                kind: BindingKind::StorageBuffer {
4513                    // The material table. One buffer in every frame's group,
4514                    // like the mesh table above and unlike the instance ring:
4515                    // a material is written when it is created, not per frame.
4516                    read_only: true,
4517                    dynamic: false,
4518                    stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4519                },
4520                count: 1,
4521                flags: BindingFlags::empty(),
4522            },
4523            BindGroupLayoutEntry {
4524                binding: BASE_COLOR_PAGE_BINDING,
4525                // Both stages, for binding 6's reason exactly: the fragment
4526                // stage samples it, and Slang's Metal backend materialises
4527                // every global in every entry point — `vertexMain` in
4528                // `msl/mesh.metal` takes the texture whether it reads it or
4529                // not, so a layout without VERTEX would break Metal alone.
4530                visibility: geometry.union(ShaderStages::FRAGMENT),
4531                // **`D2Array`, and the layout is where wgpu wants to hear it.**
4532                // The other three backends read the dimension off the bound
4533                // view and never consult this; WebGPU compares the two at
4534                // pipeline creation and refuses the pair, which is what a
4535                // layout claiming `D2` over an array view got — "expects
4536                // dimension = D2, but given a view with dimension = D2Array".
4537                kind: BindingKind::SampledImage {
4538                    view_type: ImageViewType::D2Array,
4539                    sample_type: SampleType::Float,
4540                },
4541                // **`count: 1`, and this is the binding-model decision.** One
4542                // `D2Array` image whose *layers* the material rows index is
4543                // `BindingModel::ArrayPages`; an array of `count` descriptors
4544                // indexed per fragment would be `Bindless` and would need
4545                // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4546                // So this layout is legal on every device, exactly as the six
4547                // buffers above are, and no `BindingFlags` appear anywhere in
4548                // this file yet.
4549                count: 1,
4550                flags: BindingFlags::empty(),
4551            },
4552            BindGroupLayoutEntry {
4553                binding: PAGE_SAMPLER_BINDING,
4554                visibility: geometry.union(ShaderStages::FRAGMENT),
4555                kind: BindingKind::Sampler { comparison: false },
4556                count: 1,
4557                flags: BindingFlags::empty(),
4558            },
4559        ];
4560        if emit.is_mesh() {
4561            // §3.5's four extra reads, and only on the path that has them.
4562            // Adding them unconditionally would make every device declare four
4563            // buffers `mesh.slang` does not name — and WebGPU, which checks a
4564            // bind group against its layout entry for entry, would then need
4565            // four buffers created for a path that never reads them.
4566            //
4567            // `read_only: true` on all four, which is the truth rather than a
4568            // hint: the mesh stage indexes them and writes nothing, and it is
4569            // what lets the graph merge read-after-read.
4570            //
4571            // Four different element types, so four strides, in binding order:
4572            // the clusters (`Meshlet`), the cluster vertex and corner pools
4573            // (`uint` each), and the per-cluster draw arguments
4574            // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4575            let cluster_strides = [
4576                crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4577                size_of::<u32>() as u32,
4578                size_of::<u32>() as u32,
4579                crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4580            ];
4581            mesh_entries.extend(
4582                (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4583                    .zip(cluster_strides)
4584                    .map(|(binding, stride)| {
4585                        BindGroupLayoutEntry {
4586                            binding,
4587                            // **Not the fragment stage.** These four are the geometry
4588                            // stage's alone, and `mesh_cluster.slang` has no fragment entry
4589                            // point of its own to materialise them into — its fragment
4590                            // stage is `mesh.slang`'s, which does not declare mesh-only
4591                            // buffers.
4592                            visibility: geometry,
4593                            kind: BindingKind::StorageBuffer {
4594                                read_only: true,
4595                                dynamic: false,
4596                                stride,
4597                            },
4598                            count: 1,
4599                            flags: BindingFlags::empty(),
4600                        }
4601                    }),
4602            );
4603        }
4604        // Both mesh entry points retain these declarations. Omitting unused
4605        // task buffers would shift later native buffer indices on the plain
4606        // mesh path, so the layout includes them on both paths.
4607        if emit.is_mesh() {
4608            mesh_entries.push(BindGroupLayoutEntry {
4609                binding: CLUSTER_CULL_BINDING,
4610                visibility: geometry,
4611                // **The same block the instance cull reads**, not a copy: one
4612                // camera, one frustum, and no way for the two rejections to
4613                // disagree about which. `dynamic: false` because there is one
4614                // block per frame rather than one per bucket.
4615                kind: BindingKind::UniformBuffer { dynamic: false },
4616                count: 1,
4617                flags: BindingFlags::empty(),
4618            });
4619            mesh_entries.push(BindGroupLayoutEntry {
4620                binding: CLUSTER_CULL_STATS_BINDING,
4621                visibility: geometry,
4622                kind: BindingKind::StorageBuffer {
4623                    // **The one writable binding this pass has.** The stage adds
4624                    // to a counter, so `read_only: false` is the truth rather
4625                    // than a hint, and it is what makes the graph order this
4626                    // write after the draw-argument pass's read of the same
4627                    // buffer.
4628                    read_only: false,
4629                    dynamic: false,
4630                    stride: size_of::<u32>() as u32,
4631                },
4632                count: 1,
4633                flags: BindingFlags::empty(),
4634            });
4635        }
4636        // Topic 18's cascades, read by the fragment stage and declared last —
4637        // above `mesh_cluster.slang`'s range rather than inside it, for the
4638        // reason `SHADOW_ATLAS_BINDING` gives.
4639        //
4640        // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4641        // binding 7's reason exactly: Slang's Metal backend materialises every
4642        // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4643        // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4644        // [[sampler(1)]]` whether it reads them or not.
4645        mesh_entries.push(BindGroupLayoutEntry {
4646            binding: SHADOW_ATLAS_BINDING,
4647            visibility: geometry.union(ShaderStages::FRAGMENT),
4648            kind: BindingKind::SampledImage {
4649                view_type: ImageViewType::D2,
4650                // **`Depth`, and this is the field the seam grew for this
4651                // pass.** WebGPU will only bind a `D32Float` view through a
4652                // depth sample type, and its shader side agrees — the WGSL
4653                // artifact declares `texture_depth_2d`. The other three
4654                // backends take the interpretation off the view's format and
4655                // never read this.
4656                sample_type: SampleType::Depth,
4657            },
4658            count: 1,
4659            flags: BindingFlags::empty(),
4660        });
4661        mesh_entries.push(BindGroupLayoutEntry {
4662            binding: SHADOW_SAMPLER_BINDING,
4663            visibility: geometry.union(ShaderStages::FRAGMENT),
4664            // The sampler-side twin of the line above: `sampler_comparison` in
4665            // the WGSL, `SamplerComparisonState` in the HLSL, and a
4666            // `compareEnable` on the Vulkan sampler object. The layout has to
4667            // say so on WebGPU and cannot on the other three.
4668            kind: BindingKind::Sampler { comparison: true },
4669            count: 1,
4670            flags: BindingFlags::empty(),
4671        });
4672        // DAG geometry and selection state, in the mesh-only binding range.
4673        if emit.is_mesh() {
4674            mesh_entries.push(BindGroupLayoutEntry {
4675                binding: CLUSTER_SELECT_BINDING,
4676                visibility: geometry,
4677                // Read-only and read by **both** mesh entry points, unlike the
4678                // pair below: a cluster's `vertex_base` is which level of a DAG
4679                // its geometry lives in, which an un-amplified stage needs just
4680                // as much as an amplified one.
4681                kind: BindingKind::StorageBuffer {
4682                    read_only: true,
4683                    dynamic: false,
4684                    stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4685                },
4686                count: 1,
4687                flags: BindingFlags::empty(),
4688            });
4689        }
4690        // Both on the whole mesh path, for the two above's reason exactly: the
4691        // amplification stage is the only writer and the only reader, and the
4692        // Metal argument table counts entries rather than reading binding
4693        // numbers.
4694        if emit.is_mesh() {
4695            mesh_entries.push(BindGroupLayoutEntry {
4696                binding: CLUSTER_SELECTION_BINDING,
4697                visibility: geometry,
4698                kind: BindingKind::StorageBuffer {
4699                    // The second writable binding: the amplification stage
4700                    // records the cut it chose, one word per resident cluster.
4701                    read_only: false,
4702                    dynamic: false,
4703                    stride: size_of::<u32>() as u32,
4704                },
4705                count: 1,
4706                flags: BindingFlags::empty(),
4707            });
4708            mesh_entries.push(BindGroupLayoutEntry {
4709                binding: CLUSTER_GROUP_STATE_BINDING,
4710                visibility: geometry,
4711                kind: BindingKind::StorageBuffer {
4712                    // Topic 25's hysteresis state, and read-only
4713                    // here: the draw-argument pass is its only writer, which is
4714                    // what lets a stage with one workgroup per cluster use a
4715                    // decision that has to survive a frame.
4716                    read_only: true,
4717                    dynamic: false,
4718                    stride: size_of::<u32>() as u32,
4719                },
4720                count: 1,
4721                flags: BindingFlags::empty(),
4722            });
4723        }
4724
4725        // The shared fragment light list and froxel grid are bound on every
4726        // path and in every group, unlike the four
4727        // conditional ranges above: `mesh.slang`'s fragment stage reads them
4728        // whatever geometry produced the primitive, so there is no configuration
4729        // in which the layout can omit them.
4730        //
4731        // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4732        // exactly: Slang's Metal backend materialises every global into every
4733        // entry point, so the vertex and mesh stages take these buffers whether
4734        // they read them or not.
4735        mesh_entries.push(BindGroupLayoutEntry {
4736            binding: LIGHT_LIST_BINDING,
4737            visibility: geometry.union(ShaderStages::FRAGMENT),
4738            kind: BindingKind::StorageBuffer {
4739                read_only: true,
4740                dynamic: false,
4741                stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4742            },
4743            count: 1,
4744            flags: BindingFlags::empty(),
4745        });
4746        mesh_entries.push(BindGroupLayoutEntry {
4747            binding: LIGHT_GRID_BINDING,
4748            visibility: geometry.union(ShaderStages::FRAGMENT),
4749            kind: BindingKind::StorageBuffer {
4750                // **Read-only here**, and written by the clustering pass through
4751                // a layout of its own. The graph is what orders the two.
4752                read_only: true,
4753                dynamic: false,
4754                stride: size_of::<u32>() as u32,
4755            },
4756            count: 1,
4757            flags: BindingFlags::empty(),
4758        });
4759        // Topic 46's occlusion channel, last of the set
4760        // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4761        // than tidy.
4762        //
4763        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4764        // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4765        // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4766        mesh_entries.push(BindGroupLayoutEntry {
4767            binding: AMBIENT_OCCLUSION_BINDING,
4768            visibility: geometry.union(ShaderStages::FRAGMENT),
4769            kind: BindingKind::SampledImage {
4770                view_type: ImageViewType::D2,
4771                // **`Float`, unlike the shadow atlas above.** This one is an
4772                // ordinary `R8Unorm` colour image and the WGSL artifact declares
4773                // `texture_2d<f32>` for it; `Depth` here would be a layout
4774                // claiming a depth format the view does not have.
4775                sample_type: SampleType::Float,
4776            },
4777            count: 1,
4778            flags: BindingFlags::empty(),
4779        });
4780        // The irradiance grid, past the occlusion channel — see
4781        // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4782        //
4783        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4784        // `msl/mesh.metal` is again the proof rather than the theory: its
4785        // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4786        mesh_entries.push(BindGroupLayoutEntry {
4787            binding: PROBE_TABLE_BINDING,
4788            visibility: geometry.union(ShaderStages::FRAGMENT),
4789            kind: BindingKind::StorageBuffer {
4790                // **Read-only, and it stays read-only when the updater lands.**
4791                // The rows are device-local now — see [`crate::probe`], which is
4792                // where that is argued — so the seam no longer forces this;
4793                // what forces it is that the shading path does not write a
4794                // probe and this layout has no headroom to pretend otherwise.
4795                // The raster path is at the WebGPU per-stage storage-buffer
4796                // ceiling already, which the check at the end of the layout
4797                // holds it to, so `read_only: false` here would buy a write
4798                // nothing performs at the price of a binding budget there is
4799                // none of. The irradiance probes' gather is a
4800                // compute pass with a layout of its own, and that is where the
4801                // writable binding of these rows belongs.
4802                read_only: true,
4803                dynamic: false,
4804                stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4805            },
4806            count: 1,
4807            flags: BindingFlags::empty(),
4808        });
4809        if emit.is_mesh() {
4810            // DAG group records follow the common buffer prefix; the
4811            // remaining mesh-only buffers are sorted after them below.
4812            //
4813            // **Conditional like the mesh-only bindings**, and not for tidiness:
4814            // the raster path's layout is at the WebGPU storage-buffer ceiling
4815            // already, so a row bound unconditionally would be a renderer that
4816            // cannot be built in a browser. The mesh path's own reads sit outside
4817            // that count because `ShaderStages::MESH` is not one of the three
4818            // stages it sums.
4819            mesh_entries.push(BindGroupLayoutEntry {
4820                binding: LEVEL_GROUP_TABLE_BINDING,
4821                // Only the geometry stage reads this table: the
4822                // heatmap's colour is chosen where the cluster is known, and
4823                // `mesh.slang`'s fragment stage — which is this pipeline's —
4824                // does not declare this buffer.
4825                visibility: geometry,
4826                kind: BindingKind::StorageBuffer {
4827                    // Read-only and read by **both** mesh entry points, like
4828                    // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4829                    // `emit_cluster`, so a row present for one and absent for the
4830                    // other is a descriptor read out of an empty slot.
4831                    read_only: true,
4832                    dynamic: false,
4833                    stride: size_of::<u32>() as u32,
4834                },
4835                count: 1,
4836                flags: BindingFlags::empty(),
4837            });
4838        }
4839
4840        // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4841        //
4842        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4843        // Metal backend materialises every global into every entry point, so
4844        // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4845        // whether it reads it or not.
4846        mesh_entries.push(BindGroupLayoutEntry {
4847            binding: SPECULAR_DFG_BINDING,
4848            visibility: geometry.union(ShaderStages::FRAGMENT),
4849            kind: BindingKind::SampledImage {
4850                view_type: ImageViewType::D2,
4851                // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4852                // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4853                sample_type: SampleType::Float,
4854            },
4855            count: 1,
4856            flags: BindingFlags::empty(),
4857        });
4858
4859        // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4860        //
4861        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4862        // Metal backend materialises every global into every entry point, so
4863        // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4864        // or not. **A sampled image and not a storage buffer**, which costs this
4865        // layout nothing at the WebGPU ceiling checked below — that limit counts
4866        // storage buffers, and this row is a texture.
4867        mesh_entries.push(BindGroupLayoutEntry {
4868            binding: NORMAL_PAGE_BINDING,
4869            visibility: geometry.union(ShaderStages::FRAGMENT),
4870            kind: BindingKind::SampledImage {
4871                view_type: ImageViewType::D2Array,
4872                // `Float`: an `Rgba8Unorm` image, declared
4873                // `texture_2d_array<f32>` by the WGSL artifact — the same
4874                // sample type the sRGB base-colour page reports, since both
4875                // decode to floats.
4876                sample_type: SampleType::Float,
4877            },
4878            count: 1,
4879            flags: BindingFlags::empty(),
4880        });
4881        // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4882        //
4883        // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4884        // `Float` because `Rgba16Float` is a filterable sampled format on every
4885        // target this engine opens, and the WGSL artifact declares it
4886        // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4887        // has to say what the module declared.
4888        mesh_entries.push(BindGroupLayoutEntry {
4889            binding: LTC_TABLE_BINDING,
4890            visibility: geometry.union(ShaderStages::FRAGMENT),
4891            kind: BindingKind::SampledImage {
4892                view_type: ImageViewType::D2,
4893                sample_type: SampleType::Float,
4894            },
4895            count: 1,
4896            flags: BindingFlags::empty(),
4897        });
4898        // Topic 45's contact-shadow channel, last of the set —
4899        // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4900        // tidy.
4901        //
4902        // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4903        // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4904        // backend materialises every global into every entry point whether that
4905        // stage reads it or not.
4906        mesh_entries.push(BindGroupLayoutEntry {
4907            binding: CONTACT_SHADOW_BINDING,
4908            visibility: geometry.union(ShaderStages::FRAGMENT),
4909            kind: BindingKind::SampledImage {
4910                view_type: ImageViewType::D2,
4911                sample_type: SampleType::Float,
4912            },
4913            count: 1,
4914            flags: BindingFlags::empty(),
4915        });
4916        // The irradiance probes' per-probe visibility maps, last
4917        // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4918        // structural.
4919        //
4920        // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4921        // dimension a layout entry claims against the view handed to it at
4922        // pipeline creation, which is the normal page's own note.
4923        // `UnfilterableFloat` for the same reason and measured the same way: the
4924        // image is `Rg32Float`, which is unfilterable without WebGPU's
4925        // `float32-filterable`, and this slot declared `Float` made Chromium
4926        // refuse the whole mesh bind group — "None of the supported sample types
4927        // (UnfilterableFloat) ... match the expected sample types (Float)" —
4928        // which took every 3D demo's frame to black. Reading it only with `Load`
4929        // does not lift that: the check is on the layout against the view's
4930        // format, not on how the shader gets at it.
4931        mesh_entries.push(BindGroupLayoutEntry {
4932            binding: PROBE_VISIBILITY_BINDING,
4933            visibility: geometry.union(ShaderStages::FRAGMENT),
4934            kind: BindingKind::SampledImage {
4935                view_type: ImageViewType::D2Array,
4936                sample_type: SampleType::UnfilterableFloat,
4937            },
4938            count: 1,
4939            flags: BindingFlags::empty(),
4940        });
4941        // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4942        // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4943        //
4944        // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4945        // page's three answers exactly, and for its reasons: Slang's Metal
4946        // backend materialises every global into every entry point, WebGPU
4947        // compares the declared dimension against the bound view, and both
4948        // images are `Rgba8Unorm`-family formats that decode to filterable
4949        // floats.
4950        for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4951            mesh_entries.push(BindGroupLayoutEntry {
4952                binding,
4953                visibility: geometry.union(ShaderStages::FRAGMENT),
4954                kind: BindingKind::SampledImage {
4955                    view_type: ImageViewType::D2Array,
4956                    sample_type: SampleType::Float,
4957                },
4958                count: 1,
4959                flags: BindingFlags::empty(),
4960            });
4961        }
4962        mesh_entries.sort_by_key(|entry| entry.binding);
4963        let mesh_desc = BindGroupLayoutDesc {
4964            label: Some(MESH_LAYOUT_LABEL),
4965            entries: &mesh_entries,
4966        };
4967        // **This layout is at the guaranteed limit with no headroom on the
4968        // raster path, in both raster stages**: the vertex stage takes every
4969        // storage buffer a WebGPU device promises, and since bindings 1 to 5
4970        // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4971        // takes the same number. A ninth in either is a renderer that cannot be
4972        // built in a browser or on SwiftShader, so it fails here rather than at
4973        // somebody else's `createPipelineLayout` — see
4974        // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4975        // mesh path's extra reads are outside the count.
4976        // `Some("mesh")`, which is the *pipeline* layout's label, not
4977        // `mesh_desc.label` — the error text reads "pipeline layout {label}
4978        // binds …", so naming the bind group layout there sends the reader to
4979        // the wrong object.
4980        check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4981        let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4982        rollback.bind_group_layouts.push(mesh_layout);
4983
4984        // A dynamic offset must be a multiple of the device's alignment, and one
4985        // block has to fit inside one stride. Read from the device rather than
4986        // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
4987        // typical desktop Vulkan driver.
4988        //
4989        // One stride for both blocks, sized for the larger — see
4990        // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
4991        // decided below.
4992        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
4993        let draw_stride =
4994            u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
4995                HalError::InvalidDescriptor(format!(
4996                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
4997                         offset can express"
4998                ))
4999            })?;
5000        let draw_constants = device.create_buffer(&BufferDesc {
5001            label: Some("mesh draw constants"),
5002            // A block per bucket per draw region: a region's draws name their
5003            // own run starts, and the mesh path's block names the region's
5004            // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5005            size: u64::from(draw_stride)
5006                * u64::from(bucket_count)
5007                * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
5008            usage: BufferUsage::UNIFORM,
5009            memory: MemoryLocation::HostUpload,
5010        })?;
5011        rollback.buffers.push(draw_constants);
5012        // --- the shadow map's own resources ---
5013        //
5014        // Before the bind groups, because every one of them names the atlas or
5015        // the placeholder standing in for it.
5016        let (atlas_width, atlas_height) = shadow::atlas_extent();
5017        let shadow_atlas = device.create_image(&ImageDesc {
5018            label: Some("shadow atlas"),
5019            image_type: ImageType::D2,
5020            format: Format::D32Float,
5021            extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
5022            mip_levels: 1,
5023            samples: 1,
5024            // `TRANSFER_SRC` so a test can copy the cascades back and check
5025            // that something was written into them. A shadow map that stayed at
5026            // its clear value produces a frame that looks entirely plausible —
5027            // everything is lit — so the readback is the only thing that can
5028            // tell a working pass from one that drew nothing.
5029            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
5030                .union(ImageUsage::SAMPLED)
5031                .union(ImageUsage::TRANSFER_SRC),
5032        })?;
5033        rollback.images.push(shadow_atlas);
5034        let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
5035            label: Some("shadow atlas"),
5036            image: shadow_atlas,
5037            view_type: ImageViewType::D2,
5038            format: Format::D32Float,
5039            range: ImageSubresourceRange::all(Format::D32Float),
5040        })?;
5041        rollback.image_views.push(shadow_atlas_view);
5042
5043        let shadow_placeholder = device.create_image(&ImageDesc {
5044            label: Some("shadow placeholder"),
5045            image_type: ImageType::D2,
5046            format: Format::D32Float,
5047            extent: crcbl_hal::Extent3d::d2(1, 1),
5048            mip_levels: 1,
5049            samples: 1,
5050            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
5051        })?;
5052        rollback.images.push(shadow_placeholder);
5053        let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
5054            label: Some("shadow placeholder"),
5055            image: shadow_placeholder,
5056            view_type: ImageViewType::D2,
5057            format: Format::D32Float,
5058            range: ImageSubresourceRange::all(Format::D32Float),
5059        })?;
5060        rollback.image_views.push(shadow_placeholder_view);
5061
5062        // The occlusion placeholder, beside the shadow one and for the same
5063        // reason: every group of this layout has to fill
5064        // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
5065        // graph has an occlusion image to name.
5066        //
5067        // **Uploaded rather than cleared**, unlike the depth placeholder above,
5068        // and the four bytes are the whole point — see
5069        // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
5070        // Left undefined this would be a random ambient scale *and* a random
5071        // direction to steer it along, on any frame that fell back to it.
5072        let ambient_occlusion_placeholder = uploads.texture(
5073            "ssao placeholder",
5074            Format::Rgba8Unorm,
5075            (1, 1),
5076            &[&[&AMBIENT_OCCLUSION_NONE]],
5077            ImageViewType::D2,
5078        )?;
5079        rollback.textures.push(ambient_occlusion_placeholder);
5080
5081        // The contact-shadow placeholder, beside the occlusion one and on its
5082        // terms exactly: every group of this layout has to fill
5083        // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
5084        // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
5085        // so a fragment that reads this one is a fragment the sun reaches
5086        // unobstructed.
5087        let contact_shadow_placeholder = uploads.texture(
5088            "contact shadow placeholder",
5089            Format::R8Unorm,
5090            (1, 1),
5091            &[&[&[CONTACT_SHADOW_NONE]]],
5092            ImageViewType::D2,
5093        )?;
5094        rollback.textures.push(contact_shadow_placeholder);
5095
5096        // The probe-visibility placeholder, on the two above it's terms: every
5097        // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
5098        // nothing has been captured when they are built. One texel of
5099        // [`probe_visibility_none`], which no surface is further away than, so a
5100        // probe read through it keeps all of its weight.
5101        let probe_visibility_placeholder = uploads.texture(
5102            "probe visibility placeholder",
5103            Format::Rg32Float,
5104            (1, 1),
5105            &[&[&probe_visibility_none()]],
5106            ImageViewType::D2Array,
5107        )?;
5108        rollback.textures.push(probe_visibility_placeholder);
5109
5110        // The split-sum `DFG` table, uploaded once and read by every frame this
5111        // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
5112        // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
5113        //
5114        // **Cooked bytes rather than a computed image**: the integrator
5115        // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
5116        // engine's goldens are compared across four backends with no tolerance.
5117        // Baking here would be four slightly different tables.
5118        //
5119        // **Every view's reflection march reads this same image** for its own
5120        // split-sum scale and bias — see `Ssr::dfg` — rather than uploading a
5121        // second copy of the same bytes per view.
5122        let specular_dfg = uploads.texture(
5123            "dfg table",
5124            // Two bytes of fixed point per channel, high byte first — see
5125            // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
5126            // not the `Rg16Float` the format's own doc anticipated.
5127            Format::Rgba8Unorm,
5128            (DFG_SIZE_U32, DFG_SIZE_U32),
5129            &[&[&dfg::pair_texels()]],
5130            ImageViewType::D2,
5131        )?;
5132        rollback.textures.push(specular_dfg);
5133
5134        // The area lights' fit, beside it and on its terms — cooked bytes for
5135        // the same reason, and `Rgba16Float` rather than fixed point because
5136        // these are matrix entries rather than shares of arriving light.
5137        // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
5138        let ltc_table = uploads.texture(
5139            "ltc table",
5140            Format::Rgba16Float,
5141            (LTC_SIZE_U32, LTC_SIZE_U32),
5142            &[&[&ltc::texels()]],
5143            ImageViewType::D2,
5144        )?;
5145        rollback.textures.push(ltc_table);
5146        service();
5147
5148        // **A comparison sampler, and that is the PCF.** Each
5149        // `SampleCmpLevelZero` returns the filtered fraction of four texels that
5150        // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
5151        // comparisons rather than nine raw fetches it averages itself.
5152        //
5153        // `Greater` for the engine's reversed-Z, exactly as the depth *test*
5154        // is: the receiver survives when it is nearer the light than whatever
5155        // the map stored. `SamplerDesc::compare` carries the same warning.
5156        //
5157        // Clamped on every axis so a receiver just outside a cascade's box
5158        // reads the edge rather than wrapping into the opposite corner — the
5159        // shader's own bounds check is what actually handles that case, and this
5160        // is the second line of defence one texel wide.
5161        let shadow_sampler = device.create_sampler(&SamplerDesc {
5162            label: Some("shadow comparison"),
5163            mag_filter: FilterMode::Linear,
5164            min_filter: FilterMode::Linear,
5165            mip_filter: FilterMode::Nearest,
5166            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5167            compare: Some(crcbl_hal::CompareOp::Greater),
5168            ..SamplerDesc::default()
5169        })?;
5170        rollback.samplers.push(shadow_sampler);
5171
5172        // The pipelines every generator dispatches, the camera's and each
5173        // shadow cull's, compiled once here and shared — with the occlusion
5174        // phases, because every camera's generator is built for them.
5175        let draw_pipelines = rollback
5176            .draw_pipelines
5177            .insert(DrawGenPipelines::new(device, true, service)?);
5178
5179        let mesh_set_layouts = [mesh_layout];
5180        let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5181            label: Some("mesh"),
5182            bind_group_layouts: &mesh_set_layouts,
5183            // The camera goes in the uniform buffer above rather than here:
5184            // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5185            // explicit that the substitute is a data-layout decision. So this
5186            // file needs no tier branch at all — it has been on Tier B's shape
5187            // since P1, and `crate::ui_pass` is where the split actually bites.
5188            push_constants: None,
5189        })?;
5190        rollback.pipeline_layouts.push(mesh_pipeline_layout);
5191
5192        // The colour pass's pipeline and its depth-only twin, out of one set of
5193        // modules — see [`MeshModules`], which is where the two shapes and the
5194        // reasons for them live. Both are created before either is unwrapped and
5195        // the modules are released between, so a failing creation leaks nothing.
5196        //
5197        // **Each shape has a twin per material side** — see
5198        // [`SidedPipelines`], which is where the cull modes and the reason for a
5199        // pipeline rather than a per-draw state live. The shadow tile clear is
5200        // the one exception: its triangle comes out of `SV_VertexID` and it
5201        // already culls nothing.
5202        //
5203        // Beside them: the cutout twin of the depth shape, which a frame whose
5204        // material table masks alpha is recorded with instead (see
5205        // [`MeshModules::depth_masked_pipeline`]); the one that resets a tile,
5206        // which the cadence rung needs and the attachment's load operation
5207        // cannot express ([`MeshModules::depth_clear_pipeline`]); and the
5208        // irradiance probes' reflective shadow map ([`MeshModules::rsm_pipeline`]).
5209        //
5210        // **Only what this scene can draw with is compiled.** The bucket table
5211        // above is final — nothing adds a material or changes a probe volume's
5212        // update after `build` — so `scene_modes` and the volume are the whole
5213        // of what any frame of this renderer will ask for. The single-sided
5214        // colour and depth shapes and the tile clear are built for every
5215        // scene; each `CullMode::None` twin only where a bucket is
5216        // double-sided, the cutout shape only where one masks, and the
5217        // reflective shadow map only where the probes are updated. An opaque,
5218        // single-sided scene without an updated volume, such as the demo
5219        // scene, compiles only those.
5220        //
5221        // **They are one [`pipeline_batch`], compiled side by side** where
5222        // the device allows it: on a cold driver cache each is a shader
5223        // compilation, and this is the build's longest run of them. `service`
5224        // runs before each round of the batch, or before each pipeline where the
5225        // batch is serial — see [`ForwardRenderer::with_scene_serviced`].
5226        //
5227        // **The camera's froxel volume and reflection march are members too**,
5228        // which is why this batch runs before the camera is built rather than
5229        // after it: each has one costly compile — the scatter pass and the
5230        // march — that `View::build` would otherwise make one after the other
5231        // beside nothing. Their layouts are created first and held by `pending`
5232        // until the batch has made every pipeline against them; the passes
5233        // themselves stay in the view, built eagerly — see
5234        // [`VolumetricPipelines`] and [`SsrPipelines`].
5235        let holds = |mode: u32| scene_modes.contains(&mode);
5236        // The single-sided shapes are built even where `DEPTH_MODES[0]` is not
5237        // held: they are the template the frame's draw lists are partitioned
5238        // from, and the rare scene with no opaque single-sided material pays a
5239        // compile each for them.
5240        let [_, masked, double, masked_double] = DEPTH_MODES;
5241        let any_double = holds(double) || holds(masked_double);
5242        let any_masked = holds(masked) || holds(masked_double);
5243        let updates_probes = scene.probes.update == ProbeUpdate::EveryFrame;
5244        let mut pending = Partial::new(device);
5245        let volumetric = VolumetricLayouts::new(device, &mut pending)?;
5246        let ssr = SsrLayouts::new(device, &mut pending)?;
5247        let modules = MeshModules::new(device, emit, culls_clusters)?;
5248        let layout = mesh_pipeline_layout;
5249        let [back, none] = MeshModules::SIDES;
5250        let raster = |made: Result<GraphicsPipelineHandle, HalError>| made.map(Pipeline::Graphics);
5251        let color = |cull| {
5252            raster(modules.color_pipeline(device, layout, PolygonMode::Fill, cull, "forward"))
5253        };
5254        let depth = |cull| raster(modules.depth_pipeline(device, layout, cull));
5255        let depth_masked = |cull| raster(modules.depth_masked_pipeline(device, layout, cull));
5256        let rsm = |cull| raster(modules.rsm_pipeline(device, layout, cull));
5257        let fullscreen = Self::build_fullscreen;
5258        // Each member beside whether this scene needs it, in one fixed order the
5259        // results are read back out of below.
5260        let members: [(bool, &pipeline_batch::Job<'_, _>); 9] = [
5261            (true, &|| color(back)),
5262            (any_double, &|| color(none)),
5263            (true, &|| depth(back)),
5264            (holds(double), &|| depth(none)),
5265            (any_masked, &|| depth_masked(back)),
5266            (holds(masked_double), &|| depth_masked(none)),
5267            (true, &|| {
5268                raster(modules.depth_clear_pipeline(device, layout))
5269            }),
5270            (updates_probes, &|| rsm(back)),
5271            (updates_probes && any_double, &|| rsm(none)),
5272        ];
5273        // The view passes' costly pair leads the batch, so it is in the first
5274        // round whatever a round's size, and the mesh pass's members follow it
5275        // into the earliest rounds left. Their other members, never timed alone
5276        // and taken to be cheap, trail every mesh member.
5277        let leading: [&pipeline_batch::Job<'_, _>; 2] = [
5278            &|| volumetric.scatter(device).map(Pipeline::Compute),
5279            &|| ssr.march(device, fullscreen).map(Pipeline::Graphics),
5280        ];
5281        let trailing: [&pipeline_batch::Job<'_, _>; 3] = [
5282            &|| volumetric.integrate(device).map(Pipeline::Compute),
5283            &|| {
5284                volumetric
5285                    .composite(device, fullscreen)
5286                    .map(Pipeline::Graphics)
5287            },
5288            &|| ssr.blur(device, fullscreen).map(Pipeline::Graphics),
5289        ];
5290        let jobs: Vec<&pipeline_batch::Job<'_, _>> = leading
5291            .into_iter()
5292            .chain(
5293                members
5294                    .iter()
5295                    .filter_map(|(needed, job)| needed.then_some(*job)),
5296            )
5297            .chain(trailing)
5298            .collect();
5299        let mut made = pipeline_batch::create_listed(device, service, &jobs).into_iter();
5300        let mut next = || {
5301            made.next()
5302                .unwrap_or_else(|| unreachable!("one result per job"))
5303        };
5304        let [scatter, march] = [(); 2].map(|()| next());
5305        let results: [Option<Result<Pipeline, HalError>>; 9] =
5306            members.map(|(needed, _)| needed.then(&mut next));
5307        let [integrate, composite, blur] = [(); 3].map(|()| next());
5308        modules.destroy(device);
5309        // Register every successful creation before propagating any error.
5310        // Results later in this batch may own pipelines even when the first
5311        // result failed; dropping an unvisited Result does not release a HAL
5312        // handle. The outer rollback owns the mesh pass's until build
5313        // succeeds, and `pending` the view passes' until each set is whole.
5314        for pipeline in results.iter().flatten().flatten() {
5315            rollback.pipelines.push(pipeline.graphics());
5316        }
5317        for pipeline in [&scatter, &march, &integrate, &composite, &blur]
5318            .into_iter()
5319            .flatten()
5320        {
5321            pending.add(*pipeline);
5322        }
5323        let volumetric = volumetric.finish(
5324            scatter?.compute(),
5325            integrate?.compute(),
5326            composite?.graphics(),
5327        );
5328        let ssr = ssr.finish(march?.graphics(), blur?.graphics());
5329        pending.keep();
5330        rollback.volumetric_pipelines = Some(volumetric);
5331        rollback.ssr_pipelines = Some(ssr);
5332        let [
5333            mesh_single,
5334            mesh_double,
5335            shadow_single,
5336            shadow_double,
5337            depth_masked_single,
5338            depth_masked_double,
5339            shadow_clear_pipeline,
5340            rsm_single,
5341            rsm_double,
5342        ] = results.map(|result| result.map(|made| made.map(Pipeline::graphics)).transpose());
5343        let built = |single: Option<GraphicsPipelineHandle>, double| {
5344            single.map(|single| SidedPipelines { single, double })
5345        };
5346        let mesh_pipeline = built(mesh_single?, mesh_double?).unwrap_or_else(|| {
5347            unreachable!("the colour pass's single-sided shape is always built")
5348        });
5349        let shadow_pipeline = built(shadow_single?, shadow_double?)
5350            .unwrap_or_else(|| unreachable!("the depth pass's single-sided shape is always built"));
5351        let depth_masked_pipeline = built(depth_masked_single?, depth_masked_double?);
5352        let shadow_clear_pipeline = shadow_clear_pipeline?
5353            .unwrap_or_else(|| unreachable!("the tile clear is always built"));
5354        let rsm_pipeline = built(rsm_single?, rsm_double?);
5355
5356        // --- the camera ---
5357        //
5358        // Everything the camera's picture needs of its own, built against the
5359        // scene resources above — see [`view`], which is where the line between
5360        // the two is drawn. Into the rollback whole as soon as it exists, so a
5361        // failure further down releases it with everything else.
5362        let slot_pages = vec![page_bindings; instance_buffers.len()];
5363        rollback.primary = Some(View::build(
5364            device,
5365            uploads,
5366            &ViewInputs {
5367                id: ViewId::PRIMARY,
5368                effects: RenderEffects::all(),
5369                // What the first frame resolves to unless a caller moves the
5370                // request before it: the default request against the device
5371                // effects this build hands the renderer below.
5372                expected: EffectRequest::default().resolve(RenderEffects::all()),
5373                // A renderer is built at full render scale; a caller that lowers
5374                // it before the first frame — a saved setting — has that
5375                // frame build the upscale.
5376                expected_upscale: false,
5377                background: ViewBackground::Scene,
5378                lighting: ViewLighting::Scene,
5379                target_format,
5380                emit,
5381                instances: &instance_buffers,
5382                mesh_table,
5383                draw_pipelines,
5384                bucket_meshes: &bucket_meshes,
5385                bucket_modes: &bucket_modes,
5386                bucket_clusters: &bucket_clusters,
5387                bucket_cluster_bases: &bucket_cluster_bases,
5388                mesh_levels: &mesh_levels,
5389                level_groups: &level_groups,
5390                level_meshes: &level_meshes,
5391                instance_capacity: scene.capacities.instances,
5392                light_capacity: scene.capacities.lights,
5393                clusters: rollback.clusters.as_ref(),
5394                task_lanes: view::task_lanes(culls_clusters),
5395                mesh_layout,
5396                vertices,
5397                draw_constants,
5398                materials: material_buffer,
5399                pages: &slot_pages,
5400                probes: &probe_buffers,
5401                specular_dfg: specular_dfg.view,
5402                ltc_table: ltc_table.view,
5403                shadow_map: shadow_atlas_view,
5404                shadow_sampler,
5405                ambient_occlusion: ambient_occlusion_placeholder.view,
5406                contact_shadow: contact_shadow_placeholder.view,
5407                probe_visibility: probe_visibility_placeholder.view,
5408            },
5409            // Compiled in the mesh pass's batch above, and the view's from here.
5410            ViewPipelines {
5411                volumetric: rollback
5412                    .volumetric_pipelines
5413                    .take()
5414                    .unwrap_or_else(|| unreachable!("the mesh batch made the volume's set")),
5415                ssr: rollback
5416                    .ssr_pipelines
5417                    .take()
5418                    .unwrap_or_else(|| unreachable!("the mesh batch made the march's set")),
5419            },
5420            service,
5421        )?);
5422        let primary = rollback.primary.as_ref().expect("just stored");
5423
5424        // Written here and never again: **which word holds** a bucket's run
5425        // start is fixed by the bucket table and the capacity, and both are
5426        // fixed at build. What varies per frame is where the run starts and how
5427        // much of it is filled, and the GPU writes both — the start into that
5428        // word, the count into the bucket's indirect arguments. See
5429        // `mesh.slang`'s header for why the block names a word rather than
5430        // carrying the start.
5431        //
5432        // Taken from the camera's generator and bound for every generator's
5433        // draws: the shadow culls and every secondary view are built from the
5434        // same table and the same capacity, so `bucket_start_word` answers the
5435        // same for all of them.
5436        let draws = &primary.draws;
5437        let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5438        // **Every draw region's copy**, region 0's at the offsets
5439        // `bucket_constants` records and each further region a bucket count of
5440        // strides behind the one before: a region's draw reads its own run
5441        // start and — on the mesh path — its own argument structure, and the
5442        // two are the only words a region changes. See
5443        // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5444        for (region, (bucket, index)) in
5445            (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5446                (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5447            })
5448        {
5449            let offset = (region * bucket_count + bucket) * draw_stride;
5450            if region == 0 {
5451                bucket_constants[index] = offset;
5452            }
5453            let start_at = draws.region_start_word(region, bucket);
5454            // The mesh path's block says three more things — where this
5455            // bucket's mesh's clusters are, how many it has, and which element
5456            // of the indirect arguments holds its instance count — because a
5457            // dispatch carries none of them and a `draw_indexed_indirect` does
5458            // not need them. All three are fixed when the bucket table is,
5459            // exactly like `start_at`.
5460            let block = if emit.is_mesh() {
5461                crcbl_shaders::meshlet::ClusterDrawConstants {
5462                    start_at,
5463                    cluster_base: bucket_cluster_bases[index],
5464                    cluster_count: bucket_clusters[index],
5465                    // The region's argument structure, which is where this
5466                    // region's instance count is.
5467                    bucket: region * bucket_count + bucket,
5468                    // The same number the draw-argument pass indexes the state
5469                    // with, taken from the object that owns the buffer rather
5470                    // than recomputed from the group table — the two indexing it
5471                    // differently is a cluster reading another instance's
5472                    // decision.
5473                    group_stride: draws.group_stride(),
5474                    // Where the group records are in the table buffer, from the
5475                    // object that packed it — the screen-error heatmap's one
5476                    // input that is not already in the frame block. Taken from
5477                    // `DrawGen` rather than recomputed here for `group_stride`'s
5478                    // reason: two spellings of one offset is an overlay reading
5479                    // another region's words as a group.
5480                    level_groups_at: draws.table_offsets().level_groups_at,
5481                    // The same two numbers again as words of that buffer,
5482                    // which is where a draw that is not the first of a ranged
5483                    // call reads them — `mesh_cluster.slang`'s "One call for
5484                    // a range of buckets". This bucket's, not the region's
5485                    // argument structure's: the tables hold one word a bucket.
5486                    cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5487                    cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5488                    // Where this bucket's task chunks start in this region,
5489                    // and where the region's end: what a flat call binding
5490                    // this block searches between — `mesh_cluster.slang`'s
5491                    // `taskMain`.
5492                    chunk_starts_at: draws.chunk_start_word(region, bucket),
5493                    chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5494                }
5495                .to_bytes()
5496                .to_vec()
5497            } else {
5498                // **The bucket's mesh, which is not always the drawn instance's.**
5499                // A uniform cut selects one of a DAG's levels and each level is
5500                // a mesh table entry of its own, so this is what says which
5501                // geometry the draw's index range belongs to; the instance goes
5502                // on naming level 0. See `mesh::DrawConstants::mesh`.
5503                mesh::DrawConstants {
5504                    start_at,
5505                    mesh: bucket_meshes[index],
5506                    mesh_at: draws.bucket_mesh_word(bucket),
5507                }
5508                .to_bytes()
5509                .to_vec()
5510            };
5511            device.write_buffer(draw_constants, u64::from(offset), &block)?;
5512        }
5513
5514        let region_step = RegionStep {
5515            constants: bucket_count * draw_stride,
5516            args: draws.args_region_offset(1),
5517            counts: draws.counts_region_offset(1),
5518        };
5519
5520        // §3.3's cull, once per cascade and once per shadowed light. Each gets
5521        // its own `DrawGen` and therefore its own frustum, survivor list and
5522        // indirect arguments — which is what "one cull dispatch per cascade
5523        // against the same instance/geometry pools" means, and why the instance
5524        // ring and the mesh table below are the same handles the camera's cull
5525        // was given.
5526        //
5527        // **One per light rather than one per tile**, which is topic 18's fourth
5528        // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5529        // against the light's sphere once and draw that one visible set through
5530        // six matrices.
5531        //
5532        // **Built for every slot, including the ones no light may ever hold.** A
5533        // generator's buffers are sized by the instance capacity rather than by
5534        // the scene, so building one on demand would mean allocating device
5535        // memory inside `begin_frame` — and a frame that cannot allocate is a
5536        // frame that cannot draw. The unused ones cost memory and no dispatch:
5537        // `add_shadow_pass` records passes for the occupied slots alone.
5538        for cull in 0..SHADOW_CULLS {
5539            // Into the rollback as each is built, on the same terms as the
5540            // camera's: a failure two culls in has to release the first one,
5541            // and the rollback is the only thing that knows about it.
5542            let label = if cull < shadow::CASCADES {
5543                format!("shadow cascade {cull}")
5544            } else {
5545                format!("shadow light {}", cull - shadow::CASCADES)
5546            };
5547            let draws = DrawGen::new(
5548                device,
5549                uploads,
5550                rollback
5551                    .draw_pipelines
5552                    .as_ref()
5553                    .unwrap_or_else(|| unreachable!("built ahead of the camera")),
5554                &DrawGenDesc {
5555                    label: Some(&label),
5556                    instances: &instance_buffers,
5557                    mesh_table,
5558                    bucket_meshes: &bucket_meshes,
5559                    bucket_modes: &bucket_modes,
5560                    bucket_clusters: &bucket_clusters,
5561                    bucket_cluster_bases: &bucket_cluster_bases,
5562                    mesh_levels: &mesh_levels,
5563                    level_groups: &level_groups,
5564                    level_meshes: &level_meshes,
5565                    instance_capacity: scene.capacities.instances,
5566                    // No view's: a shadow map is drawn from everything resident
5567                    // that casts, so an instance a camera hides still casts its
5568                    // shadow and one `set_instance_casts_shadow` turned off does
5569                    // not — on every geometry path, since this is the cull they
5570                    // all draw from. The reflective shadow maps draw these same
5571                    // survivors, so such an instance bounces no light either.
5572                    hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5573                    // A light slot may hold a point light, whose six faces cull
5574                    // separately into six regions of the one generator; a
5575                    // cascade never does.
5576                    mode: if cull < shadow::CASCADES {
5577                        crcbl_shaders::draw_gen::DrawMode::Plain
5578                    } else {
5579                        crcbl_shaders::draw_gen::DrawMode::Faces
5580                    },
5581                    task_lanes: view::task_lanes(culls_clusters),
5582                },
5583            )?;
5584            rollback.shadow_draws.push(draws);
5585            service();
5586        }
5587        // The handles are `Copy` and are read out here for the same reason the
5588        // camera's are above: the pool they came from is the rollback's now.
5589        let tile_buffers: Vec<TileBuffers> = rollback
5590            .shadow_draws
5591            .iter()
5592            .map(|draws| TileBuffers {
5593                runs: (0..instance_buffers.len())
5594                    .map(|frame| draws.runs(frame))
5595                    .collect(),
5596                args: (0..instance_buffers.len())
5597                    .map(|frame| draws.args(frame))
5598                    .collect(),
5599                cull_params: (0..instance_buffers.len())
5600                    .map(|frame| draws.cull_params(frame))
5601                    .collect(),
5602                cull_stats: (0..instance_buffers.len())
5603                    .map(|frame| draws.visible_count(frame))
5604                    .collect(),
5605                group_state: draws.group_state(),
5606            })
5607            .collect();
5608
5609        let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5610        let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5611        let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5612        let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5613        for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5614            // Everything a group of this layout names that is the same in all of
5615            // this frame's — the camera's list and table buffers included, which
5616            // a shadow view binds because the layout declares them and reads
5617            // nothing of. The per-group half is what `MeshGroup` below varies,
5618            // and the two exist so the colour pass's group and the shadow pass's
5619            // are one description rather than two that agree today.
5620            let shared = SharedBindings {
5621                vertices,
5622                draw_constants,
5623                mesh_table,
5624                materials: material_buffer,
5625                pages: page_bindings,
5626                clusters: rollback.clusters.as_ref(),
5627                shadow_sampler,
5628                lights: primary.lights.lights(frame),
5629                light_grid: primary.lights.grid(frame),
5630                probes: probe_buffers[frame],
5631                tables: primary.draws.tables(),
5632                specular_dfg: specular_dfg.view,
5633                ltc_table: ltc_table.view,
5634            };
5635
5636            // The same layout again, once per shadow view, differing in exactly
5637            // the things a view is: which matrix, and which cull's survivors.
5638            //
5639            // **The view's own uniforms and the cull's shared buffers**, which
5640            // is the whole of what a point light's six faces are: one visible
5641            // set, six matrices. `shadow_cull` is the map from a view to the
5642            // generator behind it, and it is a compile-time one because a bind
5643            // group names its buffers when it is created — where a face's *tile*
5644            // is decided per frame and reaches the device as a viewport.
5645            let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5646            let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5647            let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5648            let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5649            for view in 0..SHADOW_VIEWS {
5650                let buffers = &tile_buffers[if view < shadow::CASCADES {
5651                    view
5652                } else {
5653                    shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5654                }];
5655                let tile_uniforms = device.create_buffer(&BufferDesc {
5656                    label: Some("shadow view uniforms"),
5657                    size: mesh::FRAME_UNIFORMS_SIZE as u64,
5658                    usage: BufferUsage::UNIFORM,
5659                    memory: MemoryLocation::HostUpload,
5660                })?;
5661                rollback.buffers.push(tile_uniforms);
5662                let entries = MeshGroup {
5663                    uniforms: tile_uniforms,
5664                    instances: slot_instances,
5665                    runs: buffers.runs[frame],
5666                    args: buffers.args[frame],
5667                    // The amplification stage culls clusters against whatever
5668                    // frustum is in this block, and against
5669                    // `frame.camera_position` — which in a view's copy is the
5670                    // *light*. So the per-cluster cull rejects what faces away
5671                    // from the light, which is the right question for a shadow
5672                    // map and the wrong one to have asked with the camera's
5673                    // frustum.
5674                    cull_params: buffers.cull_params[frame],
5675                    cull_stats: buffers.cull_stats[frame],
5676                    // **This view's own**, and not the colour pass's: that pass
5677                    // is recorded last and would write over it. See
5678                    // `ForwardRenderer::shadow_selection`.
5679                    cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5680                    // Its cull's — see `TileBuffers::group_state`, which is
5681                    // where that budget is argued.
5682                    group_state: emit.is_mesh().then_some(buffers.group_state),
5683                    shadow_map: shadow_placeholder_view,
5684                    // A cascade shades nothing — the pipeline has no fragment
5685                    // stage — so this slot exists only because Metal
5686                    // materialises every global into every entry point.
5687                    ambient_occlusion: ambient_occlusion_placeholder.view,
5688                    contact_shadow: contact_shadow_placeholder.view,
5689                    probe_visibility: probe_visibility_placeholder.view,
5690                }
5691                .entries(&shared);
5692                let group = device.create_bind_group(&BindGroupDesc {
5693                    label: Some("shadow view"),
5694                    layout: mesh_layout,
5695                    entries: &entries,
5696                    variable_count: None,
5697                })?;
5698                rollback.bind_groups.push(group);
5699                frame_shadow_uniforms.push(tile_uniforms);
5700                frame_shadow_groups.push(group);
5701                frame_shadow_entries.push(entries);
5702                frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5703            }
5704            shadow_uniforms.push(frame_shadow_uniforms);
5705            shadow_groups.push(frame_shadow_groups);
5706            shadow_group_entries.push(frame_shadow_entries);
5707            shadow_selection.push(frame_shadow_selection);
5708            service();
5709        }
5710
5711        // --- the tonemap pass ---
5712        let tonemap_entries = [
5713            BindGroupLayoutEntry {
5714                binding: 0,
5715                visibility: ShaderStages::FRAGMENT,
5716                kind: BindingKind::SampledImage {
5717                    view_type: ImageViewType::D2,
5718                    sample_type: SampleType::Float,
5719                },
5720                count: 1,
5721                flags: BindingFlags::empty(),
5722            },
5723            BindGroupLayoutEntry {
5724                binding: 1,
5725                visibility: ShaderStages::FRAGMENT,
5726                kind: BindingKind::Sampler { comparison: false },
5727                count: 1,
5728                flags: BindingFlags::empty(),
5729            },
5730            // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5731            // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5732            // decision restated: WebGPU has no push constants at all, so a range
5733            // here would split this pass into a tier A and a tier B form —
5734            // two layouts, two buffers and, because one Slang entry point reads
5735            // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5736            // one and never both, a second copy of `tonemap.slang`. Four bytes
5737            // once a frame do not buy that.
5738            //
5739            // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5740            // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5741            // in the vertex one, because the vertex stage generates three
5742            // corners out of `SV_VertexID` and reads nothing.
5743            BindGroupLayoutEntry {
5744                binding: 2,
5745                visibility: ShaderStages::FRAGMENT,
5746                kind: BindingKind::UniformBuffer { dynamic: false },
5747                count: 1,
5748                flags: BindingFlags::empty(),
5749            },
5750            // The measured exposure — see [`crate::exposure`]. **Bound on every
5751            // frame, whether or not anything measured**, because a binding that
5752            // comes and goes is a second pipeline layout and a second group
5753            // cache keyed on which one is live, to save four bytes. The block
5754            // above carries the switch that decides whether the shader reads it.
5755            BindGroupLayoutEntry {
5756                binding: 3,
5757                visibility: ShaderStages::FRAGMENT,
5758                kind: BindingKind::StorageBuffer {
5759                    // Written by `exposure.slang`'s reduce and read here —
5760                    // `StructuredBuffer` in this shader, which is the truth
5761                    // rather than a hint.
5762                    read_only: true,
5763                    dynamic: false,
5764                    stride: size_of::<u32>() as u32,
5765                },
5766                count: 1,
5767                flags: BindingFlags::empty(),
5768            },
5769        ];
5770        let tonemap_desc = BindGroupLayoutDesc {
5771            label: Some("tonemap scene"),
5772            entries: &tonemap_entries,
5773        };
5774        check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5775        let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5776        rollback.bind_group_layouts.push(tonemap_layout);
5777        let tonemap_set_layouts = [tonemap_layout];
5778        let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5779            label: Some("tonemap"),
5780            bind_group_layouts: &tonemap_set_layouts,
5781            push_constants: None,
5782        })?;
5783        rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5784        let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5785        let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5786        let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5787            label: Some("tonemap.slang"),
5788            spirv: TONEMAP.spirv(),
5789            wgsl: TONEMAP.wgsl(),
5790            msl: TONEMAP.msl(),
5791            // A container per entry point, for the reason the mesh module above
5792            // gives.
5793            dxil: &TONEMAP.dxil_containers(),
5794        })?;
5795        let tonemap_targets = [ColorTargetState::opaque(target_format)];
5796        let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5797            label: Some("tonemap"),
5798            layout: tonemap_pipeline_layout,
5799            vertex: ShaderEntry {
5800                module: tonemap_module,
5801                entry_point: tonemap_vertex,
5802            },
5803            fragment: Some(ShaderEntry {
5804                module: tonemap_module,
5805                entry_point: tonemap_fragment,
5806            }),
5807            // The full-screen triangle is deliberately oversized, so two of its
5808            // vertices are outside the viewport and its winding is not worth
5809            // reasoning about. `CullMode::None` is the honest setting.
5810            primitive: PrimitiveState::default(),
5811            depth_stencil: None,
5812            multisample: MultisampleState::default(),
5813            color_targets: &tonemap_targets,
5814        });
5815        device.destroy_shader_module(tonemap_module);
5816        let tonemap_pipeline = tonemap_pipeline?;
5817        rollback.pipelines.push(tonemap_pipeline);
5818        service();
5819
5820        // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5821        // leave a golden image depending on two rasterisers agreeing about
5822        // texel-centre arithmetic.
5823        let sampler = device.create_sampler(&SamplerDesc {
5824            label: Some("tonemap scene"),
5825            mag_filter: FilterMode::Nearest,
5826            min_filter: FilterMode::Nearest,
5827            mip_filter: FilterMode::Nearest,
5828            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5829            ..SamplerDesc::default()
5830        })?;
5831        rollback.samplers.push(sampler);
5832
5833        // No field, so no pass: the frame every caller of this type drew
5834        // before grass existed. The two calm wind layers are one texel each
5835        // and are what makes a field with no weather set still.
5836        //
5837        // **Before the literal below, not inside it**: the literal moves the
5838        // camera, the shared draw pipelines and the pools out of the rollback,
5839        // so a failure inside it would leak them. `GrassScene::new` releases
5840        // its own half on failure, and the literal then has nothing that can
5841        // fail.
5842        let grass = GrassScene::new(device, uploads, FRAMES_IN_FLIGHT)?;
5843
5844        Ok(Self {
5845            pool: rollback
5846                .pool
5847                .take()
5848                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5849            bucket_constants,
5850            region_step,
5851            bucket_modes,
5852            instances: rollback
5853                .instances
5854                .take()
5855                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5856            mesh_ids,
5857            skinnable_meshes,
5858            skinned_instances: Vec::new(),
5859            materials: rollback
5860                .materials
5861                .take()
5862                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5863            material_ids,
5864            probes: rollback
5865                .probes
5866                .take()
5867                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5868            probe_volume: scene.probes.volume,
5869            base_color_page,
5870            normal_page,
5871            mro_page,
5872            emissive_page,
5873            page_extents,
5874            page_layers,
5875            base_color_sampler,
5876            anisotropy,
5877            // Every slot's groups were just built naming these.
5878            slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5879            retired_pages: Vec::new(),
5880            // No frame has been recorded yet, and the counters say so rather
5881            // than reporting the count a frame *would* have.
5882            recorded_draws: 0,
5883            emit,
5884            range_limit,
5885            clusters: rollback.clusters.take(),
5886            culls_clusters,
5887            draw_constants,
5888            mesh_clusters,
5889            // One entry per description mesh, each holding one bucket per level,
5890            // where the cull pass takes a uniform cut — and nothing at all where
5891            // the amplification stage takes a per-cluster one. Read off the
5892            // bucket table that was actually built rather than re-derived from
5893            // the path.
5894            mesh_level_buckets: if emit.is_mesh() {
5895                Vec::new()
5896            } else {
5897                residents
5898                    .iter()
5899                    .enumerate()
5900                    .map(|(index, resident)| {
5901                        let base = bucket_bases[index];
5902                        (base..base + resident.levels.len())
5903                            .map(|bucket| {
5904                                u32::try_from(bucket)
5905                                    .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5906                            })
5907                            .collect()
5908                    })
5909                    .collect()
5910            },
5911            lod_error_budget: LOD_ERROR_BUDGET,
5912            lod_hold_ratio: LOD_HOLD_RATIO,
5913            // Overwritten by the first `begin_frame`, which is the only thing
5914            // that can know the viewport.
5915            shadow_lod_params: [0.0, 0.0, 0.0],
5916            extra_lights: Vec::new(),
5917            primary: rollback
5918                .primary
5919                .take()
5920                .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5921            draw_pipelines: rollback
5922                .draw_pipelines
5923                .take()
5924                .unwrap_or_else(|| unreachable!("built ahead of the camera")),
5925            views: Vec::new(),
5926            draw_tables: DrawTables {
5927                bucket_meshes,
5928                bucket_clusters,
5929                bucket_cluster_bases,
5930                mesh_levels,
5931                level_groups,
5932                level_meshes,
5933                instance_capacity: scene.capacities.instances,
5934                light_capacity: scene.capacities.lights,
5935            },
5936            frame_serial: 0,
5937            frame_scene: None,
5938            frame: 0,
5939            mesh_layout,
5940            mesh_pipeline_layout,
5941            mesh_pipeline,
5942            // Off, and unbuilt, on the ground grid's terms below: the wireframe
5943            // view is opt-in, so a caller that never asks for one draws the
5944            // frame it drew before `set_wireframe` existed.
5945            wireframe_pipeline: None,
5946            wireframe_on: false,
5947            occlusion_culling: OcclusionCulling::OFF,
5948            point_face_culls: true,
5949            skinning_culls: true,
5950            skin_shadow_reach: Vec::new(),
5951            skin_cull: skin_cull::SkinCull::default(),
5952            skinned_skipped: 0,
5953            shadow_view_tamper: None,
5954            // Off, on the line above's terms: the normals view is opt-in, so a
5955            // caller that never asks for one draws the frame it drew before
5956            // `set_normals_view` existed. It builds nothing, so there is no
5957            // second field here.
5958            normals_view: false,
5959            // Off on the same terms, and "off" here is a density of zero: the
5960            // shader's composite is exactly the identity there, so a caller who
5961            // never calls `set_fog` gets the frame byte for byte.
5962            fog: Fog::NONE,
5963            sky: Sky::NONE,
5964            atmosphere: None,
5965            sky_view: None,
5966            sky_view_build: None,
5967            lod_view: false,
5968            heatmap: false,
5969            occlusion_view: false,
5970            motion_view: false,
5971            bent_normal_view: false,
5972            cascade_view: false,
5973            atlas_view: false,
5974            // Following the camera, on the line above's terms: the selection eye
5975            // is the camera's until a caller pins it, so a renderer nobody calls
5976            // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5977            // handed before this field existed.
5978            frozen_selection_eye: None,
5979            shadow_atlas,
5980            shadow_atlas_view,
5981            shadow_placeholder,
5982            shadow_placeholder_view,
5983            shadow_sampler,
5984            shadow_pipeline,
5985            depth_masked_pipeline,
5986            shadow_clear_pipeline,
5987            rsm_pipeline,
5988            probe_gather,
5989            probe_update: scene.probes.update,
5990            // Overwritten by the first `begin_frame`, which is the only reader's
5991            // only source. Zero is the honest placeholder: no cascade has been
5992            // fitted yet, and a gather recorded against it would scale by zero
5993            // rather than by a number nobody chose.
5994            cascade_reach: 0.0,
5995            // Nothing has been fitted before the first `begin_frame`.
5996            rsm_cull_ready: false,
5997            sun_color: Vec3::ZERO,
5998            shadow_draws: std::mem::take(&mut rollback.shadow_draws),
5999            shadow_uniforms,
6000            shadow_prepare_views: Vec::new(),
6001            shadow_prepare_culls: Vec::new(),
6002            shadow_groups,
6003            shadow_selection,
6004            shadow_lights: shadow::Selection::default(),
6005            // Nothing has drawn the atlas, so the first frame draws every group
6006            // whatever it is asked for — which is also what gives the image a
6007            // defined content before anything samples it. A record is never
6008            // empty, so the first frame's is a change and takes every id past
6009            // the zero below it.
6010            shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
6011            shadow_group_id: vec![0; SHADOW_CULLS],
6012            shadow_group_writes: vec![0; SHADOW_CULLS],
6013            shadow_footprints: Vec::new(),
6014            shadow_dag_elements: std::collections::BTreeSet::new(),
6015            shadow_written: Vec::new(),
6016            shadow_moved: Vec::new(),
6017            shadow_pass_id: 0,
6018            shadow_pass_ran: Arc::new(AtomicU64::new(0)),
6019            shadow_pending: None,
6020            // A reach of zero, so every centre on the first frame is further
6021            // from what the image holds than the nothing it holds reaches —
6022            // which is the reset that frame should be.
6023            shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
6024            shadow_group_redrawn: vec![false; SHADOW_CULLS],
6025            shadow_atlas_layout: None,
6026            shadow_atlas_cached: false,
6027            shadow_cadence_reset: false,
6028            shadow_faces_redrawn: 0,
6029            shadow_cadence_request: None,
6030            shadow_atlas_clears: true,
6031            shadow_frame: 0,
6032            // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
6033            // by, so a slot has been through the whole loop before it is read.
6034            // `culls_clusters` rather than the device's feature bits: what
6035            // decides whether the cluster word is a count is whether *this
6036            // renderer* built an amplification stage.
6037            cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
6038            tonemap_layout,
6039            tonemap_pipeline_layout,
6040            tonemap_pipeline,
6041            sampler,
6042            // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
6043            // renderer nobody has called `set_exposure` on writes the frame it
6044            // wrote before the block existed.
6045            exposure: tonemap::DEFAULT_EXPOSURE,
6046            exposure_adaptation: None,
6047            // And the filmic roll-off over it: this renderer shades in linear
6048            // HDR, so a view that has asked for nothing gets the operator that
6049            // range was shaded for.
6050            tonemap_curve: tonemap::TonemapCurve::Aces,
6051            target_format,
6052            ambient_occlusion_placeholder,
6053            contact_shadow_placeholder,
6054            probe_visibility_placeholder,
6055            // Nothing has been captured, so every frame drawn before
6056            // `capture_probe_visibility` reads the placeholder and weighs every
6057            // probe at one — which is the frame this renderer drew before the
6058            // maps existed.
6059            probe_visibility: None,
6060            probe_occluders,
6061            specular_dfg,
6062            ltc_table,
6063            shadow_group_entries,
6064            // Off, and unbuilt: the grid is opt-in, so a caller that never asks
6065            // for one draws the frame it drew before this module existed.
6066            ground_grid: None,
6067            ground_grid_on: false,
6068            // Empty, and unbuilt: nothing has appended a segment, so this
6069            // renderer records the frame it recorded before the layer existed.
6070            debug_draw: DebugDraw::default(),
6071            // Unbuilt: no frame has shown the atlas — see the field.
6072            atlas_viewer: None,
6073            frame_atlas_view: false,
6074            // Full resolution, which is the frame every caller of this type drew
6075            // before there was a knob — see [`Self::set_render_scale`].
6076            render_scale: 1.0,
6077            frame_render_scale: 1.0,
6078            // The default stack the view wants, no quality clamp and no
6079            // override, which resolves to every effect this device permits but
6080            // the lens one — the frame every caller of this type drew before
6081            // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
6082            effect_request: EffectRequest::default(),
6083            device_effects: RenderEffects::all(),
6084            frame_effects: RenderEffects::DEFAULT_STACK,
6085            // What the switch says today, so a renderer built and never opened
6086            // still describes the frame it would draw. `begin_frame` reads it
6087            // again for the frame it opens.
6088            frame_ssao_blurs: crate::ssao::blur_passes(),
6089            // No frame has been recorded yet, on `recorded_draws`' terms.
6090            recorded_fullscreen: 0,
6091            // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
6092            recorded_debug_draw: 0,
6093            recorded_tile_clears: 0,
6094            // No bodies, so no pass: the frame every caller of this type drew
6095            // before water existed. Nothing is allocated until a body is set.
6096            water: WaterBodies::new(FRAMES_IN_FLIGHT),
6097            recorded_water_draws: 0,
6098            grass,
6099            // No frame has begun.
6100            frame_grass: None,
6101            wind: crcbl_shaders::wind::WindParams::default(),
6102            recorded_grass_draws: 0,
6103            // The build's own batch joins once it is submitted, which is after
6104            // this returns — see `build_on_path`.
6105            uploads_in_flight: Vec::new(),
6106        })
6107    }
6108
6109    /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
6110    /// fragment entry points.
6111    ///
6112    /// One helper because every post pass in this crate wants the same
6113    /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
6114    /// differing in the module, the layout and the target format alone. The
6115    /// tonemap's stays written out where it is: it is the one that carries the
6116    /// *why* of the shape, and this is the shape repeated.
6117    ///
6118    /// The module is destroyed before the pipeline result is unwrapped, so a
6119    /// failing creation leaks nothing.
6120    ///
6121    /// # Errors
6122    ///
6123    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6124    fn build_fullscreen(
6125        device: &dyn Device,
6126        label: &str,
6127        shader: &crcbl_shaders::Shader,
6128        layout: PipelineLayoutHandle,
6129        color_targets: &[ColorTargetState],
6130    ) -> Result<GraphicsPipelineHandle, HalError> {
6131        Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
6132    }
6133
6134    /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
6135    /// against an attachment it does not write.
6136    ///
6137    /// The state is [`DepthStencilState::equal_depth_read_only`], whose
6138    /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
6139    /// depth must equal what is already there". One caller, [`crate::sky_pass`],
6140    /// which emits its triangle at the far plane so that the test selects
6141    /// exactly the pixels no geometry covered — see that module.
6142    ///
6143    /// # Errors
6144    ///
6145    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6146    fn build_tested_fullscreen(
6147        device: &dyn Device,
6148        label: &str,
6149        shader: &crcbl_shaders::Shader,
6150        layout: PipelineLayoutHandle,
6151        color_targets: &[ColorTargetState],
6152        depth_format: Format,
6153    ) -> Result<GraphicsPipelineHandle, HalError> {
6154        Self::build_fullscreen_with(
6155            device,
6156            label,
6157            shader,
6158            layout,
6159            color_targets,
6160            Some(DepthStencilState::equal_depth_read_only(depth_format)),
6161        )
6162    }
6163
6164    /// The body of the two above, which differ in their depth state and in
6165    /// nothing else.
6166    ///
6167    /// # Errors
6168    ///
6169    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6170    fn build_fullscreen_with(
6171        device: &dyn Device,
6172        label: &str,
6173        shader: &crcbl_shaders::Shader,
6174        layout: PipelineLayoutHandle,
6175        color_targets: &[ColorTargetState],
6176        depth_stencil: Option<DepthStencilState>,
6177    ) -> Result<GraphicsPipelineHandle, HalError> {
6178        let vertex = entry(shader, Stage::Vertex)?;
6179        let fragment = entry(shader, Stage::Fragment)?;
6180        let module = device.create_shader_module(&ShaderModuleDesc {
6181            label: Some(shader.source()),
6182            spirv: shader.spirv(),
6183            wgsl: shader.wgsl(),
6184            msl: shader.msl(),
6185            // A container per entry point, for the reason the mesh module gives.
6186            dxil: &shader.dxil_containers(),
6187        })?;
6188        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
6189            label: Some(label),
6190            layout,
6191            vertex: ShaderEntry {
6192                module,
6193                entry_point: vertex,
6194            },
6195            fragment: Some(ShaderEntry {
6196                module,
6197                entry_point: fragment,
6198            }),
6199            // The triangle is deliberately oversized, so two of its vertices are
6200            // outside the viewport and its winding is not worth reasoning about.
6201            primitive: PrimitiveState::default(),
6202            depth_stencil,
6203            multisample: MultisampleState::default(),
6204            color_targets,
6205        });
6206        device.destroy_shader_module(module);
6207        pipeline
6208    }
6209
6210    /// Builds a full-screen-triangle pipeline that writes a **depth**
6211    /// attachment and no colour one.
6212    ///
6213    /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
6214    /// no colour target at all, and a depth state whose comparison always
6215    /// passes so every texel of the destination takes the value the fragment
6216    /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
6217    /// in this file uses would be wrong here — this pass is not depth-testing
6218    /// anything, it is writing a reduction, and a test against the target's
6219    /// undefined contents would drop texels at random.
6220    ///
6221    /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
6222    /// a method rather than moving there because the module and the
6223    /// destroy-before-unwrap above are this file's, and both take it in exactly
6224    /// as `crate::ssao` takes the sibling.
6225    ///
6226    /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
6227    /// fragment stage per pyramid, and a stage looked up by kind would be
6228    /// ambiguous.
6229    ///
6230    /// # Errors
6231    ///
6232    /// [`HalError`] from the module or the pipeline.
6233    fn build_depth_fullscreen(
6234        device: &dyn Device,
6235        label: &str,
6236        shader: &crcbl_shaders::Shader,
6237        vertex: &str,
6238        fragment: &str,
6239        layout: PipelineLayoutHandle,
6240        format: Format,
6241    ) -> Result<GraphicsPipelineHandle, HalError> {
6242        let module = device.create_shader_module(&ShaderModuleDesc {
6243            label: Some(shader.source()),
6244            spirv: shader.spirv(),
6245            wgsl: shader.wgsl(),
6246            msl: shader.msl(),
6247            dxil: &shader.dxil_containers(),
6248        })?;
6249        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
6250            label: Some(label),
6251            layout,
6252            vertex: ShaderEntry {
6253                module,
6254                entry_point: vertex,
6255            },
6256            fragment: Some(ShaderEntry {
6257                module,
6258                entry_point: fragment,
6259            }),
6260            primitive: PrimitiveState::default(),
6261            depth_stencil: Some(DepthStencilState {
6262                format,
6263                depth_write: true,
6264                depth_compare: CompareOp::Always,
6265                stencil: None,
6266                bias: DepthBias::default(),
6267            }),
6268            multisample: MultisampleState::default(),
6269            color_targets: &[],
6270        });
6271        device.destroy_shader_module(module);
6272        pipeline
6273    }
6274
6275    /// Creates the geometry pool and makes every mesh of `scene` resident in it.
6276    ///
6277    /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
6278    /// the pool is not the rollback's until this has returned, so a failure
6279    /// between creating it and flushing the last upload releases it here.
6280    fn build_geometry(
6281        device: &dyn Device,
6282        queue: QueueHandle,
6283        scene: &SceneDesc<'_>,
6284        service: &mut dyn FnMut(),
6285    ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
6286        let mut pool = MeshPool::new(
6287            device,
6288            &MeshPoolDesc {
6289                label: Some("forward geometry"),
6290                vertex_capacity: scene.capacities.vertices,
6291                index_capacity: scene.capacities.indices,
6292                mesh_capacity: scene.capacities.meshes,
6293            },
6294        )?;
6295        match Self::residents(device, queue, &mut pool, scene, service) {
6296            Ok(residents) => Ok((pool, residents)),
6297            Err(error) => {
6298                pool.destroy(device);
6299                Err(error)
6300            }
6301        }
6302    }
6303
6304    /// Creates the material table and fills it with `scene`'s rows, returning it
6305    /// and the id of each.
6306    ///
6307    /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
6308    /// the table is not the rollback's until this has returned.
6309    fn build_materials(
6310        device: &dyn Device,
6311        scene: &SceneDesc<'_>,
6312    ) -> Result<(MaterialTable, Vec<u32>), HalError> {
6313        let mut materials = MaterialTable::new(
6314            device,
6315            &MaterialTableDesc {
6316                label: Some("forward"),
6317                capacity: scene.capacities.materials,
6318            },
6319        )?;
6320        match Self::material_rows(device, &mut materials, &scene.materials) {
6321            Ok(ids) => Ok((materials, ids)),
6322            Err(error) => {
6323                materials.destroy(device);
6324                Err(error)
6325            }
6326        }
6327    }
6328
6329    /// Inserts `rows` **in order** and returns the id of each.
6330    ///
6331    /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6332    /// be released on a failure without the borrow that filling it takes, which
6333    /// is the same shape [`ForwardRenderer::residents`] has.
6334    ///
6335    /// **In order, because row 0 is not this function's to choose**: it is what
6336    /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6337    /// without a material id shades with. Inserting a description's rows in any
6338    /// other order would move that row under every caller — see
6339    /// [`SceneDesc::materials`], which is where it is a caller's decision.
6340    fn material_rows(
6341        device: &dyn Device,
6342        materials: &mut MaterialTable,
6343        rows: &[mesh::GpuMaterial],
6344    ) -> Result<Vec<u32>, HalError> {
6345        let mut ids = Vec::with_capacity(rows.len());
6346        for row in rows {
6347            let handle = materials.insert(device, row)?;
6348            // The id is asked for rather than assumed, because the number an
6349            // instance carries is this one and nothing else knows it.
6350            ids.push(materials.index(handle).ok_or_else(|| {
6351                HalError::Backend(
6352                    "a material inserted into an empty table did not resolve".to_string(),
6353                )
6354            })?);
6355        }
6356        Ok(ids)
6357    }
6358
6359    /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6360    /// the transfers have completed.
6361    ///
6362    /// The calls are §3.1's upload path in order: the copies are recorded and
6363    /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6364    /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6365    /// before they have.
6366    ///
6367    /// **In description order**, which is what makes a mesh's table id a
6368    /// property of the description rather than of this loop — the second mesh
6369    /// uploaded is the pool's first resident at a non-zero base vertex, which is
6370    /// what the module docs call the one thing that can tell a working base
6371    /// vertex from a cancelled one.
6372    ///
6373    /// A DAG is **one upload per level**. Every level was decimated separately,
6374    /// so a coarser level's vertices are wherever the collapses put them and
6375    /// belong to no vertex of the level below — a DAG is several vertex ranges,
6376    /// and the pool suballocates in vertices, so several ranges means several
6377    /// uploads. Level 0 goes first, so every other level starts past it and the
6378    /// offsets a cluster carries are non-negative; that is checked rather than
6379    /// assumed, because the pool's free list makes no promise about where a mesh
6380    /// lands.
6381    fn residents(
6382        device: &dyn Device,
6383        queue: QueueHandle,
6384        pool: &mut MeshPool,
6385        scene: &SceneDesc<'_>,
6386        service: &mut dyn FnMut(),
6387    ) -> Result<Vec<ResidentMesh>, HalError> {
6388        let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6389            Vec::with_capacity(scene.meshes.len());
6390        for desc in &scene.meshes {
6391            match &desc.geometry {
6392                Geometry::Flat {
6393                    vertices,
6394                    indices,
6395                    uv_range,
6396                    flags,
6397                    ..
6398                } => {
6399                    uploaded.push(vec![pool.upload(
6400                        device,
6401                        queue,
6402                        &MeshUpload {
6403                            label: &desc.label,
6404                            vertices,
6405                            indices,
6406                            uv_range: *uv_range,
6407                            flags: *flags,
6408                        },
6409                    )?]);
6410                    service();
6411                }
6412                Geometry::Dag {
6413                    levels,
6414                    dag,
6415                    uv_range,
6416                    flags,
6417                } => {
6418                    let mut handles = Vec::with_capacity(levels.len());
6419                    for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6420                        handles.push(pool.upload(
6421                            device,
6422                            queue,
6423                            &MeshUpload {
6424                                label: &format!("{} level {depth}", desc.label),
6425                                vertices,
6426                                indices: &level.indices(),
6427                                // Level 0's range for every level, which is the
6428                                // one the mesh path reads whichever level it
6429                                // draws — see `Geometry::Dag::uv_range`.
6430                                uv_range: *uv_range,
6431                                // And the description's flags for every level,
6432                                // for the same reason: the levels are one
6433                                // surface, so a tangent frame either describes
6434                                // all of them or none.
6435                                flags: *flags,
6436                            },
6437                        )?);
6438                        service();
6439                    }
6440                    uploaded.push(handles);
6441                }
6442            }
6443        }
6444
6445        pool.flush(device)?;
6446        service();
6447        // The table index is the only number that leaves here — where the
6448        // geometry actually is reaches the GPU through the mesh table, and the
6449        // draw arguments are built from that table by a shader. `MeshPool::mesh`
6450        // is still asked, because it is the call that refuses a mesh whose
6451        // upload has not completed, and an id for a mesh that is not there yet
6452        // would be a draw of nothing.
6453        let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6454            (Some(_), Some(id)) => Ok(id),
6455            _ => Err(MeshPoolError::NotResident { handle }),
6456        };
6457        let base_vertex = |handle| match pool.mesh(handle) {
6458            Some(range) => Ok(range.base_vertex),
6459            None => Err(MeshPoolError::NotResident { handle }),
6460        };
6461
6462        let mut residents = Vec::with_capacity(uploaded.len());
6463        for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6464            // **Relative to level 0's base**, because that is the base the
6465            // instance resolves through its mesh id and the one the stage adds
6466            // this on top of. A level that landed *below* level 0 would make the
6467            // sum wrap, so it is refused here rather than drawn as another
6468            // mesh's vertices. A flat mesh is one level and reads zero.
6469            let level_zero = base_vertex(handles[0])?;
6470            let mut vertex_bases = Vec::with_capacity(handles.len());
6471            for (depth, &handle) in handles.iter().enumerate() {
6472                let base = base_vertex(handle)?;
6473                vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6474                    HalError::InvalidDescriptor(format!(
6475                        "{} level {depth} landed at vertex {base}, below level 0's \
6476                         {level_zero}, so its clusters cannot name their own geometry",
6477                        desc.label
6478                    ))
6479                })?);
6480            }
6481            residents.push(ResidentMesh {
6482                levels: handles
6483                    .iter()
6484                    .map(|&handle| resolve(handle))
6485                    .collect::<Result<_, _>>()?,
6486                vertex_bases,
6487                // Matched on the description rather than counted off `handles`,
6488                // so a DAG decimated to a single level is still refused: what
6489                // makes a mesh skinnable is that every draw of it reads one
6490                // vertex run, and that is a property of the geometry rather than
6491                // of how many levels it happened to arrive with.
6492                skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6493            });
6494        }
6495        Ok(residents)
6496    }
6497
6498    /// Rotates to the next frame's uniform buffer and instance buffer, writes
6499    /// this frame's camera and light into the first, and uploads whatever
6500    /// changed into the second.
6501    ///
6502    /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6503    /// Separate from `add_passes` because the write happens on the CPU and the
6504    /// passes are recorded on the GPU timeline: fusing them would hide the ring
6505    /// rotation inside a function whose name says nothing about it.
6506    ///
6507    /// **It moves nothing.** Every object's transform is the caller's, written
6508    /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6509    /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6510    /// frame in which nothing moved uploads no instance bytes at all. The
6511    /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6512    /// spins it; a still scene is free.
6513    ///
6514    /// It also writes this frame's **cull parameters** — the camera's frustum,
6515    /// extracted from the very same view-projection the uniform block carries,
6516    /// so the pass that decides what is on screen and the pass that draws it
6517    /// cannot be looking at two different cameras — and zeroes the counters the
6518    /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6519    /// zeroes come from the host.
6520    ///
6521    /// # Errors
6522    ///
6523    /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6524    /// draw-generation buffers could not be written.
6525    pub fn begin_frame(
6526        &mut self,
6527        device: &dyn Device,
6528        camera: &Camera,
6529        light: &DirectionalLight,
6530        extent: (u32, u32),
6531    ) -> Result<(), HalError> {
6532        // First, before anything this frame could release or rewrite.
6533        self.retire_uploads(device)?;
6534        // The instance pool owns the ring, so its slot is the frame index the
6535        // uniform buffer and the bind group below are picked with.
6536        self.frame = self.instances.rotate();
6537        self.instances.flush(device)?;
6538        self.begin_frame_body(device, camera, light, extent)
6539    }
6540
6541    /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6542    /// call with the skinning plan folded into it.
6543    ///
6544    /// It does four things in the one order that is correct, which is why it is
6545    /// a call and not a note in someone's docs:
6546    ///
6547    /// 1. rotates the instance ring, so the frame slot exists;
6548    /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6549    ///    uploads the palettes and **moves the ping-pong** — the only place the
6550    ///    parity ever moves;
6551    /// 3. points every object placed by
6552    ///    [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6553    ///    region the parity now names;
6554    /// 4. uploads the instance delta, so those bases are the ones this frame
6555    ///    draws.
6556    ///
6557    /// Do those three and four in the other order and the objects carry the
6558    /// previous frame's half — a character posed one frame late, every frame,
6559    /// with nothing to report it. A caller never sees a parity or a table id, and
6560    /// so cannot get that wrong.
6561    ///
6562    /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6563    /// this frame animates. A frame with **no** skinned object still calls this
6564    /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6565    /// otherwise re-dispatch whichever frame last used it.
6566    ///
6567    /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6568    /// the one that orders the dispatch before the draws.
6569    ///
6570    /// # Errors
6571    ///
6572    /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6573    /// palette, a binding count that is not the region's vertex count, more than
6574    /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6575    /// refused, this renderer's own uniform and instance writes included.
6576    ///
6577    /// # Panics
6578    ///
6579    /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6580    /// its rings are indexed by this renderer's frame slot, and
6581    /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6582    pub fn begin_skinned_frame(
6583        &mut self,
6584        device: &dyn Device,
6585        skinning: &mut Skinning,
6586        ranges: &[SkinRange<'_>],
6587        camera: &Camera,
6588        light: &DirectionalLight,
6589        extent: (u32, u32),
6590    ) -> Result<(), SkinningError> {
6591        // First, on `begin_frame`'s terms.
6592        self.retire_uploads(device)?;
6593        self.frame = self.instances.rotate();
6594        skinning.begin_frame(device, self.frame, ranges)?;
6595        self.point_skinned_instances(skinning.parity());
6596        self.instances.flush(device)?;
6597        self.begin_frame_body(device, camera, light, extent)?;
6598        Ok(())
6599    }
6600
6601    /// Whether this frame records the irradiance probes' two
6602    /// updater passes.
6603    ///
6604    /// The scene's own answer and the console's together: the volume decides
6605    /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6606    /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6607    /// on/off pair a pricing run reads the two passes' cost off with everything
6608    /// else held still.
6609    ///
6610    /// **It is not the whole condition.** The map is cascade 0's own draws, so
6611    /// the pass is recorded only where that cascade is being drawn too — see
6612    /// `add_shadow_pass`, which is where the rest of it is.
6613    fn probe_update_runs(&self) -> bool {
6614        self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6615    }
6616
6617    /// The six side-plane sets a point light's face culls test, or `None` for
6618    /// a light that is not a point — or with the face culls switched off, which
6619    /// is one cull against the light's box drawn into all six faces.
6620    ///
6621    /// `faces` are the light's face matrices in face order, the ones its tiles
6622    /// render through.
6623    fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6624        if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6625            return None;
6626        }
6627        let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6628        Some(crate::cull::face_planes(&matrices))
6629    }
6630
6631    /// Every punctual shadow face this frame draws into the punctual reflective
6632    /// shadow map, in the order the pass draws them and the producer table lists
6633    /// them.
6634    ///
6635    /// **One list for both halves of the updater**, and that is the point:
6636    /// `add_shadow_pass` sets a viewport from a face's
6637    /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6638    /// of the matching producer row, so a face the pass drew and a row the
6639    /// gather walked have to be the same face. Building the two from separate
6640    /// filters is two things that can drift, and the drift would be a light
6641    /// bouncing another light's map.
6642    ///
6643    /// **The occupied slots this frame redraws**, which is the same set
6644    /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6645    /// block and its draws are a shadow cull's, and
6646    /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6647    /// it is holding.
6648    ///
6649    /// # Every occupied tile, and no budget of its own
6650    ///
6651    /// The producers are exactly the atlas's occupied faces — up to
6652    /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6653    /// them — rather than the highest-ranked light or some smaller count.
6654    ///
6655    /// **Because the budget already exists and is spent.**
6656    /// [`shadow::Selection`] has ranked these lights by projected screen
6657    /// influence and handed out every tile there is; a second budget on top
6658    /// would rank the same lights again, differently, and produce a light that
6659    /// casts a shadow and lends no bounce. That is a difference no picture shows
6660    /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6661    /// and it is the kind of quiet inconsistency the two halves of one light are
6662    /// worst placed to have.
6663    ///
6664    /// It is affordable at the extent that was chosen for it:
6665    /// `apps/lantern` lights seven faces, and
6666    /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6667    /// carries the sweep that priced them.
6668    ///
6669    /// **Empty where shadows are off**, for that same reason — a punctual face
6670    /// *is* a shadow view. The sun's half is not, which is what
6671    /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6672    /// sun's bounce and loses every punctual one, rather than switching the
6673    /// whole updater off with them.
6674    fn punctual_faces(&self) -> Vec<PunctualFace> {
6675        if !self.probe_update_runs() {
6676            return Vec::new();
6677        }
6678        // A frame with the shadows switched off draws no atlas, so no group of
6679        // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6680        // branch has still written every one of these views and dispatched every
6681        // one of these culls, for this pass to draw through.
6682        let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6683        let mut faces = Vec::new();
6684        for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6685            let Some(held) = *held else {
6686                continue;
6687            };
6688            if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6689                continue;
6690            }
6691            let Some(light) = self.extra_lights.get(held.light) else {
6692                continue;
6693            };
6694            // A spot draws face 0 alone and a point light all six, each through
6695            // its own matrix into its own tile — `shadow::tile_span` is the same
6696            // function `Selection` allocated the run with, so a face here and a
6697            // tile there cannot disagree about how many there are.
6698            for face in 0..shadow::tile_span(light) {
6699                let tile = rsm::punctual_tile(held.base + face);
6700                faces.push(PunctualFace {
6701                    view: shadow_view(slot, face),
6702                    cull: shadow_cull(slot),
6703                    face,
6704                    tile,
6705                    producer: producer_row(light, tile),
6706                });
6707            }
6708        }
6709        faces
6710    }
6711
6712    /// Puts an object in the scene and returns the handle that names it.
6713    ///
6714    /// An instance in the pool **is** an object in the scene: the frame records
6715    /// a fixed number of draws and the cull pass decides which instances they
6716    /// walk, so adding one costs a slot in an array and not a command. It is
6717    /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6718    /// uploads it.
6719    ///
6720    /// # The index it lands at is not decoration
6721    ///
6722    /// `draw_gen.slang` keys topic 25's hysteresis state by the
6723    /// instance's **array index**, at `instance_index * group_stride`, and
6724    /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6725    /// record of which of a DAG's groups an object had expanded belongs to the
6726    /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6727    /// handed to the next `add_instance`, which inherits it. What that costs is
6728    /// one frame selected against a history that is not this object's, and the
6729    /// next frame's own judgement replaces it; it is never a wrong picture,
6730    /// because every group is judged afresh whatever the state said.
6731    ///
6732    /// That inheritance is inert while the scene holds **one** instance of a DAG
6733    /// mesh, which is every frame the engine has drawn so far — one instance's
6734    /// run has no previous occupant, and a flat mesh's
6735    /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6736    /// nothing indexes the state for it. It stops being inert the moment an
6737    /// application places a second.
6738    ///
6739    /// [`remove_instance`]: ForwardRenderer::remove_instance
6740    ///
6741    /// # A DAG mesh needs a device that can choose a level
6742    ///
6743    /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6744    /// **no** amplification stage in front of it emits every cluster of the
6745    /// bucket, which for a DAG is every level at once — several overlapping
6746    /// copies of one surface. This does not refuse it, because it has no
6747    /// vocabulary for that refusal; a caller placing a DAG asks
6748    /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6749    /// says yes. A flat mesh is unaffected on every path.
6750    ///
6751    /// # Errors
6752    ///
6753    /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6754    /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6755    /// what a caller sizes it with.
6756    ///
6757    /// # Panics
6758    ///
6759    /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6760    /// the description this renderer was built from. Both are indices a caller
6761    /// wrote against a description it holds, so an out-of-range one is a mistake
6762    /// in the calling code rather than a condition the frame can be in — and the
6763    /// alternative is an object silently drawn as some other mesh, in some other
6764    /// colour.
6765    pub fn add_instance(
6766        &mut self,
6767        desc: &InstanceDesc,
6768    ) -> Result<InstanceHandle, InstancePoolError> {
6769        let instance = self.gpu_instance(desc);
6770        self.instances.insert(&instance)
6771    }
6772
6773    /// Rewrites the object `handle` names — its mesh, its material and its
6774    /// transform, all three.
6775    ///
6776    /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6777    /// nothing, rather than overwriting whatever took its slot.
6778    ///
6779    /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6780    /// the element and nothing else: an object that did not move costs no
6781    /// transfer at all.
6782    ///
6783    /// # Panics
6784    ///
6785    /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6786    pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6787        let mut instance = self.gpu_instance(desc);
6788        instance.flags |= self.kept_flags(handle);
6789        self.instances.set(handle, &instance);
6790    }
6791
6792    /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6793    /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6794    /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6795    /// handle, whose rewrite writes nothing anyway.
6796    fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6797        self.instances.get(handle).map_or(0, |record| {
6798            record.flags
6799                & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6800        })
6801    }
6802
6803    /// Sets whether `handle` casts a shadow. Every instance starts casting.
6804    ///
6805    /// **Every shadow map and nothing else**: an instance that casts none is
6806    /// rejected by the cull of the sun's cascades and of every shadowed light,
6807    /// on every geometry path, so it lands in no tile of the atlas — and in no
6808    /// reflective shadow map, which draws those same culls' survivors, so it
6809    /// bounces no light into the probes either. Every camera still draws it,
6810    /// and it still receives the shadows the rest of the scene casts.
6811    ///
6812    /// What a model drawn for an icon wants, placed where the scene's sun can
6813    /// see it: see [`ViewBackground::Transparent`] and
6814    /// [`set_instance_views`](Self::set_instance_views).
6815    ///
6816    /// A change redraws every shadow map whose cull the instance could be kept
6817    /// by, because it is a write [`InstancePool::take_written`] names. Not a
6818    /// move, on
6819    /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6820    /// handle is ignored.
6821    pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6822        if let Some(record) = self.instances.get(handle) {
6823            let flags = if casts {
6824                record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6825            } else {
6826                record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6827            };
6828            self.instances.set_flags(handle, flags);
6829        }
6830    }
6831
6832    /// Whether `handle` casts a shadow, or `None` for a stale handle.
6833    #[must_use]
6834    pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6835        self.instances
6836            .get(handle)
6837            .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6838    }
6839
6840    /// Takes the object `handle` names back out of the scene, freeing its slot.
6841    ///
6842    /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6843    /// no longer records a draw per object: `cull.slang` asks whether an instance
6844    /// is live before it reads anything else, so removing an object and culling
6845    /// it off screen take the same path out of the frame. An instance left in the
6846    /// pool would be drawn wherever its transform put it.
6847    ///
6848    /// A stale handle removes nothing. Takes effect at the next
6849    /// [`ForwardRenderer::begin_frame`], on
6850    /// [`ForwardRenderer::set_instance`]'s terms.
6851    pub fn remove_instance(&mut self, handle: InstanceHandle) {
6852        self.instances.remove(handle);
6853    }
6854
6855    /// Captures a visibility map for every probe, from the static geometry
6856    /// standing in the scene right now.
6857    ///
6858    /// The probe visibility rung: each probe records how far
6859    /// away the nearest surface is in every direction, and `mesh.slang`'s
6860    /// `probe_irradiance` then weighs each of a fragment's eight probes by
6861    /// whether it can *see* that fragment — so a probe on the far side of a wall
6862    /// contributes nothing and a room stops lighting the room next door.
6863    /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6864    /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6865    /// format.
6866    ///
6867    /// # Call it once, after the scene's walls are placed
6868    ///
6869    /// **A description carries no instances** — [`SceneDesc`] is meshes,
6870    /// materials, a page and the probe rows, and the objects arrive afterwards
6871    /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6872    /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6873    /// call that has the room in it, and an application makes it once its static
6874    /// geometry is placed.
6875    ///
6876    /// A caller that never makes it draws exactly the frame this renderer drew
6877    /// before the maps existed: every group names the one-texel placeholder,
6878    /// which no surface is further away than, and every probe keeps all of its
6879    /// weight.
6880    ///
6881    /// **It is a capture of geometry and not a bake of light.** Nothing about
6882    /// the lights is recorded, every one of them still moves, and the rows the
6883    /// probes carry are untouched.
6884    ///
6885    /// # What it sees, and what it does not
6886    ///
6887    /// Every instance live in the pool when it is called, at the transform it
6888    /// then has, rasterised from its mesh's level-0 triangles into six 90°
6889    /// faces per probe. Objects that move
6890    /// afterwards keep the occlusion they had here, which is the accepted limit
6891    /// this technique has everywhere it is used — a probe volume is about the
6892    /// walls. Recapturing after a wall moves is this call again.
6893    ///
6894    /// **The device must be idle.** The previous capture's image is released
6895    /// here, and a frame in flight may still be reading it.
6896    ///
6897    /// # Errors
6898    ///
6899    /// [`HalError`] from the capture. The previous maps are kept on the failing
6900    /// path, so a renderer that has captured once and then failed goes on
6901    /// drawing with what it had.
6902    pub fn capture_probe_visibility(
6903        &mut self,
6904        device: &dyn Device,
6905        queue: QueueHandle,
6906    ) -> Result<(), HalError> {
6907        let placed: Vec<crate::probe_visibility::Occluder> = self
6908            .instances
6909            .live()
6910            .into_iter()
6911            .map(|record| crate::probe_visibility::Occluder {
6912                mesh: record.mesh,
6913                transform: Mat4::from_cols_array(&record.transform),
6914            })
6915            .collect();
6916        let Some(uploaded) = crate::probe_capture::capture(
6917            device,
6918            queue,
6919            &self.probe_volume,
6920            &self.probe_occluders,
6921            &placed,
6922        )?
6923        else {
6924            // No probes, or nothing placed for a map to be about. Leaving the
6925            // placeholder bound is the honest answer, and it is what a scene
6926            // with no probes has always read.
6927            return Ok(());
6928        };
6929        // The cached groups name the view this replaces, so they go before it
6930        // does — a bind group outliving the image it names is a validation
6931        // error on every backend that checks, and a use-after-free on the ones
6932        // that do not.
6933        for slot in &mut self.primary.screen_channel_groups {
6934            if let Some((_, stale)) = slot.take() {
6935                device.destroy_bind_group(stale);
6936            }
6937        }
6938        if let Some(previous) = self.probe_visibility.replace(uploaded) {
6939            previous.destroy(device);
6940        }
6941        Ok(())
6942    }
6943
6944    /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6945    /// captures the probes the step exposed.
6946    ///
6947    /// The irradiance probes' scrolling: each level moves a whole
6948    /// number of its own probe spacings towards `point`, so the probes that stay
6949    /// inside it stand exactly where they stood and go on being addressed at the
6950    /// rows they already had — and only the slabs the step brought in are
6951    /// captured. Answers how many rows that was, which is **zero for the
6952    /// ordinary frame**: the point has to travel half a probe spacing before the
6953    /// nearest whole step changes at all.
6954    ///
6955    /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6956    /// rule and `exposed` beside it is the invalidation; this is the two of them
6957    /// plus the device work they imply — the visibility maps of the exposed
6958    /// rows, and the position table the reflective-shadow-map gather reads.
6959    ///
6960    /// # A volume authored to cover its whole world does not move
6961    ///
6962    /// The steps are the ones that centre a level on `point`, and a caller whose
6963    /// volume is already the world it is in wants none of them — so a caller
6964    /// passes the point it wants the *centre* at rather than the camera outright
6965    /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6966    /// their own modules say so.
6967    ///
6968    /// # A step stalls, and a frame that does not step costs a comparison
6969    ///
6970    /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6971    /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6972    /// one does — so a step drains the device before it rewrites anything and
6973    /// leaves it drained. That is a stall, and it is why the probe records price a step
6974    /// separately from a frame. A call that steps nothing returns before the
6975    /// wait, so the ordinary frame pays a rounding per level and per axis and
6976    /// nothing else.
6977    ///
6978    /// It may therefore be called from a frame loop, but **not after**
6979    /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6980    /// recorded: the header it moves is the one that frame's uniform block has
6981    /// already been written from.
6982    ///
6983    /// A renderer that has never captured re-centres the header and captures
6984    /// nothing: there is no image to write slabs into, every group still names
6985    /// the placeholder, and the first
6986    /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6987    /// whole.
6988    ///
6989    /// # It moves the geometry and not the light
6990    ///
6991    /// What a step re-captures is the *visibility* of the probes it exposed,
6992    /// which is what the maps are about. The **rows** are not touched, so under
6993    /// [`ProbeUpdate::Authored`] a probe
6994    /// that a step brought in keeps the irradiance the probe that left had —
6995    /// authored for somewhere else. A volume that scrolls therefore wants
6996    /// [`ProbeUpdate::EveryFrame`], whose
6997    /// gather refills every row from the scene each frame and has no such gap;
6998    /// `docs/backlog.md` carries what an authored one would need instead.
6999    ///
7000    /// # Errors
7001    ///
7002    /// [`HalError`] from the recapture or from the position rewrite. The volume
7003    /// keeps the steps it had on either failing path, so a renderer that could
7004    /// not capture a slab does not go on drawing with rows about somewhere else.
7005    pub fn follow_probe_volume(
7006        &mut self,
7007        device: &dyn Device,
7008        queue: QueueHandle,
7009        point: [f32; 3],
7010    ) -> Result<u32, HalError> {
7011        let mut moved = self.probe_volume;
7012        let rows = moved.follow(point);
7013        if rows.is_empty() && moved.steps == self.probe_volume.steps {
7014            return Ok(0);
7015        }
7016        // **Before anything is written**, so a caller may make this call from
7017        // its frame loop: the layers the recapture rewrites and the position
7018        // table beside them are read by whatever frames are still in flight, and
7019        // neither is a ring. A frame that does not step never reaches this line,
7020        // which is what keeps the ordinary frame free of it.
7021        device.wait_idle()?;
7022        if let Some(captured) = &self.probe_visibility {
7023            let placed: Vec<crate::probe_visibility::Occluder> = self
7024                .instances
7025                .live()
7026                .into_iter()
7027                .map(|record| crate::probe_visibility::Occluder {
7028                    mesh: record.mesh,
7029                    transform: Mat4::from_cols_array(&record.transform),
7030                })
7031                .collect();
7032            crate::probe_capture::recapture(
7033                device,
7034                queue,
7035                &moved,
7036                &self.probe_occluders,
7037                &placed,
7038                &rows,
7039                captured.image,
7040            )?;
7041        }
7042        // After the capture, so a volume whose slabs could not be drawn keeps
7043        // the header its maps are about.
7044        if let Some(gather) = &self.probe_gather {
7045            gather.rewrite_positions(device, &moved)?;
7046        }
7047        self.probe_volume = moved;
7048        Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
7049    }
7050
7051    /// Where the irradiance clipmap stands right now — the header the frame
7052    /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
7053    /// included.
7054    #[must_use]
7055    pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
7056        self.probe_volume
7057    }
7058
7059    /// `draws` split by the **whole** material mode, each partition under the
7060    /// depth-only pipeline that honours it — what the depth prepass and every
7061    /// shadow view record instead of one call list under one pipeline.
7062    ///
7063    /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
7064    /// split total: the opaque buckets are drawn with
7065    /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
7066    /// fragment stage — the masked ones with
7067    /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
7068    /// `discard`, and each of those has a [`CullMode::None`] twin for the
7069    /// buckets whose material is double-sided. A scene with one cutout in it
7070    /// pays a fragment stage for that mesh's draws and for no others; before
7071    /// this it paid for the whole frame, which on lavapipe roughly doubled the
7072    /// prepass and added two thirds to the shadow pass.
7073    ///
7074    /// **Both depth passes and not just the atlas.** A double-sided plate whose
7075    /// back face the prepass culled writes no depth there, so the colour pass's
7076    /// `GreaterOrEqual` test against it rejects the fragment and the surface is
7077    /// missing from the frame; and a cascade that culled it casts no shadow.
7078    fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
7079        self.partitions(
7080            draws,
7081            mesh::GpuMaterial::MODE_MASK,
7082            &[
7083                (DEPTH_MODES[0], Some(self.shadow_pipeline.single)),
7084                (
7085                    DEPTH_MODES[1],
7086                    self.depth_masked_pipeline.map(|masked| masked.single),
7087                ),
7088                (DEPTH_MODES[2], self.shadow_pipeline.double),
7089                (
7090                    DEPTH_MODES[3],
7091                    self.depth_masked_pipeline.and_then(|masked| masked.double),
7092                ),
7093            ],
7094        )
7095    }
7096
7097    /// `draws` split by the material's **side** alone, each partition under the
7098    /// matching half of `pipelines` — what the colour pass and the two
7099    /// reflective shadow maps record.
7100    ///
7101    /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
7102    /// four, and the difference is the whole of what these passes do not care
7103    /// about: their pipelines carry a fragment stage either way and cut the
7104    /// alpha mask inside it, so a masked bucket and an opaque one are the same
7105    /// draw here. What they cannot express inside the stage is the cull mode.
7106    fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
7107        self.partitions(draws, mesh::GpuMaterial::DOUBLE_SIDED, &pipelines.by_side())
7108    }
7109
7110    /// Resolves a description's mesh and material indices into the table ids the
7111    /// GPU reads.
7112    ///
7113    /// The whole record every time, because [`InstancePool::set`] writes the
7114    /// whole record: an instance that lost either id would name entry 0 of that
7115    /// table, which is a mesh and a material rather than an absence.
7116    fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
7117        mesh::GpuInstance {
7118            transform: desc.transform.to_cols_array(),
7119            mesh: self.mesh_ids[desc.mesh],
7120            material: self.material_ids[desc.material],
7121            flags: self.material_mode_bits(desc.material),
7122            ..mesh::GpuInstance::default()
7123        }
7124    }
7125
7126    /// The material mode of description material `material`, in the bits an
7127    /// instance record carries it in.
7128    ///
7129    /// **Read out of the table rather than out of the description**, because the
7130    /// table is what a `set` would move and the row is what the shader shades
7131    /// through. It is the other half of the record's routing key: `draw_gen`
7132    /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
7133    /// which is how a masked material costs a fragment stage in the depth passes
7134    /// for its own mesh alone.
7135    ///
7136    /// The mode is captured **here**, when the record is written — see
7137    /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
7138    /// for what that means for a material rewritten afterwards.
7139    fn material_mode_bits(&self, material: usize) -> u32 {
7140        self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
7141    }
7142
7143    // --- skinning: reserving the region, placing the object, ordering the
7144    // dispatch ---
7145
7146    /// The vertex pool every mesh here is resident in — what
7147    /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
7148    /// takes.
7149    ///
7150    /// The skinning pass reads a bind pose out of this buffer and writes the
7151    /// deformed vertices back into another run of it, which is what makes a
7152    /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
7153    /// [`Skinning`] built against any other writes vertices no draw here can
7154    /// reach.
7155    #[must_use]
7156    pub const fn vertex_buffer(&self) -> BufferHandle {
7157        self.pool.vertex_buffer()
7158    }
7159
7160    /// Where that pool's **attribute** region begins, in words — what
7161    /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
7162    /// takes.
7163    ///
7164    /// The buffer holds two streams, so a pass that writes it needs the
7165    /// boundary as well as the handle; a [`Skinning`] built with the wrong one
7166    /// writes a mesh's attributes over another mesh's positions. See
7167    /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
7168    #[must_use]
7169    pub const fn attribute_base(&self) -> u32 {
7170        self.pool.attribute_base()
7171    }
7172
7173    /// Reserves a skinned region for description mesh `mesh`.
7174    ///
7175    /// The whole of what a caller needs to skin something, in one value: hand
7176    /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
7177    /// frame's [`SkinRange`], hand the result to
7178    /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
7179    /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
7180    /// parity never have to be spelled by the caller at all — see
7181    /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
7182    ///
7183    /// **The mesh keeps its own entry and the region takes none**, so the same
7184    /// description mesh can be drawn skinned through this and in its bind pose
7185    /// through [`add_instance`](Self::add_instance) in the same frame, both
7186    /// resolving through the one table entry it already had.
7187    ///
7188    /// Give it back with [`release_skinned`](Self::release_skinned).
7189    ///
7190    /// # Errors
7191    ///
7192    /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
7193    /// both halves. **Two vertex runs per skinned primitive** is what a scene's
7194    /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
7195    ///
7196    /// # Panics
7197    ///
7198    /// If `mesh` is past the end of the description this renderer was built
7199    /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
7200    /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
7201    /// A DAG is refused rather than skinned wrongly: its coarser levels are
7202    /// separate vertex runs no dispatch writes, so a cut that descended past
7203    /// level 0 would draw whatever the pool happened to be holding there.
7204    pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
7205        let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
7206            panic!(
7207                "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
7208                 runs no skinning dispatch writes; only a flat mesh can be skinned"
7209            )
7210        });
7211        SkinnedMesh::reserve(&mut self.pool, source)
7212    }
7213
7214    /// Gives `skinned`'s region back to the vertex pool.
7215    ///
7216    /// The device must not still be drawing it: this records no barrier, on
7217    /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
7218    /// removed — [`remove_instance`](Self::remove_instance) is what does that,
7219    /// and an instance left behind goes on drawing its source mesh's geometry
7220    /// out of vertices the pool has handed back. Remove the objects first.
7221    pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
7222        skinned.release(&mut self.pool);
7223    }
7224
7225    /// Places a skinned object in the scene.
7226    ///
7227    /// [`add_instance`](Self::add_instance) with a reserved region in place of a
7228    /// description mesh. The renderer keeps the object in a list of its own and
7229    /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
7230    /// at the half of the region that frame's dispatch fills, so the parity is
7231    /// never something a caller writes.
7232    ///
7233    /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
7234    /// therefore left pointing wherever it last was, which after the first frame
7235    /// is the pose of the frame before — the reason the two entry points are
7236    /// separate calls rather than a flag.
7237    ///
7238    /// # Errors
7239    ///
7240    /// [`InstancePoolError::PoolFull`], on
7241    /// [`add_instance`](Self::add_instance)'s terms, and
7242    /// [`InstancePoolError::InvalidBounds`] for a
7243    /// [`SkinnedInstanceDesc::bounds`] the culls could not read, before
7244    /// anything is written.
7245    ///
7246    /// # Panics
7247    ///
7248    /// If [`SkinnedInstanceDesc::material`] is past the end of the description
7249    /// this renderer was built from, on
7250    /// [`add_instance`](Self::add_instance)'s terms.
7251    pub fn add_skinned_instance(
7252        &mut self,
7253        desc: &SkinnedInstanceDesc<'_>,
7254    ) -> Result<InstanceHandle, InstancePoolError> {
7255        let bounds = bounds_fields(desc.bounds)?;
7256        // Parity zero, and it never reaches the GPU as such: the instance pool
7257        // uploads by delta at `begin_skinned_frame`, which re-points every entry
7258        // of the list below before it flushes. What this writes is the rest of
7259        // the record.
7260        let instance = self.skinned_gpu_instance(desc, bounds, 0);
7261        let handle = self.instances.insert(&instance)?;
7262        self.skinned_instances.push(SkinnedInstance {
7263            handle,
7264            bases: skinned_bases(desc.mesh),
7265            pointed: false,
7266        });
7267        Ok(handle)
7268    }
7269
7270    /// Rewrites the skinned object `handle` names — its region, its material and
7271    /// its transform.
7272    ///
7273    /// [`set_instance`](Self::set_instance) for an object placed by
7274    /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
7275    /// character's transform changes through. A stale handle writes nothing.
7276    ///
7277    /// Passing a handle this renderer has never seen skinned adopts it: the
7278    /// object joins the re-pointed list from here on. That is what lets a caller
7279    /// swap a bind-pose instance over to a region without removing and replacing
7280    /// it.
7281    ///
7282    /// **The description's box replaces whatever box the object had**,
7283    /// including one [`set_skinned_bounds`](Self::set_skinned_bounds) wrote: the
7284    /// record is rebuilt from `desc`, and [`SkinnedInstanceDesc::bounds`] is
7285    /// part of it, so a `None` here takes the object's box away. A caller that
7286    /// both places an object and moves its box — a ragdoll — passes the box in
7287    /// this description, or calls `set_skinned_bounds` after this call.
7288    ///
7289    /// # Panics
7290    ///
7291    /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms, and on
7292    /// a [`SkinnedInstanceDesc::bounds`] that call would refuse with
7293    /// [`InstancePoolError::InvalidBounds`]: this call has no `Result`, so a
7294    /// description it cannot use is a panic naming it, as an out-of-range
7295    /// material is. A box that changes every frame belongs in
7296    /// [`set_skinned_bounds`](Self::set_skinned_bounds), which returns the
7297    /// refusal instead.
7298    pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
7299        let bounds = bounds_fields_or_panic(desc.bounds);
7300        let mut instance = self.skinned_gpu_instance(desc, bounds, 0);
7301        instance.flags |= self.kept_flags(handle);
7302        if !self.instances.set(handle, &instance) {
7303            return;
7304        }
7305        let bases = skinned_bases(desc.mesh);
7306        match self
7307            .skinned_instances
7308            .iter_mut()
7309            .find(|entry| entry.handle == handle)
7310        {
7311            // **A different region is a fresh entry.** The half this object has
7312            // never been drawn out of holds whatever its reservation came with,
7313            // so the next pointing owes it rest rather than a previous
7314            // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
7315            // is what "different" means here: two calls naming one region give
7316            // the same two runs, so rewriting an object's material or transform
7317            // is not a change of region.
7318            Some(entry) => {
7319                entry.pointed &= entry.bases == bases;
7320                entry.bases = bases;
7321            }
7322            None => self.skinned_instances.push(SkinnedInstance {
7323                handle,
7324                bases,
7325                pointed: false,
7326            }),
7327        }
7328    }
7329
7330    /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
7331    /// with the region's base vertex carried in the record and the bit that says
7332    /// to read it.
7333    ///
7334    /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
7335    /// this instance is scattered into, the levels it selects through and the
7336    /// box it is culled against are the ones the undeformed mesh already had.
7337    ///
7338    /// `bounds` is [`bounds_fields`]' answer for `desc.bounds`, which the caller
7339    /// has already checked.
7340    fn skinned_gpu_instance(
7341        &self,
7342        desc: &SkinnedInstanceDesc<'_>,
7343        (bounds_flag, bounds_min, bounds_max): (u32, [f32; 3], [f32; 3]),
7344        parity: u32,
7345    ) -> mesh::GpuInstance {
7346        let base_vertex = desc.mesh.region().base(parity);
7347        mesh::GpuInstance {
7348            transform: desc.transform.to_cols_array(),
7349            mesh: desc.mesh.mesh_id(),
7350            material: self.material_ids[desc.material],
7351            // The override bit **and** the material mode: a skinned instance is
7352            // routed by the same key as a rigid one, so a skinned cutout lands
7353            // in its mesh's masked bucket rather than in the opaque twin.
7354            flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE
7355                | self.material_mode_bits(desc.material)
7356                | bounds_flag,
7357            base_vertex,
7358            // At rest, which is what a record this call writes has to be: the
7359            // object has not been drawn out of this region yet, so the other
7360            // half holds whatever its reservation came with. A frame that runs
7361            // [`point_skinned_instances`](Self::point_skinned_instances) is
7362            // what starts pointing this at the half before.
7363            previous_base_vertex: base_vertex,
7364            bounds_min,
7365            bounds_max,
7366            ..mesh::GpuInstance::default()
7367        }
7368    }
7369
7370    /// Replaces the model-space box the skinned object `handle` names is culled
7371    /// by, and **nothing else** — see [`SkinnedInstanceDesc::bounds`], whose
7372    /// terms this writes on. `None` puts it back in every cull.
7373    ///
7374    /// The call a pose that travels makes once a frame: a ragdoll's bodies
7375    /// drift metres from the object's origin while its transform stays where it
7376    /// fell, and [`set_skinned_instance`](Self::set_skinned_instance) would
7377    /// rewrite the whole record as a move to change the box. This is not a
7378    /// move, on [`set_instance_views`](Self::set_instance_views)' terms: the
7379    /// transform history is left alone, so the motion target sees no travel the
7380    /// object did not make. It is still a write
7381    /// [`InstancePool::take_written`] names, so a shadow map the box reached
7382    /// before or after it is redrawn.
7383    ///
7384    /// Takes effect at the next [`begin_frame`](Self::begin_frame) or
7385    /// [`begin_skinned_frame`](Self::begin_skinned_frame), which uploads the
7386    /// element. A stale handle writes nothing and is not an error. On a rigid
7387    /// instance the box replaces its mesh's until the next
7388    /// [`set_instance`](Self::set_instance) rewrites the record.
7389    ///
7390    /// **A later [`set_skinned_instance`](Self::set_skinned_instance) replaces
7391    /// this box with its description's**, `None` included — the description
7392    /// is authoritative. Call this after placing the object, or pass the box in
7393    /// the description.
7394    ///
7395    /// # Errors
7396    ///
7397    /// [`InstancePoolError::InvalidBounds`] for a box with a non-finite corner
7398    /// or with `min` past `max` on any axis, and the record is left as it was.
7399    /// **An error rather than a panic**, unlike
7400    /// [`set_skinned_instance`](Self::set_skinned_instance)'s: this is the
7401    /// per-frame path a simulated pose's box takes, and a body that goes `NaN`
7402    /// for a frame is a condition a game can be in, not a mistake in its code.
7403    pub fn set_skinned_bounds(
7404        &mut self,
7405        handle: InstanceHandle,
7406        bounds: Option<Aabb>,
7407    ) -> Result<(), InstancePoolError> {
7408        let (flag, min, max) = bounds_fields(bounds)?;
7409        self.instances.set_bounds(handle, flag, min, max);
7410        Ok(())
7411    }
7412
7413    /// Points every skinned object at the half of its region a frame of this
7414    /// parity fills **and at the half the frame before it filled**, and forgets
7415    /// the ones whose instance has gone.
7416    ///
7417    /// Called between the instance ring's rotation and its upload, which is the
7418    /// whole reason those two are separate calls — see
7419    /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7420    ///
7421    /// The second base is what a skinned fragment's motion vector is subtracted
7422    /// against — see
7423    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7424    /// **A region this frame's `ranges` left out was not skinned this frame**,
7425    /// so the half this points at as the current one already holds an earlier
7426    /// frame's pose. That is pre-existing — it is what a caller driving a
7427    /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7428    /// it predates this second base — and the previous half is then no worse off
7429    /// than the current one.
7430    ///
7431    /// # What the shadow cache reads from it
7432    ///
7433    /// **Every re-point is an instance write**, whether or not the entry's
7434    /// region was in this frame's `ranges`: the parity alternates on every
7435    /// skinned frame, so each entry draws out of the other half from the frame
7436    /// before, and a region left out of the plan holds an older pose there.
7437    /// [`InstancePool::take_written`] names each element, and
7438    /// [`note_caster_writes`](Self::note_caster_writes) turns it into a
7439    /// footprint, so a skinned caster's frame redraws every shadow group its box
7440    /// reaches before or after it — and every group when it has no box, whose
7441    /// footprint is [`shadow_inputs::CasterFootprint::Everywhere`]. **A
7442    /// conservative superset**, not the exact set: the footprint carries slack,
7443    /// a point light is tested against its whole-light box rather than per face,
7444    /// and the cadence can defer a group it marks to a later frame. That
7445    /// write is the whole of what keeps a held map from showing a pose the
7446    /// object has left, so a re-point that skipped an unchanged entry would
7447    /// have to be a shadow-cache decision too.
7448    fn point_skinned_instances(&mut self, parity: u32) {
7449        let Self {
7450            instances,
7451            skinned_instances,
7452            ..
7453        } = self;
7454        skinned_instances.retain_mut(|entry| {
7455            // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7456            // applied to the entry's own copy of the pair — see
7457            // [`SkinnedInstance::bases`].
7458            let base_vertex = entry.bases[(parity & 1) as usize];
7459            let previous_base_vertex = if entry.pointed {
7460                entry.bases[((parity ^ 1) & 1) as usize]
7461            } else {
7462                // Nothing has been written into the other half for this object,
7463                // so it is put at rest — see [`SkinnedInstance::pointed`].
7464                base_vertex
7465            };
7466            entry.pointed = true;
7467            // The two bases and nothing else: the transform, the material and
7468            // the mesh the caller last set survive, and so does the transform
7469            // the record moved *from* — which
7470            // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7471            // would overwrite with this frame's, leaving a skinned object's own
7472            // travel out of the motion target. See
7473            // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7474            // Its answer is also what says the instance is still there, so an
7475            // object a caller removed drops out of the list here.
7476            instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7477        });
7478    }
7479
7480    /// The lights in the frame **beside the sun**, which
7481    /// [`begin_frame`](Self::begin_frame) still takes on its own.
7482    ///
7483    /// Topic 44's light list, minus its first row: the
7484    /// sun is row 0 of every frame's list and the ones set here follow it, in
7485    /// the order given. That order is the one a froxel keeps a prefix of when it
7486    /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7487    /// overflow counter beside it — so it is a caller's lever and not an
7488    /// accident.
7489    ///
7490    /// The sun keeps a parameter of its own because it is the light that owns
7491    /// the ambient term and the shadow cascades, neither of which a [`Light`]
7492    /// has. What it stopped being is a special case in the *shader*, which is
7493    /// what the list bought.
7494    ///
7495    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7496    /// what uploads the rows.
7497    ///
7498    /// # Panics
7499    ///
7500    /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7501    /// room for once the sun has its row. Refused rather than truncated: a light
7502    /// missing from the list is missing from every froxel, and **no counter in
7503    /// the frame would report it** — the overflow counter counts what a froxel's
7504    /// budget refused, which is a different number.
7505    pub fn set_lights(&mut self, lights: &[Light]) {
7506        assert!(
7507            lights.len() < self.primary.lights.capacity() as usize,
7508            "{} lights beside the sun, in a list of {}",
7509            lights.len(),
7510            self.primary.lights.capacity()
7511        );
7512        self.extra_lights.clear();
7513        self.extra_lights.extend_from_slice(lights);
7514    }
7515
7516    /// Rows the light list holds, the sun's included.
7517    #[must_use]
7518    pub const fn light_capacity(&self) -> u32 {
7519        self.primary.lights.capacity()
7520    }
7521
7522    /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7523    /// from the viewport and the camera.
7524    ///
7525    /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7526    /// wants to know which froxel a point was shaded out of has to use the grid
7527    /// the frame really used, and re-deriving it would be a second copy of the
7528    /// arithmetic rather than a reading of the first.
7529    #[must_use]
7530    pub const fn grid(&self) -> Grid {
7531        self.primary.grid
7532    }
7533
7534    /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7535    /// pass decided.
7536    ///
7537    /// # Panics
7538    ///
7539    /// If `frame` is not a slot this was built with.
7540    #[must_use]
7541    pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7542        self.primary.lights.grid(frame)
7543    }
7544
7545    /// The pixel budget the descent compares a group's projected error against.
7546    ///
7547    /// One pixel until this is called — see the constant this crate keeps it
7548    /// in. Larger is coarser: a group
7549    /// projecting *over* the budget is expanded and its children are drawn, so
7550    /// raising it stops the descent higher up the DAG.
7551    ///
7552    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7553    /// what writes it into the frame block.
7554    pub const fn set_lod_error_budget(&mut self, budget: f32) {
7555        self.lod_error_budget = budget;
7556    }
7557
7558    /// The budget this renderer selects under unless
7559    /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7560    /// the ratio the hold budget sits at below whichever one is in force.
7561    ///
7562    /// Public because a test that drives a camera across a level boundary has to
7563    /// know where the boundary is, and where it is depends on both numbers —
7564    /// re-deriving either in the test would be a second copy to drift.
7565    pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7566    /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7567    pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7568
7569    /// How far below the budget an already-expanded group is held before it
7570    /// collapses again — topic 25's hysteresis, as a fraction of
7571    /// the budget.
7572    ///
7573    /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7574    /// of one removes the band**, which makes the two budgets equal and the
7575    /// previous frame's answer stop mattering — the setting a test uses to show
7576    /// that the band is what stops a drifting camera flickering, on the same
7577    /// code path and one number apart.
7578    ///
7579    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7580    /// what writes it into the two params blocks.
7581    pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7582        self.lod_hold_ratio = ratio;
7583    }
7584
7585    /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7586    /// pixels per unit at one unit from the eye, and the pixel budget.
7587    ///
7588    /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7589    /// starts expanding over, and the budget an expanded one is held down to.
7590    ///
7591    /// What `ClusterDag::expand` takes, so a caller reading
7592    /// [`cluster_selection`](Self::cluster_selection) back can run the same
7593    /// frames host-side rather than re-deriving the numbers from the camera and
7594    /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7595    #[must_use]
7596    pub const fn lod_params(&self) -> [f32; 3] {
7597        self.primary.lod_params
7598    }
7599
7600    /// The same three numbers the **shadow cascades** selected under, which is
7601    /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7602    /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7603    /// parameters it actually reaches the GPU as.
7604    ///
7605    /// The pixels-per-unit is the camera's, unchanged, because the cascades
7606    /// select from the camera's eye at the camera's scale; see
7607    /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7608    /// frame.
7609    #[must_use]
7610    pub const fn shadow_lod_params(&self) -> [f32; 3] {
7611        self.shadow_lod_params
7612    }
7613
7614    /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7615    /// level of it, as one run — or `None` off the mesh path, where there is no
7616    /// cluster pool at all.
7617    ///
7618    /// The base a reader adds a `(level, cluster)` to in order to index
7619    /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7620    /// finest first and contiguously, so level `d` cluster `c` is at
7621    /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7622    /// its run is its clusters and `c` indexes it directly.
7623    ///
7624    /// # Panics
7625    ///
7626    /// If `mesh` is past the end of the description this renderer was built
7627    /// from, on [`add_instance`](Self::add_instance)'s terms.
7628    #[must_use]
7629    pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7630        (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7631    }
7632
7633    /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7634    /// one `u32` per resident cluster, `1` where the cluster was drawn.
7635    ///
7636    /// `None` where there is no amplification stage, which is every device that
7637    /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7638    ///
7639    /// **This is topic 25's observable and nothing in the frame
7640    /// reads it.** A frame whose every cluster came from one level is a
7641    /// plausible picture and matches any golden blessed from it, so a golden
7642    /// cannot show per-cluster selection happening at all; this can. It is
7643    /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7644    ///
7645    /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7646    #[must_use]
7647    pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7648        self.primary.cluster_selection.get(frame).copied()
7649    }
7650
7651    /// The same, for `cascade`'s shadow pass: the cut that cascade's
7652    /// amplification stage chose this frame.
7653    ///
7654    /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7655    /// passed* is a parameter; the cut they reached under it is the behaviour,
7656    /// and this is the only thing that carries it out of a frame — the colour
7657    /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7658    /// cascades have run. Indexed and read exactly as that buffer is, through
7659    /// [`cluster_range`](Self::cluster_range).
7660    ///
7661    /// `None` where there is no amplification stage, and where `cascade` is not
7662    /// one of [`shadow::CASCADES`].
7663    #[must_use]
7664    pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7665        self.shadow_selection
7666            .get(frame)
7667            .and_then(|cascades| cascades.get(cascade))
7668            .copied()
7669    }
7670
7671    /// The buckets description mesh `mesh`'s levels draw through, finest first —
7672    /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7673    ///
7674    /// **This is the uniform cut's observable**, and it is the indirect
7675    /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7676    /// instance into the bucket for the level it selected, so exactly one of
7677    /// these buckets comes out of a frame with a non-zero instance count and
7678    /// which one it is *is* the chosen level. A reader takes
7679    /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7680    /// and looks at
7681    /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7682    ///
7683    /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7684    /// level is chosen per cluster instead — see
7685    /// [`cluster_selection`](Self::cluster_selection), which is that path's
7686    /// observable.
7687    ///
7688    /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7689    /// in any scene that has an opaque material, since the table is every
7690    /// mesh's levels once per mode the scene holds, mode by mode in
7691    /// `DEPTH_MODES` order. An instance of another mode selects the same level
7692    /// and lands in that level's bucket in its own mode's run, which this does
7693    /// not name; every scene in this tree that reads this accessor is all
7694    /// opaque, so "exactly one of these has a non-zero instance count" holds for
7695    /// them as it always did.
7696    ///
7697    /// # Panics
7698    ///
7699    /// If `mesh` is past the end of the description this renderer was built
7700    /// from, on [`add_instance`](Self::add_instance)'s terms.
7701    #[must_use]
7702    pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7703        if self.mesh_level_buckets.is_empty() {
7704            return &[];
7705        }
7706        &self.mesh_level_buckets[mesh]
7707    }
7708
7709    /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7710    /// bytes per bucket — what a reader of
7711    /// [`level_buckets`](Self::level_buckets) copies out.
7712    ///
7713    /// # Panics
7714    ///
7715    /// If `frame` is not a slot this renderer was built with.
7716    #[must_use]
7717    pub fn draw_args(&self, frame: usize) -> BufferHandle {
7718        self.primary.draws.args(frame)
7719    }
7720
7721    /// `frame`'s survivor list for the primary camera and the culling
7722    /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7723    /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7724    /// the first buffer, and their count in word
7725    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7726    /// of the second — for a test holding the GPU's occlusion verdicts against
7727    /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7728    /// behind the list; see [`crate::draw_gen`].
7729    ///
7730    /// # Panics
7731    ///
7732    /// If `frame` is not a slot this renderer was built with.
7733    #[must_use]
7734    pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7735        (
7736            self.primary.draws.visible(frame),
7737            self.primary.draws.visible_count(frame),
7738        )
7739    }
7740
7741    /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7742    /// takes it: every instance slot the pool has handed out, and the whole mesh
7743    /// table — both decoded from the host's own copies of what was uploaded.
7744    #[must_use]
7745    pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7746        (self.instances.records(), self.pool.table_entries())
7747    }
7748
7749    /// The generator behind shadow cull `cull` — a cascade's below
7750    /// [`shadow::CASCADES`], a light slot's after —
7751    /// for a test reading back what a point light's face culls kept.
7752    ///
7753    /// # Panics
7754    ///
7755    /// If `cull` is not one of the renderer's shadow culls.
7756    #[must_use]
7757    pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7758        &self.shadow_draws[cull]
7759    }
7760
7761    /// The primary camera's farthest-depth pyramid — every level's image, view
7762    /// and extent, level 1 first — or empty before a frame culled by occlusion.
7763    ///
7764    /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7765    /// exactly that, and they hold the last frame's early depth once that frame
7766    /// has finished.
7767    #[must_use]
7768    pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7769        self.primary.occlusion_pyramid.level_images()
7770    }
7771
7772    /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7773    ///
7774    /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7775    /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7776    /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7777    /// are not all filled runs fewer culls, which is what makes a free tile
7778    /// free.
7779    ///
7780    /// Derived rather than written down, because a number written down is one
7781    /// that stops matching the frame the day a pass is added — which is exactly
7782    /// how the samples' hand-picked `8` came to time the first eight passes of a
7783    /// fourteen-pass frame. A caller sizing
7784    /// [`PassTimers`](crate::timing::PassTimers) wants
7785    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7786    /// what the overlay renderers record.
7787    pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7788        + DrawGen::LATE_PASSES
7789        + LightGrid::MAX_PASSES
7790        + RENDER_PASSES;
7791
7792    /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7793    /// and returns the HDR scene target they went through.
7794    ///
7795    /// `target` is normally the imported swapchain image. Everything else — the
7796    /// HDR scene colour, the depth buffer, and every barrier between them — is
7797    /// the graph's.
7798    ///
7799    /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7800    /// the scene colour **with the screen-space reflections already added**, not
7801    /// the target the forward pass wrote. A caller that wants to add a pass of
7802    /// its own after the tonemap — a debug overlay, or a readback proving the
7803    /// HDR range is real — declares a read of it and the graph works out the
7804    /// transition, exactly as it does for the tonemap.
7805    ///
7806    /// The two are the same description and different images, which is the
7807    /// design's off-switch as data rather than as a branch: a frame with
7808    /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7809    /// pass's own id, and is bit-identical.
7810    ///
7811    /// # Which passes this adds is [`effects`](Self::effects)
7812    ///
7813    /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7814    /// and read here — see [`crate::effects`] for the four layers and for what
7815    /// each toggle removes. Every effect is on by default, which is the frame
7816    /// every caller drew before the toggles existed.
7817    ///
7818    /// A switched-off effect is **fewer passes and one different bound
7819    /// descriptor**, never a shader permutation: the shadow atlas keeps its
7820    /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7821    /// to the renderer's white 1×1, and the reflection pair simply is not there.
7822    ///
7823    /// # The ground grid comes last, and after the tonemap
7824    ///
7825    /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7826    /// and it is off by default. When it is on, its pass is added **after** the
7827    /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7828    /// against the scene depth: the grid is reference chrome, and a grid drawn
7829    /// before the tonemap would be exposed and tonemapped like geometry, so its
7830    /// colour would move with how bright the scene is. See [`crate::grid`].
7831    ///
7832    /// # `pool` is where the shadow atlas's incoming state comes from
7833    ///
7834    /// It must be the same pool the caller is about to
7835    /// [`compile`](RenderGraph::compile) and
7836    /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7837    /// its placeholder are imports this renderer owns across frames and the
7838    /// pool's ledger is the record of what the last executed graph left them in
7839    /// — [`TransientPool::imported_image_use`], with [`None`] read as
7840    /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7841    /// field of our own is what keeps the declaration and the audit
7842    /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7843    /// whose `compile` fails is a frame that never ran, and a field advanced at
7844    /// build time would already have moved on without it.
7845    ///
7846    /// # Panics
7847    ///
7848    /// If `extent` is not the extent the [`begin_frame`](Self::begin_frame)
7849    /// that opened this frame was handed: the frame's internal extent, its
7850    /// blocks and the passes it builds were all decided there.
7851    pub fn add_passes<'a>(
7852        &'a mut self,
7853        graph: &mut RenderGraph<'a>,
7854        pool: &TransientPool,
7855        target: ImageId,
7856        extent: (u32, u32),
7857    ) -> ImageId {
7858        self.add_frame_passes(
7859            graph,
7860            pool,
7861            FrameTargets::primary(target, extent, None),
7862            |_, _| {},
7863        )
7864    }
7865
7866    /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7867    /// frame with `skinning`'s dispatch in front of every pass that draws.
7868    ///
7869    /// # This takes the pass rather than its [`BufferId`], and that is the point
7870    ///
7871    /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7872    /// mesh pass can declare a read of it and be ordered after the dispatch. The
7873    /// obvious seam is therefore an id parameter here — and it is the wrong one,
7874    /// because every way of getting it wrong is silent. A caller can pass the id
7875    /// of a *different* import, add the skinning pass after this one, or not add
7876    /// it at all, and in each case the graph orders nothing, the draws read the
7877    /// region before the compute write has been made visible, and what comes out
7878    /// is a mesh that flickers between two poses on hardware and looks perfect
7879    /// under a validation layer.
7880    ///
7881    /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7882    /// this renderer's own frame slot, and declares the read on the three passes
7883    /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7884    /// and the forward pass. There is no order for a caller to get right,
7885    /// because there is only one call.
7886    ///
7887    /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7888    /// handed no ranges adds no dispatch and no declarations, and is the frame
7889    /// [`add_passes`](Self::add_passes) would have built. So is one whose every
7890    /// range was dropped because nothing the frame draws can read it — see
7891    /// [`set_skinning_culls`](Self::set_skinning_culls).
7892    ///
7893    /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7894    ///
7895    /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7896    /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7897    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7898    /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7899    ///
7900    /// # Panics
7901    ///
7902    /// If `extent` is not the extent the [`begin_skinned_frame`](Self::begin_skinned_frame)
7903    /// that opened this frame was handed: the frame's internal extent, its
7904    /// blocks and the passes it builds were all decided there.
7905    pub fn add_skinned_passes<'a>(
7906        &'a mut self,
7907        graph: &mut RenderGraph<'a>,
7908        pool: &TransientPool,
7909        target: ImageId,
7910        extent: (u32, u32),
7911        skinning: &Skinning,
7912    ) -> ImageId {
7913        self.add_frame_passes(
7914            graph,
7915            pool,
7916            FrameTargets::primary(target, extent, Some(skinning)),
7917            |_, _| {},
7918        )
7919    }
7920
7921    /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7922    /// overlay inserted after the display-space frame is complete and before
7923    /// antialiasing or render-scale reconstruction.
7924    ///
7925    /// The callback receives the display target and its matching scene depth
7926    /// attachment at the internal render extent. It may add graph passes that
7927    /// sample `display` and attach `depth` read-only; it must leave both images
7928    /// in states its declarations name. The forward renderer continues with its
7929    /// existing resolve and upscale passes after the callback returns.
7930    ///
7931    /// # Panics
7932    ///
7933    /// On [`add_skinned_passes`](Self::add_skinned_passes)' terms.
7934    pub fn add_skinned_passes_with_overlay<'a, F>(
7935        &'a mut self,
7936        graph: &mut RenderGraph<'a>,
7937        pool: &TransientPool,
7938        target: ImageId,
7939        extent: (u32, u32),
7940        skinning: &Skinning,
7941        overlay: F,
7942    ) -> ImageId
7943    where
7944        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7945    {
7946        self.add_frame_passes(
7947            graph,
7948            pool,
7949            FrameTargets::primary(target, extent, Some(skinning)),
7950            overlay,
7951        )
7952    }
7953
7954    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7955    /// for a frame that also draws secondary views — see
7956    /// [`create_view`](Self::create_view).
7957    ///
7958    /// **The scene's passes are recorded once**: one skinning dispatch (where
7959    /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7960    /// in `views` records its own cull, clustering and frame into its own
7961    /// target, and the primary camera's frame into `target` comes last — so
7962    /// `overlay` may read a view's target, which is already drawn by then.
7963    ///
7964    /// Every view named must have been begun this frame by
7965    /// [`begin_view`](Self::begin_view).
7966    ///
7967    /// # Panics
7968    ///
7969    /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7970    /// a view this renderer did not build, a view not begun this frame, or a
7971    /// view twice — or if [`FrameTargets`]' extent is not the one the frame's
7972    /// [`begin_frame`](Self::begin_frame) was handed, or a view's is not the
7973    /// one its [`begin_view`](Self::begin_view) was.
7974    pub fn add_passes_with_views<'a, F>(
7975        &'a mut self,
7976        graph: &mut RenderGraph<'a>,
7977        pool: &TransientPool,
7978        frame: FrameTargets<'_>,
7979        overlay: F,
7980    ) -> ImageId
7981    where
7982        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7983    {
7984        self.add_frame_passes(graph, pool, frame, overlay)
7985    }
7986
7987    /// The body of every `add_*passes` entry point, which differ in their
7988    /// arguments and in nothing else.
7989    fn add_frame_passes<'a, F>(
7990        &'a mut self,
7991        graph: &mut RenderGraph<'a>,
7992        pool: &TransientPool,
7993        frame: FrameTargets<'_>,
7994        overlay: F,
7995    ) -> ImageId
7996    where
7997        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7998    {
7999        let FrameTargets {
8000            target,
8001            extent,
8002            skinning,
8003            views,
8004        } = frame;
8005        // **From here down `extent` is the extent the frame is *drawn* at**,
8006        // which is the caller's at a render scale of `1.0` and smaller below it.
8007        // Every use of it in this function sizes a transient, and every one of
8008        // those transients belongs to the internal frame; `target` is the only
8009        // thing here at the caller's extent, and it is an id whose image already
8010        // knows how big it is. `begin_frame_body` shadows it the same way and
8011        // for the same reason, so the two halves of a frame cannot disagree.
8012        //
8013        // `upscaling` is derived from the two extents rather than from the scale
8014        // itself, which is what makes it exact: a target small enough that the
8015        // scaled extent rounds back onto it adds no pass, because there would be
8016        // nothing for the pass to do.
8017        //
8018        // **Both are the ones `begin_frame` froze** — see
8019        // [`View::frame_extent`]. A render scale moved since then is the next
8020        // frame's, on [`Self::set_render_scale`]'s word, and a target of
8021        // another size is refused rather than drawn out of blocks and passes
8022        // decided for this one.
8023        assert_eq!(
8024            extent, self.primary.frame_target_extent,
8025            "`add_passes` was handed a target of {extent:?}, and the `begin_frame` that \
8026             opened this frame one of {:?}: hand both the same extent",
8027            self.primary.frame_target_extent
8028        );
8029        let target_extent = extent;
8030        let extent = self.primary.frame_extent;
8031        let upscaling = extent != target_extent;
8032        let frame = self.frame;
8033        let instance_count = self.instances.slot_count();
8034        let emit = self.emit;
8035
8036        // Every secondary view the caller asked for, checked before anything of
8037        // theirs is recorded: a view that does not exist, or one nothing began
8038        // this frame, would draw out of blocks written for some other frame.
8039        let secondary: Vec<(ViewTarget, (u32, u32))> = views
8040            .iter()
8041            .map(|view| {
8042                assert!(
8043                    view.view != ViewId::PRIMARY,
8044                    "the primary camera draws into the target `add_passes_with_views` takes, \
8045                     not into a `ViewTarget`"
8046                );
8047                let built = self
8048                    .views
8049                    .get(view.view.index() - 1)
8050                    .and_then(Option::as_ref)
8051                    .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
8052                assert_eq!(
8053                    built.begun, self.frame_serial,
8054                    "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
8055                    view.view
8056                );
8057                assert!(
8058                    views.iter().filter(|other| other.view == view.view).count() == 1,
8059                    "{:?} was named twice in one frame",
8060                    view.view
8061                );
8062                assert_eq!(
8063                    view.extent, built.frame_target_extent,
8064                    "{:?} was handed a target of {:?} here and one of {:?} by `begin_view`: \
8065                     hand both the same extent",
8066                    view.view, view.extent, built.frame_target_extent
8067                );
8068                (*view, built.frame_extent)
8069            })
8070            .collect();
8071
8072        // **The skinning dispatch, before anything else is added.** It imports
8073        // the vertex pool and hands back that node's id; every pass below that
8074        // pulls vertices declares a read of it, and the graph is what turns the
8075        // two declarations into the barrier between the compute write and the
8076        // draws. `None` is a frame with nothing to skin, which adds no pass and
8077        // declares nothing — see `Skinning::add_pass`.
8078        //
8079        // **Less the regions nothing this frame draws**, decided here rather
8080        // than at `begin_skinned_frame` because only now has every view the
8081        // frame records been begun — see `cull_skinned_regions`.
8082        let skinned = skinning.and_then(|skinning| {
8083            self.cull_skinned_regions(skinning.planned_regions(frame), views);
8084            let cull = &self.skin_cull;
8085            skinning.add_pass_where(graph, frame, |region| !cull.skips(region))
8086        });
8087
8088        // The camera's cull dispatch and the draw-argument dispatch, and the
8089        // light clustering after them — before anything draws, and before the
8090        // shadow atlas, which is where they always ran. See [`View::add_cull`].
8091        let cull = self.primary.add_cull(graph, pool, frame, instance_count);
8092
8093        // Topic 25's record of each cascade's cut. Each is written by
8094        // exactly one mesh pass, so what the graph orders here is this frame's
8095        // write against the next frame's use of the same slot. Each arrives in
8096        // the state the previous frame left it in, which is the one declared as
8097        // final.
8098        let tile_selection: Vec<BufferId> = self
8099            .shadow_selection
8100            .get(self.frame)
8101            .into_iter()
8102            .flatten()
8103            .enumerate()
8104            .map(|(tile, &buffer)| {
8105                import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
8106            })
8107            .collect();
8108
8109        // **This frame's slot of the probe ring**, which is the buffer every
8110        // one of this frame's bind groups names — see [`crate::probe`] for why
8111        // there is more than one. Imported in `ShaderRead` and handed back in
8112        // it: the build's staging copy left it there and no pass in the frame
8113        // writes it yet.
8114        let probe_buffer = self.probes.buffer(frame);
8115        let probe_table = graph.import_buffer(
8116            "probes",
8117            ImportedBuffer {
8118                buffer: probe_buffer,
8119                initial: ResourceState::ShaderRead,
8120                final_state: ResourceState::ShaderRead,
8121            },
8122        );
8123
8124        // The occlusion placeholder, imported once and read by every pass whose
8125        // bind group names it: the shadow pass's views, the depth prepass's copy
8126        // of the camera's group, and — on a frame drawing without
8127        // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
8128        // uploaded at build, so it is already in `ShaderRead` and the graph has
8129        // nothing to transition; declaring it is what keeps that true if a later
8130        // pass wants it in some other state.
8131        let occlusion_placeholder = graph.import_image(
8132            "ssao-placeholder",
8133            ImportedImage {
8134                image: self.ambient_occlusion_placeholder.image,
8135                view: self.ambient_occlusion_placeholder.view,
8136                format: Format::R8Unorm,
8137                extent: (1, 1),
8138                initial: ResourceState::ShaderRead,
8139                claim: InitialClaim::Tracked,
8140                final_state: ResourceState::ShaderRead,
8141            },
8142        );
8143
8144        // The contact-shadow placeholder, imported beside the occlusion one and
8145        // on its terms exactly: every group of the mesh layout names this
8146        // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
8147        // it is what the forward pass binds.
8148        let contact_placeholder = graph.import_image(
8149            "contact-shadows-placeholder",
8150            ImportedImage {
8151                image: self.contact_shadow_placeholder.image,
8152                view: self.contact_shadow_placeholder.view,
8153                format: Format::R8Unorm,
8154                extent: (1, 1),
8155                initial: ResourceState::ShaderRead,
8156                claim: InitialClaim::Tracked,
8157                final_state: ResourceState::ShaderRead,
8158            },
8159        );
8160
8161        // §3.2's base-colour page, in every bind group of `mesh_layout` and so
8162        // read by all three of the passes that draw geometry. Like the
8163        // placeholder above it is already in `ShaderRead` and the graph has
8164        // nothing to transition on a frame nothing writes it — **the
8165        // declaration is for the frames something does**. A caller that copies a
8166        // render-to-texture view into one of its layers imports the same handle,
8167        // gets this same id back (`RenderGraph::import_image`), and the graph
8168        // then has an edge to order its write against these reads. Without the
8169        // declaration there is no such edge: the page is bound out of a
8170        // descriptor the graph never hears about, and a copy scheduled anywhere
8171        // but the tail of the frame leaves it in `TransferDst` for the passes
8172        // that sample it.
8173        let base_color_page =
8174            graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
8175        // §2's normal page beside it, declared for exactly the reason above: it
8176        // is in every group of `mesh_layout` too, so a caller copying into one
8177        // of its layers needs the same edge against these draws.
8178        let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
8179        // §2's other two pages beside them, declared for exactly the same
8180        // reason: both are in every group of `mesh_layout`, so a caller copying
8181        // into one of their layers needs the same edge against these draws.
8182        let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
8183        let emissive_page =
8184            graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
8185
8186        // What this frame draws, resolved by the `begin_frame` that opened it —
8187        // see [`crate::effects`]. Read once here so every conditional below is
8188        // about one value rather than about four reads of a field.
8189        let effects = self.frame_effects;
8190        // Read here for `effects`' reason and for one more: the passes below
8191        // borrow `self` field by field, and a `&self` method called between
8192        // them would borrow the whole of it.
8193        let draws_sky = self.draws_sky();
8194        // What the frame's water draws, or `None` for a frame with none — read
8195        // here for `draws_sky`'s reason, and the same value every view records
8196        // from.
8197        let water = self.water.frame(self.frame);
8198        // The same, for the grass field, as `begin_frame` froze it: the value
8199        // every view's passes were built and its blocks written for.
8200        let grass = self.frame_grass;
8201        // Whether this frame ends by drawing the shadow atlas over itself — the
8202        // resolved view rather than the switch, so a caller who left the atlas
8203        // up and then asked for normals gets normals — as `begin_frame` froze
8204        // it, because that call built the viewer and wrote its block.
8205        let draws_atlas_view = self.frame_atlas_view;
8206
8207        let pages = MaterialPages {
8208            base_color: base_color_page,
8209            normal: normal_page,
8210            mro: mro_page,
8211            emissive: emissive_page,
8212        };
8213        let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
8214            graph,
8215            pool,
8216            &tile_selection,
8217            ShadowReads {
8218                occlusion_placeholder,
8219                pages,
8220                skinned,
8221                probes: probe_table,
8222            },
8223        );
8224
8225        // The wireframe twin where a caller switched the view on, and `None`
8226        // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
8227        // terms, and the `filter` is what keeps "switched on" from outrunning
8228        // "built": the field is only `Some` after a build that succeeded.
8229        //
8230        // The depth prepass below takes the depth-only pipeline and is untouched
8231        // by this, which is the half that makes a wireframe frame legible: the
8232        // occlusion pair still reads solid depth. **It is also what makes this
8233        // one variable rather than two**: the colour pass's depth attachment
8234        // branches on it as well, because a wireframe is not the geometry the
8235        // prepass drew — see `MeshModules::color_depth_stencil`.
8236        let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
8237        let bucket_draws = BucketDraws {
8238            // Replaced per partition below, in both passes that draw this list —
8239            // see [`ForwardRenderer::sided_partitions`] and
8240            // [`ForwardRenderer::depth_partitions`]. The field is what the
8241            // partitions inherit everything else from.
8242            pipeline: self.mesh_pipeline.single,
8243            layout: self.mesh_pipeline_layout,
8244            indices: self.pool.index_buffer(),
8245            emit,
8246            calls: self
8247                .bucket_constants
8248                .iter()
8249                .enumerate()
8250                .map(|(bucket, constant_offset)| {
8251                    let bucket = u32::try_from(bucket)
8252                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8253                    (
8254                        *constant_offset,
8255                        self.primary.draws.args_offset(bucket),
8256                        self.primary.draws.count_offset(bucket),
8257                        self.primary.draws.mesh_args_offset(bucket),
8258                    )
8259                })
8260                .collect(),
8261            region_step: self.region_step,
8262            // Packed per partition, where the partition's buckets are known.
8263            ranges: None,
8264            flat: None,
8265        };
8266
8267        // Every draw this frame records: the shadow pass's, one per bucket — or
8268        // per range of buckets, or per partition behind a task stage — in
8269        // **each** of the depth prepass and the forward pass, and one full-screen
8270        // triangle per full-screen pass. Assigned before the passes below borrow
8271        // the fields they need, so it is the count for the frame being built
8272        // rather than the one before it — and off this frame's resolved effects
8273        // rather than off a constant, so a switched-off effect's triangle is not
8274        // counted as submitted.
8275        //
8276        // The ground grid is added on top rather than folded into
8277        // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
8278        // resolved by the toggle order — it is a caller's opt-in, off by
8279        // default — so what decides it is the field and not this frame's
8280        // effects.
8281        self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
8282                + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
8283                + if draws_sky { SkyPass::PASSES } else { 0 }
8284                // The composite on an atmosphere frame whose fog effect is off,
8285                // on the sky's terms: it is there for the air in front of the
8286                // scene, which the atmosphere decides and no effect bit does.
8287                // With the effect on, `fullscreen_passes` already counted it.
8288                + if self.primary.frame_aerial
8289                    && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
8290                {
8291                    u64::from(Volumetric::COMPOSITE_PASSES)
8292                } else {
8293                    0
8294                }
8295                // The water copy's triangle, on the sky's terms: content rather
8296                // than an effect bit, so the bodies decide it.
8297                + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
8298                // The atlas viewer, on the ground grid's terms: not an effect
8299                // bit and not resolved by the toggle order, so what decides it
8300                // is the debug view and not this frame's effects. It *replaces*
8301                // the tonemap `fullscreen_passes` counted and the grid above —
8302                // see `View::add_passes` — so its passes stand in for the one.
8303                + if draws_atlas_view {
8304                    u64::from(AtlasView::PASSES) - 1
8305                } else {
8306                    0
8307                };
8308        // The debug draw layer's own call, on the ground grid's terms: not an
8309        // effect bit, and decided by whether this frame's slot has a segment in
8310        // it. One direct draw of one instance covering every segment appended,
8311        // which is why it joins the full-screen triangles rather than the
8312        // indirect draws — `counters` counts both as submitted *and* drawn,
8313        // because the CPU knows what they cover.
8314        self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
8315        // The shadow pass's tile resets, on the same terms: one over-sized
8316        // triangle of one instance per tile it redrew, and none at all on a
8317        // frame that cleared the whole attachment — see
8318        // [`MeshModules::depth_clear_pipeline`].
8319        self.recorded_tile_clears = shadow_tile_clears;
8320        // One indexed draw per body the frame's water holds.
8321        self.recorded_water_draws = water
8322            .as_ref()
8323            .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
8324        // One indirect draw per tile slot the frame's field holds, per look it
8325        // draws.
8326        self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
8327            u64::from(grass.slots) * u64::from(grass.draws_per_slot())
8328        });
8329        // The late depth prepass is a third list of calls, on a frame whose
8330        // camera culls in two phases.
8331        let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
8332            == crcbl_shaders::draw_gen::DrawMode::Occlusion
8333        {
8334            3
8335        } else {
8336            2
8337        };
8338        let prepass_partitions = self.depth_partitions(&bucket_draws);
8339        // And the colour pass's own split, which is by **side** alone: its
8340        // pipeline has a fragment stage either way, so an alpha mask is nothing
8341        // it has to route around and a cull mode is. The wireframe twin pair
8342        // substitutes for the shaded one here exactly as the single pipeline
8343        // used to.
8344        let color_partitions =
8345            self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
8346        // Off the partitions the passes below record, because where a call
8347        // draws a range of buckets the two splits pack into different numbers
8348        // of ranges — see [`BucketDraws::call_count`].
8349        let calls = |partitions: &[BucketDraws]| -> u64 {
8350            partitions.iter().map(BucketDraws::call_count).sum()
8351        };
8352        self.recorded_draws = shadow_draws
8353            + (camera_passes - 1) * calls(&prepass_partitions)
8354            + calls(&color_partitions)
8355            + self.recorded_grass_draws
8356            + self.direct_draws();
8357
8358        // --- the probe gather ---
8359        //
8360        // The irradiance probes' updater, second half: the map
8361        // the pass above drew, read into every row of the table. **Here rather
8362        // than beside that pass** because the write is `&mut` — the group naming
8363        // the map's transient views is cached across frames, and a group naming a
8364        // transient cannot be built where the others are; see
8365        // [`crate::ssao::cached_group`].
8366        //
8367        // It is before the depth prepass and the forward pass, which is the
8368        // ordering that matters: both declare a read of these rows, so the graph
8369        // barriers this write against them.
8370        //
8371        // Which map layer a row is weighed against is the row's own index, so
8372        // the view is resolved exactly as the drawing passes resolve it — the
8373        // placeholder until `capture_probe_visibility` has run, and off entirely
8374        // where `r_probe_visibility` is off. A gather against the placeholder
8375        // occludes nothing, which is the honest answer for a scene that never
8376        // captured.
8377        let probe_visibility_view = match &self.probe_visibility {
8378            Some(captured) if crate::probe_visibility::enabled() => captured.view,
8379            _ => self.probe_visibility_placeholder.view,
8380        };
8381        let frame = self.frame;
8382        if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
8383            gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
8384        }
8385
8386        let passes = FramePasses {
8387            slot: frame,
8388            emit,
8389            target_format: self.target_format,
8390            ssao_blurs: self.frame_ssao_blurs,
8391            draws_sky,
8392            water,
8393            grass,
8394            skinned,
8395            probe_buffer,
8396            probe_table,
8397            occlusion_placeholder,
8398            contact_placeholder,
8399            pages,
8400            shadow_atlas,
8401            probe_visibility: probe_visibility_view,
8402            mesh_layout: self.mesh_layout,
8403            wireframe,
8404            prepass_partitions,
8405            color_partitions,
8406            tonemap: TonemapPipeline {
8407                sampler: self.sampler,
8408                layout: self.tonemap_layout,
8409                pipeline_layout: self.tonemap_pipeline_layout,
8410                pipeline: self.tonemap_pipeline,
8411            },
8412        };
8413        // From here the frame is borrowed field by field, because every view's
8414        // passes hold its own caches for the life of the graph.
8415        let Self {
8416            primary,
8417            views: built,
8418            debug_draw,
8419            ground_grid,
8420            ground_grid_on,
8421            atlas_viewer,
8422            cull_stats,
8423            ..
8424        } = self;
8425
8426        // **Every secondary view before the primary camera's frame**, so a pass
8427        // the primary records — an overlay compositing a scope's picture onto
8428        // the lens it is seen through — reads a view that is already drawn. Each
8429        // records its whole frame straight through: its own cull, its own
8430        // clustering, and every pass the primary records after them, against the
8431        // atlas and the probe rows the scene passes above left behind.
8432        for (index, slot) in built.iter_mut().enumerate() {
8433            let Some((view_target, view_extent)) = secondary
8434                .iter()
8435                .find(|(view, _)| view.view.index() == index + 1)
8436            else {
8437                continue;
8438            };
8439            let view = slot
8440                .as_mut()
8441                .unwrap_or_else(|| unreachable!("checked against the built views above"));
8442            let view_cull = view.add_cull(graph, pool, frame, instance_count);
8443            view.add_passes(
8444                graph,
8445                &passes,
8446                view_cull,
8447                ViewOutput {
8448                    target: view_target.target,
8449                    target_extent: view_target.extent,
8450                    extent: *view_extent,
8451                },
8452                Overlays::default(),
8453                |_, _| {},
8454            );
8455        }
8456
8457        // The statistics buffer's id, read before the cull moves into the pass
8458        // recording below: the copy that reads it is the frame's last pass.
8459        let stats_id = cull.generated.visible_count_id;
8460        let tonemapped = primary.add_passes(
8461            graph,
8462            &passes,
8463            cull,
8464            ViewOutput {
8465                target,
8466                target_extent,
8467                extent,
8468            },
8469            Overlays {
8470                debug_draw: Some(debug_draw),
8471                ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8472                atlas_viewer: atlas_viewer.as_mut().filter(|_| draws_atlas_view),
8473            },
8474            overlay,
8475        );
8476
8477        // **Last, and that is the point.** Three passes add to the statistics
8478        // buffer — the cull dispatch, the light grid's overflow counter and the
8479        // amplification stage inside the forward pass — so a copy scheduled any
8480        // earlier would take a total the frame had not finished writing. The
8481        // graph puts it in `TransferSrc` for this and back into the state the
8482        // next frame on this slot imports it in; there is not a barrier written
8483        // here.
8484        if let Some(stats) = cull_stats.as_mut() {
8485            stats.add_copy_pass(graph, stats_id);
8486        }
8487
8488        tonemapped
8489    }
8490
8491    /// Adds the cull dispatches and the depth-only pass that fill the shadow
8492    /// atlas, and returns the atlas as the graph knows it.
8493    ///
8494    /// Every tile is one viewport of one render pass. A pass per tile would be
8495    /// one clear of the same image and one more barrier per tile, and the graph
8496    /// would have to be told each of them only touches part of it — where one
8497    /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8498    /// place.
8499    ///
8500    /// **Only the occupied tiles get a cull and a viewport.** The cascades
8501    /// always are; a light tile is occupied when
8502    /// [`shadow::Selection`] gave it to a light. A free one keeps the
8503    /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8504    /// away as depth goes" — so anything that did sample it would come back
8505    /// fully lit rather than fully shadowed.
8506    ///
8507    /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8508    ///
8509    /// That is the whole switch, and it is the same mechanism a free tile
8510    /// already had rather than a second one: no cull is dispatched and no
8511    /// viewport is drawn, the pass records its clear and nothing else, and every
8512    /// comparison against the atlas comes back fully lit. The pass itself stays
8513    /// on the frame that switches it off — it is what *writes* that clear, and a
8514    /// frame that skipped it would leave the atlas holding the last frame that
8515    /// did draw into it, or undefined memory on the first frame of all.
8516    ///
8517    /// # A cached atlas records nothing at all
8518    ///
8519    /// Topic 45's static-caching rung. When
8520    /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8521    /// what this frame would draw, this adds **no cull and no pass**: the atlas
8522    /// is imported so the passes that sample it have an edge to the resource,
8523    /// and it keeps the contents an earlier frame left in it. That is why the
8524    /// image is a persistent one with a tracked ledger entry rather than a
8525    /// transient — nothing else in the frame can alias it, so what it holds is
8526    /// what the last pass to write it wrote.
8527    ///
8528    /// # Per group, and what pays for the tiles it keeps
8529    ///
8530    /// Topic 45's cadence rung. A **group** — a cascade, or a
8531    /// light slot's whole run of tiles — is redrawn or held on its own, and
8532    /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8533    /// that holds nothing clears the whole attachment, which is the recording
8534    /// that shipped before the rung; a frame that holds something **loads** the
8535    /// attachment instead and resets each tile it redraws with
8536    /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8537    /// a clear bounded to one tile.
8538    ///
8539    /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8540    /// every tile including the ones being kept, and the region-bounded
8541    /// alternatives are not portable — Metal's load action and WebGPU's
8542    /// `loadOp` have no render area to bound them, so a clear that covered part
8543    /// of the image on Vulkan and all of it on Metal would be a held tile that
8544    /// survives on one backend and is erased on another.
8545    fn add_shadow_pass(
8546        &self,
8547        graph: &mut RenderGraph<'_>,
8548        pool: &TransientPool,
8549        selection: &[BufferId],
8550        reads: ShadowReads,
8551    ) -> (ImageId, u64, u64, Option<RsmImages>) {
8552        let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8553        let (atlas_width, atlas_height) = shadow::atlas_extent();
8554        let atlas = graph.import_image(
8555            "shadow-atlas",
8556            ImportedImage {
8557                image: self.shadow_atlas,
8558                view: self.shadow_atlas_view,
8559                format: Format::D32Float,
8560                extent: (atlas_width, atlas_height),
8561                // What the previous executed frame left it in — `Undefined` on
8562                // the first, which is what makes the graph give it a layout at
8563                // all.
8564                initial: imported_state(pool, self.shadow_atlas),
8565                // The renderer keeps this image across frames, so the pool's
8566                // ledger is the record of what happened to it and the line above
8567                // is that record read back rather than a second copy of it.
8568                claim: InitialClaim::Tracked,
8569                final_state: ResourceState::ShaderRead,
8570            },
8571        );
8572        // The cached frame's whole answer: the image above and nothing that
8573        // touches it. It is already in `ShaderRead` — the frame that drew it
8574        // handed it back that way — so the graph has no transition to make, and
8575        // the passes that sample it read the maps an earlier frame left there.
8576        if self.shadow_atlas_cached {
8577            // **And no reflective shadow map either**, which cannot happen while
8578            // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8579            // exactly that case, so a frame reaching here has nothing to draw
8580            // the map from. See `probe_update_runs`.
8581            return (atlas, 0, 0, None);
8582        }
8583        let placeholder = graph.import_image(
8584            "shadow-placeholder",
8585            ImportedImage {
8586                image: self.shadow_placeholder,
8587                view: self.shadow_placeholder_view,
8588                format: Format::D32Float,
8589                extent: (1, 1),
8590                // **Its own ledger entry, not the atlas's.** The two move
8591                // together today — both are imported by this function on every
8592                // frame and both are handed back in `ShaderRead` — so one lookup
8593                // would answer both, and that is exactly the coincidence a
8594                // second declared state here stops depending on.
8595                initial: imported_state(pool, self.shadow_placeholder),
8596                claim: InitialClaim::Tracked,
8597                final_state: ResourceState::ShaderRead,
8598            },
8599        );
8600
8601        // Which light slots have a light this frame, resolved once: a slot's
8602        // cull is dispatched and its faces are drawn together or not at all, and
8603        // `begin_frame` filled that generator's parameters under exactly this
8604        // condition.
8605        //
8606        // **And only the ones this frame redraws**, since the cadence rung: a
8607        // held slot keeps the texels it has, so recording its cull and its
8608        // draws would be the same picture at the full price.
8609        let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8610            .shadow_lights
8611            .slots()
8612            .iter()
8613            .enumerate()
8614            .filter(|_| shadows)
8615            .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8616            .filter_map(|(slot, held)| {
8617                let held = (*held)?;
8618                Some((slot, held, self.extra_lights.get(held.light)?))
8619            })
8620            .collect();
8621
8622        // One cull dispatch per cascade and per occupied slot, before the pass
8623        // that draws from them — **not one per tile**, which is topic 18's
8624        // fourth decision: a point light's six faces draw one visible set.
8625        let cascades: Vec<usize> = if shadows {
8626            (0..shadow::CASCADES)
8627                .filter(|cascade| self.shadow_group_redrawn[*cascade])
8628                .collect()
8629        } else {
8630            Vec::new()
8631        };
8632        // **Cascade 0's cull, on a frame that is not drawing it into the
8633        // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8634        // no shadows — see `rsm_cull_ready` — so this is the case where the map
8635        // is drawn and the atlas keeps its clear. Chained **last**, because the
8636        // occupied slots' entries are indexed by `cascades.len() + index` a few
8637        // lines below and an insertion before them would hand a light's draws to
8638        // the wrong viewport.
8639        let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8640        // The punctual producer's faces, which are also the light slots'
8641        // atlas views — see `punctual_faces`, the one list both halves of the
8642        // updater walk.
8643        let punctual = self.punctual_faces();
8644        // And their culls on a frame that is not drawing the atlas, which
8645        // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8646        // because a point light's six faces draw one visible set, and chained
8647        // **after** the entries `views` indexes positionally below.
8648        let punctual_only_culls: Vec<usize> = if shadows {
8649            Vec::new()
8650        } else {
8651            punctual
8652                .iter()
8653                .map(|face| face.cull)
8654                .collect::<std::collections::BTreeSet<_>>()
8655                .into_iter()
8656                .collect()
8657        };
8658        let generated: Vec<(usize, GeneratedDraws)> = cascades
8659            .iter()
8660            .copied()
8661            .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8662            .chain(rsm_only_cull.then_some(0))
8663            .chain(punctual_only_culls)
8664            .map(|cull| {
8665                (
8666                    cull,
8667                    self.shadow_draws[cull].add_passes(
8668                        graph,
8669                        self.frame,
8670                        self.instances.slot_count(),
8671                    ),
8672                )
8673            })
8674            .collect();
8675
8676        // What the pass body records, in order: which view's bind group, which
8677        // rectangle of the atlas its viewport covers, and which of the culls
8678        // above it draws from. Paired rather than positional, because the free
8679        // slots are missing from every one of these lists and a bare index into
8680        // one would hand a light's draws to the wrong viewport the moment one
8681        // slot is free and a later one is not.
8682        //
8683        // **The rectangle rather than the slot**, resolved here: the body runs
8684        // in a closure that outlives this borrow, and asking the selection for
8685        // it there would be a second reading of an allocation that has to be the
8686        // one the frame block was written from.
8687        //
8688        // **And which draw region of that cull**: region 0, every survivor, for
8689        // a cascade and a spot; and for a point light whose cull tagged its
8690        // casters by face, the region of the face being drawn — see
8691        // `set_point_face_culls`.
8692        let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8693            .iter()
8694            .enumerate()
8695            .map(|(position, cascade)| {
8696                (
8697                    *cascade,
8698                    self.shadow_lights.atlas_rect(*cascade),
8699                    position,
8700                    0,
8701                )
8702            })
8703            .collect();
8704        for (index, (slot, held, light)) in occupied.iter().enumerate() {
8705            // A spot draws face 0 alone; a point light draws all six, each
8706            // through its own matrix into its own tile. `shadow::tile_span` is
8707            // the same function `Selection` allocated the run with, so a face
8708            // here and a tile there cannot disagree about how many there are.
8709            let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8710                == crcbl_shaders::draw_gen::DrawMode::Faces;
8711            for face in 0..shadow::tile_span(light) {
8712                views.push((
8713                    shadow_view(*slot, face),
8714                    self.shadow_lights
8715                        .atlas_rect(shadow::light_tile(held.base + face)),
8716                    cascades.len() + index,
8717                    face_region(by_face, face),
8718                ));
8719            }
8720        }
8721
8722        let mut pass = graph
8723            .add_render_pass("shadow")
8724            // **Stored, unlike the scene's depth.** This is the one depth buffer
8725            // in the engine that something downstream reads, which is what
8726            // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8727            // day a prepass existed.
8728            .depth(
8729                atlas,
8730                // **Loaded on a frame that is keeping a tile**, which is the
8731                // cadence rung's whole seam: a clear here covers the image, so
8732                // the tiles this frame *does* redraw are reset one at a time by
8733                // the pipeline below instead. A frame keeping nothing clears,
8734                // which is what shipped.
8735                if self.shadow_atlas_clears {
8736                    LoadOp::Clear
8737                } else {
8738                    LoadOp::Load
8739                },
8740                StoreOp::Store,
8741                crcbl_hal::ClearValue {
8742                    depth: crcbl_hal::depth::CLEAR,
8743                    ..crcbl_hal::ClearValue::default()
8744                },
8745            )
8746            // Declared so the graph gives it a shader-read layout: it is in
8747            // every cascade's bind group, standing in for the atlas this pass is
8748            // writing. See `ForwardRenderer::shadow_placeholder`.
8749            .read_image(placeholder)
8750            // Likewise, and it is in every one of those groups too — see
8751            // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8752            // it here either: the depth-only pipeline has no fragment stage.
8753            .read_image(reads.occlusion_placeholder)
8754            // And §3.2's page, which `mesh_layout` names in every group — a
8755            // cascade's included. See `ForwardRenderer::base_color_page_import`
8756            // for what the declaration buys a caller that writes the page.
8757            .read_image(reads.pages.base_color)
8758            // And §2's other three pages beside it, in those same groups and
8759            // sampled by no cascade — see
8760            // `ForwardRenderer::normal_page_import`.
8761            .read_image(reads.pages.normal)
8762            .read_image(reads.pages.mro)
8763            .read_image(reads.pages.emissive)
8764            // And the probe rows, which are in those groups too and which no
8765            // cascade reads — declared on the placeholder's and the pages'
8766            // terms, plus one of their own: the rows are device-local and a copy
8767            // destination so the irradiance probes' gather can
8768            // write them, and a pass that binds a buffer it has not declared is
8769            // one the graph cannot order that write against.
8770            .read_buffer(reads.probes);
8771        // Each tile's mesh pass records the cut it descended to, into a buffer
8772        // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8773        // there is no amplification stage to descend anything.
8774        //
8775        // Declared for every tile rather than for the occupied ones: the state
8776        // is what the buffer is *in*, which does not depend on whether this
8777        // frame happened to write it, and a free tile's buffer still has to
8778        // arrive in the state the next frame's import claims.
8779        for &buffer in selection {
8780            pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8781        }
8782        // The skinned vertices this pass may pull, and the reason it is declared
8783        // here as well as on the colour passes: a cascade draws the same
8784        // geometry out of the same pool, so a shadow that fell before the
8785        // dispatch was visible would be cast by the previous pose — a shadow
8786        // that does not match its caster, on a frame whose picture is otherwise
8787        // right.
8788        if let Some(vertices) = reads.skinned {
8789            pass = pass.read_buffer(vertices);
8790        }
8791        for (_, draws) in &generated {
8792            pass = read_draw_sources(pass, draws, self.emit);
8793        }
8794
8795        let groups = self.shadow_groups[self.frame].clone();
8796        // **What the reflective shadow map is drawn from**, read out here rather
8797        // than reconstructed by the caller: cascade 0's bind group — whose
8798        // uniform block already holds that cascade's `view_proj`, which is what
8799        // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8800        // produced a moment ago. Both are `Copy`, so recording a second pass
8801        // from them costs no second cull and no second matrix.
8802        //
8803        // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8804        // or a `r_shadow_cadence` past one that held the group anyway. The rows
8805        // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8806        // which says so.
8807        let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8808            .rsm_cull_ready
8809            .then(|| {
8810                generated
8811                    .iter()
8812                    .find(|(cull, _)| *cull == 0)
8813                    .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8814            })
8815            .flatten();
8816        // **What the punctual reflective shadow map is drawn from**, resolved
8817        // here for `cascade_zero`'s reason and on its terms: each face's own
8818        // bind group — whose uniform block already holds that face's
8819        // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8820        // moment ago. Both are `Copy`, so the second pass costs no second cull
8821        // and no second matrix.
8822        //
8823        // Found by cull id rather than by position, so this list and the atlas's
8824        // cannot be knocked out of step by a slot the other one skipped.
8825        //
8826        // And the face's draw region, on the atlas's terms: a point light whose
8827        // cull tagged its casters draws each face from that face's region.
8828        let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8829            punctual
8830                .iter()
8831                .filter_map(|face| {
8832                    let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8833                    let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8834                        == crcbl_shaders::draw_gen::DrawMode::Faces;
8835                    Some((
8836                        groups[face.view],
8837                        face.tile,
8838                        *draws,
8839                        face_region(by_face, face.face),
8840                    ))
8841                })
8842                .collect();
8843        // The culls those faces draw from, **once each**: a point light's six
8844        // faces draw one visible set, so declaring a face's sources would
8845        // declare the same buffers six times in one pass.
8846        let punctual_sources: Vec<GeneratedDraws> = punctual
8847            .iter()
8848            .map(|face| face.cull)
8849            .collect::<std::collections::BTreeSet<_>>()
8850            .into_iter()
8851            .filter_map(|cull| {
8852                let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8853                Some(*draws)
8854            })
8855            .collect();
8856        let bucket_draws = BucketDraws {
8857            // Replaced per partition below; the field is what the tile clears
8858            // and the reflective shadow map inherit, and neither binds it.
8859            pipeline: self.shadow_pipeline.single,
8860            layout: self.mesh_pipeline_layout,
8861            indices: self.pool.index_buffer(),
8862            emit: self.emit,
8863            calls: self
8864                .bucket_constants
8865                .iter()
8866                .enumerate()
8867                .map(|(bucket, constant_offset)| {
8868                    let bucket = u32::try_from(bucket)
8869                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8870                    (
8871                        *constant_offset,
8872                        self.primary.draws.args_offset(bucket),
8873                        self.primary.draws.count_offset(bucket),
8874                        self.primary.draws.mesh_args_offset(bucket),
8875                    )
8876                })
8877                .collect(),
8878            region_step: self.region_step,
8879            // Packed per partition, where the partition's buckets are known.
8880            ranges: None,
8881            flat: None,
8882        };
8883        // Kept back for the reflective shadow map below, which is the same
8884        // per-bucket call list under a different pipeline — the depth prepass
8885        // plays exactly this trick with the camera's. Cloned before the pass
8886        // body takes the original.
8887        let bucket_calls = bucket_draws.clone();
8888        // The atlas's own split by material mode: an opaque bucket's tile is
8889        // drawn with no fragment stage in a scene that has a cutout in it. Every
8890        // view draws every partition — one call per bucket, per range of
8891        // buckets, or behind a task stage one flat call, per view, under a
8892        // pipeline per mode.
8893        let tile_partitions = self.depth_partitions(&bucket_draws);
8894
8895        // Counted off the two loops the body below runs, before it takes them:
8896        // every partition's calls per occupied view. `ForwardRenderer::counters`
8897        // is what reports it, and reading it back off the same `Vec`s is what
8898        // makes it move when the tile allocation does.
8899        let recorded = views.len() as u64
8900            * tile_partitions
8901                .iter()
8902                .map(BucketDraws::call_count)
8903                .sum::<u64>();
8904        // And the tile resets beside them, which are direct draws of one
8905        // instance rather than indirect ones: a frame that cleared the whole
8906        // attachment records none, and a frame that loaded it records one per
8907        // tile it redraws.
8908        let clears = if self.shadow_atlas_clears {
8909            0
8910        } else {
8911            views.len() as u64
8912        };
8913
8914        // What the image will hold once this body has run, carried into it so
8915        // that *recording* the pass is not what claims the atlas was drawn — see
8916        // [`ForwardRenderer::shadow_atlas_drawn`].
8917        let ran = Arc::clone(&self.shadow_pass_ran);
8918        let pass_id = self.shadow_pass_id;
8919        // The tiles this pass redraws have to be reset before anything is drawn
8920        // into them, and on a frame that loaded the attachment there is nothing
8921        // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8922        // that cleared has already had every tile reset by the attachment, so
8923        // this is `None` and the recording is the one that shipped.
8924        let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8925        // **The reset draw has to bind a group, and only a browser says so.**
8926        // `MeshModules::depth_clear_pipeline` builds this pipeline from
8927        // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8928        // the one triangle's vertex shader reads a byte of it — and WebGPU
8929        // refuses a draw with any group the *layout* declares left unset, where
8930        // Vulkan and the others only care about what the shader dereferences. An
8931        // unbound reset therefore fails no native run and rejects the whole
8932        // browser frame: `No bind group set at group index 0` arrives when the
8933        // encoder is finished, so every pass recorded after it is thrown away
8934        // with it and the canvas stays at the clear colour.
8935        //
8936        // Any bucket's offset does: the block is what the mesh draws index and
8937        // this draw reads none of it, so what matters is that the offset is one
8938        // the layout accepts rather than which bucket it names.
8939        let clear_layout = bucket_draws.layout;
8940        let clear_offset = bucket_draws
8941            .calls
8942            .first()
8943            .map_or(0, |(constant_offset, ..)| *constant_offset);
8944        pass.execute(move |ctx| {
8945            ran.store(pass_id, Ordering::Relaxed);
8946            let encoder = ctx.encoder();
8947            if let Some(clear) = clear {
8948                encoder.bind_graphics_pipeline(clear);
8949                for (view, tile, _, _) in &views {
8950                    set_shadow_tile(encoder, *tile);
8951                    encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8952                    encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8953                }
8954            }
8955            for partition in &tile_partitions {
8956                partition.open(encoder);
8957                for (view, tile, cull, region) in &views {
8958                    set_shadow_tile(encoder, *tile);
8959                    partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8960                }
8961            }
8962        });
8963
8964        // --- the reflective shadow map ---
8965        //
8966        // The irradiance probes' updater, first half, recorded
8967        // here because this is where cascade 0's bind group and its
8968        // already-generated draws are. **A pass of its own at its own extent**,
8969        // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8970        // one colour attachment there spans the whole 3072² image for data only
8971        // one 768² tile is read from, and it would give all fourteen light tiles
8972        // a fragment stage.
8973        //
8974        // No viewport is set: the graph opens a pass with a full-target viewport
8975        // and scissor already, and every attachment here is the map's own square.
8976        // Both or nothing: the map is drawn with pipelines `build` made only
8977        // for a volume that is updated, so a renderer without them has no map
8978        // to record and no gather to feed.
8979        let (Some((cascade_group, cascade_draws)), Some(rsm_pipeline)) =
8980            (cascade_zero, self.rsm_pipeline)
8981        else {
8982            return (atlas, recorded, clears, None);
8983        };
8984        let extent = rsm::extent();
8985        let sun = RsmTargets {
8986            albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8987            normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
8988            world: graph.create_image("rsm-world", rsm::world_target(extent)),
8989        };
8990        // Its own depth, cleared and discarded: it resolves which surface a
8991        // texel of the map holds and nothing reads it afterwards.
8992        let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
8993        let mut rsm = graph
8994            .add_render_pass("rsm")
8995            // **Cleared, and the world target's clear is load-bearing**: `w` is
8996            // the coverage flag `RsmOutput::world` writes, so a texel the pass
8997            // draws nothing into reads back zero there and the gather skips it.
8998            // Without the clear the world origin would stand in for every part
8999            // of the cascade the geometry does not cover.
9000            .clear_color(sun.albedo, [0.0; 4])
9001            .clear_color(sun.normal, [0.0; 4])
9002            .clear_color(sun.world, [0.0; 4])
9003            .clear_depth(rsm_depth)
9004            // The same declarations the cascade above makes, for the same
9005            // reason: every group of the mesh layout names these, and this pass
9006            // binds one of those groups. Unlike the cascade, this one has a
9007            // fragment stage — so the pages really are sampled here.
9008            .read_image(placeholder)
9009            .read_image(reads.occlusion_placeholder)
9010            .read_image(reads.pages.base_color)
9011            .read_image(reads.pages.normal)
9012            .read_image(reads.pages.mro)
9013            .read_image(reads.pages.emissive)
9014            .read_buffer(reads.probes);
9015        if let Some(vertices) = reads.skinned {
9016            rsm = rsm.read_buffer(vertices);
9017        }
9018        // Cascade 0's cluster-selection buffer, which the mesh path's stages
9019        // write — declared on the atlas pass's terms, and only for the one view
9020        // this pass draws.
9021        if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
9022            rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
9023        }
9024        rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
9025        // Split by side, on the colour pass's terms: this stage cuts the alpha
9026        // mask itself, so the only thing it cannot say inside the fragment stage
9027        // is which faces the rasteriser keeps.
9028        let rsm_partitions = self.sided_partitions(&bucket_calls, rsm_pipeline);
9029        let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
9030        rsm.execute(move |ctx| {
9031            let encoder = ctx.encoder();
9032            for partition in &rsm_partitions {
9033                partition.open(encoder);
9034                partition.record(encoder, cascade_group, &cascade_draws);
9035            }
9036        });
9037
9038        // --- the punctual reflective shadow map ---
9039        //
9040        // The irradiance probes' punctual producer: the same
9041        // pipeline and the same per-bucket call list as the pass above, under
9042        // one viewport per shadowed light face instead of one whole map. A spot
9043        // is a tile and a point light is six, which is `shadow::tile_span` — so
9044        // this is the atlas pass's own view loop drawn into a second, much
9045        // smaller set of targets.
9046        //
9047        // **Recorded whether or not the frame lights a punctual face**, unlike
9048        // the map above. The clear is a legitimate answer — a frame with no
9049        // shadowed punctual light has no punctual bounce, and the coverage flag
9050        // in `w` says so at every texel — and a pass that came and went with the
9051        // lights would be a pass list that changes shape with the scene, which
9052        // is what `RENDER_PASSES` and every timing reader are written against.
9053        let punctual_extent = rsm::punctual_extent();
9054        let punctual_targets = RsmTargets {
9055            albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
9056            normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
9057            world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
9058        };
9059        let punctual_depth =
9060            graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
9061        let mut punctual_pass = graph
9062            .add_render_pass("rsm-punctual")
9063            // Cleared on the map above's terms, and the world target's clear is
9064            // load-bearing for its reason as well as for one of this map's own:
9065            // the tiles the cascades would hold are drawn into by nothing at
9066            // all, and a coverage flag of zero is what keeps the gather out of
9067            // them.
9068            .clear_color(punctual_targets.albedo, [0.0; 4])
9069            .clear_color(punctual_targets.normal, [0.0; 4])
9070            .clear_color(punctual_targets.world, [0.0; 4])
9071            .clear_depth(punctual_depth)
9072            .read_image(placeholder)
9073            .read_image(reads.occlusion_placeholder)
9074            .read_image(reads.pages.base_color)
9075            .read_image(reads.pages.normal)
9076            .read_image(reads.pages.mro)
9077            .read_image(reads.pages.emissive)
9078            .read_buffer(reads.probes);
9079        if let Some(vertices) = reads.skinned {
9080            punctual_pass = punctual_pass.read_buffer(vertices);
9081        }
9082        // Each face's own cluster-selection buffer, which the mesh path's stages
9083        // write — declared on the atlas pass's terms, and only for the views
9084        // this pass draws.
9085        for face in &punctual {
9086            if let Some(&buffer) = selection.get(face.view) {
9087                punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
9088            }
9089        }
9090        for draws in &punctual_sources {
9091            punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
9092        }
9093        let punctual_partitions = self.sided_partitions(&bucket_calls, rsm_pipeline);
9094        let punctual_recorded = punctual_views.len() as u64
9095            * punctual_partitions
9096                .iter()
9097                .map(BucketDraws::call_count)
9098                .sum::<u64>();
9099        punctual_pass.execute(move |ctx| {
9100            let encoder = ctx.encoder();
9101            // The partition is **outside** the view loop, on the shadow atlas's
9102            // terms: one pipeline bind covers every face of that side.
9103            for partition in &punctual_partitions {
9104                partition.open(encoder);
9105                for (group, tile, draws, region) in &punctual_views {
9106                    set_shadow_tile(encoder, *tile);
9107                    partition.record_region(encoder, *group, draws, *region);
9108                }
9109            }
9110        });
9111
9112        let images = RsmImages {
9113            sun,
9114            punctual: punctual_targets,
9115        };
9116        (
9117            atlas,
9118            recorded + rsm_recorded + punctual_recorded,
9119            clears,
9120            Some(images),
9121        )
9122    }
9123
9124    /// Which lights hold the atlas's light tiles this frame, and where each
9125    /// map was laid out.
9126    ///
9127    /// **The observable topic 45's priority rung otherwise has
9128    /// none for.** A map's *size* leaves no trace in the picture that a golden
9129    /// can hold anyone to: a light demoted to a quarter of a cell draws a
9130    /// slightly softer shadow, which is a perfectly plausible frame and one a
9131    /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
9132    /// off this is what says which level the allocator actually handed out, and
9133    /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
9134    ///
9135    /// Named for the selection's own subject rather than for its type, because
9136    /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
9137    /// descended to — and two accessors of one name is a caller reaching for
9138    /// the wrong one.
9139    ///
9140    /// It is this frame's answer, written by [`Self::begin_frame`]: before the
9141    /// first frame every slot is free.
9142    /// Whether this frame took the shadow atlas as an earlier frame left it,
9143    /// rather than drawing it again.
9144    ///
9145    /// Topic 45's static-caching rung, read back. True means
9146    /// this frame recorded **no** shadow cull and no shadow pass, and every map
9147    /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
9148    /// frame that did draw put there — so a caller comparing two frames' pass
9149    /// lists, draw counts or GPU timings has to know which of them redrew.
9150    ///
9151    /// Decided by [`Self::begin_frame`] out of everything each group of the
9152    /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
9153    /// and it answers `false` before the first frame, because no frame has been
9154    /// opened and so none of them has held anything.
9155    ///
9156    /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
9157    /// frame that redraws one map and holds another answers `false` here and
9158    /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
9159    /// together are what say which.
9160    #[must_use]
9161    pub const fn shadow_atlas_cached(&self) -> bool {
9162        self.shadow_atlas_cached
9163    }
9164
9165    /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
9166    /// the one an earlier frame put there.
9167    ///
9168    /// Topic 45's cadence rung, read back. **The observable
9169    /// that rung otherwise has none for**: a held map draws a shadow lagging its
9170    /// caster by a frame or two, which is a perfectly plausible picture and one
9171    /// a golden accepts — so nothing but this distinguishes a cadence that is
9172    /// working from one that is not running at all.
9173    ///
9174    /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
9175    /// frame, which is the same answer for the same reason: no map was drawn
9176    /// there.
9177    #[must_use]
9178    pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
9179        cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
9180    }
9181
9182    /// Whether this frame redrew the maps of light slot `slot` —
9183    /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
9184    /// earlier frame put there.
9185    ///
9186    /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
9187    /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
9188    /// once and draw one visible set, so they are redrawn or held as one.
9189    #[must_use]
9190    pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
9191        slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
9192    }
9193
9194    /// How many tiles of the atlas this frame redrew.
9195    ///
9196    /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
9197    /// say the budget bound rather than that it was configured. A cascade costs
9198    /// one and a point light's cube costs [`shadow::POINT_FACES`].
9199    #[must_use]
9200    pub const fn shadow_faces_redrawn(&self) -> u32 {
9201        self.shadow_faces_redrawn
9202    }
9203
9204    /// Pins the shadow cadence for this renderer, or hands it back to the
9205    /// console.
9206    ///
9207    /// [`Self::set_effect_request`]'s shape at this knob:
9208    /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
9209    /// process-global, so they are the *default* rather than the only answer —
9210    /// an application drawing two views at two qualities, or a test that needs a
9211    /// frame nothing else in the process can move, pins its own.
9212    ///
9213    /// [`None`] hands it back, which is what a renderer starts at.
9214    ///
9215    /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
9216    /// terms: this call decides it and `add_passes` acts on it.
9217    pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
9218        self.shadow_cadence_request = cadence;
9219    }
9220
9221    /// Whether this frame ignored the cadence for at least one map because the
9222    /// region that map covers had moved out from under it.
9223    ///
9224    /// Topic 45's "a moving light or camera cut resets it",
9225    /// made precise: a map is *reset* rather than merely out of date when the
9226    /// centre it is projected from has moved further than the map's own reach —
9227    /// a light further than its own radius, or a cascade's eye further than the
9228    /// sphere that cascade was fitted to. Holding such a map is not a shadow
9229    /// that lags; it is a shadow of somewhere else.
9230    ///
9231    /// A frame whose atlas was **relaid** — a light gained, lost or resized a
9232    /// tile, or shadows were switched on or off — answers `true` as well, and
9233    /// that frame redraws every map it has: the only clear this seam can make
9234    /// covers the whole image, so there is nothing left to hold.
9235    #[must_use]
9236    pub const fn shadow_cadence_reset(&self) -> bool {
9237        self.shadow_cadence_reset
9238    }
9239
9240    #[must_use]
9241    pub const fn shadow_lights(&self) -> &shadow::Selection {
9242        &self.shadow_lights
9243    }
9244
9245    /// The shadow atlas, for a caller that wants to read it back.
9246    ///
9247    /// **The observable this whole slice can otherwise hide behind.** A shadow
9248    /// pass that renders nothing leaves every texel at
9249    /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
9250    /// everything is lit — which is a perfectly plausible picture and matches
9251    /// any golden blessed from it. Copying this image back and finding a texel
9252    /// that is not the clear value is what distinguishes the two.
9253    ///
9254    /// It is created with
9255    /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
9256    /// exactly that, and its extent is [`shadow::atlas_extent`].
9257    #[must_use]
9258    pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
9259        self.shadow_atlas
9260    }
9261
9262    /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
9263    /// through, for a reader importing the atlas into a graph of its own.
9264    #[must_use]
9265    pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
9266        self.shadow_atlas_view
9267    }
9268
9269    /// The base-colour page every material row samples through
9270    /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
9271    /// as the image and the view [`crate::texture`] uploaded.
9272    ///
9273    /// **What a render-to-texture view copies into.** A second camera drawing
9274    /// into an image is only half of a monitor: the surface that *shows* it
9275    /// samples a page layer, and nothing above this crate can name the image
9276    /// that layer lives in.
9277    ///
9278    /// A caller that wants to *write* it wants
9279    /// [`base_color_page_import`](Self::base_color_page_import) instead: the
9280    /// graph can only order a copy against the draws that sample the page while
9281    /// both are declared, and the two declarations have to agree field for
9282    /// field. This one is the raw handles, for a caller that binds or reads them
9283    /// outside a graph.
9284    ///
9285    /// It is created with
9286    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
9287    /// because the upload that filled it is a copy, so a per-frame copy into it
9288    /// needs no new usage flag. Its extent is
9289    /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
9290    /// [`PageKind::BaseColor`] squared and it has one layer per
9291    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
9292    /// the description is the caller's, so the caller already knows both. A
9293    /// description naming no base-colour layer gets a 1×1 placeholder instead —
9294    /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
9295    #[must_use]
9296    pub const fn base_color_page(&self) -> UploadedTexture {
9297        self.base_color_page
9298    }
9299
9300    /// What [`add_passes`](Self::add_passes) names the base-colour page in the
9301    /// graph.
9302    ///
9303    /// [`RenderGraph::import_image`] keeps the label of whichever import ran
9304    /// first, so a caller importing the page too passes this rather than a
9305    /// string of its own — otherwise every barrier record and
9306    /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
9307    /// depending on which subsystem got there first.
9308    pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
9309
9310    /// The base-colour page **as this renderer declares it to a graph**.
9311    ///
9312    /// [`add_passes`](Self::add_passes) imports exactly this value under
9313    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
9314    /// of it on every pass whose bind group names the page, so a caller that
9315    /// writes the page — a render-to-texture view copied into one layer — gets
9316    /// the graph to order its write against those draws.
9317    ///
9318    /// **A caller that writes it imports this value rather than one of its
9319    /// own.** [`RenderGraph::import_image`] hands the second importer the id the
9320    /// first got, which is what puts the write and the reads on one state
9321    /// tracker, and it does that only while the two declarations agree in every
9322    /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
9323    /// [`compile`](RenderGraph::compile). Reading the declaration off the
9324    /// renderer that owns the page is what makes them one answer instead of two
9325    /// constants that have to be kept equal by hand.
9326    ///
9327    /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
9328    /// [`crate::texture`] leaves an uploaded page in that state, and the
9329    /// trailing barrier the `final_state` asks for puts it back there at the end
9330    /// of every frame — so the pool's ledger and this declaration are the same
9331    /// answer, which is what `Tracked` has the graph check.
9332    ///
9333    /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
9334    #[must_use]
9335    pub const fn base_color_page_import(&self) -> ImportedImage {
9336        ImportedImage {
9337            image: self.base_color_page.image,
9338            view: self.base_color_page.view,
9339            format: BASE_COLOR_PAGE_FORMAT,
9340            extent: self.page_extents[PageKind::BaseColor.index()],
9341            initial: ResourceState::ShaderRead,
9342            claim: InitialClaim::Tracked,
9343            final_state: ResourceState::ShaderRead,
9344        }
9345    }
9346
9347    /// Topic 43 §2's **normal** page, the raw handles.
9348    ///
9349    /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
9350    /// its terms: one `D2Array` image, one layer per
9351    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
9352    /// [`PageKind::Normal`], at **that kind's own extent**, and created with
9353    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
9354    /// per-frame copy into a layer needs no new usage flag. What it is *not* is
9355    /// the same format: it is `Rgba8Unorm`, where the base-colour page is
9356    /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
9357    /// is argued.
9358    #[must_use]
9359    pub const fn normal_page(&self) -> UploadedTexture {
9360        self.normal_page
9361    }
9362
9363    /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
9364    /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9365    pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
9366
9367    /// The normal page **as this renderer declares it to a graph**, on
9368    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
9369    /// — including that a caller writing a layer imports *this* value rather
9370    /// than one of its own, so the write and the draws land on one state
9371    /// tracker.
9372    #[must_use]
9373    pub const fn normal_page_import(&self) -> ImportedImage {
9374        ImportedImage {
9375            image: self.normal_page.image,
9376            view: self.normal_page.view,
9377            format: NORMAL_PAGE_FORMAT,
9378            extent: self.page_extents[PageKind::Normal.index()],
9379            initial: ResourceState::ShaderRead,
9380            claim: InitialClaim::Tracked,
9381            final_state: ResourceState::ShaderRead,
9382        }
9383    }
9384
9385    /// Topic 43 §2's packed
9386    /// **metallic-roughness-occlusion** page, the raw handles.
9387    ///
9388    /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
9389    /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
9390    /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
9391    /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
9392    #[must_use]
9393    pub const fn mro_page(&self) -> UploadedTexture {
9394        self.mro_page
9395    }
9396
9397    /// What [`add_passes`](Self::add_passes) names the
9398    /// metallic-roughness-occlusion page in the graph, on
9399    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9400    pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
9401
9402    /// The metallic-roughness-occlusion page **as this renderer declares it to a
9403    /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
9404    /// terms exactly.
9405    #[must_use]
9406    pub const fn mro_page_import(&self) -> ImportedImage {
9407        ImportedImage {
9408            image: self.mro_page.image,
9409            view: self.mro_page.view,
9410            format: MRO_PAGE_FORMAT,
9411            extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
9412            initial: ResourceState::ShaderRead,
9413            claim: InitialClaim::Tracked,
9414            final_state: ResourceState::ShaderRead,
9415        }
9416    }
9417
9418    /// Topic 43 §2's **emissive** page, the raw
9419    /// handles.
9420    ///
9421    /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
9422    /// format: an emissive texel is a colour, so this image is
9423    /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
9424    /// `EMISSIVE_PAGE_FORMAT`.
9425    #[must_use]
9426    pub const fn emissive_page(&self) -> UploadedTexture {
9427        self.emissive_page
9428    }
9429
9430    /// What [`add_passes`](Self::add_passes) names the emissive page in the
9431    /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9432    pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
9433
9434    /// The emissive page **as this renderer declares it to a graph**, on
9435    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
9436    #[must_use]
9437    pub const fn emissive_page_import(&self) -> ImportedImage {
9438        ImportedImage {
9439            image: self.emissive_page.image,
9440            view: self.emissive_page.view,
9441            format: EMISSIVE_PAGE_FORMAT,
9442            extent: self.page_extents[PageKind::Emissive.index()],
9443            initial: ResourceState::ShaderRead,
9444            claim: InitialClaim::Tracked,
9445            final_state: ResourceState::ShaderRead,
9446        }
9447    }
9448
9449    /// The model matrix for a cube spinning at `seconds` into the run.
9450    ///
9451    /// Two axes at incommensurable rates, so the animation never repeats and
9452    /// every face comes into view — which is what makes "the cube is spinning"
9453    /// observable rather than a claim about a matrix.
9454    #[must_use]
9455    pub fn spin(seconds: f32) -> Mat4 {
9456        Mat4::from_quat(
9457            Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
9458                * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
9459        )
9460    }
9461
9462    /// The format the tonemap pass renders into.
9463    #[must_use]
9464    pub const fn target_format(&self) -> Format {
9465        self.target_format
9466    }
9467
9468    /// Switches the infinite ground grid on with `style`, or off with [`None`].
9469    ///
9470    /// **Off by default.** Every sample and every golden image predates the
9471    /// grid, so a renderer nobody has called this on records exactly the passes
9472    /// it always did — see [`crate::grid`] for what the pass is and
9473    /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9474    ///
9475    /// The first `Some` builds the pipeline and the uniform ring; later calls
9476    /// only replace the style, and a `None` leaves both built. Releasing them
9477    /// here would mean releasing blocks the frames in flight may still be
9478    /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9479    /// one call that already requires an idle device.
9480    ///
9481    /// # Errors
9482    ///
9483    /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9484    /// Nothing is left switched on when that happens: the grid stays as it was.
9485    pub fn set_ground_grid(
9486        &mut self,
9487        device: &dyn Device,
9488        style: Option<GridStyle>,
9489    ) -> Result<(), HalError> {
9490        let Some(style) = style else {
9491            self.ground_grid_on = false;
9492            return Ok(());
9493        };
9494        let grid = match self.ground_grid.as_mut() {
9495            Some(grid) => grid,
9496            None => {
9497                // Built for the tonemap's target and the scene depth, because
9498                // those are the two attachments the pass is given — see
9499                // `add_passes`. Both are pipeline state, so a renderer whose
9500                // target format changed would need a new `Grid`; nothing in this
9501                // crate changes it after `build`, and `target_format` is kept
9502                // for exactly that reason.
9503                let grid = GroundGrid::new(
9504                    device,
9505                    self.primary.uniforms.len(),
9506                    self.target_format,
9507                    SCENE_DEPTH_FORMAT,
9508                )?;
9509                self.ground_grid.insert(grid)
9510            }
9511        };
9512        grid.set_style(style);
9513        self.ground_grid_on = true;
9514        Ok(())
9515    }
9516
9517    /// The debug draw layer's immediate-mode buffer, to append to.
9518    ///
9519    /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9520    /// spheres and frusta during the frame, and
9521    /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9522    /// a segment lives exactly the frame it was appended in and nothing has to
9523    /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9524    /// for the console switch that has to be on before anything is drawn.
9525    ///
9526    /// **Appending is free while the layer is off**, but building the geometry
9527    /// is the caller's: a system whose overlay costs something to compute asks
9528    /// [`DebugDraw::enabled`] first.
9529    pub fn debug_draw(&mut self) -> &mut DebugDraw {
9530        &mut self.debug_draw
9531    }
9532
9533    /// How the ground grid is drawn, or [`None`] where it is switched off.
9534    ///
9535    /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9536    /// observable a test asking "is the grid on" wants: a renderer that built
9537    /// the grid and then switched it off answers [`None`], because what it draws
9538    /// is what the question is about.
9539    #[must_use]
9540    pub fn ground_grid(&self) -> Option<&GridStyle> {
9541        self.ground_grid
9542            .as_ref()
9543            .filter(|_| self.ground_grid_on)
9544            .map(GroundGrid::style)
9545    }
9546
9547    /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9548    ///
9549    /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9550    /// [`set_sky`](Self::set_sky) or
9551    /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9552    /// here rather than left to the shader for the reason [`crate::sky_pass`]
9553    /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9554    /// frames, where adding no pass leaves them exactly as they were.
9555    fn draws_sky(&self) -> bool {
9556        self.sky != Sky::NONE || self.atmosphere.is_some()
9557    }
9558
9559    /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9560    /// per frame.
9561    ///
9562    /// Called once per [`Self::begin_frame`]. The comparison is on the
9563    /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9564    /// over, so re-setting the same sun spelled a different length is not a
9565    /// rebuild — and a caller that sets the same value every frame, which is
9566    /// the ordinary shape of a scene's update, pays the comparison and nothing
9567    /// else.
9568    ///
9569    /// # The first LUT is marched whole; every later one is marched in stripes
9570    ///
9571    /// A renderer that has no LUT has no sky to draw, so the first march after
9572    /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9573    /// call and a caller that draws a single frame gets that frame's sky. After
9574    /// that there is always a finished LUT to show, so a sun that moved starts
9575    /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9576    /// frame — the frames in between keep drawing the LUT the last completed
9577    /// march produced, and no frame pays the whole march.
9578    ///
9579    /// # A sun that moves again restarts the march rather than finishing it
9580    ///
9581    /// The build in flight is kept only while its own sun is still the one the
9582    /// caller wants; a sun that moved during it is a new build from row zero,
9583    /// because finishing the old one would swap in a LUT for a sun that is
9584    /// already wrong and then immediately start marching again. **A sun that
9585    /// moves every frame therefore never completes a build and goes on showing
9586    /// the last one it finished** — a sky frozen at the sun it last caught up
9587    /// with, rather than a sky that stutters at whatever the march last passed.
9588    /// That is the trade this makes: the frame cost is bounded and the sky
9589    /// lags, where the whole-march rebuild it replaced had the sky exact and
9590    /// the frame cost unbounded. A caller that wants the sky exact stops the
9591    /// sun on a value and leaves it there: the march then completes, and the
9592    /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9593    ///
9594    /// **The aerial-perspective LUT is marched in the same steps** — see
9595    /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9596    /// frame as the sky and lags the sun by the same frames, never a sun apart
9597    /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9598    /// on the same terms, since it is part of the parameters compared.
9599    fn refresh_sky_view(&mut self) {
9600        let Some(atmosphere) = self.atmosphere else {
9601            self.sky_view = None;
9602            self.sky_view_build = None;
9603            return;
9604        };
9605        let parameters = atmosphere.parameters();
9606        if self
9607            .sky_view
9608            .as_ref()
9609            .is_some_and(|presented| presented.parameters == parameters)
9610        {
9611            self.sky_view_build = None;
9612            return;
9613        }
9614        if self.sky_view.is_none() {
9615            self.sky_view_build = None;
9616            self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(&parameters)));
9617            return;
9618        }
9619        let mut build = match self.sky_view_build.take() {
9620            Some(build) if build.atmosphere() == parameters => build,
9621            _ => SkyViewBuild::start(&parameters),
9622        };
9623        if build.step(SKY_VIEW_BUILD_ROWS) {
9624            self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9625        } else {
9626            self.sky_view_build = Some(build);
9627        }
9628    }
9629
9630    /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9631    /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9632    ///
9633    /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9634    /// the value `tonemap.slang` held as a compile-time constant until this
9635    /// became a runtime one — so a renderer nobody calls this on draws the frame
9636    /// it always drew, and every golden image is untouched.
9637    ///
9638    /// It takes effect on the next
9639    /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9640    /// frame already recorded reads the value it was recorded with.
9641    ///
9642    /// **The clamp is here rather than at the call site** so that no caller can
9643    /// reach a picture it cannot get back from, and so that a control which
9644    /// steps by reading this back and setting a multiple of it — which is what
9645    /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9646    /// then need as many presses to come back.
9647    pub const fn set_exposure(&mut self, exposure: f32) {
9648        // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9649        // and a NaN reaching the block is a frame of NaN pixels with no key to
9650        // press to get out of it. `f32::max` returns the bound instead, so a NaN
9651        // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9652        self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9653    }
9654
9655    /// How far auto-exposure may travel toward its measurement in one frame.
9656    ///
9657    /// **[`None`] is the whole distance**, which is what a renderer nobody
9658    /// calls this on does and what the pass did before adaptation existed — so
9659    /// no golden moved when this arrived. A view that wants the roll asks, and
9660    /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9661    /// own delta: this crate has no clock, and the frame time lives where the
9662    /// frame loop is.
9663    ///
9664    /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9665    /// what writes the block, and it does nothing at all on a frame that did not
9666    /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9667    /// the ones that bit adds.
9668    pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9669        self.exposure_adaptation = adaptation;
9670    }
9671
9672    /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9673    /// handed.
9674    #[must_use]
9675    pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9676        self.exposure_adaptation
9677    }
9678
9679    /// Which operator the tonemap pass runs on the exposed scene colour.
9680    ///
9681    /// **The ACES fit by default**, because this renderer shades in linear HDR
9682    /// and the roll-off is what that range is for. What a caller asks *for* here
9683    /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9684    /// identity on `0..=1`, so display-referred content reaches the swapchain
9685    /// exactly, and a fixture that predicts a code value from a host model of
9686    /// the shading needs the frame to stay scene-referred. Every 2D sample in
9687    /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9688    /// instead, so none of them reaches this pass at all.
9689    ///
9690    /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9691    /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9692    /// there, and a frame already recorded reads the value it was recorded
9693    /// with.
9694    ///
9695    /// **There is nothing to refuse and no `supports_` probe beside it.** The
9696    /// selector is a lane of a uniform block read by a branch every device
9697    /// already runs, so unlike the wireframe there is no second pipeline for a
9698    /// device to decline to build.
9699    pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9700        self.tonemap_curve = curve;
9701    }
9702
9703    /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9704    /// value the next frame will be drawn with.
9705    #[must_use]
9706    pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9707        self.tonemap_curve
9708    }
9709
9710    /// How large the internal render target is as a fraction of the extent
9711    /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9712    /// `MIN_RENDER_SCALE..=1.0`.
9713    ///
9714    /// **This is the largest performance knob this renderer has.** Every pass
9715    /// before the upscale costs what its extent costs, so a scale of `0.7` is
9716    /// roughly half the shading work of `1.0`; the UI is composited onto the
9717    /// target afterwards at native resolution, so text stays sharp while the 3D
9718    /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9719    /// 48-post-processing plan left behind_) is where that trade is written down.
9720    ///
9721    /// **`1.0` is not a special case with a fast path, it is the absence of the
9722    /// feature.** At full scale the internal extent *is* the caller's, the post
9723    /// chain writes the target directly, and no upscale pass is recorded — which
9724    /// is what makes a renderer nobody has called this on draw the frame it drew
9725    /// before the knob existed, bit for bit.
9726    ///
9727    /// **Above `1.0` is clamped away rather than supported.** Supersampling
9728    /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9729    /// *reconstruction*; running it as a minification filter would alias, which
9730    /// is the opposite of what a caller asking for it wants. A non-finite scale
9731    /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9732    /// the failure it produces is a zero-sized target somewhere downstream.
9733    ///
9734    /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9735    /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9736    /// recorded is drawn at the scale it was recorded with.
9737    pub fn set_render_scale(&mut self, scale: f32) {
9738        self.render_scale = if scale.is_finite() {
9739            scale.clamp(MIN_RENDER_SCALE, 1.0)
9740        } else {
9741            1.0
9742        };
9743    }
9744
9745    /// The render scale in force, after the clamp
9746    /// [`set_render_scale`](Self::set_render_scale) applied.
9747    ///
9748    /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9749    #[must_use]
9750    pub const fn render_scale(&self) -> f32 {
9751        self.render_scale
9752    }
9753
9754    /// The anisotropy the base-colour page is sampled with, in force from the
9755    /// next [`begin_frame`](Self::begin_frame).
9756    ///
9757    /// Topic 43's filtering rung, the player's half:
9758    /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9759    /// called this on samples with, and this is what a settings row moves it
9760    /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9761    /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9762    /// was not — the row can turn the filter off or push it to the device's
9763    /// ceiling, and nothing it asks reaches a `create_sampler` that would
9764    /// refuse it. A value that is not a number is the default, on
9765    /// [`set_render_scale`](Self::set_render_scale)'s terms.
9766    ///
9767    /// **A sampler is a resource a bind group holds by handle**, so a new
9768    /// anisotropy is a new sampler, and every group of the mesh layout has to
9769    /// be rebuilt to name it. That happens per frame slot, at the slot's own
9770    /// `begin_frame`, which is the moment the ring guarantees the slot's
9771    /// previous submission has retired — the guarantee every host write in
9772    /// that call already leans on — so a frame in flight goes on naming the
9773    /// sampler it was recorded with, and the replaced sampler is destroyed once
9774    /// no slot names it. This call creates the sampler and nothing else, and
9775    /// asking for the anisotropy already in force creates nothing.
9776    ///
9777    /// # Errors
9778    ///
9779    /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9780    /// stays in force.
9781    pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9782        let caps = device.caps();
9783        let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9784            caps.limits.max_sampler_anisotropy
9785        } else {
9786            1.0
9787        };
9788        let wanted = if anisotropy.is_finite() {
9789            anisotropy.clamp(1.0, ceiling)
9790        } else {
9791            Self::anisotropy_for(&caps)
9792        };
9793        // Bit-equal rather than within an epsilon: both sides came out of the
9794        // same clamp, and a row that lands on the value in force must not
9795        // rebuild every group for it.
9796        if wanted.to_bits() == self.anisotropy.to_bits() {
9797            return Ok(());
9798        }
9799        let sampler = Self::create_page_sampler(device, wanted)?;
9800        self.retired_pages
9801            .push(RetiredPage::Sampler(std::mem::replace(
9802                &mut self.base_color_sampler,
9803                sampler,
9804            )));
9805        self.anisotropy = wanted;
9806        Ok(())
9807    }
9808
9809    /// The anisotropy in force, after the clamp
9810    /// [`set_anisotropy`](Self::set_anisotropy) applied.
9811    ///
9812    /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9813    #[must_use]
9814    pub const fn anisotropy(&self) -> f32 {
9815        self.anisotropy
9816    }
9817
9818    /// The anisotropy the base-colour page's sampler is created with on a
9819    /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9820    /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9821    /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9822    /// not.
9823    ///
9824    /// **Granted, not supported.** The feature is optional at every open site
9825    /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9826    /// without asking refuses a sampler above one even on hardware that has
9827    /// it, which is the shape every backend's `create_sampler` documents. So
9828    /// the question is what this device was opened *with*, and a caller that
9829    /// wants the plan's default has to name the feature beside the others it
9830    /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9831    /// one, so a browser samples isotropically until `docs/backlog.md`'s
9832    /// ceiling decision is taken.
9833    #[must_use]
9834    pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9835        if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9836            DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9837        } else {
9838            1.0
9839        }
9840    }
9841
9842    /// The base-colour page's sampler at `anisotropy`, which the caller has
9843    /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9844    /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9845    ///
9846    /// **Trilinear over the whole chain, anisotropic where the device is** —
9847    /// topic 43's filtering rung: a minified surface
9848    /// reads the level its footprint matches instead of shimmering through
9849    /// level 0, a magnified one blends four texels instead of stepping between
9850    /// them, and a surface at a grazing angle keeps its detail along the long
9851    /// axis of its footprint rather than blurring to the short one. A second
9852    /// sampler object rather than sharing the tonemap's, so a capture names
9853    /// each for what it filters.
9854    ///
9855    /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9856    /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9857    /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9858    /// wrapping address mode makes the page tile across it rather than
9859    /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9860    /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9861    /// clamped read return the same nearest texel for it.
9862    fn create_page_sampler(
9863        device: &dyn Device,
9864        anisotropy: f32,
9865    ) -> Result<SamplerHandle, HalError> {
9866        device.create_sampler(&SamplerDesc {
9867            label: Some("material base colour"),
9868            mag_filter: FilterMode::Linear,
9869            min_filter: FilterMode::Linear,
9870            mip_filter: FilterMode::Linear,
9871            address_mode: [SamplerAddressMode::Repeat; 3],
9872            anisotropy,
9873            ..SamplerDesc::default()
9874        })
9875    }
9876
9877    /// The extent the next frame handed `target` is actually drawn at, at the
9878    /// render scale in force.
9879    ///
9880    /// Test-only: a frame takes its extents at the scale its `begin_frame`
9881    /// froze, through [`scaled_extent`](Self::scaled_extent), and this is the
9882    /// prediction a test checks that against.
9883    #[cfg(all(test, not(target_arch = "wasm32")))]
9884    fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9885        Self::scaled_extent(self.render_scale, target)
9886    }
9887
9888    /// The extent a frame handed `target` is drawn at under `scale` — what a
9889    /// frame's own extents are taken at, with
9890    /// [`frame_render_scale`](Self::frame_render_scale).
9891    ///
9892    /// Rounds rather than truncates, and floors at one texel in each dimension:
9893    /// a zero here would reach a transient image description, and an image of
9894    /// zero extent is a device error rather than a small frame. A caller who
9895    /// minimised the window already hands a zero extent through, and that path
9896    /// is unchanged — `max(1)` on a zero is one either way.
9897    fn scaled_extent(scale: f32, target: (u32, u32)) -> (u32, u32) {
9898        if scale >= 1.0 {
9899            return target;
9900        }
9901        let scale = f64::from(scale);
9902        (
9903            ((f64::from(target.0) * scale).round() as u32).max(1),
9904            ((f64::from(target.1) * scale).round() as u32).max(1),
9905        )
9906    }
9907
9908    /// The exposure in force, after the clamp
9909    /// [`set_exposure`](Self::set_exposure) applied.
9910    ///
9911    /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9912    /// caller wants is the number the frame is drawn with, not the one it asked
9913    /// for — which is also what makes a multiplicative step land on the end of
9914    /// the range rather than run past it.
9915    #[must_use]
9916    pub const fn exposure(&self) -> f32 {
9917        self.exposure
9918    }
9919
9920    /// Whether `device` can draw the wireframe view at all.
9921    ///
9922    /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9923    /// error, asked **before** anything is switched on — so an application can
9924    /// tell its user that this device has no wireframe rather than binding a key
9925    /// that fails, and can say so once at start-up instead of on every press.
9926    /// WebGPU has no line fill mode at all, so the browser is the case this
9927    /// exists for and not a hypothetical.
9928    ///
9929    /// An associated function rather than a method: it is a fact about the
9930    /// device, and a caller wants it before it has decided anything.
9931    #[must_use]
9932    pub fn supports_wireframe(device: &dyn Device) -> bool {
9933        device.caps().supports(Features::POLYGON_MODE_LINE)
9934    }
9935
9936    /// Asks every camera's cull to drop what is hidden or too small to see —
9937    /// topic 03 §3.3's occlusion cull and its
9938    /// small-feature test. See [`crate::occlusion_cull`].
9939    ///
9940    /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9941    /// guesses from the previous frame's depth, the second tests every rejected
9942    /// instance against this frame's, and only the second's rejections are
9943    /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9944    /// and is off unless a threshold is named.
9945    ///
9946    /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9947    /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9948    /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9949    /// alone, because a wireframe shows the edges a depth test would hide.
9950    pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9951        self.occlusion_culling = culling;
9952    }
9953
9954    /// Whether a skinned frame skips the dispatch of a region nothing this
9955    /// frame can draw — **on** by default.
9956    ///
9957    /// A region is skipped only when every object drawn out of it carries a
9958    /// [`SkinnedInstanceDesc::bounds`] box, and that box is outside the camera
9959    /// of every view the frame records and outside every shadow cull it
9960    /// redraws — a map the cadence holds draws nothing this frame — and every
9961    /// cull the probe updater draws through with shadows off.
9962    /// An object with no box keeps its region dispatched, and so does a region
9963    /// no object is drawn out of. The host asks the device cull's question with
9964    /// slack in the safe direction, so a skipped object is one no cull draws.
9965    ///
9966    /// **An object that comes back into view is at rest for one frame**: its
9967    /// region's halves hold the poses of the last frame that skinned it, so the
9968    /// frame it returns on writes its current half into both base lanes, as an
9969    /// object's first frame out of a region does. Its own travel is still
9970    /// reported. [`skinned_regions_skipped`](Self::skinned_regions_skipped)
9971    /// says how many regions a frame skipped.
9972    ///
9973    /// **Off is the opt-out for a caller that reads a region back**: a skipped
9974    /// region's halves keep an older pose, which nothing in this renderer reads,
9975    /// and which a readback of [`vertex_buffer`](Self::vertex_buffer) would. It
9976    /// is also the other half of a price. Both settings draw the same colour;
9977    /// the motion target differs on the frame a skipped object returns, which
9978    /// reads no deformation motion with the cull on and the motion its pose
9979    /// made since the frame before with it off.
9980    ///
9981    /// Read by the next call that records a frame's passes —
9982    /// [`add_skinned_passes`](Self::add_skinned_passes),
9983    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
9984    /// or [`add_passes_with_views`](Self::add_passes_with_views) — and moot for
9985    /// one handed no [`Skinning`].
9986    pub fn set_skinning_culls(&mut self, on: bool) {
9987        self.skinning_culls = on;
9988    }
9989
9990    /// Whether a point light's shadow cull tags each caster with the faces of
9991    /// its cube it reaches, so each face draws only those — **on** by default.
9992    ///
9993    /// Off is the cull this replaced: one test against the light's box, and
9994    /// every caster in it drawn into all six faces for the rasteriser to clip.
9995    /// The two write the same atlas, texel for texel — the six faces' pyramids
9996    /// tile the box, so a caster a face drops has no texel in that face's tile —
9997    /// and the switch exists so a test can hold them against each other and a
9998    /// price can be read off both.
9999    pub fn set_point_face_culls(&mut self, on: bool) {
10000        self.point_face_culls = on;
10001    }
10002
10003    /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
10004    /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
10005    /// on its way to the GPU, or stops doing so with [`None`] — the default,
10006    /// and the only value a frame outside a test runs under.
10007    ///
10008    /// Applied **after** the atlas cache has read the blocks, so the rewrite is
10009    /// invisible to the decision whether to redraw a map and visible only to the
10010    /// depth pass that draws it. That is what makes it a probe of the shaders:
10011    /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
10012    /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
10013    /// perturbed through here and holds the depth to the untampered frame's, bit
10014    /// for bit. It reaches the atlas's views alone — not the probe updater's
10015    /// shadows-off writes, which draw nothing into the atlas.
10016    pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
10017        self.shadow_view_tamper = tamper;
10018    }
10019
10020    /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
10021    /// for, before the console switches and the wireframe are applied.
10022    #[must_use]
10023    pub const fn occlusion_culling(&self) -> OcclusionCulling {
10024        self.occlusion_culling
10025    }
10026
10027    /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
10028    /// with the console switches applied, and nothing on a wireframe frame.
10029    #[must_use]
10030    pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
10031        if self.wireframe_on {
10032            return OcclusionCulling::OFF;
10033        }
10034        let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
10035        OcclusionCulling {
10036            occlusion: self.occlusion_culling.occlusion
10037                || crate::occlusion_cull::r_occlusion_cull.get_bool(),
10038            small_feature_pixels: self
10039                .occlusion_culling
10040                .small_feature_pixels
10041                .or((console_pixels > 0.0).then_some(console_pixels)),
10042        }
10043    }
10044
10045    /// Draws the scene's triangles as lines, or goes back to filling them.
10046    ///
10047    /// **Off by default.** Every sample and every golden image predates the
10048    /// view, so a renderer nobody has called this on records exactly the frame
10049    /// it always did.
10050    ///
10051    /// # What it is, and what it is not
10052    ///
10053    /// The **colour pass** alone changes fill mode. The depth prepass and the
10054    /// shadow cascades keep drawing filled triangles, because they are what the
10055    /// occlusion pair and the shadow lookups read and depth drawn as lines is
10056    /// depth with holes in it. So a wireframe frame is the same geometry, the
10057    /// same shading and the same lights, rasterised as edges: what was inside a
10058    /// triangle becomes the clear colour, and what was on its edge stays lit.
10059    ///
10060    /// # It is built on the first `true`
10061    ///
10062    /// The pipeline is compiled here rather than beside the filled one at
10063    /// [`with_scene`](Self::with_scene), and that is the trade this
10064    /// call makes: one pipeline compile on the first press — a hitch, in a view
10065    /// the user just asked for — against a second compile in the start-up of
10066    /// every sample, golden run and headless test that never asks for one. Later
10067    /// calls only flip the switch, and a `false` leaves the pipeline built, for
10068    /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
10069    /// the frames in flight may still be recording against is what
10070    /// [`destroy`](Self::destroy) — which already requires an idle device — is
10071    /// for.
10072    ///
10073    /// # Errors
10074    ///
10075    /// [`HalError::UnsupportedFeatures`] naming
10076    /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
10077    /// when `on` is `true` on a device that has not got it — ask
10078    /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
10079    /// than quietly filled: a caller who asked for a wireframe and got a solid
10080    /// frame back with no error has no way to tell that from a wireframe of a
10081    /// solid-looking model.
10082    ///
10083    /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
10084    /// when either happens**: the view stays as it was.
10085    pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
10086        if !on {
10087            self.wireframe_on = false;
10088            return Ok(());
10089        }
10090        if self.wireframe_pipeline.is_none() {
10091            if !Self::supports_wireframe(device) {
10092                return Err(HalError::UnsupportedFeatures {
10093                    missing: Features::POLYGON_MODE_LINE,
10094                });
10095            }
10096            let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
10097            let line = |cull| {
10098                modules.color_pipeline(
10099                    device,
10100                    self.mesh_pipeline_layout,
10101                    PolygonMode::Line,
10102                    cull,
10103                    "wireframe",
10104                )
10105            };
10106            let [back, none] = MeshModules::SIDES;
10107            // The twin only where the shaded pass has one — see
10108            // [`SidedPipelines`] — so a wireframe covers exactly the buckets
10109            // the shaded frame beside it draws.
10110            let single = line(back);
10111            let double = self.mesh_pipeline.double.map(|_| line(none)).transpose();
10112            modules.destroy(device);
10113            // **Both or neither.** A caller that got one twin back would draw a
10114            // frame missing every double-sided surface and nothing would say
10115            // so; released here rather than kept, because `destroy` is what
10116            // releases what this field holds and it holds nothing yet.
10117            let pipelines = match (single, double) {
10118                (Ok(single), Ok(double)) => SidedPipelines { single, double },
10119                (Ok(built), Err(error)) | (Err(error), Ok(Some(built))) => {
10120                    device.destroy_graphics_pipeline(built);
10121                    return Err(error);
10122                }
10123                (Err(error), Ok(None) | Err(_)) => return Err(error),
10124            };
10125            self.wireframe_pipeline = Some(pipelines);
10126        }
10127        self.wireframe_on = true;
10128        Ok(())
10129    }
10130
10131    /// Whether the colour pass draws lines instead of filled triangles.
10132    ///
10133    /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
10134    /// observable a test asking "is this frame a wireframe" wants: a renderer
10135    /// that built the pipeline and then switched it off answers `false`, because
10136    /// what it draws is what the question is about.
10137    #[must_use]
10138    pub const fn wireframe(&self) -> bool {
10139        self.wireframe_on
10140    }
10141
10142    /// Draws each surface's **world-space** normal instead of shading it, so a
10143    /// modeller can see whether the normals a document carries are sane.
10144    ///
10145    /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
10146    /// is a tool's view of a document, and every sample and every golden image
10147    /// predates it. It takes effect on the next
10148    /// [`begin_frame`](Self::begin_frame), which is what writes the block.
10149    ///
10150    /// # What the colours mean
10151    ///
10152    /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
10153    /// green, +Z blue, and a face whose winding was inverted reads the
10154    /// **complement** of the colour it should have. A missing or degenerate
10155    /// normal reads as whatever the vertex data actually holds rather than as the
10156    /// plausible shading a light would have given it, which is the point.
10157    ///
10158    /// # World space, not view space
10159    ///
10160    /// The two diagnose different things and this one is world space, so a face
10161    /// keeps its colour while the camera orbits: "is this face inverted" is then
10162    /// something a modeller *sees*, instead of inferring it from a picture that
10163    /// re-colours whenever they move. View-space normals answer the other
10164    /// question — is this normal smooth, is this seam split — by re-colouring on
10165    /// purpose, and they are not a thing this block could express anyway: it
10166    /// carries `view_proj` and no separate view matrix, so there is no rotation in
10167    /// the shader to take a normal into eye space with.
10168    ///
10169    /// # It builds nothing and adds no pass
10170    ///
10171    /// Unlike the wireframe, which needs a second pipeline and so a device that
10172    /// can build one: this is one lane of the frame's uniform block — see
10173    /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
10174    /// stage every device already runs. There is nothing to refuse and nothing to
10175    /// release, which is why it cannot fail and there is no `supports_` probe
10176    /// beside it.
10177    ///
10178    /// The tonemap still applies: at
10179    /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
10180    /// is the identity on `0..=1` and the encoded normal reaches the swapchain
10181    /// exactly, and at any other exposure the picture is scaled per channel — so
10182    /// which channel dominates a face never changes, but a caller reading exact
10183    /// values wants [`set_exposure`](Self::set_exposure) left alone.
10184    ///
10185    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
10186    pub const fn set_normals_view(&mut self, on: bool) {
10187        self.normals_view = on;
10188    }
10189
10190    /// Sets the exponential height fog the colour pass composites over every
10191    /// shaded surface.
10192    ///
10193    /// Topic 43 §4's cheapest large win: distance
10194    /// reads as distance, a valley fills while a hilltop stays clear, and it
10195    /// costs four numbers in a block every pipeline already binds.
10196    ///
10197    /// # It adds no pass and cannot fail
10198    ///
10199    /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
10200    /// rows of the frame's uniform block, read by arithmetic in the fragment
10201    /// stage every device already runs. There is nothing to build, so there is
10202    /// nothing to refuse and no `supports_` probe beside it.
10203    ///
10204    /// # Off is exactly off
10205    ///
10206    /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
10207    /// not an approximate one: the optical depth is zero, its transmittance is
10208    /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
10209    /// rather than as a `lerp`, which at `t == 1` would return
10210    /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
10211    /// the fog colour. So this feature moves no frame it is not switched on
10212    /// for.
10213    ///
10214    /// # What it does not fog
10215    ///
10216    /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
10217    /// which arrive unfogged onto an already-fogged surface — see
10218    /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
10219    /// the reflection composite is one pass later.
10220    pub const fn set_fog(&mut self, fog: Fog) {
10221        self.fog = fog;
10222    }
10223
10224    /// Lights the scene with a gradient sky, on top of whatever ambient and
10225    /// irradiance grid it already has.
10226    ///
10227    /// Topic 43 §8's rung. [`Sky`] is three
10228    /// radiances — zenith, horizon, ground — and what reaches a surface is that
10229    /// gradient projected onto the L1 basis the probe grid already uses, so a
10230    /// surface facing up receives the sky and one facing down the ground's
10231    /// bounce. Three colours, no extra pass.
10232    ///
10233    /// # It adds no pass and cannot fail
10234    ///
10235    /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
10236    /// frame's uniform block and three dot products in a fragment stage every
10237    /// device already runs. Nothing to build, so nothing to refuse and no
10238    /// `supports_` probe beside it.
10239    ///
10240    /// # Off is exactly off
10241    ///
10242    /// [`Sky::NONE`] is the default and a black gradient projects to every
10243    /// coefficient zero — each is a product with a zero factor — so the
10244    /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
10245    /// before this existed, bit for bit.
10246    ///
10247    /// # What it does not do
10248    ///
10249    /// **Draw anything.** The background is still the scene target's clear
10250    /// colour, and a scene lit by a sky it cannot see is what this rung leaves
10251    /// behind until the pass that draws the gradient lands. The environment
10252    /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
10253    /// a mirror under a sky still reflects whatever the probes hold.
10254    pub const fn set_sky(&mut self, sky: Sky) {
10255        self.sky = sky;
10256    }
10257
10258    /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
10259    /// gradient back.
10260    ///
10261    /// Topic 43 §8. A frame with an atmosphere takes
10262    /// it for all three of the things a sky is: the background the sky pass
10263    /// draws, the L1 ambient term `mesh.slang` adds, and the environment
10264    /// `ssr.slang` falls back to when a ray hits nothing. The
10265    /// [`Sky`] a caller may also have set is not read on those frames.
10266    ///
10267    /// # What it costs
10268    ///
10269    /// **A march on the host, not on the device.** The first
10270    /// [`begin_frame`](Self::begin_frame) after this is called marches
10271    /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
10272    /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
10273    /// paid where it is asked for. Every later move of the sun is marched
10274    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
10275    /// drawn, so no frame after the first pays the whole march;
10276    /// `refresh_sky_view` is where that is written down, including what a sun
10277    /// that moves *every* frame gets. A frame whose
10278    /// sun has not moved costs the comparison that finds nothing to do and
10279    /// nothing else: the LUT's two projections are cached beside it. The device
10280    /// pays four buffer loads and a blend, which is what the gradient pays.
10281    ///
10282    /// # Off is exactly off
10283    ///
10284    /// `None` is the default, and a renderer nobody calls this on writes the
10285    /// same block, adds the same passes and draws the same frame it did before
10286    /// this existed — `sky.slang`'s arm is
10287    /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
10288    ///
10289    /// # What it does not do
10290    ///
10291    /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
10292    /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
10293    /// pass already shades with, and pointing the two the same way is the
10294    /// caller's job.
10295    ///
10296    /// **Put the air in front of a surface.** That is the paper's third LUT and
10297    /// this engine's froxel column, and neither reads this.
10298    pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
10299        self.atmosphere = atmosphere;
10300    }
10301
10302    /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
10303    /// and this crate's `water` module for how.
10304    ///
10305    /// Replaces whatever was set before. Each body is meshed here, by
10306    /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
10307    /// slot as that slot next begins, so the call touches no device and a frame
10308    /// still in flight keeps the buffers it was submitted with. The first frame
10309    /// with a body builds each view's water passes — a hitch, cold, on that
10310    /// frame, which [`prepare_content`](Self::prepare_content) moves under a
10311    /// loading screen.
10312    ///
10313    /// # Off is exactly off
10314    ///
10315    /// An empty slice is the default, and a renderer with no bodies records no
10316    /// water pass at all: the frame it draws is the one it drew before this
10317    /// existed, bit for bit. Water is content, not a
10318    /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
10319    ///
10320    /// # Errors
10321    ///
10322    /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
10323    /// too few points, a non-finite coordinate, an outline that crosses itself,
10324    /// a negative coefficient — and then **nothing is replaced**: the bodies set
10325    /// before this call go on drawing.
10326    pub fn set_water(
10327        &mut self,
10328        bodies: &[crcbl_water::WaterBody],
10329    ) -> Result<(), crcbl_water::BodyError> {
10330        self.water.set(bodies)
10331    }
10332
10333    /// The bodies of water this renderer draws, as they were last set.
10334    #[must_use]
10335    pub fn water(&self) -> &[crcbl_water::WaterBody] {
10336        self.water.bodies()
10337    }
10338
10339    /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
10340    /// and G3, and this crate's `grass` module for how.
10341    ///
10342    /// Replaces whatever was set before. The field's ground, cover map, blade
10343    /// table and per-tile blocks are uploaded here, and the buffers a dispatch
10344    /// writes are created here; a field replaced while a frame is in flight
10345    /// leaves its resources alive until the ring has come round, so the call is
10346    /// safe at any point between frames. The field is drawn from the next
10347    /// [`begin_frame`](Self::begin_frame) on, which builds each view's grass
10348    /// passes the first time it sees one — a hitch, cold, on that frame, which
10349    /// [`prepare_content`](Self::prepare_content) moves under a loading screen.
10350    ///
10351    /// # Off is exactly off
10352    ///
10353    /// [`None`] is the default, and a renderer with no field records no grass
10354    /// pass at all: the frame it draws is the one it drew before this existed,
10355    /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
10356    /// [`set_water`](Self::set_water)'s terms.
10357    ///
10358    /// # Errors
10359    ///
10360    /// [`crate::grass::SetError::Field`] for a description the field itself
10361    /// refuses — no tiles, a zero texel scale, an empty blade table — and then
10362    /// **nothing is replaced**: the field set before this call goes on drawing.
10363    /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
10364    /// terms.
10365    pub fn set_grass(
10366        &mut self,
10367        device: &dyn Device,
10368        queue: QueueHandle,
10369        field: Option<&crate::grass::GrassField>,
10370    ) -> Result<(), crate::grass::SetError> {
10371        self.grass.set(device, queue, field)
10372    }
10373
10374    /// The field of grass this renderer draws, as it was last set.
10375    #[must_use]
10376    pub fn grass(&self) -> Option<&crate::grass::GrassField> {
10377        self.grass.field()
10378    }
10379
10380    /// Builds every view's water and grass passes for the bodies and the field
10381    /// set now, so the first frame that draws them does not.
10382    ///
10383    /// **Optional, and for a loading screen.** Without it the first frame with
10384    /// a body or a field builds them — a hitch, cold, on that frame. Called
10385    /// after [`set_water`](Self::set_water) and
10386    /// [`set_grass`](Self::set_grass) while a game is still loading, it pays
10387    /// the same compiles with `service` between them, on
10388    /// [`with_scene_serviced`](Self::with_scene_serviced)'s terms. A view that
10389    /// holds a pass already keeps it, and a view made after this call builds
10390    /// its own on its first frame with them.
10391    ///
10392    /// Between frames, on [`create_view`](Self::create_view)'s terms: it
10393    /// creates objects and records nothing.
10394    ///
10395    /// # Errors
10396    ///
10397    /// [`HalError`] from the device. The view that failed holds what it held
10398    /// before; the views before it keep what this call built them, which is
10399    /// what their next frame would have built.
10400    pub fn prepare_content(
10401        &mut self,
10402        device: &dyn Device,
10403        service: &mut dyn FnMut(),
10404    ) -> Result<(), HalError> {
10405        let water = !self.water.bodies().is_empty();
10406        let grass = self.grass.field().is_some();
10407        for view in std::iter::once(&mut self.primary).chain(self.views.iter_mut().flatten()) {
10408            view.build_content(device, water, grass, service)?;
10409        }
10410        Ok(())
10411    }
10412
10413    /// The two buffers the grass generation pass writes, or [`None`] for a
10414    /// renderer with no field.
10415    ///
10416    /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
10417    /// blade and to read each slot's instance count, on
10418    /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
10419    /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
10420    /// last frame that generated left there, which for a field nobody has drawn
10421    /// yet is undefined rather than empty.
10422    #[must_use]
10423    pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
10424        self.grass.buffers()
10425    }
10426
10427    /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
10428    /// as the GPU copy of the field samples them.
10429    ///
10430    /// [`None`] restores the calm placeholder: one texel of no deflection and
10431    /// one of zero intensity, which is what makes a field with no weather set
10432    /// stand still. A replaced pair waits for the ring exactly as a replaced
10433    /// field does, and like a field it is drawn from the next `begin_frame` on:
10434    /// the frame freezes its layers with its field.
10435    ///
10436    /// The new pair is uploaded in one batch that is **not waited for**, on
10437    /// the build's terms: `queue` must be the device's graphics queue, and
10438    /// the batch's staging is retired by a later `begin_frame`.
10439    ///
10440    /// # Errors
10441    ///
10442    /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
10443    /// texel of the grid it came with, a `queue` that is not the device's
10444    /// graphics queue, or a seam call that failed.
10445    pub fn set_wind_layers(
10446        &mut self,
10447        device: &dyn Device,
10448        queue: QueueHandle,
10449        layers: Option<&crate::grass::WindLayers>,
10450    ) -> Result<(), crate::grass::WindLayerError> {
10451        crcbl_frame::require_frame_queue(device, queue, "a forward renderer's wind layers")?;
10452        let pending = self.grass.set_wind_layers(device, queue, layers)?;
10453        self.uploads_in_flight.push(pending);
10454        Ok(())
10455    }
10456
10457    /// The wind's uniform block for the frames from here on —
10458    /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
10459    /// `f64` formula is narrowed to `f32`.
10460    ///
10461    /// Everything in it is camera-relative or already wrapped, so a caller
10462    /// writes it once per frame from the field's own state and never from a
10463    /// world-scale coordinate. The default is a base speed of zero, which is
10464    /// calm.
10465    pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
10466        self.wind = params;
10467    }
10468
10469    /// The wind block this renderer writes, as it was last set.
10470    #[must_use]
10471    pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
10472        self.wind
10473    }
10474
10475    /// The atmosphere this renderer draws, if it has one.
10476    #[must_use]
10477    pub const fn atmosphere(&self) -> Option<Atmosphere> {
10478        self.atmosphere
10479    }
10480
10481    /// Draws each cluster tinted by the DAG level it was decimated to, instead
10482    /// of shading it.
10483    ///
10484    /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
10485    /// several levels across its own surface is a statement a test can assert
10486    /// and nobody can see, and this is what makes it visible. The mesh path
10487    /// tints per cluster; the two indirect paths select one level per instance
10488    /// and have no per-cluster level at all, so they draw one flat grey — which
10489    /// is the comparison rather than a shortfall.
10490    ///
10491    /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
10492    /// of the frame's uniform block, read by a branch every device already runs.
10493    /// Nothing to build, nothing to refuse, nothing to release.
10494    ///
10495    /// **Wins over the normals view when both are on**, because the two share a
10496    /// lane and the fragment stage tests this one first.
10497    pub const fn set_lod_view(&mut self, on: bool) {
10498        self.lod_view = on;
10499    }
10500
10501    /// Whether the colour pass tints clusters by their DAG level.
10502    ///
10503    /// **What was asked for, not what is drawn.** The three debug views share
10504    /// one lane and resolve in one order, so a renderer with this and
10505    /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
10506    /// answers `true` here — the caller's setting is what a caller's toggle has
10507    /// to read back, and [`debug_view`](Self::debug_view) is what says which one
10508    /// the frame actually took.
10509    #[must_use]
10510    pub const fn lod_view(&self) -> bool {
10511        self.lod_view
10512    }
10513
10514    /// Shades each cluster by the **projected screen-space error** the LOD
10515    /// selection judged it on, instead of shading it.
10516    ///
10517    /// The LOD tint's sibling, and the other half of topic 25's
10518    /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
10519    /// looking at", and this answers "how close to the budget is this, and where
10520    /// is the selection about to switch". The number is the one
10521    /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
10522    /// cluster's *producing* group's error, projected from this frame's eye at
10523    /// this frame's pixels per unit.
10524    ///
10525    /// # What the colours mean
10526    ///
10527    /// A ramp that climbs in luminance from a cold floor to white, with a hue
10528    /// break at each of the two budgets: the hold budget where the hysteresis
10529    /// band starts, and the expand budget at the top, which is white. So the two
10530    /// budgets draw themselves as contour lines across the surface, and
10531    /// "brighter is closer to switching" reads even in a greyscale screenshot.
10532    /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
10533    /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
10534    /// to being readable as an ordering.
10535    ///
10536    /// A cluster nothing simplified — the original surface, at the bottom of the
10537    /// DAG — costs exactly zero and takes the ramp's floor.
10538    ///
10539    /// # Mesh path only, and that is the capability rather than a shortfall
10540    ///
10541    /// A per-cluster error exists only where selection is per cluster.
10542    /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
10543    /// choose one level per *instance*, so there is no per-cluster number for
10544    /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
10545    /// the LOD tint gets. Standing the two beside each other is the comparison.
10546    ///
10547    /// # It builds nothing and adds no pass
10548    ///
10549    /// One lane of the frame's uniform block, on
10550    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
10551    /// storage-buffer read in the mesh stage, which the mesh path's layout
10552    /// already carries. Nothing to build, nothing to refuse, nothing to release.
10553    ///
10554    /// **Wins over both the LOD tint and the normals view when several are on**;
10555    /// see [`debug_view`](Self::debug_view), which is that order stated once.
10556    ///
10557    /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
10558    /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
10559    pub const fn set_heatmap(&mut self, on: bool) {
10560        self.heatmap = on;
10561    }
10562
10563    /// Whether the colour pass shades clusters by their projected error.
10564    ///
10565    /// **What was asked for, not what is drawn**, on
10566    /// [`lod_view`](Self::lod_view)'s terms.
10567    #[must_use]
10568    pub const fn heatmap(&self) -> bool {
10569        self.heatmap
10570    }
10571
10572    /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10573    ///
10574    /// One is white and fully occluded is black — the buffer the forward pass
10575    /// multiplies its ambient term by, shown as itself. **This is how the AO
10576    /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10577    /// composited frame shows occlusion times albedo times ambient, and a
10578    /// difference in the first is not separable from a difference in the other
10579    /// two by looking at the result.
10580    ///
10581    /// # What it draws with occlusion switched off
10582    ///
10583    /// White, everywhere. A frame without
10584    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10585    /// a computed channel, and this view shows that image rather than pretending
10586    /// to a channel nothing computed — "no occlusion was computed" and "nothing
10587    /// occludes here" are the same value to the shading, and the view does not
10588    /// get to disagree with the shading about it.
10589    ///
10590    /// # It builds nothing and adds no pass
10591    ///
10592    /// One lane of the frame's uniform block, on
10593    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10594    /// tint and the heatmap it needs nothing from the geometry stage, so it
10595    /// draws on every [`GeometryPath`] rather than on
10596    /// the mesh-shader one alone.
10597    ///
10598    /// **Wins over every other view when several are on**; see
10599    /// [`debug_view`](Self::debug_view), which is that order stated once.
10600    pub const fn set_occlusion_view(&mut self, on: bool) {
10601        self.occlusion_view = on;
10602    }
10603
10604    /// Whether the colour pass draws the occlusion channel instead of shading.
10605    ///
10606    /// **What was asked for, not what is drawn**, on
10607    /// [`lod_view`](Self::lod_view)'s terms.
10608    #[must_use]
10609    pub const fn occlusion_view(&self) -> bool {
10610        self.occlusion_view
10611    }
10612
10613    /// Draws each fragment's motion vector instead of shading it.
10614    ///
10615    /// The two components are stretched by
10616    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10617    /// on grey, into red and green, with blue left at zero. A pixel at rest is
10618    /// grey in both channels to within one half-float step —
10619    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10620    /// not exactly — and a surface travelling right and down the screen
10621    /// brightens both.
10622    ///
10623    /// # It is the motion-vector target's only reader today
10624    ///
10625    /// The forward pass writes a motion vector into a third colour attachment on
10626    /// every frame — see [`crate::targets::motion`] — and no pass reads it
10627    /// yet; TAA (`docs/backlog.md`) is the first that will. This
10628    /// view is therefore what says the subtraction behind it is the right one,
10629    /// which is why it exists ahead of a consumer.
10630    ///
10631    /// # It builds nothing and adds no pass
10632    ///
10633    /// One lane of the frame's uniform block, on
10634    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10635    /// the occlusion view it needs nothing from the geometry stage that a
10636    /// shaded frame does not already produce — so it draws on every
10637    /// [`GeometryPath`].
10638    ///
10639    /// **Wins over every other view when several are on**; see
10640    /// [`debug_view`](Self::debug_view), which is that order stated once.
10641    pub const fn set_motion_view(&mut self, on: bool) {
10642        self.motion_view = on;
10643    }
10644
10645    /// Whether the colour pass draws the motion vector instead of shading.
10646    ///
10647    /// **What was asked for, not what is drawn**, on
10648    /// [`lod_view`](Self::lod_view)'s terms.
10649    #[must_use]
10650    pub const fn motion_view(&self) -> bool {
10651        self.motion_view
10652    }
10653
10654    /// Draws the occlusion channel's **bent direction** instead of shading.
10655    ///
10656    /// The three channels beside the visibility scalar, passed through as the
10657    /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10658    /// +Z blue, which is the mapping
10659    /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10660    /// normal. A fragment the occlusion pass had no direction for reads as the
10661    /// mid grey the zero sentinel encodes to.
10662    ///
10663    /// # What it is for
10664    ///
10665    /// The bent direction is what the ambient term is sampled *along*, and a
10666    /// composited frame cannot show it: ambient times albedo times a
10667    /// direction-dependent irradiance is one colour, and a direction that is
10668    /// subtly wrong looks like a lighting choice. This draws the direction
10669    /// alone, which is how a corner that leans the wrong way out of its own
10670    /// wall is a thing a reviewer sees rather than infers.
10671    ///
10672    /// # What it draws with occlusion switched off
10673    ///
10674    /// Mid grey, everywhere. A frame without
10675    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10676    /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10677    /// three channels, and this view shows that image rather than pretending to
10678    /// a direction nothing computed — which is the same answer the shading
10679    /// takes, since `mesh.slang` reads that sentinel as "use the shading
10680    /// normal".
10681    ///
10682    /// # It builds nothing and adds no pass
10683    ///
10684    /// One lane of the frame's uniform block, on
10685    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10686    /// the occlusion view it needs nothing from the geometry stage — so it
10687    /// draws on every [`GeometryPath`].
10688    ///
10689    /// **Wins over every other view when several are on**; see
10690    /// [`debug_view`](Self::debug_view), which is that order stated once.
10691    pub const fn set_bent_normal_view(&mut self, on: bool) {
10692        self.bent_normal_view = on;
10693    }
10694
10695    /// Whether the colour pass draws the bent direction instead of shading.
10696    ///
10697    /// **What was asked for, not what is drawn**, on
10698    /// [`lod_view`](Self::lod_view)'s terms.
10699    #[must_use]
10700    pub const fn bent_normal_view(&self) -> bool {
10701        self.bent_normal_view
10702    }
10703
10704    /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10705    /// shadow was sampled from.
10706    ///
10707    /// Topic 45's eighth decision made the cascade switch a
10708    /// band rather than a step, and this is the picture that band is judged in:
10709    /// each fragment's shading multiplied by
10710    /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10711    /// selected, and inside the band by the *blend* of the two — the same weight
10712    /// the visibility itself was mixed with. So the boundary reads as a
10713    /// gradient, and a seam where two cascades disagree shows up as a step in
10714    /// the gradient rather than as a ring somebody has to already suspect.
10715    ///
10716    /// # It keeps the shaded picture, which is why it loses to every other view
10717    ///
10718    /// Every other view replaces the frame; this one multiplies it, so the geometry
10719    /// stays readable underneath and the shadow the cascades produced is still
10720    /// in the picture being coloured. That is also what puts it last in
10721    /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10722    /// is no shading left for a tint to reach.
10723    ///
10724    /// # What it draws where no cascade covers a fragment
10725    ///
10726    /// Nothing at all —
10727    /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10728    /// A surface facing away from the sun and one past the last cascade's reach
10729    /// are both that, because neither was sampled through a cascade, and a
10730    /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10731    /// white everywhere for the same reason. Colouring those would be inventing
10732    /// a cascade for a pixel no map covers.
10733    ///
10734    /// # It builds nothing and adds no pass
10735    ///
10736    /// One lane of the frame's uniform block, on
10737    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10738    /// the occlusion view it needs nothing from the geometry stage — so it draws
10739    /// on every [`GeometryPath`].
10740    pub const fn set_cascade_view(&mut self, on: bool) {
10741        self.cascade_view = on;
10742    }
10743
10744    /// Whether the colour pass tints the picture by the sun's cascades.
10745    ///
10746    /// **What was asked for, not what is drawn**, on
10747    /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10748    /// case rather than the corner one: this view loses to every other one, so a
10749    /// renderer with any of them also on answers `true` here and draws that one.
10750    #[must_use]
10751    pub const fn cascade_view(&self) -> bool {
10752        self.cascade_view
10753    }
10754
10755    /// Draws the **shadow atlas itself** over the finished frame: the
10756    /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10757    /// each texel's stored depth as a grey and a border round every occupied
10758    /// slot.
10759    ///
10760    /// Sundial's atlas viewer, and the answer to a
10761    /// question no other view can be asked: which slot holds which map, and
10762    /// which slots hold nothing. A tile that was never rendered into, or
10763    /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10764    /// produces is plausible and every golden blessed from it passes. Here it is
10765    /// a rectangle that is visibly empty.
10766    ///
10767    /// # It is a pass, and it is the only debug view that is
10768    ///
10769    /// Every other view rides in one lane of the frame's uniform block and is a
10770    /// branch in `mesh.slang`, because every other view is a function of the
10771    /// fragment being shaded. The atlas is not: it is one image the whole frame
10772    /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10773    /// the frame instead — after the tonemap, in display space, for that
10774    /// module's reason — and the frame block is byte-identical either way.
10775    ///
10776    /// # Where it resolves, and what it costs when it is off
10777    ///
10778    /// Below every replacing view and above
10779    /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10780    /// [`debug_view`](Self::debug_view), which is that order stated once. A
10781    /// frame that resolved anything else records **no pass**, no pipeline bind
10782    /// and no block read, which is what makes the off position bit-identical on
10783    /// `crate::sky_pass`'s terms.
10784    pub const fn set_atlas_view(&mut self, on: bool) {
10785        self.atlas_view = on;
10786    }
10787
10788    /// Whether the frame draws the shadow atlas over the picture.
10789    ///
10790    /// **What was asked for, not what is drawn**, on
10791    /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10792    /// also on answers `true` here and draws that one.
10793    #[must_use]
10794    pub const fn atlas_view(&self) -> bool {
10795        self.atlas_view
10796    }
10797
10798    /// Pins the eye topic 25's selection is projected from, so the
10799    /// cut stops following the camera.
10800    ///
10801    /// [`None`] is the default and means "the camera's own eye", which is what
10802    /// every frame before this existed did. `Some(eye)` selects detail for a
10803    /// viewer standing at `eye` while the frame is still drawn, culled and lit
10804    /// from wherever the camera actually is.
10805    ///
10806    /// # What it is for
10807    ///
10808    /// Per-cluster LOD is only checkable from somewhere other than the point
10809    /// that chose it. Looked at from the selecting eye, a cut that is far too
10810    /// coarse and a cut that is exactly right produce the same silhouette —
10811    /// that is what a screen-space error budget *means* — so the one viewpoint
10812    /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10813    /// judged from. Pin the eye and fly away from it, and the boundaries between
10814    /// levels become geometry a reviewer can walk up to and look at edge-on.
10815    ///
10816    /// # Only the selection freezes
10817    ///
10818    /// The frame has three places a viewer position is read, and this moves
10819    /// exactly one of them:
10820    ///
10821    /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10822    ///   `DrawGenParams::camera_position` and is the only thing that decides the
10823    ///   cut. It writes the group hysteresis state that the mesh path's
10824    ///   amplification stage then descends, so freezing this one field freezes
10825    ///   the cut on the per-cluster path and the two indirect paths alike. This
10826    ///   is what moves.
10827    /// * **the frustum culls** — `cull.slang`'s instance test and
10828    ///   `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10829    ///   the frame's own view-projection and never read a camera position at
10830    ///   all. Unaffected, and it has to be: a frame culled against a frustum the
10831    ///   reviewer has flown out of would draw nothing.
10832    /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10833    ///   reads [`FrameUniforms::camera_position`] and asks which way a cluster
10834    ///   faces *relative to the viewer*. That question is about the eye the
10835    ///   picture is drawn from, not the eye it was selected for; frozen, a
10836    ///   reviewer who flew round to the other side of the face would have every
10837    ///   cluster now facing them rejected for facing away from a viewpoint
10838    ///   nobody is standing at. It stays live.
10839    ///
10840    /// The split is not new. `DrawGenParams::camera_position` and
10841    /// [`FrameUniforms::camera_position`] are already separate fields carrying
10842    /// different values on a shadow cascade — that one holds the sun while this
10843    /// one stays the camera, because detail is denominated in the camera's
10844    /// pixels and facing is asked about the light. This freezes the same seam
10845    /// from the other side, and needs no new binding, no new shader input and no
10846    /// shader change of any kind.
10847    ///
10848    /// # It freezes the cascades' selection too
10849    ///
10850    /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10851    /// cascade's draw generator, because a cascade selects detail for the
10852    /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10853    /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10854    /// is a difference in the picture that belongs to neither.
10855    ///
10856    /// # The heatmap reads the live eye, and says so
10857    ///
10858    /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10859    /// group's projected error, computed in the mesh stage from
10860    /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10861    /// frozen selection the two overlays answer different questions: the cut is
10862    /// the one chosen at the pinned eye, and the heat is what the error would be
10863    /// if it were chosen from here now. That is readable — flying towards the
10864    /// face brightens the clusters the frozen cut is not refining, which is the
10865    /// selection's sensitivity made visible — but it does mean the ramp's
10866    /// contours stop coinciding with the level boundaries while frozen.
10867    /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10868    /// unconditionally: a cluster's level is a property of the cut and of
10869    /// nothing else.
10870    ///
10871    /// Carrying the pinned eye into the mesh stage as well would need a second
10872    /// position in the frame block, which is a new shader input in every backend
10873    /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10874    ///
10875    /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10876    pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10877        self.frozen_selection_eye = eye;
10878    }
10879
10880    /// Where the selection is pinned, or [`None`] while it follows the camera.
10881    ///
10882    /// The read-back half of
10883    /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10884    /// debug panel says "frozen at" out of — "frozen" without the position is a
10885    /// row nobody can act on.
10886    #[must_use]
10887    pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10888        self.frozen_selection_eye
10889    }
10890
10891    /// Which of the debug views the next frame will actually draw.
10892    ///
10893    /// **The one place the precedence is decided**, and every other statement of
10894    /// it in this crate reads it back from here. The switches ride in one float
10895    /// lane of the frame block — see
10896    /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10897    /// — and the shaders test the outermost threshold first, so a sentinel for
10898    /// an outer view clears every threshold below it. Resolving here rather than
10899    /// letting each caller guess is what stops "which view is on" being answered
10900    /// differently by a menu row, a debug panel and the picture.
10901    #[must_use]
10902    pub const fn debug_view(&self) -> DebugView {
10903        if self.bent_normal_view {
10904            DebugView::BentNormal
10905        } else if self.motion_view {
10906            DebugView::Motion
10907        } else if self.occlusion_view {
10908            DebugView::AmbientOcclusion
10909        } else if self.heatmap {
10910            DebugView::Heatmap
10911        } else if self.lod_view {
10912            DebugView::LodTint
10913        } else if self.normals_view {
10914            DebugView::Normals
10915        } else if self.atlas_view {
10916            // **Below every view above it, and above the tint below.**
10917            //
10918            // Below, because every branch before this one is a question about
10919            // the *picture* — a cluster's error, a surface's normal, the
10920            // occlusion channel — and this one is not a picture of the scene at
10921            // all. A caller who left the atlas up and then asked for normals has
10922            // asked to look at the frame again, and the frame is what the branch
10923            // above draws; the atlas is one keystroke away and is not lost by
10924            // being deferred to.
10925            //
10926            // Above, because the cascade tint multiplies the shaded picture and
10927            // this replaces it: a tint on a frame the atlas overwrote would be a
10928            // tint on the atlas, which is a colour standing for nothing.
10929            DebugView::ShadowAtlas
10930        } else if self.cascade_view {
10931            // **Innermost, and the only view that sits below the others rather
10932            // than above them.** Every branch before this one draws something
10933            // *instead of* the shaded picture and returns before the shading; a
10934            // cascade tint is a multiply on that shading, so there is nothing
10935            // for it to modulate while one of them is showing and a caller with
10936            // both on has asked for the picture the outer one draws. The lane
10937            // says the same thing from the other end — the cascade sentinel is
10938            // negative, so it clears none of the shaders' thresholds — and
10939            // `crcbl_shaders`'
10940            // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10941            // what holds that half.
10942            DebugView::Cascades
10943        } else {
10944            DebugView::Shaded
10945        }
10946    }
10947
10948    /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10949    /// carries.
10950    const fn debug_view_lane(&self) -> f32 {
10951        match self.debug_view() {
10952            DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10953            DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10954            DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10955            DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10956            DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10957            DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10958            DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10959            // **The off sentinel, and it is not an omission.** This view is a
10960            // pass rather than a branch in `mesh.slang` — see
10961            // [`crate::atlas_view`] — so the colour pass draws exactly the
10962            // shaded picture it always drew and the pass afterwards replaces it.
10963            // A lane of its own would be a threshold no shader tests.
10964            DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10965        }
10966    }
10967
10968    /// Whether the colour pass draws world-space normals instead of shading.
10969    ///
10970    /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10971    /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10972    /// is about.
10973    #[must_use]
10974    pub const fn normals_view(&self) -> bool {
10975        self.normals_view
10976    }
10977
10978    /// The cull and draw-argument passes, and the buffers they produce.
10979    ///
10980    /// What a caller reads the culling statistics out of — topic 03 §3.6's
10981    /// delayed readback ring is [`DrawGen::visible_count`] — and what
10982    /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10983    /// arguments against the draws this pass used to record itself.
10984    #[must_use]
10985    pub const fn draws(&self) -> &DrawGen {
10986        &self.primary.draws
10987    }
10988
10989    /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
10990    /// and the exposure the reduce wrote out of them.
10991    ///
10992    /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
10993    /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
10994    /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
10995    /// there, so a frame drawn without
10996    /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
10997    /// hands back the frame before it rather than nothing.
10998    ///
10999    /// # Panics
11000    ///
11001    /// If `frame` is not a slot this renderer was built with.
11002    #[must_use]
11003    pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
11004        self.primary.auto_exposure.buffers(frame)
11005    }
11006
11007    /// `frame`'s froxel column: the buffers the froxel volume's
11008    /// three passes write, and the block they read.
11009    ///
11010    /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
11011    /// froxel against `crcbl_shaders::volumetric`, on
11012    /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
11013    ///
11014    /// # Panics
11015    ///
11016    /// If `frame` is not a slot this renderer was built with.
11017    #[must_use]
11018    pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
11019        self.primary.volumetric.buffers(frame)
11020    }
11021
11022    /// The three layers a caller supplies to the toggle resolution order — see
11023    /// [`crate::effects`].
11024    ///
11025    /// Read back rather than only written, so a caller changing one layer does
11026    /// not have to remember the other two: take this, edit the field it owns,
11027    /// hand it back to [`set_effect_request`](Self::set_effect_request).
11028    #[must_use]
11029    pub const fn effect_request(&self) -> EffectRequest {
11030        self.effect_request
11031    }
11032
11033    /// Replaces all three requested layers, and resolves them at the next
11034    /// [`begin_frame`](Self::begin_frame).
11035    ///
11036    /// **The frame in flight does not move.** `begin_frame` freezes what it
11037    /// resolved and [`add_passes`](Self::add_passes) records that, because the
11038    /// two halves of a frame have to agree about which culls were parametrised:
11039    /// `begin_frame` skips a shadow cull's parameter write when shadows are off
11040    /// and `add_passes` skips its dispatch, and a request landing between the two
11041    /// would dispatch a cull against numbers nothing zeroed.
11042    pub const fn set_effect_request(&mut self, request: EffectRequest) {
11043        self.effect_request = request;
11044    }
11045
11046    /// Replaces the **camera** layer with what `stack` asks for, and leaves the
11047    /// other three where they are.
11048    ///
11049    /// The file half of [`crate::stack`] reaching the renderer: a view that has
11050    /// a render stack writes it here, and the player's `[engine.video]` clamp,
11051    /// the antialiasing rung they picked and any programmatic override are
11052    /// untouched — which is the property that makes the four layers four rather
11053    /// than one. A caller that wants to move more than this layer builds an
11054    /// [`EffectRequest`] and uses
11055    /// [`set_effect_request`](Self::set_effect_request).
11056    ///
11057    /// **The frame in flight does not move**, on `set_effect_request`'s terms
11058    /// and for its reason: this writes the request and
11059    /// [`begin_frame`](Self::begin_frame) is what resolves it.
11060    pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
11061        self.effect_request.camera = stack.compile();
11062    }
11063
11064    /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
11065    ///
11066    /// The resolved set, not a layer: every effect in it has survived the
11067    /// camera's stack, the player's quality clamp, any programmatic override and
11068    /// the device — which is the one question a test asking "did this frame have
11069    /// shadows in it" wants answered.
11070    ///
11071    /// [`RenderEffects::all`] before the first frame, which is what a renderer
11072    /// nobody has changed would draw.
11073    #[must_use]
11074    pub const fn effects(&self) -> RenderEffects {
11075        self.frame_effects
11076    }
11077
11078    /// What a frame begun **now** would draw: the whole order applied to the
11079    /// current request.
11080    ///
11081    /// [`effects`](Self::effects)' question one frame earlier, and the one a
11082    /// caller reporting its own configuration wants — a debug panel built at
11083    /// startup has no frame behind it yet, and printing what the last one drew
11084    /// would print a default.
11085    ///
11086    /// **A debug view takes the antialiasing resolve off** — either tier of it
11087    /// — whatever the four layers said. Those views are readouts rather than
11088    /// pictures — a pixel's colour *is* the cluster's projected error or its
11089    /// DAG level, read back against a legend — and a filter that blends two
11090    /// clusters' shades invents a ramp position no cluster occupies.
11091    /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
11092    /// frame's distinct colours.
11093    #[must_use]
11094    pub fn resolved_effects(&self) -> RenderEffects {
11095        let resolved = self.effect_request.resolve(self.device_effects);
11096        if matches!(self.debug_view(), DebugView::Shaded) {
11097            resolved
11098        } else {
11099            // **Both tiers**, because the slot is what a readout cannot have
11100            // rather than one filter in particular.
11101            resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
11102        }
11103    }
11104
11105    /// Which tonemap operator the next frame runs:
11106    /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
11107    /// the clamp for a readout.
11108    ///
11109    /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
11110    /// operator instead of to the resolve.** A debug view's pixels *are* data —
11111    /// an encoded normal, an occlusion channel, a cascade's colour code — and a
11112    /// curve is a monotone remapping of every one of them. `apps/alcove`'s
11113    /// `--bent-view` reads a normal back and compares it against the geometry's
11114    /// own, which under ACES is 49 code values out; the clamp is the identity on
11115    /// `0..=1`, so it is the operator that leaves a readout readable. A caller
11116    /// that wants a curved readout has none, deliberately: there is no reading
11117    /// it would make easier.
11118    #[must_use]
11119    pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
11120        if matches!(self.debug_view(), DebugView::Shaded) {
11121            self.tonemap_curve
11122        } else {
11123            tonemap::TonemapCurve::Clamp
11124        }
11125    }
11126
11127    /// Which effects this **device** permits, which is the fourth layer and
11128    /// clamps last.
11129    ///
11130    /// Every one of them today — see [`ForwardRenderer::device_effects`], which
11131    /// is where that is argued per effect rather than asserted.
11132    #[must_use]
11133    pub const fn device_effects(&self) -> RenderEffects {
11134        self.device_effects
11135    }
11136
11137    /// Which [`GeometryPath`] this renderer was **built for** — not what the
11138    /// device reports, but what it actually built.
11139    ///
11140    /// The device may prefer a path below its capability ceiling when a higher
11141    /// one uses emulation. This reports the preference actually built, rather
11142    /// than the ceiling: [`GeometryPath::MeshShader`] here means
11143    /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
11144    /// cluster buffers, and created **no** raster pipeline for the pass to fall
11145    /// back to. So a frame this renderer drew came out of a mesh stage, and a
11146    /// silent degradation is not a state it has — which is the claim a golden
11147    /// image on its own could never make, because a fall-through draws the same
11148    /// picture.
11149    #[must_use]
11150    pub const fn geometry_path(&self) -> GeometryPath {
11151        match self.emit {
11152            EmitTail::Mesh => GeometryPath::MeshShader,
11153            EmitTail::Count => GeometryPath::IndirectCount,
11154            EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
11155        }
11156    }
11157
11158    /// Whether this renderer **built** §3.5's per-cluster cull — an
11159    /// amplification stage in front of the mesh stage, rejecting a surviving
11160    /// instance's back-facing and off-screen clusters.
11161    ///
11162    /// `false` on the two indirect tails, which draw index ranges and have no
11163    /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
11164    /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
11165    /// that device draws every cluster of every surviving instance and the
11166    /// picture is the same one.
11167    ///
11168    /// The instance cull runs on every path either way, and is unaffected by
11169    /// this.
11170    ///
11171    /// It is asked of the renderer rather than of the device for
11172    /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
11173    /// built, so `true` means
11174    /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
11175    /// cluster word is a number the frame produced rather than the zero the
11176    /// clearing pass left.
11177    #[must_use]
11178    pub const fn culls_clusters(&self) -> bool {
11179        self.culls_clusters
11180    }
11181
11182    /// Whether this renderer can choose **which level** of a
11183    /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
11184    /// [`ForwardRenderer::add_instance`] may be given one at all.
11185    ///
11186    /// Topic 25's selection happens in the amplification stage where
11187    /// there is one, and in the cull pass where the tail is indirect and a level
11188    /// is an ordinary index range. **One device shape has neither**: a mesh stage
11189    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
11190    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
11191    /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
11192    /// of the bucket — and a DAG's bucket is every level end to end, so the frame
11193    /// is several overlapping copies of one surface. That is a real and supported
11194    /// device state rather than a degradation, so this reports it instead of
11195    /// refusing to build.
11196    ///
11197    /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
11198    /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
11199    /// which is why this is asked only before placing a DAG.
11200    ///
11201    /// Asked of the renderer rather than of the device for
11202    /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
11203    ///
11204    /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
11205    #[must_use]
11206    pub const fn selects_levels(&self) -> bool {
11207        !self.emit.is_mesh() || self.culls_clusters
11208    }
11209
11210    /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
11211    /// rotated to, which is the slot every per-frame buffer is indexed by.
11212    #[must_use]
11213    pub const fn frame(&self) -> usize {
11214        self.frame
11215    }
11216
11217    /// What the last [`add_passes`](Self::add_passes) recorded, and what it
11218    /// cannot know.
11219    ///
11220    /// Zero draws until a frame has been built: this reports what was recorded,
11221    /// not what a frame would record.
11222    ///
11223    /// # The triangles are [`None`] here, on every geometry path
11224    ///
11225    /// Every draw this renderer records except the full-screen passes' and the
11226    /// debug draw layer's is **indirect**:
11227    /// the instance count and the index range live in the argument buffer
11228    /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
11229    /// about what it covered. That is true of
11230    /// [`GeometryPath::MeshShader`] and of
11231    /// both indirect tails alike — the three differ in which call is recorded,
11232    /// not in who decides the counts — so
11233    /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
11234    /// is [`None`] whatever the device supports. Nothing counts a triangle on
11235    /// the GPU either, and a cluster count times a nominal triangles-per-cluster
11236    /// would read as authoritative and be neither.
11237    ///
11238    /// # The instances drawn come back off the GPU, a few frames late
11239    ///
11240    /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
11241    /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
11242    /// plus the frame's direct draws — the ones here whose instance the CPU
11243    /// knows about, and the ones that are also in
11244    /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
11245    /// comparable: the same quantity submitted and kept.
11246    ///
11247    /// **The camera's cull alone.** The shadow culls test other frustums and
11248    /// their survivors are counted into buffers of their own; adding them here
11249    /// would give a "drawn" larger than "submitted" on any frame with a shadow
11250    /// in it.
11251    ///
11252    /// It is [`None`] — the row says `indirect` — for the first few frames of a
11253    /// renderer's life, while the ring has not come round, and for good on a
11254    /// device that would not give out a readback.
11255    /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
11256    /// the number is about whenever there is one.
11257    ///
11258    /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
11259    /// is known and is the plan's "submitted" half: the live instances
11260    /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
11261    /// frame's direct draws — every full-screen pass's triangle and the debug
11262    /// draw layer's line list.
11263    #[must_use]
11264    pub fn counters(&self) -> FrameCounters {
11265        if self.recorded_draws == 0 {
11266            return FrameCounters::default();
11267        }
11268        let stats = self.cull_stats();
11269        let direct = self.direct_draws();
11270        FrameCounters {
11271            draws: self.recorded_draws,
11272            instances: self.instances.len() as u64 + direct,
11273            // Each direct draw is submitted and drawn, and none of them is in
11274            // the cull's count — they are draws of one instance, added on both
11275            // sides so the two halves of the row measure the same thing. Off the
11276            // frame that *was* recorded rather than off a constant, so a frame
11277            // with an effect switched off does not count a triangle it never
11278            // submitted.
11279            // Less what the occlusion cull's second phase rejected, which were
11280            // survivors of the frustum and were not drawn.
11281            drawn: stats
11282                .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
11283            triangles: None,
11284            // The survivors alone: the panel row is "clusters drawn", and the
11285            // frustum and cone rejection counts beside them are a different
11286            // question — `CullStats::clusters` carries all three for a caller
11287            // that wants the split, which `apps/quarry`'s own panel row is.
11288            clusters: stats
11289                .and_then(|stats| stats.clusters)
11290                .map(|cull| cull.survivors),
11291            cull_frame: stats.map(|stats| stats.frame),
11292        }
11293    }
11294
11295    /// The draws this renderer records **directly** — the ones whose instance
11296    /// the CPU knows about, as opposed to the indirect calls whose counts live
11297    /// in a buffer a shader wrote.
11298    ///
11299    /// Every full-screen pass's over-sized triangle, plus the debug draw
11300    /// layer's line list on a frame that has one. One instance each, which is
11301    /// why [`counters`](Self::counters) adds this to both halves of its
11302    /// submitted/drawn pair.
11303    fn direct_draws(&self) -> u64 {
11304        self.recorded_fullscreen * FULLSCREEN_DRAWS
11305            + self.recorded_debug_draw
11306            + self.recorded_tile_clears
11307            + self.recorded_water_draws
11308    }
11309
11310    /// What the camera's cull kept, on the frame the ring has reached.
11311    ///
11312    /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
11313    /// round — see [`crate::cull_stats`] for the latency and for what makes it
11314    /// free of any wait. [`counters`](Self::counters) is where this reaches the
11315    /// panel; it is exposed on its own because the frame number and the cluster
11316    /// word are both things a test asserts about directly.
11317    #[must_use]
11318    pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
11319        self.cull_stats.as_ref().and_then(CullStatsRing::latest)
11320    }
11321
11322    /// Describes the imported swapchain image the frame ends in.
11323    ///
11324    /// A helper rather than something every caller writes, because getting
11325    /// `initial`/`final_state` wrong is exactly the hand-written barrier this
11326    /// slice removed: an acquired image's contents are undefined, and the
11327    /// compositor may only be handed one in [`ResourceState::Present`].
11328    #[must_use]
11329    pub fn present_target(
11330        image: crcbl_hal::ImageHandle,
11331        view: ImageViewHandle,
11332        format: Format,
11333        extent: (u32, u32),
11334    ) -> ImportedImage {
11335        ImportedImage {
11336            image,
11337            view,
11338            format,
11339            extent,
11340            initial: ResourceState::Undefined,
11341            // The acquire's semaphore, not a barrier, is what orders this frame
11342            // after the last use of the image — which is what makes `Undefined`
11343            // honest here and what makes it uncheckable. See `InitialClaim`.
11344            claim: InitialClaim::Acquired,
11345            final_state: ResourceState::Present,
11346        }
11347    }
11348
11349    /// Releases everything, in dependency order. The device must be idle.
11350    ///
11351    /// The start-up uploads are waited for first all the same: a renderer
11352    /// destroyed before any frame has a build batch nothing else has waited
11353    /// for, and its copies write the placeholders and fills released below.
11354    pub fn destroy(mut self, device: &dyn Device) {
11355        self.wait_for_uploads(device, "destroy");
11356        if let Some(stats) = self.cull_stats {
11357            stats.destroy(device);
11358        }
11359        // The cameras first: their groups name the scene's buffers, pages and
11360        // atlas below, and they own nothing the scene's groups name.
11361        for view in self.views.into_iter().flatten() {
11362            view.destroy(device);
11363        }
11364        self.primary.destroy(device);
11365        // After every view, whose grass and water groups name these buffers.
11366        self.grass.destroy(device);
11367        self.water.destroy(device);
11368        device.destroy_sampler(self.sampler);
11369        device.destroy_graphics_pipeline(self.tonemap_pipeline);
11370        device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
11371        device.destroy_bind_group_layout(self.tonemap_layout);
11372
11373        let depth_and_rsm = [
11374            Some(self.shadow_pipeline),
11375            self.depth_masked_pipeline,
11376            self.rsm_pipeline,
11377        ];
11378        for pipeline in depth_and_rsm
11379            .into_iter()
11380            .flatten()
11381            .flat_map(SidedPipelines::handles)
11382        {
11383            device.destroy_graphics_pipeline(pipeline);
11384        }
11385        device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
11386        for groups in self.shadow_groups {
11387            for group in groups {
11388                device.destroy_bind_group(group);
11389            }
11390        }
11391        for buffers in self.shadow_uniforms {
11392            for buffer in buffers {
11393                device.destroy_buffer(buffer);
11394            }
11395        }
11396        for buffers in self.shadow_selection {
11397            for buffer in buffers {
11398                device.destroy_buffer(buffer);
11399            }
11400        }
11401        for draws in self.shadow_draws {
11402            draws.destroy(device);
11403        }
11404        // After every generator: the cameras' above and the shadow culls'.
11405        DrawGenPipelines::release(self.draw_pipelines, device);
11406        device.destroy_sampler(self.shadow_sampler);
11407        device.destroy_image_view(self.shadow_atlas_view);
11408        device.destroy_image(self.shadow_atlas);
11409        device.destroy_image_view(self.shadow_placeholder_view);
11410        device.destroy_image(self.shadow_placeholder);
11411
11412        if let Some(grid) = self.ground_grid {
11413            grid.destroy(device);
11414        }
11415        // Nothing to release on a renderer nobody drew a segment through — see
11416        // [`crate::debug_draw`], whose pipeline is built on first use.
11417        self.debug_draw.destroy(device);
11418        if let Some(atlas_viewer) = self.atlas_viewer {
11419            atlas_viewer.destroy(device);
11420        }
11421        self.ambient_occlusion_placeholder.destroy(device);
11422        self.contact_shadow_placeholder.destroy(device);
11423        self.probe_visibility_placeholder.destroy(device);
11424        if let Some(captured) = self.probe_visibility {
11425            captured.destroy(device);
11426        }
11427        self.specular_dfg.destroy(device);
11428        self.ltc_table.destroy(device);
11429        self.normal_page.destroy(device);
11430        self.mro_page.destroy(device);
11431        self.emissive_page.destroy(device);
11432
11433        // The wireframe pair is released here and nowhere else —
11434        // `set_wireframe(.., false)` deliberately is not, because this call is
11435        // the one that requires an idle device.
11436        let colour = [Some(self.mesh_pipeline), self.wireframe_pipeline];
11437        for pipeline in colour
11438            .into_iter()
11439            .flatten()
11440            .flat_map(SidedPipelines::handles)
11441        {
11442            device.destroy_graphics_pipeline(pipeline);
11443        }
11444        device.destroy_pipeline_layout(self.mesh_pipeline_layout);
11445        device.destroy_bind_group_layout(self.mesh_layout);
11446        self.base_color_page.destroy(device);
11447        device.destroy_sampler(self.base_color_sampler);
11448        for retired in self.retired_pages {
11449            retired.destroy(device);
11450        }
11451        device.destroy_buffer(self.draw_constants);
11452        if let Some(clusters) = self.clusters {
11453            clusters.destroy(device);
11454        }
11455        // Before the probe table, because its bind groups name that table's
11456        // rows — the same ordering the light grid is under above.
11457        if let Some(gather) = self.probe_gather {
11458            gather.destroy(device);
11459        }
11460        self.probes.destroy(device);
11461        self.materials.destroy(device);
11462        self.instances.destroy(device);
11463        self.pool.destroy(device);
11464    }
11465}
11466
11467/// What the shadow pass a frame recorded would leave the image holding, held
11468/// until the frame after can say whether its body ran.
11469///
11470/// Topic 45's static-caching rung, per group: recording a pass
11471/// is not drawing one, so nothing here is believed until
11472/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
11473/// out of the graph.
11474#[derive(Clone, Debug)]
11475struct ShadowCommit {
11476    /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
11477    id: u64,
11478    /// `[group]`: what the group's entry of
11479    /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
11480    /// redraws, and [`None`] for the groups it holds.
11481    groups: Vec<Option<(u64, Vec3, f32)>>,
11482    /// The layout the pass draws under, where it clears the whole attachment —
11483    /// and [`None`] where it loads, because a loading pass leaves every tile it
11484    /// does not redraw exactly as it found it.
11485    layout: Option<Vec<shadow::TileRect>>,
11486}
11487
11488/// The shader modules a mesh pipeline is built from, with its entry points
11489/// already resolved.
11490///
11491/// **A type rather than a run of locals in `build`** because there are now two
11492/// callers: `build`, which makes the colour pipeline and its depth-only twin,
11493/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
11494/// in [`PolygonMode::Line`] long after `build` released its modules. The
11495/// alternative was a second copy of a descriptor that names two modules, their
11496/// entry points, the colour targets and a depth state — the pair that drifts.
11497///
11498/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
11499/// in the same function. A module is not needed once the pipeline exists.
11500struct MeshModules {
11501    /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
11502    /// fragment stage on both.
11503    mesh: ShaderModuleHandle,
11504    /// `vertexMain`, unused on the mesh-shader path.
11505    vertex: &'static str,
11506    /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
11507    /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
11508    /// vertex pool and no attribute region at all. Unused on the mesh-shader
11509    /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
11510    depth_vertex: &'static str,
11511    /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
11512    /// builds the tile clear from: three corners off `SV_VertexID` and no input
11513    /// at all, so it resets one tile of the atlas without reading a vertex.
11514    ///
11515    /// **The same stage on every path**, unlike the two above: a device with a
11516    /// mesh stage still has a vertex stage, and a clear that produced no
11517    /// geometry is a primitive, not a cluster.
11518    depth_clear_vertex: &'static str,
11519    fragment: &'static str,
11520    /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
11521    /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
11522    /// all.
11523    ///
11524    /// **The same stage on both paths**, unlike the two vertex entry points
11525    /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
11526    /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
11527    /// mesh stage writes on the mesh one. So the cutout is one comparison in one
11528    /// place rather than one per geometry path.
11529    depth_masked_fragment: &'static str,
11530    /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
11531    /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
11532    /// describing the surface rather than shading it.
11533    ///
11534    /// **The reason the shaded stage above is looked up by name.** A module with
11535    /// two fragment entry points has no unambiguous one, which is what `entry`
11536    /// answers `None` for.
11537    rsm_fragment: &'static str,
11538    /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
11539    cluster: Option<ClusterStages>,
11540}
11541
11542/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
11543/// and the stages taken out of it.
11544struct ClusterStages {
11545    /// The module the mesh stage is built from, and the one the task stage is,
11546    /// which are **two modules rather than one**.
11547    ///
11548    /// `mesh_cluster.slang` compiles to a combined module carrying every entry
11549    /// point and to one module per stage, and these are the per-stage ones. A
11550    /// module holding a task entry point and its mesh partner carries two
11551    /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
11552    /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
11553    /// which draws cluster 0 of instance slot 0 of every bucket and nothing
11554    /// else. See `crcbl_shaders::EntryPoint`.
11555    mesh_module: ShaderModuleHandle,
11556    /// The task stage's own module, on the same terms. [`None`] exactly when
11557    /// [`task`](Self::task) is.
11558    task_module: Option<ShaderModuleHandle>,
11559    /// Which of the module's two mesh entry points this path builds — the
11560    /// amplified one where the device has a task stage to feed it.
11561    mesh: &'static str,
11562    /// §3.5's per-cluster cull, where the device has the stage to run it in.
11563    /// [`None`] is not a degradation: `meshMain` draws the same picture out of
11564    /// the same clusters, having rejected none of them, which is what a device
11565    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
11566    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
11567    task: Option<&'static str>,
11568}
11569
11570impl MeshModules {
11571    /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
11572    /// writes the shaded colour, then topic 47's
11573    /// reflectivity channel, then topic 43 §9's motion
11574    /// vector — and both pipeline shapes name that same entry point, so each
11575    /// target is one more element of this array and not a second pipeline, a
11576    /// second entry point or a new interpolant. The refusal the AO section
11577    /// records was about the depth prepass, which has no fragment stage and no
11578    /// colour target at all; it does not reach this array.
11579    ///
11580    /// Element order is `SV_Target` order, and each format is the one the
11581    /// matching `TransientImageDesc` creates: a pipeline built for a format the
11582    /// attachment is not in is a validation error on WebGPU and a silent
11583    /// reinterpretation elsewhere.
11584    const COLOR_TARGETS: [ColorTargetState; 3] = [
11585        ColorTargetState::opaque(Format::Rgba16Float),
11586        ColorTargetState::opaque(Format::Rgba8Unorm),
11587        ColorTargetState::opaque(MOTION_FORMAT),
11588    ];
11589
11590    /// **Three targets again, and a different three.** `mesh.slang`'s
11591    /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11592    /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11593    /// which is what the irradiance probes' gather needs of a
11594    /// texel and nothing more.
11595    ///
11596    /// Element order is `SV_Target` order and each format is the one the
11597    /// matching description in [`crate::rsm`] creates: a pipeline built for a
11598    /// format the attachment is not in is a validation error on WebGPU and a
11599    /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11600    /// in that module is the other half of the pair.
11601    const RSM_TARGETS: [ColorTargetState; 3] = [
11602        ColorTargetState::opaque(Format::Rgba16Float),
11603        ColorTargetState::opaque(Format::Rgba8Unorm),
11604        ColorTargetState::opaque(Format::Rgba32Float),
11605    ];
11606
11607    /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11608    /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11609    /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11610    ///
11611    /// Taken from the crate that owns the shader source rather than written
11612    /// out, as
11613    /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11614    /// requires: only Metal reads this field, so a literal that disagreed with
11615    /// the shader would launch the wrong number of threads on one backend and
11616    /// nowhere else.
11617    const MESH_WORKGROUP_SIZE: [u32; 3] =
11618        [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11619
11620    /// Invocations per task workgroup: `taskMain` is
11621    /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11622    /// pair of its chunk. Taken from the crate that owns the shader, on
11623    /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11624    const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11625
11626    /// The two cull modes a sided shape is built with, in
11627    /// [`SidedPipelines`]' order: [`single`](SidedPipelines::single) culls
11628    /// back faces, [`double`](SidedPipelines::double) culls nothing.
11629    const SIDES: [CullMode; 2] = [CullMode::Back, CullMode::None];
11630
11631    /// Loads whichever modules `emit` needs and resolves their entry points.
11632    ///
11633    /// # Errors
11634    ///
11635    /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11636    /// entry point, and [`HalError`] from either module. A failure after the
11637    /// first module was created releases it rather than leaking it.
11638    fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11639        // Entry points resolved before the module exists: a manifest that
11640        // disagreed with the SPIR-V would otherwise fail inside the descriptor
11641        // literal, with the module already created and nothing holding it.
11642        //
11643        // **The vertex stage is named rather than looked up by stage**, for
11644        // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11645        // this module has two vertex entry points, and a stage lookup answers
11646        // `None` for two matches. Which of the two a pipeline names is the whole
11647        // of what the split-stream vertex pool bought.
11648        let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11649        let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11650        let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11651        // **Named rather than looked up by stage, on the vertex entry points'
11652        // terms exactly.** Since the irradiance probes' updater
11653        // landed, this module has *two* fragment entry points — the shaded one
11654        // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11655        // a stage lookup here refuses the build outright with "exposes no
11656        // unambiguous Fragment entry point".
11657        let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11658        let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11659        let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11660        // **Named rather than looked up by stage**, because the module has two
11661        // mesh entry points and a stage lookup would refuse an ambiguous one —
11662        // see `named_entry`. Which of the two this names is the whole of the
11663        // amplification decision.
11664        let cluster_stages = emit
11665            .is_mesh()
11666            .then(|| {
11667                let mesh = named_entry(
11668                    &MESH_CLUSTER,
11669                    if culls_clusters {
11670                        "amplifiedMeshMain"
11671                    } else {
11672                        "meshMain"
11673                    },
11674                    Stage::Mesh,
11675                )?;
11676                let task = culls_clusters
11677                    .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11678                    .transpose()?;
11679                Ok::<_, HalError>((mesh, task))
11680            })
11681            .transpose()?;
11682
11683        let mesh = device.create_shader_module(&ShaderModuleDesc {
11684            label: Some("mesh.slang"),
11685            spirv: MESH.spirv(),
11686            wgsl: MESH.wgsl(),
11687            msl: MESH.msl(),
11688            // **Both containers, and still one module.** A DXIL container holds
11689            // exactly one entry point, so this is a list where its three
11690            // neighbours are single artifacts; the backend that consumes it
11691            // picks the container named by the stage it is building. Nothing
11692            // here branches on a backend, and the three that ignore DXIL see
11693            // the same module they always did.
11694            dxil: &MESH.dxil_containers(),
11695        })?;
11696        let cluster = match cluster_stages {
11697            None => None,
11698            Some((cluster_mesh, task)) => {
11699                // **The mesh stage's module is `mesh_cluster.slang`; the
11700                // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11701                // module per stage, so the shading — Lambert, the GGX lobe, the
11702                // material row, the page sample — is the same code both paths
11703                // run rather than a copy that agrees today.
11704                // `mesh_cluster.slang`'s header carries the argument, and its
11705                // `VertexOutput` is what the two agree through.
11706                // **One module per stage, each carrying that stage's own
11707                // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11708                // artifact per source whatever the stage, and a DXIL container
11709                // is already per entry point, so both are handed over unchanged
11710                // and the backends that read them see what they always did.
11711                let stage_module = |entry_point: &str| {
11712                    device.create_shader_module(&ShaderModuleDesc {
11713                        label: Some("mesh_cluster.slang"),
11714                        // The combined module where this stage has none of its
11715                        // own, which is every stage of every other shader.
11716                        spirv: MESH_CLUSTER
11717                            .spirv_for(entry_point)
11718                            .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11719                        // `None`, and it is the whole reason this is a second
11720                        // file: WGSL cannot express a mesh stage at all.
11721                        wgsl: MESH_CLUSTER.wgsl(),
11722                        msl: MESH_CLUSTER.msl(),
11723                        dxil: &MESH_CLUSTER.dxil_containers(),
11724                    })
11725                };
11726                let mesh_module = match stage_module(cluster_mesh) {
11727                    Ok(module) => module,
11728                    Err(error) => {
11729                        device.destroy_shader_module(mesh);
11730                        return Err(error);
11731                    }
11732                };
11733                let task_module = match task.map(stage_module).transpose() {
11734                    Ok(module) => module,
11735                    Err(error) => {
11736                        device.destroy_shader_module(mesh);
11737                        device.destroy_shader_module(mesh_module);
11738                        return Err(error);
11739                    }
11740                };
11741                Some(ClusterStages {
11742                    mesh_module,
11743                    task_module,
11744                    mesh: cluster_mesh,
11745                    task,
11746                })
11747            }
11748        };
11749        Ok(Self {
11750            mesh,
11751            vertex,
11752            depth_vertex,
11753            depth_clear_vertex,
11754            fragment,
11755            depth_masked_fragment,
11756            rsm_fragment,
11757            cluster,
11758        })
11759    }
11760
11761    /// The rasteriser state every pipeline shape here shares, because the only
11762    /// things that differ between them are which stage produces the geometry and
11763    /// which side of it survives.
11764    ///
11765    /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11766    /// been on from the first mesh. The cube's winding is asserted by
11767    /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11768    /// failure rather than a debugging session — and a mesh drawn without
11769    /// culling would let a winding mistake survive into P7's geometry pool. The
11770    /// mesh stage emits its corner triples in the index buffer's own order, so
11771    /// the winding it produces is the same one.
11772    ///
11773    /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11774    /// §3.9.6's first half — and the twin built with it is the only way a back
11775    /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11776    fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11777        PrimitiveState {
11778            cull_mode,
11779            polygon_mode,
11780            ..PrimitiveState::default()
11781        }
11782    }
11783
11784    /// What a pipeline built with `cull` adds to its label, so a capture and
11785    /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11786    /// the [`SidedPipelines::single`] it was built beside.
11787    ///
11788    /// Empty for the culling modes, because those pipelines' labels are the ones
11789    /// every existing capture and every test lookup already names.
11790    fn side_label(cull: CullMode) -> &'static str {
11791        match cull {
11792            CullMode::None => " double-sided",
11793            CullMode::Front | CullMode::Back => "",
11794        }
11795    }
11796
11797    /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11798    /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11799    /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11800    /// matrix that agrees with **both** comes from [`crate::camera`].
11801    fn depth_stencil() -> Option<DepthStencilState> {
11802        Some(DepthStencilState::default())
11803    }
11804
11805    /// The colour pass's depth state, which is not the same shape as
11806    /// [`MeshModules::depth_stencil`] because the depth prepass has already
11807    /// drawn this geometry.
11808    ///
11809    /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11810    /// paid for once per pixel.** The prepass runs the same draws through
11811    /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11812    /// stage — so the depth already in the attachment is this pass's own answer,
11813    /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11814    /// that would have won the write. What it removes is the clustered-forward
11815    /// shading of every fragment a nearer one goes on to cover.
11816    ///
11817    /// **Lines: the writing default, because a wireframe is not the geometry the
11818    /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11819    /// and an edge pixel's depth is interpolated along the line rather than
11820    /// across the face, so testing it for equality against a filled prepass
11821    /// rejects most of the wireframe. That frame keeps the pass shape this pass
11822    /// had before the prepass existed — see the colour pass's depth attachment,
11823    /// which branches on the same condition.
11824    fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11825        match polygon_mode {
11826            PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11827            _ => Self::depth_stencil(),
11828        }
11829    }
11830
11831    /// The colour pass's pipeline, filled or wireframe, culling back faces or
11832    /// nothing.
11833    ///
11834    /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11835    /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11836    /// names the side, so a capture tells all four apart.
11837    fn color_pipeline(
11838        &self,
11839        device: &dyn Device,
11840        layout: PipelineLayoutHandle,
11841        polygon_mode: PolygonMode,
11842        cull: CullMode,
11843        label: &str,
11844    ) -> Result<GraphicsPipelineHandle, HalError> {
11845        let primitive = Self::primitive(polygon_mode, cull);
11846        let depth_stencil = Self::color_depth_stencil(polygon_mode);
11847        let side = Self::side_label(cull);
11848        let fragment = Some(ShaderEntry {
11849            module: self.mesh,
11850            entry_point: self.fragment,
11851        });
11852        match self.cluster.as_ref() {
11853            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11854                label: Some(&format!("{label}{side} mesh cluster")),
11855                layout,
11856                task: cluster
11857                    .task
11858                    .zip(cluster.task_module)
11859                    .map(|(entry_point, module)| ShaderEntry {
11860                        module,
11861                        entry_point,
11862                    }),
11863                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11864                mesh: ShaderEntry {
11865                    module: cluster.mesh_module,
11866                    entry_point: cluster.mesh,
11867                },
11868                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11869                fragment,
11870                primitive,
11871                depth_stencil,
11872                multisample: MultisampleState::default(),
11873                color_targets: &Self::COLOR_TARGETS,
11874            }),
11875            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11876                label: Some(&format!("{label}{side} mesh")),
11877                layout,
11878                vertex: ShaderEntry {
11879                    module: self.mesh,
11880                    entry_point: self.vertex,
11881                },
11882                fragment,
11883                primitive,
11884                depth_stencil,
11885                multisample: MultisampleState::default(),
11886                color_targets: &Self::COLOR_TARGETS,
11887            }),
11888        }
11889    }
11890
11891    /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11892    /// same modules and the same layout: no fragment stage, no colour target,
11893    /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11894    ///
11895    /// **The transform is identical and the fetch is not, which is the point.**
11896    /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11897    /// depth pass plus whatever emit tail the device selected", and what makes
11898    /// that work is a frame block whose `view_proj` is the cascade's matrix
11899    /// rather than a second transform path: a cascade that disagreed with the
11900    /// colour pass about where a vertex is would produce shadows that do not
11901    /// line up with their casters, which is indistinguishable from a bias
11902    /// problem. `depthVertexMain` is that same clip position written the same
11903    /// way, with everything the discarded varyings needed — the attribute
11904    /// region and the previous frame's position — left unread;
11905    /// topic 43 §2 split the pool for exactly this
11906    /// pass, and this is where it is spent.
11907    ///
11908    /// **The mesh-shader path still runs the colour pipeline's geometry
11909    /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11910    /// mesh stage is a second entry point in that module and its own rung; a
11911    /// device with a mesh stage goes on reading whole vertices here.
11912    ///
11913    /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11914    /// prepass, and depth drawn as lines is depth with holes in it — which the
11915    /// occlusion pair would read as geometry that is not there.
11916    fn depth_pipeline(
11917        &self,
11918        device: &dyn Device,
11919        layout: PipelineLayoutHandle,
11920        cull: CullMode,
11921    ) -> Result<GraphicsPipelineHandle, HalError> {
11922        let primitive = Self::primitive(PolygonMode::Fill, cull);
11923        let side = Self::side_label(cull);
11924        match self.cluster.as_ref() {
11925            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11926                label: Some(&format!("shadow cascade{side} mesh cluster")),
11927                layout,
11928                task: cluster
11929                    .task
11930                    .zip(cluster.task_module)
11931                    .map(|(entry_point, module)| ShaderEntry {
11932                        module,
11933                        entry_point,
11934                    }),
11935                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11936                mesh: ShaderEntry {
11937                    module: cluster.mesh_module,
11938                    entry_point: cluster.mesh,
11939                },
11940                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11941                fragment: None,
11942                primitive,
11943                depth_stencil: Self::depth_stencil(),
11944                multisample: MultisampleState::default(),
11945                color_targets: &[],
11946            }),
11947            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11948                label: Some(&format!("shadow cascade{side}")),
11949                layout,
11950                vertex: ShaderEntry {
11951                    module: self.mesh,
11952                    entry_point: self.depth_vertex,
11953                },
11954                fragment: None,
11955                primitive,
11956                depth_stencil: Self::depth_stencil(),
11957                multisample: MultisampleState::default(),
11958                color_targets: &[],
11959            }),
11960        }
11961    }
11962
11963    /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11964    /// state and the same absent colour targets, `depthMaskedFragmentMain`
11965    /// behind the geometry stage, and [`MeshModules::vertex`] in
11966    /// [`MeshModules::depth_vertex`]'s place.
11967    ///
11968    /// Topic 43 §3's cutout, in the two passes that
11969    /// write depth without shading. A masked instance drawn through the pipeline
11970    /// above writes its full silhouette: it occludes itself through the hole it
11971    /// can see through, and it casts the shadow of a leaf that has none.
11972    ///
11973    /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11974    /// needs the UV, which lives in the attribute region `depthVertexMain`
11975    /// exists not to read — so this stage reads a whole vertex, exactly as
11976    /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11977    /// What that buys is one fragment entry point for both geometry paths: the
11978    /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11979    /// compared in one place rather than once per path.
11980    ///
11981    /// **Which draws are recorded with it is the bucket's own material mode**,
11982    /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11983    /// masks nothing has no bucket in this partition, records through the
11984    /// pipeline above with no fragment stage anywhere, and is never compiled
11985    /// this pipeline at all; a scene that masks one mesh pays the fragment stage
11986    /// for that mesh's draws alone.
11987    fn depth_masked_pipeline(
11988        &self,
11989        device: &dyn Device,
11990        layout: PipelineLayoutHandle,
11991        cull: CullMode,
11992    ) -> Result<GraphicsPipelineHandle, HalError> {
11993        let primitive = Self::primitive(PolygonMode::Fill, cull);
11994        let side = Self::side_label(cull);
11995        let fragment = Some(ShaderEntry {
11996            module: self.mesh,
11997            entry_point: self.depth_masked_fragment,
11998        });
11999        match self.cluster.as_ref() {
12000            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
12001                label: Some(&format!("shadow cascade masked{side} mesh cluster")),
12002                layout,
12003                task: cluster
12004                    .task
12005                    .zip(cluster.task_module)
12006                    .map(|(entry_point, module)| ShaderEntry {
12007                        module,
12008                        entry_point,
12009                    }),
12010                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
12011                mesh: ShaderEntry {
12012                    module: cluster.mesh_module,
12013                    entry_point: cluster.mesh,
12014                },
12015                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
12016                fragment,
12017                primitive,
12018                depth_stencil: Self::depth_stencil(),
12019                multisample: MultisampleState::default(),
12020                color_targets: &[],
12021            }),
12022            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
12023                label: Some(&format!("shadow cascade masked{side}")),
12024                layout,
12025                vertex: ShaderEntry {
12026                    module: self.mesh,
12027                    entry_point: self.vertex,
12028                },
12029                fragment,
12030                primitive,
12031                depth_stencil: Self::depth_stencil(),
12032                multisample: MultisampleState::default(),
12033                color_targets: &[],
12034            }),
12035        }
12036    }
12037
12038    /// The reflective shadow map's pipeline: the colour pipeline's geometry
12039    /// stage, `rsmFragmentMain` in the shaded stage's place, and
12040    /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
12041    ///
12042    /// The irradiance probes' updater draws the sun's near
12043    /// cascade a second time through this — see [`crate::rsm`], which owns the
12044    /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
12045    /// pass out of that cascade's own bind group and its own already-generated
12046    /// draws.
12047    ///
12048    /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
12049    /// the cascade this rides beside: a fragment stage that writes a world
12050    /// position, a normal and an albedo needs the varyings `depthVertexMain`
12051    /// exists to leave unread. On the mesh path it is the very same geometry
12052    /// stage the colour pass runs, for the reason `depth_pipeline` gives.
12053    ///
12054    /// **Its own depth, written**, rather than the colour pass's read-only
12055    /// equality test: nothing has drawn this view's depth before it, and the
12056    /// pass is what decides which surface a texel of the map holds.
12057    fn rsm_pipeline(
12058        &self,
12059        device: &dyn Device,
12060        layout: PipelineLayoutHandle,
12061        cull: CullMode,
12062    ) -> Result<GraphicsPipelineHandle, HalError> {
12063        let primitive = Self::primitive(PolygonMode::Fill, cull);
12064        let side = Self::side_label(cull);
12065        let fragment = Some(ShaderEntry {
12066            module: self.mesh,
12067            entry_point: self.rsm_fragment,
12068        });
12069        match self.cluster.as_ref() {
12070            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
12071                label: Some(&format!("rsm{side} mesh cluster")),
12072                layout,
12073                task: cluster
12074                    .task
12075                    .zip(cluster.task_module)
12076                    .map(|(entry_point, module)| ShaderEntry {
12077                        module,
12078                        entry_point,
12079                    }),
12080                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
12081                mesh: ShaderEntry {
12082                    module: cluster.mesh_module,
12083                    entry_point: cluster.mesh,
12084                },
12085                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
12086                fragment,
12087                primitive,
12088                depth_stencil: Self::depth_stencil(),
12089                multisample: MultisampleState::default(),
12090                color_targets: &Self::RSM_TARGETS,
12091            }),
12092            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
12093                label: Some(&format!("rsm{side}")),
12094                layout,
12095                vertex: ShaderEntry {
12096                    module: self.mesh,
12097                    entry_point: self.vertex,
12098                },
12099                fragment,
12100                primitive,
12101                depth_stencil: Self::depth_stencil(),
12102                multisample: MultisampleState::default(),
12103                color_targets: &Self::RSM_TARGETS,
12104            }),
12105        }
12106    }
12107
12108    /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
12109    /// some tiles and redraw others.
12110    ///
12111    /// Topic 45's cadence rung needs a tile cleared on its own,
12112    /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
12113    /// whole image, and the region-bounded forms are not portable. This is the
12114    /// portable statement of the same thing: `mesh.slang`'s
12115    /// `depthClearVertexMain` covers the viewport the shadow pass has already
12116    /// set over the tile, and the depth state below writes
12117    /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
12118    ///
12119    /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
12120    /// clear rather than a draw: the tile holds the previous frame's depths, and
12121    /// under the engine's [`CompareOp::Greater`] a clear value of zero would
12122    /// fail against every one of them and leave the tile exactly as it was.
12123    ///
12124    /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
12125    /// is generated from `SV_VertexID` rather than wound by an artist, so a
12126    /// culling rule meant for scene geometry would decide whether the clear
12127    /// happens at all.
12128    ///
12129    /// **A vertex pipeline on every path**, including the mesh-shader one: a
12130    /// device with a mesh stage still has a vertex stage, and the clear has no
12131    /// clusters to descend.
12132    fn depth_clear_pipeline(
12133        &self,
12134        device: &dyn Device,
12135        layout: PipelineLayoutHandle,
12136    ) -> Result<GraphicsPipelineHandle, HalError> {
12137        device.create_graphics_pipeline(&GraphicsPipelineDesc {
12138            label: Some("shadow tile clear"),
12139            // The mesh layout, so binding this pipeline in the middle of the
12140            // shadow pass does not disturb the bind group the draws around it
12141            // are recorded with. The stage reads none of it.
12142            layout,
12143            vertex: ShaderEntry {
12144                module: self.mesh,
12145                entry_point: self.depth_clear_vertex,
12146            },
12147            fragment: None,
12148            primitive: PrimitiveState {
12149                cull_mode: CullMode::None,
12150                polygon_mode: PolygonMode::Fill,
12151                ..PrimitiveState::default()
12152            },
12153            depth_stencil: Some(DepthStencilState {
12154                depth_compare: CompareOp::Always,
12155                ..DepthStencilState::default()
12156            }),
12157            multisample: MultisampleState::default(),
12158            color_targets: &[],
12159        })
12160    }
12161
12162    /// Releases every module. The pipelines built from them stay valid.
12163    fn destroy(self, device: &dyn Device) {
12164        device.destroy_shader_module(self.mesh);
12165        if let Some(cluster) = self.cluster {
12166            device.destroy_shader_module(cluster.mesh_module);
12167            if let Some(task) = cluster.task_module {
12168                device.destroy_shader_module(task);
12169            }
12170        }
12171    }
12172}
12173
12174/// The entry point for `stage`, or an error naming the shader.
12175///
12176/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
12177/// expose both stages — but the alternative is an `expect` in engine code.
12178fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
12179    shader.entry_point(stage).ok_or_else(|| {
12180        HalError::ShaderCompilation(format!(
12181            "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
12182             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
12183            shader.name()
12184        ))
12185    })
12186}
12187
12188/// The entry point called `name`, checked to be `stage`'s.
12189///
12190/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
12191/// points — one behind the amplification stage and one without it — and a
12192/// lookup by stage answers `None` for two matches rather than picking one, for
12193/// the good reason that picking one would draw the wrong geometry.
12194///
12195/// The stage is still checked rather than taken on trust: a name that resolved
12196/// to the wrong stage would be a pipeline built with an amplification stage in
12197/// its mesh slot, and the failure would arrive as a driver error rather than as
12198/// this sentence.
12199pub(crate) fn named_entry(
12200    shader: &crcbl_shaders::Shader,
12201    name: &'static str,
12202    stage: Stage,
12203) -> Result<&'static str, HalError> {
12204    let found = shader
12205        .entry_points()
12206        .iter()
12207        .find(|entry| entry.name() == name && entry.stage() == stage);
12208    found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
12209        HalError::ShaderCompilation(format!(
12210            "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
12211             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
12212            shader.name()
12213        ))
12214    })
12215}
12216
12217// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
12218#[cfg(all(test, not(target_arch = "wasm32")))]
12219mod tests {
12220    mod draw_pipelines;
12221    mod frame_extents;
12222    mod instance_upload;
12223    mod lazy_content;
12224    mod lazy_passes;
12225    mod load_service;
12226    mod mesh_variants;
12227    mod page_reload;
12228    mod partial_builds;
12229    mod shadow_reach;
12230    mod skin_cull;
12231    mod upload_waits;
12232
12233    use super::*;
12234    use crate::effects::{Antialiasing, EffectOverride};
12235    use crate::scene::{
12236        DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
12237        DEMO_UNTINTED,
12238    };
12239    use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
12240    use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
12241
12242    #[test]
12243    fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
12244        let recorder = Recorder::new();
12245        let mut limits = crcbl_hal::Limits::desktop();
12246        limits.max_color_attachments = 2;
12247        let features = Features::COMPUTE | Features::MESH_SHADER;
12248        let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
12249            .with_recorder(recorder.clone());
12250        let device = instance
12251            .create_device(&DeviceDesc {
12252                label: None,
12253                adapter: crcbl_hal::AdapterId(0),
12254                required_features: features,
12255                optional_features: Features::empty(),
12256                compatible_surface: None,
12257            })
12258            .unwrap();
12259        let queue = device.queue(QueueKind::Graphics).unwrap();
12260        let before = recorder.total_live_objects();
12261        let error = ForwardRenderer::with_scene_on_path(
12262            device.as_ref(),
12263            queue,
12264            Format::Rgba8UnormSrgb,
12265            &scene::demo(),
12266            GeometryPath::MeshShader,
12267        )
12268        .expect_err("three-target color pipelines must be refused");
12269        assert!(
12270            error
12271                .to_string()
12272                .contains("3 colour targets exceeds max_color_attachments 2"),
12273            "{error}"
12274        );
12275        assert!(
12276            recorder.events().iter().any(|event| matches!(
12277                event,
12278                Event::Created {
12279                    kind: ObjectKind::GraphicsPipeline,
12280                    ..
12281                }
12282            )),
12283            "the refusal must exercise cleanup of successful pipelines"
12284        );
12285        assert_eq!(
12286            recorder.total_live_objects(),
12287            before,
12288            "partial pipeline construction leaked resources"
12289        );
12290        recorder.assert_valid();
12291    }
12292
12293    #[test]
12294    fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
12295        let recorder = Recorder::new();
12296        let instance = NullInstance::gpu_driven()
12297            .with_geometry_preference(GeometryPath::IndirectPerBatch)
12298            .with_recorder(recorder.clone());
12299        let device = instance
12300            .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
12301            .unwrap();
12302        let queue = device.queue(QueueKind::Graphics).unwrap();
12303        assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
12304        let default = ForwardRenderer::with_scene(
12305            device.as_ref(),
12306            queue,
12307            Format::Rgba8UnormSrgb,
12308            &scene::demo(),
12309        )
12310        .unwrap();
12311        assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
12312        default.destroy(device.as_ref());
12313        recorder.clear();
12314        let mut exact = ForwardRenderer::with_scene_on_path(
12315            device.as_ref(),
12316            queue,
12317            Format::Rgba8UnormSrgb,
12318            &scene::demo(),
12319            GeometryPath::IndirectCount,
12320        )
12321        .unwrap();
12322        assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
12323        let rendered = frame(device.as_ref(), &mut exact, queue);
12324        let commands = commands_in_pass(&recorder, "forward");
12325        assert!(commands.iter().any(|command| matches!(
12326            command,
12327            crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
12328        )));
12329        assert!(
12330            !commands
12331                .iter()
12332                .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
12333        );
12334        rendered.finish(device.as_ref(), exact);
12335    }
12336
12337    /// **A device with a draw index draws a range of buckets per call, and one
12338    /// without it a call per bucket** — both indirect tails, read off the
12339    /// recorded stream of a whole frame.
12340    ///
12341    /// The ranged frame records one bind and one multi-draw per range in the
12342    /// depth prepass, whose draws together cover every bucket exactly once,
12343    /// and no count draw anywhere; the per-bucket frame records the call per
12344    /// bucket it always did. Both frames' counters are what they recorded.
12345    #[test]
12346    fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
12347        use crcbl_hal::null::Command;
12348
12349        let _seam = ssao_split_switch();
12350        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
12351            for ranged in [false, true] {
12352                let optional = if ranged {
12353                    Features::GPU_DRIVEN | Features::DRAW_INDEX
12354                } else {
12355                    DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
12356                };
12357                let (recorder, device, queue) = open_with(optional);
12358                let mut renderer = ForwardRenderer::with_scene_on_path(
12359                    device.as_ref(),
12360                    queue,
12361                    Format::Rgba8UnormSrgb,
12362                    &scene::demo(),
12363                    path,
12364                )
12365                .expect("the demo scene builds");
12366                assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
12367                let buckets = renderer.bucket_modes.len();
12368                assert!(buckets > 1, "one bucket packs into one call either way");
12369                let rendered = frame(device.as_ref(), &mut renderer, queue);
12370
12371                let commands = commands_in_pass(&recorder, "depth-prepass");
12372                let binds = commands
12373                    .iter()
12374                    .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
12375                    .count();
12376                let draws: Vec<u32> = commands
12377                    .iter()
12378                    .filter_map(|command| match command {
12379                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
12380                        Command::DrawIndexedIndirectCount(draw) => {
12381                            assert!(!ranged, "{path:?}: a ranged pass records no count draw");
12382                            assert_eq!(draw.max_draw_count, 1);
12383                            Some(1)
12384                        }
12385                        _ => None,
12386                    })
12387                    .collect();
12388                assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
12389                assert_eq!(
12390                    draws.iter().sum::<u32>() as usize,
12391                    buckets,
12392                    "{path:?}: every bucket drawn once"
12393                );
12394                if ranged {
12395                    assert!(
12396                        draws.len() < buckets,
12397                        "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
12398                    );
12399                } else {
12400                    assert_eq!(draws, vec![1; buckets], "{path:?}");
12401                }
12402                assert!(
12403                    !recorder
12404                        .commands()
12405                        .iter()
12406                        .any(|command| ranged
12407                            && matches!(command, Command::DrawIndexedIndirectCount(_))),
12408                    "{path:?}: a ranged frame records no count draw"
12409                );
12410                assert_eq!(
12411                    renderer.counters().draws,
12412                    recorded_draws(&recorder) as u64,
12413                    "{path:?}, ranged {ranged}"
12414                );
12415                rendered.finish(device.as_ref(), renderer);
12416                recorder.assert_valid();
12417            }
12418        }
12419    }
12420
12421    /// **A scene holding every material mode draws each pipeline's buckets as
12422    /// one ranged call**, because the bucket table is numbered mode-major: the
12423    /// depth prepass records one call per depth pipeline and the colour pass
12424    /// one per sided pipeline, on both indirect tails.
12425    ///
12426    /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
12427    /// and every partition's runs are one bucket long, so the prepass would
12428    /// record a call per bucket — the counts below are what tell the two
12429    /// numberings apart, and the sums are what say every bucket still drew.
12430    #[test]
12431    fn every_mode_partition_of_a_ranged_frame_is_one_call() {
12432        use crcbl_hal::null::Command;
12433        use crcbl_shaders::mesh::GpuMaterial;
12434
12435        let scene = {
12436            let mut scene = crate::scene::demo();
12437            while scene.materials.len() < 4 {
12438                scene.materials.push(GpuMaterial::UNTINTED);
12439            }
12440            let rows = [
12441                0,
12442                GpuMaterial::ALPHA_MODE_MASK,
12443                GpuMaterial::DOUBLE_SIDED,
12444                GpuMaterial::MODE_MASK,
12445            ];
12446            for (row, flags) in scene.materials.iter_mut().zip(rows) {
12447                row.flags = flags;
12448            }
12449            scene
12450        };
12451        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
12452            let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
12453            let mut renderer = ForwardRenderer::with_scene_on_path(
12454                device.as_ref(),
12455                queue,
12456                Format::Rgba8UnormSrgb,
12457                &scene,
12458                path,
12459            )
12460            .expect("the four-mode demo builds");
12461            assert!(renderer.range_limit.is_some(), "{path:?}");
12462            let buckets = renderer.bucket_modes.len();
12463            let per_mode = buckets / DEPTH_MODES.len();
12464            assert_eq!(
12465                per_mode * DEPTH_MODES.len(),
12466                buckets,
12467                "{path:?}: four twins"
12468            );
12469            assert!(
12470                per_mode > 1,
12471                "{path:?}: a mode of one bucket is one call under either numbering"
12472            );
12473            let rendered = frame(device.as_ref(), &mut renderer, queue);
12474
12475            let draws = |label: &str| -> Vec<u32> {
12476                commands_in_pass(&recorder, label)
12477                    .iter()
12478                    .filter_map(|command| match command {
12479                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
12480                        _ => None,
12481                    })
12482                    .collect()
12483            };
12484            let prepass = draws("depth-prepass");
12485            assert_eq!(
12486                prepass,
12487                vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
12488                "{path:?}: one call per depth pipeline, each a whole mode"
12489            );
12490            let forward = draws("forward");
12491            assert_eq!(
12492                forward,
12493                vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
12494                "{path:?}: one call per sided pipeline, each two adjacent modes"
12495            );
12496            rendered.finish(device.as_ref(), renderer);
12497            recorder.assert_valid();
12498        }
12499    }
12500
12501    /// **Behind an amplification stage the mesh tail records one flat call per
12502    /// partition, and without one a range of buckets per call on a device with
12503    /// a draw index and a call per bucket without** — read off the recorded
12504    /// stream of a whole frame.
12505    ///
12506    /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
12507    /// colour pass's sided segments in region 0, under the segment's first
12508    /// bucket's block — whatever the bucket count, and whether or not the
12509    /// device granted a draw index, which the flat call does not read. Without
12510    /// the stage the colour pass's calls, unrolled a structure at a time, are
12511    /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
12512    /// bucket's own extents, each once. Either way the counters are what the
12513    /// frame recorded.
12514    #[test]
12515    fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
12516        use crcbl_hal::null::Command;
12517
12518        let _seam = ssao_split_switch();
12519        // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
12520        // bucket each, in one material mode — so one run of `n` buckets.
12521        for cubes in [None, Some(4), Some(33)] {
12522            for task in [Features::TASK_SHADER, Features::empty()] {
12523                for ranged in [false, true] {
12524                    let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
12525                    let recorder = Recorder::new();
12526                    let optional = if ranged {
12527                        task | Features::DRAW_INDEX
12528                    } else {
12529                        task
12530                    };
12531                    let (device, queue) = open_mesh_path(&recorder, optional);
12532                    let mut scene = scene::demo();
12533                    if let Some(cubes) = cubes {
12534                        scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
12535                        scene.capacities.meshes = cubes;
12536                        scene.capacities.vertices =
12537                            cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
12538                        scene.capacities.indices =
12539                            cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
12540                    }
12541                    let mut renderer = ForwardRenderer::with_scene_on_path(
12542                        device.as_ref(),
12543                        queue,
12544                        Format::Rgba8UnormSrgb,
12545                        &scene,
12546                        GeometryPath::MeshShader,
12547                    )
12548                    .expect("the mesh renderer builds");
12549                    assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
12550                    assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
12551                    let buckets = renderer.bucket_constants.len();
12552                    assert!(buckets > 1, "one bucket packs into one call either way");
12553                    let rendered = frame(device.as_ref(), &mut renderer, queue);
12554
12555                    let commands = commands_in_pass(&recorder, "forward");
12556                    let bound: Vec<u32> = commands
12557                        .iter()
12558                        .filter_map(|command| match command {
12559                            Command::BindGroup {
12560                                slot: 0,
12561                                dynamic_offsets,
12562                                ..
12563                            } => Some(dynamic_offsets[0]),
12564                            _ => None,
12565                        })
12566                        .collect();
12567                    let calls: Vec<DrawIndirect> = commands
12568                        .iter()
12569                        .filter_map(|command| match command {
12570                            Command::DrawMeshTasksIndirect(draw) => Some(*draw),
12571                            Command::DrawMeshTasks { .. }
12572                            | Command::DrawIndexedIndirect(_)
12573                            | Command::DrawIndexedIndirectCount(_) => {
12574                                panic!("{case}: the mesh tail recorded {command:?}")
12575                            }
12576                            _ => None,
12577                        })
12578                        .collect();
12579                    assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12580                    assert!(
12581                        calls
12582                            .iter()
12583                            .all(|call| call.stride
12584                                == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12585                        "{case}: one structure a bucket, or a flat call's one"
12586                    );
12587                    if task.is_empty() {
12588                        // Each call a structure at a time: what a call per
12589                        // bucket would have recorded for the buckets it
12590                        // stands for.
12591                        let mut unrolled: Vec<DrawIndirect> = calls
12592                            .iter()
12593                            .flat_map(|call| {
12594                                (0..call.draw_count).map(|draw| DrawIndirect {
12595                                    offset: call.offset + u64::from(draw) * u64::from(call.stride),
12596                                    draw_count: 1,
12597                                    ..*call
12598                                })
12599                            })
12600                            .collect();
12601                        unrolled.sort_by_key(|draw| draw.offset);
12602                        assert_eq!(
12603                            unrolled,
12604                            mesh_dispatch_calls(&renderer),
12605                            "{case}: every bucket's own extents, each once"
12606                        );
12607                        let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12608                        match (ranged, cubes) {
12609                            (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12610                            (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12611                            (true, None) => assert!(
12612                                calls.len() < buckets,
12613                                "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12614                            ),
12615                        }
12616                    } else {
12617                        let (expected, firsts) = flat_dispatch_calls(
12618                            &renderer,
12619                            crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12620                        );
12621                        assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12622                        assert_eq!(
12623                            bound,
12624                            firsts
12625                                .iter()
12626                                .map(|&bucket| renderer.bucket_constants[bucket as usize])
12627                                .collect::<Vec<_>>(),
12628                            "{case}: each under its segment's first bucket's block"
12629                        );
12630                    }
12631                    assert_eq!(
12632                        renderer.counters().draws,
12633                        recorded_draws(&recorder) as u64,
12634                        "{case}"
12635                    );
12636                    rendered.finish(device.as_ref(), renderer);
12637                    recorder.assert_valid();
12638                }
12639            }
12640        }
12641    }
12642
12643    /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12644    /// block carries**, in every draw region.
12645    ///
12646    /// The host half of `mesh_cluster.slang`'s "One call for a range of
12647    /// buckets": a ranged call binds its first bucket's block alone, and the
12648    /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12649    /// the two table words it names. So each bucket's block has to sit one word
12650    /// past the one before in all four, and the table words have to hold the
12651    /// bucket's own cluster base and count — read out of the bytes that reached
12652    /// the device, since a block written wrong leaves the renderer's fields
12653    /// right.
12654    #[test]
12655    fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12656        let recorder = Recorder::new();
12657        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12658        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12659            .expect("the mesh renderer builds");
12660        let blocks = recorder
12661            .buffer_bytes(renderer.draw_constants)
12662            .expect("the blocks are live");
12663        let tables = recorder
12664            .buffer_bytes(renderer.primary.draws.tables())
12665            .expect("the tables are live");
12666        let word = |bytes: &[u8], at: usize| {
12667            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12668        };
12669        let buckets = renderer.bucket_constants.len();
12670        assert!(buckets > 1, "a range needs two buckets to step between");
12671        let bucket_count = u32::try_from(buckets).expect("a few buckets");
12672        let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12673        let block = |region: u32, bucket: u32| {
12674            let at = ((region * bucket_count + bucket) * stride) as usize;
12675            let field = |index: usize| word(&blocks, at + index * 4);
12676            crcbl_shaders::meshlet::ClusterDrawConstants {
12677                start_at: field(0),
12678                cluster_base: field(1),
12679                cluster_count: field(2),
12680                bucket: field(3),
12681                group_stride: field(4),
12682                level_groups_at: field(5),
12683                cluster_base_at: field(6),
12684                cluster_count_at: field(7),
12685                chunk_starts_at: field(8),
12686                chunk_starts_end: field(9),
12687            }
12688        };
12689        let mut bases = Vec::new();
12690        for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12691            let first = block(region, 0);
12692            for bucket in 0..bucket_count {
12693                let own = block(region, bucket);
12694                assert_eq!(
12695                    word(&tables, own.cluster_base_at as usize * 4),
12696                    own.cluster_base,
12697                    "region {region} bucket {bucket}: the base word holds the base"
12698                );
12699                assert_eq!(
12700                    word(&tables, own.cluster_count_at as usize * 4),
12701                    own.cluster_count,
12702                    "region {region} bucket {bucket}: the count word holds the count"
12703                );
12704                // What draw `bucket` of a call bound at bucket 0's block reads
12705                // — and a flat call's workgroup that found bucket `bucket` by
12706                // searching the chunk starts from bucket 0's word to the
12707                // region's end.
12708                assert_eq!(
12709                    (
12710                        first.start_at + bucket,
12711                        first.bucket + bucket,
12712                        first.cluster_base_at + bucket,
12713                        first.cluster_count_at + bucket,
12714                        first.group_stride,
12715                        first.level_groups_at,
12716                        first.chunk_starts_at + bucket,
12717                        first.chunk_starts_end,
12718                    ),
12719                    (
12720                        own.start_at,
12721                        own.bucket,
12722                        own.cluster_base_at,
12723                        own.cluster_count_at,
12724                        own.group_stride,
12725                        own.level_groups_at,
12726                        own.chunk_starts_at,
12727                        own.chunk_starts_end,
12728                    ),
12729                    "region {region} bucket {bucket}"
12730                );
12731                assert_eq!(
12732                    own.chunk_starts_at,
12733                    crcbl_shaders::draw_gen::chunk_start_word(
12734                        renderer.primary.draws.visible_capacity(),
12735                        bucket_count,
12736                        region,
12737                        bucket,
12738                    ),
12739                    "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12740                );
12741                assert_eq!(
12742                    own.chunk_starts_end - own.chunk_starts_at,
12743                    bucket_count - bucket,
12744                    "region {region} bucket {bucket}: the search ends at the region's end word"
12745                );
12746                if region == 0 {
12747                    bases.push(own.cluster_base);
12748                }
12749            }
12750        }
12751        assert!(
12752            bases.windows(2).any(|pair| pair[0] != pair[1]),
12753            "the buckets' meshes start at different clusters, so a range reading its \
12754             first bucket's base for every draw would be seen: {bases:?}"
12755        );
12756        renderer.destroy(device.as_ref());
12757        recorder.assert_valid();
12758    }
12759
12760    #[test]
12761    fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12762    {
12763        for features in [
12764            Features::GPU_DRIVEN,
12765            Features::COMPUTE | Features::MESH_SHADER,
12766        ] {
12767            let recorder = Recorder::new();
12768            let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12769                features,
12770                limits: crcbl_hal::Limits::desktop(),
12771            })
12772            .with_recorder(recorder.clone());
12773            let device = instance
12774                .create_device(&DeviceDesc {
12775                    label: None,
12776                    adapter: crcbl_hal::AdapterId(0),
12777                    required_features: Features::COMPUTE,
12778                    optional_features: features,
12779                    compatible_surface: None,
12780                })
12781                .expect("null device opens");
12782            let queue = device.queue(QueueKind::Graphics).unwrap();
12783            for (path, required) in [
12784                (GeometryPath::IndirectPerBatch, Features::empty()),
12785                (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12786                (GeometryPath::MeshShader, Features::MESH_SHADER),
12787            ] {
12788                recorder.clear();
12789                let result = ForwardRenderer::with_scene_on_path(
12790                    device.as_ref(),
12791                    queue,
12792                    Format::Rgba8UnormSrgb,
12793                    &scene::demo(),
12794                    path,
12795                );
12796                if features.contains(required) {
12797                    let renderer = result.expect("supported exact tail builds");
12798                    assert_eq!(renderer.geometry_path(), path);
12799                    renderer.destroy(device.as_ref());
12800                } else {
12801                    assert!(
12802                        matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12803                    );
12804                    assert!(
12805                        recorder.events().is_empty(),
12806                        "unsupported selection must not touch device objects"
12807                    );
12808                }
12809                recorder.assert_valid();
12810            }
12811        }
12812    }
12813
12814    pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12815        open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12816    }
12817
12818    /// [`open`] asking for `optional_features` instead of
12819    /// [`DeviceDesc::for_adapter`]'s.
12820    ///
12821    /// The null preset *has* more than the default request asks for, and a
12822    /// granted feature set is the intersection of the two — so this is how a test
12823    /// reaches a device with something the ordinary one lacks. What it exists for
12824    /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12825    /// device has no line fill mode, which is the other half of the wireframe
12826    /// pair of tests below.
12827    fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12828        let recorder = Recorder::new();
12829        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12830        let adapter = instance.adapters().remove(0);
12831        let device = instance
12832            .create_device(&DeviceDesc {
12833                optional_features,
12834                ..DeviceDesc::for_adapter(adapter.id)
12835            })
12836            .expect("the null backend always opens");
12837        let queue = device.queue(QueueKind::Graphics).expect("always present");
12838        (recorder, device, queue)
12839    }
12840
12841    /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12842    ///
12843    /// **Insertion order is what the caller decides**, and it is load-bearing:
12844    /// the slot an object lands in is topic 25's hysteresis key. So
12845    /// every test below places its objects in the order the frame used to hold
12846    /// them — the cube first, wherever there is one.
12847    /// The label of every graphics pipeline `recorder`'s device has created, in
12848    /// creation order — so `labels[handle.index()]` names the pipeline a bind
12849    /// of `handle` bound.
12850    ///
12851    /// What lets two renderers' bind streams be compared: `build` compiles only
12852    /// the mesh pipelines its scene draws with, so two scenes' renderers hand
12853    /// out different handle values for the same pipeline, and a label is what
12854    /// stays the same. Valid only while no graphics pipeline was destroyed,
12855    /// since the pool reuses a freed slot — which this asserts.
12856    fn graphics_pipeline_labels(recorder: &Recorder) -> Vec<String> {
12857        let events = recorder.events();
12858        assert!(
12859            !events.iter().any(|event| matches!(
12860                event,
12861                Event::Destroyed {
12862                    kind: ObjectKind::GraphicsPipeline
12863                }
12864            )),
12865            "a graphics pipeline was destroyed, so a handle's index is no longer its creation \
12866             order"
12867        );
12868        events
12869            .into_iter()
12870            .filter_map(|event| match event {
12871                Event::Created {
12872                    kind: ObjectKind::GraphicsPipeline,
12873                    label,
12874                } => Some(label.unwrap_or_default()),
12875                _ => None,
12876            })
12877            .collect()
12878    }
12879
12880    fn place_demo(
12881        renderer: &mut ForwardRenderer,
12882        mesh: usize,
12883        material: usize,
12884        transform: Mat4,
12885    ) -> InstanceHandle {
12886        renderer
12887            .add_instance(&InstanceDesc {
12888                mesh,
12889                material,
12890                transform,
12891            })
12892            .expect("a pool of thousands has room for a handful of objects")
12893    }
12894
12895    /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12896    /// always had.
12897    ///
12898    /// `begin_frame` used to write this object for every caller; the tests below
12899    /// that are about a frame with something in it place it themselves now.
12900    pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12901        place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12902    }
12903
12904    /// The whole renderer builds and tears down against a backend with no
12905    /// driver, which is what makes it testable on every CI leg.
12906    #[test]
12907    fn the_forward_renderer_builds_and_leaks_nothing() {
12908        let (recorder, device, queue) = open();
12909        let before = recorder.total_live_objects();
12910        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12911            .expect("the null backend accepts every descriptor");
12912        assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12913        assert!(recorder.total_live_objects() > before);
12914        renderer.destroy(device.as_ref());
12915        assert_eq!(
12916            recorder.total_live_objects(),
12917            before,
12918            "every object created must be destroyed"
12919        );
12920        recorder.assert_valid();
12921    }
12922
12923    /// The uniform ring really rotates, or a spinning cube is a
12924    /// read-after-write hazard across submissions.
12925    #[test]
12926    fn the_uniform_ring_rotates() {
12927        let (_, device, queue) = open();
12928        let mut renderer =
12929            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12930        let camera = Camera::default();
12931        let light = DirectionalLight::default();
12932
12933        let mut seen = Vec::new();
12934        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12935            renderer
12936                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12937                .expect("write");
12938            seen.push(renderer.primary.uniforms[renderer.frame]);
12939        }
12940        assert_ne!(
12941            seen[0], seen[1],
12942            "consecutive frames must not share a buffer"
12943        );
12944        assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12945        renderer.destroy(device.as_ref());
12946    }
12947
12948    /// **The tonemap's block is a ring too, and it carries the exposure the
12949    /// caller set.**
12950    ///
12951    /// The bytes are the observable rather than the field, because the field is
12952    /// what a renderer that never wired the block up would also have: the claim
12953    /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12954    /// null recorder's write log can say so.
12955    ///
12956    /// The default is checked first — a renderer nobody has called
12957    /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12958    /// `EXPOSURE` constant held, under
12959    /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12960    #[test]
12961    fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12962        let (recorder, device, queue) = open();
12963        let mut renderer =
12964            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12965        let camera = Camera::default();
12966        let light = DirectionalLight::default();
12967
12968        renderer
12969            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12970            .expect("write");
12971        assert_eq!(
12972            recorder
12973                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12974                .expect("begin_frame wrote the block"),
12975            crcbl_shaders::tonemap::TonemapParams {
12976                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12977                curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12978                auto_exposure: false,
12979                coverage_alpha: false,
12980            }
12981            .to_bytes(),
12982            "an untouched renderer must write the exposure the constant used to hold, \
12983             under the operator this renderer starts on",
12984        );
12985
12986        // A value that is neither the default nor a bound, so a block left at
12987        // either would fail.
12988        renderer.set_exposure(3.5);
12989        let mut slots = Vec::new();
12990        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12991            renderer
12992                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12993                .expect("write");
12994            slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
12995            assert_eq!(
12996                recorder
12997                    .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12998                    .expect("begin_frame wrote the block"),
12999                crcbl_shaders::tonemap::TonemapParams {
13000                    exposure: 3.5,
13001                    curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
13002                    auto_exposure: false,
13003                    coverage_alpha: false,
13004                }
13005                .to_bytes(),
13006                "the frame's own block must carry the exposure in force",
13007            );
13008        }
13009        assert_ne!(
13010            slots[0], slots[1],
13011            "consecutive frames must not share a block"
13012        );
13013        assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
13014
13015        renderer.destroy(device.as_ref());
13016    }
13017
13018    /// **The curve reaches the block, and a caller can move it off the
13019    /// default.**
13020    ///
13021    /// The selector is a lane of the same ring the exposure rides in, and a lane
13022    /// nothing wrote would read as
13023    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
13024    /// whatever a caller asked for — a setter that compiles, a frame that looks
13025    /// right, and a curve that never runs. Since the renderer now *starts* on
13026    /// the fit, that failure would read as a working default, so the check runs
13027    /// in both directions: the untouched block carries the fit, and asking for
13028    /// the clamp changes the bytes on every frame of the ring.
13029    #[test]
13030    fn the_tonemap_block_carries_the_curve_a_caller_selected() {
13031        use crcbl_shaders::tonemap::TonemapCurve;
13032
13033        let (recorder, device, queue) = open();
13034        let mut renderer =
13035            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13036        let camera = Camera::default();
13037        let light = DirectionalLight::default();
13038
13039        assert_eq!(
13040            renderer.tonemap_curve(),
13041            TonemapCurve::Aces,
13042            "a renderer nobody configured must run the operator the goldens were blessed under",
13043        );
13044        renderer
13045            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13046            .expect("write");
13047        let by_default = recorder
13048            .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13049            .expect("begin_frame wrote the block");
13050
13051        renderer.set_tonemap_curve(TonemapCurve::Clamp);
13052        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
13053        for _ in 0..FRAMES_IN_FLIGHT * 2 {
13054            renderer
13055                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13056                .expect("write");
13057            let written = recorder
13058                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13059                .expect("begin_frame wrote the block");
13060            assert_eq!(
13061                written,
13062                crcbl_shaders::tonemap::TonemapParams {
13063                    exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
13064                    curve: TonemapCurve::Clamp,
13065                    auto_exposure: false,
13066                    coverage_alpha: false,
13067                }
13068                .to_bytes(),
13069                "every frame of the ring must carry the selected curve",
13070            );
13071            assert_ne!(
13072                written, by_default,
13073                "and it must differ from the block a default renderer writes",
13074            );
13075        }
13076
13077        // **A readout runs the clamp whatever was selected**, and the selection
13078        // survives it: the caller's curve is still the caller's, the frame's is
13079        // the identity, and the shaded frame after gets the curve back. Asked of
13080        // the fit, which is the selection a readout has something to lose under.
13081        renderer.set_tonemap_curve(TonemapCurve::Aces);
13082        renderer.set_normals_view(true);
13083        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
13084        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
13085        renderer
13086            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13087            .expect("write");
13088        assert_eq!(
13089            recorder
13090                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13091                .expect("begin_frame wrote the block"),
13092            crcbl_shaders::tonemap::TonemapParams {
13093                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
13094                curve: TonemapCurve::Clamp,
13095                auto_exposure: false,
13096                coverage_alpha: false,
13097            }
13098            .to_bytes(),
13099            "a debug view's block must carry the clamp, since its pixels are data",
13100        );
13101        renderer.set_normals_view(false);
13102        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
13103
13104        renderer.destroy(device.as_ref());
13105    }
13106
13107    /// **The exposure is clamped where it is set**, so no caller can reach a
13108    /// frame it cannot get back from.
13109    ///
13110    /// Each case is a different way of leaving the range, and the NaN one is the
13111    /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
13112    /// propagates a NaN into the block, which is a frame of NaN pixels with no
13113    /// key to press to escape it.
13114    #[test]
13115    fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
13116        let (_, device, queue) = open();
13117        let mut renderer =
13118            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13119        assert!(
13120            (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
13121            "the default is {}",
13122            renderer.exposure(),
13123        );
13124
13125        for (asked, expected) in [
13126            (2.0, 2.0),
13127            (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
13128            (f32::INFINITY, EXPOSURE_MAX),
13129            (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
13130            (0.0, EXPOSURE_MIN),
13131            (-8.0, EXPOSURE_MIN),
13132            (f32::NEG_INFINITY, EXPOSURE_MIN),
13133            (f32::NAN, EXPOSURE_MIN),
13134        ] {
13135            renderer.set_exposure(asked);
13136            assert!(
13137                (renderer.exposure() - expected).abs() < f32::EPSILON,
13138                "{asked} was clamped to {}, not {expected}",
13139                renderer.exposure(),
13140            );
13141        }
13142
13143        renderer.destroy(device.as_ref());
13144    }
13145
13146    /// **The debug views resolve in one order, however they are set.**
13147    ///
13148    /// Every one of them rides in one float lane and the shaders test the
13149    /// outermost threshold first, so a renderer with two switches on draws
13150    /// exactly one picture — and which one has to be a rule rather than
13151    /// whichever branch a caller's setter happened to run last. Every
13152    /// combination of the switches is walked, because a precedence written as an
13153    /// `if` chain is right for most of them by accident: a chain in the wrong
13154    /// order agrees with this one on every combination where at most one switch
13155    /// is set.
13156    ///
13157    /// **The two innermost views are the exception the walk is worth most for.**
13158    /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
13159    /// it, so it resolves *last* and its sentinel runs the other way down the
13160    /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
13161    /// *off* sentinel, because it is a pass rather than a branch. Every
13162    /// combination where either is set beside a replacing view is a combination
13163    /// an order written any other way answers differently, and there is no
13164    /// single-switch case that could tell them apart.
13165    ///
13166    /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
13167    /// a panel reads back and the value the shader branches on cannot drift —
13168    /// they are the same function.
13169    #[test]
13170    fn the_debug_views_resolve_in_one_order_however_they_are_set() {
13171        // `w` of the second `float4` of the block — the lane
13172        // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
13173        // spells out, and for its reason.
13174        const AMBIENT_W: usize = 64 + 16 + 12;
13175
13176        let (recorder, device, queue) = open();
13177        let mut renderer =
13178            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13179        let camera = Camera::default();
13180        let light = DirectionalLight::default();
13181
13182        for bent in [false, true] {
13183            for motion in [false, true] {
13184                for occlusion in [false, true] {
13185                    for heatmap in [false, true] {
13186                        for lod in [false, true] {
13187                            for normals in [false, true] {
13188                                for (atlas, cascades) in
13189                                    [false, true].into_iter().flat_map(|atlas| {
13190                                        [false, true].map(|cascades| (atlas, cascades))
13191                                    })
13192                                {
13193                                    renderer.set_bent_normal_view(bent);
13194                                    renderer.set_motion_view(motion);
13195                                    renderer.set_occlusion_view(occlusion);
13196                                    renderer.set_heatmap(heatmap);
13197                                    renderer.set_lod_view(lod);
13198                                    renderer.set_normals_view(normals);
13199                                    renderer.set_atlas_view(atlas);
13200                                    renderer.set_cascade_view(cascades);
13201                                    let set = format!(
13202                                        "bent={bent} motion={motion} occlusion={occlusion} \
13203                                 heatmap={heatmap} lod={lod} normals={normals} \
13204                                 atlas={atlas} cascades={cascades}"
13205                                    );
13206                                    // Each switch reads back what it was set to, whatever
13207                                    // the others are: a caller's toggle is about the
13208                                    // caller's setting, and only `debug_view` is about the
13209                                    // picture.
13210                                    assert_eq!(renderer.bent_normal_view(), bent);
13211                                    assert_eq!(renderer.motion_view(), motion);
13212                                    assert_eq!(renderer.occlusion_view(), occlusion);
13213                                    assert_eq!(renderer.heatmap(), heatmap);
13214                                    assert_eq!(renderer.lod_view(), lod);
13215                                    assert_eq!(renderer.normals_view(), normals);
13216                                    assert_eq!(renderer.atlas_view(), atlas);
13217                                    assert_eq!(renderer.cascade_view(), cascades);
13218
13219                                    let expected = if bent {
13220                                        DebugView::BentNormal
13221                                    } else if motion {
13222                                        DebugView::Motion
13223                                    } else if occlusion {
13224                                        DebugView::AmbientOcclusion
13225                                    } else if heatmap {
13226                                        DebugView::Heatmap
13227                                    } else if lod {
13228                                        DebugView::LodTint
13229                                    } else if normals {
13230                                        DebugView::Normals
13231                                    } else if atlas {
13232                                        // **Below every replacing view above and
13233                                        // above the tint below**, which is the
13234                                        // half of this order no single-switch
13235                                        // case reaches: with a replacing view
13236                                        // also set the frame is that view's, and
13237                                        // with the tint also set the frame is the
13238                                        // atlas.
13239                                        DebugView::ShadowAtlas
13240                                    } else if cascades {
13241                                        // **Last, which is the half of this order a
13242                                        // chain in any other arrangement would get
13243                                        // right by accident.** The cascade tint is a
13244                                        // multiply on the shaded picture, so every
13245                                        // combination that also names a replacing
13246                                        // view has to resolve to *that* view — and
13247                                        // those are exactly the combinations an
13248                                        // `if cascades` written one line higher
13249                                        // would answer differently.
13250                                        DebugView::Cascades
13251                                    } else {
13252                                        DebugView::Shaded
13253                                    };
13254                                    assert_eq!(renderer.debug_view(), expected, "{set}");
13255
13256                                    renderer
13257                                        .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13258                                        .expect("write");
13259                                    let block = recorder
13260                                        .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13261                                        .expect("begin_frame wrote the block");
13262                                    let sentinel = match expected {
13263                                        DebugView::BentNormal => {
13264                                            mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
13265                                        }
13266                                        DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
13267                                        DebugView::AmbientOcclusion => {
13268                                            mesh::FrameUniforms::OCCLUSION_VIEW_ON
13269                                        }
13270                                        DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
13271                                        DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
13272                                        DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
13273                                        DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
13274                                        // **The atlas view carries the *off*
13275                                        // sentinel**, which is what makes this
13276                                        // assertion say something rather than
13277                                        // restate `debug_view_lane`: the colour
13278                                        // pass draws the shaded picture and
13279                                        // `crate::atlas_view`'s pass replaces
13280                                        // it, so a lane of its own here would be
13281                                        // a threshold no shader tests.
13282                                        DebugView::ShadowAtlas | DebugView::Shaded => {
13283                                            mesh::FrameUniforms::NORMALS_VIEW_OFF
13284                                        }
13285                                    };
13286                                    assert_eq!(
13287                                        &block[AMBIENT_W..AMBIENT_W + 4],
13288                                        &sentinel.to_le_bytes(),
13289                                        "{set} resolved to {expected:?}, and the lane says otherwise"
13290                                    );
13291                                    // And the resolve comes off for every one of them:
13292                                    // these frames are read back as data, so their colours
13293                                    // have to stay the ones the shader wrote — see
13294                                    // `resolved_effects`. The whole slot rather than one
13295                                    // tier of it, because which tier the default carries
13296                                    // is not what this is about.
13297                                    assert_eq!(
13298                                        renderer.effects().intersects(Antialiasing::SLOT),
13299                                        expected == DebugView::Shaded,
13300                                        "{set}"
13301                                    );
13302                                }
13303                            }
13304                        }
13305                    }
13306                }
13307            }
13308        }
13309
13310        renderer.destroy(device.as_ref());
13311    }
13312
13313    /// **The atlas viewer records one pass, and only on the frame it is the view
13314    /// showing.**
13315    ///
13316    /// The mechanism no other check in this file can see. Every other debug view
13317    /// is a lane of the frame block, so
13318    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
13319    /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
13320    /// is a claim about the command stream and about nothing else. A switch that
13321    /// resolved correctly and recorded nothing would satisfy every other
13322    /// assertion in this module and draw the frame unchanged.
13323    ///
13324    /// Three arms, and the third is the one that makes the first two mean
13325    /// something:
13326    ///
13327    /// * off — no pass at all, which is what makes the off position
13328    ///   bit-identical for every golden in this workspace;
13329    /// * on — the pass, with the full-screen triangle in it;
13330    /// * on **beside a replacing view** — no pass, because
13331    ///   [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
13332    ///   not what this frame draws. That is the half a `self.atlas_view` read at
13333    ///   the recording site would get wrong while passing both arms above.
13334    ///
13335    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
13336    /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
13337    /// the draw count follows.**
13338    ///
13339    /// The viewer fills every display pixel with a `DontCare` load, so a
13340    /// tonemapped frame or a grid recorded under it is stored and discarded.
13341    /// The pass counts go red if either comes back; the counter goes red if
13342    /// `counters` still charges the frame for the triangles it no longer
13343    /// records.
13344    #[test]
13345    fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
13346        let _seam = ssao_split_switch();
13347        let (recorder, device, queue) = open();
13348        let mut renderer =
13349            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13350        renderer
13351            .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
13352            .expect("the null backend builds every pipeline");
13353        renderer.set_atlas_view(true);
13354        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
13355
13356        let viewing = frame(device.as_ref(), &mut renderer, queue);
13357        let opened = |label: &str| {
13358            recorder
13359                .commands()
13360                .iter()
13361                .filter(|command| {
13362                    matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
13363                })
13364                .count()
13365        };
13366        assert_eq!(opened(crate::atlas_view::LABEL), 1);
13367        assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
13368        assert_eq!(opened("grid"), 0, "and the grid drawn over it");
13369        assert_eq!(
13370            renderer.counters().draws,
13371            recorded_draws(&recorder) as u64,
13372            "the counter charges the frame for exactly the draws it recorded"
13373        );
13374        viewing.finish(device.as_ref(), renderer);
13375    }
13376
13377    #[test]
13378    fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
13379        use crcbl_hal::null::Command;
13380
13381        let (recorder, device, queue) = open();
13382        let device = device.as_ref();
13383        let mut renderer =
13384            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
13385        let (camera, sun) = (Camera::default(), DirectionalLight::default());
13386
13387        // How many times the viewer's pass was opened since `from`, which is
13388        // where the previous arm's commands ended.
13389        let opened = |from: usize| {
13390            recorder.commands()[from..]
13391                .iter()
13392                .filter(|command| {
13393                    matches!(
13394                        command.opens_pass(),
13395                        Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
13396                    )
13397                })
13398                .count()
13399        };
13400
13401        let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13402        assert_eq!(
13403            opened(0),
13404            0,
13405            "a frame drawing the shaded picture recorded the atlas viewer's pass"
13406        );
13407        let after_shaded = recorder.commands().len();
13408        shaded.release(device);
13409
13410        renderer.set_atlas_view(true);
13411        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
13412        let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13413        assert_eq!(
13414            opened(after_shaded),
13415            1,
13416            "the atlas viewer is on and its pass was not recorded exactly once"
13417        );
13418        // And what it recorded is the over-sized triangle and nothing else: a
13419        // pass that bound a pipeline and drew no vertices would open above and
13420        // leave the frame the tonemap wrote.
13421        let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
13422            .into_iter()
13423            .filter_map(|command| match command {
13424                Command::Draw {
13425                    vertices,
13426                    instances,
13427                } => Some((
13428                    vertices.end - vertices.start,
13429                    instances.end - instances.start,
13430                )),
13431                _ => None,
13432            })
13433            .collect();
13434        assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
13435        let after_viewing = recorder.commands().len();
13436        viewing.release(device);
13437
13438        // The switch left on, and a replacing view asked for over the top of it.
13439        renderer.set_normals_view(true);
13440        assert_eq!(
13441            renderer.debug_view(),
13442            DebugView::Normals,
13443            "the atlas view does not lose to a replacing view, so the arm below asks nothing"
13444        );
13445        let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13446        assert_eq!(
13447            opened(after_viewing),
13448            0,
13449            "the frame resolved to the normals view and still recorded the atlas viewer's \
13450             pass over the top of it"
13451        );
13452        normals.release(device);
13453
13454        renderer.destroy(device);
13455    }
13456
13457    /// **The heatmap moves the ambient's last lane and no other byte**, and
13458    /// switching it off puts the block back.
13459    ///
13460    /// The normals view's assertion below, for the outermost of the three: the
13461    /// overlay costs one lane, so every golden image ever blessed is untouched
13462    /// by the feature existing. The `lod_params` row the heatmap reads is
13463    /// written every frame whether it is on or not — it is the numbers the
13464    /// selection used — so this compares two frames of the *same* camera and
13465    /// budget, where that row is equal on both sides and any byte outside the
13466    /// lane is a real difference.
13467    #[test]
13468    fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
13469        const AMBIENT_W: usize = 64 + 16 + 12;
13470
13471        // Held for the whole comparison, and it is not this check's own knob:
13472        // `r_shadow_filter` and `r_shadow_split` land in the block's
13473        // `shadow_filter` row on every `begin_frame`, and the filter checks in
13474        // this module move them under this lock while `cargo test` runs the
13475        // module's checks as threads of one process. Two frames read either side
13476        // of such a move differ at that row, which is outside every lane below —
13477        // one run in twelve, measured 2026-09-04.
13478        let _filter = shadow_filter_switch();
13479        let (recorder, device, queue) = open();
13480        let mut renderer =
13481            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13482        let camera = Camera::default();
13483        let light = DirectionalLight::default();
13484        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
13485            renderer
13486                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13487                .expect("write");
13488            recorder
13489                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13490                .expect("begin_frame wrote the block")
13491        };
13492
13493        assert!(
13494            !renderer.heatmap(),
13495            "the heatmap has to be off in a renderer nobody has asked",
13496        );
13497        let shaded = block(&mut renderer);
13498        assert_eq!(
13499            &shaded[AMBIENT_W..AMBIENT_W + 4],
13500            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
13501            "an untouched renderer must write the value every golden image was blessed with",
13502        );
13503
13504        renderer.set_heatmap(true);
13505        let heatmap = block(&mut renderer);
13506        assert_eq!(
13507            &heatmap[AMBIENT_W..AMBIENT_W + 4],
13508            &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
13509            "the switch has to reach the lane the mesh stage branches on",
13510        );
13511        let outside: Vec<usize> = shaded
13512            .iter()
13513            .zip(heatmap.iter())
13514            .enumerate()
13515            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13516            .map(|(at, _)| at)
13517            .collect();
13518        assert!(
13519            outside.is_empty(),
13520            "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
13521        );
13522
13523        renderer.set_heatmap(false);
13524        assert_eq!(
13525            block(&mut renderer),
13526            shaded,
13527            "switching the view off has to put the block back, not just stop reporting it",
13528        );
13529
13530        renderer.destroy(device.as_ref());
13531    }
13532
13533    /// **The normals view moves one lane of the frame block and nothing else.**
13534    ///
13535    /// The mechanism, at the level a null device can observe it: which bytes of
13536    /// the buffer `mesh.slang` reads changed. A field on the renderer would say
13537    /// only that a flag moved; the block is what the shader actually branches on.
13538    ///
13539    /// Four claims, and each rules out a different way of passing wrongly:
13540    ///
13541    /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
13542    ///   is what makes every golden image untouched by this feature;
13543    /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
13544    ///   shader reads, at the offset `std140` puts it at rather than at one this
13545    ///   test picked;
13546    /// * **those four bytes are the only ones that moved**, so the switch did not
13547    ///   come at the cost of the ambient colour beside it or of any matrix;
13548    /// * and switching off puts the block back exactly, so the view is a toggle
13549    ///   rather than a one-way door.
13550    ///
13551    /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
13552    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
13553    #[test]
13554    fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
13555        // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
13556        // then three floats of ambient colour. Spelled as the sum rather than as
13557        // `92` so that a member arriving before it is a compile-time question
13558        // about `FrameUniforms`' own layout and not a silent read of a matrix.
13559        const AMBIENT_W: usize = 64 + 16 + 12;
13560
13561        // Held for the whole comparison, and it is not this check's own knob:
13562        // `r_shadow_filter` and `r_shadow_split` land in the block's
13563        // `shadow_filter` row on every `begin_frame`, and the filter checks in
13564        // this module move them under this lock while `cargo test` runs the
13565        // module's checks as threads of one process. Two frames read either side
13566        // of such a move differ at that row, which is outside every lane below —
13567        // one run in twelve, measured 2026-09-04.
13568        let _filter = shadow_filter_switch();
13569        let (recorder, device, queue) = open();
13570        let mut renderer =
13571            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13572        let camera = Camera::default();
13573        let light = DirectionalLight::default();
13574        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
13575            renderer
13576                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13577                .expect("write");
13578            recorder
13579                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13580                .expect("begin_frame wrote the block")
13581        };
13582
13583        assert!(
13584            !renderer.normals_view(),
13585            "the normals view has to be off in a renderer nobody has asked",
13586        );
13587        let shaded = block(&mut renderer);
13588        assert_eq!(
13589            &shaded[AMBIENT_W..AMBIENT_W + 4],
13590            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
13591            "an untouched renderer must write the value every golden image was blessed with",
13592        );
13593
13594        renderer.set_normals_view(true);
13595        assert!(renderer.normals_view());
13596        let normals = block(&mut renderer);
13597        assert_eq!(
13598            &normals[AMBIENT_W..AMBIENT_W + 4],
13599            &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
13600            "the switch has to reach the lane the fragment stage branches on",
13601        );
13602        // The bytes that moved, and they all have to be inside the lane — not
13603        // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
13604        // and an equality against the whole range would be a test about IEEE 754
13605        // rather than about the block.
13606        let outside: Vec<usize> = shaded
13607            .iter()
13608            .zip(normals.iter())
13609            .enumerate()
13610            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13611            .map(|(at, _)| at)
13612            .collect();
13613        assert!(
13614            outside.is_empty(),
13615            "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13616        );
13617
13618        renderer.set_normals_view(false);
13619        assert!(!renderer.normals_view());
13620        assert_eq!(
13621            block(&mut renderer),
13622            shaded,
13623            "switching the view off has to put the block back, not just stop reporting it",
13624        );
13625
13626        renderer.destroy(device.as_ref());
13627    }
13628
13629    /// **A frame uploads the instances a caller moved, and a frame nobody moved
13630    /// anything in uploads nothing at all.**
13631    ///
13632    /// The second half is the stronger claim and it is the one that needed the
13633    /// cube to become an ordinary instance: `begin_frame` used to take the
13634    /// cube's transform as an argument and write it into the pool every frame,
13635    /// so that slot was dirty in every ring slot forever and a motionless scene
13636    /// paid a spinning one's transfer. The bytes were identical, so no golden
13637    /// image could ever have shown it — the recorder's write log is the only
13638    /// place the difference is visible.
13639    ///
13640    /// The pyramid is here so that "only the one that moved" is a claim about a
13641    /// choice: with one instance in the array, uploading it and uploading
13642    /// everything are the same event.
13643    #[test]
13644    fn only_the_instance_that_moved_is_uploaded() {
13645        let (recorder, device, queue) = open();
13646        let mut renderer =
13647            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13648        let instance_buffers = renderer.instances.buffers().to_vec();
13649        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13650        place_demo(
13651            &mut renderer,
13652            DEMO_PYRAMID,
13653            DEMO_UNTINTED,
13654            Mat4::from_translation(Vec3::X),
13655        );
13656
13657        // Both instances are dirty in *every* slot when they are inserted, so
13658        // the first frames upload both however well delta upload works. The ring
13659        // has to be walked right through before an upload is evidence about the
13660        // delta rather than about initialisation.
13661        let frame = |renderer: &mut ForwardRenderer| {
13662            renderer
13663                .begin_frame(
13664                    device.as_ref(),
13665                    &Camera::default(),
13666                    &DirectionalLight::default(),
13667                    (64, 48),
13668                )
13669                .expect("write");
13670        };
13671        for _ in 0..FRAMES_IN_FLIGHT {
13672            frame(&mut renderer);
13673        }
13674        let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13675            recorder
13676                .events()
13677                .into_iter()
13678                .skip(from)
13679                .filter_map(|event| match event {
13680                    crcbl_hal::null::Event::BufferWritten {
13681                        buffer,
13682                        offset,
13683                        len,
13684                    } if instance_buffers.contains(&buffer) => Some((offset, len)),
13685                    _ => None,
13686                })
13687                .collect()
13688        };
13689
13690        let before = recorder.events().len();
13691        frame(&mut renderer);
13692        assert_eq!(
13693            instance_writes(before),
13694            [],
13695            "a frame in which nothing moved must upload no instance bytes at all"
13696        );
13697
13698        let before = recorder.events().len();
13699        let model = ForwardRenderer::spin(1.25);
13700        renderer.set_instance(
13701            cube,
13702            &InstanceDesc {
13703                mesh: DEMO_CUBE,
13704                material: DEMO_UNTINTED,
13705                transform: model,
13706            },
13707        );
13708        frame(&mut renderer);
13709        assert_eq!(
13710            renderer
13711                .instances
13712                .get(cube)
13713                .expect("the cube is live")
13714                .transform,
13715            model.to_cols_array(),
13716            "the model matrix must land in the instance, not the uniform block"
13717        );
13718        let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13719            * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13720        assert_eq!(
13721            instance_writes(before),
13722            [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13723            "a steady-state frame must upload exactly the one instance that changed"
13724        );
13725
13726        renderer.destroy(device.as_ref());
13727        recorder.assert_valid();
13728    }
13729
13730    /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13731    /// it back for the next object to reuse.**
13732    ///
13733    /// The three-call bookkeeping every caller of the instance API depends on,
13734    /// checked on the pool rather than on the recorder. A `set_instance` that
13735    /// inserted instead would take a fresh slot per call — the pool exhausted in
13736    /// a few thousand frames of a caller that writes a transform per frame, which
13737    /// is what every sample does — and every slot it abandoned would stay
13738    /// **live**, so the frame would draw a copy of the object at each transform
13739    /// it had ever been given. Neither is something a golden image would show
13740    /// until the pool ran out.
13741    ///
13742    /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13743    /// reads the recorder; this is the bookkeeping half and reads the pool, which
13744    /// is where an abandoned slot would still be counted.
13745    ///
13746    /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13747    /// slot carries topic 25's hysteresis state — the reuse below is
13748    /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13749    /// previous occupant's expanded groups.
13750    #[test]
13751    fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13752        for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13753            let (recorder, device, queue) = open();
13754            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13755                .expect("built");
13756            // The null backend takes an indirect tail, so the DAG is placeable
13757            // here; the arm that cannot select a level refuses before an
13758            // application ever calls this.
13759            assert!(
13760                renderer.selects_levels(),
13761                "an indirect tail chooses a level for every mesh, DAG included"
13762            );
13763            // What the pool holds before anything is placed, which is nothing: a
13764            // renderer places no object of its own any more.
13765            let resident = renderer.instances.len();
13766            assert_eq!(resident, 0, "a fresh renderer holds no objects");
13767
13768            let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13769            let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13770            assert_eq!(
13771                renderer.instances.len(),
13772                resident + 1,
13773                "mesh {mesh}: add_instance takes one slot"
13774            );
13775
13776            // The rewrite is the whole test: the same handle, the same slot
13777            // count, and the new transform in it.
13778            let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13779            renderer.set_instance(
13780                handle,
13781                &InstanceDesc {
13782                    mesh,
13783                    material: DEMO_UNTINTED,
13784                    transform: second,
13785                },
13786            );
13787            assert_eq!(
13788                renderer.instances.len(),
13789                resident + 1,
13790                "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13791            );
13792            assert_eq!(
13793                renderer.instances.slot_count(),
13794                u32::try_from(resident + 1).expect("a handful of instances"),
13795                "mesh {mesh}: set_instance must not have reached past the slot it holds"
13796            );
13797            assert_eq!(
13798                renderer
13799                    .instances
13800                    .get(handle)
13801                    .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13802                    .transform,
13803                second.to_cols_array(),
13804                "mesh {mesh}: set_instance must have written the second transform"
13805            );
13806
13807            // And a removal gives the slot back, so a caller toggling an object
13808            // is not a leak either.
13809            renderer.remove_instance(handle);
13810            assert_eq!(
13811                renderer.instances.len(),
13812                resident,
13813                "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13814            );
13815            place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13816            assert_eq!(
13817                renderer.instances.slot_count(),
13818                u32::try_from(resident + 1).expect("a handful of instances"),
13819                "mesh {mesh}: the object after a removal must reuse the freed slot"
13820            );
13821
13822            renderer.destroy(device.as_ref());
13823            recorder.assert_valid();
13824        }
13825    }
13826
13827    /// **The description resolves to the ids the renderer used to hand itself**:
13828    /// one table entry per description mesh, in description order, with the DAG
13829    /// occupying one per level after them — and every level's vertex base
13830    /// measured from level 0's, which is zero.
13831    ///
13832    /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13833    /// box out of the entry the *instance* names. So a description walked in
13834    /// another order, or a DAG whose levels landed among the flat meshes, would
13835    /// leave every instance naming a mesh that is not its own: the cube culled
13836    /// against the pyramid's box, the dunes patch drawn as an open box. Every
13837    /// one of those is a frame that still looks like a frame.
13838    ///
13839    /// The bases are asserted against the table bytes rather than against
13840    /// `ResidentMesh`, because the table is what the GPU reads.
13841    #[test]
13842    fn the_description_resolves_to_the_ids_it_was_written_in() {
13843        let (recorder, device, queue) = open();
13844        let renderer =
13845            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13846
13847        assert_eq!(
13848            renderer.mesh_ids,
13849            [0, 1, 2, 3],
13850            "the four description meshes take the first four table entries, in order"
13851        );
13852
13853        // The DAG's coarser levels follow level 0, so a cut that spans them
13854        // reads entries the flat meshes never occupied.
13855        let scene = scene::demo();
13856        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13857            panic!("the demo description's fourth mesh is the DAG");
13858        };
13859        let level_ids: Vec<u32> = (0..dag.levels.len())
13860            .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13861            .collect();
13862        assert!(
13863            level_ids
13864                .iter()
13865                .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13866            "every dunes level is past the flat residents: {level_ids:?}"
13867        );
13868
13869        // **Level 0 is at the pool's own first vertex**, which is what makes
13870        // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13871        // sum the mesh stage forms with the instance's own base.
13872        let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13873            .iter()
13874            .map(|&id| mesh_entry(&recorder, &renderer, id))
13875            .collect();
13876        let level_zero = entries[0].base_vertex;
13877        assert_eq!(
13878            level_zero,
13879            mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13880                + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13881            "the DAG starts where the last flat resident ends"
13882        );
13883        let bases: Vec<u32> = entries
13884            .iter()
13885            .map(|entry| {
13886                entry
13887                    .base_vertex
13888                    .checked_sub(level_zero)
13889                    .expect("a level below level 0 would wrap the offset a cluster carries")
13890            })
13891            .collect();
13892        assert_eq!(
13893            bases[0], 0,
13894            "level 0 is the base every other is measured from"
13895        );
13896        assert!(
13897            bases.windows(2).all(|pair| pair[0] < pair[1]),
13898            "each level starts past the one below it: {bases:?}"
13899        );
13900
13901        renderer.destroy(device.as_ref());
13902        recorder.assert_valid();
13903    }
13904
13905    /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13906    ///
13907    /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13908    /// number of DAGs, and until this nothing had put either through it — every
13909    /// golden image and every end-to-end run is `scene::demo()`, whose four
13910    /// meshes hold one DAG between them.
13911    ///
13912    /// What only a second DAG exercises is the **concatenation**: `level_groups`
13913    /// is every DAG's groups laid end to end and a DAG reaches its own run
13914    /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13915    /// which is zero for the first one and therefore invisible while there is
13916    /// only one. A second DAG whose records still named the first's groups would
13917    /// descend a hierarchy belonging to another surface — a cut that is a
13918    /// plausible picture and matches no assertion the CPU makes about the frame.
13919    ///
13920    /// On the mesh path, because that is where the offset is *used*: an indirect
13921    /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13922    ///
13923    /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13924    #[test]
13925    fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13926        use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13927
13928        let recorder = Recorder::new();
13929        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13930
13931        // The engine has one DAG, so a second one is a second copy of it. That
13932        // is the whole point: two DAGs whose *groups* are alike is the case
13933        // where reaching the wrong run still produces a cut, and so the case a
13934        // frame comparison could never catch.
13935        let mut scene = scene::demo();
13936        let mut again = scene.meshes[DEMO_DUNES].clone();
13937        again.label = "dunes again".into();
13938        scene.meshes.push(again);
13939        // Room for the second copy. Doubling rather than measuring, because the
13940        // number that matters is that the description carries its own sizes at
13941        // all — see `Capacities`, which is the caller's to choose.
13942        scene.capacities.vertices *= 2;
13943        scene.capacities.indices *= 2;
13944        let second_dag = scene.meshes.len() - 1;
13945
13946        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13947            panic!("the demo description's fourth mesh is the DAG");
13948        };
13949        let levels = dag.levels.len();
13950        let groups = dag.level_groups().len();
13951        assert!(groups > 0, "a DAG with no groups would select nothing");
13952
13953        let mut renderer =
13954            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13955                .expect("a five-mesh description with two DAGs is one this can make resident");
13956
13957        // Every level of both is its own table entry, laid down in description
13958        // order, so the second DAG's level 0 is a whole hierarchy past the
13959        // first's.
13960        assert_eq!(
13961            renderer.mesh_ids.len(),
13962            scene.meshes.len(),
13963            "one id per description mesh, whatever the count"
13964        );
13965        assert_eq!(
13966            renderer.mesh_ids[second_dag],
13967            renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13968            "the second DAG's level 0 starts past every level of the first"
13969        );
13970
13971        // **The hysteresis state is per instance per resident group**, and
13972        // `group_stride` is what says how many groups that is. One DAG made this
13973        // number a single hierarchy's; two is what tells a stride that sums from
13974        // one that took the first answer it found.
13975        assert_eq!(
13976            renderer.primary.draws.group_stride(),
13977            u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13978            "every resident DAG's groups are in the stride, not just the first's"
13979        );
13980
13981        // The records themselves: which group each cluster produces and which
13982        // contains it, as the amplification stage reads them.
13983        let clusters = renderer
13984            .clusters
13985            .as_ref()
13986            .expect("the mesh path builds a cluster pool");
13987        let selection = recorder
13988            .buffer_bytes(clusters.selection())
13989            .expect("the selection records are live");
13990        // Entries are laid down in description order, a flat mesh taking one and
13991        // a DAG one per level — so the second DAG's start a hierarchy past the
13992        // first's, which start past the three flat residents.
13993        let first_entry = DEMO_DUNES;
13994        let record = |entry: usize| -> Vec<ClusterSelect> {
13995            let range = clusters.range(entry).expect("one range per entry");
13996            (range.base..range.base + range.count)
13997                .map(|cluster| {
13998                    let at = cluster as usize * CLUSTER_SELECT_STRIDE;
13999                    ClusterSelect::from_bytes(
14000                        selection[at..at + CLUSTER_SELECT_STRIDE]
14001                            .try_into()
14002                            .expect("one whole record"),
14003                    )
14004                })
14005                .collect()
14006        };
14007        // The named group of every record that has one, per DAG — and the count,
14008        // because a comparison over an empty set is a check that cannot fail.
14009        let named = |base: usize| -> Vec<u32> {
14010            (base..base + levels)
14011                .flat_map(record)
14012                .flat_map(|select| {
14013                    let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
14014                        .then_some(select.producer_group);
14015                    let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
14016                        .then_some(select.container_group);
14017                    producer.into_iter().chain(container)
14018                })
14019                .collect()
14020        };
14021        let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
14022        let first = named(first_entry);
14023        let second = named(first_entry + levels);
14024        assert!(
14025            !first.is_empty() && first.len() == second.len(),
14026            "the two copies must name the same number of groups: {} against {}",
14027            first.len(),
14028            second.len()
14029        );
14030        assert!(
14031            first.iter().all(|&group| group < boundary),
14032            "the first DAG's records stay inside its own run: {first:?}"
14033        );
14034        assert!(
14035            second
14036                .iter()
14037                .all(|&group| (boundary..boundary * 2).contains(&group)),
14038            "the second DAG's records must name the groups past the first's, and \
14039             `first_group` is the only thing that puts them there: {second:?}"
14040        );
14041
14042        // And both are placeable through the runtime API, which is what a
14043        // description of a shape no `set_*` method names is *for*.
14044        let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
14045            renderer
14046                .add_instance(&InstanceDesc {
14047                    mesh,
14048                    material: DEMO_UNTINTED,
14049                    transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
14050                })
14051                .expect("the pool has room")
14052        };
14053        let near = place(&mut renderer, DEMO_DUNES, -64.0);
14054        let far = place(&mut renderer, second_dag, 64.0);
14055        let index = |handle| {
14056            renderer
14057                .instances
14058                .index(handle)
14059                .expect("a just-added instance is live")
14060        };
14061        assert_ne!(
14062            index(near),
14063            index(far),
14064            "two instances take two slots, and the index is the hysteresis key"
14065        );
14066        assert_eq!(
14067            renderer.instances.get(far).expect("live").mesh,
14068            renderer.mesh_ids[second_dag],
14069            "an InstanceDesc's mesh index resolves through the description, not through \
14070             a table id the caller cannot know"
14071        );
14072
14073        renderer.destroy(device.as_ref());
14074        recorder.assert_valid();
14075    }
14076
14077    /// **A description the renderer cannot make resident is refused before the
14078    /// first device object exists**, so a rejection leaks nothing.
14079    ///
14080    /// `build` hands the geometry pool and the material table to the rollback
14081    /// and then creates a dozen objects with `?` between them. A check that ran
14082    /// part way down that list would be a new early exit on the wrong side of a
14083    /// handover, and the pool would go with it — which is exactly the leak
14084    /// `Rollback` exists to prevent and which
14085    /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
14086    /// only walks the happy path.
14087    ///
14088    /// Each arm below is a *different* refusal, so a check that stopped running
14089    /// would show up as one arm leaking rather than as all of them — and each
14090    /// names a fragment of the message it must be refused *with*, or an arm
14091    /// would pass on some other check's answer.
14092    /// **A description with no meshes is refused by name**, before anything
14093    /// is created, rather than reaching the mesh table's sizing with nothing
14094    /// to size it from.
14095    #[test]
14096    fn a_scene_with_no_meshes_is_refused_by_name() {
14097        let (recorder, device, queue) = open();
14098        let before = recorder.total_live_objects();
14099        let mut scene = scene::demo();
14100        scene.meshes.clear();
14101        let error =
14102            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14103                .expect_err("a scene of no meshes must be refused");
14104        assert!(
14105            error.to_string().contains("at least one mesh"),
14106            "the refusal says what is missing: {error}"
14107        );
14108        assert_eq!(
14109            recorder.total_live_objects(),
14110            before,
14111            "the refusal created something"
14112        );
14113    }
14114
14115    #[test]
14116    fn a_refused_description_creates_nothing_at_all() {
14117        /// One way of writing a description the renderer cannot build, and the
14118        /// words that say it was this refusal rather than another.
14119        type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
14120
14121        let cases: [Break; 9] = [
14122            (
14123                "a row naming a layer the page has not got",
14124                |scene| {
14125                    scene.materials[DEMO_TEXTURED].base_color_texture = 7;
14126                },
14127                "material row 2 samples base-colour page layer 7",
14128            ),
14129            // And the same on the two kinds rung 3 added, because `check_scene`
14130            // reads a different column of the row for each: a check written per
14131            // kind is only worth what its arms cover, and a column nobody broke
14132            // here could be read out of the wrong material field for ever.
14133            // `demo` names no layer of either, so any index at all is past the
14134            // end.
14135            (
14136                "a row naming a packed-page layer the page has not got",
14137                |scene| {
14138                    scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
14139                },
14140                "material row 2 samples metallic-roughness-occlusion page layer 3",
14141            ),
14142            (
14143                "a row naming an emissive layer the page has not got",
14144                |scene| {
14145                    scene.materials[DEMO_TEXTURED].emissive_texture = 3;
14146                },
14147                "material row 2 samples emissive page layer 3",
14148            ),
14149            // The one page refusal a caller can actually spell: `push_layer`
14150            // takes bytes it cannot measure against the extent.
14151            (
14152                "a page layer of the wrong length",
14153                |scene| {
14154                    scene.page = scene::PageDesc::empty();
14155                    scene
14156                        .page
14157                        .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
14158                    scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
14159                    scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
14160                },
14161                "base-colour page layer 0 carries 4 bytes",
14162            ),
14163            (
14164                "a DAG level with no vertices",
14165                |scene| {
14166                    let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
14167                    else {
14168                        panic!("the demo description's fourth mesh is the DAG");
14169                    };
14170                    levels.pop();
14171                },
14172                "vertex array(s) for a DAG of",
14173            ),
14174            // The four capacities, each of which is a pool a caller sized and
14175            // a description outgrew. Written as a capacity the description is
14176            // too large for rather than as a description too large for the
14177            // default, because that is the shape of the mistake: the numbers on
14178            // `Capacities` are the ones an application picks.
14179            (
14180                "more vertices than the pool holds",
14181                |scene| {
14182                    scene.capacities.vertices = 1;
14183                },
14184                "the vertex pool holds 1 and the description needs",
14185            ),
14186            (
14187                "more indices than the pool holds",
14188                |scene| {
14189                    scene.capacities.indices = 1;
14190                },
14191                "the index pool holds 1 and the description needs",
14192            ),
14193            (
14194                "more meshes than the table holds",
14195                |scene| {
14196                    scene.capacities.meshes = 1;
14197                },
14198                "the mesh table holds 1 and the description needs",
14199            ),
14200            (
14201                "more material rows than the table holds",
14202                |scene| {
14203                    scene.capacities.materials = 2;
14204                },
14205                "the material table holds 2 and the description needs 3",
14206            ),
14207        ];
14208
14209        for (what, break_it, says) in cases {
14210            let (recorder, device, queue) = open();
14211            let before = recorder.total_live_objects();
14212            let mut scene = scene::demo();
14213            break_it(&mut scene);
14214            let error =
14215                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14216                    .expect_err(&format!("{what} must be refused"));
14217            assert!(
14218                matches!(error, HalError::InvalidDescriptor(_)),
14219                "{what} must be refused as an invalid descriptor, not as {error:?}"
14220            );
14221            assert!(
14222                error.to_string().contains(says),
14223                "{what} must be refused with a message saying so, and this one says {error}"
14224            );
14225            assert_eq!(
14226                recorder.total_live_objects(),
14227                before,
14228                "{what} was refused after something had been created, and the rollback \
14229                 is the only thing that could have released it"
14230            );
14231            recorder.assert_valid();
14232        }
14233
14234        // **And the refusal that is not free**, which is the half of the
14235        // handover every arm above walks past: `check_scene` settles what the
14236        // whole description says, and what one mesh's *bytes* say is the pool's,
14237        // which only sees them one upload at a time. Vertex bytes that are not a
14238        // whole number of vertices reach `MeshPool::upload` — so the third of
14239        // the four meshes is refused with the pool created, two device-local
14240        // buffers in it and the first two meshes already staged into them.
14241        // `build_geometry` is what releases that, and it can only do so because
14242        // the pool is not the rollback's until it has returned.
14243        let (recorder, device, queue) = open();
14244        let before = recorder.total_live_objects();
14245        // So the count below is this build's and not `open`'s.
14246        recorder.clear();
14247        let mut scene = scene::demo();
14248        let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
14249            panic!("the demo description's third mesh is flat");
14250        };
14251        vertices.to_mut().push(0);
14252        let error =
14253            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14254                .expect_err("a mesh of part of a vertex must be refused");
14255        assert!(
14256            error.to_string().contains("is not a whole number of"),
14257            "the pool's own refusal reaches the caller with its numbers, and this \
14258             one says {error}"
14259        );
14260        assert!(
14261            recorder
14262                .events()
14263                .iter()
14264                .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
14265            "this arm is evidence about the rollback only if the refusal came after \
14266             something had been created"
14267        );
14268        assert_eq!(
14269            recorder.total_live_objects(),
14270            before,
14271            "a mesh refused part way through the list left the geometry pool behind, \
14272             which is exactly what `build_geometry` being self-cleaning is for"
14273        );
14274        recorder.assert_valid();
14275    }
14276
14277    /// **The one capacity a description cannot be checked against, and the one
14278    /// an application is expected to handle while it runs.**
14279    ///
14280    /// Every other number on [`scene::Capacities`] sizes something the
14281    /// description fills once, so `check_scene` refuses an over-large one before
14282    /// a device object exists. Objects are placed at any point in a renderer's
14283    /// life, so the only honest answer for that one is the error
14284    /// [`ForwardRenderer::add_instance`] returns — and it returns
14285    /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
14286    /// what is in it survive to the caller that chose them.
14287    ///
14288    /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
14289    /// value of its own rather than the default, which is what makes the pool
14290    /// fillable at all: a renderer that ignored the number the description
14291    /// carries and reserved the default would draw every frame in the tree
14292    /// identically and refuse nothing here.
14293    #[test]
14294    fn a_full_instance_pool_reaches_the_application_that_sized_it() {
14295        let (recorder, device, queue) = open();
14296        let mut scene = scene::demo();
14297        scene.capacities.instances = 2;
14298        let mut renderer =
14299            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14300                .expect("a scene with room for two objects builds");
14301        let place = |renderer: &mut ForwardRenderer| {
14302            renderer.add_instance(&InstanceDesc {
14303                mesh: DEMO_CUBE,
14304                material: DEMO_UNTINTED,
14305                transform: Mat4::IDENTITY,
14306            })
14307        };
14308        place(&mut renderer).expect("the first of two");
14309        place(&mut renderer).expect("the second of two");
14310        let error = place(&mut renderer).expect_err("a third object has no slot to go in");
14311        assert!(
14312            matches!(
14313                error,
14314                InstancePoolError::PoolFull {
14315                    capacity: 2,
14316                    in_use: 2
14317                }
14318            ),
14319            "a full pool must reach the caller as a full pool, with the capacity it \
14320             chose; this arrived as {error}"
14321        );
14322        renderer.destroy(device.as_ref());
14323        recorder.assert_valid();
14324    }
14325
14326    /// **One mesh and one material row is a scene, and it draws.**
14327    ///
14328    /// The floor is gone. `with_scene` used to refuse anything shorter than
14329    /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
14330    /// demo wrappers named those entries by position, and the renderer's own
14331    /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
14332    /// `DEMO_DUNES` besides. So an application's own description was not merely
14333    /// refused: with the check removed it would have panicked out of `build`.
14334    ///
14335    /// A frame is recorded rather than only a build, because that is where the
14336    /// positional indexing was: the bucket table, the cluster ranges and the
14337    /// draw-argument blocks are all one-per-description-mesh, and a renderer that
14338    /// still assumed four would come apart here rather than at `with_scene`.
14339    #[test]
14340    fn a_description_smaller_than_the_demo_is_a_scene() {
14341        use std::borrow::Cow;
14342
14343        let scene = SceneDesc {
14344            meshes: vec![scene::MeshDesc {
14345                label: Cow::Borrowed("the only mesh"),
14346                geometry: Geometry::Flat {
14347                    vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
14348                    uv_range: crcbl_shaders::mesh::demo_uv_range(),
14349                    indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
14350                    clusters: crcbl_shaders::meshlet::cube_clusters(),
14351                    flags: 0,
14352                },
14353            }],
14354            materials: vec![mesh::GpuMaterial::UNTINTED],
14355            page: scene::PageDesc::empty(),
14356            probes: scene::ProbeGrid::default(),
14357            capacities: scene::Capacities::default(),
14358        };
14359        assert!(
14360            scene.meshes.len() < scene::demo().meshes.len()
14361                && scene.materials.len() < scene::demo().materials.len(),
14362            "this description must be smaller than the demo's in both, or it says nothing \
14363             about the floor"
14364        );
14365
14366        let (recorder, device, queue) = open();
14367        let mut renderer =
14368            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14369                .expect("one mesh and one row is a description the renderer can hold");
14370        assert_eq!(
14371            renderer.mesh_ids,
14372            [0],
14373            "the one description mesh takes the one table entry"
14374        );
14375        assert_eq!(
14376            renderer.bucket_constants.len(),
14377            1,
14378            "one bucket per description mesh, and there is one"
14379        );
14380        renderer
14381            .add_instance(&InstanceDesc {
14382                mesh: 0,
14383                material: 0,
14384                transform: Mat4::IDENTITY,
14385            })
14386            .expect("an empty pool has room for the only object");
14387        let recorded = frame(device.as_ref(), &mut renderer, queue);
14388        assert_eq!(
14389            commands_in_pass(&recorder, "forward")
14390                .into_iter()
14391                .filter(|command| matches!(
14392                    command,
14393                    crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
14394                ))
14395                .count(),
14396            1,
14397            "a one-mesh scene records the one bucket's indirect call"
14398        );
14399        recorded.finish(device.as_ref(), renderer);
14400    }
14401
14402    /// **A description that exactly fills what it reserved is built, not
14403    /// refused.**
14404    ///
14405    /// The other side of the capacity check, and the side nothing else in the
14406    /// tree can fail on: every other scene reserves far more than it holds, so a
14407    /// comparison written `>=` instead of `>` would pass the whole suite and
14408    /// refuse only the application that had sized its pools exactly right.
14409    ///
14410    /// The two capacities asserted here are the two a caller can size without
14411    /// re-deriving anything the renderer knows: one mesh table entry per
14412    /// [`Geometry::levels`], which is what that method is documented to answer,
14413    /// and one row per material. The four rows share one comparison, so they
14414    /// stand or fall together.
14415    #[test]
14416    fn a_description_that_exactly_fits_its_capacities_is_built() {
14417        let (recorder, device, queue) = open();
14418        let mut scene = scene::demo();
14419        scene.capacities.meshes = scene
14420            .meshes
14421            .iter()
14422            .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
14423            .sum();
14424        scene.capacities.materials =
14425            u32::try_from(scene.materials.len()).expect("a few material rows");
14426        let renderer =
14427            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14428                .expect("a description that fits exactly is not too large for itself");
14429        renderer.destroy(device.as_ref());
14430        recorder.assert_valid();
14431    }
14432
14433    /// **The level tables cover every mesh-table slot an instance can name**,
14434    /// not only the slots the description filled.
14435    ///
14436    /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
14437    /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
14438    /// "every entry an instance can name is filled". An instance's mesh id is a
14439    /// bare table index, so a table sized to the description alone makes that
14440    /// read land in whatever the packer put next for any slot the description
14441    /// left empty.
14442    ///
14443    /// Growing the capacity by a known number of slots grows the tables buffer
14444    /// by exactly what those slots occupy: one `MeshLevels` record and one
14445    /// `level_meshes` word each. The arithmetic is the assertion, so nothing
14446    /// here is a number to keep in step by hand.
14447    #[test]
14448    fn the_level_tables_cover_every_slot_the_mesh_table_has() {
14449        const EXTRA: u32 = 4;
14450
14451        let sized = |extra: u32| {
14452            let (recorder, device, queue) = open();
14453            let mut scene = scene::demo();
14454            scene.capacities.meshes += extra;
14455            let renderer =
14456                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14457                    .expect("a description with room to spare");
14458            let size = recorder
14459                .buffer_bytes(renderer.primary.draws.tables())
14460                .expect("the table buffer is live")
14461                .len();
14462            renderer.destroy(device.as_ref());
14463            recorder.assert_valid();
14464            size
14465        };
14466
14467        let grown = sized(EXTRA) - sized(0);
14468        let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
14469        assert_eq!(
14470            grown, want,
14471            "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
14472             level words, and added {grown} bytes"
14473        );
14474    }
14475
14476    /// The property the whole arrangement exists for: the pool's second
14477    /// resident is **not** at base vertex zero, so a frame containing it is a
14478    /// frame that fails if the base is lost between the pool and the shader.
14479    ///
14480    /// Read out of the **mesh table** rather than out of a renderer field,
14481    /// because the table is where a generated draw's index range comes from:
14482    /// `draw_gen.slang` builds every argument structure out of these bytes and
14483    /// nothing on the CPU is consulted.
14484    ///
14485    /// Without this the pass is back where it started — one mesh, base 0, and a
14486    /// base-vertex bug that no picture can show.
14487    #[test]
14488    fn the_second_mesh_lands_past_the_first() {
14489        let (recorder, device, queue) = open();
14490        let renderer =
14491            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14492        let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
14493        let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
14494
14495        assert_eq!(cube.base_vertex, 0, "the cube is first");
14496        assert_eq!(
14497            pyramid.base_vertex as usize,
14498            crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
14499            "the pyramid must start where the cube ends, or the pools are not \
14500             suballocating at all"
14501        );
14502        assert_eq!(
14503            pyramid.index_count as usize,
14504            crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
14505            "and the entry carries the whole range, which is what the draw-argument \
14506             pass builds its arguments out of"
14507        );
14508        // And the two buckets read different constant blocks, or both would walk
14509        // the same run of instances.
14510        assert_ne!(
14511            renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
14512            "each bucket needs a block of its own"
14513        );
14514        renderer.destroy(device.as_ref());
14515    }
14516
14517    /// **Each bucket's block points at that bucket's own run**, and the runs do
14518    /// not overlap.
14519    ///
14520    /// This is what replaced "the block names an instance": a draw covers
14521    /// however many instances survived culling, so what it can say for itself is
14522    /// only where to find its slice of the survivors. Two buckets naming one
14523    /// start word would draw each other's objects — with the *right* geometry,
14524    /// because the index range comes from the arguments, which is exactly the
14525    /// kind of plausible wrong picture a golden image struggles with.
14526    ///
14527    /// Read out of the bytes that reached the device rather than out of the
14528    /// renderer's own fields, because the failure is a block written wrong and
14529    /// the field would still be right.
14530    #[test]
14531    fn each_bucket_walks_its_own_run_of_survivors() {
14532        let (recorder, device, queue) = open();
14533        let renderer =
14534            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14535        let blocks = recorder
14536            .buffer_bytes(renderer.draw_constants)
14537            .expect("the blocks are live");
14538        let start_word_at = |offset: u32| {
14539            let at = offset as usize;
14540            u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
14541        };
14542
14543        let draws = &renderer.primary.draws;
14544        let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
14545        let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
14546        // **Behind the survivors, their routes and the runs**, which share the
14547        // buffer: a block naming a word inside the runs would have the draw read
14548        // an instance index as its start, and one inside the survivor list or
14549        // the routes a start that is the same instances in a different order, or
14550        // a bucket number — both of which draw a plausible picture.
14551        assert_eq!(
14552            cube,
14553            draws.runs_at() + draws.visible_capacity(),
14554            "the first bucket's start word is the first word past one capacity of runs"
14555        );
14556        assert_eq!(
14557            pyramid,
14558            cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
14559            "and the second's is a word later — a start per bucket, not a run per bucket"
14560        );
14561        assert_eq!(
14562            cube,
14563            draws.bucket_start_word(DEMO_CUBE as u32),
14564            "the block carries what `DrawGen::bucket_start_word` says, because a reader \
14565             copying a run back uses that accessor and the shader uses this block"
14566        );
14567        renderer.destroy(device.as_ref());
14568    }
14569
14570    /// **An instance's record carries its material's mode**, in the bits
14571    /// `draw_gen.slang` routes by.
14572    ///
14573    /// The host half of the per-bucket split, and the half no picture and no
14574    /// pipeline bind can show: the bucket table can be perfectly twinned and
14575    /// every partition bound to the right pipeline while every instance still
14576    /// answers mode zero, in which case the masked twins are empty, the cutout
14577    /// partition draws nothing, and a cutout casts a solid shadow. The record is
14578    /// where that is decided.
14579    ///
14580    /// Both directions, so the check is shown to discriminate: the opaque
14581    /// instance's mode bits have to be **clear**, or a writer that set them
14582    /// unconditionally would satisfy a one-sided assertion. And the two records
14583    /// are asserted to differ in `flags` and nothing else, so this is about the
14584    /// mode rather than about two unrelated instances.
14585    #[test]
14586    fn an_instances_record_carries_its_materials_mode() {
14587        let masked_scene = {
14588            let mut scene = crate::scene::demo();
14589            scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
14590            scene
14591        };
14592        let (recorder, device, queue) = open();
14593        let device = device.as_ref();
14594        let mut renderer =
14595            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
14596                .expect("the null backend accepts the demo description");
14597        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14598        let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14599        let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14600
14601        let record = |handle: InstanceHandle| {
14602            renderer
14603                .instances
14604                .get(handle)
14605                .expect("the instance was inserted and is live")
14606        };
14607        let opaque = record(opaque);
14608        let masked = record(masked);
14609        assert_eq!(
14610            opaque.material_mode(),
14611            0,
14612            "an opaque material's instance carries no mode bits, or every instance in the tree \
14613             routes to a cutout bucket"
14614        );
14615        assert_eq!(
14616            masked.material_mode(),
14617            crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14618            "and a masked material's instance carries its mode, or it scatters into the opaque \
14619             twin and the depth passes write its full silhouette"
14620        );
14621        assert_eq!(
14622            mesh::GpuInstance {
14623                flags: opaque.flags,
14624                material: opaque.material,
14625                ..masked
14626            },
14627            opaque,
14628            "the two records differ in the mode bits and the material id and in nothing else"
14629        );
14630
14631        renderer.destroy(device);
14632        recorder.assert_valid();
14633    }
14634
14635    /// **A scene whose materials are all opaque gets exactly the bucket table
14636    /// it had before material modes existed** — one bucket per (mesh, level),
14637    /// and no twin.
14638    ///
14639    /// The zero-cost half of the per-bucket split, and the one a null device can
14640    /// state exactly. A bucket is not free: every pass records one indirect call
14641    /// per bucket per view, and every generator holds a run start per bucket. So
14642    /// a table that twinned unconditionally would double the recorded draws of
14643    /// every demo and every golden in this tree, none of which mask anything.
14644    ///
14645    /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14646    /// built from a mesh's own level count rather than from the table's length —
14647    /// so a build that emitted a twin per mesh has more buckets than levels and
14648    /// this says so. And the twinned scenes below are asserted to be exactly as
14649    /// many times as long as they hold modes, or the comparison would pass on a
14650    /// renderer that had stopped twinning at all.
14651    ///
14652    /// # A twin per mode the scene **holds**, not per mode that exists
14653    ///
14654    /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14655    /// records one indirect call per bucket — so the rule that matters is which
14656    /// values the description's own materials carry. Two rows of two modes are
14657    /// two twins whichever two they are, and the pair below says so both ways:
14658    /// three modes across three rows is three, and three rows collapsed onto two
14659    /// *values* is two even though between them they set both mode bits.
14660    #[test]
14661    fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14662        use crcbl_shaders::mesh::GpuMaterial;
14663
14664        let (recorder, device, queue) = open();
14665        let device = device.as_ref();
14666        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14667        // The uniform-cut path, where a DAG is one bucket per level. The mesh
14668        // path folds a DAG into one bucket and reports no level buckets at all,
14669        // which would leave the oracle below empty.
14670        assert!(
14671            !renderer.emit.is_mesh(),
14672            "this preset built a mesh-shader path, whose level buckets are empty"
14673        );
14674        let levels: usize = (0..crate::scene::demo().meshes.len())
14675            .map(|mesh| renderer.level_buckets(mesh).len())
14676            .sum();
14677        assert!(levels > 0, "the demo has meshes, so it has levels");
14678        assert_eq!(
14679            renderer.bucket_constants.len(),
14680            levels,
14681            "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14682             twin: {levels} level(s) against {} bucket(s)",
14683            renderer.bucket_constants.len()
14684        );
14685        assert_eq!(
14686            renderer.bucket_modes,
14687            vec![0; levels],
14688            "and every one of them draws the OPAQUE mode"
14689        );
14690        let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14691        let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14692            .map(|mesh| renderer.level_buckets(mesh).to_vec())
14693            .collect();
14694        renderer.destroy(device);
14695        recorder.assert_valid();
14696
14697        // Every arrangement worth stating, as the modes its material rows carry
14698        // and the number of twins that has to produce. The demo has three rows;
14699        // a fourth is appended where four distinct modes are wanted, which
14700        // nothing instances and which therefore changes nothing but the mode
14701        // set.
14702        for (rows, modes, what) in [
14703            (
14704                vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14705                2,
14706                "one masked row beside two opaque ones",
14707            ),
14708            (
14709                vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14710                2,
14711                "one double-sided row beside two opaque ones",
14712            ),
14713            (
14714                vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14715                3,
14716                "a masked row, a double-sided one and an opaque one",
14717            ),
14718            (
14719                vec![
14720                    GpuMaterial::ALPHA_MODE_MASK,
14721                    GpuMaterial::DOUBLE_SIDED,
14722                    GpuMaterial::ALPHA_MODE_MASK,
14723                ],
14724                2,
14725                "three rows carrying two mode values between them — both mode bits are set \
14726                 somewhere and neither row is opaque, so a rule counting bits rather than \
14727                 values would say three",
14728            ),
14729            (
14730                vec![
14731                    0,
14732                    GpuMaterial::ALPHA_MODE_MASK,
14733                    GpuMaterial::DOUBLE_SIDED,
14734                    GpuMaterial::MODE_MASK,
14735                ],
14736                4,
14737                "one row of each mode, which is the only arrangement that pays for four",
14738            ),
14739        ] {
14740            let scene = {
14741                let mut scene = crate::scene::demo();
14742                while scene.materials.len() < rows.len() {
14743                    scene.materials.push(GpuMaterial::UNTINTED);
14744                }
14745                for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14746                    row.flags = *flags;
14747                }
14748                scene
14749            };
14750            let (recorder, device, queue) = open();
14751            let device = device.as_ref();
14752            let twinned =
14753                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14754                    .expect("the null backend accepts the demo description");
14755            assert_eq!(
14756                twinned.bucket_constants.len(),
14757                modes * levels,
14758                "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14759                 has {}",
14760                modes * levels,
14761                twinned.bucket_constants.len()
14762            );
14763            // The modes present, as a set — which is the claim, since the order
14764            // is `DEPTH_MODES`' and the count above already pins the length.
14765            let held: std::collections::BTreeSet<u32> =
14766                twinned.bucket_modes.iter().copied().collect();
14767            let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14768            assert_eq!(
14769                held, want,
14770                "{what}: the table twins the modes its materials carry and no others"
14771            );
14772            for mode in &held {
14773                assert_eq!(
14774                    twinned
14775                        .bucket_modes
14776                        .iter()
14777                        .filter(|held| *held == mode)
14778                        .count(),
14779                    levels,
14780                    "{what}: every mode present gets every mesh's levels once"
14781                );
14782            }
14783            // **Mode-major**: each held mode is one contiguous run of the
14784            // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14785            // partition is one range of buckets.
14786            let held_in_order: Vec<u32> = DEPTH_MODES
14787                .into_iter()
14788                .filter(|mode| held.contains(mode))
14789                .collect();
14790            assert_eq!(
14791                twinned.bucket_modes,
14792                held_in_order
14793                    .iter()
14794                    .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14795                    .collect::<Vec<_>>(),
14796                "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14797            );
14798            assert_eq!(
14799                twinned.draw_tables.bucket_meshes,
14800                opaque_meshes.repeat(held_in_order.len()),
14801                "{what}: each mode's run is the all-opaque table, mesh by mesh"
14802            );
14803            for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14804                assert_eq!(
14805                    twinned.level_buckets(mesh),
14806                    opaque.as_slice(),
14807                    "{what}: mesh {mesh}'s level buckets are the first mode's run"
14808                );
14809            }
14810            // And the `(mesh, mode) → bucket` lookup the scatter routes through
14811            // sends every key to its mode's run, at the mesh's own offset.
14812            let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14813                &twinned.draw_tables.bucket_meshes,
14814                &twinned.bucket_modes,
14815            )
14816            .expect("a small lookup");
14817            for (slot, mode) in held_in_order.iter().enumerate() {
14818                for (offset, mesh) in opaque_meshes.iter().enumerate() {
14819                    let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14820                    assert_eq!(
14821                        lookup[key as usize] as usize,
14822                        slot * levels + offset,
14823                        "{what}: mesh {mesh} in mode {mode}"
14824                    );
14825                }
14826            }
14827            twinned.destroy(device);
14828            recorder.assert_valid();
14829        }
14830    }
14831
14832    /// **The two pyramids differ in exactly one field, and it is the material
14833    /// id — which names a row holding a different colour and a different
14834    /// roughness.**
14835    ///
14836    /// The whole of what §3.2's table buys, stated as the two things that have
14837    /// to be true at once. Placed at the *same* transform, so "differ only in
14838    /// material" is literal rather than nearly: same mesh id, same matrix, same
14839    /// flags, and a `GpuInstance` comparison that would fail on any other
14840    /// field. And the ids they carry name rows the device actually holds —
14841    /// asserted on the bytes in the buffer, because a table the renderer agrees
14842    /// with itself about is not a table a shader can read.
14843    ///
14844    /// The two rows are asserted to differ, or the pair would be evidence of
14845    /// nothing: two instances naming two rows of the same colour draw the same
14846    /// picture whether or not either id was ever used.
14847    #[test]
14848    fn the_two_pyramids_differ_only_in_their_material() {
14849        let (recorder, device, queue) = open();
14850        let mut renderer =
14851            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14852        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14853        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14854        let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14855
14856        let instance = |handle: InstanceHandle| {
14857            renderer
14858                .instances
14859                .get(handle)
14860                .expect("the instance was inserted and is live")
14861        };
14862        let plain = instance(plain_handle);
14863        let tinted = instance(tinted_handle);
14864        assert_ne!(
14865            plain.material, tinted.material,
14866            "the two pyramids must not share a material row"
14867        );
14868        assert_eq!(
14869            mesh::GpuInstance {
14870                material: tinted.material,
14871                ..plain
14872            },
14873            tinted,
14874            "the two instances must differ in the material id and in nothing else"
14875        );
14876
14877        let bytes = recorder
14878            .buffer_bytes(renderer.materials.buffer())
14879            .expect("the table is live");
14880        let row = |index: u32| {
14881            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14882            mesh::GpuMaterial::from_bytes(
14883                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14884                    .try_into()
14885                    .expect("one row"),
14886            )
14887        };
14888        assert_eq!(
14889            row(plain.material),
14890            mesh::GpuMaterial::UNTINTED,
14891            "the plain pyramid's row must be the factor that changes nothing"
14892        );
14893        assert_eq!(
14894            row(tinted.material),
14895            mesh::GpuMaterial {
14896                base_color: scene::PYRAMID_TINT,
14897                roughness: scene::PYRAMID_ROUGHNESS,
14898                ..mesh::GpuMaterial::UNTINTED
14899            },
14900            "the tinted pyramid's row must be the tint and the tighter lobe"
14901        );
14902        // The shading half of that row, on its own: a roughness equal to the
14903        // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14904        // against itself, and that test would go green on a shader that had
14905        // never read the column.
14906        assert_ne!(
14907            row(plain.material).roughness,
14908            row(tinted.material).roughness,
14909            "the two rows must differ in roughness, or the highlight the render e2e measures \
14910             is not attributable to the material"
14911        );
14912        assert_ne!(
14913            row(plain.material),
14914            row(tinted.material),
14915            "two rows holding the same colour would make the pair prove nothing"
14916        );
14917        // And the tint is the *only* thing that differs between them: a row that
14918        // also changed its page layer would make this pair evidence about two
14919        // columns at once, which is what the third pyramid exists to avoid.
14920        assert_eq!(
14921            row(plain.material).base_color_texture,
14922            row(tinted.material).base_color_texture,
14923            "the factor pair must sample the same page layer"
14924        );
14925
14926        // And the second pyramid leaves the frame the way the first does: the
14927        // instance is removed, not a draw skipped.
14928        renderer.remove_instance(tinted_handle);
14929        assert!(
14930            renderer.instances.get(tinted_handle).is_none(),
14931            "the instance must be given back, or an object nobody asked for stays in the scene"
14932        );
14933
14934        renderer.destroy(device.as_ref());
14935    }
14936
14937    /// **The same claim one column along: the plain and textured pyramids
14938    /// differ in exactly one field, and the rows it names differ in exactly one
14939    /// column — the base-colour page layer.**
14940    ///
14941    /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14942    /// *texture indices* rather than its *factors*. The factors of the two rows
14943    /// are asserted **equal** here, which is the half that makes the pair
14944    /// evidence about the texture at all: a textured row that also carried a
14945    /// tint would draw a different picture for a reason the frame could not
14946    /// distinguish from the tinted pyramid's.
14947    ///
14948    /// The layer numbers are asserted against the page the renderer actually
14949    /// uploaded, so a row naming a layer that does not exist is caught here
14950    /// rather than as an out-of-range sample on a device.
14951    #[test]
14952    fn the_textured_pyramid_differs_only_in_its_page_layer() {
14953        let (recorder, device, queue) = open();
14954        let mut renderer =
14955            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14956        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14957        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14958        let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14959
14960        let instance = |handle: InstanceHandle| {
14961            renderer
14962                .instances
14963                .get(handle)
14964                .expect("the instance was inserted and is live")
14965        };
14966        let plain = instance(plain_handle);
14967        let textured = instance(textured_handle);
14968        assert_ne!(
14969            plain.material, textured.material,
14970            "the two pyramids must not share a material row"
14971        );
14972        assert_eq!(
14973            mesh::GpuInstance {
14974                material: textured.material,
14975                ..plain
14976            },
14977            textured,
14978            "the two instances must differ in the material id and in nothing else"
14979        );
14980
14981        let bytes = recorder
14982            .buffer_bytes(renderer.materials.buffer())
14983            .expect("the table is live");
14984        let row = |index: u32| {
14985            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14986            mesh::GpuMaterial::from_bytes(
14987                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14988                    .try_into()
14989                    .expect("one row"),
14990            )
14991        };
14992        assert_eq!(
14993            row(plain.material).base_color,
14994            row(textured.material).base_color,
14995            "the texture pair must share a factor, or the pair is evidence about both columns"
14996        );
14997        assert_eq!(
14998            row(plain.material).base_color_texture,
14999            mesh::GpuMaterial::NO_PAGE
15000        );
15001        assert_eq!(
15002            row(textured.material).base_color_texture,
15003            scene::CHECKER_LAYER
15004        );
15005        assert_ne!(
15006            row(plain.material),
15007            row(textured.material),
15008            "two rows naming the same layer would make the pair prove nothing"
15009        );
15010        // The layer that number names is a layer the page has, and it is not
15011        // one flat colour — a checker of one repeated texel would pass every
15012        // assertion above and draw the picture the untextured row draws.
15013        let page = scene::demo().page;
15014        let layers = page.layers(PageKind::BaseColor);
15015        assert!(
15016            (scene::CHECKER_LAYER as usize) < layers.len(),
15017            "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
15018             nothing below the seam would report",
15019            scene::CHECKER_LAYER,
15020            layers.len()
15021        );
15022        let checker = &layers[scene::CHECKER_LAYER as usize];
15023        assert!(
15024            checker
15025                .as_chunks::<4>()
15026                .0
15027                .iter()
15028                .any(|texel| texel != &checker[..4]),
15029            "a flat checker layer would shade the textured row exactly as the untextured \
15030             one shades, and the pair would prove nothing"
15031        );
15032
15033        renderer.remove_instance(textured_handle);
15034        assert!(
15035            renderer.instances.get(textured_handle).is_none(),
15036            "the instance must be given back, or an object nobody asked for stays in the scene"
15037        );
15038
15039        renderer.destroy(device.as_ref());
15040    }
15041
15042    /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
15043    /// and a third again for its chain.
15044    ///
15045    /// This is what row (d) bought, and it is the half of it no picture can
15046    /// show: the frame a scene with no normal map draws is byte-identical either
15047    /// way, because `mesh.slang` returns before it fetches. What changes is the
15048    /// image the renderer created, and the copies into it are where that is
15049    /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
15050    /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
15051    /// is the device-side half saying the frame did not move.
15052    ///
15053    /// [`scene::demo`] is the scene: every one of its rows carries
15054    /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
15055    /// the description every golden in this tree is a variation of.
15056    ///
15057    /// # Sabotage
15058    ///
15059    /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
15060    /// and its chain instead of the placeholder — the shape this replaced. Red
15061    /// on 2026-09-06 with `"a description with no normal map must upload the
15062    /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
15063    /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
15064    /// extent² × 4 bytes and a third again for its chain, on every scene in the
15065    /// tree"`.
15066    #[test]
15067    fn a_page_kind_nothing_names_costs_one_texel() {
15068        use crcbl_hal::null::Command;
15069
15070        let scene = scene::demo();
15071        assert!(
15072            scene
15073                .materials
15074                .iter()
15075                .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
15076            "a row naming a normal layer would make the description one that *does* name \
15077             the page, and this test would be about the other case"
15078        );
15079        assert!(
15080            scene.page.layers(PageKind::Normal).is_empty()
15081                && scene.page.extent(PageKind::BaseColor) > 1,
15082            "the description must name no normal layer while naming base-colour ones, or \
15083             a placeholder-sized copy says nothing about which page it landed in"
15084        );
15085
15086        let (recorder, device, queue) = open();
15087        let renderer =
15088            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
15089                .expect("a description naming no normal page is one this can make resident");
15090
15091        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
15092            .commands()
15093            .into_iter()
15094            .filter_map(|command| match command {
15095                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
15096                    Some(copy)
15097                }
15098                _ => None,
15099            })
15100            .collect();
15101        let extents: Vec<crcbl_hal::Extent3d> =
15102            copies.iter().map(|copy| copy.image_extent).collect();
15103        assert_eq!(
15104            extents,
15105            vec![crcbl_hal::Extent3d::d2(1, 1)],
15106            "a description with no normal map must upload the one-texel placeholder, and \
15107             this copied {} level(s) at {extents:?} — a burned neutral layer costs \
15108             extent² × 4 bytes and a third again for its chain, on every scene in the tree",
15109            copies.len()
15110        );
15111
15112        // The placeholder is one layer, and the graph declaration says so: a
15113        // caller importing this page to write a layer of its own would get
15114        // `ImportDeclarationConflict` against an extent that was not 1×1.
15115        assert_eq!(
15116            renderer.normal_page_import().extent,
15117            (1, 1),
15118            "the declaration names the placeholder's extent, not the base-colour page's"
15119        );
15120        renderer.destroy(device.as_ref());
15121    }
15122
15123    /// **A page and a material table that are the caller's own, not
15124    /// [`scene::demo`]'s**: a different extent per kind, more layers than the
15125    /// demo page holds, a normal page the demo does not have at all, and rows
15126    /// past the three the demo writes.
15127    ///
15128    /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
15129    /// at most — so until this nothing had put an app-supplied *layer* or an
15130    /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
15131    /// build that uploaded the demo's two layers and stopped, or that inserted
15132    /// its three rows and stopped, would leave every golden byte-identical and
15133    /// pass every other assertion in this module: the demo scene cannot tell a
15134    /// table filled from the description from one filled up to the description's
15135    /// third row.
15136    ///
15137    /// Read off the recorder rather than off the description, because the
15138    /// description is the input. The copies are what reached the image and the
15139    /// table buffer is what the shader indexes, and neither is a restatement of
15140    /// what was handed in.
15141    #[test]
15142    fn an_app_page_and_table_reach_the_device_whole() {
15143        use crcbl_hal::null::Command;
15144
15145        /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
15146        /// rather than read off the page shows up as a copy of the wrong size.
15147        const APP_EXTENT: u32 = 4;
15148
15149        /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
15150        /// extent bought: a renderer that still sized the normal page from the
15151        /// base-colour page's number would copy this layer at 4² and the copy
15152        /// list below would say so.
15153        const APP_NORMAL_EXTENT: u32 = 2;
15154        let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
15155
15156        // Three base-colour layers, each flat and each a value of its own: a
15157        // build that uploaded one layer twice, or that stopped short, is a
15158        // different sequence of copies. Then one normal layer at the other
15159        // extent, which the demo scene has no page for at all.
15160        let mut page = scene::PageDesc::empty();
15161        page.set_extent(PageKind::BaseColor, APP_EXTENT);
15162        page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
15163        let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
15164            .into_iter()
15165            .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
15166            .collect();
15167        let app_normal = page.push_layer(
15168            PageKind::Normal,
15169            scene::PageDesc::NEUTRAL_NORMAL
15170                .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
15171        );
15172
15173        let mut scene = scene::demo();
15174        scene.page = page;
15175        // One row per appended layer, and each with a factor of its own as well,
15176        // so a row that landed at another row's id is not a row that happens to
15177        // look like it. The last of them names the normal layer too, so the
15178        // table carries a row through both pages.
15179        for (nth, &layer) in app_layers.iter().enumerate() {
15180            let shade = 0.25 * (nth as f32 + 1.0);
15181            let last = nth + 1 == app_layers.len();
15182            scene.materials.push(mesh::GpuMaterial {
15183                base_color: [shade, shade, shade, 1.0],
15184                base_color_texture: layer,
15185                normal_texture: if last {
15186                    app_normal
15187                } else {
15188                    mesh::GpuMaterial::NO_PAGE
15189                },
15190                ..mesh::GpuMaterial::UNTINTED
15191            });
15192        }
15193        assert!(
15194            scene.materials.len() > scene::demo().materials.len()
15195                && scene.page.layers(PageKind::BaseColor).len()
15196                    > scene::demo().page.layers(PageKind::BaseColor).len(),
15197            "the description under test must exceed the demo's in both, or this is a \
15198             demo test wearing another name"
15199        );
15200        assert_eq!(
15201            scene::demo().page.extent(PageKind::Normal),
15202            0,
15203            "the demo scene must name no normal page, or the normal copies below are \
15204             evidence about the demo's page rather than the caller's"
15205        );
15206
15207        let (recorder, device, queue) = open();
15208        let mut renderer =
15209            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
15210                .expect("a page and a table of the caller's own are ones this can make resident");
15211
15212        // The page, layer by layer. Filtered by image because the build uploads
15213        // the ambient-occlusion placeholder through the same path.
15214        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
15215            .commands()
15216            .into_iter()
15217            .filter_map(|command| match command {
15218                Command::CopyBufferToImage(copy)
15219                    if copy.image == renderer.base_color_page.image =>
15220                {
15221                    Some(copy)
15222                }
15223                _ => None,
15224            })
15225            .collect();
15226        // Every layer goes up with its chain — three levels for this extent —
15227        // so the copies are layer-major, level-minor, each at its level's own
15228        // extent.
15229        let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
15230            .full_mip_levels(crcbl_hal::ImageType::D2);
15231        assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
15232        let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
15233            .expect("a page of a few layers");
15234        assert_eq!(
15235            copies
15236                .iter()
15237                .map(|copy| (
15238                    copy.image_subresource.base_layer,
15239                    copy.image_subresource.mip
15240                ))
15241                .collect::<Vec<(u32, u32)>>(),
15242            (0..layer_count)
15243                .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
15244                .collect::<Vec<(u32, u32)>>(),
15245            "every level of every layer the description carries must be copied into the page, \
15246             in order"
15247        );
15248        assert!(
15249            copies.iter().all(|copy| {
15250                let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
15251                copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
15252            }),
15253            "the page is the extent the caller wrote, not the demo's, halved per level: \
15254             {copies:?}"
15255        );
15256
15257        // The normal page, at **its own** extent. One layer, two levels for a
15258        // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
15259        // that carried one extent for both kinds would put this layer up at 4².
15260        let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
15261            .commands()
15262            .into_iter()
15263            .filter_map(|command| match command {
15264                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
15265                    Some(copy)
15266                }
15267                _ => None,
15268            })
15269            .collect();
15270        let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
15271            .full_mip_levels(crcbl_hal::ImageType::D2);
15272        assert_eq!(
15273            normal_copies
15274                .iter()
15275                .map(|copy| (
15276                    copy.image_subresource.base_layer,
15277                    copy.image_subresource.mip,
15278                    copy.image_extent
15279                ))
15280                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
15281            (0..normal_levels)
15282                .map(|level| {
15283                    let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
15284                    (0, level, crcbl_hal::Extent3d::d2(side, side))
15285                })
15286                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
15287            "the normal page is the extent the caller wrote for *that* kind, halved per \
15288             level: {normal_copies:?}"
15289        );
15290        assert_eq!(
15291            renderer.normal_page_import().extent,
15292            (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
15293            "the graph declaration names the normal page's own extent, or a caller \
15294             importing it to write a layer gets ImportDeclarationConflict"
15295        );
15296        assert_eq!(
15297            renderer.base_color_page_import().extent,
15298            (APP_EXTENT, APP_EXTENT),
15299            "and the base-colour declaration names its own, which is a different number"
15300        );
15301
15302        // The table, row by row, out of the buffer `mesh.slang` indexes.
15303        let bytes = recorder
15304            .buffer_bytes(renderer.materials.buffer())
15305            .expect("the table is live");
15306        let row = |id: u32| {
15307            let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
15308            mesh::GpuMaterial::from_bytes(
15309                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
15310                    .try_into()
15311                    .expect("one row"),
15312            )
15313        };
15314        assert_eq!(
15315            renderer.material_ids.len(),
15316            scene.materials.len(),
15317            "one id per description row, whatever the count"
15318        );
15319        for (index, wrote) in scene.materials.iter().enumerate() {
15320            assert_eq!(
15321                &row(renderer.material_ids[index]),
15322                wrote,
15323                "description row {index} must be the row its id names"
15324            );
15325        }
15326
15327        // And a caller can place an object through a row only its own
15328        // description has, which is the whole point of the rows being the
15329        // caller's.
15330        let last = scene.materials.len() - 1;
15331        let handle = renderer
15332            .add_instance(&InstanceDesc {
15333                mesh: DEMO_CUBE,
15334                material: last,
15335                transform: Mat4::IDENTITY,
15336            })
15337            .expect("an empty pool of thousands has room for one object");
15338        assert_eq!(
15339            renderer
15340                .instances
15341                .get(handle)
15342                .expect("a just-added instance is live")
15343                .material,
15344            renderer.material_ids[last],
15345            "an InstanceDesc's material index resolves through the description, not \
15346             through a table id the caller cannot know"
15347        );
15348
15349        renderer.destroy(device.as_ref());
15350        recorder.assert_valid();
15351    }
15352
15353    /// **The frame records two compute dispatches and exactly one indirect draw
15354    /// per bucket — whatever is in the scene.**
15355    ///
15356    /// The property topic 03 opens with, checked on the recorded command stream:
15357    /// adding the pyramid adds an instance and changes no command. A pass that
15358    /// had kept a draw per object would record one command here and two there,
15359    /// which is what this used to assert and what the indirect path replaced.
15360    ///
15361    /// It also pins the arguments each call names: bucket `n` reads the `n`-th
15362    /// argument structure and the `n`-th count, at the stride every API fixed.
15363    /// Two calls pointing at one structure is a frame that draws one object
15364    /// twice.
15365    #[test]
15366    fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
15367        use crcbl_hal::null::Command;
15368
15369        for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
15370            let (recorder, device, queue) = open();
15371            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15372                .expect("built");
15373            // The cube in both scenes, so the difference between them is the
15374            // pyramid alone. It also keeps both frames non-empty, and an empty
15375            // one would be a weaker comparison than this claims: `cull`'s
15376            // dispatch covers no workgroups when the pool is empty, and the pass
15377            // records nothing rather than a dispatch of zero — see
15378            // [`DrawGen::add_passes`].
15379            place_cube(&mut renderer, Mat4::IDENTITY);
15380            if let Some(at) = pyramid {
15381                place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
15382            }
15383            let frame = frame(device.as_ref(), &mut renderer, queue);
15384
15385            let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
15386            let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
15387                .map(|bucket| {
15388                    (
15389                        renderer.bucket_constants[bucket],
15390                        bucket as u64 * u64::from(stride),
15391                        bucket as u64 * 4,
15392                    )
15393                })
15394                .collect();
15395
15396            // The dynamic offset last bound before each draw, paired with the
15397            // offsets that draw read its arguments and its count from.
15398            let mut offset = None;
15399            let mut seen: Vec<(u32, u64, u64)> = Vec::new();
15400            let mut dispatches = 0;
15401            for command in recorder.commands() {
15402                if matches!(command, Command::Dispatch { .. }) {
15403                    dispatches += 1;
15404                }
15405            }
15406            for command in commands_in_pass(&recorder, "forward") {
15407                match command {
15408                    Command::BindGroup {
15409                        slot: 0,
15410                        dynamic_offsets,
15411                        ..
15412                    } => offset = dynamic_offsets.first().copied(),
15413                    Command::DrawIndexedIndirectCount(draw) => {
15414                        assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
15415                        assert_eq!(
15416                            draw.max_draw_count, 1,
15417                            "one argument structure per bucket, so one is the ceiling"
15418                        );
15419                        seen.push((
15420                            offset.expect("a draw is preceded by its constant block"),
15421                            draw.args_offset,
15422                            draw.count_offset,
15423                        ));
15424                    }
15425                    Command::DrawIndexed { .. } => {
15426                        panic!("the forward pass must not record a CPU-counted draw any more")
15427                    }
15428                    _ => {}
15429                }
15430            }
15431            assert_eq!(
15432                dispatches,
15433                DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
15434                "the clearing pass, the cull pass and the draw-argument pass's three, in \
15435                 front of the draws — once for the camera and once per shadow cascade — plus \
15436                 topic 18's one clustering dispatch, which is the camera's alone because a \
15437                 cascade shades nothing, plus the resolve's own"
15438            );
15439            assert_eq!(
15440                seen, expected,
15441                "with pyramid = {pyramid:?}, the pass must record one indirect call per \
15442                 bucket, each pointing at its own arguments, its own count and its own \
15443                 block"
15444            );
15445
15446            frame.finish(device.as_ref(), renderer);
15447        }
15448    }
15449
15450    /// **The two `GeometryPath` arms record different calls and nothing else
15451    /// differs.**
15452    ///
15453    /// A device with a GPU-side count takes it from GPU memory; one without —
15454    /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
15455    /// bucket's one argument structure unconditionally. Same buckets, same
15456    /// arguments, same block: the tail is the only thing that moves, which is
15457    /// what topic 03 means by "the lesser path is
15458    /// a constraint on data layout, not a separate renderer".
15459    ///
15460    /// Both presets are run here rather than only the one this machine has,
15461    /// because the arm a device never selects is the arm nothing tests.
15462    #[test]
15463    fn each_geometry_path_records_its_own_indirect_call() {
15464        use crcbl_hal::null::Command;
15465
15466        for (preset, path, counted) in [
15467            (
15468                NullInstance::gpu_driven(),
15469                GeometryPath::IndirectCount,
15470                true,
15471            ),
15472            (
15473                NullInstance::portable(),
15474                GeometryPath::IndirectPerBatch,
15475                false,
15476            ),
15477        ] {
15478            let recorder = Recorder::new();
15479            let instance = preset.with_recorder(recorder.clone());
15480            let adapter = instance.adapters().remove(0);
15481            assert_eq!(
15482                instance
15483                    .adapter_caps(adapter.id)
15484                    .expect("the null backend describes its adapter")
15485                    .geometry_path(),
15486                path,
15487                "the preset must select the path this arm is about"
15488            );
15489            // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
15490            // portable preset does not have; the forward pass does not need one
15491            // either, so this asks for what it uses. The optional set matters:
15492            // a device is opened with the features it *asked* for, and the path
15493            // is derived from those rather than from the adapter's.
15494            let device = instance
15495                .create_device(&DeviceDesc {
15496                    label: None,
15497                    adapter: adapter.id,
15498                    required_features: Features::COMPUTE,
15499                    optional_features: Features::GPU_DRIVEN,
15500                    compatible_surface: None,
15501                })
15502                .expect("the null backend always opens");
15503            assert_eq!(
15504                device.caps().geometry_path(),
15505                path,
15506                "and the opened device still selects it"
15507            );
15508            let queue = device.queue(QueueKind::Graphics).expect("always present");
15509            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15510                .expect("built");
15511            let frame = frame(device.as_ref(), &mut renderer, queue);
15512
15513            let mut counted_calls = 0;
15514            let mut per_batch_calls = 0;
15515            for command in commands_in_pass(&recorder, "forward") {
15516                match command {
15517                    Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
15518                    Command::DrawIndexedIndirect(draw) => {
15519                        assert_eq!(
15520                            draw.draw_count, 1,
15521                            "one argument structure per bucket, read unconditionally"
15522                        );
15523                        per_batch_calls += 1;
15524                    }
15525                    _ => {}
15526                }
15527            }
15528            let buckets = renderer.bucket_constants.len();
15529            let (expected_counted, expected_per_batch) =
15530                if counted { (buckets, 0) } else { (0, buckets) };
15531            assert_eq!(
15532                (counted_calls, per_batch_calls),
15533                (expected_counted, expected_per_batch),
15534                "{path:?} must record one call of its own kind per bucket and none of the other"
15535            );
15536
15537            frame.finish(device.as_ref(), renderer);
15538        }
15539    }
15540
15541    /// Serialises the two checks that move
15542    /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
15543    /// afterwards.
15544    ///
15545    /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
15546    /// `cargo test` runs a crate's tests as threads of *one* process: two checks
15547    /// that move the switch are then two writers to one cell, which shows up as
15548    /// a flake rather than as a failure anybody can read.
15549    /// `crcbl::debug_view::for_test` is the same shape one crate up and there
15550    /// for the same reason; this one is smaller because nothing outside these
15551    /// two tests ever writes the cell.
15552    fn debug_draw_switch() -> DebugDrawSwitch {
15553        let guard = DEBUG_DRAW_SWITCH
15554            .lock()
15555            .unwrap_or_else(std::sync::PoisonError::into_inner);
15556        let switch = DebugDrawSwitch { _guard: guard };
15557        switch.set(false);
15558        switch
15559    }
15560
15561    /// What [`debug_draw_switch`] hands back: the switch is this thread's until
15562    /// it drops, and it goes back off when it does.
15563    struct DebugDrawSwitch {
15564        _guard: std::sync::MutexGuard<'static, ()>,
15565    }
15566
15567    impl DebugDrawSwitch {
15568        /// Moves the switch.
15569        fn set(&self, on: bool) {
15570            crate::debug_draw::r_debug_draw
15571                .set(&crcbl_console::Value::Bool(on))
15572                .expect("`r_debug_draw` is a writable bool");
15573        }
15574    }
15575
15576    impl Drop for DebugDrawSwitch {
15577        fn drop(&mut self) {
15578            // Off at both ends, so a check that panicked mid-way does not hand
15579            // the next holder a switched-on layer.
15580            self.set(false);
15581        }
15582    }
15583
15584    /// [`debug_draw_switch`]'s lock.
15585    ///
15586    /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
15587    /// both — see that function for what the opposite order cost.
15588    static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15589
15590    /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
15591    /// default when the guard drops.
15592    ///
15593    /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
15594    /// `cargo test` run shares one process between tests, and a variable this
15595    /// one left moved is a frame the next test did not ask for.
15596    ///
15597    /// **Every test whose assertion depends on the shape of a frame takes this,
15598    /// not only the one that moves the count.** The variable is a process
15599    /// global and `cargo test` runs this module's tests on threads that share
15600    /// it, so a frame built while
15601    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
15602    /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
15603    /// that the test building it never asked for. Taking the guard both
15604    /// serialises against that test and pins the count for the frames this one
15605    /// builds.
15606    ///
15607    /// Two shapes need it, and the second is easy to miss. A test comparing a
15608    /// frame against a **literal pass list** breaks whenever the count is two.
15609    /// A test comparing **two frames it built itself** — a difference in draws,
15610    /// an equality between pass lists, a "one pass longer" claim — breaks only
15611    /// when the count *moves between them*, which is a narrower window and why
15612    /// this reproduced at roughly one run in eight rather than every run.
15613    ///
15614    /// Both were established by experiment on 2026-09-01 rather than by
15615    /// reading: pinning the count at two reddens the first shape, and making
15616    /// `crate::ssao::blur_passes` alternate reddens the second.
15617    ///
15618    /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15619    /// These are two plain mutexes with no ordering between them, so two tests
15620    /// acquiring both in opposite orders deadlock — which is not a hazard this
15621    /// comment is guessing at: adding the guard to the two debug-draw tests
15622    /// above their existing one did exactly that on 2026-09-01, and turned a
15623    /// 0.2 second suite into one that had not finished in ten minutes. It is
15624    /// invisible in a single-threaded run, where the same suite passes in a
15625    /// second, so `--test-threads=1` is not a check for it.
15626    ///
15627    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15628    pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15629        let guard = SSAO_BLUR_SWITCH
15630            .lock()
15631            .unwrap_or_else(std::sync::PoisonError::into_inner);
15632        let switch = SsaoBlurSwitch { _guard: guard };
15633        switch.set(1);
15634        switch
15635    }
15636
15637    /// What [`ssao_blur_switch`] hands back.
15638    pub(super) struct SsaoBlurSwitch {
15639        _guard: std::sync::MutexGuard<'static, ()>,
15640    }
15641
15642    impl SsaoBlurSwitch {
15643        /// Asks for `passes` of them.
15644        fn set(&self, passes: i64) {
15645            crate::ssao::r_ssao_blur_passes
15646                .set(&crcbl_console::Value::Int(passes))
15647                .expect("`r_ssao_blur_passes` is a writable int in range");
15648        }
15649    }
15650
15651    impl Drop for SsaoBlurSwitch {
15652        fn drop(&mut self) {
15653            // Back to the shipping count at both ends, so a check that panicked
15654            // mid-way does not hand the next holder a three-pass frame.
15655            self.set(1);
15656        }
15657    }
15658
15659    /// [`ssao_blur_switch`]'s lock.
15660    static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15661
15662    /// Takes `r_ssao_split` for this thread and puts it back when the guard
15663    /// drops.
15664    ///
15665    /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15666    /// makes the occlusion chain record its second march, so a test about the
15667    /// widest frame a renderer can produce has to hold this as well as the blur
15668    /// count — see `crate::ssao`'s `r_ssao_split`.
15669    ///
15670    /// **Every test comparing [`ForwardRenderer::counters`]' draws with
15671    /// [`recorded_draws`] takes this too**, because that march is a draw the
15672    /// counters leave out (`Ssao::passes` says why): a frame built while
15673    /// another test holds a seam records one draw more than it counts. Found
15674    /// on 2026-11-01 by the mesh-tail test reading 13 against 14 under a
15675    /// threaded `cargo test`, and confirmed by a seam on by default reddening
15676    /// every such test that did not hold this.
15677    pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15678        let guard = SSAO_SPLIT_SWITCH
15679            .lock()
15680            .unwrap_or_else(std::sync::PoisonError::into_inner);
15681        let switch = SsaoSplitSwitch { _guard: guard };
15682        switch.set(0.0);
15683        switch
15684    }
15685
15686    /// What [`ssao_split_switch`] hands back.
15687    pub(super) struct SsaoSplitSwitch {
15688        _guard: std::sync::MutexGuard<'static, ()>,
15689    }
15690
15691    impl SsaoSplitSwitch {
15692        /// Asks for a seam at `at`, or for none at zero.
15693        fn set(&self, at: f32) {
15694            crate::ssao::r_ssao_split
15695                .set(&crcbl_console::Value::Float(at))
15696                .expect("`r_ssao_split` is a writable float in range");
15697        }
15698    }
15699
15700    impl Drop for SsaoSplitSwitch {
15701        fn drop(&mut self) {
15702            // Back to the default at both ends, so a check that panicked
15703            // mid-way does not hand the next holder a comparing frame.
15704            self.set(0.0);
15705        }
15706    }
15707
15708    /// [`ssao_split_switch`]'s lock.
15709    ///
15710    /// **Third in the lock order**: after [`DEBUG_DRAW_SWITCH`] and
15711    /// [`SSAO_BLUR_SWITCH`], and before [`SSAO_SLICE_SWITCH`],
15712    /// `crate::ssao::TECHNIQUE_SWITCH` and `crate::shadow::FILTER_SWITCH`.
15713    static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15714
15715    /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15716    /// them both back at their defaults when the guard drops.
15717    ///
15718    /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15719    /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15720    /// is where that is argued, and why the lock lives there rather than beside
15721    /// this function: `crate::shadow`'s own tests move the same two.
15722    fn shadow_filter_switch() -> ShadowFilterSwitch {
15723        let guard = crate::shadow::FILTER_SWITCH
15724            .lock()
15725            .unwrap_or_else(std::sync::PoisonError::into_inner);
15726        let switch = ShadowFilterSwitch { _guard: guard };
15727        switch.reset();
15728        switch
15729    }
15730
15731    /// What [`shadow_filter_switch`] hands back.
15732    struct ShadowFilterSwitch {
15733        _guard: std::sync::MutexGuard<'static, ()>,
15734    }
15735
15736    impl ShadowFilterSwitch {
15737        /// Asks for `filter` on the near side of the seam.
15738        fn filter(&self, filter: shadow::Filter) {
15739            crate::shadow::r_shadow_filter
15740                .set(&crcbl_console::Value::Enum(filter.label()))
15741                .expect("`r_shadow_filter` is a writable enum in the set");
15742        }
15743
15744        /// Asks for a seam at `at`, or for none at zero.
15745        fn seam(&self, at: f32) {
15746            crate::shadow::r_shadow_split
15747                .set(&crcbl_console::Value::Float(at))
15748                .expect("`r_shadow_split` is a writable float in range");
15749        }
15750
15751        /// Asks for `texels` of constant bias.
15752        fn bias(&self, texels: f32) {
15753            crate::shadow::r_shadow_bias
15754                .set(&crcbl_console::Value::Float(texels))
15755                .expect("`r_shadow_bias` is a writable float in range");
15756        }
15757
15758        /// Asks for `texels` of normal offset.
15759        fn offset(&self, texels: f32) {
15760            crate::shadow::r_shadow_normal_offset
15761                .set(&crcbl_console::Value::Float(texels))
15762                .expect("`r_shadow_normal_offset` is a writable float in range");
15763        }
15764
15765        /// Back to the frame every golden was blessed as.
15766        fn reset(&self) {
15767            self.filter(shadow::shipped_filter());
15768            self.seam(0.0);
15769            self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15770            self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15771        }
15772    }
15773
15774    /// The float `var` declares as its default — what a frame nobody typed at
15775    /// is drawn with, read off the variable rather than written down here.
15776    fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15777        match var.default() {
15778            crcbl_console::Value::Float(shipped) => *shipped,
15779            other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15780        }
15781    }
15782
15783    impl Drop for ShadowFilterSwitch {
15784        fn drop(&mut self) {
15785            // Back to the defaults at both ends, so a check that panicked
15786            // mid-way does not hand the next holder a comparing frame.
15787            self.reset();
15788        }
15789    }
15790
15791    /// Takes `r_ssao_slices` for this thread and puts it back at its default
15792    /// when the guard drops.
15793    ///
15794    /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15795    /// `cargo test` run shares one process between tests, and a variable this
15796    /// one left moved is a frame the next test did not ask for.
15797    fn ssao_slice_switch() -> SsaoSliceSwitch {
15798        let guard = SSAO_SLICE_SWITCH
15799            .lock()
15800            .unwrap_or_else(std::sync::PoisonError::into_inner);
15801        let switch = SsaoSliceSwitch { _guard: guard };
15802        switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15803        switch
15804    }
15805
15806    /// What [`ssao_slice_switch`] hands back.
15807    struct SsaoSliceSwitch {
15808        _guard: std::sync::MutexGuard<'static, ()>,
15809    }
15810
15811    impl SsaoSliceSwitch {
15812        /// Asks each pixel for `slices` of them.
15813        fn set(&self, slices: i64) {
15814            crate::ssao::r_ssao_slices
15815                .set(&crcbl_console::Value::Int(slices))
15816                .expect("`r_ssao_slices` is a writable int in range");
15817        }
15818    }
15819
15820    impl Drop for SsaoSliceSwitch {
15821        fn drop(&mut self) {
15822            // Back to the shipping count at both ends, so a check that panicked
15823            // mid-way does not hand the next holder a four-slice frame — which
15824            // is a frame every golden in this workspace was blessed without.
15825            self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15826        }
15827    }
15828
15829    /// [`ssao_slice_switch`]'s lock.
15830    static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15831
15832    /// Takes `r_ssao_technique` for this thread and puts it back at its default
15833    /// when the guard drops.
15834    ///
15835    /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15836    /// a **pipeline** rather than a lane of a uniform block, so a frame that
15837    /// picked it up from another thread's test gathers through a shader that
15838    /// test never selected.
15839    ///
15840    /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15841    /// it is the one switch here whose does: `ssao`'s own
15842    /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15843    /// variable, and a second mutex would serialise neither against the other.
15844    /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15845    fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15846        let guard = crate::ssao::TECHNIQUE_SWITCH
15847            .lock()
15848            .unwrap_or_else(std::sync::PoisonError::into_inner);
15849        let switch = SsaoTechniqueSwitch { _guard: guard };
15850        switch.set(shipped_technique_name());
15851        switch
15852    }
15853
15854    /// The technique name the chain ships, and the one
15855    /// [`ssao_technique_switch`] restores.
15856    ///
15857    /// **Read off the variable rather than written down**, which is
15858    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15859    /// rule about the slice count and for its reason: which value ships is a
15860    /// thing that moves, and a test naming the wrong one would be comparing the
15861    /// shipped configuration against itself.
15862    ///
15863    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15864    fn shipped_technique_name() -> &'static str {
15865        match crate::ssao::r_ssao_technique.default() {
15866            crcbl_console::Value::Enum(name) => name,
15867            other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15868        }
15869    }
15870
15871    /// A name from the variable's own set that is **not** the one it ships.
15872    ///
15873    /// [`shipped_technique_name`]'s clause from the other side: the tests below
15874    /// need a technique to move the console to, and picking it out of the
15875    /// declared set is what keeps them from naming one the variable does not
15876    /// offer — or, if a third arrived, from silently going on comparing the
15877    /// same two.
15878    fn other_technique_name() -> &'static str {
15879        let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15880            panic!("`r_ssao_technique` is an enum variable");
15881        };
15882        let ships = shipped_technique_name();
15883        names
15884            .iter()
15885            .copied()
15886            .find(|name| *name != ships)
15887            .expect("`r_ssao_technique` offers a technique other than the one it ships")
15888    }
15889
15890    /// What [`ssao_technique_switch`] hands back.
15891    struct SsaoTechniqueSwitch {
15892        _guard: std::sync::MutexGuard<'static, ()>,
15893    }
15894
15895    impl SsaoTechniqueSwitch {
15896        /// Asks for the gather `name` selects.
15897        fn set(&self, name: &'static str) {
15898            crate::ssao::r_ssao_technique
15899                .set(&crcbl_console::Value::Enum(name))
15900                .expect("`r_ssao_technique` is a writable enum in the set");
15901        }
15902    }
15903
15904    impl Drop for SsaoTechniqueSwitch {
15905        fn drop(&mut self) {
15906            // Back to what ships at both ends, so a check that panicked mid-way
15907            // does not hand the next holder a frame gathered through the cheap
15908            // tier — which is a frame no golden in this workspace was blessed
15909            // on.
15910            self.set(shipped_technique_name());
15911        }
15912    }
15913
15914    /// Every draw the recorded stream holds, whichever call recorded it.
15915    ///
15916    /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15917    /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15918    /// the thing to compare it against is the whole frame.
15919    fn recorded_draws(recorder: &Recorder) -> usize {
15920        use crcbl_hal::null::Command;
15921
15922        recorder
15923            .commands()
15924            .into_iter()
15925            .filter(|command| {
15926                matches!(
15927                    command,
15928                    Command::Draw { .. }
15929                        | Command::DrawIndexed { .. }
15930                        | Command::DrawIndirect(_)
15931                        | Command::DrawIndexedIndirect(_)
15932                        | Command::DrawIndirectCount(_)
15933                        | Command::DrawIndexedIndirectCount(_)
15934                        | Command::DrawMeshTasks { .. }
15935                        | Command::DrawMeshTasksIndirect(_)
15936                )
15937            })
15938            .count()
15939    }
15940
15941    /// **The draw count is what the frame recorded, and the two GPU-side
15942    /// counters are `None` rather than a guess.**
15943    ///
15944    /// Both halves matter and both are checked here against something that
15945    /// moves. The draws are compared with the recorded stream, so a count that
15946    /// forgot the shadow pass's share or the tonemap's triangle fails. The
15947    /// instances are read before and after a pyramid is put in the pool, so a
15948    /// counter wired to a constant — or to the pool's *capacity*, which does not
15949    /// move — fails too.
15950    ///
15951    /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15952    /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15953    /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15954    /// number invented before any readback landed. That is the assertion that
15955    /// catches the tempting version of this method: an instance count taken from
15956    /// the pool and reported as "drawn" would read as a culling win of exactly
15957    /// zero on every frame, which is the number the whole cull exists to change.
15958    /// What happens once the ring *has* come round is the test below.
15959    #[test]
15960    fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15961        let _blurs = ssao_blur_switch();
15962        let _seam = ssao_split_switch();
15963        let (recorder, device, queue) = open();
15964        let mut renderer =
15965            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15966
15967        // Before any frame: nothing recorded, and said as a known zero.
15968        assert_eq!(renderer.counters(), FrameCounters::default());
15969
15970        let first = frame(device.as_ref(), &mut renderer, queue);
15971        let counters = renderer.counters();
15972        assert_eq!(
15973            counters.draws,
15974            recorded_draws(&recorder) as u64,
15975            "the counter and the frame's recorded draws disagree",
15976        );
15977        // Derived from what the frame resolved rather than from a constant, so
15978        // this is still the every-effect frame's count and would follow a frame
15979        // that switched one off.
15980        let fullscreen = fullscreen_passes(
15981            renderer.effects(),
15982            TEST_EXTENT,
15983            false,
15984            renderer.frame_ssao_blurs,
15985        ) * FULLSCREEN_DRAWS;
15986        assert!(
15987            counters.draws > fullscreen,
15988            "a frame that recorded only its full-screen passes drew no scene",
15989        );
15990        assert_eq!(
15991            counters.instances,
15992            renderer.instances.len() as u64 + fullscreen,
15993        );
15994        assert_eq!(
15995            counters.drawn, None,
15996            "the ring has not come round, so there is no survivor count yet",
15997        );
15998        assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
15999        assert_eq!(counters.triangles, None);
16000        first.release(device.as_ref());
16001
16002        // A second scene: one more instance in the pool, and the counter moves
16003        // with it. The draws do not — one call per bucket whatever the scene
16004        // holds is what §3.3 is about, and this is where that shows.
16005        place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
16006        recorder.clear();
16007        let second = frame(device.as_ref(), &mut renderer, queue);
16008        let richer = renderer.counters();
16009        assert_eq!(
16010            richer.instances,
16011            counters.instances + 1,
16012            "an instance added to the pool must move the counter",
16013        );
16014        assert_eq!(
16015            richer.draws, counters.draws,
16016            "the recorded call count is independent of what the scene holds",
16017        );
16018        assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
16019
16020        second.finish(device.as_ref(), renderer);
16021    }
16022
16023    /// **Once the ring has come round, `drawn` is a number and it says which
16024    /// frame it is from.**
16025    ///
16026    /// The other half of the test above: `indirect` while the readback is in
16027    /// flight, a count afterwards, and a `cull_frame` naming a frame several
16028    /// behind the one just recorded. The null backend executes no copy, so the
16029    /// *value* here is the full-screen passes' own draws and nothing else — what the cull
16030    /// really kept is asserted against a real GPU, in the umbrella crate's
16031    /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
16032    ///
16033    /// The frame number is the assertion with teeth here: a ring that read the
16034    /// slot it had just written would report the frame it is on, and a
16035    /// `cull_frame` left at `None` would put a latent number on the panel with
16036    /// nothing to say how old it is.
16037    #[test]
16038    fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
16039        let (_recorder, device, queue) = open();
16040        let mut renderer =
16041            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16042
16043        let mut frames = Vec::new();
16044        for _ in 0..CULL_STATS_FLOOR {
16045            frames.push(frame(device.as_ref(), &mut renderer, queue));
16046            assert_eq!(
16047                renderer.counters().drawn,
16048                None,
16049                "no readback has even been polled yet, so there is nothing back",
16050            );
16051        }
16052
16053        frames.push(frame(device.as_ref(), &mut renderer, queue));
16054        let counters = renderer.counters();
16055        assert_eq!(
16056            counters.drawn,
16057            Some(
16058                fullscreen_passes(
16059                    renderer.effects(),
16060                    TEST_EXTENT,
16061                    false,
16062                    renderer.frame_ssao_blurs,
16063                ) * FULLSCREEN_DRAWS,
16064            ),
16065            "the survivor count the null backend produced is zero, plus one instance per \
16066             full-screen pass — which is on both sides of the row",
16067        );
16068        assert_eq!(
16069            counters.cull_frame,
16070            Some(1),
16071            "the report is the frame whose copy answered, not the frame just recorded",
16072        );
16073        assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
16074
16075        for frame in frames {
16076            frame.release(device.as_ref());
16077        }
16078        renderer.destroy(device.as_ref());
16079    }
16080
16081    /// The frames a culling counter cannot possibly have arrived in.
16082    ///
16083    /// Two: the copy is recorded on one frame and the readback for it requested
16084    /// on the next, so the earliest frame that can poll anything is the third.
16085    /// A device that answers its first poll — the null backend, and every native
16086    /// one — reports there; a browser answers later, which is why this is a
16087    /// floor rather than a latency. See [`crate::cull_stats`].
16088    const CULL_STATS_FLOOR: usize = 2;
16089
16090    /// **A light that takes a shadow tile moves the draw count**, because the
16091    /// shadow pass records one call per bucket per occupied view.
16092    ///
16093    /// The observable a `recorded_draws` comparison alone would miss: a
16094    /// `counters` that counted only the colour pass and the tonemap agrees with
16095    /// nothing here, and one that hard-coded the cascades agrees with the first
16096    /// frame and not the second.
16097    #[test]
16098    fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
16099        let _seam = ssao_split_switch();
16100        let (recorder, device, queue) = open();
16101        let mut renderer =
16102            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16103
16104        let dark = frame(device.as_ref(), &mut renderer, queue);
16105        let without = renderer.counters().draws;
16106        assert_eq!(without, recorded_draws(&recorder) as u64);
16107        dark.release(device.as_ref());
16108
16109        renderer.set_lights(&[shadowable_spot(0.0)]);
16110        recorder.clear();
16111        let lit = frame(device.as_ref(), &mut renderer, queue);
16112        let with = renderer.counters().draws;
16113        assert!(
16114            with > without,
16115            "a shadow-casting light adds a view and therefore draws: {with} against {without}",
16116        );
16117        assert_eq!(
16118            with,
16119            recorded_draws(&recorder) as u64,
16120            "and the counter still matches the stream",
16121        );
16122        lit.finish(device.as_ref(), renderer);
16123    }
16124
16125    /// Opens a null device offering `optional` on top of the mesh path, and
16126    /// asserts it really selected that path.
16127    ///
16128    /// Asked for rather than merely reported, because a device grants what it
16129    /// enabled: leaving mesh shaders out of the optional set opens a device on
16130    /// an indirect tail and tests nothing.
16131    ///
16132    /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
16133    /// only where `optional` asks for it — so a test that does not gets the
16134    /// mesh tail's call per bucket.
16135    fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
16136        let caps = crcbl_hal::DeviceCaps {
16137            features: Features::GPU_DRIVEN
16138                | Features::MESH_SHADER
16139                | Features::TASK_SHADER
16140                | Features::DRAW_INDEX,
16141            limits: crcbl_hal::Limits::desktop(),
16142        };
16143        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
16144        let adapter = instance.adapters().remove(0);
16145        assert_eq!(
16146            instance
16147                .adapter_caps(adapter.id)
16148                .expect("the null backend describes its adapter")
16149                .geometry_path(),
16150            GeometryPath::MeshShader,
16151            "a device with mesh shaders selects them, which is the case this is about"
16152        );
16153        let device = instance
16154            .create_device(&DeviceDesc {
16155                label: None,
16156                adapter: adapter.id,
16157                required_features: Features::COMPUTE,
16158                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
16159                compatible_surface: None,
16160            })
16161            .expect("the null backend always opens");
16162        assert_eq!(
16163            device.caps().geometry_path(),
16164            GeometryPath::MeshShader,
16165            "and the opened device still selects it"
16166        );
16167        let queue = device.queue(QueueKind::Graphics).expect("always present");
16168        (device, queue)
16169    }
16170
16171    /// **The four material pages are created with the format their contents
16172    /// call for, and it is only a *colour* that is sRGB.**
16173    ///
16174    /// Topic 44's rung 2 calls this the classic PBR bug and
16175    /// says why it survives review: a base-colour texel and an emissive one are
16176    /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
16177    /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
16178    /// decoding either of those through the sRGB curve is wrong by a gamma and
16179    /// looks merely like a surface bumpier or shinier than the author drew.
16180    /// Nothing in a frame reports it, no golden comparison can name it, and the
16181    /// four constants sit a few lines apart with the wrong one compiling.
16182    ///
16183    /// So this is the whole guard, and it is three claims rather than one: that
16184    /// each constant is the one it should be, that
16185    /// [`PageKind::format`] — which is what the upload loop actually calls —
16186    /// answers with it, and, the half that would otherwise be a check that
16187    /// cannot fail, that the format each page is *created* with is the format
16188    /// its `ImportedImage` declares. A declaration naming a format the image is
16189    /// not in picks the wrong aspects in a barrier.
16190    #[test]
16191    fn the_page_formats_split_colour_from_number() {
16192        assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
16193        assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
16194        assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
16195        assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
16196        // Through the dispatch the upload loop actually calls, rather than the
16197        // constants alone: one loop creates every image now, and a `format` arm
16198        // pointed at the wrong constant is the way that loop gets it wrong.
16199        assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
16200        assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
16201        assert_eq!(
16202            PageKind::MetallicRoughnessOcclusion.format(),
16203            MRO_PAGE_FORMAT
16204        );
16205        assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
16206        assert_ne!(
16207            BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
16208            "a normal page created sRGB decodes every texel through a gamma it never had"
16209        );
16210        assert_ne!(
16211            EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
16212            "a packed roughness page created sRGB shades every surface smoother than authored"
16213        );
16214
16215        let (recorder, device, queue) = open();
16216        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16217            .expect("the forward renderer builds on the null backend");
16218        assert_eq!(
16219            renderer.base_color_page_import().format,
16220            BASE_COLOR_PAGE_FORMAT
16221        );
16222        assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
16223        assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
16224        assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
16225        // And they really are four images, not one bound four times — which is
16226        // the other way a page could be "linear" and still be sampled through
16227        // the sRGB one.
16228        let created = [
16229            renderer.base_color_page(),
16230            renderer.normal_page(),
16231            renderer.mro_page(),
16232            renderer.emissive_page(),
16233        ];
16234        for (at, page) in created.iter().enumerate() {
16235            for other in &created[at + 1..] {
16236                assert_ne!(page.image, other.image, "two page kinds share one image");
16237                assert_ne!(page.view, other.view, "two page kinds share one view");
16238            }
16239        }
16240        // The labels come off the recorder rather than off the handles, so this
16241        // is evidence about what the device was asked to create.
16242        let images: Vec<String> = recorder
16243            .events()
16244            .into_iter()
16245            .filter_map(|event| match event {
16246                Event::Created {
16247                    kind: ObjectKind::Image,
16248                    label: Some(label),
16249                } => Some(label),
16250                _ => None,
16251            })
16252            .collect();
16253        for kind in PageKind::ALL {
16254            let page = kind.upload_label();
16255            assert!(
16256                images.iter().any(|label| label == page),
16257                "no image was created for the {page} page, and it is {images:?} that were"
16258            );
16259        }
16260        renderer.destroy(device.as_ref());
16261    }
16262
16263    /// Compare native argument indices from the shipped entry points with the
16264    /// actual renderer layout. A shared fragment buffer must have the same index
16265    /// even when geometry introduces additional resources in another module.
16266    #[test]
16267    fn mesh_pipeline_buffers_match_native_shader_arguments() {
16268        for optional in [Features::TASK_SHADER, Features::empty()] {
16269            let recorder = Recorder::new();
16270            let (device, queue) = open_mesh_path(&recorder, optional);
16271            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16272                .expect("the mesh renderer builds");
16273            let (_, entries) = recorder
16274                .bind_group_layouts_created()
16275                .into_iter()
16276                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
16277                .expect("the actual mesh layout");
16278            let mut buffers: Vec<_> = entries
16279                .iter()
16280                .filter(|entry| {
16281                    matches!(
16282                        entry.kind,
16283                        BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
16284                    )
16285                })
16286                .collect();
16287            buffers.sort_by_key(|entry| entry.binding);
16288            assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
16289            for (source, shader, names) in [
16290                (
16291                    include_str!("../../crcbl-shaders/shaders/mesh.slang"),
16292                    &MESH,
16293                    &["fragmentMain"][..],
16294                ),
16295                (
16296                    include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
16297                    &MESH_CLUSTER,
16298                    &["meshMain", "taskMain", "amplifiedMeshMain"][..],
16299                ),
16300            ] {
16301                let declarations: Vec<_> = source.lines().collect();
16302                let bindings: Vec<_> = declarations
16303                    .windows(2)
16304                    .filter_map(|lines| {
16305                        let binding = lines[0]
16306                            .trim()
16307                            .strip_prefix("[[vk::binding(")?
16308                            .split(',')
16309                            .next()?
16310                            .parse::<u32>()
16311                            .ok()?;
16312                        // The name is the last word before the D3D12 register.
16313                        let name = lines[1]
16314                            .split(" D3D12_REGISTER(")
16315                            .next()?
16316                            .split_whitespace()
16317                            .last()?
16318                            .trim_end_matches(';');
16319                        Some((name, binding))
16320                    })
16321                    .collect();
16322                for name in names {
16323                    let signature = shader
16324                        .msl()
16325                        .expect("committed native shader")
16326                        .lines()
16327                        .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
16328                        .expect("native entry signature");
16329                    let mut checked = 0;
16330                    for argument in signature.split(", ") {
16331                        let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
16332                            continue;
16333                        };
16334                        let native: usize = tail.split(')').next().unwrap().parse().unwrap();
16335                        let variable = declaration.split_whitespace().last().unwrap();
16336                        let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
16337                        let binding = bindings
16338                            .iter()
16339                            .find(|(candidate, _)| *candidate == variable)
16340                            .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
16341                            .1;
16342                        let expected = buffers
16343                            .iter()
16344                            .position(|entry| entry.binding == binding)
16345                            .expect("shader binding exists in the renderer layout");
16346                        assert_eq!(
16347                            native, expected,
16348                            "{name}: {variable}, logical binding {binding}, native shader vs global layout"
16349                        );
16350                        checked += 1;
16351                    }
16352                    assert!(
16353                        checked >= 10,
16354                        "entry parsing must cover the complete buffer interface"
16355                    );
16356                }
16357            }
16358            renderer.destroy(device.as_ref());
16359        }
16360    }
16361
16362    #[test]
16363    fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
16364        let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
16365        for optional in [Features::TASK_SHADER, Features::empty()] {
16366            let recorder = Recorder::new();
16367            let (device, queue) = open_mesh_path(&recorder, optional);
16368            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16369                .expect("the forward renderer builds on both device shapes");
16370            assert_eq!(
16371                renderer.culls_clusters(),
16372                optional.contains(Features::TASK_SHADER),
16373                "the two arms must actually differ, or this compares a device with itself"
16374            );
16375            let (label, entries) = recorder
16376                .bind_group_layouts_created()
16377                .into_iter()
16378                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
16379                .expect("the mesh pass declares its layout by name");
16380            assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
16381            declared.push(
16382                entries
16383                    .iter()
16384                    .map(|entry| (entry.binding, entry.kind))
16385                    .collect(),
16386            );
16387        }
16388
16389        let [amplified, plain] = declared
16390            .try_into()
16391            .unwrap_or_else(|_| unreachable!("two arms were run"));
16392        assert_eq!(
16393            amplified, plain,
16394            "the mesh layout's bindings changed with the task stage, which moves every Metal \
16395             argument-table index above the difference"
16396        );
16397        // These mesh declarations remain present without a task stage.
16398        for binding in [
16399            CLUSTER_CULL_BINDING,
16400            CLUSTER_CULL_STATS_BINDING,
16401            CLUSTER_SELECT_BINDING,
16402            CLUSTER_SELECTION_BINDING,
16403            CLUSTER_GROUP_STATE_BINDING,
16404        ] {
16405            assert!(
16406                plain.iter().any(|(number, _)| *number == binding),
16407                "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
16408            );
16409        }
16410        // Logical gaps consume no native slots. The complete shader union must
16411        // remain sorted, and every mesh-only buffer follows the fragment prefix.
16412        let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
16413        let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
16414        assert_eq!(
16415            numbers, expected,
16416            "the complete sparse shader binding union"
16417        );
16418    }
16419
16420    /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
16421    /// is built, and a device without it still draws.**
16422    ///
16423    /// The two capabilities are separate, and the adapter above offers both — so
16424    /// asking for one and not the other is a device state a real driver has and
16425    /// this can reach. Neither arm is a skip:
16426    ///
16427    /// * With the task stage, the renderer builds the amplification stage and
16428    ///   [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
16429    ///   task stage on a device without the flag, so an arm that computed this
16430    ///   wrongly would fail to build rather than pass quietly. It records one
16431    ///   flat call per partition — [`flat_dispatch_calls`].
16432    /// * Without it, the renderer builds `meshMain` — the un-amplified entry
16433    ///   point — and draws every cluster of every surviving instance, one
16434    ///   indirect dispatch per bucket reading its own extents.
16435    #[test]
16436    fn the_task_stage_is_built_only_where_the_device_has_one() {
16437        use crcbl_hal::null::Command;
16438
16439        for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
16440            let recorder = Recorder::new();
16441            let (device, queue) = open_mesh_path(&recorder, optional);
16442            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16443                .expect("the forward renderer builds on both device shapes");
16444            assert_eq!(
16445                device.caps().supports(Features::TASK_SHADER),
16446                expected,
16447                "the device must actually differ between the arms, or both test the same thing"
16448            );
16449            assert_eq!(
16450                renderer.culls_clusters(),
16451                expected,
16452                "the amplification stage is built exactly where the device has one"
16453            );
16454            assert_eq!(
16455                renderer.geometry_path(),
16456                GeometryPath::MeshShader,
16457                "both arms are the mesh path; only the stage in front of it differs"
16458            );
16459
16460            let frame = frame(device.as_ref(), &mut renderer, queue);
16461            // After the frame, because the buffer named is the slot the frame
16462            // rotated to — asking before it names the previous slot's ring
16463            // entry and the comparison is against a buffer nothing drew from.
16464            let expected = if expected {
16465                flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
16466            } else {
16467                mesh_dispatch_calls(&renderer)
16468            };
16469
16470            let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
16471                .into_iter()
16472                .filter_map(|command| match command {
16473                    Command::DrawMeshTasksIndirect(draw) => Some(draw),
16474                    _ => None,
16475                })
16476                .collect();
16477            assert_eq!(
16478                dispatched, expected,
16479                "a flat call per partition behind the stage, and a dispatch per bucket reading \
16480                 its own extents without it"
16481            );
16482
16483            frame.finish(device.as_ref(), renderer);
16484        }
16485    }
16486
16487    /// The flat calls a pass splitting the bucket table by the material-mode
16488    /// bits `key` records behind a task stage, in region 0, in partition order
16489    /// — one per segment the table holds buckets of — and each segment's first
16490    /// bucket, whose block the call binds.
16491    ///
16492    /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
16493    /// camera generator's own region count rather than from
16494    /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
16495    fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
16496        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
16497        let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
16498        let regions = renderer.primary.draws.mode().regions();
16499        let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
16500        let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
16501            vec![0, key]
16502        } else {
16503            DEPTH_MODES.to_vec()
16504        };
16505        values
16506            .into_iter()
16507            .filter(|value| {
16508                renderer
16509                    .bucket_modes
16510                    .iter()
16511                    .any(|mode| mode & key == *value)
16512            })
16513            .map(|value| {
16514                let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
16515                    .expect("a split every pass makes");
16516                (
16517                    DrawIndirect {
16518                        args: renderer.primary.draws.mesh_args(renderer.frame),
16519                        offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
16520                            buckets, regions, 0, segment, 0,
16521                        )) * 4,
16522                        draw_count: 1,
16523                        stride,
16524                    },
16525                    segments[segment as usize].0,
16526                )
16527            })
16528            .unzip()
16529    }
16530
16531    /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
16532    /// order.
16533    ///
16534    /// Built from the buffer the draw-argument pass writes and the stride the
16535    /// APIs fixed, so a test comparing against it is asserting that the call
16536    /// reads *this frame's* arguments at *this bucket's* offset — the two ways
16537    /// an indirect dispatch goes wrong while still dispatching something.
16538    ///
16539    /// **The offsets are multiplied out here rather than asked of
16540    /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
16541    /// comparison and a tautology: an offset function that returned zero for
16542    /// every bucket would agree with itself, and three calls onto one structure
16543    /// is a frame that draws one bucket's geometry three times.
16544    fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
16545        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
16546        // The extents share a buffer with the one draw count per bucket that
16547        // precedes them, so every offset is that far in. Written out from the
16548        // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
16549        // for the reason above: a base of zero is exactly the mistake this
16550        // comparison exists to catch, and it would agree with itself.
16551        let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
16552        (0..renderer.bucket_constants.len())
16553            .map(|bucket| DrawIndirect {
16554                args: renderer.primary.draws.mesh_args(renderer.frame),
16555                offset: counts_bytes + bucket as u64 * u64::from(stride),
16556                draw_count: 1,
16557                stride,
16558            })
16559            .collect()
16560    }
16561
16562    /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
16563    /// pipeline, and records no indirect draw and no index-buffer bind at all.**
16564    ///
16565    /// The three halves are one claim. That it dispatched says the path is
16566    /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
16567    /// did not quietly fall through to a tail that draws the same picture; and
16568    /// that it bound no index buffer says the geometry really came out of the
16569    /// cluster records rather than out of the index pool. Until 2026-08 this
16570    /// device degraded and logged that it had, which is exactly the shape —
16571    /// "not implemented" arriving as a passing frame — the three together rule
16572    /// out.
16573    ///
16574    /// **The extents are not here to be checked, and that is the point.** They
16575    /// are three words the draw-argument pass writes, so what this can pin is
16576    /// the call reading *this* bucket's structure out of *this* frame's buffer
16577    /// — and the CPU-side half of the x extent, the per-bucket cluster table
16578    /// the host uploaded, which the null backend keeps the bytes of. What the
16579    /// GPU then makes of it needs a GPU: `crcbl-vk`'s
16580    /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
16581    /// arguments back.
16582    #[test]
16583    fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
16584        use crcbl_hal::null::Command;
16585
16586        let recorder = Recorder::new();
16587        let caps = crcbl_hal::DeviceCaps {
16588            features: Features::GPU_DRIVEN | Features::MESH_SHADER,
16589            limits: crcbl_hal::Limits::desktop(),
16590        };
16591        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
16592        let adapter = instance.adapters().remove(0);
16593        assert_eq!(
16594            instance
16595                .adapter_caps(adapter.id)
16596                .expect("the null backend describes its adapter")
16597                .geometry_path(),
16598            GeometryPath::MeshShader,
16599            "a device with mesh shaders selects them, which is the case this is about"
16600        );
16601        let device = instance
16602            .create_device(&DeviceDesc {
16603                label: None,
16604                adapter: adapter.id,
16605                required_features: Features::COMPUTE,
16606                // Asked for, because a device reports what it enabled: leaving
16607                // mesh shaders out of the optional set would open a device that
16608                // selects an indirect path outright and test nothing.
16609                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
16610                compatible_surface: None,
16611            })
16612            .expect("the null backend always opens");
16613        assert_eq!(
16614            device.caps().geometry_path(),
16615            GeometryPath::MeshShader,
16616            "and the opened device still selects it"
16617        );
16618        let queue = device.queue(QueueKind::Graphics).expect("always present");
16619        let mut renderer =
16620            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16621        assert_eq!(
16622            renderer.geometry_path(),
16623            GeometryPath::MeshShader,
16624            "the renderer must have *built* the mesh path, not merely been offered it"
16625        );
16626        let frame = frame(device.as_ref(), &mut renderer, queue);
16627        let expected = mesh_dispatch_calls(&renderer);
16628        // The table is written once at build, into a host-visible buffer the
16629        // null backend keeps the bytes of — so it is readable whether or not a
16630        // shader ever ran. It shares that buffer with the four other tables the
16631        // draw-argument pass reads, so the region has to be cut out at the
16632        // offset the renderer told the shader about rather than at zero.
16633        let table_bytes = recorder
16634            .buffer_bytes(renderer.primary.draws.tables())
16635            .expect("the table buffer is one of this recorder's buffers");
16636        let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16637        let clusters: Vec<u32> = table_bytes[clusters_at..]
16638            .as_chunks::<4>()
16639            .0
16640            .iter()
16641            .take(renderer.bucket_constants.len())
16642            .map(|word| u32::from_le_bytes(*word))
16643            .collect();
16644
16645        let mut dispatched = Vec::new();
16646        let mut index_binds = 0;
16647        for command in commands_in_pass(&recorder, "forward") {
16648            match command {
16649                Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16650                Command::DrawMeshTasks { .. } => panic!(
16651                    "the mesh path recorded a CPU-sized dispatch, which is the extent \
16652                     the instance cull is supposed to have taken over"
16653                ),
16654                Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16655                    panic!(
16656                        "the mesh path recorded an indirect draw, which is the silent \
16657                         fall-through this test exists to rule out"
16658                    )
16659                }
16660                Command::BindIndexBuffer { .. } => index_binds += 1,
16661                _ => {}
16662            }
16663        }
16664        assert_eq!(
16665            dispatched, expected,
16666            "one indirect dispatch per bucket, each reading its own argument structure \
16667             out of this frame's buffer"
16668        );
16669        assert_eq!(
16670            clusters.len(),
16671            renderer.bucket_constants.len(),
16672            "one x extent per bucket: {clusters:?}"
16673        );
16674        assert!(
16675            clusters.iter().all(|&count| count > 0),
16676            "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16677             {clusters:?}"
16678        );
16679        // **The x extents are not all the same number**, which is what makes
16680        // the table a statement about each bucket's own mesh. Two
16681        // single-cluster meshes would let a table hard-coded to one cluster
16682        // pass; the open box is five, one per face.
16683        assert_eq!(
16684            clusters[DEMO_OPEN_BOX] as usize,
16685            crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16686            "the open box dispatches one workgroup per face, and that is the only \
16687             resident whose cluster count is not one: {clusters:?}"
16688        );
16689        assert_eq!(
16690            index_binds, 0,
16691            "a mesh pipeline has no index buffer; binding one would mean the geometry \
16692             came from the index pool after all"
16693        );
16694
16695        frame.finish(device.as_ref(), renderer);
16696    }
16697
16698    /// **The cull pass is told the camera the frame is drawn with**, and how
16699    /// many array elements to walk.
16700    ///
16701    /// Both halves fail silently: a frustum from a different aspect ratio culls
16702    /// geometry that is on screen, and an instance count short of the pool's
16703    /// high-water mark stops testing the instances above a freed slot. Neither
16704    /// is visible in a picture until something disappears from an edge.
16705    #[test]
16706    fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16707        let (recorder, device, queue) = open();
16708        let mut renderer =
16709            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16710        // The cube first and the pyramid above it, because the second half of
16711        // this test frees the lower slot and asks what the walk still covers.
16712        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16713        place_demo(
16714            &mut renderer,
16715            DEMO_PYRAMID,
16716            DEMO_UNTINTED,
16717            Mat4::from_translation(Vec3::X),
16718        );
16719
16720        let camera = Camera {
16721            eye: Vec3::new(1.6, 1.2, 2.2),
16722            ..Camera::default()
16723        };
16724        let extent = (256u32, 192u32);
16725        renderer
16726            .begin_frame(
16727                device.as_ref(),
16728                &camera,
16729                &DirectionalLight::default(),
16730                extent,
16731            )
16732            .expect("write");
16733
16734        let aspect = extent.0 as f32 / extent.1 as f32;
16735        let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16736        let written = recorder
16737            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16738            .expect("this frame's cull parameters are live");
16739        assert_eq!(
16740            &written[..crcbl_shaders::cull::PARAMS_SIZE],
16741            &crcbl_shaders::cull::Params {
16742                planes: expected.planes.map(|plane| plane.to_array()),
16743                instance_count: 2,
16744                capacity: scene::Capacities::default().instances,
16745                hidden_view: ViewId::PRIMARY.hidden_bit(),
16746                ..crcbl_shaders::cull::Params::default()
16747            }
16748            .to_bytes()[..],
16749            "the cull block must carry this frame's own frustum, the pool's whole \
16750             occupied range, and the visible list's capacity"
16751        );
16752
16753        // And the high-water mark is what is written, not the live count: remove
16754        // the cube and the pyramid above it still has to be tested.
16755        renderer.remove_instance(cube);
16756        renderer
16757            .begin_frame(
16758                device.as_ref(),
16759                &camera,
16760                &DirectionalLight::default(),
16761                extent,
16762            )
16763            .expect("write");
16764        let written = recorder
16765            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16766            .expect("live");
16767        assert_eq!(
16768            u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16769            2,
16770            "one live instance, two occupied slots — a walk of one would never \
16771             reach the pyramid"
16772        );
16773
16774        renderer.destroy(device.as_ref());
16775        recorder.assert_valid();
16776    }
16777
16778    /// **Every counter both compute passes add to is zeroed by a pass of its
16779    /// own, before either of them runs.**
16780    ///
16781    /// The two shaders only ever increment, so a counter carrying the previous
16782    /// frame's total makes a bucket's argument structure claim more instances
16783    /// than its run holds — which draws whatever the run's stale tail happens to
16784    /// name.
16785    ///
16786    /// # This once read the bytes back, and no longer can
16787    ///
16788    /// It used to poison every counter with `0xAB` and assert `begin_frame`
16789    /// had written zeroes over them — the poison being the whole test, because
16790    /// the null backend runs no shader and a counter nothing wrote reads as the
16791    /// zero it was created with. The counters are device-local now, so nothing
16792    /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16793    /// them: the zero is a dispatch inside the frame, and a backend that runs no
16794    /// shader cannot observe it at all.
16795    ///
16796    /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16797    /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16798    /// generated arguments — and what is checkable *here* is the schedule: that
16799    /// the frame contains the clearing pass, that it writes exactly those
16800    /// buffers, and that the graph orders the two accumulating passes after it.
16801    /// Each of the counts below goes red if a buffer is dropped from the
16802    /// clearing pass, and the pass list goes red if the pass leaves the frame.
16803    #[test]
16804    fn every_frame_starts_from_zeroed_counters() {
16805        let (recorder, device, queue) = open();
16806        let mut renderer =
16807            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16808        place_cube(&mut renderer, Mat4::IDENTITY);
16809        let imported = swapchain_image(device.as_ref());
16810        // Twice round the ring, because a slot cleared only on its first use is
16811        // exactly the failure this is about.
16812        for round in 0..FRAMES_IN_FLIGHT * 2 {
16813            renderer
16814                .begin_frame(
16815                    device.as_ref(),
16816                    &Camera::default(),
16817                    &DirectionalLight::default(),
16818                    (64, 48),
16819                )
16820                .expect("write");
16821            let mut graph = crate::RenderGraph::new(queue);
16822            let target = graph.import_image("target", imported);
16823            let pool = crate::TransientPool::new();
16824            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16825            let compiled = graph.compile(&pool).expect("a legal frame");
16826
16827            let clear = &compiled.passes()[0];
16828            assert_eq!(
16829                clear.label(),
16830                "clear-counters",
16831                "round {round}: the zero has to be written before anything adds to it"
16832            );
16833            let barriers = &clear.barriers().buffers;
16834            assert_eq!(
16835                barriers.len(),
16836                3,
16837                "round {round}: the survivor count, the draw arguments, and the buffer \
16838                 holding both the draw counts and the mesh-dispatch arguments, and \
16839                 nothing else: {barriers:?}"
16840            );
16841            assert!(
16842                barriers
16843                    .iter()
16844                    .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16845                "round {round}: every one of them is written by this pass: {barriers:?}"
16846            );
16847            // The ones the frame leaves as indirect arguments are the two a
16848            // driver reads; the survivor count rests in a shader read. That
16849            // split is what names them without a handle to compare.
16850            assert_eq!(
16851                barriers
16852                    .iter()
16853                    .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16854                    .count(),
16855                2,
16856                "round {round}: out of the state a draw read them in: {barriers:?}"
16857            );
16858
16859            let after = |label: &str| {
16860                compiled
16861                    .passes()
16862                    .iter()
16863                    .find(|pass| pass.label() == label)
16864                    .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16865                    .barriers()
16866                    .buffers
16867                    .iter()
16868                    .filter(|barrier| {
16869                        barrier.from == ResourceState::ShaderReadWrite
16870                            && barrier.to == ResourceState::ShaderReadWrite
16871                    })
16872                    .count()
16873            };
16874            assert_eq!(
16875                after("cull"),
16876                1,
16877                "round {round}: the survivor count reaches the cull pass's atomic behind a \
16878                 barrier on the write that zeroed it"
16879            );
16880            assert_eq!(
16881                after("draw-args"),
16882                4,
16883                "round {round}: and so do the draw arguments and the buffer holding the \
16884                 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16885                 which the cull pass has just written and this pass reads through the same \
16886                 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16887                 hysteresis state, which the clearing pass does *not* zero and which is \
16888                 behind the same kind of barrier for the opposite reason: it is the one \
16889                 buffer here carrying a value out of the previous frame, so what it needs \
16890                 ordering against is that frame rather than this one's clear"
16891            );
16892            // **And the prefix sum and the scatter behind barriers of their own**,
16893            // on every buffer the stage before them wrote. This is what orders
16894            // them on a device that runs undeclared commands in any order — see
16895            // `DrawGen::add_passes` — and what three dispatches in one pass
16896            // silently lacked.
16897            for label in ["draw-starts", "draw-scatter"] {
16898                assert_eq!(
16899                    after(label),
16900                    4,
16901                    "round {round}: `{label}` reads what the pass before it wrote, so every \
16902                     buffer they share is ordered behind a barrier"
16903                );
16904            }
16905
16906            // The compiled graph borrows the renderer's pass bodies, so it has
16907            // to go before the next frame borrows the renderer again.
16908            drop(compiled);
16909        }
16910        renderer.destroy(device.as_ref());
16911        device.destroy_image_view(imported.view);
16912        device.destroy_image(imported.image);
16913        recorder.assert_valid();
16914    }
16915
16916    /// **A frame with no instances leaves out every generator's cull and
16917    /// scatter passes**, and keeps the clear and the two stages that write each
16918    /// bucket's arguments.
16919    ///
16920    /// An empty pass is not a harmless no-op on Metal: the backend opens an
16921    /// encoder for every graph pass and strict validation rejects ending one
16922    /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16923    /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16924    #[test]
16925    fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16926        let (recorder, device, queue) = open();
16927        let mut renderer =
16928            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16929        renderer
16930            .begin_frame(
16931                device.as_ref(),
16932                &Camera::default(),
16933                &DirectionalLight::default(),
16934                (64, 48),
16935            )
16936            .expect("write");
16937        let imported = swapchain_image(device.as_ref());
16938        let mut graph = crate::RenderGraph::new(queue);
16939        let target = graph.import_image("target", imported);
16940        let pool = crate::TransientPool::new();
16941        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16942        let compiled = graph.compile(&pool).expect("a legal frame");
16943
16944        let count = |label: &str| {
16945            compiled
16946                .passes()
16947                .iter()
16948                .filter(|pass| pass.label() == label)
16949                .count()
16950        };
16951        // The camera's generator and one per shadow cascade.
16952        let generators = 1 + shadow::CASCADES;
16953        for label in ["clear-counters", "draw-args", "draw-starts"] {
16954            assert_eq!(
16955                count(label),
16956                generators,
16957                "`{label}` still has work with nothing to draw: the clear erases the \
16958                 previous frame's counts and the argument stages write zero draws"
16959            );
16960        }
16961        for label in ["cull", "draw-scatter"] {
16962            assert_eq!(
16963                count(label),
16964                0,
16965                "`{label}` has no workgroups to dispatch with no instances"
16966            );
16967        }
16968
16969        drop(compiled);
16970        renderer.destroy(device.as_ref());
16971        device.destroy_image_view(imported.view);
16972        device.destroy_image(imported.image);
16973        recorder.assert_valid();
16974    }
16975
16976    /// **The graph transitions the generated arguments into
16977    /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16978    /// runs into a shader read.
16979    ///
16980    /// The seam calls this the single most important barrier in a GPU-driven
16981    /// frame and says its absence produces "sometimes nothing draws" — which is
16982    /// exactly the failure a golden image on one driver would not catch. It is
16983    /// asserted on the compiled graph, which is pure and needs no device.
16984    #[test]
16985    fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
16986        let _blurs = ssao_blur_switch();
16987        let (recorder, device, queue) = open();
16988        let mut renderer =
16989            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16990        place_cube(&mut renderer, Mat4::IDENTITY);
16991        renderer
16992            .begin_frame(
16993                device.as_ref(),
16994                &Camera::default(),
16995                &DirectionalLight::default(),
16996                (64, 48),
16997            )
16998            .expect("write");
16999
17000        let imported = swapchain_image(device.as_ref());
17001        let mut graph = crate::RenderGraph::new(queue);
17002        let target = graph.import_image("target", imported);
17003        let pool = crate::TransientPool::new();
17004        renderer.add_passes(&mut graph, &pool, target, (64, 48));
17005        let compiled = graph.compile(&pool).expect("a legal frame");
17006
17007        let passes: Vec<String> = compiled
17008            .passes()
17009            .iter()
17010            .map(|pass| pass.label().to_string())
17011            .collect();
17012        // The camera's five compute passes and topic 18's clustering dispatch,
17013        // then five per shadow cascade, then the depth-only pass they feed and
17014        // the colour pass that samples it.
17015        //
17016        // **The clustering pass is after the camera's clearing dispatch**, and
17017        // that is the ordering the overflow counter depends on: the clearing
17018        // pass zeroes the statistics word this one adds to, and both declare
17019        // the same buffer, so the graph is what puts the barrier between them.
17020        let mut expected: Vec<String> = Vec::new();
17021        for cascade in 0..=shadow::CASCADES {
17022            expected.extend(
17023                [
17024                    "clear-counters",
17025                    "cull",
17026                    "draw-args",
17027                    "draw-starts",
17028                    "draw-scatter",
17029                ]
17030                .into_iter()
17031                .map(str::to_string),
17032            );
17033            if cascade == 0 {
17034                expected.push("light-cluster".to_string());
17035            }
17036        }
17037        // And the culling-statistics copy **last**, after every pass that adds
17038        // to the buffer it reads — the cull dispatch, the clustering pass and
17039        // the amplification stage inside the colour pass.
17040        expected.extend(
17041            [
17042                "shadow",
17043                "depth-prepass",
17044                "ssao",
17045                "ssao-blur",
17046                // The reconstruction that ends the occlusion chain, between the
17047                // blur it reads and the pass that binds what it wrote — see
17048                // [`crate::ssao`]'s header on why the first two run smaller than
17049                // the frame and this one does not.
17050                "ssao-upsample",
17051                "forward",
17052                // The pyramid the march climbs, between the pass that wrote
17053                // level 0 and the pass that reads the chain. Two levels at this
17054                // extent, written out for the reason `crate::bloom`'s chain is
17055                // in the toggle test below: a table generated from
17056                // `crate::hiz::levels_for` could not fail.
17057                "hiz-1",
17058                "hiz-2",
17059                "ssr",
17060                "ssr-blur",
17061                "tonemap",
17062                // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
17063                // CMAA2's three rather than FXAA's one —
17064                // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
17065                // where the swap between the two tiers is pinned.
17066                "cmaa2-edges",
17067                "cmaa2-shapes",
17068                "cmaa2-apply",
17069                "cull-stats-readback",
17070            ]
17071            .into_iter()
17072            .map(str::to_string),
17073        );
17074        assert_eq!(
17075            passes, expected,
17076            "each cull's five compute passes come first, and in that order"
17077        );
17078
17079        // **The depth prepass, not the colour pass**, and that is what says the
17080        // prepass really is the first thing to draw from the camera's cull: it is
17081        // where the draw buffers leave the compute pass's writes. The colour pass
17082        // below then needs none of these, because they are already in the state it
17083        // wants — which is the assertion after it.
17084        let prepass = compiled
17085            .passes()
17086            .iter()
17087            .find(|pass| pass.label() == "depth-prepass")
17088            .expect("the pass list above");
17089        let into_indirect = prepass
17090            .barriers()
17091            .buffers
17092            .iter()
17093            .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
17094            .count();
17095        assert_eq!(
17096            into_indirect,
17097            2,
17098            "the arguments and the count, out of the compute pass's writes and into \
17099             the state a draw reads them in: {:?}",
17100            prepass.barriers().buffers
17101        );
17102        assert!(
17103            prepass.barriers().buffers.iter().any(|barrier| {
17104                barrier.from == ResourceState::ShaderReadWrite
17105                    && barrier.to == ResourceState::ShaderRead
17106            }),
17107            "and the runs, which the vertex stage reads: {:?}",
17108            prepass.barriers().buffers
17109        );
17110
17111        let forward = compiled
17112            .passes()
17113            .iter()
17114            .find(|pass| pass.label() == "forward")
17115            .expect("the pass list above");
17116        assert!(
17117            forward
17118                .barriers()
17119                .buffers
17120                .iter()
17121                .all(|barrier| barrier.to != ResourceState::IndirectArgument),
17122            "the prepass draws from the same arguments, so the colour pass finds them \
17123             already in the state it wants — a barrier here would mean something between \
17124             the two put them back: {:?}",
17125            forward.barriers().buffers
17126        );
17127        // What the colour pass *does* still have to be given: the froxel grid,
17128        // which no earlier pass reads.
17129        assert!(
17130            forward.barriers().buffers.iter().any(|barrier| {
17131                barrier.from == ResourceState::ShaderReadWrite
17132                    && barrier.to == ResourceState::ShaderRead
17133            }),
17134            "and the froxel grid, which its fragment stage reads: {:?}",
17135            forward.barriers().buffers
17136        );
17137
17138        let draw_args = compiled
17139            .passes()
17140            .iter()
17141            .find(|pass| pass.label() == "draw-args")
17142            .expect("the pass list above");
17143        assert!(
17144            draw_args.barriers().buffers.iter().any(|barrier| {
17145                barrier.from == ResourceState::ShaderReadWrite
17146                    && barrier.to == ResourceState::ShaderRead
17147            }),
17148            "and the visible list is ordered after the cull pass wrote it: {:?}",
17149            draw_args.barriers().buffers
17150        );
17151
17152        // The compiled graph borrows the renderer's pass bodies, so it has to go
17153        // before the renderer does.
17154        drop(compiled);
17155        renderer.destroy(device.as_ref());
17156        device.destroy_image_view(imported.view);
17157        device.destroy_image(imported.image);
17158        recorder.assert_valid();
17159    }
17160
17161    /// One more frame than the uniform ring is deep, so at least one lap both
17162    /// reuses a slot and follows a lap that already sampled the atlas.
17163    const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
17164
17165    /// **Every frame's first barrier on the shadow atlas names what the previous
17166    /// frame left it in**, and the same for its placeholder.
17167    ///
17168    /// # Why this cannot be read off one frame
17169    ///
17170    /// The atlas is neither a transient nor a swapchain image. The pool never
17171    /// hands one out and has no description to size it from, and no acquire
17172    /// semaphore sits between one frame's use of it and the next — so
17173    /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
17174    /// makes the transition true.
17175    ///
17176    /// What it declares is [`imported_state`], the pool's record of what the
17177    /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
17178    /// can only ever find the two agreeing for this one import — deliberately,
17179    /// because a declaration and an audit reading one value cannot drift apart
17180    /// the way a renderer-held copy of it could. The audit still has teeth
17181    /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
17182    /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
17183    /// what shows it fires on those.
17184    ///
17185    /// So neither mechanism says anything about the barriers on either side of
17186    /// the declaration — whether the frame that ran actually reached the state
17187    /// the ledger now claims, and whether the next frame's first barrier comes
17188    /// out of it — which is what the stream below is for.
17189    ///
17190    /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
17191    /// failure this catches. It expands to `srcStageMask = NONE,
17192    /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
17193    /// into the depth-only pass's attachment state orders against nothing — while
17194    /// the previous frame's colour pass is still sampling the very same image.
17195    /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
17196    /// `read_barriers: 0`; every other backend resolves it however the driver
17197    /// likes.
17198    ///
17199    /// # Why the command stream is the observable
17200    ///
17201    /// Nothing above the seam can see a wrong declaration: the frame still
17202    /// renders, the golden still matches, and no state is ever read back. So this
17203    /// replays the recorded stream with a tracker, which is the same check a
17204    /// validation layer performs and needs no GPU at all — the shape
17205    /// `crcbl::screenshot`'s
17206    /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
17207    /// One difference: `Undefined` is **not** waved through after the first
17208    /// touch. It is true for a swapchain image because the acquire's semaphore
17209    /// makes it true, and there is no such semaphore here.
17210    #[test]
17211    fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
17212        use crcbl_hal::null::Command;
17213
17214        let (recorder, device, queue) = open();
17215        let device = device.as_ref();
17216        let mut renderer =
17217            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17218        let atlas = renderer.shadow_atlas();
17219        let placeholder = renderer.shadow_placeholder;
17220        let mut pool = crate::TransientPool::new();
17221        let imported = swapchain_image(device);
17222        let mut recorded = Vec::with_capacity(SHADOW_LAPS);
17223
17224        for lap in 0..SHADOW_LAPS {
17225            renderer
17226                .begin_frame(
17227                    device,
17228                    &Camera::default(),
17229                    // **A different sun each lap**, so every lap redraws the
17230                    // atlas: this is a test about the barrier a frame that
17231                    // writes the image declares, and a lap that cached would
17232                    // record no pass and no transition at all. See
17233                    // [`moving_sun`].
17234                    &moving_sun(u32::try_from(lap).expect("a handful of laps")),
17235                    (64, 48),
17236                )
17237                .expect("write");
17238            let mut graph = crate::RenderGraph::new(queue);
17239            let target = graph.import_image("target", imported);
17240            renderer.add_passes(&mut graph, &pool, target, (64, 48));
17241            let compiled = graph.compile(&pool).expect("a legal frame");
17242            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17243                label: Some("shadow lap"),
17244                queue,
17245            });
17246            compiled
17247                .execute(device, &mut pool, encoder.as_mut(), None)
17248                .expect("the graph executed");
17249            recorded.push(encoder.finish().expect("recording succeeded"));
17250        }
17251
17252        // The two images the renderer owns across frames. A transient's state is
17253        // the pool's business and the fake swapchain image's is the acquire's, so
17254        // neither belongs in here.
17255        let mut tracked = [
17256            (atlas, ResourceState::Undefined),
17257            (placeholder, ResourceState::Undefined),
17258        ];
17259        let mut atlas_writes = 0usize;
17260        let mut named = 0usize;
17261        for command in recorder.commands() {
17262            let Command::Barrier { images, .. } = command else {
17263                continue;
17264            };
17265            for barrier in images {
17266                let Some((_, state)) = tracked
17267                    .iter_mut()
17268                    .find(|(handle, _)| *handle == barrier.image)
17269                else {
17270                    continue;
17271                };
17272                assert_eq!(
17273                    barrier.from, *state,
17274                    "a barrier declared {:?} -> {:?} on an image the frame before it left in \
17275                     {:?}. `Undefined` carries no source scope, so a transition declaring it \
17276                     orders against nothing and the previous frame's sampled read is still in \
17277                     flight underneath it.",
17278                    barrier.from, barrier.to, *state
17279                );
17280                if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
17281                    atlas_writes += 1;
17282                }
17283                *state = barrier.to;
17284                named += 1;
17285            }
17286        }
17287
17288        // Both halves of the loop above are silent on an empty stream, so the
17289        // shape it walked is asserted rather than assumed: one transition into
17290        // the depth-only pass's attachment state per lap, the last one included.
17291        assert_eq!(
17292            atlas_writes, SHADOW_LAPS,
17293            "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
17294             {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
17295             the sun, so every lap redraws the atlas, and anything else means the loop above \
17296             asserted on a stream that does not contain the transition it is about"
17297        );
17298        let (_, ended) = tracked[0];
17299        assert_eq!(
17300            ended,
17301            ResourceState::ShaderRead,
17302            "the import promises to hand the atlas back in the state the next frame declares"
17303        );
17304
17305        renderer.destroy(device);
17306        for commands in recorded {
17307            device.destroy_command_buffer(commands);
17308        }
17309        pool.destroy(device);
17310        device.destroy_image_view(imported.view);
17311        device.destroy_image(imported.image);
17312        recorder.assert_valid();
17313    }
17314
17315    /// A renderer with a shadowed spot beside the sun's cascades and a caster
17316    /// for both to draw, which is the smallest scene the atlas cache has
17317    /// anything to say about: without a light tile the only maps are the
17318    /// cascades, and without a caster every tile is a clear.
17319    fn shadow_cache_scene(
17320        device: &dyn Device,
17321        queue: QueueHandle,
17322    ) -> (ForwardRenderer, InstanceHandle) {
17323        let mut renderer =
17324            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17325        // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
17326        // are process-global and `the_console_moves_both_limits` holds them at
17327        // a four-frame hold and three faces a frame for the length of its
17328        // check. A cache test reading the console inside that window reports
17329        // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
17330        // holding both limits at those values inside the arm's own process,
17331        // which the pin makes harmless.
17332        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17333        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
17334        renderer.set_lights(&[shadowable_spot(-1.0)]);
17335        (renderer, cube)
17336    }
17337
17338    /// Draws one frame and answers whether it drew the shadow atlas, **read two
17339    /// ways that have to agree**.
17340    ///
17341    /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
17342    /// the recorded stream is what the device was actually told; either on its
17343    /// own would be satisfied by a renderer that reported one thing and did the
17344    /// other, which is precisely the failure a cache has. `seen` is the cursor
17345    /// into the cumulative recorder, so each call reads its own frame.
17346    fn drew_the_atlas(
17347        recorder: &Recorder,
17348        seen: &mut usize,
17349        device: &dyn Device,
17350        renderer: &mut ForwardRenderer,
17351        queue: QueueHandle,
17352        camera: &Camera,
17353        sun: &DirectionalLight,
17354    ) -> bool {
17355        let drawn = frame_seen_from(device, renderer, queue, camera, sun);
17356        let claimed = renderer.shadow_atlas_cached();
17357        let commands = recorder.commands();
17358        let opened = commands[*seen..].iter().any(|command| {
17359            command
17360                .opens_pass()
17361                .is_some_and(|(_, label)| label == Some("shadow"))
17362        });
17363        *seen = commands.len();
17364        drawn.release(device);
17365        assert_eq!(
17366            opened,
17367            !claimed,
17368            "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
17369            if opened { "opened" } else { "opened no" }
17370        );
17371        opened
17372    }
17373
17374    #[test]
17375    fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
17376        let (recorder, device, queue) = open();
17377        let device = device.as_ref();
17378        let (mut renderer, _) = shadow_cache_scene(device, queue);
17379        let camera = Camera::default();
17380        let sun = DirectionalLight::default();
17381        let mut seen = 0;
17382        assert!(drew_the_atlas(
17383            &recorder,
17384            &mut seen,
17385            device,
17386            &mut renderer,
17387            queue,
17388            &camera,
17389            &sun
17390        ));
17391        let capacity = (
17392            renderer.shadow_prepare_views.capacity(),
17393            renderer.shadow_prepare_culls.capacity(),
17394        );
17395        assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
17396        assert!(renderer.shadow_prepare_views.is_empty());
17397        assert!(renderer.shadow_prepare_culls.is_empty());
17398        for _ in 0..FRAMES_IN_FLIGHT {
17399            assert!(!drew_the_atlas(
17400                &recorder,
17401                &mut seen,
17402                device,
17403                &mut renderer,
17404                queue,
17405                &camera,
17406                &sun
17407            ));
17408            assert!(renderer.shadow_prepare_views.is_empty());
17409            assert!(renderer.shadow_prepare_culls.is_empty());
17410            assert_eq!(
17411                (
17412                    renderer.shadow_prepare_views.capacity(),
17413                    renderer.shadow_prepare_culls.capacity()
17414                ),
17415                capacity
17416            );
17417        }
17418        for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
17419            // The spot moves for its own view and the camera for the cascades',
17420            // which are fitted to it: a moved spot alone is no input of theirs.
17421            renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
17422            let camera = Camera {
17423                eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
17424                ..camera
17425            };
17426            let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
17427            let short = device
17428                .create_buffer(&BufferDesc {
17429                    label: Some("refused shadow scratch test upload"),
17430                    size: std::mem::size_of::<f32>() as u64,
17431                    usage: BufferUsage::UNIFORM,
17432                    memory: MemoryLocation::HostUpload,
17433                })
17434                .unwrap();
17435            let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
17436            let before = recorder.buffer_bytes(short).unwrap();
17437            let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
17438            renderer.shadow_uniforms[slot][view] = original;
17439            assert!(
17440                matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
17441                "observe a refused shadow uniform: {result:?}"
17442            );
17443            assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
17444            assert!(!recorder.events().iter().any(
17445                |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
17446            ));
17447            assert!(renderer.shadow_prepare_views.is_empty());
17448            assert!(renderer.shadow_prepare_culls.is_empty());
17449            assert_eq!(
17450                (
17451                    renderer.shadow_prepare_views.capacity(),
17452                    renderer.shadow_prepare_culls.capacity()
17453                ),
17454                capacity
17455            );
17456            let refused_inputs = renderer.shadow_group_inputs.clone();
17457            device.destroy_buffer(short);
17458            recorder.assert_valid();
17459            assert!(drew_the_atlas(
17460                &recorder,
17461                &mut seen,
17462                device,
17463                &mut renderer,
17464                queue,
17465                &camera,
17466                &sun
17467            ));
17468            assert_eq!(renderer.shadow_group_inputs, refused_inputs);
17469            assert!(renderer.shadow_prepare_views.is_empty());
17470            assert!(renderer.shadow_prepare_culls.is_empty());
17471            assert_eq!(
17472                (
17473                    renderer.shadow_prepare_views.capacity(),
17474                    renderer.shadow_prepare_culls.capacity()
17475                ),
17476                capacity
17477            );
17478            assert!(!drew_the_atlas(
17479                &recorder,
17480                &mut seen,
17481                device,
17482                &mut renderer,
17483                queue,
17484                &camera,
17485                &sun
17486            ));
17487        }
17488        renderer.destroy(device);
17489        recorder.assert_valid();
17490        assert_eq!(recorder.total_live_objects(), 0);
17491    }
17492
17493    /// **A frame over a scene nothing moved in does not draw the shadow atlas
17494    /// again**, and what it saves is the whole of the atlas's work.
17495    ///
17496    /// Topic 45's static-caching rung, and the observable it
17497    /// otherwise has none for: the map a cached frame samples is byte for byte
17498    /// the map the frame before it sampled, so no golden image and no readback
17499    /// can tell the two frames apart. The recorded command stream can — and the
17500    /// dispatch count is the half that says the *culls* went with the pass,
17501    /// rather than the frame still paying for the draws it decided not to
17502    /// record.
17503    #[test]
17504    fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
17505        use crcbl_hal::null::Command;
17506
17507        // The blur count is a process-global console variable, and the frame's
17508        // draw count below includes the full-screen triangle each blur records
17509        // — so a concurrent test holding `r_ssao_blur_passes` at two would move
17510        // it under this one. Held rather than merely read, which is the
17511        // convention that variable's own test set.
17512        let _blurs = ssao_blur_switch();
17513        let (recorder, device, queue) = open();
17514        let device = device.as_ref();
17515        let (mut renderer, _) = shadow_cache_scene(device, queue);
17516        let camera = Camera::default();
17517        let sun = DirectionalLight::default();
17518
17519        let mut seen = 0usize;
17520        let dispatches = |recorder: &Recorder, from: usize| {
17521            recorder.commands()[from..]
17522                .iter()
17523                .filter(|command| matches!(command, Command::Dispatch { .. }))
17524                .count()
17525        };
17526
17527        let at = seen;
17528        assert!(
17529            drew_the_atlas(
17530                &recorder,
17531                &mut seen,
17532                device,
17533                &mut renderer,
17534                queue,
17535                &camera,
17536                &sun
17537            ),
17538            "the first frame of all has to draw the atlas: nothing has put anything in it"
17539        );
17540        let first = dispatches(&recorder, at);
17541        let drawing_draws = renderer.counters().draws;
17542        let buckets = renderer.bucket_constants.len() as u64;
17543        assert!(
17544            renderer.shadow_lights().base_of(0).is_some(),
17545            "the spot must hold a run for the count below to include a light slot's cull"
17546        );
17547        // The camera's own draw generation and topic 18's clustering dispatch,
17548        // plus a generation per cascade and one for the spot's slot.
17549        assert_eq!(
17550            first,
17551            DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
17552            "the drawing frame did not record the culls this test is about skipping"
17553        );
17554
17555        for round in 0..3 {
17556            let at = seen;
17557            assert!(
17558                !drew_the_atlas(
17559                    &recorder,
17560                    &mut seen,
17561                    device,
17562                    &mut renderer,
17563                    queue,
17564                    &camera,
17565                    &sun
17566                ),
17567                "round {round} redrew an atlas nothing had changed"
17568            );
17569            assert_eq!(
17570                dispatches(&recorder, at),
17571                DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
17572                "round {round} kept a shadow cull it had no pass to feed"
17573            );
17574            assert_eq!(
17575                drawing_draws - renderer.counters().draws,
17576                (shadow::CASCADES + 1) as u64 * buckets,
17577                "round {round}: the frame's own draw count did not lose exactly the atlas's \
17578                 calls — one per bucket per cascade, and one per bucket for the spot's tile"
17579            );
17580        }
17581
17582        renderer.destroy(device);
17583        recorder.assert_valid();
17584    }
17585
17586    /// A cadence that holds every map one rung down for a frame, with the whole
17587    /// atlas's worth of tiles to spend.
17588    ///
17589    /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
17590    /// the console: [`shadow::r_shadow_cadence`] is process-global and the
17591    /// shadow pass is in every frame's pass list, so a test that moved it would
17592    /// change the frame every other test in this module draws.
17593    const HOLD_TWO: shadow::Cadence = shadow::Cadence {
17594        hold: 2,
17595        faces: shadow::TILES,
17596    };
17597
17598    /// How the shadow pass loaded its depth attachment, over the commands from
17599    /// `from` on, and [`None`] where the frame recorded no such pass.
17600    ///
17601    /// **The observable the tile clear otherwise has none for.** A frame that
17602    /// kept a tile and a frame that redrew every one of them sample maps that
17603    /// may be identical, so nothing in the picture separates them; this is the
17604    /// declaration that says which the device was told.
17605    fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
17606        use crcbl_hal::null::Command;
17607
17608        recorder.commands()[from..].iter().find_map(|command| {
17609            let Command::BeginRenderPass {
17610                label,
17611                depth_stencil_attachment,
17612                ..
17613            } = command
17614            else {
17615                return None;
17616            };
17617            if label.as_deref() != Some("shadow") {
17618                return None;
17619            }
17620            depth_stencil_attachment
17621                .as_ref()
17622                .map(|attachment| attachment.depth_load)
17623        })
17624    }
17625
17626    /// Direct draws recorded inside the shadow pass, over the commands from
17627    /// `from` on — which is one per tile the pass reset itself, the atlas's
17628    /// geometry being drawn indirectly.
17629    fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
17630        use crcbl_hal::null::Command;
17631
17632        let mut inside = false;
17633        let mut clears = 0;
17634        for command in &recorder.commands()[from..] {
17635            if let Some((_, label)) = command.opens_pass() {
17636                inside = label == Some("shadow");
17637                continue;
17638            }
17639            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17640                inside = false;
17641                continue;
17642            }
17643            if inside && matches!(command, Command::Draw { .. }) {
17644                clears += 1;
17645            }
17646        }
17647        clears
17648    }
17649
17650    /// **The far cascade is redrawn every second frame and the near one every
17651    /// frame**, on a scene where the eye moves and so every map is out of date.
17652    ///
17653    /// Topic 45's cadence rung, and the observable it otherwise
17654    /// has none for: a held map draws a shadow one frame behind its caster,
17655    /// which is a plausible picture and one a golden accepts.
17656    ///
17657    /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17658    /// reset — that is asserted rather than assumed, because a reset would make
17659    /// every frame redraw everything and this test would pass by having
17660    /// switched the cadence off.
17661    #[test]
17662    fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17663        let _blurs = ssao_blur_switch();
17664        let (recorder, device, queue) = open();
17665        let device = device.as_ref();
17666        let (mut renderer, _) = shadow_cache_scene(device, queue);
17667        let sun = DirectionalLight::default();
17668        renderer.set_shadow_cadence(Some(HOLD_TWO));
17669
17670        const FRAMES: usize = 8;
17671        let mut near = 0;
17672        let mut far = 0;
17673        for step in 0..FRAMES {
17674            #[expect(
17675                clippy::cast_precision_loss,
17676                reason = "a handful of frames, and the step is what is wanted"
17677            )]
17678            let camera = Camera {
17679                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17680                ..Camera::default()
17681            };
17682            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17683            assert_eq!(
17684                renderer.shadow_cadence_reset(),
17685                step == 0,
17686                "frame {step}: only the first frame has an atlas to lay out, and a reset \
17687                 after it would redraw everything and leave nothing for the cadence to hold"
17688            );
17689            near += usize::from(renderer.shadow_cascade_redrawn(0));
17690            far += usize::from(renderer.shadow_cascade_redrawn(1));
17691            drawn.release(device);
17692        }
17693        assert_eq!(
17694            near, FRAMES,
17695            "the near cascade is fitted to the eye and is on the top rung: every frame"
17696        );
17697        assert_eq!(
17698            far,
17699            FRAMES / 2,
17700            "the far cascade is one rung down, so every second frame"
17701        );
17702
17703        renderer.destroy(device);
17704        recorder.assert_valid();
17705    }
17706
17707    /// **A frame that keeps a tile loads the attachment and resets the tiles it
17708    /// redraws itself**, and a frame that keeps none clears it — which is what
17709    /// shipped.
17710    ///
17711    /// The half of the cadence a redraw count cannot see: holding a tile is only
17712    /// worth anything if the tile survives, and the one clear this seam has
17713    /// covers the whole image. A frame that loaded and reset nothing would draw
17714    /// into tiles still holding the last frame's depths, and under reversed-Z a
17715    /// caster that moved away would go on occluding.
17716    #[test]
17717    fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17718        let _blurs = ssao_blur_switch();
17719        let (recorder, device, queue) = open();
17720        let device = device.as_ref();
17721        let (mut renderer, _) = shadow_cache_scene(device, queue);
17722        let sun = DirectionalLight::default();
17723
17724        // The first frame lays the atlas out, so it clears and redraws
17725        // everything whatever the console says.
17726        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17727        first.release(device);
17728        assert_eq!(
17729            shadow_pass_depth_load(&recorder, 0),
17730            Some(LoadOp::Clear),
17731            "the frame that lays the atlas out has nothing to keep"
17732        );
17733        assert_eq!(
17734            tile_clears_in_the_shadow_pass(&recorder, 0),
17735            0,
17736            "and so resets no tile of its own"
17737        );
17738
17739        renderer.set_shadow_cadence(Some(HOLD_TWO));
17740        let mut seen = recorder.commands().len();
17741        let mut loaded = 0;
17742        for step in 1..4 {
17743            #[expect(
17744                clippy::cast_precision_loss,
17745                reason = "a handful of frames, and the step is what is wanted"
17746            )]
17747            let camera = Camera {
17748                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17749                ..Camera::default()
17750            };
17751            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17752            let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17753            let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17754            let faces = renderer.shadow_faces_redrawn() as usize;
17755            if load == LoadOp::Load {
17756                loaded += 1;
17757                assert_eq!(
17758                    clears, faces,
17759                    "frame {step} loaded the attachment and reset {clears} of the {faces} \
17760                     tiles it redrew"
17761                );
17762                assert!(
17763                    faces < shadow::TILES,
17764                    "frame {step} loaded an attachment while redrawing every tile"
17765                );
17766            } else {
17767                assert_eq!(
17768                    clears, 0,
17769                    "frame {step} cleared the attachment and reset {clears} tiles again"
17770                );
17771            }
17772            seen = recorder.commands().len();
17773            drawn.release(device);
17774        }
17775        assert!(
17776            loaded > 0,
17777            "no frame kept a tile, so nothing here is about the load path"
17778        );
17779
17780        renderer.destroy(device);
17781        recorder.assert_valid();
17782    }
17783
17784    /// A point light costs the budget every face it draws, not one.
17785    ///
17786    /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17787    /// a sum over the groups a frame redrew of the maps each of them owns, and
17788    /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17789    /// here is built on the sun and a spot, which own one map each — so a face
17790    /// count that answered `1` for every group would satisfy all of them, and
17791    /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17792    /// suite. This is what binds on the difference.
17793    #[test]
17794    fn a_point_light_costs_the_budget_every_face_it_draws() {
17795        let _blurs = ssao_blur_switch();
17796        let (_recorder, device, queue) = open();
17797        let device = device.as_ref();
17798        let mut renderer =
17799            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17800        let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17801        renderer.set_lights(&[shadowable_point(-1.0)]);
17802        let sun = DirectionalLight::default();
17803
17804        // Every group is forced on the first frame — the image has held none of
17805        // them — so this counts what a full redraw actually costs.
17806        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17807        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17808        first.release(device);
17809        let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17810        assert!(
17811            renderer.shadow_lights().base_of(0).is_some(),
17812            "the point must hold a run of tiles, or there is no multi-face group to count"
17813        );
17814        assert!(
17815            renderer.shadow_faces_redrawn() >= point_faces,
17816            "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17817             {point_faces} it owns — so the budget is counting groups rather than the maps they \
17818             draw, and a cube would slip past a budget of one",
17819            renderer.shadow_faces_redrawn()
17820        );
17821    }
17822
17823    /// **A frame never redraws more tiles than the budget allows**, and every
17824    /// map still gets its turn.
17825    ///
17826    /// The starvation half is what makes this more than an inequality: a
17827    /// schedule that spent the budget on the same maps every frame would satisfy
17828    /// the bound and never draw the rest at all.
17829    #[test]
17830    fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17831        let _blurs = ssao_blur_switch();
17832        let (recorder, device, queue) = open();
17833        let device = device.as_ref();
17834        let (mut renderer, _) = shadow_cache_scene(device, queue);
17835        let sun = DirectionalLight::default();
17836
17837        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17838        first.release(device);
17839        assert!(
17840            renderer.shadow_lights().base_of(0).is_some(),
17841            "the spot must hold a run, or the budget has only the cascades to bind on"
17842        );
17843
17844        // One tile a frame: the two cascades and the spot's map cannot all fit,
17845        // so something is held on every frame of the run below.
17846        const BUDGET: u32 = 1;
17847        renderer.set_shadow_cadence(Some(shadow::Cadence {
17848            hold: 1,
17849            faces: BUDGET as usize,
17850        }));
17851        const FRAMES: usize = 12;
17852        let mut drew = [0usize; 3];
17853        for step in 1..=FRAMES {
17854            #[expect(
17855                clippy::cast_precision_loss,
17856                reason = "a handful of frames, and the step is what is wanted"
17857            )]
17858            let camera = Camera {
17859                eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17860                ..Camera::default()
17861            };
17862            // The spot drifts too: its map is not fitted to the camera, so a
17863            // moving eye alone leaves it up to date and asking for nothing.
17864            #[expect(
17865                clippy::cast_precision_loss,
17866                reason = "a handful of frames, and the step is what is wanted"
17867            )]
17868            renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17869            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17870            assert!(
17871                renderer.shadow_faces_redrawn() <= BUDGET,
17872                "frame {step} redrew {} tiles against a budget of {BUDGET}",
17873                renderer.shadow_faces_redrawn()
17874            );
17875            drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17876            drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17877            drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17878            drawn.release(device);
17879        }
17880        for (map, count) in drew.iter().enumerate() {
17881            assert!(
17882                *count > 0,
17883                "map {map} was never redrawn in {FRAMES} frames under a budget of \
17884                 {BUDGET}: {drew:?}"
17885            );
17886        }
17887
17888        renderer.destroy(device);
17889        recorder.assert_valid();
17890    }
17891
17892    /// **A light that jumps further than its own radius resets the cadence**,
17893    /// and one that drifts inside it does not.
17894    ///
17895    /// Topic 45's "a moving light or camera cut resets it",
17896    /// made precise: a map whose centre has moved past the map's own reach is
17897    /// not a frame out of date, it is about somewhere else — so it is redrawn on
17898    /// the frame that notices rather than when its turn comes round. Both arms,
17899    /// because a reset that fired on every move would be the cadence switched
17900    /// off.
17901    #[test]
17902    fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17903        let _blurs = ssao_blur_switch();
17904        let (recorder, device, queue) = open();
17905        let device = device.as_ref();
17906        let (mut renderer, _) = shadow_cache_scene(device, queue);
17907        let sun = DirectionalLight::default();
17908        let camera = Camera::default();
17909        // The coarsest hold there is, so a redraw of the spot's map on the
17910        // frames below is the reset and not its turn.
17911        renderer.set_shadow_cadence(Some(shadow::Cadence {
17912            hold: 8,
17913            faces: shadow::TILES,
17914        }));
17915
17916        let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17917        settle.release(device);
17918        for _ in 0..2 {
17919            settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17920            settle.release(device);
17921        }
17922        assert!(
17923            !renderer.shadow_cadence_reset(),
17924            "the scene has settled, so nothing is about somewhere else"
17925        );
17926
17927        // A drift well inside the light's own radius: out of date, not moved.
17928        renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17929        let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17930        drifted.release(device);
17931        assert!(
17932            !renderer.shadow_cadence_reset(),
17933            "a light that moved a sixteenth of its radius is a map a frame out of date"
17934        );
17935
17936        // And a jump past it. `shadowable_spot`'s radius is what the reach is
17937        // taken from, so this is a light standing where its own map says
17938        // nothing.
17939        renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17940        let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17941        jumped.release(device);
17942        assert!(
17943            renderer.shadow_cadence_reset(),
17944            "a light that jumped five times its own radius must not hold its map"
17945        );
17946        assert!(
17947            renderer.shadow_slot_redrawn(0),
17948            "and the reset is only a reset if the map is actually redrawn"
17949        );
17950
17951        renderer.destroy(device);
17952        recorder.assert_valid();
17953    }
17954
17955    /// **A console knob about *sampling* the atlas does not redraw it.**
17956    ///
17957    /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17958    /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17959    /// receiver it reads — and not one byte of what the depth pass writes into
17960    /// it is any of theirs. Yet the
17961    /// shadow views' blocks are the frame's block spread, and the cache record
17962    /// is those blocks' bytes — so until the views zeroed the row, a person
17963    /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17964    /// and in this crate's own test process the filter tests moving that cell
17965    /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17966    /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17967    /// here is what makes the move below the only one in flight.
17968    #[test]
17969    fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17970        let switch = shadow_filter_switch();
17971        let (recorder, device, queue) = open();
17972        let device = device.as_ref();
17973        let (mut renderer, _) = shadow_cache_scene(device, queue);
17974        let camera = Camera::default();
17975        let sun = DirectionalLight::default();
17976        let mut seen = 0usize;
17977        assert!(
17978            drew_the_atlas(
17979                &recorder,
17980                &mut seen,
17981                device,
17982                &mut renderer,
17983                queue,
17984                &camera,
17985                &sun
17986            ),
17987            "the first frame of all draws the atlas"
17988        );
17989        assert!(
17990            !drew_the_atlas(
17991                &recorder,
17992                &mut seen,
17993                device,
17994                &mut renderer,
17995                queue,
17996                &camera,
17997                &sun
17998            ),
17999            "a still second frame has to hold it, or the move below proves nothing"
18000        );
18001
18002        switch.filter(shadow::Filter::Box);
18003        switch.seam(0.5);
18004        assert!(
18005            !drew_the_atlas(
18006                &recorder,
18007                &mut seen,
18008                device,
18009                &mut renderer,
18010                queue,
18011                &camera,
18012                &sun
18013            ),
18014            "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
18015             sampling knob reached the record of what the maps were drawn from"
18016        );
18017
18018        // The bias pair sits in a different row of the same block, and the
18019        // second row it reaches is `Cascades::params`, which is rebuilt every
18020        // frame — so this is the arm that says the *whole* row is kept out of
18021        // the record rather than the one lane the filter is in.
18022        switch.bias(8.0);
18023        switch.offset(8.0);
18024        assert!(
18025            !drew_the_atlas(
18026                &recorder,
18027                &mut seen,
18028                device,
18029                &mut renderer,
18030                queue,
18031                &camera,
18032                &sun
18033            ),
18034            "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
18035             the bias row reached the record of what the maps were drawn from"
18036        );
18037
18038        renderer.destroy(device);
18039        recorder.assert_valid();
18040    }
18041
18042    /// **Every input the atlas is drawn from redraws it**, one at a time.
18043    ///
18044    /// The half that stops "cached everything, for ever" from passing every
18045    /// assertion above. Each arm moves exactly one thing and asserts the next
18046    /// frame draws again — and then holds still and asserts it stops, so an arm
18047    /// cannot pass by having broken the cache outright.
18048    ///
18049    /// The camera is in here because it is not obvious: a shadow map is drawn
18050    /// from a light, not from the eye. But a cascade is fitted to the camera's
18051    /// own frustum, and every shadow cull selects a DAG's detail at the camera's
18052    /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
18053    /// different light map wherever a DAG is in the light's cull.
18054    /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
18055    /// caster must *not* redraw.
18056    ///
18057    /// `settles` is how many still frames it takes to go quiet again, and it is
18058    /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
18059    /// instance's `previous_transform` back at rest on the frame *after* the
18060    /// move, and that is a write, which is a change this record cannot tell
18061    /// from any other. See `InstancePool::take_written`, which says so.
18062    #[test]
18063    fn each_thing_the_atlas_is_drawn_from_redraws_it() {
18064        let camera = Camera::default();
18065        let sun = DirectionalLight::default();
18066        let moved_camera = Camera {
18067            eye: camera.eye + Vec3::X * 4.0,
18068            ..camera
18069        };
18070        type Change = fn(&mut ForwardRenderer, InstanceHandle);
18071        let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
18072            (
18073                "a caster moved",
18074                |renderer, cube| {
18075                    renderer.set_instance(
18076                        cube,
18077                        &InstanceDesc {
18078                            mesh: DEMO_CUBE,
18079                            material: DEMO_UNTINTED,
18080                            transform: Mat4::from_translation(Vec3::X),
18081                        },
18082                    );
18083                },
18084                &camera,
18085                &sun,
18086                2,
18087            ),
18088            (
18089                "a caster removed",
18090                |renderer, cube| renderer.remove_instance(cube),
18091                &camera,
18092                &sun,
18093                1,
18094            ),
18095            (
18096                "the light moved",
18097                |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
18098                &camera,
18099                &sun,
18100                1,
18101            ),
18102            ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
18103        ];
18104
18105        for (what, change, camera, sun, settles) in arms {
18106            let (recorder, device, queue) = open();
18107            let device = device.as_ref();
18108            let (mut renderer, cube) = shadow_cache_scene(device, queue);
18109            let mut seen = 0usize;
18110            // Two frames, so the atlas is drawn and then held: the arm's own
18111            // assertion is about a frame that would otherwise have cached.
18112            for round in 0..2 {
18113                let drew = drew_the_atlas(
18114                    &recorder,
18115                    &mut seen,
18116                    device,
18117                    &mut renderer,
18118                    queue,
18119                    &Camera::default(),
18120                    &DirectionalLight::default(),
18121                );
18122                assert_eq!(
18123                    drew,
18124                    round == 0,
18125                    "{what}: the still frames before the change did not settle"
18126                );
18127            }
18128
18129            change(&mut renderer, cube);
18130            assert!(
18131                drew_the_atlas(
18132                    &recorder,
18133                    &mut seen,
18134                    device,
18135                    &mut renderer,
18136                    queue,
18137                    camera,
18138                    sun
18139                ),
18140                "{what} and the atlas was not drawn again"
18141            );
18142            // And it goes quiet again in exactly `settles` frames, so the arm
18143            // cannot pass by having broken the cache rather than by having
18144            // invalidated it — and a change that started redrawing for ever
18145            // fails here rather than going unnoticed.
18146            for round in 0..settles {
18147                assert_eq!(
18148                    drew_the_atlas(
18149                        &recorder,
18150                        &mut seen,
18151                        device,
18152                        &mut renderer,
18153                        queue,
18154                        camera,
18155                        sun
18156                    ),
18157                    round + 1 < settles,
18158                    "{what}: the still frames after the change did not settle in {settles}"
18159                );
18160            }
18161
18162            renderer.destroy(device);
18163            recorder.assert_valid();
18164        }
18165    }
18166
18167    /// **A frame skinning an object with no box always redraws the atlas**,
18168    /// and that is a limit written down rather than a gap.
18169    ///
18170    /// A skinned caster's vertices are produced by a compute dispatch into the
18171    /// pool, so there is nothing on the host to compare: the palette a caller
18172    /// hands over is not the geometry, and the geometry is never read back. The
18173    /// honest answer is to redraw, and the dishonest one is a map of a pose the
18174    /// character has left. Without [`SkinnedInstanceDesc::bounds`] nothing says
18175    /// which maps the pose is in, so it is every one — see `shadow_reach`'s
18176    /// skinned tests for an object that has a box.
18177    #[test]
18178    fn a_frame_skinning_an_unboxed_object_never_caches_the_atlas() {
18179        let (recorder, device, queue) = open();
18180        let device = device.as_ref();
18181        let mut fixture = SkinnedFixture::build(device, queue);
18182        // Pinned, on `shadow_cache_scene`'s terms: a console hold would make a
18183        // lap cache for a reason that is not the one asked about.
18184        fixture
18185            .renderer
18186            .set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
18187        fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
18188        fixture
18189            .renderer
18190            .add_skinned_instance(&SkinnedInstanceDesc {
18191                mesh: &fixture.skinned,
18192                material: DEMO_UNTINTED,
18193                transform: Mat4::IDENTITY,
18194                bounds: None,
18195            })
18196            .expect("room for one object");
18197        let imported = swapchain_image_at(device, TEST_EXTENT);
18198        let mut pool = crate::TransientPool::new();
18199
18200        // The same palette and the same plan every lap, so nothing a host-side
18201        // comparison could see has moved.
18202        for lap in 0..3 {
18203            fixture.begin(device);
18204            let mut graph = crate::RenderGraph::new(queue);
18205            let target = graph.import_image("target", imported);
18206            fixture.renderer.add_skinned_passes(
18207                &mut graph,
18208                &pool,
18209                target,
18210                TEST_EXTENT,
18211                &fixture.skinning,
18212            );
18213            let compiled = graph.compile(&pool).expect("a legal frame");
18214            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18215                label: Some("skinned lap"),
18216                queue,
18217            });
18218            compiled
18219                .execute(device, &mut pool, encoder.as_mut(), None)
18220                .expect("the graph executed");
18221            device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
18222            assert!(
18223                !fixture.renderer.shadow_atlas_cached(),
18224                "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
18225            );
18226            assert!(
18227                fixture.renderer.shadow_lights().base_of(0).is_some(),
18228                "the spot must hold a slot for its group to be asked about"
18229            );
18230            assert_eq!(
18231                [
18232                    fixture.renderer.shadow_cascade_redrawn(0),
18233                    fixture.renderer.shadow_cascade_redrawn(1),
18234                    fixture.renderer.shadow_slot_redrawn(0),
18235                ],
18236                [true; 3],
18237                "lap {lap}: an object with no box held a group its pose could be in"
18238            );
18239        }
18240
18241        fixture.destroy(device);
18242        pool.destroy(device);
18243        device.destroy_image_view(imported.view);
18244        device.destroy_image(imported.image);
18245        recorder.assert_valid();
18246    }
18247
18248    /// **Switching the shadows off clears the atlas once, and then holds the
18249    /// clear**, which is the same cache answering a frame that draws nothing.
18250    ///
18251    /// The switched-off frame is not itself a cached frame: the pass has to run
18252    /// to write the reversed-Z clear that makes every comparison come back lit,
18253    /// and the image holds the last drawn maps until it does. What *is* cached
18254    /// is every frame after it, and the record for a switched-off frame is
18255    /// deliberately blind to the camera and the casters, because nothing about
18256    /// them reaches an atlas nothing draws into.
18257    #[test]
18258    fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
18259        let (recorder, device, queue) = open();
18260        let device = device.as_ref();
18261        let (mut renderer, cube) = shadow_cache_scene(device, queue);
18262        let camera = Camera::default();
18263        let sun = DirectionalLight::default();
18264        let mut seen = 0usize;
18265
18266        assert!(
18267            drew_the_atlas(
18268                &recorder,
18269                &mut seen,
18270                device,
18271                &mut renderer,
18272                queue,
18273                &camera,
18274                &sun
18275            ),
18276            "the first frame draws the maps"
18277        );
18278        renderer.set_effect_request(EffectRequest {
18279            programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
18280            ..EffectRequest::default()
18281        });
18282        assert!(
18283            drew_the_atlas(
18284                &recorder,
18285                &mut seen,
18286                device,
18287                &mut renderer,
18288                queue,
18289                &camera,
18290                &sun
18291            ),
18292            "the frame that switched the shadows off has to run the pass that clears the maps \
18293             out of the image"
18294        );
18295        assert!(
18296            !drew_the_atlas(
18297                &recorder,
18298                &mut seen,
18299                device,
18300                &mut renderer,
18301                queue,
18302                &camera,
18303                &sun
18304            ),
18305            "a second switched-off frame cleared an atlas that was already clear"
18306        );
18307        // And nothing about the scene reaches a frame that draws no map: the
18308        // caster moves and the atlas is still the clear it was.
18309        renderer.set_instance(
18310            cube,
18311            &InstanceDesc {
18312                mesh: DEMO_CUBE,
18313                material: DEMO_UNTINTED,
18314                transform: Mat4::from_translation(Vec3::X),
18315            },
18316        );
18317        assert!(
18318            !drew_the_atlas(
18319                &recorder,
18320                &mut seen,
18321                device,
18322                &mut renderer,
18323                queue,
18324                &camera,
18325                &sun
18326            ),
18327            "a caster moved with the shadows off, and the frame cleared the atlas over again"
18328        );
18329
18330        renderer.set_effect_request(EffectRequest::default());
18331        assert!(
18332            drew_the_atlas(
18333                &recorder,
18334                &mut seen,
18335                device,
18336                &mut renderer,
18337                queue,
18338                &camera,
18339                &sun
18340            ),
18341            "switching the shadows back on has to draw the maps the clear replaced"
18342        );
18343
18344        renderer.destroy(device);
18345        recorder.assert_valid();
18346    }
18347
18348    /// **A frame the graph refuses leaves the shadow atlas where it was.**
18349    ///
18350    /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
18351    /// described in full and then thrown away, and
18352    /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
18353    /// thing that writes the pool's ledger — never runs. That is the case a
18354    /// renderer-held `ResourceState`, stepped forward while the passes were
18355    /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
18356    /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
18357    /// object, because with nothing recorded there is nothing to contradict. The
18358    /// guard would be silent on precisely the drift it exists to find, which is
18359    /// why [`imported_state`] reads the ledger instead of a second copy of it.
18360    ///
18361    /// The observable is the first barrier the *next* frame records on the
18362    /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
18363    /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
18364    /// layout the image was never in, which is a layout mismatch on every
18365    /// backend and a discarded image on some.
18366    #[test]
18367    fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
18368        use crcbl_hal::null::Command;
18369
18370        let (recorder, device, queue) = open();
18371        let device = device.as_ref();
18372        let mut renderer =
18373            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18374        let atlas = renderer.shadow_atlas();
18375        let placeholder = renderer.shadow_placeholder;
18376        let mut pool = crate::TransientPool::new();
18377        let imported = swapchain_image(device);
18378
18379        // The refused frame: every pass a real frame declares, and beside them
18380        // one transient nothing reads or writes. `compile` answers
18381        // `UnusedTransient` and the whole description — the shadow atlas's
18382        // import included — is dropped without a command being recorded.
18383        renderer
18384            .begin_frame(
18385                device,
18386                &Camera::default(),
18387                &DirectionalLight::default(),
18388                (64, 48),
18389            )
18390            .expect("write");
18391        {
18392            let mut graph = crate::RenderGraph::new(queue);
18393            let target = graph.import_image("target", imported);
18394            renderer.add_passes(&mut graph, &pool, target, (64, 48));
18395            graph.create_image("orphan", crate::targets::scene_color((64, 48)));
18396            let refused = graph
18397                .compile(&pool)
18398                .expect_err("a transient no pass declares");
18399            assert!(
18400                matches!(refused, crate::GraphError::UnusedTransient { .. }),
18401                "the frame has to be refused for the reason this test is about — a graph that \
18402                 compiled would go on to execute and the ledger would be written after all: \
18403                 {refused:?}"
18404            );
18405        }
18406        assert_eq!(
18407            pool.imported_image_use(atlas),
18408            None,
18409            "nothing executed, so the ledger has nothing to say about the atlas — this is the \
18410             emptiness `InitialClaim::Tracked` cannot check against"
18411        );
18412
18413        // And the frame after it, which does run.
18414        renderer
18415            .begin_frame(
18416                device,
18417                &Camera::default(),
18418                &DirectionalLight::default(),
18419                (64, 48),
18420            )
18421            .expect("write");
18422        let mut graph = crate::RenderGraph::new(queue);
18423        let target = graph.import_image("target", imported);
18424        renderer.add_passes(&mut graph, &pool, target, (64, 48));
18425        let compiled = graph.compile(&pool).expect("a legal frame");
18426        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18427            label: Some("frame after a refusal"),
18428            queue,
18429        });
18430        compiled
18431            .execute(device, &mut pool, encoder.as_mut(), None)
18432            .expect("the graph executed");
18433        let commands = encoder.finish().expect("recording succeeded");
18434
18435        // The first barrier each of the two images gets. Only the refused frame
18436        // ran before this one and it recorded nothing, so these are the frame's
18437        // opening transitions.
18438        let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
18439        for command in recorder.commands() {
18440            let Command::Barrier { images, .. } = command else {
18441                continue;
18442            };
18443            for barrier in images {
18444                if barrier.image != atlas && barrier.image != placeholder {
18445                    continue;
18446                }
18447                if opened.iter().any(|(image, _, _)| *image == barrier.image) {
18448                    continue;
18449                }
18450                opened.push((barrier.image, barrier.from, barrier.to));
18451            }
18452        }
18453        for (image, from, to) in &opened {
18454            assert_eq!(
18455                *from,
18456                ResourceState::Undefined,
18457                "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
18458                 layout to. The declaration is what makes the transition true, so one that has \
18459                 moved on without an executed frame behind it names a source scope and an old \
18460                 layout the image was never in — and the ledger is empty, so nothing refuses it \
18461                 either. Image {image:?}"
18462            );
18463        }
18464        // The loop above is silent on an empty list and on a short one, and a
18465        // wrong declaration shortens it: an image declared in the state it is
18466        // wanted in needs no transition, so it drops out of the stream
18467        // altogether rather than appearing with the wrong source.
18468        assert_eq!(
18469            opened.len(),
18470            2,
18471            "the atlas and its placeholder are both imported every frame and both are wanted in a \
18472             state they are not in, so both have to be barriered: {opened:?}"
18473        );
18474        assert!(
18475            opened
18476                .iter()
18477                .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
18478            "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
18479        );
18480
18481        renderer.destroy(device);
18482        device.destroy_command_buffer(commands);
18483        pool.destroy(device);
18484        device.destroy_image_view(imported.view);
18485        device.destroy_image(imported.image);
18486        recorder.assert_valid();
18487    }
18488
18489    /// **The import audit still refuses an engine site whose declaration is
18490    /// wrong**, now that the shadow atlas's is read out of the same ledger it is
18491    /// checked against.
18492    ///
18493    /// That pair is deliberately circular and this test is what keeps it from
18494    /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
18495    /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
18496    /// ever find them agreeing — their safety comes from there being one answer
18497    /// rather than from the check. Every *other* import in the frame declares a
18498    /// constant, and `ssao-placeholder` is the one this drives a ledger entry
18499    /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
18500    /// declared so on every frame, so a graph that leaves it somewhere else is a
18501    /// declaration the next `compile` has to refuse.
18502    #[test]
18503    fn the_guard_still_catches_an_engine_import_that_lies() {
18504        let (recorder, device, queue) = open();
18505        let device = device.as_ref();
18506        let mut renderer =
18507            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18508        let mut pool = crate::TransientPool::new();
18509        let imported = swapchain_image(device);
18510        let occlusion = renderer.ambient_occlusion_placeholder.image;
18511
18512        // A graph of this test's own, which moves the renderer's occlusion
18513        // placeholder somewhere `add_passes` does not expect. Same image handle,
18514        // so the entry it leaves in the ledger is the one the next `compile`
18515        // reads for `ssao-placeholder`.
18516        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18517            label: Some("move the placeholder"),
18518            queue,
18519        });
18520        {
18521            let mut graph = crate::RenderGraph::new(queue);
18522            let moved = graph.import_image(
18523                "moved-placeholder",
18524                ImportedImage {
18525                    image: occlusion,
18526                    view: renderer.ambient_occlusion_placeholder.view,
18527                    format: Format::Rgba8Unorm,
18528                    extent: (1, 1),
18529                    initial: ResourceState::ShaderRead,
18530                    claim: InitialClaim::Tracked,
18531                    final_state: ResourceState::TransferSrc,
18532                },
18533            );
18534            graph
18535                .add_copy_pass("read the placeholder")
18536                .use_image(moved, ResourceState::TransferSrc)
18537                .execute(|_| {});
18538            graph
18539                .compile(&pool)
18540                .expect("a legal frame")
18541                .execute(device, &mut pool, encoder.as_mut(), None)
18542                .expect("the graph executed");
18543        }
18544        let commands = encoder.finish().expect("recording succeeded");
18545        assert_eq!(
18546            pool.imported_image_use(occlusion),
18547            Some(ResourceState::TransferSrc),
18548            "the ledger has to have moved for the frame below to have anything to disagree with"
18549        );
18550
18551        renderer
18552            .begin_frame(
18553                device,
18554                &Camera::default(),
18555                &DirectionalLight::default(),
18556                (64, 48),
18557            )
18558            .expect("write");
18559        let mut graph = crate::RenderGraph::new(queue);
18560        let target = graph.import_image("target", imported);
18561        renderer.add_passes(&mut graph, &pool, target, (64, 48));
18562        let refused = graph
18563            .compile(&pool)
18564            .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
18565        let crate::GraphError::ImportStateMismatch {
18566            resource,
18567            declared,
18568            left,
18569        } = &refused
18570        else {
18571            panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
18572        };
18573        assert_eq!(resource, "ssao-placeholder");
18574        assert_eq!(*declared, ResourceState::ShaderRead);
18575        assert_eq!(*left, ResourceState::TransferSrc);
18576
18577        renderer.destroy(device);
18578        device.destroy_command_buffer(commands);
18579        pool.destroy(device);
18580        device.destroy_image_view(imported.view);
18581        device.destroy_image(imported.image);
18582        recorder.assert_valid();
18583    }
18584
18585    /// Compiles one frame and names the passes it turned out to be, in order.
18586    ///
18587    /// Compiled and not executed: what a pass costs is not the question here,
18588    /// only which of them the frame declared. Names rather than a count since
18589    /// the toggles landed — a count says a frame lost two passes and a list says
18590    /// *which* two, which is the difference between "the switch did something"
18591    /// and "the switch did the thing it is for".
18592    fn passes_in_a_frame(
18593        device: &dyn Device,
18594        queue: QueueHandle,
18595        renderer: &mut ForwardRenderer,
18596        imported: ImportedImage,
18597        pool: &crate::TransientPool,
18598        extent: (u32, u32),
18599    ) -> Vec<String> {
18600        renderer
18601            .begin_frame(
18602                device,
18603                &Camera::default(),
18604                &DirectionalLight::default(),
18605                extent,
18606            )
18607            .expect("write");
18608        let mut graph = crate::RenderGraph::new(queue);
18609        let target = graph.import_image("target", imported);
18610        renderer.add_passes(&mut graph, pool, target, extent);
18611        graph
18612            .compile(pool)
18613            .expect("a legal frame")
18614            .passes()
18615            .iter()
18616            .map(|pass| pass.label().to_string())
18617            .collect()
18618    }
18619
18620    /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
18621    /// radius, a direction and a cone well inside the widest one allowed.
18622    /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
18623    /// than one.
18624    ///
18625    /// The spot beside it is one tile and one face, so a scene built only from
18626    /// spots cannot tell a budget counting **faces** from one counting groups —
18627    /// which is what this exists to give a check something to bind on.
18628    fn shadowable_point(x: f32) -> Light {
18629        Light::Point(crate::light::PointLight {
18630            position: Vec3::new(x, 2.0, 0.0),
18631            radius: 8.0,
18632            color: Vec3::ONE,
18633            fill: false,
18634        })
18635    }
18636
18637    fn shadowable_spot(x: f32) -> Light {
18638        Light::Spot(crate::light::SpotLight {
18639            position: Vec3::new(x, 2.0, 0.0),
18640            radius: 8.0,
18641            color: Vec3::ONE,
18642            direction: -Vec3::Y,
18643            inner_angle: 0.3,
18644            outer_angle: 0.6,
18645            fill: false,
18646        })
18647    }
18648
18649    /// The page's anisotropy is the plan's default clamped to the device, and
18650    /// one on a device that was not granted the feature — whatever its limit
18651    /// says.
18652    ///
18653    /// The last arm is the one worth having: `gate_limits_on_features` narrows
18654    /// a declined feature's limit on `crcbl-vk`, but a backend that did not
18655    /// would report sixteen beside an absent feature, and a clamp that read the
18656    /// limit alone would ask for a sampler the device refuses.
18657    #[test]
18658    fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
18659        let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
18660            features,
18661            limits: crcbl_hal::Limits {
18662                max_sampler_anisotropy,
18663                ..crcbl_hal::Limits::desktop()
18664            },
18665        };
18666        let granted = Features::SAMPLER_ANISOTROPY;
18667        assert!(
18668            (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18669                < f32::EPSILON,
18670            "a device above the default gets the default"
18671        );
18672        assert!(
18673            (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18674            "a device below the default gets its own limit"
18675        );
18676        assert!(
18677            (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18678                < f32::EPSILON,
18679            "a device that was not granted the feature gets one, whatever its limit says"
18680        );
18681    }
18682
18683    /// A new anisotropy is a new sampler, and every slot moves onto it at its
18684    /// own frame — the old one living until the last slot has left it.
18685    ///
18686    /// Counted on the null recorder rather than looked at: the sampler count
18687    /// rises by one at the call, holds through every slot's frame but the
18688    /// last, and falls back there, while the live group count never moves at
18689    /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18690    /// destroyed a group a slot in flight still held, and one that never
18691    /// happened each move one of those counts; a second lap of the ring
18692    /// creating any group at all would be a rebuild that did not know it was
18693    /// done.
18694    #[test]
18695    fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18696        let (recorder, device, queue) =
18697            open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18698        let device = device.as_ref();
18699        let mut renderer =
18700            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18701        assert!(
18702            (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18703            "a renderer nobody has called the setter on samples at the default"
18704        );
18705        let samplers = recorder.live_objects(ObjectKind::Sampler);
18706        let groups = recorder.live_objects(ObjectKind::BindGroup);
18707        let groups_created = || {
18708            recorder
18709                .events()
18710                .iter()
18711                .filter(|event| {
18712                    matches!(
18713                        event,
18714                        Event::Created {
18715                            kind: ObjectKind::BindGroup,
18716                            ..
18717                        }
18718                    )
18719                })
18720                .count()
18721        };
18722
18723        renderer
18724            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18725            .expect("the device allows it");
18726        assert_eq!(
18727            recorder.live_objects(ObjectKind::Sampler),
18728            samplers,
18729            "the value in force creates nothing"
18730        );
18731
18732        renderer
18733            .set_anisotropy(device, 4.0)
18734            .expect("the device allows it");
18735        assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18736        assert_eq!(
18737            recorder.live_objects(ObjectKind::Sampler),
18738            samplers + 1,
18739            "the new sampler stands beside the one every slot still names"
18740        );
18741        assert_eq!(
18742            recorder.live_objects(ObjectKind::BindGroup),
18743            groups,
18744            "no group moves until its slot's frame"
18745        );
18746
18747        for round in 0..FRAMES_IN_FLIGHT {
18748            renderer
18749                .begin_frame(
18750                    device,
18751                    &Camera::default(),
18752                    &DirectionalLight::default(),
18753                    (64, 48),
18754                )
18755                .expect("write");
18756            let expected = if round + 1 < FRAMES_IN_FLIGHT {
18757                samplers + 1
18758            } else {
18759                samplers
18760            };
18761            assert_eq!(
18762                recorder.live_objects(ObjectKind::Sampler),
18763                expected,
18764                "round {round}: the replaced sampler lives until the last slot has left it"
18765            );
18766            assert_eq!(
18767                recorder.live_objects(ObjectKind::BindGroup),
18768                groups,
18769                "round {round}: every rebuilt group replaced one"
18770            );
18771        }
18772        let created = groups_created();
18773        for _ in 0..FRAMES_IN_FLIGHT {
18774            renderer
18775                .begin_frame(
18776                    device,
18777                    &Camera::default(),
18778                    &DirectionalLight::default(),
18779                    (64, 48),
18780                )
18781                .expect("write");
18782        }
18783        assert_eq!(
18784            groups_created(),
18785            created,
18786            "a slot already on the sampler in force rebuilds nothing"
18787        );
18788
18789        // The clamp: the device's ceiling above it, off below one, the default
18790        // for a value that is not a number.
18791        let ceiling = device.caps().limits.max_sampler_anisotropy;
18792        renderer
18793            .set_anisotropy(device, ceiling * 4.0)
18794            .expect("clamped to what the device allows");
18795        assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18796        renderer
18797            .set_anisotropy(device, 0.0)
18798            .expect("one is the value that turns it off");
18799        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18800        renderer
18801            .set_anisotropy(device, f32::NAN)
18802            .expect("the default is a sampler the device allows");
18803        assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18804
18805        recorder.assert_valid();
18806        renderer.destroy(device);
18807        assert_eq!(
18808            recorder.live_objects(ObjectKind::Sampler),
18809            0,
18810            "the samplers no slot ever adopted went with the renderer"
18811        );
18812    }
18813
18814    /// A device without the feature samples isotropically whatever is asked:
18815    /// the ceiling is one, so the clamp lands on the value already in force and
18816    /// no sampler is created that `create_sampler` would refuse.
18817    #[test]
18818    fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18819        let (recorder, device, queue) = open();
18820        let device = device.as_ref();
18821        assert!(
18822            !device
18823                .caps()
18824                .features
18825                .contains(Features::SAMPLER_ANISOTROPY),
18826            "the default request does not name the feature"
18827        );
18828        let mut renderer =
18829            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18830        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18831        let samplers = recorder.live_objects(ObjectKind::Sampler);
18832
18833        renderer
18834            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18835            .expect("asks for nothing the device lacks");
18836        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18837        assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18838        renderer.destroy(device);
18839    }
18840
18841    /// The knob clamps to the range it documents, in both directions and on a
18842    /// value that is neither.
18843    ///
18844    /// **The `NaN` arm is the one worth having.** A slider that divided by a
18845    /// zero, or a settings file that carried a nonsense string, reaches this
18846    /// with a value that fails every comparison it is put through — so a naive
18847    /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18848    /// `as u32` below would produce a zero extent and a device error a long way
18849    /// from here.
18850    #[test]
18851    fn the_render_scale_is_clamped_to_the_range_it_documents() {
18852        let (recorder, device, queue) = open();
18853        let device = device.as_ref();
18854        let mut renderer =
18855            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18856
18857        assert!(
18858            (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18859            "a renderer nobody has called the setter on draws at full scale"
18860        );
18861
18862        renderer.set_render_scale(0.5);
18863        assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18864
18865        // Above one is supersampling, which this filter is the wrong one for.
18866        renderer.set_render_scale(2.0);
18867        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18868
18869        renderer.set_render_scale(0.01);
18870        assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18871
18872        renderer.set_render_scale(f32::NAN);
18873        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18874        renderer.set_render_scale(f32::INFINITY);
18875        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18876
18877        renderer.destroy(device);
18878        recorder.assert_valid();
18879    }
18880
18881    /// The internal extent is the target rounded, never zero, and is the target
18882    /// itself at full scale.
18883    ///
18884    /// **The floor is not decoration.** A transient image of zero extent is a
18885    /// device error rather than a small frame, and a 4×3 target at the minimum
18886    /// scale is exactly the arithmetic that would produce one.
18887    #[test]
18888    fn the_internal_extent_rounds_and_never_reaches_zero() {
18889        let (recorder, device, queue) = open();
18890        let device = device.as_ref();
18891        let mut renderer =
18892            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18893
18894        assert_eq!(
18895            renderer.internal_extent((1920, 1080)),
18896            (1920, 1080),
18897            "full scale is the absence of the feature, not a resize by one"
18898        );
18899
18900        renderer.set_render_scale(0.5);
18901        assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18902
18903        // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18904        // 756 — both exact — so a target that does *not* divide evenly is what
18905        // shows the rounding. 1281 * 0.7 = 896.7.
18906        renderer.set_render_scale(0.7);
18907        assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18908
18909        renderer.set_render_scale(MIN_RENDER_SCALE);
18910        assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18911        assert_eq!(
18912            renderer.internal_extent((0, 0)),
18913            (1, 1),
18914            "a minimised window is the caller's zero extent, and this may not \
18915             pass it through as one"
18916        );
18917
18918        renderer.destroy(device);
18919        recorder.assert_valid();
18920    }
18921
18922    /// **The upscale is a pass below full scale and is not there above it**, and
18923    /// the frame is otherwise the same list.
18924    ///
18925    /// This is the observable the knob is: everything else about it — the
18926    /// clamps, the rounding — is arithmetic that could be right while the frame
18927    /// went on being drawn at the caller's extent. What says the feature works
18928    /// is that the pass appears, that it appears **last**, and that switching it
18929    /// off leaves the frame that was there before it existed.
18930    #[test]
18931    fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18932        let _blurs = ssao_blur_switch();
18933        let (recorder, device, queue) = open();
18934        let device = device.as_ref();
18935        let mut renderer =
18936            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18937        let imported = swapchain_image_at(device, TEST_EXTENT);
18938        let pool = crate::TransientPool::new();
18939
18940        let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18941        assert!(
18942            !full.contains(&"upscale".to_string()),
18943            "a frame at full scale has no upscale in it: {full:?}"
18944        );
18945
18946        renderer.set_render_scale(0.5);
18947        let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18948        assert_eq!(
18949            scaled.iter().filter(|label| *label == "upscale").count(),
18950            1,
18951            "a scaled frame records exactly one upscale: {scaled:?}"
18952        );
18953        // Last of the passes that draw. The statistics copy is genuinely after
18954        // it and says so — see the comment on `add_copy_pass`'s placement.
18955        let upscale = scaled
18956            .iter()
18957            .position(|label| label == "upscale")
18958            .expect("the assertion above");
18959        let tonemap = scaled
18960            .iter()
18961            .position(|label| label == "tonemap")
18962            .expect("every frame tonemaps");
18963        assert!(
18964            upscale > tonemap,
18965            "the upscale carries what the post chain ended with: {scaled:?}"
18966        );
18967
18968        // **The pyramid gets shorter, and that is the evidence the rest of the
18969        // frame really is smaller.** Everything above this is about the last
18970        // pass; a knob that added an upscale while going on rendering at the
18971        // caller's extent would pass every one of those assertions and save
18972        // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18973        // level count is a number read out of the frame that can only be the
18974        // internal extent's.
18975        let levels = |passes: &[String]| {
18976            passes
18977                .iter()
18978                .filter(|label| label.starts_with("hiz-"))
18979                .count()
18980        };
18981        let internal = renderer.internal_extent(TEST_EXTENT);
18982        assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18983        assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18984        assert!(
18985            levels(&scaled) < levels(&full),
18986            "at this extent the halved frame has to lose a level, or this \
18987             assertion is not looking at anything: {scaled:?}"
18988        );
18989
18990        // And nothing else moved: an upscale is a pass added to the frame, not a
18991        // frame rebuilt around one. The pyramid is the one part that is a
18992        // function of the extent, so it is compared by the count above and
18993        // dropped from the list here.
18994        let without_hiz = |passes: &[String]| -> Vec<String> {
18995            passes
18996                .iter()
18997                .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
18998                .cloned()
18999                .collect()
19000        };
19001        assert_eq!(
19002            without_hiz(&scaled),
19003            without_hiz(&full),
19004            "the scaled frame is the full-scale frame, one pass longer and one \
19005             pyramid shorter"
19006        );
19007
19008        renderer.set_render_scale(1.0);
19009        let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19010        assert_eq!(
19011            back, full,
19012            "the knob goes back, which is what a settings slider does"
19013        );
19014
19015        renderer.destroy(device);
19016        device.destroy_image_view(imported.view);
19017        device.destroy_image(imported.image);
19018        recorder.assert_valid();
19019    }
19020
19021    /// **A skinned-frame overlay receives the display and depth images at the
19022    /// internal extent, before either resolve reconstructs the target.**
19023    ///
19024    /// The callback's own pass attaches the display and depth it received. That
19025    /// makes matching dimensions a graph invariant rather than a comparison of
19026    /// numbers the callback could have been handed without ever using the
19027    /// images; changing either id to a target-sized image makes compilation
19028    /// refuse the mismatched attachments.
19029    #[test]
19030    fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
19031        let (recorder, device, queue) = open();
19032        let device = device.as_ref();
19033        let mut fixture = SkinnedFixture::build(device, queue);
19034        fixture.renderer.set_render_scale(0.5);
19035        fixture.renderer.set_effect_request(EffectRequest {
19036            antialiasing: Some(Antialiasing::Fxaa),
19037            ..EffectRequest::default()
19038        });
19039        fixture.begin(device);
19040        let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
19041
19042        let imported = swapchain_image_at(device, TEST_EXTENT);
19043        let mut pool = crate::TransientPool::new();
19044        {
19045            let mut graph = crate::RenderGraph::new(queue);
19046            let target = graph.import_image("target", imported);
19047            let mut received = None;
19048            fixture.renderer.add_skinned_passes_with_overlay(
19049                &mut graph,
19050                &pool,
19051                target,
19052                TEST_EXTENT,
19053                &fixture.skinning,
19054                |graph, targets| {
19055                    received = Some(targets);
19056                    graph
19057                        .add_render_pass("overlay-probe")
19058                        .color(
19059                            targets.display,
19060                            LoadOp::Load,
19061                            StoreOp::Store,
19062                            crcbl_hal::ClearValue::default(),
19063                        )
19064                        .depth_read(targets.depth)
19065                        .execute(|_| {});
19066                },
19067            );
19068            let received = received.expect("the overlay callback runs while the frame is built");
19069            assert_eq!(
19070                received.internal_extent, internal_extent,
19071                "the overlay receives the extent its display and depth attachments have"
19072            );
19073
19074            let compiled = graph.compile(&pool).expect("the shared attachments match");
19075            let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
19076            let overlay = labels
19077                .iter()
19078                .position(|label| *label == "overlay-probe")
19079                .expect("the callback's pass is part of the frame");
19080            let fxaa = labels
19081                .iter()
19082                .position(|label| *label == "fxaa")
19083                .expect("the requested resolve is part of the frame");
19084            let upscale = labels
19085                .iter()
19086                .position(|label| *label == "upscale")
19087                .expect("the half-scale frame reconstructs its target");
19088            assert!(
19089                overlay < fxaa && overlay < upscale,
19090                "the overlay must write display before its resolve and upscale: {labels:?}"
19091            );
19092        }
19093
19094        fixture.destroy(device);
19095        pool.destroy(device);
19096        device.destroy_image_view(imported.view);
19097        device.destroy_image(imported.image);
19098        recorder.assert_valid();
19099    }
19100
19101    /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
19102    ///
19103    /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
19104    /// halves matter: a bound under the widest frame times part of it and drops
19105    /// the rest, and a bound well over it buys query sets nothing ever writes.
19106    /// A shadowable spot per light slot fills every one of them, which is the
19107    /// most culls a frame can run and so the widest frame there is — it must land
19108    /// exactly on the constant, and the frame with no shadowed light at all must
19109    /// be short of it by exactly the culls those slots would have added.
19110    ///
19111    /// The ground grid is switched on for **both** frames, because the widest
19112    /// frame is the one that has it: it is off by default and not a
19113    /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
19114    /// debug draw layer is on for both frames for the same reason, and it needs
19115    /// a segment appended before each rather than one switch, because
19116    /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
19117    ///
19118    /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
19119    /// [`TEST_EXTENT`], with every effect forced on and the render scale off
19120    /// full.** The bloom chain's length is a function of the extent the frame is
19121    /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
19122    /// records is a *large* one, and a bound checked against a 64×48 frame would
19123    /// sit six passes above what that frame runs and this assertion would have
19124    /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
19125    /// frame buys query sets nothing writes, and only an exact comparison
19126    /// notices.
19127    ///
19128    /// **The render scale is what makes those two requirements compose.** The
19129    /// upscale is a pass only below full scale, and below full scale the chain
19130    /// runs at the *internal* extent — so a frame with both is one whose
19131    /// internal extent is the longest chain's, and whose target is larger than
19132    /// that. Halving a target of 2048×1024 is what arranges it, and the two
19133    /// assertions below check the arrangement rather than trusting it.
19134    ///
19135    /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
19136    #[test]
19137    fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
19138        /// The extent whose bloom chain is the longest [`crate::bloom`] will
19139        /// build: six halvings of 512 leave sixteen by eight, which is still at
19140        /// or above that module's floor. The widest frame is drawn at this,
19141        /// which is why it is the internal one and not the target.
19142        const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
19143        /// Half, so the frame records an upscale and draws at
19144        /// [`WIDEST_INTERNAL`].
19145        const WIDEST_SCALE: f32 = 0.5;
19146        /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
19147        const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
19148
19149        let (recorder, device, queue) = open();
19150        let device = device.as_ref();
19151        // **A scene whose probes ask to be updated**, because the widest frame
19152        // is the one with every pass in it and
19153        // the irradiance probes' two are recorded by a volume
19154        // rather than by an effect bit — the ground grid's argument exactly. A
19155        // renderer built on the demo's empty grid records neither, and the bound
19156        // would then be checked against a frame that could not reach it.
19157        let mut scene = scene::demo();
19158        scene.capacities.probes = 1;
19159        scene.probes = scene::ProbeGrid {
19160            volume: crcbl_shaders::probe::ProbeVolume {
19161                origin: [0.0; 3],
19162                inv_spacing: [1.0; 3],
19163                counts: [1, 1, 1],
19164                levels: 1,
19165                steps: crcbl_shaders::probe::ProbeSteps::default(),
19166            },
19167            probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
19168            update: ProbeUpdate::EveryFrame,
19169        };
19170        let mut renderer =
19171            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
19172                .expect("built");
19173        // A maximum-width graph must include actual instances to cull.
19174        place_cube(&mut renderer, Mat4::IDENTITY);
19175        renderer
19176            .set_ground_grid(device, Some(GridStyle::default()))
19177            .expect("the null backend builds every pipeline");
19178        // **And the occlusion cull**, whose late prepass, farthest pyramid and
19179        // three late compute passes are the ground grid's kind of pass: off
19180        // unless a caller asks, and in the widest frame when one does.
19181        renderer.set_occlusion_culling(OcclusionCulling {
19182            occlusion: true,
19183            small_feature_pixels: None,
19184        });
19185        // **A body of water**, on the ground grid's terms: content rather than
19186        // an effect bit, so the widest frame is one a caller gave water to, and
19187        // `Water::PASSES` is in the bound for it.
19188        renderer
19189            .set_water(&[crcbl_water::WaterBody {
19190                outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
19191                level: 0.0,
19192                medium: crcbl_water::Medium {
19193                    absorption: [0.4, 0.1, 0.05],
19194                    scattering: [0.01, 0.01, 0.01],
19195                },
19196            }])
19197            .expect("a square meshes");
19198        // **A field of grass**, on the water body's terms exactly: content
19199        // rather than an effect bit, so the widest frame is one a caller gave a
19200        // field to and `Grass::PASSES` is in the bound for it.
19201        renderer
19202            .set_grass(
19203                device,
19204                queue,
19205                Some(
19206                    &crate::grass::GrassField::new(
19207                        [1, 1],
19208                        4.0,
19209                        [-2.0, -2.0],
19210                        50.0,
19211                        crate::grass::Heightfield {
19212                            texels: [4, 4],
19213                            metres_per_texel: 1.0,
19214                            origin: [-2.0, -2.0],
19215                            heights: vec![0.0; 16],
19216                        },
19217                        crate::grass::CoverMap {
19218                            texels: [4, 4],
19219                            metres_per_texel: 1.0,
19220                            origin: [-2.0, -2.0],
19221                            cover: vec![[255, 0]; 16],
19222                        },
19223                        // A shell row and a mesh blade row, so the widest
19224                        // frame records every look's draw the grass pass has.
19225                        [
19226                            crate::grass::BladeLook::Shells,
19227                            crate::grass::BladeLook::Blades,
19228                        ]
19229                        .map(|look| crate::grass::BladeType {
19230                            root_color: [0.05, 0.1, 0.02],
19231                            tip_color: [0.3, 0.5, 0.1],
19232                            height: 0.3,
19233                            half_width: 0.03,
19234                            height_spread: 0.3,
19235                            width_spread: 0.2,
19236                            look,
19237                            style: crate::grass::BladeStyle::PLAIN,
19238                            shape: crate::grass::BladeShape::STRAIGHT,
19239                            clumping: crate::grass::Clumping::NONE,
19240                        })
19241                        .to_vec(),
19242                    )
19243                    .expect("a real field"),
19244                ),
19245            )
19246            .expect("the null backend uploads every map");
19247        renderer.set_render_scale(WIDEST_SCALE);
19248        assert_eq!(
19249            renderer.internal_extent(WIDEST_EXTENT),
19250            WIDEST_INTERNAL,
19251            "the scale has to take the target to the extent whose chain is the \
19252             longest one, or the bound below is checked against a frame that \
19253             could not reach it"
19254        );
19255        // **Both post effects forced on.** Neither is in the default camera
19256        // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
19257        // for one reason and the resolve out for another — and the widest frame
19258        // is the one that has every effect in it, the ground grid's argument
19259        // exactly.
19260        renderer.set_effect_request(EffectRequest {
19261            programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
19262            ..EffectRequest::default()
19263        });
19264        let imported = swapchain_image_at(device, WIDEST_EXTENT);
19265        let mut pool = crate::TransientPool::new();
19266
19267        // The debug draw layer on for both frames below, because it is a pass
19268        // the bound counts and no effect bit switches on — the ground grid's
19269        // argument again. A segment before each, since `begin_frame` clears the
19270        // buffer: the layer is immediate mode.
19271        let switch = debug_draw_switch();
19272        switch.set(true);
19273        // And the occlusion pair's second blur, for exactly that reason: it is a
19274        // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
19275        // frame at the shipping count comes one short of the bound and this test
19276        // would be asserting the bound against a frame that could not reach it.
19277        let blurs = ssao_blur_switch();
19278        blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
19279        // And the comparison seam, which is the occlusion chain's other
19280        // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
19281        // same reason the blur count is: the bound counts a frame that compares,
19282        // so a frame that does not could never reach it.
19283        let split = ssao_split_switch();
19284        split.set(0.5);
19285        renderer
19286            .debug_draw()
19287            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
19288        let bare =
19289            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
19290        assert_eq!(
19291            crate::bloom::mips_for(WIDEST_INTERNAL),
19292            crate::bloom::MAX_MIPS,
19293            "the widest frame has to be one whose chain is the longest one there \
19294             is, or the bound below is checked against a frame that could not \
19295             reach it"
19296        );
19297        assert!(
19298            bare < ForwardRenderer::MAX_PASSES as usize,
19299            "a frame with no shadowed light runs {bare} passes, which is already the \
19300             bound of {} — then the bound does not cover the slots this scene left free",
19301            ForwardRenderer::MAX_PASSES
19302        );
19303
19304        // One spot per slot, spaced so no two of them share an influence — the
19305        // list has to fill every slot or the bound below is checked against a
19306        // frame that could not reach it.
19307        #[expect(
19308            clippy::cast_precision_loss,
19309            reason = "a handful of slots, and the value is only a position"
19310        )]
19311        let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
19312            .map(|slot| shadowable_spot(1.0 + slot as f32))
19313            .collect();
19314        renderer.set_lights(&spots);
19315        renderer
19316            .debug_draw()
19317            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
19318        let widest =
19319            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
19320        assert_eq!(
19321            renderer.shadow_lights.slots().iter().flatten().count(),
19322            shadow::LIGHT_SLOTS,
19323            "the spots must actually hold every slot, or this is the bare frame again \
19324             under another name"
19325        );
19326        assert_eq!(
19327            widest,
19328            ForwardRenderer::MAX_PASSES as usize,
19329            "the widest frame is what the bound is for"
19330        );
19331        assert_eq!(
19332            widest - bare,
19333            DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
19334            "a filled slot costs a cull's passes and nothing else"
19335        );
19336
19337        renderer.destroy(device);
19338        pool.destroy(device);
19339        device.destroy_image_view(imported.view);
19340        device.destroy_image(imported.image);
19341        recorder.assert_valid();
19342    }
19343
19344    /// **A toggle reaches the recorded frame, and takes exactly its own passes
19345    /// with it.**
19346    ///
19347    /// The observable is the compiled pass list, because the thing that could
19348    /// otherwise be true is that the switch is stored and read by nothing: a
19349    /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
19350    /// draws a frame that looks right, reports the right effect set, and has not
19351    /// switched anything off.
19352    ///
19353    /// So each arm compares the whole list rather than its length. Two passes
19354    /// fewer is satisfied by removing the wrong two, and it is satisfied by a
19355    /// frame that lost its tonemap.
19356    ///
19357    /// The shadow arm is the one that cannot be written by name — a cascade's
19358    /// cull passes are labelled exactly as the camera's are — so it is written as
19359    /// its two halves instead: the count moves by a cull's worth per cascade and
19360    /// per filled light slot, and everything from the `shadow` pass onwards is
19361    /// unchanged. The `shadow` pass itself **stays**, because it is what writes
19362    /// the clear that reads as "fully lit".
19363    #[test]
19364    fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
19365        let _blurs = ssao_blur_switch();
19366        let (recorder, device, queue) = open();
19367        let device = device.as_ref();
19368        let mut renderer =
19369            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19370        place_cube(&mut renderer, Mat4::IDENTITY);
19371        // One shadowed light beside the cascades, so the shadow arm below covers
19372        // a light slot's cull as well as a cascade's.
19373        renderer.set_lights(&[shadowable_spot(-1.0)]);
19374        let imported = swapchain_image(device);
19375        let mut pool = crate::TransientPool::new();
19376
19377        // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
19378        // [`frame_switching_off`]'s terms exactly: the default camera stack
19379        // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
19380        // control built on the default alone would have nothing for their arms
19381        // to remove. `force` clears the other side, so an arm whose `off` is one
19382        // of them still resolves to off.
19383        //
19384        // [`frame_switching_off`]: fn@frame_switching_off
19385        let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
19386            renderer.set_effect_request(EffectRequest {
19387                programmatic: EffectOverride::none()
19388                    .force(OUTSIDE_THE_DEFAULT, Some(true))
19389                    .force(off, Some(false)),
19390                ..EffectRequest::default()
19391            });
19392            passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
19393        };
19394
19395        let all_on = without(&mut renderer, RenderEffects::empty());
19396        assert_eq!(
19397            renderer.effects(),
19398            RenderEffects::all(),
19399            "the control frame has to be the every-effect one"
19400        );
19401        assert_eq!(
19402            renderer.shadow_lights.slots().iter().flatten().count(),
19403            1,
19404            "the spot must actually hold a slot, or the shadow arm below is only about cascades"
19405        );
19406
19407        // **None of the three leaves anything behind it**, and for the same
19408        // reason: nothing reads what it would have written. The occlusion pair's
19409        // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
19410        // its `Load` into it — and the reflection pair's and the chain's readers
19411        // both tonemap whatever image they would have read anyway.
19412        //
19413        // The chain's labels are written out rather than built from
19414        // `crate::bloom`'s arithmetic, because a table generated from the code
19415        // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
19416        // downsamples, the one upsample between them, and the composite — and if
19417        // that extent moves this is the assertion that says so.
19418        for (off, gone) in [
19419            (
19420                RenderEffects::AMBIENT_OCCLUSION,
19421                ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
19422            ),
19423            (
19424                RenderEffects::CONTACT_SHADOWS,
19425                // One pass and no blur — `crate::contact_shadows`'s header says
19426                // why the occlusion pair's second pass has no counterpart here.
19427                ["contact-shadows"].as_slice(),
19428            ),
19429            (
19430                RenderEffects::REFLECTIONS,
19431                // **The pyramid goes with the march**, which is the whole of
19432                // what makes it an optimisation rather than a resource: it is
19433                // recorded on the frames that reflect and on no others. Two
19434                // levels at `TEST_EXTENT`, written out on the chain's terms
19435                // above.
19436                ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
19437            ),
19438            (
19439                RenderEffects::BLOOM,
19440                [
19441                    "bloom-down-1",
19442                    "bloom-down-2",
19443                    "bloom-up-1",
19444                    "bloom-composite",
19445                ]
19446                .as_slice(),
19447            ),
19448            (
19449                RenderEffects::AUTO_EXPOSURE,
19450                // All three go together and the tonemap stays: the pass reads
19451                // the measurement only when the block says to, and the block
19452                // says so on exactly the frames these three ran on.
19453                ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
19454            ),
19455        ] {
19456            let labels = without(&mut renderer, off);
19457            assert_eq!(
19458                renderer.effects(),
19459                RenderEffects::all().difference(off),
19460                "{off:?}: the frame must have resolved to the set the request asked for"
19461            );
19462            // **The control frame has to contain what this arm removes**, and
19463            // that is not a restatement of the comparison below: the comparison
19464            // builds `expected` by filtering `gone` out of `all_on`, so an arm
19465            // naming a pass the control never recorded filters nothing, matches,
19466            // and passes whether the effect draws anything or not. Removing the
19467            // resolve pass entirely left this loop green until this assertion
19468            // existed.
19469            for label in gone {
19470                assert!(
19471                    all_on.iter().any(|recorded| recorded == label),
19472                    "{off:?}: the every-effect frame does not record `{label}`, so removing it \
19473                     below proves nothing: {all_on:#?}"
19474                );
19475            }
19476            let expected: Vec<String> = all_on
19477                .iter()
19478                .filter(|label| !gone.contains(&label.as_str()))
19479                .cloned()
19480                .collect();
19481            assert_eq!(
19482                labels, expected,
19483                "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
19484                 every other pass"
19485            );
19486        }
19487
19488        // **The two antialiasing tiers share one resolve slot**, so neither is
19489        // a plain removal and neither belongs in the loop above: switching
19490        // CMAA2 off while FXAA stays on swaps three passes for one rather than
19491        // losing three, and the loop's "gain nothing in their place" comparison
19492        // is exactly what that violates. Three frames say it instead.
19493        let both = all_on.clone();
19494        let cheap = without(&mut renderer, RenderEffects::CMAA2);
19495        let neither = without(
19496            &mut renderer,
19497            RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
19498        );
19499        const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
19500        let resolve_of = |labels: &[String]| -> Vec<String> {
19501            labels
19502                .iter()
19503                .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
19504                .cloned()
19505                .collect()
19506        };
19507        let without_resolve = |labels: &[String]| -> Vec<String> {
19508            labels
19509                .iter()
19510                .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
19511                .cloned()
19512                .collect()
19513        };
19514        assert_eq!(
19515            resolve_of(&both),
19516            CMAA2_PASSES.map(str::to_string).to_vec(),
19517            "with both bits set the higher tier takes the slot and the cheap one \
19518             records nothing"
19519        );
19520        assert_eq!(
19521            resolve_of(&cheap),
19522            vec!["fxaa".to_string()],
19523            "with only the cheap bit set the slot is FXAA's"
19524        );
19525        assert!(
19526            resolve_of(&neither).is_empty(),
19527            "with neither bit set the frame has no resolve at all: {neither:#?}"
19528        );
19529        // And nothing else moved: the tiers swap in one slot rather than
19530        // rebuilding the frame around themselves.
19531        assert_eq!(without_resolve(&both), without_resolve(&cheap));
19532        assert_eq!(without_resolve(&both), without_resolve(&neither));
19533        // The slot is where the ordering argument puts it — directly after the
19534        // last pass that writes the display image, which at this extent is the
19535        // tonemap.
19536        for labels in [&both, &cheap] {
19537            let at = labels
19538                .iter()
19539                .position(|label| label == "tonemap")
19540                .expect("a frame has to reach the swapchain");
19541            assert_eq!(
19542                &labels[at + 1..=at + resolve_of(labels).len()],
19543                resolve_of(labels).as_slice(),
19544                "the resolve must follow the tonemap: {labels:#?}"
19545            );
19546        }
19547
19548        let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
19549        assert_eq!(
19550            renderer.effects(),
19551            RenderEffects::all().difference(RenderEffects::SHADOWS),
19552        );
19553        assert_eq!(
19554            all_on.len() - no_shadows.len(),
19555            DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
19556            "shadows off must drop a cull's passes per cascade and per filled slot"
19557        );
19558        let from_the_atlas = |labels: &[String]| {
19559            let at = labels
19560                .iter()
19561                .position(|label| label == "shadow")
19562                .expect("the atlas pass is recorded whether or not anything draws into it");
19563            labels[at..].to_vec()
19564        };
19565        assert_eq!(
19566            from_the_atlas(&no_shadows),
19567            from_the_atlas(&all_on),
19568            "only the culls go: the atlas pass and everything after it are unchanged"
19569        );
19570
19571        renderer.destroy(device);
19572        pool.destroy(device);
19573        device.destroy_image_view(imported.view);
19574        device.destroy_image(imported.image);
19575        recorder.assert_valid();
19576    }
19577
19578    /// **The contact march is a pass a frame records only when it was asked
19579    /// for, and the mask it writes is what the forward pass then reads.**
19580    ///
19581    /// Two observables, because either alone is satisfied by a mistake the other
19582    /// one catches:
19583    ///
19584    /// * **The compiled pass list.** `contact-shadows` appears between the
19585    ///   prepass whose depth it marches and the forward pass that binds it, and
19586    ///   appears at all only on the frame that asked. The toggle test above
19587    ///   already says a frame loses this pass and nothing else; what is added
19588    ///   here is *where* it sits, which is the half a set comparison cannot see
19589    ///   — a march recorded after the pass that reads it compiles and draws a
19590    ///   mask nothing ever looks at.
19591    /// * **The forward pass's own barriers.** On the frame that marched, one
19592    ///   more image is transitioned into [`ResourceState::ShaderRead`] before
19593    ///   the forward pass opens than on the frame that did not — which is the
19594    ///   mask leaving the colour attachment it was written as. That is what says
19595    ///   the pass's output reaches the shading, rather than being written into a
19596    ///   transient and dropped while the shader goes on reading the 1×1
19597    ///   placeholder. The placeholder is imported in `ShaderRead` already and
19598    ///   needs no transition, so it contributes nothing to this count and the
19599    ///   difference is exactly the mask.
19600    ///
19601    /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
19602    /// while its re-bless is pending — see that constant — so the `on` frame has
19603    /// to force it and the `off` frame is what a view saying nothing draws.
19604    #[test]
19605    fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
19606        let (recorder, device, queue) = open();
19607        let device = device.as_ref();
19608        let mut renderer =
19609            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19610        let imported = swapchain_image(device);
19611        let mut pool = crate::TransientPool::new();
19612
19613        let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
19614            renderer.set_effect_request(EffectRequest {
19615                programmatic: EffectOverride::none()
19616                    .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
19617                ..EffectRequest::default()
19618            });
19619            renderer
19620                .begin_frame(
19621                    device,
19622                    &Camera::default(),
19623                    &DirectionalLight::default(),
19624                    TEST_EXTENT,
19625                )
19626                .expect("write");
19627            let mut graph = crate::RenderGraph::new(queue);
19628            let target = graph.import_image("target", imported);
19629            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19630            let compiled = graph.compile(&pool).expect("a legal frame");
19631            let labels: Vec<String> = compiled
19632                .passes()
19633                .iter()
19634                .map(|pass| pass.label().to_string())
19635                .collect();
19636            let readable = compiled
19637                .passes()
19638                .iter()
19639                .find(|pass| pass.label() == "forward")
19640                .expect("every frame draws its geometry")
19641                .barriers()
19642                .images
19643                .iter()
19644                .filter(|barrier| barrier.to == ResourceState::ShaderRead)
19645                .count();
19646            (labels, readable)
19647        };
19648
19649        let (marched, marched_reads) = frame(&mut renderer, true);
19650        assert!(
19651            renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19652            "the forced frame has to have resolved with the bit set"
19653        );
19654        let (bare, bare_reads) = frame(&mut renderer, false);
19655        assert!(
19656            !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19657            "and the control frame without it"
19658        );
19659
19660        assert!(
19661            !bare.iter().any(|label| label == "contact-shadows"),
19662            "a frame that did not ask must record no march at all: {bare:#?}"
19663        );
19664        let at = |labels: &[String], wanted: &str| {
19665            labels
19666                .iter()
19667                .position(|label| label == wanted)
19668                .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19669        };
19670        let march = at(&marched, "contact-shadows");
19671        assert!(
19672            march > at(&marched, "depth-prepass"),
19673            "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19674        );
19675        assert!(
19676            march < at(&marched, "forward"),
19677            "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19678        );
19679
19680        assert_eq!(
19681            marched_reads,
19682            bare_reads + 1,
19683            "the forward pass has to take one more image into `ShaderRead` on the frame that \
19684             marched — the mask. Equal counts mean the pass wrote a transient the shading \
19685             never reads."
19686        );
19687
19688        renderer.destroy(device);
19689        pool.destroy(device);
19690        device.destroy_image_view(imported.view);
19691        device.destroy_image(imported.image);
19692        recorder.assert_valid();
19693    }
19694
19695    /// **The ground grid is off until a caller asks, and then it is the last
19696    /// pass of the frame — after the tonemap.**
19697    ///
19698    /// Three claims and each is a separate way to get this wrong. Off by default
19699    /// is what keeps every sample and every golden image where they were. *After
19700    /// the tonemap* is the placement decision: added a line earlier it would
19701    /// draw into the HDR scene colour and be tonemapped like geometry, which
19702    /// compiles, draws a grid, and gives it a colour that moves with the
19703    /// exposure. And switching it off again has to remove the pass, not merely
19704    /// stop reporting it.
19705    ///
19706    /// The whole list is compared rather than its length, for the reason the
19707    /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19708    /// one.
19709    #[test]
19710    fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19711        let _blurs = ssao_blur_switch();
19712        let (recorder, device, queue) = open();
19713        let device = device.as_ref();
19714        let mut renderer =
19715            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19716        let imported = swapchain_image(device);
19717        let mut pool = crate::TransientPool::new();
19718
19719        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19720        assert!(
19721            renderer.ground_grid().is_none(),
19722            "a renderer nobody asked has no grid"
19723        );
19724        assert!(
19725            !off.contains(&"grid".to_string()),
19726            "the grid must not be in a frame nobody asked for it in: {off:#?}"
19727        );
19728
19729        renderer
19730            .set_ground_grid(device, Some(GridStyle::default()))
19731            .expect("the null backend builds every pipeline");
19732        assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19733        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19734
19735        let mut expected = off.clone();
19736        // The statistics copy is added after every render pass and stays last —
19737        // see `add_passes`. So the grid goes in front of it, which is directly
19738        // after the tonemap.
19739        let tonemap = expected
19740            .iter()
19741            .position(|label| label == "tonemap")
19742            .expect("a frame has to reach the swapchain");
19743        expected.insert(tonemap + 1, "grid".to_string());
19744        assert_eq!(
19745            on, expected,
19746            "the grid must be the one pass gained, and it must sit after the tonemap"
19747        );
19748
19749        renderer
19750            .set_ground_grid(device, None)
19751            .expect("switching off builds nothing");
19752        assert!(renderer.ground_grid().is_none());
19753        assert_eq!(
19754            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19755            off,
19756            "switching the grid off has to remove its pass, not just stop reporting it"
19757        );
19758
19759        renderer.destroy(device);
19760        pool.destroy(device);
19761        device.destroy_image_view(imported.view);
19762        device.destroy_image(imported.image);
19763        recorder.assert_valid();
19764    }
19765
19766    /// **A second occlusion blur is a pass the frame records, an image it takes
19767    /// out of the pool, and a triangle its counter reports** — or it is a switch
19768    /// that does nothing.
19769    ///
19770    /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19771    /// by driving the pipelines itself, so nothing there would notice that a
19772    /// real frame never records it. The three things below are what a frame has
19773    /// to do differently, and each of them fails silently on its own: a missing
19774    /// pass draws a slightly rougher picture, a missing image is a bind of the
19775    /// wrong one, and a counter short by one is a number nobody reads until it
19776    /// is quoted.
19777    ///
19778    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19779    /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19780    /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19781    /// whichever blur ran into it.
19782    ///
19783    /// **The one thing about that chain no other check can see.** The pass list
19784    /// is identical either way, the graph accepts a written-and-never-read
19785    /// transient without complaint, and every golden is at one blur where the
19786    /// two blur answers coincide — so a frame bound to the wrong image draws
19787    /// something nobody would question, which is exactly what the function's
19788    /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19789    /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19790    /// suites and lantern's golden all stayed green.
19791    ///
19792    /// **Since the halving it is a second silent failure and a louder one.**
19793    /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19794    /// returned working id is not merely a rougher channel — it is an image a
19795    /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19796    /// which its clamp turns into occlusion smeared over the top-left quarter of
19797    /// the frame rather than into an error.
19798    #[test]
19799    fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19800        let (_recorder, device, queue) = open();
19801        let device = device.as_ref();
19802        let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19803        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19804
19805        let one = {
19806            let mut graph = crate::RenderGraph::new(queue);
19807            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19808            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19809            let blurred =
19810                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19811            let upsampled = graph.create_image(
19812                "ssao-upsampled",
19813                crate::targets::ambient_occlusion(TEST_EXTENT),
19814            );
19815            let got = ssao.add_passes(
19816                &mut graph,
19817                0,
19818                TEST_EXTENT,
19819                depth,
19820                crate::ssao::OcclusionImages {
19821                    raw,
19822                    blurred,
19823                    again: None,
19824                    upsampled,
19825                },
19826            );
19827            (got == upsampled, got == blurred || got == raw)
19828        };
19829        assert!(one.0, "one blur finishes in the reconstruction's image");
19830        assert!(
19831            !one.1,
19832            "and never in one of the half-extent images the chain worked in"
19833        );
19834
19835        let two = {
19836            let mut graph = crate::RenderGraph::new(queue);
19837            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19838            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19839            let blurred =
19840                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19841            let again = graph.create_image(
19842                "ssao-blurred-2",
19843                crate::targets::ambient_occlusion(gathered),
19844            );
19845            let upsampled = graph.create_image(
19846                "ssao-upsampled",
19847                crate::targets::ambient_occlusion(TEST_EXTENT),
19848            );
19849            let got = ssao.add_passes(
19850                &mut graph,
19851                0,
19852                TEST_EXTENT,
19853                depth,
19854                crate::ssao::OcclusionImages {
19855                    raw,
19856                    blurred,
19857                    again: Some(again),
19858                    upsampled,
19859                },
19860            );
19861            (got == upsampled, got == again || got == blurred)
19862        };
19863        assert!(
19864            two.0,
19865            "two blurs finish in the reconstruction's image as well, which is the id the forward \
19866             pass binds"
19867        );
19868        assert!(
19869            !two.1,
19870            "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19871             would question"
19872        );
19873    }
19874
19875    /// **The gather runs at half the frame and the reconstruction runs at all
19876    /// of it** — or the halving is a description nobody rendered into.
19877    ///
19878    /// The pass list cannot see this: three passes with the right labels in the
19879    /// right order is exactly what a chain that halved nothing would record. The
19880    /// **render area** is where the halving is observable, and the graph derives
19881    /// it from each pass's colour attachment — so this is the check that the
19882    /// transients [`ForwardRenderer::add_passes`] created are the ones
19883    /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19884    /// the frame-sized one.
19885    ///
19886    /// Neither mistake is an error anywhere else. Working images at the frame's
19887    /// extent are four times the march and a reconstruction reading the corner
19888    /// of its input; a frame-sized image handed to the march and a half-sized
19889    /// one to the forward pass is occlusion smeared over a quarter of the
19890    /// picture by `mesh.slang`'s clamp. Both are pictures.
19891    ///
19892    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19893    /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19894    /// occlusion chain's passes up by name, and a second blur arriving from
19895    /// another thread's switch is a pass this frame did not ask for.
19896    #[test]
19897    fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19898        let _switch = ssao_blur_switch();
19899
19900        let (recorder, device, queue) = open();
19901        let device = device.as_ref();
19902        let mut renderer =
19903            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19904        let imported = swapchain_image(device);
19905        let mut pool = crate::TransientPool::new();
19906        renderer
19907            .begin_frame(
19908                device,
19909                &Camera::default(),
19910                &DirectionalLight::default(),
19911                TEST_EXTENT,
19912            )
19913            .expect("write");
19914        let mut graph = crate::RenderGraph::new(queue);
19915        let target = graph.import_image("target", imported);
19916        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19917        let compiled = graph.compile(&pool).expect("a legal frame");
19918        let area_of = |label: &str| {
19919            let pass = compiled
19920                .passes()
19921                .iter()
19922                .find(|pass| pass.label() == label)
19923                .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19924            let area = pass.render_area();
19925            (area.width, area.height)
19926        };
19927
19928        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19929        assert_ne!(
19930            gathered, TEST_EXTENT,
19931            "the fixture extent has to halve to something else, or every assertion below holds \
19932             of a chain that halved nothing"
19933        );
19934        assert_eq!(
19935            area_of("ssao"),
19936            gathered,
19937            "the march has to run over the gather extent"
19938        );
19939        assert_eq!(
19940            area_of("ssao-blur"),
19941            gathered,
19942            "and so does the blur over what the march wrote"
19943        );
19944        assert_eq!(
19945            area_of("ssao-upsample"),
19946            TEST_EXTENT,
19947            "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19948             runs at the frame's own extent"
19949        );
19950
19951        drop(compiled);
19952        renderer.destroy(device);
19953        pool.destroy(device);
19954        device.destroy_image_view(imported.view);
19955        device.destroy_image(imported.image);
19956        recorder.assert_valid();
19957    }
19958
19959    /// [`ssr_resolution_switch`]'s lock.
19960    static SSR_RESOLUTION_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
19961
19962    /// Takes `r_ssr_resolution` for this thread and puts full resolution back
19963    /// when the guard drops, on [`ssao_blur_switch`]'s terms.
19964    fn ssr_resolution_switch() -> std::sync::MutexGuard<'static, ()> {
19965        SSR_RESOLUTION_SWITCH
19966            .lock()
19967            .unwrap_or_else(std::sync::PoisonError::into_inner)
19968    }
19969
19970    /// **The reflection march runs at its share of the frame and the composite
19971    /// at all of it**, at every share a quality tier writes.
19972    ///
19973    /// On the occlusion chain's terms just above: the pass list is the same at
19974    /// every share, so the **render area** is where the scale is observable. A
19975    /// march image left at the frame's extent would be a march that saved
19976    /// nothing, and a composite at the march's extent would tonemap a truncated
19977    /// frame.
19978    #[test]
19979    fn the_reflection_march_runs_at_its_share_and_composites_at_the_frame() {
19980        let _switch = ssr_resolution_switch();
19981
19982        let (recorder, device, queue) = open();
19983        let device = device.as_ref();
19984        let mut renderer =
19985            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19986        let imported = swapchain_image(device);
19987        let mut pool = crate::TransientPool::new();
19988        for share in [1.0, 0.75, 0.5, 0.25] {
19989            crate::ssr::r_ssr_resolution
19990                .set(&crcbl_console::Value::Float(share))
19991                .expect("every tier's share is in the variable's range");
19992            renderer
19993                .begin_frame(
19994                    device,
19995                    &Camera::default(),
19996                    &DirectionalLight::default(),
19997                    TEST_EXTENT,
19998                )
19999                .expect("write");
20000            let mut graph = crate::RenderGraph::new(queue);
20001            let target = graph.import_image("target", imported);
20002            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
20003            let compiled = graph.compile(&pool).expect("a legal frame");
20004            let area_of = |label: &str| {
20005                let pass = compiled
20006                    .passes()
20007                    .iter()
20008                    .find(|pass| pass.label() == label)
20009                    .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
20010                let area = pass.render_area();
20011                (area.width, area.height)
20012            };
20013            let marched = crate::ssr::march_extent(TEST_EXTENT, share);
20014            assert_eq!(
20015                area_of("ssr"),
20016                marched,
20017                "at {share} the march has to run over its own share of the frame"
20018            );
20019            assert_eq!(
20020                area_of("ssr-blur"),
20021                TEST_EXTENT,
20022                "at {share} the composite replaces the scene colour, so it runs at the frame's \
20023                 own extent"
20024            );
20025            drop(compiled);
20026        }
20027        crate::ssr::r_ssr_resolution
20028            .set(&crcbl_console::Value::Float(1.0))
20029            .expect("full resolution is in range");
20030
20031        renderer.destroy(device);
20032        pool.destroy(device);
20033        device.destroy_image_view(imported.view);
20034        device.destroy_image(imported.image);
20035        recorder.assert_valid();
20036    }
20037
20038    /// **The comparison seam records a second march, scissored to the columns
20039    /// the first one was kept off.**
20040    ///
20041    /// `crate::split`'s geometry, read off the encoder rather than off the code
20042    /// that drove it: two passes, and two `SetScissor` rectangles that tile the
20043    /// gather extent between them.
20044    ///
20045    /// **What this cannot see is which block each march bound.** The reference
20046    /// backend records a bind group as a handle and a layout, not as the
20047    /// resources behind it, so pointing both marches at one buffer leaves this
20048    /// test green — measured, by doing exactly that. The group inequality below
20049    /// is kept because it is free and would catch the two marches sharing a
20050    /// cache, which is a different fault; what covers the blocks is
20051    /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
20052    /// is not covered at all is the wiring between them. `docs/backlog.md`
20053    /// carries that gap.
20054    ///
20055    /// **The control is the same frame without a seam**, and it is what makes
20056    /// the assertions mean anything: a chain that scissored unconditionally
20057    /// would satisfy every claim below and change every golden in the workspace,
20058    /// so the frame nobody asked to compare has to record one march and set no
20059    /// rectangle at all.
20060    ///
20061    /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
20062    /// is process-wide state and a frame that picked one up from another
20063    /// thread's test is a frame with a pass this one did not ask for.
20064    #[test]
20065    fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
20066        use crcbl_hal::null::Command;
20067
20068        let _blurs = ssao_blur_switch();
20069        let split = ssao_split_switch();
20070        // Third, after the two above: the only other test that takes this one
20071        // takes it alone, so this is the whole order and there is no cycle in
20072        // it. Moved below, because two blocks holding the same scalars are
20073        // equal whatever the seam did.
20074        let slices = ssao_slice_switch();
20075        // The count the seam's far side reads, and one that is not it. Read off
20076        // the variable rather than written down: which end of the range ships
20077        // has changed once already, and a test naming the wrong end would be
20078        // comparing the shipped configuration against itself.
20079        let ships = match crate::ssao::r_ssao_slices.default() {
20080            crcbl_console::Value::Int(count) => *count,
20081            other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
20082        };
20083        let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
20084            i64::from(ssao::SLICE_COUNT_DEFAULT)
20085        } else {
20086            i64::from(ssao::SLICE_COUNT_MAX)
20087        };
20088        assert_ne!(
20089            ships, moved,
20090            "the two slice counts this compares are one count, so the blocks below would differ \
20091             by nothing whatever the seam did"
20092        );
20093        slices.set(ships);
20094
20095        let gathered = crate::ssao::half_extent(TEST_EXTENT);
20096        // One entry per march the frame recorded: the last rectangle that pass
20097        // left the scissor at, and the group it bound.
20098        //
20099        // **The last and not the only one.** The graph opens every pass with a
20100        // scissor over the whole render area, so a march that sets none of its
20101        // own still records one — which is why "did it scissor at all" is not
20102        // the question and "what did it end up cropped to" is.
20103        let marches = |recorder: &Recorder, from: usize| {
20104            let mut inside = false;
20105            let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
20106            let mut rect = None;
20107            let mut group = None;
20108            for command in &recorder.commands()[from..] {
20109                if let Some((_, label)) = command.opens_pass() {
20110                    inside = matches!(label, Some("ssao" | "ssao-shipped"));
20111                    (rect, group) = (None, None);
20112                    continue;
20113                }
20114                if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
20115                    if let (true, Some(rect), Some(group)) = (inside, rect, group) {
20116                        found.push((rect, group));
20117                    }
20118                    inside = false;
20119                    continue;
20120                }
20121                if !inside {
20122                    continue;
20123                }
20124                match command {
20125                    Command::SetScissor(at) => rect = Some(*at),
20126                    Command::BindGroup { group: bound, .. } => group = Some(*bound),
20127                    _ => {}
20128                }
20129            }
20130            found
20131        };
20132
20133        let (recorder, device, queue) = open();
20134        let device = device.as_ref();
20135        let mut renderer =
20136            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20137
20138        split.set(0.0);
20139        let alone = frame_seen_from(
20140            device,
20141            &mut renderer,
20142            queue,
20143            &Camera::default(),
20144            &DirectionalLight::default(),
20145        );
20146        let plain = marches(&recorder, 0);
20147        let after = recorder.commands().len();
20148        let (console, shipped) = renderer
20149            .primary
20150            .ssao
20151            .as_ref()
20152            .expect("the default stack builds the occlusion pair")
20153            .blocks(renderer.frame);
20154        let (uncompared_console, uncompared_shipped) = (
20155            recorder.buffer_bytes(console).expect("the console's block"),
20156            recorder.buffer_bytes(shipped).expect("the seam's block"),
20157        );
20158        alone.release(device);
20159
20160        split.set(0.5);
20161        slices.set(moved);
20162        let frame = frame_seen_from(
20163            device,
20164            &mut renderer,
20165            queue,
20166            &Camera::default(),
20167            &DirectionalLight::default(),
20168        );
20169        let compared = marches(&recorder, after);
20170        let (console, shipped) = renderer
20171            .primary
20172            .ssao
20173            .as_ref()
20174            .expect("the default stack builds the occlusion pair")
20175            .blocks(renderer.frame);
20176        let (compared_console, compared_shipped) = (
20177            recorder.buffer_bytes(console).expect("the console's block"),
20178            recorder.buffer_bytes(shipped).expect("the seam's block"),
20179        );
20180        frame.finish(device, renderer);
20181
20182        assert_eq!(
20183            plain.len(),
20184            1,
20185            "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
20186            plain.len()
20187        );
20188        assert_eq!(
20189            (
20190                plain[0].0.x,
20191                plain[0].0.y,
20192                plain[0].0.width,
20193                plain[0].0.height
20194            ),
20195            (0, 0, gathered.0, gathered.1),
20196            "a frame comparing nothing left its march cropped to something other than the whole \
20197             gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
20198             and every golden in this workspace was blessed on a frame that does not"
20199        );
20200
20201        assert_eq!(
20202            compared.len(),
20203            2,
20204            "a frame comparing two configurations recorded {} march(es)",
20205            compared.len()
20206        );
20207        let (left, right) = (compared[0].0, compared[1].0);
20208        assert_eq!(
20209            (left.x, left.y, right.y),
20210            (0, 0, 0),
20211            "both halves start at the top and the left one at the edge"
20212        );
20213        assert_eq!(
20214            i64::from(right.x),
20215            i64::from(left.width),
20216            "the second march starts where the first one ended, or a column is drawn twice"
20217        );
20218        assert_eq!(
20219            (left.width + right.width, left.height, right.height),
20220            (gathered.0, gathered.1, gathered.1),
20221            "the two rectangles have to cover the gather extent {gathered:?} exactly"
20222        );
20223        assert!(
20224            left.width < gathered.0 && right.width < gathered.0,
20225            "one half covers the whole extent, so the other draws over it and the seam is a \
20226             rectangle that crops nothing"
20227        );
20228        assert_ne!(
20229            compared[0].1, compared[1].1,
20230            "the two marches bound one group, so they cannot be reading two blocks"
20231        );
20232
20233        // How far the reference backend can follow the far side. It will say
20234        // what bytes a buffer holds and it will not say which buffer a group
20235        // names, so the two together are "there are two blocks, and they differ
20236        // by the knob that was moved" — not "the right march read the right
20237        // one". Pointing both marches at one buffer still passes; see this
20238        // module's entry in `docs/backlog.md`.
20239        assert_eq!(
20240            uncompared_console, uncompared_shipped,
20241            "the console sat at its defaults and the two blocks still differ, so the seam's far \
20242             side is not this frame with the shipped scalars — it is another frame"
20243        );
20244        assert_ne!(
20245            compared_console, compared_shipped,
20246            "one slice count was moved off the shipped one and both blocks still hold the same \
20247             bytes, so a comparison shows the same picture twice"
20248        );
20249
20250        recorder.assert_valid();
20251    }
20252
20253    /// Every gather pipeline the frame bound, in the order the marches ran.
20254    ///
20255    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
20256    /// `marches` closure asking the other question of the same stream: that one
20257    /// reads the scissor and the group, and this one reads the pipeline. Only
20258    /// the `ssao` and `ssao-shipped` passes are looked at, because every other
20259    /// pass in the chain binds a pipeline too and a filter over the whole stream
20260    /// would be counting blurs.
20261    ///
20262    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
20263    fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
20264        use crcbl_hal::null::Command;
20265
20266        let mut inside = false;
20267        let mut found = Vec::new();
20268        for command in &recorder.commands()[from..] {
20269            if let Some((_, label)) = command.opens_pass() {
20270                inside = matches!(label, Some("ssao" | "ssao-shipped"));
20271                continue;
20272            }
20273            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
20274                inside = false;
20275                continue;
20276            }
20277            if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
20278                found.push(*pipeline);
20279            }
20280        }
20281        found
20282    }
20283
20284    /// **`r_ssao_technique` decides which shader the gather runs**, read off the
20285    /// pipeline the `ssao` pass bound.
20286    ///
20287    /// The observable `docs/backlog.md` says the uniform block cannot have. The
20288    /// reference backend records a bind group as a handle and a layout rather
20289    /// than as the resources behind it, so nothing can ask which *block* a march
20290    /// read — but a pipeline is recorded as itself, so which *technique* a march
20291    /// ran is a question this backend answers. `Ssao::gathers` is what names the
20292    /// two, so this is an equality against the pipeline built from each shader
20293    /// rather than an inequality that any two handles would satisfy.
20294    ///
20295    /// **The default arm is the load-bearing half.** A selector that read the
20296    /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
20297    /// change the frame when the console moved; what would go with it is every
20298    /// golden in this workspace, which is blessed on the technique that ships.
20299    ///
20300    /// Holds [`ssao_blur_switch`] for its own reason and
20301    /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
20302    /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
20303    #[test]
20304    fn the_occlusion_technique_picks_the_gathers_pipeline() {
20305        let _blurs = ssao_blur_switch();
20306        let _seam = ssao_split_switch();
20307        let technique = ssao_technique_switch();
20308        // The name to move to, taken out of the variable's own set — see
20309        // `other_technique_name`.
20310        let other = other_technique_name();
20311
20312        let (recorder, device, queue) = open();
20313        let device = device.as_ref();
20314        let mut renderer =
20315            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20316        let (ships, cheap) = renderer
20317            .primary
20318            .ssao
20319            .as_ref()
20320            .expect("the default stack builds the occlusion pair")
20321            .gathers();
20322        assert_ne!(
20323            ships, cheap,
20324            "the renderer built one gather pipeline for both techniques, so nothing below can \
20325             tell them apart"
20326        );
20327
20328        let shipped = frame_seen_from(
20329            device,
20330            &mut renderer,
20331            queue,
20332            &Camera::default(),
20333            &DirectionalLight::default(),
20334        );
20335        let by_default = gathers_bound(&recorder, 0);
20336        let after = recorder.commands().len();
20337        shipped.release(device);
20338
20339        technique.set(other);
20340        let moved_frame = frame_seen_from(
20341            device,
20342            &mut renderer,
20343            queue,
20344            &Camera::default(),
20345            &DirectionalLight::default(),
20346        );
20347        let moved = gathers_bound(&recorder, after);
20348        moved_frame.finish(device, renderer);
20349
20350        assert_eq!(
20351            by_default,
20352            vec![ships],
20353            "a frame nobody has touched the console on gathered through something other than \
20354             `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
20355        );
20356        assert_eq!(
20357            moved,
20358            vec![cheap],
20359            "`r_ssao_technique {other}` left the frame gathering through the pipeline \
20360             it gathered through before, so the selector reaches nothing"
20361        );
20362        recorder.assert_valid();
20363    }
20364
20365    /// **The comparison seam's two marches run two techniques**, which is what
20366    /// the seam was built for.
20367    ///
20368    /// Alcove's second milestone is SSAO and GTAO in
20369    /// one frame, and this is that claim as a pair of pipeline handles: with the
20370    /// technique moved the near side runs the cheap tier and the far side the
20371    /// one that ships, and with it at its default both marches run the same
20372    /// shader and the seam separates nothing.
20373    ///
20374    /// **The control is the frame at the default**, and it is what makes the
20375    /// first half mean anything: a far side that always ran `ssao.slang` would
20376    /// satisfy the inequality below whatever `shipped_technique` did, and a
20377    /// chain that had simply forgotten to pass the far side a pipeline of its
20378    /// own would too.
20379    #[test]
20380    fn the_comparison_seam_marches_through_two_techniques() {
20381        let _blurs = ssao_blur_switch();
20382        let seam = ssao_split_switch();
20383        let technique = ssao_technique_switch();
20384        let other = other_technique_name();
20385
20386        let (recorder, device, queue) = open();
20387        let device = device.as_ref();
20388        let mut renderer =
20389            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20390        let (ships, cheap) = renderer
20391            .primary
20392            .ssao
20393            .as_ref()
20394            .expect("the default stack builds the occlusion pair")
20395            .gathers();
20396
20397        seam.set(0.5);
20398        let compared = frame_seen_from(
20399            device,
20400            &mut renderer,
20401            queue,
20402            &Camera::default(),
20403            &DirectionalLight::default(),
20404        );
20405        let one_technique = gathers_bound(&recorder, 0);
20406        let after = recorder.commands().len();
20407        compared.release(device);
20408
20409        technique.set(other);
20410        let frame = frame_seen_from(
20411            device,
20412            &mut renderer,
20413            queue,
20414            &Camera::default(),
20415            &DirectionalLight::default(),
20416        );
20417        let two_techniques = gathers_bound(&recorder, after);
20418        frame.finish(device, renderer);
20419
20420        assert_eq!(
20421            one_technique,
20422            vec![ships, ships],
20423            "a seam with the technique at its default has to march the shipped gather twice — \
20424             both sides read `shipped`'s configuration, and the picture is one technique either \
20425             side of a line"
20426        );
20427        assert_eq!(
20428            two_techniques,
20429            vec![cheap, ships],
20430            "with `r_ssao_technique {other}` the near side has to run the cheap tier \
20431             and the far side what ships; the far side follows the variable's *default*, exactly \
20432             as the four scalars do"
20433        );
20434        recorder.assert_valid();
20435    }
20436
20437    /// **The frame block carries the console's shadow filter on the near side
20438    /// of the seam, the shipped one on the far side, and the column
20439    /// [`crate::split::halves`] counted.**
20440    ///
20441    /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
20442    /// other seam, and it has to be a claim about *bytes* rather than about
20443    /// pass handles: the occlusion chain compares two pipelines and this
20444    /// compares two arms of one, so there is nothing in the pass list to look
20445    /// at. What a person sees is decided entirely by the row this asserts.
20446    ///
20447    /// **The frame at the default is the control**, and it is what makes the
20448    /// rest mean anything: a block that always wrote the shipped filter into
20449    /// both lanes would satisfy the third case's far side whatever
20450    /// `shipped_filter` did, and one that copied the near lane into the far one
20451    /// would satisfy the first two.
20452    ///
20453    /// The column is compared against `halves`' own answer rather than against
20454    /// a number written here, which is the seam module's whole point: a test
20455    /// that multiplied the fraction by the width itself would be a second
20456    /// opinion about the rounding, and the floor is exactly what that module's
20457    /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
20458    ///
20459    /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
20460    #[test]
20461    fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
20462        let switch = shadow_filter_switch();
20463
20464        let (recorder, device, queue) = open();
20465        let device = device.as_ref();
20466        let mut renderer =
20467            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20468
20469        // The seam is counted over the extent the scene is *drawn* at, which is
20470        // what `SV_Position.x` is denominated in — not the caller's window.
20471        let internal = renderer.internal_extent(TEST_EXTENT);
20472        let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
20473        assert!(
20474            left.width > 0,
20475            "a seam with no columns on one side would make every assertion below hold of a \
20476             frame that compares nothing"
20477        );
20478
20479        let ships = shadow::shipped_filter();
20480        let other = shadow::Filter::Box;
20481        assert_ne!(
20482            other.mode(),
20483            ships.mode(),
20484            "the filter this test moves the console to is the one that ships, so the seam it \
20485             asks for compares one kernel against itself"
20486        );
20487
20488        let draw = |renderer: &mut ForwardRenderer| {
20489            renderer
20490                .begin_frame(
20491                    device,
20492                    &Camera::default(),
20493                    &DirectionalLight::default(),
20494                    TEST_EXTENT,
20495                )
20496                .expect("write");
20497            let bytes = recorder
20498                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
20499                .expect("this frame's uniform block is live");
20500            let at = mesh::FRAME_UNIFORMS_SIZE - 16;
20501            core::array::from_fn(|lane| {
20502                u32::from_le_bytes(
20503                    bytes[at + lane * 4..at + lane * 4 + 4]
20504                        .try_into()
20505                        .expect("four bytes"),
20506                )
20507            })
20508        };
20509
20510        let shipped: [u32; 4] = draw(&mut renderer);
20511        assert_eq!(
20512            shipped,
20513            [ships.mode(), ships.mode(), 0, 0],
20514            "a frame nobody has touched the console on must carry the shipped filter in both \
20515             lanes and no column, which is the row every golden in this workspace was blessed \
20516             under"
20517        );
20518
20519        switch.filter(other);
20520        let unsplit: [u32; 4] = draw(&mut renderer);
20521        assert_eq!(
20522            unsplit,
20523            [other.mode(), other.mode(), 0, 0],
20524            "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
20525            other.label()
20526        );
20527
20528        switch.seam(0.5);
20529        let compared: [u32; 4] = draw(&mut renderer);
20530        assert_eq!(
20531            compared,
20532            [other.mode(), ships.mode(), left.width, 0],
20533            "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
20534             shipped one right of it; the far side follows the variable's *default*, exactly \
20535             as the occlusion chain's does"
20536        );
20537
20538        renderer.destroy(device);
20539        recorder.assert_valid();
20540    }
20541
20542    #[test]
20543    fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
20544        let switch = ssao_blur_switch();
20545
20546        let (recorder, device, queue) = open();
20547        let device = device.as_ref();
20548        let mut renderer =
20549            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20550        let imported = swapchain_image(device);
20551        let pool = crate::TransientPool::new();
20552
20553        let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20554        let counted_once = renderer.counters().instances;
20555        assert!(
20556            once.contains(&"ssao-blur".to_string()),
20557            "the shipping frame has to blur once, or the arm below is about a frame with no \
20558             occlusion in it at all: {once:#?}"
20559        );
20560        assert!(
20561            !once.contains(&"ssao-blur-2".to_string()),
20562            "a frame nobody moved the switch for must record one blur: {once:#?}"
20563        );
20564
20565        switch.set(2);
20566        let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20567        let counted_twice = renderer.counters().instances;
20568        assert!(
20569            twice.contains(&"ssao-blur-2".to_string()),
20570            "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
20571        );
20572        assert_eq!(
20573            twice.len(),
20574            once.len() + 1,
20575            "the second blur is the only pass that may join the frame: {twice:#?}"
20576        );
20577        assert_eq!(
20578            counted_twice,
20579            counted_once + FULLSCREEN_DRAWS,
20580            "the frame recorded a full-screen triangle its counter did not report"
20581        );
20582
20583        // The pass has to write somewhere the forward pass then reads, and the
20584        // graph is what would refuse a frame that bound an image nothing wrote.
20585        // `passes_in_a_frame` compiles rather than executes, so this is the
20586        // check that the third transient was requested at all.
20587        assert!(
20588            twice.iter().any(|pass| pass == "forward"),
20589            "the frame still has to reach its forward pass: {twice:#?}"
20590        );
20591        recorder.assert_valid();
20592    }
20593
20594    /// Every host-written buffer at the end of a whole ring of frames, keyed by
20595    /// the handle written and holding what that handle last held.
20596    ///
20597    /// A whole ring rather than one frame, because the blocks a frame writes are
20598    /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
20599    /// so one frame touches one slot of each and two single-frame batches would
20600    /// be comparing different buffers. A ring writes every slot, so two batches'
20601    /// keys line up and a difference between them is a difference in *bytes*.
20602    ///
20603    /// Only the events this call appends are read, so a caller can take one
20604    /// batch after another off the same recorder.
20605    fn host_buffers_over_a_ring(
20606        recorder: &Recorder,
20607        device: &dyn Device,
20608        renderer: &mut ForwardRenderer,
20609        queue: QueueHandle,
20610    ) -> std::collections::BTreeMap<u64, Vec<u8>> {
20611        let from = recorder.events().len();
20612        for _ in 0..FRAMES_IN_FLIGHT {
20613            frame(device, renderer, queue).release(device);
20614        }
20615        recorder.events()[from..]
20616            .iter()
20617            .filter_map(|event| match event {
20618                Event::BufferWritten { buffer, .. } => Some(*buffer),
20619                _ => None,
20620            })
20621            .map(|buffer| {
20622                let bytes = recorder
20623                    .buffer_bytes(buffer)
20624                    .expect("the stream only names buffers this recorder created");
20625                (buffer.to_bits(), bytes)
20626            })
20627            .collect()
20628    }
20629
20630    /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
20631    /// the ring, and moves nothing else in the frame.**
20632    ///
20633    /// The device test drives the two occlusion pipelines directly and
20634    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
20635    /// count, so until this the slice count was a variable with a `get_i64` and
20636    /// no evidence that a rendered frame ever carried it: `slice_count` could
20637    /// have returned its default unconditionally and every check in this
20638    /// workspace would still be green.
20639    ///
20640    /// So the observable is the bytes, taken off the null recorder's write log
20641    /// after a whole ring of frames at each setting and compared **by handle**.
20642    /// Two claims come out of that comparison and both are load-bearing:
20643    ///
20644    /// * **Some block moved** — every ring slot, in fact, which is what says the
20645    ///   count reaches the frame at all rather than only the slot the last frame
20646    ///   happened to land in.
20647    /// * **Every block that moved, moved only there.** A frame is a few dozen
20648    ///   host writes and the slice count has business with exactly one word of
20649    ///   one of them; a setting that perturbed a matrix, an instance or a shadow
20650    ///   view would be drawing a different frame for a reason nobody asked for,
20651    ///   and the "at least one differs" half alone would pass on it happily.
20652    ///
20653    /// **Holds every switch whose row is in a block it compares**, in the lock
20654    /// order: the two batches are compared byte for byte over every host
20655    /// buffer the frame writes, so any console row another test moves between
20656    /// them — the blur count, the seam, the technique, the shadow filter, or
20657    /// `crate::ssao`'s own mover of the params block — reads here as "some
20658    /// other write moving". [`ssao_technique_switch`] is the one that
20659    /// serialises against that mover.
20660    #[test]
20661    fn four_slices_reach_the_frame_the_shader_reads() {
20662        let _blurs = ssao_blur_switch();
20663        let _seam = ssao_split_switch();
20664        let switch = ssao_slice_switch();
20665        let _technique = ssao_technique_switch();
20666        let _filter = shadow_filter_switch();
20667
20668        let (recorder, device, queue) = open();
20669        let device = device.as_ref();
20670        let mut renderer =
20671            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20672
20673        // A ring rendered before either batch is taken, because the two below
20674        // are compared by handle and the renderer's opening frame writes blocks
20675        // no later frame writes again: it fills a cold shadow atlas, so the
20676        // shadow views' uniform blocks and the draw-generation blocks of the
20677        // cascades that were drawn are written once and never again while the
20678        // cache holds. Those would be in the first batch and missing from the
20679        // second, and a key that is only in one of them is a difference this
20680        // test cannot say anything about.
20681        for _ in 0..FRAMES_IN_FLIGHT {
20682            frame(device, &mut renderer, queue).release(device);
20683        }
20684        let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20685        switch.set(i64::from(ssao::SLICE_COUNT_MAX));
20686        let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20687        assert_eq!(
20688            shipping.keys().collect::<Vec<_>>(),
20689            asked.keys().collect::<Vec<_>>(),
20690            "the two batches must write the same buffers, or they are not comparable",
20691        );
20692
20693        // Which bytes moving the count alone is allowed to move, asked of
20694        // `SsaoParams::to_bytes` rather than written here as an offset: the
20695        // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
20696        // of the count would leave a number spelled here pointing at the radius.
20697        let block_of = |slices| {
20698            ssao::SsaoParams {
20699                inv_proj: [0.0; 16],
20700                proj: [0.0; 16],
20701                inv_view: [0.0; 16],
20702                radius: 0.0,
20703                slices,
20704                intensity: ssao::INTENSITY_DEFAULT,
20705                bent_normals: crate::ssao::bent_normals(),
20706            }
20707            .to_bytes()
20708        };
20709        let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
20710        let at_max = block_of(ssao::SLICE_COUNT_MAX);
20711        let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
20712            .filter(|at| at_shipping[*at] != at_max[*at])
20713            .collect();
20714
20715        let mut moved = 0;
20716        for (handle, before) in &shipping {
20717            let after = &asked[handle];
20718            if before == after {
20719                continue;
20720            }
20721            moved += 1;
20722            let mut only_the_count = before.clone();
20723            for at in &count_word {
20724                assert_eq!(
20725                    before[*at], at_shipping[*at],
20726                    "buffer {handle} differs between the batches but did not go in holding the \
20727                     shipping slice count, so this is some other write moving",
20728                );
20729                only_the_count[*at] = at_max[*at];
20730            }
20731            assert_eq!(
20732                after, &only_the_count,
20733                "buffer {handle} moved somewhere other than the slice count's word: the setting \
20734                 is perturbing a block it has no business in",
20735            );
20736        }
20737        assert_eq!(
20738            moved, FRAMES_IN_FLIGHT,
20739            "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
20740             none of them is a console variable no rendered frame reads",
20741        );
20742
20743        renderer.destroy(device);
20744        recorder.assert_valid();
20745    }
20746
20747    /// **The debug draw layer costs a frame nothing until something is appended
20748    /// *and* the console switch is on, and then it is the pass immediately
20749    /// before the tonemap.**
20750    ///
20751    /// Four claims, and each is a separate way to get this wrong.
20752    ///
20753    /// * **Off by default** is what keeps every golden image in the workspace
20754    ///   where it was blessed.
20755    /// * **A segment appended while the switch is off records nothing**, so a
20756    ///   system may append unconditionally.
20757    /// * **The switch on with an empty buffer records nothing either** — this is
20758    ///   the "costs nothing when empty" claim as a check rather than a sentence:
20759    ///   the compiled pass list is compared whole against the frame drawn before
20760    ///   the layer was switched on, so a pass that clears, blits or barriers
20761    ///   anything would show up here.
20762    /// * **Before the tonemap**, which is
20763    ///   `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20764    ///   the ground grid above. Recorded a line later it would draw into the
20765    ///   display-space target and be free of the exposure, which compiles and
20766    ///   draws lines and is the wrong picture.
20767    ///
20768    /// And the fifth, which is what "immediate mode" means: the frame *after*
20769    /// the one that appended records nothing again, because
20770    /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20771    ///
20772    /// The whole list is compared rather than its length, for the ground grid
20773    /// test's reason: one more pass is satisfied by gaining the wrong one.
20774    ///
20775    /// **This test owns `r_debug_draw` for its duration**, through
20776    /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20777    /// between tests, so the two checks here that move it have to take turns.
20778    /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20779    /// none of it.
20780    #[test]
20781    fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20782        let switch = debug_draw_switch();
20783        let _blurs = ssao_blur_switch();
20784
20785        let (recorder, device, queue) = open();
20786        let device = device.as_ref();
20787        let mut renderer =
20788            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20789        let imported = swapchain_image(device);
20790        let mut pool = crate::TransientPool::new();
20791
20792        assert!(
20793            !crate::DebugDraw::enabled(),
20794            "the layer must be off before anything switches it on, or every claim below is \
20795             about a different default"
20796        );
20797        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20798        assert!(
20799            !off.contains(&"debug-draw".to_string()),
20800            "the layer must not be in a frame nobody switched it on for: {off:#?}"
20801        );
20802
20803        renderer
20804            .debug_draw()
20805            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20806        assert_eq!(
20807            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20808            off,
20809            "a segment appended while the switch is off must record no pass"
20810        );
20811
20812        switch.set(true);
20813        assert_eq!(
20814            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20815            off,
20816            "the switch on with an empty buffer must record the frame the layer's absence would"
20817        );
20818
20819        renderer
20820            .debug_draw()
20821            .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20822        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20823        let mut expected = off.clone();
20824        let tonemap = expected
20825            .iter()
20826            .position(|label| label == "tonemap")
20827            .expect("a frame has to reach the swapchain");
20828        expected.insert(tonemap, "debug-draw".to_string());
20829        assert_eq!(
20830            on, expected,
20831            "the layer must be the one pass gained, and it must sit before the tonemap"
20832        );
20833
20834        assert_eq!(
20835            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20836            off,
20837            "the buffer is immediate mode: the frame after the one that appended must record \
20838             nothing"
20839        );
20840
20841        switch.set(false);
20842        renderer.destroy(device);
20843        pool.destroy(device);
20844        device.destroy_image_view(imported.view);
20845        device.destroy_image(imported.image);
20846        recorder.assert_valid();
20847    }
20848
20849    /// **The debug draw layer's own call is counted in the frame's draws.**
20850    ///
20851    /// [`ForwardRenderer::counters`]' draw count is compared against the
20852    /// commands the null backend actually recorded, which is the same instrument
20853    /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20854    /// uses — so a layer whose line list was recorded and not counted fails here
20855    /// rather than quietly making every panel's draw row one short.
20856    ///
20857    /// Both directions are asserted: the frame that drew a segment records one
20858    /// more draw than the frame before it, *and* the counter moved by the same
20859    /// one. A count wired to a constant satisfies neither.
20860    ///
20861    /// It owns `r_debug_draw` for its duration, on
20862    /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20863    /// terms.
20864    #[test]
20865    fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20866        let switch = debug_draw_switch();
20867        let _blurs = ssao_blur_switch();
20868        let _seam = ssao_split_switch();
20869
20870        let (recorder, device, queue) = open();
20871        let device = device.as_ref();
20872        let mut renderer =
20873            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20874
20875        // A different sun in each of the two frames, so both of them redraw the
20876        // shadow atlas: the claim below is that the layer's own call is the one
20877        // draw the second frame gained, and a second frame that cached its
20878        // atlas would have lost the atlas's draws at the same time. See
20879        // [`moving_sun`].
20880        let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20881        let without = renderer.counters().draws;
20882        assert_eq!(
20883            without,
20884            recorded_draws(&recorder) as u64,
20885            "the counter and the frame's recorded draws disagree before the layer draws at all"
20886        );
20887        quiet.release(device);
20888
20889        switch.set(true);
20890        renderer
20891            .debug_draw()
20892            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20893        let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20894        let with = renderer.counters().draws;
20895        assert_eq!(
20896            with,
20897            without + 1,
20898            "the layer records one draw, so the count has to move by one"
20899        );
20900        assert_eq!(
20901            recorded_draws(&recorder) as u64,
20902            without + with,
20903            "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20904             counted somewhere it was not recorded or recorded somewhere it was not counted"
20905        );
20906
20907        switch.set(false);
20908        drawn.finish(device, renderer);
20909        recorder.assert_valid();
20910    }
20911
20912    /// **The depth-only passes run the depth-only entry point, and the colour
20913    /// pass does not.**
20914    ///
20915    /// Topic 43 §2 split the vertex pool so a pass
20916    /// that wants a clip position and no more could fetch stream 0 alone, and
20917    /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20918    /// is the whole of how that split is spent. **Nothing else in the tree sees
20919    /// it.** `crcbl_shaders::mesh`'s
20920    /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20921    /// compiled artifact and would pass with the entry point built and unused;
20922    /// no golden moves, because the two stages compute the same clip position on
20923    /// purpose; the render graph records a legal frame either way; and the
20924    /// measured price says nothing — pointing this pipeline back at `vertexMain`
20925    /// cost the depth prepass about a tenth more on lavapipe and nothing to
20926    /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20927    /// asserted here, against the reference backend, which records the entry
20928    /// point a pipeline names precisely so this question has an answer.
20929    ///
20930    /// **Both halves, so the check is shown to discriminate.** A lookup that
20931    /// answered `depthVertexMain` for every pipeline would satisfy the first
20932    /// assertion alone, and the colour pipeline is the one that must *not* have
20933    /// moved. The labels are the descriptors' own and are what the two are told
20934    /// apart by, so a renamed pipeline fails at the `expect` rather than
20935    /// silently matching nothing.
20936    #[test]
20937    fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20938        let (recorder, device, queue) = open();
20939        let device = device.as_ref();
20940        // A masked row, so the build compiles the cutout shape the third
20941        // assertion reads — a scene that masks nothing gets none.
20942        let mut scene = scene::demo();
20943        scene.materials[DEMO_UNTINTED].flags = mesh::GpuMaterial::ALPHA_MODE_MASK;
20944        let renderer = ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
20945            .expect("built");
20946        // A mesh stage has no vertex entry point to name, and this whole rung is
20947        // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20948        // preset reports no `Features::MESH_SHADER`, so this is what it built;
20949        // asserted rather than assumed, because a preset that grew the feature
20950        // would leave every assertion below looking for pipelines that do not
20951        // exist.
20952        assert_ne!(
20953            renderer.geometry_path(),
20954            crcbl_hal::GeometryPath::MeshShader,
20955            "this device built a mesh-shader path, whose geometry stage names no vertex \
20956             entry point at all"
20957        );
20958
20959        let pipelines = recorder.graphics_pipeline_vertex_entries();
20960        let entry_of = |label: &str| -> String {
20961            let found: Vec<&str> = pipelines
20962                .iter()
20963                .filter(|(name, _)| name.as_deref() == Some(label))
20964                .map(|(_, entry)| entry.as_str())
20965                .collect();
20966            assert_eq!(
20967                found.len(),
20968                1,
20969                "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20970                found.len()
20971            );
20972            found[0].to_owned()
20973        };
20974
20975        assert_eq!(
20976            entry_of("shadow cascade"),
20977            "depthVertexMain",
20978            "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20979             that reads the position stream alone"
20980        );
20981        assert_eq!(
20982            entry_of("forward mesh"),
20983            "vertexMain",
20984            "the colour pass needs every attribute the depth pass skips, so it is the entry \
20985             point that reads a whole vertex"
20986        );
20987        assert_eq!(
20988            entry_of("shadow cascade masked"),
20989            "vertexMain",
20990            "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
20991             in the attribute region `depthVertexMain` exists not to read"
20992        );
20993
20994        renderer.destroy(device);
20995        recorder.assert_valid();
20996    }
20997
20998    /// **A masked material moves that mesh's depth draws onto the cutout
20999    /// pipeline, and moves nothing else.**
21000    ///
21001    /// The mechanism is which pipeline handle the recorded stream binds and
21002    /// which buckets' indirect calls follow each bind — the wireframe test's
21003    /// observable, for the same reason: a field saying a mode was read would
21004    /// prove the flag was read, not that the frame changed.
21005    ///
21006    /// Four claims, and each rules out a different way of passing wrongly:
21007    ///
21008    /// * a scene with nothing masked binds the vertex-only pipeline and
21009    ///   **never** the cutout one, which is the "an opaque frame costs what it
21010    ///   always did" claim at the level a null device can see it;
21011    /// * a scene with one masked row binds **both** in the depth prepass and
21012    ///   both in the shadow atlas — a per-frame choice binds one or the other,
21013    ///   never the pair;
21014    /// * the calls following each bind are exactly that mode's buckets, in
21015    ///   bucket order, read off the argument offsets the draws name. A split
21016    ///   that bound both pipelines and drew every bucket under each would
21017    ///   satisfy the claim above and double the frame's draws;
21018    /// * and folding the two handles together — then collapsing the runs of
21019    ///   equal binds the fold creates — leaves the two frames' bind streams
21020    ///   **equal**, so the colour pass, the tile clears and the reflective
21021    ///   shadow map are all where they were. A change that had also moved the
21022    ///   colour pass would satisfy the first three and fail this.
21023    ///
21024    /// The two scenes differ in one flags word and nothing else.
21025    #[test]
21026    fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
21027        use crcbl_hal::null::Command;
21028
21029        // The occlusion blur count is a process-global console variable and a
21030        // frame binds one pipeline per blur, so a concurrent test moving it
21031        // would put a bind in one of these frames and not the other — the
21032        // wireframe test's hazard exactly.
21033        let _blurs = ssao_blur_switch();
21034
21035        let masked_scene = {
21036            let mut scene = crate::scene::demo();
21037            scene.materials[DEMO_UNTINTED].flags =
21038                crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
21039            scene
21040        };
21041
21042        /// What one scene's frame reveals: the bucket count and each bucket's
21043        /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
21044        /// pairs the depth prepass and the shadow atlas recorded, and the whole
21045        /// bind stream with the two depth handles folded into one.
21046        struct Recorded {
21047            modes: Vec<u32>,
21048            cutouts: usize,
21049            plains: usize,
21050            prepass: Vec<(bool, u32)>,
21051            atlas: Vec<(bool, u32)>,
21052            folded: Vec<String>,
21053        }
21054
21055        // One frame each, from two renderers rather than two frames from one:
21056        // a bucket table is fixed at build, and two builds keep the frames'
21057        // shadow-atlas state identical — both are a first frame.
21058        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
21059            let (recorder, device, queue) = open();
21060            let device = device.as_ref();
21061            let mut renderer =
21062                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
21063                    .expect("the null backend accepts the demo description");
21064            place_cube(&mut renderer, Mat4::IDENTITY);
21065            let imported = swapchain_image(device);
21066            let mut pool = crate::TransientPool::new();
21067            renderer
21068                .begin_frame(
21069                    device,
21070                    &Camera::default(),
21071                    &DirectionalLight::default(),
21072                    (64, 48),
21073                )
21074                .expect("write");
21075            let mut graph = crate::RenderGraph::new(queue);
21076            let target = graph.import_image("target", imported);
21077            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21078            let compiled = graph.compile(&pool).expect("a legal frame");
21079            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21080                label: Some("alpha mask lap"),
21081                queue,
21082            });
21083            compiled
21084                .execute(device, &mut pool, encoder.as_mut(), None)
21085                .expect("the graph executed");
21086            encoder.finish().expect("recording succeeded");
21087            let plain = renderer.shadow_pipeline.single;
21088            // `None` for the opaque scene, which builds no cutout shape at all
21089            // and so can bind none — the comparisons below read it as such.
21090            let cutout = renderer.depth_masked_pipeline.map(|masked| masked.single);
21091            assert_ne!(
21092                Some(plain),
21093                cutout,
21094                "the two depth pipelines have to be two objects, or nothing below discriminates"
21095            );
21096            // Which bucket a draw is, recovered from the argument offset it
21097            // names — the offsets are the renderer's own accessor, so a call
21098            // pointing at the wrong bucket has no entry here at all.
21099            let bucket_of = |args_offset: u64| -> u32 {
21100                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
21101                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
21102                    .unwrap_or_else(|| {
21103                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
21104                    })
21105            };
21106            // Per depth pass: the pipeline in force at each indirect call and
21107            // the bucket that call drew, in the order they were recorded.
21108            let pass_calls = |label: &str| -> Vec<(bool, u32)> {
21109                let mut current = None;
21110                let mut out = Vec::new();
21111                for command in commands_in_pass(&recorder, label) {
21112                    match command {
21113                        Command::BindGraphicsPipeline(handle) => current = Some(handle),
21114                        Command::DrawIndexedIndirectCount(draw) => {
21115                            let handle = current.expect("a draw follows a pipeline bind");
21116                            assert!(
21117                                handle == plain || Some(handle) == cutout,
21118                                "a depth pass drew under a pipeline that is neither depth one"
21119                            );
21120                            out.push((Some(handle) == cutout, bucket_of(draw.args_offset)));
21121                        }
21122                        _ => {}
21123                    }
21124                }
21125                out
21126            };
21127            let prepass = pass_calls("depth-prepass");
21128            let atlas = pass_calls("shadow");
21129            let binds: Vec<GraphicsPipelineHandle> = recorder
21130                .commands()
21131                .iter()
21132                .filter_map(|command| match command {
21133                    Command::BindGraphicsPipeline(handle) => Some(*handle),
21134                    _ => None,
21135                })
21136                .collect();
21137            let cutouts = binds
21138                .iter()
21139                .filter(|handle| Some(**handle) == cutout)
21140                .count();
21141            let plains = binds.iter().filter(|handle| **handle == plain).count();
21142            let labels = graphics_pipeline_labels(&recorder);
21143            let mut folded: Vec<String> = Vec::with_capacity(binds.len());
21144            for handle in binds {
21145                let handle = if Some(handle) == cutout {
21146                    plain
21147                } else {
21148                    handle
21149                };
21150                let handle = labels[handle.index() as usize].clone();
21151                // The fold turns the masked frame's `plain, cutout` pair into
21152                // `plain, plain`; collapsing a run of equal binds is what makes
21153                // the two streams comparable without hiding a bind of anything
21154                // else, since no pass in either frame binds two *different*
21155                // pipelines that the fold could bring together.
21156                if folded.last() != Some(&handle) {
21157                    folded.push(handle);
21158                }
21159            }
21160            let modes = renderer.bucket_modes.clone();
21161            renderer.destroy(device);
21162            recorder.assert_valid();
21163            Recorded {
21164                modes,
21165                cutouts,
21166                plains,
21167                prepass,
21168                atlas,
21169                folded,
21170            }
21171        };
21172
21173        let opaque = bound(&crate::scene::demo());
21174        let masked = bound(&masked_scene);
21175
21176        assert_eq!(
21177            opaque.cutouts, 0,
21178            "a scene with nothing masked must never bind the cutout pipeline"
21179        );
21180        assert!(
21181            opaque.plains > 0,
21182            "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
21183             above is about a frame with no depth pass in it"
21184        );
21185        assert!(
21186            opaque.modes.iter().all(|mode| *mode == 0),
21187            "and every one of its buckets is opaque: {:?}",
21188            opaque.modes
21189        );
21190        assert_eq!(
21191            opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
21192            0,
21193            "so no opaque draw is recorded under the cutout pipeline"
21194        );
21195
21196        assert!(
21197            masked.cutouts > 0 && masked.plains > 0,
21198            "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
21199             the choice is still per frame",
21200            masked.cutouts,
21201            masked.plains
21202        );
21203        // What each depth pass should have recorded: every opaque bucket under
21204        // the plain pipeline in bucket order, then every masked one under the
21205        // cutout, which is the partition order `depth_partitions` lays down.
21206        let want: Vec<(bool, u32)> = [false, true]
21207            .into_iter()
21208            .flat_map(|cutout| {
21209                masked
21210                    .modes
21211                    .iter()
21212                    .enumerate()
21213                    .filter(move |(_, mode)| {
21214                        (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
21215                    })
21216                    .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
21217            })
21218            .collect();
21219        assert!(
21220            want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
21221            "the masked demo has to hold buckets of both modes, or this compares one partition \
21222             against itself: {:?}",
21223            masked.modes
21224        );
21225        assert_eq!(
21226            masked.prepass, want,
21227            "the depth prepass must record each bucket once, under the pipeline its own mode \
21228             asked for"
21229        );
21230        // The atlas draws every bucket once per occupied view, and the
21231        // partition is **outside** the view loop — one pipeline bind covers
21232        // every view of that mode — so its stream is each partition's bucket
21233        // list repeated once per view.
21234        let views = masked.atlas.len() / want.len();
21235        assert!(
21236            views > 0 && masked.atlas.len() % want.len() == 0,
21237            "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
21238             of views",
21239            masked.atlas.len(),
21240            want.len()
21241        );
21242        let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
21243        for cutout in [false, true] {
21244            let partition: Vec<(bool, u32)> = want
21245                .iter()
21246                .copied()
21247                .filter(|(mode, _)| *mode == cutout)
21248                .collect();
21249            for _ in 0..views {
21250                atlas_want.extend_from_slice(&partition);
21251            }
21252        }
21253        assert_eq!(
21254            masked.atlas, atlas_want,
21255            "and every shadow view draws both partitions, each under its own pipeline"
21256        );
21257
21258        assert_eq!(
21259            masked.folded, opaque.folded,
21260            "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
21261        );
21262    }
21263
21264    /// **A double-sided material moves every pass's draws for its own buckets
21265    /// onto the `CullMode::None` twins, and moves nothing else.**
21266    ///
21267    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
21268    /// claim for glTF's other mode, and it is wider by construction: an alpha
21269    /// mask is cut inside a fragment stage, so only the two depth-only passes
21270    /// route around it, while a cull mode is a pipeline state and **every** pass
21271    /// that draws the surface has to route around it — the colour pass, both
21272    /// depth passes and the two reflective shadow maps.
21273    ///
21274    /// So this walks the whole recorded stream rather than two named passes:
21275    /// every render pass that recorded an indirect draw is read back as the
21276    /// (side, bucket) pairs it recorded, and each of the four claims below is
21277    /// about all of them at once.
21278    ///
21279    /// * a scene with nothing double-sided binds **no** cull-none twin
21280    ///   anywhere, which is the "an all-single-sided frame costs what it always
21281    ///   did" claim at the level a null device can see it;
21282    /// * a scene with one double-sided row binds a twin in every pass that
21283    ///   draws — a frame that had only routed the colour pass would satisfy
21284    ///   nothing below, and one that had only routed the depth passes would
21285    ///   draw a surface the prepass wrote no depth for;
21286    /// * the calls following each bind are exactly that side's buckets, in
21287    ///   bucket order. A split that bound both pipelines and drew every bucket
21288    ///   under each would satisfy the claim above and double the frame's draws;
21289    /// * and folding each twin onto the pipeline it is a twin of — then
21290    ///   collapsing the runs of equal binds the fold creates — leaves the two
21291    ///   frames' bind streams **equal**, so nothing else in the frame moved.
21292    ///
21293    /// The two scenes differ in one flags word and nothing else.
21294    ///
21295    /// [`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
21296    #[test]
21297    fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
21298        use crcbl_hal::null::Command;
21299
21300        // The occlusion blur count is a process-global console variable and a
21301        // frame binds one pipeline per blur — the masked test's hazard exactly.
21302        let _blurs = ssao_blur_switch();
21303
21304        // **A scene whose probes ask to be updated**, because the reflective
21305        // shadow maps are recorded by a volume rather than by an effect bit —
21306        // and they are two of the five passes this claim is about. The demo's
21307        // empty grid records neither, which would leave the widest half of the
21308        // routing unchecked.
21309        let scene_with_probes = || {
21310            let mut scene = crate::scene::demo();
21311            scene.capacities.probes = 1;
21312            scene.probes = crate::scene::ProbeGrid {
21313                volume: crcbl_shaders::probe::ProbeVolume {
21314                    origin: [0.0; 3],
21315                    inv_spacing: [1.0; 3],
21316                    counts: [1, 1, 1],
21317                    levels: 1,
21318                    steps: crcbl_shaders::probe::ProbeSteps::default(),
21319                },
21320                probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
21321                update: ProbeUpdate::EveryFrame,
21322            };
21323            scene
21324        };
21325        let single_scene = scene_with_probes();
21326        let double_scene = {
21327            let mut scene = scene_with_probes();
21328            scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
21329            scene
21330        };
21331
21332        /// What one scene's frame reveals: each bucket's mode, how often a
21333        /// cull-none twin was bound at all, every drawing pass's (side, bucket)
21334        /// pairs in record order, and the whole bind stream with each twin
21335        /// folded onto the pipeline it twins.
21336        struct Recorded {
21337            modes: Vec<u32>,
21338            twins_bound: usize,
21339            passes: Vec<(String, Vec<(bool, u32)>)>,
21340            folded: Vec<String>,
21341        }
21342
21343        // One frame each, from two renderers rather than two frames from one, on
21344        // the masked test's terms: a bucket table is fixed at build, and two
21345        // builds keep both frames a first frame.
21346        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
21347            let (recorder, device, queue) = open();
21348            let device = device.as_ref();
21349            let mut renderer =
21350                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
21351                    .expect("the null backend accepts the demo description");
21352            assert!(
21353                !renderer.emit.is_mesh(),
21354                "this preset built a mesh-shader path, whose draws carry no argument offset to \
21355                 recover a bucket from"
21356            );
21357            place_cube(&mut renderer, Mat4::IDENTITY);
21358            // **One shadowed spot**, so the punctual reflective shadow map has a
21359            // face to draw into: the pass is recorded on every frame but its
21360            // view loop is empty without one, and an empty loop records no draw
21361            // for the claim below to be about.
21362            renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
21363                position: Vec3::new(0.0, 2.0, 0.0),
21364                radius: 8.0,
21365                color: Vec3::splat(4.0),
21366                direction: Vec3::NEG_Y,
21367                inner_angle: 0.3,
21368                outer_angle: 0.6,
21369                fill: false,
21370            })]);
21371            let imported = swapchain_image(device);
21372            let mut pool = crate::TransientPool::new();
21373            renderer
21374                .begin_frame(
21375                    device,
21376                    &Camera::default(),
21377                    &DirectionalLight::default(),
21378                    (64, 48),
21379                )
21380                .expect("write");
21381            let mut graph = crate::RenderGraph::new(queue);
21382            let target = graph.import_image("target", imported);
21383            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21384            let compiled = graph.compile(&pool).expect("a legal frame");
21385            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21386                label: Some("double sided lap"),
21387                queue,
21388            });
21389            compiled
21390                .execute(device, &mut pool, encoder.as_mut(), None)
21391                .expect("the graph executed");
21392            encoder.finish().expect("recording succeeded");
21393
21394            // Every twin and the pipeline it twins, so a bind can be reported as
21395            // a side and folded back. Asserted distinct, or nothing here
21396            // discriminates.
21397            // The scene masks nothing, so it built no cutout shape to twin.
21398            assert_eq!(renderer.depth_masked_pipeline, None);
21399            let sided: Vec<SidedPipelines> = [
21400                Some(renderer.mesh_pipeline),
21401                Some(renderer.shadow_pipeline),
21402                renderer.rsm_pipeline,
21403            ]
21404            .into_iter()
21405            .flatten()
21406            .collect();
21407            for pair in &sided {
21408                assert_ne!(
21409                    Some(pair.single),
21410                    pair.double,
21411                    "a pipeline and its cull-none twin have to be two objects"
21412                );
21413            }
21414            let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
21415                sided
21416                    .iter()
21417                    .find(|pair| pair.double == Some(handle))
21418                    .map(|pair| pair.single)
21419            };
21420            let bucket_of = |args_offset: u64| -> u32 {
21421                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
21422                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
21423                    .unwrap_or_else(|| {
21424                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
21425                    })
21426            };
21427
21428            let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
21429            let labels = graphics_pipeline_labels(&recorder);
21430            let mut folded: Vec<String> = Vec::new();
21431            let mut twins_bound = 0usize;
21432            let mut current: Option<GraphicsPipelineHandle> = None;
21433            let mut label: Option<String> = None;
21434            let mut calls: Vec<(bool, u32)> = Vec::new();
21435            let commands = recorder.commands();
21436            for command in &commands {
21437                match command {
21438                    Command::BeginRenderPass { label: name, .. } => {
21439                        label = name.clone();
21440                        calls = Vec::new();
21441                    }
21442                    Command::EndRenderPass => {
21443                        if !calls.is_empty() {
21444                            passes.push((
21445                                label.clone().expect("every pass here is labelled"),
21446                                std::mem::take(&mut calls),
21447                            ));
21448                        }
21449                    }
21450                    Command::BindGraphicsPipeline(handle) => {
21451                        current = Some(*handle);
21452                        if twin_of(*handle).is_some() {
21453                            twins_bound += 1;
21454                        }
21455                        // The fold turns a `single, double` pair into
21456                        // `single, single`; collapsing a run of equal binds is
21457                        // what makes the two streams comparable without hiding
21458                        // a bind of anything else.
21459                        let folded_handle = twin_of(*handle).unwrap_or(*handle);
21460                        let folded_label = &labels[folded_handle.index() as usize];
21461                        if folded.last() != Some(folded_label) {
21462                            folded.push(folded_label.clone());
21463                        }
21464                    }
21465                    Command::DrawIndexedIndirectCount(draw) => {
21466                        let handle = current.expect("a draw follows a pipeline bind");
21467                        calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
21468                    }
21469                    Command::DrawIndexedIndirect(draw) => {
21470                        let handle = current.expect("a draw follows a pipeline bind");
21471                        calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
21472                    }
21473                    _ => {}
21474                }
21475            }
21476            let modes = renderer.bucket_modes.clone();
21477            renderer.destroy(device);
21478            pool.destroy(device);
21479            device.destroy_image_view(imported.view);
21480            device.destroy_image(imported.image);
21481            recorder.assert_valid();
21482            Recorded {
21483                modes,
21484                twins_bound,
21485                passes,
21486                folded,
21487            }
21488        };
21489
21490        let single = bound(&single_scene);
21491        let double = bound(&double_scene);
21492
21493        assert_eq!(
21494            single.twins_bound, 0,
21495            "a scene with nothing double-sided must never bind a cull-none twin"
21496        );
21497        // Named rather than counted, because the claim is that **every** pass
21498        // that draws the surface routes: a frame that had quietly stopped
21499        // recording one of them would satisfy a count and leave that pass's
21500        // routing unchecked for ever.
21501        let drawing: Vec<&str> = single
21502            .passes
21503            .iter()
21504            .map(|(name, _)| name.as_str())
21505            .collect();
21506        for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
21507            assert!(
21508                drawing.contains(&pass),
21509                "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
21510            );
21511        }
21512        assert!(
21513            double.twins_bound > 0,
21514            "a double-sided scene must bind the cull-none twins"
21515        );
21516        assert_eq!(
21517            double
21518                .passes
21519                .iter()
21520                .map(|(name, _)| name)
21521                .collect::<Vec<_>>(),
21522            single
21523                .passes
21524                .iter()
21525                .map(|(name, _)| name)
21526                .collect::<Vec<_>>(),
21527            "the two frames must draw in the same passes, or they are not comparable"
21528        );
21529
21530        // What each drawing pass should have recorded: every single-sided bucket
21531        // under the plain pipeline in bucket order, then every double-sided one
21532        // under the twin — the partition order `sided_partitions` lays down —
21533        // repeated once per view for a pass that draws several.
21534        let want: Vec<(bool, u32)> = [false, true]
21535            .into_iter()
21536            .flat_map(|twin| {
21537                double
21538                    .modes
21539                    .iter()
21540                    .enumerate()
21541                    .filter(move |(_, mode)| {
21542                        (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
21543                    })
21544                    .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
21545            })
21546            .collect();
21547        assert!(
21548            want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
21549            "the double-sided demo has to hold buckets of both sides, or this compares one \
21550             partition against itself: {:?}",
21551            double.modes
21552        );
21553        for (name, calls) in &double.passes {
21554            let views = calls.len() / want.len();
21555            assert!(
21556                views > 0 && calls.len() % want.len() == 0,
21557                "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
21558                 views",
21559                calls.len(),
21560                want.len()
21561            );
21562            // The partition is **outside** any view loop — one pipeline bind
21563            // covers every view of that side — so the stream is each partition's
21564            // bucket list repeated once per view.
21565            let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
21566            for twin in [false, true] {
21567                let partition: Vec<(bool, u32)> = want
21568                    .iter()
21569                    .copied()
21570                    .filter(|(side, _)| *side == twin)
21571                    .collect();
21572                for _ in 0..views {
21573                    expected.extend_from_slice(&partition);
21574                }
21575            }
21576            assert_eq!(
21577                *calls, expected,
21578                "`{name}` must record each bucket once per view, under the pipeline its own \
21579                 side asked for"
21580            );
21581        }
21582
21583        assert_eq!(
21584            double.folded, single.folded,
21585            "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
21586             pipeline it twins"
21587        );
21588    }
21589
21590    /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
21591    ///
21592    /// The mechanism, at the level a null device can observe it: which pipeline
21593    /// handle each pass of the recorded stream binds. A field on the renderer
21594    /// would say only that a flag moved — this says the *frame* moved, and says
21595    /// which part of it did.
21596    ///
21597    /// Four claims, and each rules out a different way of passing wrongly:
21598    ///
21599    /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
21600    ///   one does not exist;
21601    /// * switching on **removes** the filled pipeline from the stream — a second
21602    ///   pipeline that was built and never bound would still leave it there;
21603    /// * every other pipeline the frame binds is unchanged, so the depth prepass
21604    ///   and the shadow cascades are still filling triangles;
21605    /// * and switching off puts the stream back exactly, so the view is a toggle
21606    ///   rather than a one-way door.
21607    #[test]
21608    fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
21609        use crcbl_hal::null::Command;
21610
21611        // The pipelines a frame binds include one per occlusion blur, and the
21612        // blur count is a process-global console variable — so a concurrent
21613        // test holding `r_ssao_blur_passes` at two adds a bind to one of the
21614        // frames below and not to the others. It reddened this assertion on
21615        // 2026-08-31 under a workspace `cargo test`.
21616        let _blurs = ssao_blur_switch();
21617        let (recorder, device, queue) =
21618            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21619        let device = device.as_ref();
21620        assert!(
21621            ForwardRenderer::supports_wireframe(device),
21622            "this test needs the line fill mode, and asked the device for it",
21623        );
21624        let mut renderer =
21625            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21626        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21627        let imported = swapchain_image(device);
21628        let mut pool = crate::TransientPool::new();
21629
21630        // The pipelines one frame binds, in record order. Cumulative recorder,
21631        // so each call takes the tail its own frame added.
21632        let mut seen = 0usize;
21633        // A different sun each lap, so the shadow atlas is redrawn in every one
21634        // of them: the comparison below is "which pipelines did this frame
21635        // bind", and a lap that cached its atlas would bind the depth-only
21636        // pipeline one fewer time for a reason that has nothing to do with the
21637        // wireframe. See [`moving_sun`].
21638        let mut lap = 0u32;
21639        let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
21640            lap += 1;
21641            renderer
21642                .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
21643                .expect("write");
21644            let mut graph = crate::RenderGraph::new(queue);
21645            let target = graph.import_image("target", imported);
21646            renderer.add_passes(&mut graph, pool, target, (64, 48));
21647            let compiled = graph.compile(pool).expect("a legal frame");
21648            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21649                label: Some("wireframe lap"),
21650                queue,
21651            });
21652            compiled
21653                .execute(device, pool, encoder.as_mut(), None)
21654                .expect("the graph executed");
21655            encoder.finish().expect("recording succeeded");
21656            let commands = recorder.commands();
21657            let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
21658                .iter()
21659                .filter_map(|command| match command {
21660                    Command::BindGraphicsPipeline(handle) => Some(*handle),
21661                    _ => None,
21662                })
21663                .collect();
21664            seen = commands.len();
21665            bound
21666        };
21667
21668        let filled = renderer.mesh_pipeline.single;
21669        let off = pipelines_in_a_frame(&mut renderer, &mut pool);
21670        assert!(
21671            off.contains(&filled),
21672            "a frame nobody asked has to bind the filled pipeline: {off:?}",
21673        );
21674        assert!(!renderer.wireframe());
21675        assert!(
21676            renderer.wireframe_pipeline.is_none(),
21677            "the wireframe pipeline must not be built until it is asked for",
21678        );
21679
21680        renderer
21681            .set_wireframe(device, true)
21682            .expect("a device with the line fill mode builds it");
21683        assert!(renderer.wireframe());
21684        let lines = renderer
21685            .wireframe_pipeline
21686            .expect("switching on is what builds it")
21687            .single;
21688        let on = pipelines_in_a_frame(&mut renderer, &mut pool);
21689        assert!(
21690            !on.contains(&filled),
21691            "the colour pass still bound the filled pipeline: {on:?}",
21692        );
21693        assert_eq!(
21694            on.iter().filter(|handle| **handle == lines).count(),
21695            1,
21696            "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
21697        );
21698        let substituted: Vec<GraphicsPipelineHandle> = on
21699            .iter()
21700            .map(|handle| if *handle == lines { filled } else { *handle })
21701            .collect();
21702        assert_eq!(
21703            substituted, off,
21704            "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
21705             {off:?}",
21706        );
21707
21708        renderer
21709            .set_wireframe(device, false)
21710            .expect("switching off builds nothing");
21711        assert!(!renderer.wireframe());
21712        assert_eq!(
21713            pipelines_in_a_frame(&mut renderer, &mut pool),
21714            off,
21715            "switching the view off has to put the filled pipeline back, not just stop reporting \
21716             it",
21717        );
21718
21719        renderer.destroy(device);
21720        pool.destroy(device);
21721        device.destroy_image_view(imported.view);
21722        device.destroy_image(imported.image);
21723        recorder.assert_valid();
21724    }
21725
21726    /// **The colour pass tests against the prepass's depth instead of clearing
21727    /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
21728    /// does the opposite, because lines do not reproduce a filled prepass.
21729    ///
21730    /// Both halves have to hold together or the frame is wrong in one of two
21731    /// ways, so both are asserted here. The attachment alone read-only while the
21732    /// pipeline still wrote would be a pipeline writing to a read-only
21733    /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
21734    /// this pass had just *cleared* would reject every fragment and draw a black
21735    /// frame. Neither shows up as an error — the first is a validation message
21736    /// on one backend and undefined behaviour on the rest, the second is a
21737    /// picture — which is why the observable is read off the compiled graph and
21738    /// off the pipeline state rather than off a screenshot.
21739    #[test]
21740    fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
21741        let (recorder, device, queue) =
21742            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21743        let device = device.as_ref();
21744        let mut renderer =
21745            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21746        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21747        let imported = swapchain_image(device);
21748        let mut pool = crate::TransientPool::new();
21749
21750        // Each pass's depth attachment, off the graph's own dump: the label it
21751        // was declared under, and the `load`/`store`/`write` triple the backend
21752        // is handed. A pass with no depth attachment contributes nothing, which
21753        // is what makes the lookup below a search rather than an index.
21754        let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
21755            renderer
21756                .begin_frame(
21757                    device,
21758                    &Camera::default(),
21759                    &DirectionalLight::default(),
21760                    (64, 48),
21761                )
21762                .expect("write");
21763            let mut graph = crate::RenderGraph::new(queue);
21764            let target = graph.import_image("target", imported);
21765            renderer.add_passes(&mut graph, pool, target, (64, 48));
21766            let dump = graph.compile(pool).expect("a legal frame").dump();
21767            let mut pass = String::new();
21768            let mut found = None;
21769            for line in dump.lines() {
21770                if let Some(rest) = line.split(" pass \"").nth(1) {
21771                    pass = rest.trim_end_matches('"').to_string();
21772                    if let Some((name, _)) = pass.split_once('"') {
21773                        pass = name.to_string();
21774                    }
21775                }
21776                if pass == label
21777                    && let Some(at) = line.find("depth load=")
21778                {
21779                    // Without the slot note the dump appends: which physical
21780                    // image the transient landed on is aliasing's business, not
21781                    // this assertion's.
21782                    let role = &line[at..];
21783                    let role = role.split_once(" [").map_or(role, |(head, _)| head);
21784                    found = Some(role.trim().to_string());
21785                }
21786            }
21787            found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21788        };
21789
21790        assert_eq!(
21791            depth_of(&mut renderer, &mut pool, "depth-prepass"),
21792            "depth load=Clear store=Store write=yes",
21793            "the prepass is what puts the depth there, so it clears, writes and keeps it",
21794        );
21795        assert_eq!(
21796            depth_of(&mut renderer, &mut pool, "forward"),
21797            "depth load=Load store=Store write=no",
21798            "and the colour pass reads it: a clear here would throw away the prepass and \
21799             pay for the overdraw again, and a write would be a second pass writing the \
21800             same values",
21801        );
21802        assert_eq!(
21803            MeshModules::color_depth_stencil(PolygonMode::Fill),
21804            Some(DepthStencilState {
21805                format: Format::D32Float,
21806                depth_write: false,
21807                depth_compare: CompareOp::GreaterOrEqual,
21808                stencil: None,
21809                bias: DepthBias::default(),
21810            }),
21811            "and the pipeline agrees with the attachment: equality against the prepass, \
21812             reachable only through the `OrEqual` under reversed-Z",
21813        );
21814
21815        renderer
21816            .set_wireframe(device, true)
21817            .expect("this device was asked for the line fill mode");
21818        assert_eq!(
21819            depth_of(&mut renderer, &mut pool, "forward"),
21820            "depth load=Clear store=Store write=yes",
21821            "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21822             along the edge rather than across the face, so testing it against a filled \
21823             prepass rejects most of the wireframe — and *loading* that depth under the \
21824             writing default's `Greater` would reject all of it",
21825        );
21826        assert_eq!(
21827            MeshModules::color_depth_stencil(PolygonMode::Line),
21828            MeshModules::depth_stencil(),
21829            "which is the writing default, the same state the depth-only twin uses",
21830        );
21831
21832        renderer.destroy(device);
21833        pool.destroy(device);
21834        device.destroy_image_view(imported.view);
21835        device.destroy_image(imported.image);
21836        recorder.assert_valid();
21837    }
21838
21839    /// **A device with no line fill mode is refused, not quietly filled.**
21840    ///
21841    /// The failure this rules out is the silent one: a caller who binds a key to
21842    /// this, presses it, and gets the solid frame back with nothing anywhere
21843    /// saying why — which on a model whose silhouette hides its interior is
21844    /// indistinguishable from a wireframe that worked. WebGPU is the real device
21845    /// this happens on; `open`'s null device stands in for it, because
21846    /// [`DeviceDesc::for_adapter`] asks for
21847    /// [`Features::GPU_DRIVEN`] and nothing else.
21848    #[test]
21849    fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21850        let (recorder, device, queue) = open();
21851        let device = device.as_ref();
21852        assert!(
21853            !ForwardRenderer::supports_wireframe(device),
21854            "this device was not asked for the line fill mode, so it must not report it",
21855        );
21856        let mut renderer =
21857            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21858
21859        let refused = renderer
21860            .set_wireframe(device, true)
21861            .expect_err("a device without the feature has to say so");
21862        assert!(
21863            matches!(
21864                refused,
21865                HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21866            ),
21867            "the refusal has to name the feature to go and look up, and is {refused:?}",
21868        );
21869        assert!(
21870            !renderer.wireframe(),
21871            "a refused request must leave the view off rather than half on",
21872        );
21873        assert!(
21874            renderer.wireframe_pipeline.is_none(),
21875            "nothing may be left behind by a refusal",
21876        );
21877        // And switching *off* is still fine on such a device: it builds nothing.
21878        renderer
21879            .set_wireframe(device, false)
21880            .expect("switching off asks the device for nothing");
21881
21882        renderer.destroy(device);
21883        recorder.assert_valid();
21884    }
21885
21886    /// The grid's own full-screen triangle is counted as submitted, and only
21887    /// while it is on.
21888    ///
21889    /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21890    /// row, and every full-screen pass in the frame contributes one — so a grid
21891    /// that drew and was not counted makes that row disagree with the frame by
21892    /// exactly one triangle, silently.
21893    #[test]
21894    fn the_grids_triangle_is_counted_only_while_it_is_on() {
21895        let _blurs = ssao_blur_switch();
21896        let (recorder, device, queue) = open();
21897        let device = device.as_ref();
21898        let mut renderer =
21899            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21900        let imported = swapchain_image(device);
21901        let mut pool = crate::TransientPool::new();
21902
21903        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21904        let off = renderer.counters();
21905
21906        renderer
21907            .set_ground_grid(device, Some(GridStyle::default()))
21908            .expect("the null backend builds every pipeline");
21909        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21910        let on = renderer.counters();
21911
21912        assert_eq!(
21913            on.draws - off.draws,
21914            FULLSCREEN_DRAWS,
21915            "the grid records exactly one draw"
21916        );
21917        assert_eq!(
21918            on.instances - off.instances,
21919            FULLSCREEN_DRAWS,
21920            "and exactly one submitted instance"
21921        );
21922
21923        renderer.destroy(device);
21924        pool.destroy(device);
21925        device.destroy_image_view(imported.view);
21926        device.destroy_image(imported.image);
21927        recorder.assert_valid();
21928    }
21929
21930    /// One frame on a device of its own, under an override switching `off`.
21931    ///
21932    /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21933    /// device's whole life: asking "did the atlas pass draw" of a recorder that
21934    /// has seen two frames answers about both of them, and the arm that matters
21935    /// most here is the one whose answer must be zero.
21936    ///
21937    /// Returns what the frame reported and what its atlas pass actually drew.
21938    fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21939        use crcbl_hal::null::Command;
21940
21941        let recorder = Recorder::new();
21942        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21943        let adapter = instance.adapters().remove(0);
21944        let opened = instance
21945            .create_device(&DeviceDesc::for_adapter(adapter.id))
21946            .expect("the null backend always opens");
21947        let device = opened.as_ref();
21948        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21949        let mut renderer =
21950            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21951        // A shadowed light beside the cascades, so the atlas pass has draws to
21952        // lose rather than being empty either way.
21953        renderer.set_lights(&[shadowable_spot(-1.0)]);
21954        // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21955        // camera stack leaves both of them out — see
21956        // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21957        // default alone would be measuring three effects and calling it five,
21958        // and their arms below would be switching off something already off.
21959        // `force` clears the other side, so an arm whose `off` is one of them
21960        // still resolves to off.
21961        renderer.set_effect_request(EffectRequest {
21962            programmatic: EffectOverride::none()
21963                .force(OUTSIDE_THE_DEFAULT, Some(true))
21964                .force(off, Some(false)),
21965            ..EffectRequest::default()
21966        });
21967
21968        let recorded = frame(device, &mut renderer, queue);
21969        assert_eq!(
21970            renderer.effects(),
21971            RenderEffects::all().difference(off),
21972            "the frame must have resolved to the set the request asked for"
21973        );
21974        let counters = renderer.counters();
21975        let instances = renderer.instances.len() as u64;
21976        let atlas_draws = commands_in_pass(&recorder, "shadow")
21977            .into_iter()
21978            .filter(|command| {
21979                matches!(
21980                    command,
21981                    Command::DrawIndexedIndirect(_)
21982                        | Command::DrawIndexedIndirectCount(_)
21983                        | Command::DrawMeshTasksIndirect(_)
21984                )
21985            })
21986            .count();
21987        assert_eq!(
21988            counters.draws,
21989            recorded_draws(&recorder) as u64,
21990            "the counter and the frame's own recorded stream must agree, whatever is switched off"
21991        );
21992        recorded.finish(device, renderer);
21993        recorder.assert_valid();
21994        (counters, instances, atlas_draws)
21995    }
21996
21997    /// **A switched-off effect is work the frame did not record**, and a frame
21998    /// that still executes with the placeholder bound in place of what it lost.
21999    ///
22000    /// The other half of the pass-list test above, and the half a pass list
22001    /// cannot make: the `shadow` pass is still *there* with shadows off, so the
22002    /// question is whether it drew. That answer comes off the recorded command
22003    /// stream, which is a different instrument from `recorded_draws` — the number
22004    /// under test.
22005    ///
22006    /// Executed rather than only compiled, because the occlusion switch changes
22007    /// which image the forward pass has bound. A frame that declared a read of a
22008    /// transient it never created, or bound a view the graph never realised,
22009    /// fails here and compiles perfectly.
22010    #[test]
22011    fn a_switched_off_effect_is_work_the_frame_did_not_record() {
22012        let _blurs = ssao_blur_switch();
22013        let _seam = ssao_split_switch();
22014        let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
22015        assert!(
22016            atlas_draws > 0,
22017            "with shadows on the atlas pass has to draw something, or turning it off means \
22018             nothing"
22019        );
22020        assert_eq!(
22021            control.instances,
22022            instances
22023                + fullscreen_passes(
22024                    RenderEffects::all(),
22025                    TEST_EXTENT,
22026                    false,
22027                    crate::ssao::blur_passes(),
22028                ) * FULLSCREEN_DRAWS,
22029            "the control frame submits one triangle per full-screen pass"
22030        );
22031
22032        // Each pair is one full-screen triangle per pass, and the atlas is
22033        // untouched by either.
22034        for (off, fewer) in [
22035            (
22036                RenderEffects::AMBIENT_OCCLUSION,
22037                u64::from(Ssao::passes(crate::ssao::blur_passes())),
22038            ),
22039            // The contact march's one pass, and a constant rather than a
22040            // function of anything: it has no blur behind it and no chain.
22041            (
22042                RenderEffects::CONTACT_SHADOWS,
22043                u64::from(ContactShadows::PASSES),
22044            ),
22045            // The march's two passes and the reductions that feed them, which
22046            // is what makes this arm's number a function of the extent the way
22047            // the chain's below is.
22048            (
22049                RenderEffects::REFLECTIONS,
22050                u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
22051            ),
22052            // Not a constant, unlike the occlusion pair above: the chain's
22053            // length is a function of the extent, and this is what it is at
22054            // `TEST_EXTENT`.
22055            (
22056                RenderEffects::BLOOM,
22057                u64::from(Bloom::passes_for(TEST_EXTENT)),
22058            ),
22059        ] {
22060            let (counters, instances, atlas) = frame_switching_off(off);
22061            assert_eq!(
22062                counters.draws,
22063                control.draws - fewer * FULLSCREEN_DRAWS,
22064                "{off:?}: the frame must record one draw fewer per pass it did not add"
22065            );
22066            assert_eq!(
22067                counters.instances,
22068                instances
22069                    + fullscreen_passes(
22070                        RenderEffects::all().difference(off),
22071                        TEST_EXTENT,
22072                        false,
22073                        crate::ssao::blur_passes(),
22074                    ) * FULLSCREEN_DRAWS,
22075                "{off:?}: and must not report as submitted a triangle it never submitted"
22076            );
22077            assert_eq!(
22078                atlas, atlas_draws,
22079                "{off:?}: a screen-space effect must not touch the shadow atlas"
22080            );
22081        }
22082
22083        // Shadows: the atlas pass survives and draws nothing at all, which is
22084        // the mechanism — a cleared reversed-Z atlas reads as fully lit.
22085        let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
22086        assert_eq!(
22087            atlas, 0,
22088            "with shadows off the atlas pass must record its clear and no draw"
22089        );
22090        assert_eq!(
22091            counters.draws,
22092            control.draws - atlas_draws as u64,
22093            "and the frame must record exactly the atlas pass's draws fewer"
22094        );
22095    }
22096
22097    /// **Every pass the frame records gets a row in the report, except the ones
22098    /// that open no scope.**
22099    ///
22100    /// The observable the bound exists for: the samples' hand-picked capacity
22101    /// timed the first eight passes of a fourteen-pass frame and reported eight
22102    /// rows, which reads exactly like a frame that has eight passes. Sized from
22103    /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
22104    /// pass the graph compiled, in order — so a bound one short of the frame
22105    /// makes this list short too.
22106    ///
22107    /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
22108    /// expectation rather than expected to be missing by accident. The seam
22109    /// takes a timestamp only where a pass opens and closes and a copy opens
22110    /// nothing, so `PassTimers` gives it no query pair and no row — a row
22111    /// reading 0.000 ms would be a measurement nobody made.
22112    #[test]
22113    fn every_pass_of_the_frame_gets_a_timing_row() {
22114        let _blurs = ssao_blur_switch();
22115        // And the comparison seam, so the frame this checks carries the
22116        // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
22117        // for a *per-technique* cost, and what makes that true is this test's
22118        // own claim — every pass that opens a scope gets a row — applied to a
22119        // frame that compares. See `crate::ssao`'s `r_ssao_split`.
22120        let split = ssao_split_switch();
22121        split.set(0.5);
22122        let recorder = Recorder::new();
22123        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
22124        let adapter = instance.adapters().remove(0);
22125        // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
22126        // may lack it — so a device that wants timers has to ask for it, and
22127        // `open` above, which uses `DeviceDesc::for_adapter`, does not.
22128        let opened = instance
22129            .create_device(&DeviceDesc {
22130                label: Some("timed frame"),
22131                adapter: adapter.id,
22132                required_features: Features::GPU_DRIVEN,
22133                optional_features: Features::TIMESTAMP_QUERY,
22134                compatible_surface: None,
22135            })
22136            .expect("the null backend always opens");
22137        let queue = opened.queue(QueueKind::Graphics).expect("always present");
22138        let device = opened.as_ref();
22139        let mut renderer =
22140            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
22141        renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
22142        let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
22143            .expect("the tier A null adapter has timestamp queries");
22144        let imported = swapchain_image(device);
22145        let mut pool = crate::TransientPool::new();
22146        let mut recorded = Vec::new();
22147        let mut compiled_labels = Vec::new();
22148
22149        // The ring is one slot longer than the frames in flight and resolves a
22150        // slot only when it comes round again, so the first frame's report is
22151        // that many frames behind it — see the [`timing`](crate::timing) docs.
22152        for _ in 0..FRAMES_IN_FLIGHT + 2 {
22153            renderer
22154                .begin_frame(
22155                    device,
22156                    &Camera::default(),
22157                    &DirectionalLight::default(),
22158                    (64, 48),
22159                )
22160                .expect("write");
22161            let mut graph = crate::RenderGraph::new(queue);
22162            let target = graph.import_image("target", imported);
22163            renderer.add_passes(&mut graph, &pool, target, (64, 48));
22164            let compiled = graph.compile(&pool).expect("a legal frame");
22165            if compiled_labels.is_empty() {
22166                compiled_labels = compiled
22167                    .passes()
22168                    .iter()
22169                    .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
22170                    .map(|pass| pass.label().to_string())
22171                    .collect();
22172            }
22173            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22174                label: Some("timed frame"),
22175                queue,
22176            });
22177            compiled
22178                .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
22179                .expect("the graph executed");
22180            recorded.push(encoder.finish().expect("recording succeeded"));
22181        }
22182
22183        let reported: Vec<&str> = timers
22184            .latest()
22185            .passes
22186            .iter()
22187            .map(|timing| timing.label.as_str())
22188            .collect();
22189        // Anti-vacuity for the seam held above: a frame that did not compare
22190        // would satisfy the equality below and say nothing about a
22191        // per-technique cost, because there would be one technique in it.
22192        for label in ["ssao", "ssao-shipped"] {
22193            assert!(
22194                compiled_labels.iter().any(|pass| pass == label),
22195                "the frame compiled no `{label}` pass, so the seam did not reach it and this \
22196                 test says nothing about a comparison having a cost per side. Its passes: \
22197                 {compiled_labels:?}"
22198            );
22199        }
22200        assert_eq!(
22201            reported,
22202            compiled_labels,
22203            "the report must name every pass the frame compiled that opens a scope, in order \
22204             — {} of {} timed with a capacity of {}",
22205            reported.len(),
22206            compiled_labels.len(),
22207            timers.capacity()
22208        );
22209
22210        timers.destroy(device);
22211        renderer.destroy(device);
22212        for commands in recorded {
22213            device.destroy_command_buffer(commands);
22214        }
22215        pool.destroy(device);
22216        device.destroy_image_view(imported.view);
22217        device.destroy_image(imported.image);
22218        recorder.assert_valid();
22219    }
22220
22221    /// One mesh-table entry, decoded from the bytes that reached the device.
22222    fn mesh_entry(
22223        recorder: &Recorder,
22224        renderer: &ForwardRenderer,
22225        id: u32,
22226    ) -> crcbl_shaders::mesh::GpuMesh {
22227        let table = recorder
22228            .buffer_bytes(renderer.pool.table_buffer())
22229            .expect("the table is live");
22230        let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
22231        crcbl_shaders::mesh::GpuMesh::from_bytes(
22232            table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
22233                .try_into()
22234                .expect("one whole entry"),
22235        )
22236    }
22237
22238    // --- skinning: the seam a caller draws a skinned mesh through -----------
22239
22240    /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
22241    /// [`Skinning`] built against that renderer's own vertex pool.
22242    struct SkinnedFixture {
22243        renderer: ForwardRenderer,
22244        skinning: Skinning,
22245        skinned: SkinnedMesh,
22246        palette: Vec<Mat4>,
22247        bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
22248    }
22249
22250    impl SkinnedFixture {
22251        fn build(device: &dyn Device, queue: QueueHandle) -> Self {
22252            Self::build_with_scene(device, queue, &scene::demo())
22253        }
22254
22255        /// [`SkinnedFixture::build`] over `scene` in place of
22256        /// [`scene::demo`], which must hold [`DEMO_CUBE`].
22257        fn build_with_scene(
22258            device: &dyn Device,
22259            queue: QueueHandle,
22260            scene: &SceneDesc<'_>,
22261        ) -> Self {
22262            let mut renderer =
22263                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
22264                    .expect("the null backend accepts every descriptor");
22265            let skinned = renderer
22266                .reserve_skinned(DEMO_CUBE)
22267                .expect("a default pool has room for two halves of a cube");
22268            let skinning = Skinning::new(
22269                device,
22270                &crate::skinning::SkinningDesc {
22271                    label: Some("skinned fixture"),
22272                    frames: FRAMES_IN_FLIGHT,
22273                    ranges: 1,
22274                    joints: 1,
22275                    bindings: skinned.vertex_count(),
22276                    // The renderer's own pool, which is the whole of what makes
22277                    // the dispatch's output reachable by its draws.
22278                    vertices: renderer.vertex_buffer(),
22279                    attribute_base: renderer.attribute_base(),
22280                },
22281            )
22282            .expect("the null backend accepts every descriptor");
22283            let bindings = vec![
22284                crcbl_shaders::skinning::SkinBinding {
22285                    joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
22286                    weights: [1.0, 0.0, 0.0, 0.0],
22287                };
22288                skinned.vertex_count() as usize
22289            ];
22290            Self {
22291                renderer,
22292                skinning,
22293                skinned,
22294                palette: vec![Mat4::IDENTITY],
22295                bindings,
22296            }
22297        }
22298
22299        /// One skinned frame's `begin_skinned_frame`, with this fixture's single
22300        /// range.
22301        fn begin(&mut self, device: &dyn Device) {
22302            let range = self.skinned.skin_range(&self.palette, &self.bindings);
22303            self.renderer
22304                .begin_skinned_frame(
22305                    device,
22306                    &mut self.skinning,
22307                    &[range],
22308                    &Camera::default(),
22309                    &DirectionalLight::default(),
22310                    TEST_EXTENT,
22311                )
22312                .expect("a legal skinning plan");
22313        }
22314
22315        fn destroy(mut self, device: &dyn Device) {
22316            self.renderer.release_skinned(self.skinned);
22317            self.skinning.destroy(device);
22318            self.renderer.destroy(device);
22319        }
22320    }
22321
22322    /// How many times the host wrote the mesh-table entry `id` names.
22323    fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
22324        let table = renderer.pool.table_buffer();
22325        let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
22326        recorder
22327            .events()
22328            .into_iter()
22329            .filter(|event| {
22330                matches!(
22331                    event,
22332                    crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
22333                        if *buffer == table && *offset == at
22334                )
22335            })
22336            .count()
22337    }
22338
22339    /// The record `handle` names, out of the ring buffer **this frame draws
22340    /// from** rather than out of the pool's host mirror.
22341    ///
22342    /// A mirror and a buffer that disagree is exactly the defect a re-pointing
22343    /// design can have, so every claim about a skinned instance's bases is read
22344    /// off the bytes a shader would.
22345    fn instance_record(
22346        recorder: &Recorder,
22347        renderer: &ForwardRenderer,
22348        handle: InstanceHandle,
22349    ) -> mesh::GpuInstance {
22350        let buffer = renderer.instances.buffers()[renderer.frame()];
22351        let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
22352        let index = renderer
22353            .instances
22354            .index(handle)
22355            .expect("the object is live") as usize;
22356        let at = index * mesh::INSTANCE_STRIDE;
22357        mesh::GpuInstance::from_bytes(
22358            bytes[at..at + mesh::INSTANCE_STRIDE]
22359                .try_into()
22360                .expect("one whole instance"),
22361        )
22362    }
22363
22364    /// **A skinned primitive takes no mesh-table entry of its own, and nothing
22365    /// rewrites the one it draws through.**
22366    ///
22367    /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
22368    /// precisely because nothing rewrites an entry between frames, so a design
22369    /// that re-pointed an entry at the half a frame writes would be wrong only
22370    /// on the frames that overlap — which is to say invisibly. What alternates
22371    /// instead is a field of the *instance*, and instances go through a ring.
22372    ///
22373    /// So a skinned object draws through the source mesh's own entry: the same
22374    /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
22375    /// carrying the bind pose's base vertex, still written exactly once after
22376    /// four skinned frames. That shared entry is also what lets one mesh be
22377    /// drawn skinned and unskinned in the same frame.
22378    #[test]
22379    fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
22380        let (recorder, device, queue) = open();
22381        let device = device.as_ref();
22382        let mut fixture = SkinnedFixture::build(device, queue);
22383
22384        let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
22385        assert_eq!(
22386            fixture.skinned.mesh_id(),
22387            bind_pose_id,
22388            "a skinned instance names the mesh it was deformed from, so the bucket, the level \
22389             tables and the bounding box all resolve as the bind pose's"
22390        );
22391
22392        let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
22393        assert_eq!(
22394            bind_pose.base_vertex,
22395            fixture.skinned.input_base(),
22396            "the entry goes on naming the bind pose the dispatch reads, not either half it \
22397             writes"
22398        );
22399        for parity in 0..2 {
22400            assert_ne!(
22401                fixture.skinned.region().base(parity),
22402                bind_pose.base_vertex,
22403                "half {parity} must not be the bind pose, which the kernel reads while it \
22404                 writes them"
22405            );
22406        }
22407        assert_ne!(
22408            fixture.skinned.region().base(0),
22409            fixture.skinned.region().base(1),
22410            "the two halves are separate reservations, or the ping-pong is one buffer"
22411        );
22412
22413        // Counted before the frames rather than compared against a literal:
22414        // `MeshPool::new` clears the whole table with one write at offset zero,
22415        // which lands on this entry too, so the number here is the pool's
22416        // start-up and not this test's business. What the loop below has to
22417        // leave alone is whatever it is.
22418        let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
22419        assert!(
22420            writes_before > 0,
22421            "the entry was written at least once before any frame ran, or the counter below \
22422             is counting nothing and the comparison after the frames is vacuous"
22423        );
22424
22425        // Four frames, which is two of each parity: enough that a design
22426        // rewriting an entry per frame would have written four more times.
22427        let imported = swapchain_image_at(device, TEST_EXTENT);
22428        let mut pool = crate::TransientPool::new();
22429        for _ in 0..4 {
22430            fixture.begin(device);
22431            let mut graph = crate::RenderGraph::new(queue);
22432            let target = graph.import_image("target", imported);
22433            fixture.renderer.add_skinned_passes(
22434                &mut graph,
22435                &pool,
22436                target,
22437                TEST_EXTENT,
22438                &fixture.skinning,
22439            );
22440            graph.compile(&pool).expect("a legal frame");
22441        }
22442
22443        assert_eq!(
22444            table_writes(&recorder, &fixture.renderer, bind_pose_id),
22445            writes_before,
22446            "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
22447             table is one buffer rather than a ring is that nothing rewrites an entry between \
22448             frames"
22449        );
22450
22451        fixture.destroy(device);
22452        pool.destroy(device);
22453        device.destroy_image_view(imported.view);
22454        device.destroy_image(imported.image);
22455        recorder.assert_valid();
22456    }
22457
22458    /// **A skinned object's recorded base vertex follows the parity of the frame
22459    /// it is drawn in**, and it carries the bit that makes a shader read it.
22460    ///
22461    /// The other half of the design: the table entry never moves, so what has to
22462    /// alternate is a field of the *instance* — and it has to alternate in the
22463    /// buffer the frame actually draws from, which is why this reads the
22464    /// instance ring's bytes rather than the host's mirror.
22465    ///
22466    /// Three claims, and the last two are what stop the first being vacuous. The
22467    /// base must be the one this frame's parity names; the record must carry
22468    /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
22469    /// without which the raster stages read the mesh entry and the field is
22470    /// decoration; and two consecutive frames must have named **different**
22471    /// halves, without which a renderer ignoring the parity entirely would pass.
22472    #[test]
22473    fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
22474        let (recorder, device, queue) = open();
22475        let device = device.as_ref();
22476        let mut fixture = SkinnedFixture::build(device, queue);
22477        let handle = fixture
22478            .renderer
22479            .add_skinned_instance(&SkinnedInstanceDesc {
22480                mesh: &fixture.skinned,
22481                material: DEMO_UNTINTED,
22482                transform: Mat4::IDENTITY,
22483                bounds: None,
22484            })
22485            .expect("a pool of thousands has room for one object");
22486
22487        let mut carried = Vec::new();
22488        for _ in 0..2 {
22489            fixture.begin(device);
22490            let parity = fixture.skinning.parity();
22491            let instance = instance_record(&recorder, &fixture.renderer, handle);
22492            assert_eq!(
22493                instance.base_vertex,
22494                fixture.skinned.region().base(parity),
22495                "the buffer this frame draws from must carry the base parity {parity} writes"
22496            );
22497            assert_eq!(
22498                instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
22499                mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
22500                "without the bit the raster stages resolve the mesh entry's base and this \
22501                 field is never read"
22502            );
22503            assert_eq!(
22504                instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
22505                "and the record still names the source mesh, which is what its bucket, its \
22506                 levels and its bounding box resolve through"
22507            );
22508            carried.push(instance.base_vertex);
22509        }
22510        assert_ne!(
22511            carried[0], carried[1],
22512            "two consecutive frames must have drawn different halves, or a renderer that \
22513             ignored the parity entirely would pass this"
22514        );
22515
22516        fixture.destroy(device);
22517        recorder.assert_valid();
22518    }
22519
22520    /// **A skinned object's own box reaches the buffer a frame draws from, and
22521    /// [`ForwardRenderer::set_skinned_bounds`] moves it without moving the
22522    /// object.**
22523    ///
22524    /// Read out of the instance ring rather than the host mirror, and put to
22525    /// [`crate::cull::visible_instances`] — the CPU reference the device's cull
22526    /// is held to — so what is asserted is that reference's decision on the
22527    /// bytes a frame uploads: kept while the box is around the origin the
22528    /// camera looks at, culled once the setter moves it thirty metres away,
22529    /// and kept again — in every cull, as a boxless skinned object always is —
22530    /// once the setter takes the box away.
22531    ///
22532    /// **And the box is not a move.** The object is moved a metre first, and
22533    /// the box set after the move and before the frame: the record must still
22534    /// say it travelled from where it was, which a box written through
22535    /// [`InstancePool::set`] would overwrite with the transform it already
22536    /// carries.
22537    #[test]
22538    fn a_skinned_box_is_carried_and_moved_without_a_move() {
22539        let (recorder, device, queue) = open();
22540        let device = device.as_ref();
22541        let mut fixture = SkinnedFixture::build(device, queue);
22542        let near = Aabb {
22543            min: Vec3::splat(-0.5),
22544            max: Vec3::splat(0.5),
22545        };
22546        let handle = fixture
22547            .renderer
22548            .add_skinned_instance(&SkinnedInstanceDesc {
22549                mesh: &fixture.skinned,
22550                material: DEMO_UNTINTED,
22551                transform: Mat4::IDENTITY,
22552                bounds: Some(near),
22553            })
22554            .expect("a pool of thousands has room for one object");
22555        let frustum = Frustum::from_view_projection(Camera::default().view_projection(1.0));
22556        let meshes = fixture.renderer.pool.table_entries();
22557        let kept = |record: mesh::GpuInstance| {
22558            !crate::cull::visible_instances(&frustum, &[record], &meshes, 0).is_empty()
22559        };
22560
22561        fixture.begin(device);
22562        let first = instance_record(&recorder, &fixture.renderer, handle);
22563        assert_ne!(first.flags & mesh::GpuInstance::OWNS_BOUNDS, 0);
22564        assert_eq!(
22565            (first.bounds_min, first.bounds_max),
22566            (near.min.to_array(), near.max.to_array())
22567        );
22568        assert!(kept(first), "a box around the origin is in view");
22569
22570        let stepped = Mat4::from_translation(Vec3::X);
22571        fixture.renderer.set_skinned_instance(
22572            handle,
22573            &SkinnedInstanceDesc {
22574                mesh: &fixture.skinned,
22575                material: DEMO_UNTINTED,
22576                transform: stepped,
22577                bounds: Some(near),
22578            },
22579        );
22580        let far = Aabb {
22581            min: Vec3::new(29.5, -0.5, -0.5),
22582            max: Vec3::new(30.5, 0.5, 0.5),
22583        };
22584        fixture
22585            .renderer
22586            .set_skinned_bounds(handle, Some(far))
22587            .expect("a finite, ordered box");
22588        fixture.begin(device);
22589        let moved = instance_record(&recorder, &fixture.renderer, handle);
22590        assert_eq!(
22591            (moved.bounds_min, moved.bounds_max),
22592            (far.min.to_array(), far.max.to_array())
22593        );
22594        assert!(
22595            !kept(moved),
22596            "the moved box is off screen, so the object is culled"
22597        );
22598        assert_eq!(moved.transform, stepped.to_cols_array());
22599        assert_eq!(
22600            moved.previous_transform, first.transform,
22601            "the box was set after the move, and the record must still say where the \
22602             object moved from"
22603        );
22604        assert_ne!(
22605            moved.base_vertex, first.base_vertex,
22606            "the frame still re-pointed the object, and the box survived it"
22607        );
22608
22609        fixture
22610            .renderer
22611            .set_skinned_bounds(handle, None)
22612            .expect("no box is always accepted");
22613        fixture.begin(device);
22614        let cleared = instance_record(&recorder, &fixture.renderer, handle);
22615        assert_eq!(cleared.flags & mesh::GpuInstance::OWNS_BOUNDS, 0);
22616        assert!(
22617            kept(cleared),
22618            "without a box the object is in every cull again"
22619        );
22620
22621        fixture.destroy(device);
22622        recorder.assert_valid();
22623    }
22624
22625    /// **A replace takes its description's box**: a box
22626    /// [`ForwardRenderer::set_skinned_bounds`] wrote is gone after a
22627    /// [`ForwardRenderer::set_skinned_instance`] whose description says
22628    /// `None`, and replaced by the description's when it says `Some`. The
22629    /// description is authoritative, which is what a caller placing an object
22630    /// every frame has to know — see `set_skinned_instance`'s docs.
22631    #[test]
22632    fn a_skinned_replace_takes_its_descriptions_box() {
22633        let (recorder, device, queue) = open();
22634        let device = device.as_ref();
22635        let mut fixture = SkinnedFixture::build(device, queue);
22636        let desc = |bounds| SkinnedInstanceDesc {
22637            mesh: &fixture.skinned,
22638            material: DEMO_UNTINTED,
22639            transform: Mat4::IDENTITY,
22640            bounds,
22641        };
22642        let handle = fixture
22643            .renderer
22644            .add_skinned_instance(&desc(None))
22645            .expect("a pool of thousands has room for one object");
22646        let set = Aabb {
22647            min: Vec3::splat(-2.0),
22648            max: Vec3::splat(2.0),
22649        };
22650        let given = Aabb {
22651            min: Vec3::splat(-1.0),
22652            max: Vec3::splat(1.0),
22653        };
22654        let record = |renderer: &ForwardRenderer| {
22655            renderer.instances.get(handle).expect("the object is live")
22656        };
22657
22658        fixture
22659            .renderer
22660            .set_skinned_bounds(handle, Some(set))
22661            .expect("a finite, ordered box");
22662        assert_ne!(
22663            record(&fixture.renderer).flags & mesh::GpuInstance::OWNS_BOUNDS,
22664            0
22665        );
22666        fixture.renderer.set_skinned_instance(handle, &desc(None));
22667        assert_eq!(
22668            record(&fixture.renderer).flags & mesh::GpuInstance::OWNS_BOUNDS,
22669            0,
22670            "a description with no box takes the set box away"
22671        );
22672
22673        fixture
22674            .renderer
22675            .set_skinned_bounds(handle, Some(set))
22676            .expect("a finite, ordered box");
22677        fixture
22678            .renderer
22679            .set_skinned_instance(handle, &desc(Some(given)));
22680        let replaced = record(&fixture.renderer);
22681        assert_ne!(replaced.flags & mesh::GpuInstance::OWNS_BOUNDS, 0);
22682        assert_eq!(
22683            (replaced.bounds_min, replaced.bounds_max),
22684            (given.min.to_array(), given.max.to_array()),
22685            "a description with a box replaces the set one with its own"
22686        );
22687
22688        fixture.begin(device);
22689        fixture.destroy(device);
22690        recorder.assert_valid();
22691    }
22692
22693    /// **A box the culls could not read is refused at the boundary**: an
22694    /// inverted one and one with a `NaN` or an infinite corner are
22695    /// [`InstancePoolError::InvalidBounds`] from
22696    /// [`ForwardRenderer::add_skinned_instance`] and from
22697    /// [`ForwardRenderer::set_skinned_bounds`], neither of which writes
22698    /// anything, and a panic naming the box from
22699    /// [`ForwardRenderer::set_skinned_instance`], which has no `Result` — while
22700    /// a degenerate box, a single point, is a box and is accepted.
22701    #[test]
22702    fn an_unusable_skinned_box_is_refused() {
22703        let (recorder, device, queue) = open();
22704        let device = device.as_ref();
22705        let mut fixture = SkinnedFixture::build(device, queue);
22706        let desc = |bounds| SkinnedInstanceDesc {
22707            mesh: &fixture.skinned,
22708            material: DEMO_UNTINTED,
22709            transform: Mat4::IDENTITY,
22710            bounds: Some(bounds),
22711        };
22712        let unusable = [
22713            Aabb {
22714                min: Vec3::new(1.0, -1.0, -1.0),
22715                max: Vec3::new(-1.0, 1.0, 1.0),
22716            },
22717            Aabb {
22718                min: Vec3::new(-1.0, f32::NAN, -1.0),
22719                max: Vec3::ONE,
22720            },
22721            Aabb {
22722                min: Vec3::splat(-1.0),
22723                max: Vec3::new(1.0, 1.0, f32::INFINITY),
22724            },
22725        ];
22726        let live = fixture.renderer.instances.live().len();
22727        for bounds in unusable {
22728            let refused = fixture.renderer.add_skinned_instance(&desc(bounds));
22729            assert!(
22730                matches!(refused, Err(InstancePoolError::InvalidBounds { .. })),
22731                "{bounds:?} was not refused by name: {refused:?}"
22732            );
22733        }
22734        assert_eq!(
22735            fixture.renderer.instances.live().len(),
22736            live,
22737            "a refused object takes no slot"
22738        );
22739
22740        let point = Aabb {
22741            min: Vec3::ONE,
22742            max: Vec3::ONE,
22743        };
22744        let handle = fixture
22745            .renderer
22746            .add_skinned_instance(&desc(point))
22747            .expect("a single point is a box");
22748        for bounds in unusable {
22749            let refused = fixture.renderer.set_skinned_bounds(handle, Some(bounds));
22750            assert!(
22751                matches!(refused, Err(InstancePoolError::InvalidBounds { .. })),
22752                "set_skinned_bounds did not refuse {bounds:?} by name: {refused:?}"
22753            );
22754            let skinned = &fixture.skinned;
22755            let renderer = &mut fixture.renderer;
22756            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
22757                renderer.set_skinned_instance(
22758                    handle,
22759                    &SkinnedInstanceDesc {
22760                        mesh: skinned,
22761                        material: DEMO_UNTINTED,
22762                        transform: Mat4::IDENTITY,
22763                        bounds: Some(bounds),
22764                    },
22765                );
22766            }));
22767            assert!(panicked.is_err(), "set_skinned_instance wrote {bounds:?}");
22768        }
22769        let kept = fixture
22770            .renderer
22771            .instances
22772            .get(handle)
22773            .expect("the object is live");
22774        assert_eq!(
22775            (kept.bounds_min, kept.bounds_max),
22776            (point.min.to_array(), point.max.to_array()),
22777            "a refused box leaves the one before it in place"
22778        );
22779
22780        fixture.begin(device);
22781        fixture.destroy(device);
22782        recorder.assert_valid();
22783    }
22784
22785    /// **A skinned object's record names the half the frame before it filled**,
22786    /// and it starts at rest.
22787    ///
22788    /// The other half of a skinned motion vector. The base above is where a
22789    /// fragment *is*; this is where it *was*, and without it the geometry stages
22790    /// put the previous transform through this frame's deformed vertex — so a
22791    /// limb that swung reports the motion of the body it hangs off. See
22792    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
22793    ///
22794    /// Four claims, and the first and last are what stop the middle two being a
22795    /// restatement of the parity:
22796    ///
22797    /// * the **first** frame of a fresh object writes the base it draws out of,
22798    ///   because the other half holds whatever its reservation came with and a
22799    ///   motion vector against undefined vertices is worse than no motion;
22800    /// * the frames after it write
22801    ///   [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
22802    ///   which must also **differ** from the base they draw out of — a renderer
22803    ///   that wrote the current base into both lanes would satisfy every "it is
22804    ///   a legal base" reading of this and leave every skinned instance at rest;
22805    /// * and moving the object onto a **different region** puts it back at rest
22806    ///   for one frame, because the halves it now names are two runs it has
22807    ///   never been drawn out of.
22808    #[test]
22809    fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
22810        let (recorder, device, queue) = open();
22811        let device = device.as_ref();
22812        let mut fixture = SkinnedFixture::build(device, queue);
22813        let handle = fixture
22814            .renderer
22815            .add_skinned_instance(&SkinnedInstanceDesc {
22816                mesh: &fixture.skinned,
22817                material: DEMO_UNTINTED,
22818                transform: Mat4::IDENTITY,
22819                bounds: None,
22820            })
22821            .expect("a pool of thousands has room for one object");
22822
22823        for frame in 1..=3u32 {
22824            fixture.begin(device);
22825            let parity = fixture.skinning.parity();
22826            let instance = instance_record(&recorder, &fixture.renderer, handle);
22827            assert_eq!(
22828                instance.base_vertex,
22829                fixture.skinned.region().base(parity),
22830                "frame {frame} must draw out of the half parity {parity} fills"
22831            );
22832            if frame == 1 {
22833                assert_eq!(
22834                    instance.previous_base_vertex, instance.base_vertex,
22835                    "a fresh object has no previous deformation, so its first frame owes rest \
22836                     rather than a half no dispatch has written"
22837                );
22838            } else {
22839                assert_eq!(
22840                    instance.previous_base_vertex,
22841                    fixture.skinned.region().previous_base(parity),
22842                    "frame {frame} must subtract against the half the frame before it filled"
22843                );
22844                assert_ne!(
22845                    instance.previous_base_vertex, instance.base_vertex,
22846                    "frame {frame} named one half twice, which is every skinned fragment at \
22847                     rest however far its surface moved"
22848                );
22849            }
22850        }
22851
22852        // The same object, moved onto a region it has never been drawn out of:
22853        // both halves are runs no dispatch of this object's has filled, so the
22854        // rule that put the first frame at rest applies again.
22855        let second = fixture
22856            .renderer
22857            .reserve_skinned(DEMO_CUBE)
22858            .expect("a default pool has room for two more halves of a cube");
22859        assert_ne!(
22860            second.region().base(0),
22861            fixture.skinned.region().base(0),
22862            "the second reservation is the same two runs as the first, so nothing below is \
22863             about a change of region at all"
22864        );
22865        fixture.renderer.set_skinned_instance(
22866            handle,
22867            &SkinnedInstanceDesc {
22868                mesh: &second,
22869                material: DEMO_UNTINTED,
22870                transform: Mat4::IDENTITY,
22871                bounds: None,
22872            },
22873        );
22874
22875        for frame in 1..=2u32 {
22876            fixture.begin(device);
22877            let parity = fixture.skinning.parity();
22878            let instance = instance_record(&recorder, &fixture.renderer, handle);
22879            assert_eq!(
22880                instance.base_vertex,
22881                second.region().base(parity),
22882                "frame {frame} after the move must draw out of the new region"
22883            );
22884            if frame == 1 {
22885                assert_eq!(
22886                    instance.previous_base_vertex, instance.base_vertex,
22887                    "the first frame on a new region owes rest, exactly as a fresh object does"
22888                );
22889            } else {
22890                assert_eq!(
22891                    instance.previous_base_vertex,
22892                    second.region().previous_base(parity),
22893                    "and the frame after it is subtracting against the new region's other half"
22894                );
22895            }
22896        }
22897
22898        fixture.renderer.release_skinned(second);
22899        fixture.destroy(device);
22900        recorder.assert_valid();
22901    }
22902
22903    /// **A skinned object that moves carries the transform it moved from**, and
22904    /// the frame after it is back at rest.
22905    ///
22906    /// The transform half of a skinned motion vector, and the half the
22907    /// per-frame re-point used to erase: it rewrote the record through
22908    /// [`InstancePool::set`], which fills the previous transform out of the
22909    /// record it overwrites — and that record already held this frame's
22910    /// transform, because
22911    /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
22912    /// it there. Every skinned instance then read `previous_transform ==
22913    /// transform` on every frame, so a character that walked contributed
22914    /// nothing to the motion target from the walk, only from its deformation.
22915    /// [`InstancePool::set_bases`] is what the re-point goes through instead.
22916    ///
22917    /// Both frames are the claim. Without the second, a re-point that wrote
22918    /// some *other* stale transform into the field would pass; and the second
22919    /// is the pool's own rest rule reaching a skinned object at all, which a
22920    /// re-point that kept enrolling the element every frame would suppress
22921    /// for ever.
22922    ///
22923    /// Read out of the ring buffer the frame draws from, on
22924    /// [`instance_record`]'s terms.
22925    #[test]
22926    fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
22927        let (recorder, device, queue) = open();
22928        let device = device.as_ref();
22929        let mut fixture = SkinnedFixture::build(device, queue);
22930        let handle = fixture
22931            .renderer
22932            .add_skinned_instance(&SkinnedInstanceDesc {
22933                mesh: &fixture.skinned,
22934                material: DEMO_UNTINTED,
22935                transform: Mat4::IDENTITY,
22936                bounds: None,
22937            })
22938            .expect("a pool of thousands has room for one object");
22939
22940        // Two frames standing still, so the history the move is measured
22941        // against is a settled record rather than a fresh one.
22942        fixture.begin(device);
22943        fixture.begin(device);
22944
22945        let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
22946        fixture.renderer.set_skinned_instance(
22947            handle,
22948            &SkinnedInstanceDesc {
22949                mesh: &fixture.skinned,
22950                material: DEMO_UNTINTED,
22951                transform: moved,
22952                bounds: None,
22953            },
22954        );
22955        fixture.begin(device);
22956        let instance = instance_record(&recorder, &fixture.renderer, handle);
22957        assert_eq!(
22958            instance.transform,
22959            moved.to_cols_array(),
22960            "the frame that moved the object must draw it where it arrived"
22961        );
22962        assert_eq!(
22963            instance.previous_transform,
22964            Mat4::IDENTITY.to_cols_array(),
22965            "and it must say where from — a previous transform equal to the current one is \
22966             the re-point having overwritten the move"
22967        );
22968
22969        fixture.begin(device);
22970        let settled = instance_record(&recorder, &fixture.renderer, handle);
22971        assert_eq!(
22972            settled.transform,
22973            moved.to_cols_array(),
22974            "nothing moved it again"
22975        );
22976        assert_eq!(
22977            settled.previous_transform, settled.transform,
22978            "so the frame after the move owes rest; a re-point that enrolled the element \
22979             every frame would keep it reporting the move for ever"
22980        );
22981
22982        fixture.destroy(device);
22983        recorder.assert_valid();
22984    }
22985
22986    /// **The graph barriers the skinning dispatch's write before every pass that
22987    /// pulls vertices**, and it does so because `add_skinned_passes` added the
22988    /// dispatch itself rather than trusting a caller to.
22989    ///
22990    /// Pass order alone would not settle it — a dispatch that ran first and was
22991    /// never barriered is the exact defect, and it produces a correct-looking
22992    /// frame on a desktop driver. So the transition out of
22993    /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
22994    /// it must sit after the dispatch, and it must sit at or before the first of
22995    /// the three passes that draw.
22996    #[test]
22997    fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
22998        let (recorder, device, queue) = open();
22999        let device = device.as_ref();
23000        let mut fixture = SkinnedFixture::build(device, queue);
23001        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
23002        fixture
23003            .renderer
23004            .add_skinned_instance(&SkinnedInstanceDesc {
23005                mesh: &fixture.skinned,
23006                material: DEMO_UNTINTED,
23007                transform: Mat4::IDENTITY,
23008                bounds: None,
23009            })
23010            .expect("room for one object");
23011        fixture.begin(device);
23012
23013        let imported = swapchain_image_at(device, TEST_EXTENT);
23014        let mut pool = crate::TransientPool::new();
23015        let mut graph = crate::RenderGraph::new(queue);
23016        let target = graph.import_image("target", imported);
23017        // The same node `Skinning::add_pass` imports — one handle is one node —
23018        // so the barriers below can be named rather than guessed at.
23019        let vertices = graph.import_buffer(
23020            "vertex-pool",
23021            ImportedBuffer {
23022                buffer: fixture.renderer.vertex_buffer(),
23023                initial: ResourceState::ShaderRead,
23024                final_state: ResourceState::ShaderRead,
23025            },
23026        );
23027        fixture.renderer.add_skinned_passes(
23028            &mut graph,
23029            &pool,
23030            target,
23031            TEST_EXTENT,
23032            &fixture.skinning,
23033        );
23034        let compiled = graph.compile(&pool).expect("a legal frame");
23035        let labels: Vec<&str> = compiled
23036            .passes()
23037            .iter()
23038            .map(crate::graph::CompiledPass::label)
23039            .collect();
23040
23041        let dispatch = labels
23042            .iter()
23043            .position(|label| *label == "skinning")
23044            .expect("add_skinned_passes adds the dispatch itself");
23045        let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
23046            .into_iter()
23047            .map(|wanted| {
23048                labels
23049                    .iter()
23050                    .position(|label| *label == wanted)
23051                    .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
23052            })
23053            .collect();
23054        for (label, at) in ["shadow", "depth-prepass", "forward"]
23055            .into_iter()
23056            .zip(&drawing)
23057        {
23058            assert!(
23059                dispatch < *at,
23060                "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
23061            );
23062        }
23063
23064        // Each drawing pass declares the read for itself, and this is asserted
23065        // per pass rather than left to the single barrier below. The graph
23066        // transitions the region once, before the first reader, and a later
23067        // pass that never declared the read finds it already in the state it
23068        // wanted — so dropping the declaration from `forward` alone changes no
23069        // barrier and moves no label, and every assertion in this test still
23070        // passes. What it does drop is that pass's *dependency* on the
23071        // dispatch, which is the only thing keeping the two in this order.
23072        for (label, at) in ["shadow", "depth-prepass", "forward"]
23073            .into_iter()
23074            .zip(&drawing)
23075        {
23076            assert!(
23077                compiled.passes()[*at].reads_buffer(vertices),
23078                "{label} draws skinned vertices and must declare that it reads them, or \
23079                 nothing but declaration order keeps it after the dispatch"
23080            );
23081        }
23082
23083        let released: Vec<usize> = compiled
23084            .passes()
23085            .iter()
23086            .enumerate()
23087            .filter(|(_, pass)| {
23088                pass.barriers().buffers.iter().any(|barrier| {
23089                    barrier.buffer == vertices
23090                        && barrier.from == ResourceState::ShaderReadWrite
23091                        && barrier.to == ResourceState::ShaderRead
23092                })
23093            })
23094            .map(|(at, _)| at)
23095            .collect();
23096        assert_eq!(
23097            released.len(),
23098            1,
23099            "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
23100        );
23101        let barrier = released[0];
23102        let first_draw = *drawing.iter().min().expect("three passes");
23103        assert!(
23104            dispatch < barrier && barrier <= first_draw,
23105            "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
23106             draws at {first_draw} — a draw that reads the region before the write is made \
23107             visible is the whole defect this seam exists to prevent"
23108        );
23109
23110        drop(compiled);
23111        fixture.destroy(device);
23112        pool.destroy(device);
23113        device.destroy_image_view(imported.view);
23114        device.destroy_image(imported.image);
23115        recorder.assert_valid();
23116    }
23117
23118    /// A frame with nothing to skin adds no dispatch and declares no read, and
23119    /// is the frame [`ForwardRenderer::add_passes`] would have built.
23120    #[test]
23121    fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
23122        let _blurs = ssao_blur_switch();
23123        let (recorder, device, queue) = open();
23124        let device = device.as_ref();
23125        let mut fixture = SkinnedFixture::build(device, queue);
23126        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
23127
23128        let imported = swapchain_image_at(device, TEST_EXTENT);
23129        let pool = crate::TransientPool::new();
23130        let mut skinned_labels = Vec::new();
23131        for _ in 0..1 {
23132            fixture
23133                .renderer
23134                .begin_skinned_frame(
23135                    device,
23136                    &mut fixture.skinning,
23137                    &[],
23138                    &Camera::default(),
23139                    &DirectionalLight::default(),
23140                    TEST_EXTENT,
23141                )
23142                .expect("an empty plan is a legal one");
23143            let mut graph = crate::RenderGraph::new(queue);
23144            let target = graph.import_image("target", imported);
23145            fixture.renderer.add_skinned_passes(
23146                &mut graph,
23147                &pool,
23148                target,
23149                TEST_EXTENT,
23150                &fixture.skinning,
23151            );
23152            skinned_labels = graph
23153                .compile(&pool)
23154                .expect("a legal frame")
23155                .passes()
23156                .iter()
23157                .map(|pass| pass.label().to_string())
23158                .collect();
23159        }
23160        let plain = passes_in_a_frame(
23161            device,
23162            queue,
23163            &mut fixture.renderer,
23164            imported,
23165            &pool,
23166            TEST_EXTENT,
23167        );
23168        assert_eq!(
23169            skinned_labels, plain,
23170            "a frame with nothing to skin must cost the vertex pool no barrier at all"
23171        );
23172
23173        fixture.destroy(device);
23174        let mut pool = pool;
23175        pool.destroy(device);
23176        device.destroy_image_view(imported.view);
23177        device.destroy_image(imported.image);
23178        recorder.assert_valid();
23179    }
23180
23181    /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
23182    /// the commands land in.
23183    ///
23184    /// Returned rather than cleaned up here because the caller reads the
23185    /// recorder afterwards, and everything below must outlive that.
23186    struct Frame {
23187        imported: ImportedImage,
23188        pool: crate::TransientPool,
23189        commands: crcbl_hal::CommandBufferHandle,
23190    }
23191
23192    impl Frame {
23193        /// Releases the frame and the image it drew into, leaving the renderer
23194        /// alive for another one.
23195        fn release(self, device: &dyn Device) {
23196            device.destroy_command_buffer(self.commands);
23197            let mut pool = self.pool;
23198            pool.destroy(device);
23199            device.destroy_image_view(self.imported.view);
23200            device.destroy_image(self.imported.image);
23201        }
23202
23203        /// Releases the frame, the renderer and the image it drew into.
23204        fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
23205            self.release(device);
23206            renderer.destroy(device);
23207        }
23208    }
23209
23210    /// Everything one labelled pass recorded, and nothing any other pass did.
23211    ///
23212    /// **Every draw assertion below is scoped through this**, and the reason is
23213    /// topic 18: the frame now records the same indirect call the colour pass
23214    /// records once per shadow cascade as well, out of that cascade's own
23215    /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
23216    /// would see one per cascade as well as the colour pass's, and could not
23217    /// say which pass any of them belonged to — so "the forward pass records one
23218    /// call per bucket" would become a claim about a total, which a shadow pass
23219    /// recording the wrong thing could satisfy.
23220    /// The compute dispatches a default frame's **resolve** records, which
23221    /// every dispatch count in this module sees and none of them is about.
23222    ///
23223    /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
23224    /// shape classification are dispatches; its apply is a draw and does not
23225    /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
23226    /// what pins the resolve's pass list itself, so a tier that grew a dispatch
23227    /// fails there first and arrives here as a second red rather than as a
23228    /// silent skew.
23229    const RESOLVE_DISPATCHES: usize = 2;
23230
23231    fn commands_in_pass(
23232        recorder: &crcbl_hal::null::Recorder,
23233        label: &str,
23234    ) -> Vec<crcbl_hal::null::Command> {
23235        use crcbl_hal::null::Command;
23236
23237        let mut inside = false;
23238        let mut out = Vec::new();
23239        for command in recorder.commands() {
23240            if let Some((_, recorded)) = command.opens_pass() {
23241                inside = recorded == Some(label);
23242                continue;
23243            }
23244            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
23245                inside = false;
23246                continue;
23247            }
23248            if inside {
23249                out.push(command);
23250            }
23251        }
23252        assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
23253        out
23254    }
23255
23256    /// The extent every helper frame in this module is drawn at.
23257    ///
23258    /// Named since the bloom chain, whose length is a function of it — see
23259    /// [`crate::bloom`] — so a test comparing a pass count against
23260    /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
23261    /// at. Small on purpose: two chain levels is enough for every arm here, and
23262    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
23263    /// test that needs a frame large enough for six.
23264    ///
23265    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
23266    const TEST_EXTENT: (u32, u32) = (64, 48);
23267
23268    /// The effects a caller has to ask for, because the default stack leaves
23269    /// them out — see [`RenderEffects::DEFAULT_STACK`].
23270    ///
23271    /// Named rather than written out at each of the three sites that force them
23272    /// on, because the point of those sites is "every effect there is" and the
23273    /// bug they exist to catch is a new effect joining the set and one site
23274    /// still measuring the old one while calling it the whole stack. They are
23275    /// held out of the default for different reasons — [`crate::effects`] gives
23276    /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
23277    /// pending re-bless rather than a decision — and share only that a test
23278    /// wanting the widest frame must ask.
23279    ///
23280    /// **Named for what it is rather than for what most of it is**: the set held
23281    /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
23282    /// march is neither.
23283    const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
23284        .union(RenderEffects::ANTIALIASING)
23285        .union(RenderEffects::VOLUMETRIC_FOG)
23286        .union(RenderEffects::AUTO_EXPOSURE)
23287        .union(RenderEffects::CMAA2)
23288        .union(RenderEffects::CONTACT_SHADOWS);
23289
23290    /// Every effect this renderer draws is either in the default stack or in
23291    /// [`OUTSIDE_THE_DEFAULT`].
23292    ///
23293    /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
23294    /// call the result "every effect", which is only true while nothing else is
23295    /// held out. An effect added outside the default stack and not added
23296    /// here makes this red before it makes a pass-list assertion red — which is
23297    /// the useful order, since a pass list going red says a label moved and this
23298    /// says what actually happened.
23299    #[test]
23300    fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
23301        assert_eq!(
23302            RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
23303            RenderEffects::all(),
23304            "an effect outside the default stack that no test forces on is an effect \
23305             the every-effect frames below have never drawn"
23306        );
23307    }
23308
23309    /// The default sun, turned a little further round for each `lap`.
23310    ///
23311    /// Topic 45's static-caching rung means a second frame over
23312    /// a scene nothing moved in records **no shadow pass at all** — see
23313    /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
23314    /// a difference that every A/B drawing two frames from one renderer would
23315    /// otherwise be measuring on top of the one it is about. Turning the sun is
23316    /// the smallest input the atlas depends on: the cascades are refitted, so
23317    /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
23318    /// with it.
23319    ///
23320    /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
23321    /// frame is the ordinary one keeps the frame every other test draws.
23322    fn moving_sun(lap: u32) -> DirectionalLight {
23323        let sun = DirectionalLight::default();
23324        // A degree a lap, about the axis the default direction is not parallel
23325        // to. Small enough that every cascade still sees the scene, and large
23326        // enough that the snapped cascade origin actually moves.
23327        let turn = Mat4::from_rotation_y(
23328            f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
23329                / 180.0,
23330        );
23331        DirectionalLight {
23332            direction: turn.transform_vector3(sun.direction).normalize(),
23333            ..sun
23334        }
23335    }
23336
23337    /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
23338    /// not the one the lap before it left in the image.
23339    fn frame_moving_the_sun(
23340        device: &dyn Device,
23341        renderer: &mut ForwardRenderer,
23342        queue: QueueHandle,
23343        lap: u32,
23344    ) -> Frame {
23345        frame_lit_by(device, renderer, queue, &moving_sun(lap))
23346    }
23347
23348    fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
23349        frame_lit_by(device, renderer, queue, &DirectionalLight::default())
23350    }
23351
23352    fn frame_lit_by(
23353        device: &dyn Device,
23354        renderer: &mut ForwardRenderer,
23355        queue: QueueHandle,
23356        sun: &DirectionalLight,
23357    ) -> Frame {
23358        frame_seen_from(device, renderer, queue, &Camera::default(), sun)
23359    }
23360
23361    fn frame_seen_from(
23362        device: &dyn Device,
23363        renderer: &mut ForwardRenderer,
23364        queue: QueueHandle,
23365        camera: &Camera,
23366        sun: &DirectionalLight,
23367    ) -> Frame {
23368        renderer
23369            .begin_frame(device, camera, sun, TEST_EXTENT)
23370            .expect("write");
23371        let imported = swapchain_image(device);
23372        let mut graph = crate::RenderGraph::new(queue);
23373        let target = graph.import_image("target", imported);
23374        let mut pool = crate::TransientPool::new();
23375        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
23376        let compiled = graph.compile(&pool).expect("a legal frame");
23377        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
23378            label: Some("forward frame"),
23379            queue,
23380        });
23381        compiled
23382            .execute(device, &mut pool, encoder.as_mut(), None)
23383            .expect("the graph executed");
23384        let commands = encoder.finish().expect("recording succeeded");
23385        Frame {
23386            imported,
23387            pool,
23388            commands,
23389        }
23390    }
23391
23392    /// A stand-in for the acquired swapchain image the frame normally ends in,
23393    /// at [`TEST_EXTENT`].
23394    fn swapchain_image(device: &dyn Device) -> ImportedImage {
23395        swapchain_image_at(device, TEST_EXTENT)
23396    }
23397
23398    /// The same, at an extent of the caller's choosing.
23399    ///
23400    /// A frame's attachments must all be one size — the graph refuses a pass
23401    /// whose colour target and depth disagree — so a test drawing at anything
23402    /// but [`TEST_EXTENT`] has to import a target of that size too.
23403    pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
23404        let format = Format::Rgba8UnormSrgb;
23405        let image = device
23406            .create_image(&crcbl_hal::ImageDesc {
23407                label: Some("fake swapchain image"),
23408                image_type: crcbl_hal::ImageType::D2,
23409                extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
23410                format,
23411                mip_levels: 1,
23412                samples: 1,
23413                usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
23414            })
23415            .expect("an image");
23416        let view = device
23417            .create_image_view(&crcbl_hal::ImageViewDesc {
23418                label: Some("fake swapchain view"),
23419                image,
23420                view_type: crcbl_hal::ImageViewType::D2,
23421                format,
23422                range: crcbl_hal::ImageSubresourceRange::all(format),
23423            })
23424            .expect("a view");
23425        ForwardRenderer::present_target(image, view, format, extent)
23426    }
23427
23428    /// The spin is a rotation: no scale, no shear, so the cube neither grows
23429    /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
23430    /// picture of one cube.
23431    ///
23432    /// That is also what keeps those goldens insensitive to `mesh.slang`'s
23433    /// `normal_basis`. A matrix with orthonormal rows and a positive
23434    /// determinant is its own cofactor matrix, to within a rounding step, so
23435    /// the vertex stage writes the normals it wrote when it multiplied by the
23436    /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
23437    /// longer requires a caller to be rigid at all.
23438    #[test]
23439    fn the_spin_matrix_stays_rigid() {
23440        for seconds in [0.0f32, 0.5, 3.25, 100.0] {
23441            let model = ForwardRenderer::spin(seconds);
23442            let basis = glam::Mat3::from_mat4(model);
23443            let product = basis * basis.transpose();
23444            for (row, expected) in [
23445                (product.x_axis, Vec3::X),
23446                (product.y_axis, Vec3::Y),
23447                (product.z_axis, Vec3::Z),
23448            ] {
23449                assert!(
23450                    (row - expected).length() < 1e-5,
23451                    "the spin at {seconds}s is not orthonormal: {product:?}"
23452                );
23453            }
23454            assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
23455        }
23456        // And it actually moves.
23457        assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
23458    }
23459
23460    /// The swapchain import says what a swapchain image actually needs, which is
23461    /// the knowledge the hand-written barriers used to carry.
23462    #[test]
23463    fn the_present_target_starts_undefined_and_ends_presentable() {
23464        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
23465        let image = pool.insert(0).cast();
23466        let view = pool.insert(0).cast();
23467        let imported =
23468            ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
23469        assert_eq!(imported.initial, ResourceState::Undefined);
23470        assert_eq!(imported.final_state, ResourceState::Present);
23471        assert_eq!(imported.extent, (1280, 720));
23472    }
23473
23474    /// The scene target is `Rgba16Float`, and the depth target is the
23475    /// reversed-Z format. Both are locked decisions and both are cheap to pin.
23476    #[test]
23477    fn the_scene_targets_are_hdr_and_reversed_z() {
23478        let color = crate::targets::scene_color((64, 48));
23479        assert_eq!(color.format, Format::Rgba16Float);
23480        assert!(color.format.is_hdr_capable());
23481        assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
23482
23483        let depth = crate::targets::scene_depth((64, 48));
23484        assert_eq!(depth.format, Format::D32Float);
23485        assert_eq!(
23486            DepthStencilState::default().depth_compare,
23487            crcbl_hal::CompareOp::Greater
23488        );
23489    }
23490
23491    /// A sun ten degrees or so above the horizon, and one further round: two
23492    /// atmospheres whose LUTs are nowhere near each other, so a comparison
23493    /// between them cannot pass by the two skies being alike.
23494    ///
23495    /// Spelled as directions rather than as angles for
23496    /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
23497    /// own — and normalised by `Atmosphere::parameters` on the way in.
23498    const MOVED_SUN: Atmosphere = Atmosphere {
23499        sun_direction: Vec3::new(1.0, 0.2, 0.0),
23500        ..Atmosphere::NOON
23501    };
23502
23503    /// [`MOVED_SUN`] again, further round and lower.
23504    const MOVED_AGAIN: Atmosphere = Atmosphere {
23505        sun_direction: Vec3::new(1.0, 0.05, 0.5),
23506        ..Atmosphere::NOON
23507    };
23508
23509    /// Frames the striped march takes to cross the LUT.
23510    const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
23511
23512    /// The bytes the most recent sky-view LUT upload put on the device.
23513    ///
23514    /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
23515    /// that has an atmosphere, into the slot that frame is using — so the last
23516    /// write to any of the ring's buffers is the LUT the frame just recorded
23517    /// would draw. That is the only place the presented LUT is observable: the
23518    /// renderer's own copy is what a test could assert about instead, and it
23519    /// would then be asserting about the thing rather than about what reached
23520    /// the device.
23521    fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
23522        recorder
23523            .events()
23524            .into_iter()
23525            .rev()
23526            .find_map(|event| match event {
23527                crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
23528                    recorder.buffer_bytes(buffer)
23529                }
23530                _ => None,
23531            })
23532            .expect("a frame with an atmosphere uploads a sky-view LUT")
23533    }
23534
23535    /// A renderer with an atmosphere set and its first LUT marched, and the
23536    /// buffers that LUT reaches the device through.
23537    ///
23538    /// The three tests below all start here: the first march is synchronous, so
23539    /// one frame is what it takes to have a sky to be stale about.
23540    fn with_marched_atmosphere(
23541        device: &dyn Device,
23542        queue: QueueHandle,
23543        atmosphere: Atmosphere,
23544    ) -> (ForwardRenderer, Vec<BufferHandle>) {
23545        let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
23546            .expect("the null backend builds a renderer");
23547        let luts = renderer.primary.sky_pass.luts().to_vec();
23548        renderer.set_atmosphere(Some(atmosphere));
23549        atmosphere_frame(&mut renderer, device);
23550        (renderer, luts)
23551    }
23552
23553    /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
23554    /// is what writes the blocks and steps the march.
23555    fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
23556        renderer
23557            .begin_frame(
23558                device,
23559                &Camera::default(),
23560                &DirectionalLight::default(),
23561                (64, 48),
23562            )
23563            .expect("the frame's blocks are written");
23564    }
23565
23566    /// A sun that moved is marched a stripe per frame, and every frame until it
23567    /// is finished still uploads the LUT of the sun before it.
23568    ///
23569    /// **The amortisation, from the device's side.** Before this, one
23570    /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
23571    /// tens of milliseconds of CPU in every frame. The claim now is three
23572    /// things at once, and only the middle one is about performance: the march
23573    /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
23574    /// device meanwhile are the *previous* sun's rather than a half-marched
23575    /// sky, and the new sun's LUT arrives whole on the frame the march ends.
23576    ///
23577    /// **And the aerial-perspective LUT keeps the same pace**: it rides the
23578    /// same stripes, so it too uploads the previous sun's air on every frame
23579    /// of the march and the new sun's on the frame that ends it — the lag
23580    /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
23581    /// reach the device a sun apart.
23582    #[test]
23583    fn a_moving_sun_is_marched_a_stripe_per_frame() {
23584        let (recorder, device, queue) = open();
23585        let (mut renderer, luts) =
23586            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23587        let aerials = renderer.primary.sky_pass.aerials().to_vec();
23588
23589        let before_view = SkyView::build(&Atmosphere::NOON.parameters());
23590        let after_view = SkyView::build(&MOVED_SUN.parameters());
23591        let before = before_view.rows();
23592        let after = after_view.rows();
23593        let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
23594        assert_ne!(
23595            before, after,
23596            "the two suns march to the same LUT, so nothing below distinguishes them"
23597        );
23598        assert_ne!(
23599            air_before, air_after,
23600            "the two suns march to the same air, so nothing below distinguishes them"
23601        );
23602        assert!(
23603            renderer.sky_view_build.is_none(),
23604            "the first march is synchronous, so no build is left in flight"
23605        );
23606        assert_eq!(
23607            presented_lut(&recorder, &luts),
23608            before,
23609            "the frame after `set_atmosphere` did not upload that sun's LUT"
23610        );
23611        assert_eq!(
23612            presented_lut(&recorder, &aerials),
23613            air_before,
23614            "the frame after `set_atmosphere` did not upload that sun's air"
23615        );
23616
23617        renderer.set_atmosphere(Some(MOVED_SUN));
23618        for step in 1..MARCH_FRAMES {
23619            atmosphere_frame(&mut renderer, device.as_ref());
23620            assert_eq!(
23621                renderer
23622                    .sky_view_build
23623                    .as_ref()
23624                    .map(SkyViewBuild::rows_done),
23625                Some(step * SKY_VIEW_BUILD_ROWS),
23626                "frame {step} of the march is not a stripe further along than frame {} was",
23627                step - 1
23628            );
23629            assert_eq!(
23630                presented_lut(&recorder, &luts),
23631                before,
23632                "frame {step} of the march uploaded something other than the sky it is still \
23633                 drawing"
23634            );
23635            assert_eq!(
23636                presented_lut(&recorder, &aerials),
23637                air_before,
23638                "frame {step} of the march uploaded air other than the sky it is still drawing's"
23639            );
23640        }
23641
23642        atmosphere_frame(&mut renderer, device.as_ref());
23643        assert!(
23644            renderer.sky_view_build.is_none(),
23645            "the march did not finish in the frames its own stripe says it takes"
23646        );
23647        assert_eq!(
23648            presented_lut(&recorder, &luts),
23649            after,
23650            "the frame that finished the march did not upload the new sun's LUT"
23651        );
23652        assert_eq!(
23653            presented_lut(&recorder, &aerials),
23654            air_after,
23655            "the frame that finished the march did not upload the new sun's air"
23656        );
23657    }
23658
23659    /// An atmosphere adds the composite for its air whether or not the fog
23660    /// effect is on, and the block tells the composite which halves to read.
23661    ///
23662    /// **The seam between the two volumes, on the renderer's side.** Three
23663    /// frames of one renderer: no atmosphere and the default stack, which has
23664    /// no fog effect in it — no composite at all, the frame drawn before the
23665    /// air existed; an atmosphere and the same stack — the composite and
23666    /// nothing of the column, and a block saying so; and an atmosphere with
23667    /// the fog effect forced on — all three passes, and a block saying both.
23668    /// The counters are held to the frame on the second: the composite is a
23669    /// full-screen triangle, and a frame that drew it and did not count it
23670    /// makes the debug panel's row disagree with the frame by one.
23671    #[test]
23672    fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
23673        let _blurs = ssao_blur_switch();
23674        let (recorder, device, queue) = open();
23675        let device = device.as_ref();
23676        let mut renderer =
23677            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
23678        let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
23679            .map(|frame| renderer.primary.volumetric.buffers(frame).params)
23680            .collect();
23681        let imported = swapchain_image(device);
23682        let mut pool = crate::TransientPool::new();
23683        let block = |recorder: &Recorder| {
23684            let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
23685                presented_lut(recorder, &blocks)
23686                    .try_into()
23687                    .expect("the block is its own size");
23688            crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
23689        };
23690        let column = ["volumetric-scatter", "volumetric-integrate"];
23691
23692        let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23693        let before = renderer.counters();
23694        assert!(
23695            !bare.iter().any(|pass| pass.starts_with("volumetric")),
23696            "a frame with neither fog nor an atmosphere records {bare:?}"
23697        );
23698        let off = block(&recorder);
23699        assert_eq!(
23700            off.aerial_params,
23701            [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
23702            "a frame with no atmosphere writes something into the aerial row"
23703        );
23704
23705        renderer.set_atmosphere(Some(Atmosphere::NOON));
23706        let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23707        assert!(
23708            air.iter().any(|pass| pass == "volumetric-composite")
23709                && !air.iter().any(|pass| column.contains(&pass.as_str())),
23710            "an atmosphere with the fog effect off records {air:?}, where it should composite its \
23711             air and run nothing of the column"
23712        );
23713        let after = renderer.counters();
23714        assert_eq!(
23715            after.draws - before.draws,
23716            (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
23717            "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
23718        );
23719        let aerial_only = block(&recorder);
23720        let sun = Atmosphere::NOON.parameters().sun_direction;
23721        assert_eq!(
23722            aerial_only.aerial_params,
23723            [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
23724            "the aerial row does not carry the atmosphere's sun and its switch"
23725        );
23726        assert_eq!(
23727            aerial_only.fog_params[3],
23728            crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
23729            "the block tells the composite to read a column no pass filled"
23730        );
23731
23732        renderer.set_effect_request(EffectRequest {
23733            programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
23734            ..EffectRequest::default()
23735        });
23736        let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23737        assert!(
23738            column
23739                .iter()
23740                .chain(&["volumetric-composite"])
23741                .all(|name| both.iter().any(|pass| pass == name)),
23742            "an atmosphere with the fog effect on records {both:?}"
23743        );
23744        assert_eq!(
23745            block(&recorder).fog_params[3],
23746            crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
23747            "the block tells the composite to skip a column the frame filled"
23748        );
23749
23750        renderer.destroy(device);
23751        pool.destroy(device);
23752        device.destroy_image_view(imported.view);
23753        device.destroy_image(imported.image);
23754        recorder.assert_valid();
23755    }
23756
23757    /// A sun that moves while a march is in flight restarts it from row zero.
23758    ///
23759    /// **The decision `refresh_sky_view` writes down**, and the reason a sun
23760    /// that moves every frame shows a frozen sky rather than a stuttering one:
23761    /// finishing a march for a sun that has already moved would swap in a LUT
23762    /// that is wrong on arrival. What is observable is the progress counter —
23763    /// a build that kept its rows would be two stripes along here rather than
23764    /// one — and the sun the build in flight names.
23765    #[test]
23766    fn a_sun_that_moves_mid_march_restarts_it() {
23767        let (recorder, device, queue) = open();
23768        let (mut renderer, luts) =
23769            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23770        let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
23771
23772        renderer.set_atmosphere(Some(MOVED_SUN));
23773        atmosphere_frame(&mut renderer, device.as_ref());
23774        atmosphere_frame(&mut renderer, device.as_ref());
23775        assert_eq!(
23776            renderer
23777                .sky_view_build
23778                .as_ref()
23779                .map(SkyViewBuild::rows_done),
23780            Some(2 * SKY_VIEW_BUILD_ROWS),
23781            "two frames of marching did not leave two stripes marched"
23782        );
23783
23784        renderer.set_atmosphere(Some(MOVED_AGAIN));
23785        atmosphere_frame(&mut renderer, device.as_ref());
23786        assert_eq!(
23787            renderer
23788                .sky_view_build
23789                .as_ref()
23790                .map(SkyViewBuild::rows_done),
23791            Some(SKY_VIEW_BUILD_ROWS),
23792            "the march kept the rows it had marched for a sun that has since moved"
23793        );
23794        assert_eq!(
23795            renderer
23796                .sky_view_build
23797                .as_ref()
23798                .map(SkyViewBuild::atmosphere),
23799            Some(MOVED_AGAIN.parameters()),
23800            "the build in flight is marching a sun the caller has moved away from"
23801        );
23802        assert_eq!(
23803            presented_lut(&recorder, &luts),
23804            before,
23805            "a restart uploaded something other than the last LUT that finished"
23806        );
23807    }
23808
23809    /// A frame whose sun has not moved marches nothing and re-takes neither
23810    /// projection.
23811    ///
23812    /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
23813    /// be taken from the LUT in every `begin_frame`, which is host work a still
23814    /// sun has no reason to pay. Both are now taken once, where the march
23815    /// finishes — so a sentinel written over the cached gradient survives a
23816    /// frame if and only if that frame took neither the march nor the
23817    /// projection again, and the same sentinel's bytes turn up in what the
23818    /// frame wrote, which is what says the cache is the thing being read.
23819    #[test]
23820    fn a_still_sun_marches_nothing_and_reprojects_nothing() {
23821        let (recorder, device, queue) = open();
23822        let (mut renderer, _luts) =
23823            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23824
23825        let sentinel = crcbl_shaders::sky::SkyGradient {
23826            zenith: [0.125, 0.25, 0.375],
23827            horizon: [0.5, 0.625, 0.75],
23828            ground: [0.875, 1.125, 1.375],
23829        };
23830        let presented = renderer
23831            .sky_view
23832            .as_mut()
23833            .expect("the first frame marched a LUT");
23834        assert_ne!(
23835            presented.gradient, sentinel,
23836            "the sentinel is what the real projection already returns, so it proves nothing"
23837        );
23838        presented.gradient = sentinel;
23839
23840        let before = recorder.events().len();
23841        atmosphere_frame(&mut renderer, device.as_ref());
23842        assert_eq!(
23843            renderer
23844                .sky_view
23845                .as_ref()
23846                .map(|presented| presented.gradient),
23847            Some(sentinel),
23848            "a frame under a sun that has not moved re-took the projections"
23849        );
23850        assert!(
23851            renderer.sky_view_build.is_none(),
23852            "a frame under a sun that has not moved started a march"
23853        );
23854
23855        let wanted: Vec<u8> = sentinel
23856            .rows()
23857            .iter()
23858            .flatten()
23859            .flat_map(|value| value.to_le_bytes())
23860            .collect();
23861        let used = recorder
23862            .events()
23863            .into_iter()
23864            .skip(before)
23865            .filter_map(|event| match event {
23866                crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
23867                    recorder.buffer_bytes(buffer)
23868                }
23869                _ => None,
23870            })
23871            .any(|bytes| {
23872                bytes
23873                    .windows(wanted.len())
23874                    .any(|window| window == wanted.as_slice())
23875            });
23876        assert!(
23877            used,
23878            "the cached gradient reached no block this frame wrote, so the frame is not reading \
23879             the cache at all"
23880        );
23881    }
23882
23883    /// **The frame block's ambient rows carry the marched LUT's own L1
23884    /// projection**, and not the three-band fit's.
23885    ///
23886    /// `begin_frame` writes [`PresentedSky::irradiance`] into
23887    /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
23888    /// test nothing read them back. The only reader of those rows is arithmetic
23889    /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
23890    /// surface under an atmosphere — `crcbl`'s
23891    /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
23892    /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
23893    /// instead, the three-band fit's projection rather than the LUT's, was a
23894    /// swap `docs/backlog.md` recorded passing every suite in the tree on
23895    /// 2026-09-06.
23896    ///
23897    /// **Both halves are needed and the second is the sabotage's.** The rows
23898    /// equalling the LUT's projection is the wiring; the rows *differing* from
23899    /// the fit's is what makes the equality a claim about which projection
23900    /// arrived rather than about two numbers that happen to agree. The
23901    /// `assert_ne` above them is the anti-vacuity: a sun for which the two
23902    /// projections coincide would make this test pass under the swap.
23903    ///
23904    /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
23905    #[test]
23906    fn an_atmosphere_writes_the_luts_own_ambient_term() {
23907        /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
23908        /// puts in the block.
23909        fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
23910            [probe.sh_r, probe.sh_g, probe.sh_b]
23911                .iter()
23912                .flatten()
23913                .flat_map(|value| value.to_le_bytes())
23914                .collect()
23915        }
23916
23917        let (recorder, device, queue) = open();
23918        let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
23919
23920        let view = SkyView::build(&MOVED_SUN.parameters());
23921        let marched = rows(&view.irradiance());
23922        let fitted = rows(&view.gradient_fit().irradiance());
23923        assert_ne!(
23924            marched, fitted,
23925            "this sun's LUT and its three-band fit project to the same rows, so a block \
23926             carrying either would satisfy the check below and the swap it exists for would \
23927             pass"
23928        );
23929
23930        let block = recorder
23931            .buffer_bytes(renderer.primary.uniforms[renderer.frame])
23932            .expect("a frame with an atmosphere writes its uniform block");
23933        let at = mesh::SKY_SH_R_OFFSET;
23934        assert_eq!(
23935            &block[at..at + marched.len()],
23936            marched.as_slice(),
23937            "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
23938             marched, so the ambient term the fragment stage evaluates comes from somewhere \
23939             else"
23940        );
23941        assert_ne!(
23942            &block[at..at + fitted.len()],
23943            fitted.as_slice(),
23944            "the frame block's sky rows are the gradient fit's projection — the LUT was \
23945             marched and then thrown away for the three-band approximation of it"
23946        );
23947
23948        renderer.destroy(device.as_ref());
23949    }
23950}