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,
156    sky_prefilter, ssao, ssr, 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::{
229    FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput, ViewPipelineLayouts,
230    ViewPipelines,
231};
232pub use view::{
233    FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
234};
235
236/// The clear behind the mesh, in **linear** light.
237///
238/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
239/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
240/// display-referred colour here would come out visibly paler, which is the
241/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
242pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
243
244/// How many frames of uniform buffers to keep. Matches the frame loop's
245/// frames-in-flight.
246pub const FRAMES_IN_FLIGHT: usize = 2;
247
248// The UI pass this renderer draws its HUD through keeps a ring of its own,
249// built at `crcbl_frame`'s default depth; held equal here, where both are in
250// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
251const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);
252
253/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
254/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
255///
256/// The floor exists so that the control cannot be driven somewhere it cannot be
257/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
258/// unclamped input has two dead ends: far enough down and every pixel rounds to
259/// the same black byte, far enough up and every pixel saturates to white — and
260/// in both the picture stops carrying the information a user would need to see
261/// which way to go. Five stops is well inside either: it is a sixteenth of the
262/// scene's brightness, dark but plainly still a picture, and it is the range a
263/// camera's exposure-compensation dial covers.
264pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
265
266/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
267/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
268/// [`EXPOSURE_MIN`]'s reason.
269pub const EXPOSURE_MAX: f32 = 32.0;
270
271/// The default has to be reachable from both ends of the range, or a control
272/// that steps by a ratio starts somewhere it can only leave in one direction.
273const _: () = assert!(
274    EXPOSURE_MIN > 0.0
275        && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
276        && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
277);
278
279/// The format the frame's depth buffer is created with, taken from the
280/// description that creates it rather than written down a second time.
281///
282/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
283/// depth attachment before there is a frame to ask. The extent is irrelevant to
284/// a format, which is why any is passed.
285pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
286
287/// The format the frame's HDR scene target is created with, taken from the
288/// description that creates it rather than written down a second time.
289///
290/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
291/// chain of HDR passes ended with — every one of them is a
292/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
293/// which is why any is passed.
294pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
295
296/// The format §3.2's base-colour page is created with.
297///
298/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
299/// for it is at the `upload_texture_mip_layers` call inside
300/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
301/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
302/// the image was created with, and a barrier naming a format the image is not in
303/// picks the wrong aspects.
304const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
305
306/// The format topic 43 §2's **normal** page is
307/// created with.
308///
309/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
310/// Topic 44's rung 2 argues it: a base-colour texel is a
311/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
312/// the sampler decode it; a normal texel is a *number* — three components of a
313/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
314/// transfer curve is wrong by a gamma. What that looks like is not an error but
315/// a surface that leans further off vertical than the author drew, which is why
316/// the mistake survives review everywhere it is made.
317///
318/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
319/// worth having because the four constants sit a few lines apart and the wrong
320/// one compiles.
321const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
322
323/// The format topic 43 §2's **metallic-roughness-
324/// occlusion** page is created with.
325///
326/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
327/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
328/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
329/// linear factors — and a surface shaded through an sRGB decode of them is
330/// smoother and shinier than the author drew, which is a failure that survives
331/// review because it looks like a choice.
332///
333/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
334/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
335/// one of them wanted a different format should be an edit here rather than a
336/// search for which callers of a shared name meant which page.
337const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
338
339/// The format topic 43 §2's **emissive** page is
340/// created with.
341///
342/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
343/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
344/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
345/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
346/// what puts the two in one space before they are multiplied.
347///
348/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
349/// and `the_page_formats_split_colour_from_number` is the guard that the four
350/// do not drift into one another.
351const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
352
353/// What the renderer needs of a [`PageKind`] to create and fill its image.
354///
355/// Written here rather than in [`crate::scene`] because the two answers are the
356/// device's: the format is the one [`base_color_page_import`] and
357/// [`normal_page_import`] have to declare, and the filter is the one
358/// [`crate::mip`] builds the chain with. A kind added by
359/// topic 43 §2's rung 3 is a new arm in each.
360///
361/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
362/// [`normal_page_import`]: ForwardRenderer::normal_page_import
363impl PageKind {
364    /// The format this kind's image is created with.
365    ///
366    /// The sRGB in one and its absence in the other is the whole colour-space
367    /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
368    /// which is where each is argued.
369    const fn format(self) -> Format {
370        match self {
371            Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
372            Self::Normal => NORMAL_PAGE_FORMAT,
373            Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
374            Self::Emissive => EMISSIVE_PAGE_FORMAT,
375        }
376    }
377
378    /// Every mip level below `level0`, built on the host with this kind's own
379    /// filter.
380    ///
381    /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
382    /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
383    /// weights by alpha. A normal map mipped through the colour filter leans
384    /// further off vertical at every level than the map it was built from, and
385    /// nothing in a frame reports it.
386    fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
387        match self {
388            Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
389            Self::Normal => crate::mip::normal_chain(level0, extent),
390            Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
391        }
392    }
393
394    /// The device label this kind's image is created under.
395    const fn upload_label(self) -> &'static str {
396        match self {
397            Self::BaseColor => "material base colour",
398            Self::Normal => "material normals",
399            Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
400            Self::Emissive => "material emissive",
401        }
402    }
403}
404
405/// The one texel a page **nothing names** is created with.
406///
407/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
408/// every bind group of the mesh layout has to fill both page bindings whether or
409/// not the description carried either page — so a [`PageKind`] with no layers
410/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
411/// nobody samples. That is the whole of what row (d) bought back:
412/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
413/// every scene in the tree that has no normal map used to carry a full neutral
414/// layer and a third again for its chain.
415///
416/// **Magenta, and it is never sampled for its value.** A material naming no page
417/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
418/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
419/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
420/// at all. So nothing should ever read this — and the value is chosen so that if
421/// something does, the frame says so in a colour no lit surface in this engine
422/// produces. White would blend into every untextured surface and black would
423/// read as a shadow; both are failures a golden could pass.
424const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
425
426/// The format the motion-vector target is created with: two channels of half
427/// float, topic 43 §9's third colour attachment.
428///
429/// **Named here rather than in [`crate::targets::motion`]**, on
430/// [`crate::graph`]'s other format-owning descriptions' terms: the description
431/// and
432/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
433/// pipeline is the one that owns the answer.
434///
435/// # The convention the target holds, so a consumer never has to guess it
436///
437/// **Current minus previous, in texture coordinates, `+y` down.** A pass
438/// holding the previous frame reads its history at `uv - motion`, and a surface
439/// travelling right and down the screen has both components positive.
440/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
441/// is the same sentence on the host side, because the first consumer will read
442/// one of the two and not both.
443///
444/// # Two channels and half float
445///
446/// A motion vector is a screen-space offset and has no third component. Half
447/// float rather than a normalised integer because the value is signed and
448/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
449/// — and because the interesting magnitudes are small: a surface moving a
450/// tenth of a pixel is the case a temporal filter is most sensitive to, and
451/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
452/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
453/// names motion vectors as the use for.
454pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
455
456/// Which picture the colour pass draws instead of the shaded one.
457///
458/// The engine's debug views, as one value rather than as independent booleans,
459/// because they are not independent: every one of them rides in a single lane of
460/// the frame's uniform block and the shaders test the thresholds outermost
461/// first, so a renderer with two of them set draws exactly one.
462/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
463/// answers with — so a menu row, a debug panel and the picture cannot disagree
464/// about which view is on.
465///
466/// **The declaration order is not the precedence** — each view was appended as
467/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
468/// decided. The sentinels in
469/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
470/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
471/// first.
472#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
473pub enum DebugView {
474    /// The lit picture. What every frame draws unless a caller asked otherwise.
475    #[default]
476    Shaded,
477    /// Each cluster shaded by the projected screen-space error the LOD
478    /// selection judged it on — [`ForwardRenderer::set_heatmap`].
479    Heatmap,
480    /// Each cluster tinted by the DAG level it was decimated to —
481    /// [`ForwardRenderer::set_lod_view`].
482    LodTint,
483    /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
484    Normals,
485    /// The ambient-occlusion channel alone, as grey —
486    /// [`ForwardRenderer::set_occlusion_view`].
487    AmbientOcclusion,
488    /// The motion vector each fragment wrote, stretched and centred on grey —
489    /// [`ForwardRenderer::set_motion_view`].
490    Motion,
491    /// The bent direction the occlusion channel carries beside its scalar, as
492    /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
493    /// every other view.**
494    BentNormal,
495    /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
496    /// atlas itself, letterboxed over the finished frame with a border round
497    /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
498    ///
499    /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
500    /// therefore the one whose lane is the off sentinel: the colour pass draws
501    /// the shaded picture exactly as it always did and `crate::atlas_view`
502    /// replaces it afterwards. That module's header is where the placement is
503    /// argued.
504    ///
505    /// It resolves **below every view above and above [`Self::Cascades`]** — see
506    /// [`ForwardRenderer::debug_view`].
507    ShadowAtlas,
508    /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
509    /// was sampled from, with the cross-fade band drawn as the blend of the two
510    /// — [`ForwardRenderer::set_cascade_view`].
511    ///
512    /// **Loses to every other view**, and it is the only one that does. The views
513    /// above draw something *instead of* the shaded picture; this one draws the
514    /// shaded picture and multiplies it, so there is nothing left for it to
515    /// modulate as soon as one of them is on. See
516    /// [`ForwardRenderer::debug_view`].
517    Cascades,
518}
519
520impl DebugView {
521    /// What a panel row or a summary line calls it.
522    #[must_use]
523    pub const fn label(self) -> &'static str {
524        match self {
525            Self::Shaded => "shaded",
526            Self::Heatmap => "heatmap",
527            Self::LodTint => "lod tint",
528            Self::Normals => "normals",
529            Self::AmbientOcclusion => "ambient occlusion",
530            Self::Motion => "motion",
531            Self::BentNormal => "bent normal",
532            Self::ShadowAtlas => "shadow atlas",
533            Self::Cascades => "cascades",
534        }
535    }
536}
537
538// Mesh-only resources follow the complete common fragment binding range.
539// Metal assigns dense native indices by resource-table order, so inserting a
540// mesh-only buffer before lights/probes would shift the layout away from the
541// independently compiled fragment stage. Sparse logical bindings cost no slots.
542const CLUSTERS_BINDING: u32 = 32;
543const CLUSTER_VERTICES_BINDING: u32 = 33;
544const CLUSTER_CORNERS_BINDING: u32 = 34;
545const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
546const CLUSTER_CULL_BINDING: u32 = 36;
547const CLUSTER_CULL_STATS_BINDING: u32 = 37;
548const CLUSTER_SELECT_BINDING: u32 = 38;
549const CLUSTER_SELECTION_BINDING: u32 = 39;
550const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
551
552/// The shared fragment shader's shadow atlas slot. Historical logical gaps
553/// remain reserved so the raster shader bindings stay unchanged.
554const SHADOW_ATLAS_BINDING: u32 = 15;
555
556/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
557const SHADOW_SAMPLER_BINDING: u32 = 16;
558
559/// The bind-group slot the base-colour page is bound to.
560///
561/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
562/// of the mesh layout, as it does each page's binding — see
563/// `pages::page_binding`.
564const BASE_COLOR_PAGE_BINDING: u32 = 7;
565
566/// The bind-group slot the base-colour page's sampler is bound to.
567///
568/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
569/// in every group of the mesh layout: a sampler is a resource a group holds by
570/// handle, so a new sampler is a new group, and the rebuild finds the entry by
571/// this number.
572const PAGE_SAMPLER_BINDING: u32 = 8;
573
574/// The shared fragment shader's light list. Both shader modules declare it
575/// before mesh-only buffers so native buffer index 7 is common to both stages.
576const LIGHT_LIST_BINDING: u32 = 20;
577
578/// The bind-group slot the froxel grid is read through.
579const LIGHT_GRID_BINDING: u32 = 21;
580
581/// The fragment shader's screen-space occlusion texture. Mesh-only additions
582/// are buffers, so this resource does not shift their native argument table.
583const AMBIENT_OCCLUSION_BINDING: u32 = 22;
584
585/// The shared irradiance probe table, native buffer 9 in both shader modules.
586/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
587const PROBE_TABLE_BINDING: u32 = 23;
588
589/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
590/// Its logical binding stays 24; after the shared fragment buffer prefix it is
591/// native buffer 10. The raster path does not declare this storage buffer.
592const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
593
594/// The bind-group slot the split-sum `DFG` table is fetched through — how much
595/// of the light arriving at a GGX lobe that lobe hands back.
596///
597/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
598/// after the shared prefix. The fragment shader's `specular_dfg` remains at
599/// native texture 3, following `ambient_occlusion` at texture 2.
600///
601/// **An image rather than a storage buffer, and that is forced.** The table is
602/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
603/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
604/// Metal backend materialises every global into every entry point — so a row
605/// bound to the fragment stage alone would be a global the vertex stage names
606/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
607/// binding 7's `geometry` visibility.
608const SPECULAR_DFG_BINDING: u32 = 25;
609
610/// The bind-group slot §2's normal page is sampled through.
611///
612/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
613/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
614/// next index in its Metal argument table by counting the same-table entries of
615/// this layout, and Slang numbers a stage's arguments by declaration order, so
616/// the two agree only while both ascend. No mirror is needed in
617/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
618///
619/// **No sampler of its own.** The page is read through
620/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
621/// base-colour page uses, because it is sampled at the same UV over an image of
622/// the same extent. A second sampler would be a second layout entry, a second
623/// index in Metal's sampler argument table, and a second thing
624/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
625/// be identical.
626const NORMAL_PAGE_BINDING: u32 = 26;
627
628/// The bind-group slot topic 44's rung 5 reads its linearly
629/// transformed cosine table through.
630///
631/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
632/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
633/// Metal argument table by counting the same-table entries of this layout, and
634/// Slang numbers a stage's arguments by declaration order, so the two agree only
635/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
636/// needs no mirror there and no index anything already owns moves.
637///
638/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
639/// blend written out in the shader, because a hardware filter's weights are
640/// fixed-function arithmetic four rasterisers compute independently and these
641/// goldens are compared across all four.
642const LTC_TABLE_BINDING: u32 = 27;
643
644/// The bind-group slot topic 45's contact-shadow channel is
645/// read through.
646///
647/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
648/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
649/// argument table by counting the same-table entries of this layout, and Slang
650/// numbers a stage's arguments by declaration order, so the two agree only while
651/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
652/// no mirror there and no index anything already owns moves.
653///
654/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
655/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
656/// the frame on every pass that computed one.
657const CONTACT_SHADOW_BINDING: u32 = 28;
658
659/// The bind-group slot the irradiance probes' per-probe
660/// visibility maps are read through: one `Rg32Float` layer per probe.
661///
662/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
663/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
664/// Metal argument table by counting the same-table entries of this layout, and
665/// Slang numbers a stage's arguments by declaration order, so the two agree only
666/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
667/// needs no mirror there and no index anything already owns moves —
668/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
669///
670/// **A texture rather than a storage buffer, and that is forced**: the raster
671/// path's vertex stage is already at every storage buffer a WebGPU device
672/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
673///
674/// **No sampler**, like the occlusion channel and both cooked tables:
675/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
676/// out, because a hardware filter's weights are fixed-function arithmetic four
677/// rasterisers compute independently — and because `Rg32Float` is not a
678/// filterable format on WebGPU without an optional feature.
679const PROBE_VISIBILITY_BINDING: u32 = 29;
680
681/// The bind-group slot topic 43 §2's packed
682/// **metallic-roughness-occlusion** page is sampled through.
683///
684/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
685/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
686/// next index in its Metal argument table by counting the same-table entries of
687/// this layout, and Slang numbers a stage's arguments by declaration order, so
688/// the two agree only while both ascend. No mirror is needed in
689/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
690///
691/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
692/// read at the same UV over an image of the same shape as the base-colour one,
693/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
694/// Metal's sampler argument table.
695const MRO_PAGE_BINDING: u32 = 30;
696
697/// The bind-group slot topic 43 §2's **emissive**
698/// page is sampled through.
699///
700/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
701/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
702/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
703/// mirror there and no index anything already owns moves.
704const EMISSIVE_PAGE_BINDING: u32 = 31;
705
706/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
707///
708/// The table is square, and its size is a compile-time constant, so the
709/// conversion belongs here rather than as a fallible one at the upload.
710const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
711
712/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
713///
714/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
715/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
716/// what says the two tables are the same square, and each upload naming its own
717/// module is what would make a day they were not into a compile error here
718/// rather than a stretched image.
719const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
720
721/// [`crcbl_shaders::sky_prefilter::PREFILTER_SIZE`] as an image extent, on
722/// [`DFG_SIZE_U32`]'s terms.
723const SKY_PREFILTER_SIZE_U32: u32 = sky_prefilter::PREFILTER_SIZE as u32;
724
725/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
726///
727/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
728/// what `mesh.slang` reads on a frame drawing without
729/// [`RenderEffects::AMBIENT_OCCLUSION`].
730///
731/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
732/// this and the term is untouched. Any other value would be a silent global
733/// ambient scale.
734///
735/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
736/// direction** — the sentinel the occlusion chain writes wherever it has no
737/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
738/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
739/// direction at this pixel" are one case with one answer, and a frame drawn
740/// with the effect off is the frame this renderer drew before the channel was
741/// widened. Encoding a direction here instead would tilt every ambient term in
742/// such a frame towards one world axis.
743const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
744    0xFF,
745    ssao::BENT_NORMAL_NONE,
746    ssao::BENT_NORMAL_NONE,
747    ssao::BENT_NORMAL_NONE,
748];
749
750/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
751///
752/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
753/// what `mesh.slang` reads on a frame drawing without
754/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
755/// and the cascades have the last word alone. Any other value would be a silent
756/// global scale on the sun.
757///
758/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
759/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
760/// placeholders stand for different facts, and a day one of them wanted a
761/// different value should be an edit here rather than a search for which
762/// callers of a shared name meant which thing.
763const CONTACT_SHADOW_NONE: u8 = 0xFF;
764
765/// The one `Rg32Float` texel that occludes nothing: a mean distance of
766/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
767/// square.
768///
769/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
770/// what `mesh.slang` reads on a frame drawn before anything was captured or with
771/// `r_probe_visibility` off. No surface in any scene is further away than that,
772/// so `probe_weight` answers one for every probe and every fragment, and the
773/// grid is the unweighted trilinear blend it was before this rung — which is
774/// what makes the off position bit-identical rather than merely close.
775///
776/// Any *smaller* value would be a silent occluder: every probe in every scene
777/// would read as being behind a wall, and the whole grid would collapse onto
778/// `PROBE_OCCLUDED_WEIGHT`.
779fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
780    let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
781    let far = crcbl_shaders::probe_visibility::FAR;
782    texel[..4].copy_from_slice(&far.to_le_bytes());
783    texel[4..].copy_from_slice(&(far * far).to_le_bytes());
784    texel
785}
786
787/// The reversed-Z far plane, in the two places that have to agree about it.
788///
789/// `ssao.slang` leaves early at exactly this depth because the unprojection there
790/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
791/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
792/// the mirror is checked here — which is the only place both names are in scope.
793const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
794
795/// How many buckets a resident mesh occupies, which is **not the same on every
796/// geometry path** — the one place in this renderer the two differ in shape
797/// rather than in the call they record.
798///
799/// A flat mesh is one bucket either way. A DAG is one bucket on
800/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
801/// topic 25's per-cluster selection is that one dispatch covers
802/// several levels at once, so the run is every level's clusters end to end and
803/// the bucket's mesh id is level 0's.
804///
805/// On the two indirect tails a DAG is one bucket **per level**, because there
806/// the same plan takes a uniform cut and a level is drawn as an ordinary index
807/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
808/// selects one per instance, and a bucket is what an indexed draw of one index
809/// range *is*. See [`ForwardRenderer::level_buckets`].
810const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
811    if emit.is_mesh() { 1 } else { levels }
812}
813
814/// Every material mode this renderer routes a draw by, and the order the bucket
815/// table lays its per-mode runs of every mesh's levels down in.
816///
817/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
818/// the routing is total rather than checked: a row's mode is
819/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
820/// double-sided one, and the four combinations of them are these — so no
821/// material can carry a mode that is not in this list and no instance can
822/// scatter into a bucket that does not exist. Widening the mask means adding the
823/// mode here **and** giving it a depth pipeline in
824/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
825/// producer and the consumer of one list.
826///
827/// **A scene emits a twin per mode its own materials carry**, not one per
828/// entry here: two materials of two modes are two twins whichever two they are,
829/// and only a scene actually holding all four pays for four. The build below is
830/// where that filter is, and this module's
831/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
832const DEPTH_MODES: [u32; 4] = [
833    0,
834    mesh::GpuMaterial::ALPHA_MODE_MASK,
835    mesh::GpuMaterial::DOUBLE_SIDED,
836    mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
837];
838
839/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
840/// draw single-sided and double-sided buckets of one frame.
841///
842/// **A pipeline rather than a per-draw state, because no backend seam exposes
843/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
844/// is the precedent for why one would not be added: a raster state a recorded
845/// stream carried per draw is a state every backend has to be able to change
846/// between two indirect calls, and the portable answer to "this draw rasterises
847/// differently" is a second pipeline. Which draws take which is
848/// [`ForwardRenderer::sided_partitions`].
849///
850/// Four passes need the pair — the colour pass, the two depth-only ones and the
851/// reflective shadow map — so it is a type rather than eight fields.
852///
853/// **The twin exists only where the scene can draw with it.** A bucket table is
854/// fixed at build, from the modes the description's materials carry (see
855/// [`ForwardRenderer::bucket_modes`]), and nothing adds a material afterwards;
856/// so `build` knows then whether any bucket will ever be double-sided, and
857/// compiles the twin for that scene alone. Each twin is a cold compile as long
858/// as the pipeline it twins.
859///
860/// [`ForwardRenderer::partitions`] is what makes an unbuilt twin unbindable:
861/// it takes each pipeline as an [`Option`], so there is no handle to record
862/// for one that was never compiled, and a partition with draws in it and no
863/// pipeline is a panic rather than a bind.
864#[derive(Clone, Copy, Debug, PartialEq, Eq)]
865struct SidedPipelines {
866    /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
867    /// every bucket of every scene that does not use `doubleSided`.
868    single: GraphicsPipelineHandle,
869    /// [`CullMode::None`]: the buckets whose material carries
870    /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED), and
871    /// [`None`] for a scene with no such bucket.
872    double: Option<GraphicsPipelineHandle>,
873}
874
875impl SidedPipelines {
876    /// Both halves, single-sided first, for a pass to hand
877    /// [`ForwardRenderer::partitions`] — keyed by the
878    /// [`DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED) bit.
879    fn by_side(self) -> [(u32, Option<GraphicsPipelineHandle>); 2] {
880        [
881            (0, Some(self.single)),
882            (mesh::GpuMaterial::DOUBLE_SIDED, self.double),
883        ]
884    }
885
886    /// Every pipeline this holds, for a release.
887    fn handles(self) -> impl Iterator<Item = GraphicsPipelineHandle> {
888        std::iter::once(self.single).chain(self.double)
889    }
890}
891
892/// The pixel budget topic 25's descent compares a group's projected
893/// error against, unless a caller sets another with
894/// [`ForwardRenderer::set_lod_error_budget`].
895///
896/// One pixel, because that is what the metric is *for*: a level's error is how
897/// far its simplification may have moved the surface, so a budget of a pixel is
898/// the point at which a level change stops being something a viewer can see.
899/// The plan's "correct thresholds make pops sub-pixel by definition" is this
900/// number.
901const LOD_ERROR_BUDGET: f32 = 1.0;
902
903/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
904/// it holds.
905///
906/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
907/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
908/// because which one a bucket holds is the geometry path's decision and the
909/// buffer, its dynamic stride and the range the bind group names are all fixed
910/// before that decision reaches them.
911///
912/// **The bound range is the half that bites.** A range sized for the smaller
913/// block leaves the larger one's tail outside it, and a uniform read past the
914/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
915/// path's `group_stride` read back as zero and every instance descended against
916/// instance zero's LOD state.
917const DRAW_CONSTANTS_BLOCK: u64 =
918    if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
919        mesh::DRAW_CONSTANTS_SIZE as u64
920    } else {
921        crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
922    };
923
924/// How far below the budget an already-expanded group is held before it
925/// collapses again — topic 25's "switch-up and switch-down differ",
926/// as a fraction of [`LOD_ERROR_BUDGET`].
927///
928/// A ratio and not an offset because the band has to scale with the budget: a
929/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
930/// one. A fifth of the budget is a deadband a camera has to move decisively out
931/// of, and one a camera drifting along a boundary never leaves — which is the
932/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
933/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
934/// the setting that shows the band is what stops the flicker.
935const LOD_HOLD_RATIO: f32 = 0.8;
936
937/// How much larger than the camera's the pixel budget a shadow cascade selects
938/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
939/// selects +1/+2 coarser levels — casters are cheap where it never shows".
940///
941/// # A budget factor, because a level is not a parameter of the rule
942///
943/// The descent compares a group's projected error to a pixel budget; it never
944/// names a level. So "one or two levels coarser" is an *intent*, and the budget
945/// that produces it is the setting — and the two do not convert, because how far
946/// apart two levels' errors are is a property of the mesh. The committed dunes
947/// DAG is the demonstration: the step from one level's error to the next is
948/// several times larger in the middle of that hierarchy than at its base, and
949/// across its top levels there is no step at all — they report one error and are
950/// never separately selected by any budget. A bias expressed in levels would
951/// mean something different at each of those. `cook-clusters` prints the per
952/// level errors it built.
953///
954/// Four, then, is two doublings of the budget: enough that a caster is drawn
955/// coarser than the same object is in the colour pass, and small enough to stay
956/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
957/// the atlas is read through a comparison sampler with linear filtering, so an
958/// edge arrives already spread over neighbouring texels — and that the atlas
959/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
960/// samples it.
961///
962/// # Why one number, applied to the whole pass
963///
964/// **A cut is a cover only while expansion is monotone up the DAG**, and this
965/// scaling is what keeps it so. Multiplying both budgets by one positive
966/// constant leaves the rule in
967/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
968/// that module's induction turns on the projected error being monotone up the
969/// DAG rather than on what the constants are — so the shadow pass's cut is a
970/// cover for exactly the reason the camera's is. A bias that varied by cluster,
971/// by group, by level or by cascade would not be: two groups on one branch would
972/// be judged against different budgets, and a child expanding under an
973/// unexpanded parent is a hole.
974///
975/// Being larger than one also makes the shadow pass's expanded set a **subset**
976/// of the colour pass's, since the two now select from one eye at one scale: a
977/// group over `k` times the budget is over the budget. So the shadow cut is
978/// never finer than the camera's anywhere, which is the property
979/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
980/// and asserts.
981pub const SHADOW_LOD_BIAS: f32 = 4.0;
982
983/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
984/// light**, whatever kind of light it is.
985///
986/// Topic 18's fourth decision, as a number. A point light's six faces share the
987/// light's sphere — which is what a cull tests against — so they share one
988/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
989/// viewport. Six generators per light would be six copies of
990/// [`TileBuffers::group_state`], which is where the cost of one is written down.
991const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
992
993/// How many shadow *views* there are: one per cascade, and one per face of every
994/// light slot.
995///
996/// A view is what has a matrix, so it is what has a frame-block copy, a bind
997/// group and a cut of its own — while a *tile* is where a view lands in the
998/// atlas and a *cull* is which visible set it draws. The three were one number
999/// until a light could own six tiles.
1000///
1001/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
1002/// point or a spot, because a bind group names its buffers when it is created
1003/// and the kind of light holding a slot changes per frame. A spot uses face 0's
1004/// view and the other five are never recorded — they cost a uniform buffer and a
1005/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
1006/// would cost.
1007const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
1008
1009/// Cascade 0's view, which is the one the irradiance probes'
1010/// reflective shadow map is drawn through.
1011///
1012/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
1013/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
1014/// [`shadow::CASCADES`], so it is not the function to reach for here.
1015const CASCADE_ZERO_VIEW: usize = 0;
1016
1017const _: () = assert!(
1018    CASCADE_ZERO_VIEW < shadow::CASCADES,
1019    "cascade 0's view has to be one of the cascades' own, not a light slot's"
1020);
1021
1022/// Which view is face `face` of light slot `slot`.
1023const fn shadow_view(slot: usize, face: usize) -> usize {
1024    shadow::CASCADES + slot * shadow::POINT_FACES + face
1025}
1026
1027/// Which cull light slot `slot` draws from.
1028const fn shadow_cull(slot: usize) -> usize {
1029    shadow::CASCADES + slot
1030}
1031
1032/// One punctual shadow face this frame draws into the punctual reflective
1033/// shadow map, and everything both halves of the updater need of it.
1034///
1035/// The irradiance probes' punctual producer. It carries no
1036/// matrix and no visible set: a face's transform is already in the uniform block
1037/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
1038/// slot's cull generated for the atlas — which is what makes this rung cost no
1039/// second cull and no second matrix.
1040#[derive(Clone, Copy, Debug)]
1041struct PunctualFace {
1042    /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1043    /// of the bind group whose block holds that face's own `view_proj`.
1044    view: usize,
1045    /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1046    /// answer for the slot this face belongs to.
1047    cull: usize,
1048    /// Which face of its light this is, and so — where the light's cull tagged
1049    /// its casters by face — which draw region it draws.
1050    face: usize,
1051    /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1052    /// rectangle the pass sets its viewport to *and* the one the gather reads
1053    /// this face's texels out of.
1054    tile: shadow::TileRect,
1055    /// The light this is a face of, as the gather weighs its texels.
1056    producer: PunctualProducer,
1057}
1058
1059/// The draw region face `face` of a light draws: its own region where the
1060/// light's cull tagged casters by face, and region 0 — every survivor — where it
1061/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1062fn face_region(by_face: bool, face: usize) -> u32 {
1063    if by_face {
1064        crcbl_shaders::draw_gen::FACE_REGION_BASE
1065            + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1066    } else {
1067        0
1068    }
1069}
1070
1071/// One light's row in the gather's producer table, for the face standing at
1072/// `tile`.
1073///
1074/// **Built out of the light's own row**, which is the one place a light becomes
1075/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1076/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1077/// than a second reading of the same fields that could round or widen
1078/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1079/// because a producer occludes through nothing: the gather gates a texel with
1080/// the probe's own visibility map, not with the light's.
1081fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1082    let row = light.row(None);
1083    PunctualProducer {
1084        position: [row.position[0], row.position[1], row.position[2]],
1085        radius: row.position[3],
1086        color: [row.color[0], row.color[1], row.color[2]],
1087        cos_outer: row.direction[3],
1088        axis: [row.direction[0], row.direction[1], row.direction[2]],
1089        cos_inner: row.cos_inner,
1090        origin: [tile.x, tile.y],
1091        side: tile.side,
1092        kind: row.kind,
1093    }
1094}
1095
1096const _: () = assert!(
1097    SHADOW_CULLS == shadow::GROUPS,
1098    "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1099     dispatches, and two different counts would schedule a group nothing draws"
1100);
1101
1102/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1103/// generates from `SV_VertexID`. No geometry is bound.
1104const TILE_CLEAR_VERTICES: u32 = 3;
1105
1106const _: () = assert!(
1107    crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1108    "the stage that resets one tile writes a depth the attachment's own clear \
1109     does not, so a held tile and a cleared one would answer differently where \
1110     nothing was drawn"
1111);
1112
1113/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1114///
1115/// The rectangle the allocator handed out — the same one the fragment stage
1116/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1117/// the whole atlas before the pass body ran, and this is what narrows it: the
1118/// same clip-space matrix mapped into a different part of the image, and for a
1119/// point light six different matrices into six of them off one visible set.
1120///
1121/// A function rather than the two calls inline, because the tile clear and the
1122/// draws that follow it walk the same tiles and a viewport set one way for one
1123/// of them would clear a rectangle nothing draws into.
1124fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1125    let rect = Rect2d {
1126        x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1127        y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1128        width: tile.side,
1129        height: tile.side,
1130    };
1131    encoder.set_viewport(&Viewport {
1132        x: rect.x as f32,
1133        y: rect.y as f32,
1134        width: rect.width as f32,
1135        height: rect.height as f32,
1136        ..Viewport::from_size(rect.width, rect.height)
1137    });
1138    encoder.set_scissor(&rect);
1139}
1140
1141/// What the last executed graph left the renderer-owned import `image` in, as an
1142/// [`ImportedImage::initial`].
1143///
1144/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1145/// fallback around one.** The ledger records what a graph *executed*, so nothing
1146/// recorded means nothing has run against this image on this pool — a freshly
1147/// created image before its first frame, and an image whose pool has been
1148/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1149/// barrier has moved is in. It is also the only declaration that lets the
1150/// incoming barrier hand the image a layout at all: every other state names an
1151/// old layout the image is not in.
1152///
1153/// The reason this is a lookup and not a field the renderer advances: a graph is
1154/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1155/// stepped forward while the passes were declared would have moved for a frame
1156/// that never reached the GPU, and the next frame's declaration — now wrong —
1157/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1158/// it through. One source of truth is what removes that gap rather than
1159/// narrowing it.
1160fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1161    pool.imported_image_use(image)
1162        .unwrap_or(ResourceState::Undefined)
1163}
1164
1165/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1166/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1167/// the debug draw layer, the tonemap, the ground grid and the
1168/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1169/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1170/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1171///
1172/// [`AtlasView::PASSES`] has no term of its own and is inside
1173/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1174/// viewer and the resolve are never both recorded.
1175///
1176/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1177/// ground grid's terms: all three are off unless a scene's
1178/// [`ProbeUpdate`] asks for them, and a bound short
1179/// of the frame that does ask would silently stop timing its last pass. The
1180/// punctual map is a pass whether or not the frame has a punctual light to draw
1181/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1182/// gather reads on a frame that lights none.
1183///
1184/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1185/// [`LightGrid`], which is why this is the only count written here rather than
1186/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1187/// though a device that refused the readback records one fewer: this is a
1188/// ceiling, and one that came up short would silently stop timing the last pass
1189/// of every frame. It is the **all-effects-on** count for the same reason: a
1190/// frame that switched one off records fewer, and a bound that tracked the
1191/// toggles would have to be re-sized whenever they moved.
1192///
1193/// The ground grid is counted on the same terms, even though it is off by
1194/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1195/// records one more pass, and a bound short of that would silently stop timing
1196/// the last pass of every frame it drew. The render-scale upscale is the second
1197/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1198/// therefore absent until a caller moves it. The debug draw layer is the third,
1199/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1200///
1201/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1202/// counts**: a chain's length is a function of the target's extent — see
1203/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1204/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1205/// either an extent or a console is known. The frame that lands on
1206/// it is a large one with bloom switched on; every smaller frame records fewer,
1207/// exactly as a frame with a free shadow slot does.
1208const RENDER_PASSES: u32 = 8
1209    // The occlusion cull's late depth prepass and its farthest pyramid, on the
1210    // ground grid's terms: off unless a caller switches the cull on.
1211    + 1
1212    + OcclusionPyramid::PASSES
1213    + DebugDraw::MAX_PASSES
1214    + ProbeGather::PASSES
1215    + Ssao::MAX_PASSES
1216    + ContactShadows::PASSES
1217    + Hiz::PASSES
1218    + Ssr::PASSES
1219    + Volumetric::PASSES
1220    + Water::PASSES
1221    + Grass::PASSES
1222    + Exposure::PASSES
1223    + Bloom::MAX_PASSES
1224    + POST_TONEMAP_PASSES
1225    + Upscale::PASSES;
1226
1227/// What the frame's one resolve slot costs at its widest: the larger of the two
1228/// antialiasing tiers.
1229///
1230/// **The larger and not the sum**, because the two are never both recorded —
1231/// [`RenderEffects::CMAA2`] carries that in writing and
1232/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1233/// all-effects-on count as well as the ceiling, which is the property
1234/// [`RENDER_PASSES`] needs from every term it adds up.
1235///
1236/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1237const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1238    Fxaa::PASSES
1239} else {
1240    Cmaa2::PASSES
1241};
1242
1243/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1244/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1245/// filtering it.
1246///
1247/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1248/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1249/// antialiasing tiers off for every debug view, and the atlas viewer records
1250/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1251/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1252/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1253/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1254/// is what holds the arithmetic to a frame that was actually recorded.
1255const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1256    RESOLVE_PASSES
1257} else {
1258    AtlasView::PASSES
1259};
1260
1261/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1262///
1263/// The smallest fraction of the target extent a frame may be drawn at.
1264///
1265/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1266/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1267/// stops being a picture of the scene and starts being a picture of the filter,
1268/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1269/// engine's resolution slider bottoms out somewhere; this is where this one
1270/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1271/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1272/// draw.
1273pub const MIN_RENDER_SCALE: f32 = 0.25;
1274
1275/// The anisotropy the base-colour page is sampled with where the device grants
1276/// [`Features::SAMPLER_ANISOTROPY`].
1277///
1278/// Eight, which is topic 43's filtering rung's
1279/// default and the figure current engines default their own slider to: past it
1280/// the footprint's long axis is already sampled finely enough that sixteen is
1281/// invisible at a grazing angle and costs the same again in fetches. A device
1282/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1283/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1284/// device without the feature gets one, which is the value that turns it off.
1285pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1286
1287/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1288/// because these are the only draws in this file whose instance and triangle
1289/// counts the CPU knows exactly — everything else here goes through an indirect
1290/// call.
1291const FULLSCREEN_DRAWS: u64 = 1;
1292
1293/// How many full-screen passes a frame drawing `effects` at `extent` records:
1294/// the tonemap, always, and each switched-on effect's passes beside it.
1295///
1296/// **A function of the frame rather than a constant**, since
1297/// topic 48's toggles: it was the tonemap alone, then
1298/// five, and either written down is a number that stops matching the frame. The
1299/// tonemap is the one that is not conditional — a frame has to reach the
1300/// swapchain.
1301///
1302/// **`extent` is here because the bloom chain's length depends on it** — see
1303/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1304/// size. A frame too small for even one chain level records none of them, which
1305/// is the same arithmetic as the toggle being off. It is the **internal** render
1306/// extent for the same reason: that is the extent every one of these passes runs
1307/// at.
1308///
1309/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1310/// resolution, not an effect — so it arrives as its own argument, on the ground
1311/// grid's terms. It is false on every frame at full render scale, which is the
1312/// frame this function counted before the knob existed.
1313///
1314/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1315/// variable rather than an effect bit, and it is the caller's job to read it
1316/// **once** for the frame. Reading it here as well would be a second read that
1317/// a command landing between the two could disagree with, and the disagreement
1318/// would be a counter describing a frame that was not recorded.
1319fn fullscreen_passes(
1320    effects: RenderEffects,
1321    extent: (u32, u32),
1322    upscaling: bool,
1323    ssao_blurs: u32,
1324) -> u64 {
1325    let mut passes = 1;
1326    if upscaling {
1327        passes += Upscale::PASSES as u64;
1328    }
1329    if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1330        passes += u64::from(Ssao::passes(ssao_blurs));
1331    }
1332    if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1333        passes += u64::from(ContactShadows::PASSES);
1334    }
1335    if effects.contains(RenderEffects::REFLECTIONS) {
1336        // The march's pair, and the pyramid it climbs — which is as long as the
1337        // extent allows and is zero on a frame too small to halve once, so this
1338        // term is the only one here that is not a constant per effect.
1339        passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1340    }
1341    if effects.contains(RenderEffects::BLOOM) {
1342        passes += u64::from(Bloom::passes_for(extent));
1343    }
1344    // **One resolve slot, and the higher tier takes it.** Both bits set is a
1345    // frame with CMAA2's passes and no FXAA pass at all, which is what
1346    // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1347    // an `else if` rather than two independent terms.
1348    //
1349    // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1350    // function counts is full-screen *draws*, and two of that tier's three
1351    // passes are compute dispatches. [`crate::exposure`]'s three are left out
1352    // of this arithmetic for the same reason.
1353    if effects.contains(RenderEffects::CMAA2) {
1354        passes += Cmaa2::FULLSCREEN_PASSES;
1355    } else if effects.contains(RenderEffects::ANTIALIASING) {
1356        passes += Fxaa::PASSES as u64;
1357    }
1358    if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1359        // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1360        // scatter and the column scan are compute dispatches; what this
1361        // function counts is full-screen *draws*, and only the composite is
1362        // one. An atmosphere runs the composite without the effect, and the
1363        // caller adds that one — it is not an effect bit.
1364        passes += u64::from(Volumetric::COMPOSITE_PASSES);
1365    }
1366    // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1367    // entry here: all three of its passes are compute dispatches, and the
1368    // exposure they measure reaches the picture through the tonemap's own draw.
1369    passes
1370}
1371
1372/// The budget an **orthographic** camera selects under: one no group satisfies,
1373/// so every group expands and the base level is drawn whole.
1374///
1375/// The metric divides a projected error by the distance to the group's sphere,
1376/// and an orthographic projection has no such falloff — see
1377/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1378/// Drawing the finest level is the conservative answer and the honest one; a
1379/// distance term invented for a projection that has none would be neither.
1380///
1381/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1382const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1383
1384/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1385/// [`SkinnedMesh`] where the description's mesh index would be.
1386///
1387/// The mesh is a reservation rather than an index because a skinned draw is not
1388/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1389/// fills, and which of the reservation's two runs that is changes every frame.
1390/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1391/// here carries a parity.
1392#[derive(Clone, Copy, Debug)]
1393pub struct SkinnedInstanceDesc<'a> {
1394    /// The region this object is drawn out of, from
1395    /// [`ForwardRenderer::reserve_skinned`].
1396    pub mesh: &'a SkinnedMesh,
1397    /// Which [`SceneDesc::materials`] row it shades through, exactly as
1398    /// [`InstanceDesc::material`].
1399    pub material: usize,
1400    /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1401    ///
1402    /// The joints are **not** in it — a palette carries each joint's global
1403    /// transform times its inverse bind matrix, and this is what puts the
1404    /// deformed mesh in the world. See
1405    /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1406    pub transform: Mat4,
1407    /// A **model-space** box around every pose this object will be drawn in
1408    /// until it is next set, in the space [`transform`](Self::transform)
1409    /// carries into the world — or `None`, which keeps it in every cull.
1410    ///
1411    /// **`None` is the safe default and the costly one.** The region's source
1412    /// mesh's box is its bind pose, which says nothing about where a skinning
1413    /// dispatch moves the vertices, so an object without a box of its own is
1414    /// drawn by every camera and every shadow map wherever it is. With one, the
1415    /// frustum culls, the occlusion culls and the shadow cache's footprints
1416    /// test it exactly as they test a rigid mesh's box. **The box has to
1417    /// contain every vertex the palette can put anywhere**: a cull that finds
1418    /// it outside drops the whole object, so a box that misses part of a pose
1419    /// can make an object vanish while that part is on screen.
1420    /// [`ForwardRenderer::set_skinned_bounds`] moves it each frame, for a pose
1421    /// — a ragdoll — that travels far from the object's origin.
1422    ///
1423    /// Every corner must be finite and `min` must not exceed `max` on any
1424    /// axis. An inverted or non-finite box is refused rather than written,
1425    /// because the culls would read it as a box nothing reaches and drop the
1426    /// object everywhere — see [`InstancePoolError::InvalidBounds`].
1427    pub bounds: Option<Aabb>,
1428}
1429
1430/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1431///
1432/// **The two projections are cached beside the LUT rather than taken per
1433/// frame**, which is what makes a frame under a sun that has not moved do no
1434/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1435/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1436/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1437/// rows per frame, because those are writes into the frame's own ring slots
1438/// rather than projections.
1439#[derive(Clone, Debug)]
1440struct PresentedSky {
1441    /// The normalised sun and viewpoint the LUT was marched for, which is what
1442    /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1443    /// against.
1444    parameters: crcbl_shaders::atmosphere::Atmosphere,
1445    /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1446    /// samples.
1447    view: SkyView,
1448    /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1449    /// pass's block carries.
1450    gradient: crcbl_shaders::sky::SkyGradient,
1451    /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1452    irradiance: crcbl_shaders::probe::GpuProbe,
1453}
1454
1455impl PresentedSky {
1456    /// Takes both projections from a LUT that has just been marched.
1457    fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1458        Self {
1459            parameters,
1460            gradient: view.gradient_fit(),
1461            irradiance: view.irradiance(),
1462            view,
1463        }
1464    }
1465}
1466
1467/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1468/// secondary view begun after it writes its blocks against the same sun, light
1469/// rows and shadow matrices the primary camera's were written against.
1470///
1471/// Everything here is decided by the primary camera and drawn once: the rows
1472/// carry the shadow tiles the primary camera's selection handed out, and the
1473/// cascades are fitted to its frustum. A secondary view samples the maps those
1474/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1475#[derive(Clone, Debug)]
1476struct FrameScene {
1477    light: DirectionalLight,
1478    rows: Vec<crcbl_shaders::light::GpuLight>,
1479    cascades: Cascades,
1480    shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1481    light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1482    atlas_rects: [[f32; 4]; shadow::TILES],
1483}
1484
1485/// The bucket and level tables a scene's generators are all built from, kept
1486/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1487/// returned.
1488#[derive(Debug)]
1489struct DrawTables {
1490    bucket_meshes: Vec<u32>,
1491    bucket_clusters: Vec<u32>,
1492    bucket_cluster_bases: Vec<u32>,
1493    mesh_levels: Vec<level_select::MeshLevels>,
1494    level_groups: Vec<level_select::LevelGroup>,
1495    level_meshes: Vec<u32>,
1496    instance_capacity: u32,
1497    light_capacity: u32,
1498}
1499
1500/// The primary frame attachments an overlay may use before antialiasing and
1501/// render-scale reconstruction.
1502///
1503/// `display` is the display-space image the tonemap and post-tonemap overlays
1504/// have written. `depth` is the matching internal scene depth image, retained
1505/// as a read-only attachment for depth-tested overlays. Both have
1506/// `internal_extent` dimensions.
1507#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1508pub struct ForwardOverlayTargets {
1509    pub display: ImageId,
1510    pub depth: ImageId,
1511    pub internal_extent: (u32, u32),
1512}
1513
1514/// Everything the forward frame owns, created once.
1515#[derive(Debug)]
1516pub struct ForwardRenderer {
1517    // Geometry: the global pools, and the meshes resident in them. Each
1518    // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1519    // for a mesh whose upload has completed — so there is no way to reach a
1520    // draw below with a mesh the GPU has not received.
1521    pool: MeshPool,
1522    /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1523    /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1524    /// [`buckets_for`] says is a property of the path as well as of the scene.
1525    ///
1526    /// **The whole of what the CPU still says per draw.** Everything else a
1527    /// draw needs — how many instances, which indices, which vertices — is in
1528    /// the arguments the GPU wrote or in a table it resolves them through.
1529    bucket_constants: Vec<u32>,
1530    /// What one draw region adds to a bucket's offsets — the same for every
1531    /// generator this renderer built, because they share one bucket table.
1532    region_step: RegionStep,
1533    /// The material mode of each bucket, in the same order — the copy the
1534    /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1535    /// against.
1536    ///
1537    /// What it is for: the depth prepass and the shadow atlas partition their
1538    /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1539    /// scene with a cutout in it keeps the vertex-only stage. See
1540    /// [`ForwardRenderer::depth_partitions`].
1541    ///
1542    /// All zeroes for a scene whose materials are all opaque — every demo and
1543    /// every golden in this tree — which is exactly one bucket per mesh and one
1544    /// partition, byte for byte the stream they recorded before modes existed.
1545    bucket_modes: Vec<u32>,
1546
1547    // The instance array, and the objects' places in it. Nothing here is
1548    // rewritten per frame: the pool uploads what a caller changed and nothing
1549    // else, so a scene nobody moved costs no transfer at all.
1550    instances: InstancePool,
1551    /// The mesh table id of each description mesh's **level 0**, in
1552    /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1553    /// resolves through.
1554    ///
1555    /// Level 0's and not the whole run, because that is the entry an instance
1556    /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1557    /// levels approximate the same surface inside the same box. The coarser
1558    /// entries are resident and no instance names one — a cluster reaches its
1559    /// own level's vertices through
1560    /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1561    /// uniform cut reaches them through the bucket table.
1562    ///
1563    /// Kept rather than resolved per call because every write of an instance
1564    /// writes the whole record, and an instance that lost its mesh id would
1565    /// resolve to entry 0 — which is a mesh, and the wrong one.
1566    mesh_ids: Vec<u32>,
1567    /// Level 0's pool handle for each description mesh that can be skinned, in
1568    /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1569    /// [`ResidentMesh::skinnable`].
1570    ///
1571    /// What [`ForwardRenderer::reserve_skinned`] resolves an
1572    /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1573    /// there is no way back from a table id to the handle that owns it: an id is
1574    /// a bare index and a [`MeshHandle`] is generational.
1575    skinnable_meshes: Vec<Option<MeshHandle>>,
1576    /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1577    /// two base vertices it alternates between.
1578    ///
1579    /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1580    /// at the half of its region *this* frame's dispatch fills. Entries whose
1581    /// instance has gone stale are dropped as it walks, so
1582    /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1583    /// skinning.
1584    skinned_instances: Vec<SkinnedInstance>,
1585
1586    /// §3.2's material table, and the rows in it.
1587    ///
1588    /// One buffer shared by every frame's bind group, not a ring — see
1589    /// [`crate::material_table`], which is where that decision lives.
1590    materials: MaterialTable,
1591    /// The table row of each description material, in [`SceneDesc::materials`]
1592    /// order — what an [`InstanceDesc::material`] index resolves through.
1593    ///
1594    /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1595    /// whole record, and an instance that lost its material id would name row 0
1596    /// by accident, which is a material and only *happens* to be the untinted
1597    /// one.
1598    material_ids: Vec<u32>,
1599    /// Topic 50's irradiance grid, row by row.
1600    ///
1601    /// One buffer shared by every frame's bind group, like the material table
1602    /// and for a stronger version of its reason: a probe is written when the
1603    /// scene is made resident and there is no call that rewrites one. See
1604    /// [`crate::probe`].
1605    probes: ProbeTable,
1606    /// Where those rows are, which rides in the frame block rather than in a
1607    /// buffer of its own — a fragment needs it before it knows which row to
1608    /// fetch.
1609    ///
1610    /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1611    /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1612    /// grid of nothing, which is what a description with no probes leaves here
1613    /// and what makes the whole feature add zero.
1614    probe_volume: crcbl_shaders::probe::ProbeVolume,
1615    /// §3.2's texture side: one `D2Array` image whose layers the material rows
1616    /// index. One page, bound once, for every material — see the module docs on
1617    /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1618    /// a bindless descriptor array.
1619    base_color_page: UploadedTexture,
1620    /// §2's second page: one `D2Array` image of tangent-space normals, whose
1621    /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1622    /// indexes.
1623    ///
1624    /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1625    /// through the same UV and the same sampler, and **created linear** — see
1626    /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1627    /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1628    /// base-colour one is what the caller wrote and what this holds.
1629    normal_page: UploadedTexture,
1630    /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1631    /// roughness and metallic, whose layers
1632    /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1633    /// indexes.
1634    ///
1635    /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1636    /// same UV and the same sampler, and **created linear** — see
1637    /// [`MRO_PAGE_FORMAT`].
1638    mro_page: UploadedTexture,
1639    /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1640    /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1641    ///
1642    /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1643    /// **created sRGB** rather than linear, because an emissive texel is a
1644    /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1645    emissive_page: UploadedTexture,
1646    /// Each [`PageKind`]'s image size in texels, as a width and a height,
1647    /// indexed by [`PageKind::index`].
1648    ///
1649    /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1650    /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1651    /// named no layer of, which is the placeholder's extent and not the
1652    /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1653    /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1654    /// to the graph and an [`ImportedImage`] names an extent, and the
1655    /// description they came from is the caller's, read once at build.
1656    page_extents: [(u32, u32); PageKind::ALL.len()],
1657    /// The sampler the page is read through.
1658    base_color_sampler: SamplerHandle,
1659    /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1660    /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1661    anisotropy: f32,
1662    /// How many layers each [`PageKind`]'s page holds, indexed by
1663    /// [`PageKind::index`] — zero for a kind the description named none of.
1664    ///
1665    /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1666    /// replacement to, so every material row's layer number goes on naming the
1667    /// same texture.
1668    page_layers: [usize; PageKind::ALL.len()],
1669    /// `[frame]`: the page sampler and the four page views that slot's
1670    /// mesh-layout groups name.
1671    ///
1672    /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1673    /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1674    /// so this is what says which slots still name a sampler
1675    /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1676    /// [`replace_page`](ForwardRenderer::replace_page) did.
1677    slot_pages: Vec<PageBindings>,
1678    /// Page samplers and pages replaced while some slot may still name them.
1679    /// Each is destroyed as the last slot naming it moves off, or at
1680    /// [`destroy`](ForwardRenderer::destroy).
1681    retired_pages: Vec<RetiredPage>,
1682
1683    /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1684    /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1685    ///
1686    /// Kept rather than recomputed because the shadow pass's share is the number
1687    /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1688    /// out from topic 45's tile allocation and nothing outside
1689    /// it can restate without becoming the second copy that drifts.
1690    recorded_draws: u64,
1691    /// Which call the forward pass records — the device's [`GeometryPath`],
1692    /// resolved once.
1693    emit: EmitTail,
1694    /// The most buckets one call of the geometry passes draws, or `None` where
1695    /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1696    /// build with [`emit`](Self::emit) and for its reason.
1697    range_limit: Option<u32>,
1698    /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1699    /// tails draw the same geometry out of the index pool and read none of
1700    /// this. `None` is therefore the ordinary state on most devices rather than
1701    /// a failure, and it is also what makes a fall-through impossible — see
1702    /// [`ForwardRenderer::geometry_path`].
1703    clusters: Option<ClusterPool>,
1704    /// Whether the mesh pipeline was built with §3.5's amplification stage in
1705    /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1706    /// what it means is written down.
1707    culls_clusters: bool,
1708    /// Where each description mesh's clusters are in
1709    /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1710    /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1711    /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1712    mesh_clusters: Vec<ClusterRange>,
1713    /// The bucket each level of each description mesh draws through, finest
1714    /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1715    /// [`ForwardRenderer::level_buckets`].
1716    ///
1717    /// **The run for the scene's first material mode**, which is `OPAQUE`
1718    /// wherever the scene has an opaque material at all: the table is every
1719    /// mesh's levels once per mode the scene holds, mode by mode, and this
1720    /// names a mesh's levels in the first of those runs. See
1721    /// [`ForwardRenderer::bucket_modes`].
1722    mesh_level_buckets: Vec<Vec<u32>>,
1723    /// The pixel budget topic 25's descent compares a group's
1724    /// projected error against. [`LOD_ERROR_BUDGET`] until
1725    /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1726    lod_error_budget: f32,
1727    /// How far below that an expanded group is held before it collapses again.
1728    /// [`LOD_HOLD_RATIO`] until
1729    /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1730    lod_hold_ratio: f32,
1731    /// The same three numbers the shadow cascades selected under, which is
1732    /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1733    /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1734    ///
1735    /// Kept beside the camera's for its reason: a reader comparing the two cuts
1736    /// takes both pairs from here rather than re-deriving the bias, which would
1737    /// be comparing two copies of one arithmetic instead of two selections.
1738    shadow_lod_params: [f32; 3],
1739
1740    /// The lights a caller set beside the sun, as
1741    /// [`ForwardRenderer::set_lights`] was handed them.
1742    ///
1743    /// Kept rather than converted on the way in, because a row is the *frame's*
1744    /// artefact: the sun arrives per frame at
1745    /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1746    /// frame uploads cannot be assembled until then.
1747    extra_lights: Vec<Light>,
1748
1749    /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1750    /// alignment apart. Shared by every frame's bind group rather than ringed,
1751    /// because nothing rewrites it after `build`: a mesh's base vertex and an
1752    /// object's instance index are decided when the pools allocate them.
1753    draw_constants: BufferHandle,
1754    /// The camera's resources and history — see [`view`], which is where the
1755    /// line between a camera's state and the scene's is drawn.
1756    primary: View,
1757    /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1758    /// [`ViewId::index`] less one — a free id is `None`.
1759    views: Vec<Option<View>>,
1760    /// The tables a view's generator is built from — see [`DrawTables`].
1761    draw_tables: DrawTables,
1762    /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1763    /// say which frame it was last begun for — see [`View::begun`].
1764    frame_serial: u64,
1765    /// The frame the last `begin_frame` opened, for
1766    /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1767    frame_scene: Option<FrameScene>,
1768    /// Which frame-in-flight slot is current. Set from
1769    /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1770    /// uniform ring and the instance ring cannot drift apart.
1771    frame: usize,
1772
1773    mesh_layout: BindGroupLayoutHandle,
1774    mesh_pipeline_layout: PipelineLayoutHandle,
1775    mesh_pipeline: SidedPipelines,
1776    /// [`ForwardRenderer::mesh_pipeline`] again in
1777    /// [`PolygonMode::Line`], for
1778    /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1779    ///
1780    /// [`None`] until a caller first switches the view on — the ground grid's
1781    /// arrangement exactly, and for its reason: a second pipeline compiled at
1782    /// build would be paid for by every sample, golden and headless run that
1783    /// never asks for a wireframe, which is all of them. Once built it is kept,
1784    /// because switching the view off is
1785    /// [`ForwardRenderer::wireframe_on`] and not a release.
1786    ///
1787    /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1788    /// does not disable culling: a single-sided wireframe drawn over a
1789    /// double-sided bucket would leave a surface out of the debug view that the
1790    /// shaded frame beside it draws, which is a view of the document that
1791    /// disagrees with the document.
1792    wireframe_pipeline: Option<SidedPipelines>,
1793    /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1794    /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1795    /// default**: a wireframe is a tool's view of a document, and every sample
1796    /// and every golden image predates it.
1797    wireframe_on: bool,
1798    /// The occlusion and small-feature culls a caller asked for — see
1799    /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1800    occlusion_culling: OcclusionCulling,
1801    /// Whether the skinning dispatch skips a region no view and no shadow
1802    /// cull can draw this frame — see
1803    /// [`set_skinning_culls`](ForwardRenderer::set_skinning_culls).
1804    skinning_culls: bool,
1805    /// Every shadow cull this frame redraws, and the probe updater's on a
1806    /// frame with shadows off: the shadow half of what
1807    /// [`ForwardRenderer::cull_skinned_regions`] tests a skinned object's
1808    /// footprint against. Written by `begin_frame_body`.
1809    skin_shadow_reach: Vec<Frustum>,
1810    /// The skinning cull's storage and its last answer — see
1811    /// [`ForwardRenderer::cull_skinned_regions`].
1812    skin_cull: skin_cull::SkinCull,
1813    /// Regions the last recorded skinned frame planned and did not dispatch —
1814    /// see [`skinned_regions_skipped`](ForwardRenderer::skinned_regions_skipped).
1815    skinned_skipped: u32,
1816    /// Whether a point light's six faces cull separately — see
1817    /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1818    point_face_culls: bool,
1819    /// What a test asked every shadow view's uploaded block to be rewritten
1820    /// with — see
1821    /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1822    /// [`None`] outside a test.
1823    shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1824    /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1825    /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1826    /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1827    /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1828    ///
1829    /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1830    /// exactly: it is a tool's view of a document, and every sample and every
1831    /// golden image predates it.
1832    ///
1833    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1834    normals_view: bool,
1835
1836    /// The exponential height fog the colour pass composites over its
1837    /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1838    ///
1839    /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1840    /// terms: a caller who never asks for fog draws the frame this renderer
1841    /// drew before the feature existed, and exactly that frame — the shader's
1842    /// composite is an identity at zero density rather than an interpolation
1843    /// that nearly is.
1844    fog: Fog,
1845
1846    /// The gradient sky whose irradiance the colour pass adds to the ambient
1847    /// term — see [`set_sky`](ForwardRenderer::set_sky).
1848    ///
1849    /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1850    /// gradient projects to coefficients that are all zero, so the three dot
1851    /// products the fragment stage adds are zero and no frame drawn before a
1852    /// sky existed moves.
1853    sky: Sky,
1854    /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1855    /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1856    ///
1857    /// `None` by default, so a renderer nobody calls that on is the renderer it
1858    /// was.
1859    atmosphere: Option<Atmosphere>,
1860    /// The marched sky-view LUT this renderer is drawing, with the parameters
1861    /// it was marched for and the projections taken from it.
1862    ///
1863    /// **Cached against the parameters rather than rebuilt per frame**, because
1864    /// the march is tens of milliseconds of CPU and the sun in most frames has
1865    /// not moved. The stored parameters are the *normalised* ones the shader
1866    /// crate takes, so a caller handing over the same sun spelled two lengths
1867    /// does not force a rebuild.
1868    ///
1869    /// This is the LUT a frame is **drawn from**, which is not the one being
1870    /// marched: see [`Self::sky_view_build`].
1871    sky_view: Option<PresentedSky>,
1872    /// The march in flight, when the sun has moved away from
1873    /// [`Self::sky_view`]'s.
1874    ///
1875    /// [`ForwardRenderer::refresh_sky_view`] steps it
1876    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1877    /// [`Self::sky_view`] when it finishes.
1878    ///
1879    /// **The host side is where the double buffer is**: the LUT being drawn and
1880    /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1881    /// device ring is untouched. Putting the stripe on the device instead would
1882    /// mean writing part of a ring slot per frame, and that ring's slots are
1883    /// written whole precisely because each is a frame in flight — a partial
1884    /// write would have to track, per slot, which rows of *which* sun that slot
1885    /// already holds, which is bookkeeping the host copy does not need at all.
1886    sky_view_build: Option<SkyViewBuild>,
1887
1888    /// Whether the colour pass tints each cluster by its DAG level instead of
1889    /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1890    ///
1891    /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1892    /// because one uniform lane carries both switches and the fragment stage
1893    /// tests the LOD threshold first. `crcbl_shaders`'
1894    /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1895    /// order true.
1896    lod_view: bool,
1897
1898    /// Whether the colour pass shades each cluster by the projected error the
1899    /// LOD selection judged it on, instead of shading it or tinting it — see
1900    /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1901    ///
1902    /// **Wins over both [`lod_view`](Self::lod_view) and
1903    /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1904    /// reason: one uniform lane carries all three switches and the shaders test
1905    /// the outermost threshold first. `crcbl_shaders`'
1906    /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1907    /// order true, and
1908    /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1909    /// holds this side to it.
1910    heatmap: bool,
1911
1912    /// Whether the colour pass draws the ambient-occlusion channel as grey
1913    /// instead of shading — see
1914    /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1915    ///
1916    /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1917    /// for its reason: one uniform lane, outermost threshold first.
1918    /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1919    /// what keeps that order true, and
1920    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1921    /// this side to it.
1922    occlusion_view: bool,
1923
1924    /// Whether the colour pass draws the motion vector instead of shading — see
1925    /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1926    ///
1927    /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1928    /// terms and for its reason: one uniform lane, outermost threshold first.
1929    /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1930    /// is what keeps that order true, and
1931    /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1932    /// this side to it.
1933    motion_view: bool,
1934    /// Whether the colour pass draws the occlusion channel's bent direction
1935    /// instead of shading — see
1936    /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1937    ///
1938    /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1939    /// terms: it is the outermost sentinel in the lane, and
1940    /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1941    /// is what holds the shader's branch order to it.
1942    bent_normal_view: bool,
1943
1944    /// Whether the colour pass tints the shaded picture by the cascade each
1945    /// sun-lit fragment's shadow was sampled from — see
1946    /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1947    ///
1948    /// **Loses to every other view**, which is the opposite of every field
1949    /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1950    /// replaces the shaded picture and this one multiplies it, so a frame drawing
1951    /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1952    /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1953    /// holds the shader to the same order, from the other end of the lane.
1954    cascade_view: bool,
1955
1956    /// Whether the frame draws the shadow atlas over the finished picture — see
1957    /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1958    ///
1959    /// **Not a lane of the frame block**, unlike every field above: this view is
1960    /// a pass rather than a branch in `mesh.slang`, so what reads this is
1961    /// [`ForwardRenderer::add_passes`] deciding whether to record
1962    /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1963    /// [`cascade_view`](Self::cascade_view) — see
1964    /// [`ForwardRenderer::debug_view`].
1965    atlas_view: bool,
1966
1967    /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1968    /// topic 25's selection from, when that is not the camera's own
1969    /// eye — see
1970    /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1971    ///
1972    /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1973    /// every frame the engine has drawn so far did: the eye handed to
1974    /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1975    /// never sets this writes the parameter block it wrote before this field
1976    /// existed.
1977    ///
1978    /// **Not a [`DebugView`]**, and deliberately: the three views are one
1979    /// picture chosen between, while this is a change to what the *selection*
1980    /// answers and leaves the picture's choice alone. A reviewer freezing the
1981    /// cut and then reading it off the LOD tint is the combination the feature
1982    /// exists for, so the two cannot be alternatives.
1983    frozen_selection_eye: Option<Vec3>,
1984
1985    /// Topic 18's shadow atlas: one `D32Float` image holding
1986    /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1987    /// first, then one per shadowed light.
1988    ///
1989    /// Owned here rather than created by the graph per frame, because its
1990    /// extent is a **quality setting and not a window size** — nothing about it
1991    /// changes on a resize, so a transient would be re-created for no reason
1992    /// and could not be read back by a test that does not own the graph.
1993    shadow_atlas: ImageHandle,
1994    shadow_atlas_view: ImageViewHandle,
1995    /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1996    /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1997    ///
1998    /// Both halves of that sentence are forced:
1999    ///
2000    /// * **The slot has to be filled.** Slang's Metal backend materialises every
2001    ///   global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
2002    ///   `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
2003    ///   depth-only pipeline sharing this layout still declares the argument. A
2004    ///   layout with the slot removed would break Metal alone, on a runner this
2005    ///   team cannot debug on, which is the trap binding 6's comment already
2006    ///   records.
2007    /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
2008    ///   attachment and a bind-group resource in the same pass, and the shadow
2009    ///   pass is exactly that pass.
2010    ///
2011    /// Nothing samples it: the shadow pipeline has no fragment stage. It is
2012    /// brought into the graph beside the atlas so its layout transition is the
2013    /// graph's like every other, rather than a hand-written barrier.
2014    shadow_placeholder: ImageHandle,
2015    shadow_placeholder_view: ImageViewHandle,
2016    /// The **comparison** sampler the atlas is read through — hardware PCF.
2017    shadow_sampler: SamplerHandle,
2018    /// The depth-only pipeline every tile is rendered with — and, driven with
2019    /// the camera's own draws, the depth prepass's: `mesh.slang`'s
2020    /// `depthVertexMain` where the geometry comes from a vertex stage, the same
2021    /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
2022    /// a mesh one, and no fragment stage in either case.
2023    shadow_pipeline: SidedPipelines,
2024    /// The same two passes' pipeline for the buckets whose material mode cuts
2025    /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
2026    /// [`MeshModules::depth_masked_pipeline`].
2027    ///
2028    /// [`None`] for a scene whose materials mask nothing, such as the demo
2029    /// scene: the bucket table is fixed at build, so a scene
2030    /// without a masked bucket then never has one — see [`SidedPipelines`] for
2031    /// the twin's same argument. Which buckets are drawn with it is
2032    /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
2033    /// frame's draws** rather than a choice for the whole frame.
2034    depth_masked_pipeline: Option<SidedPipelines>,
2035    /// The pipeline that resets one tile of the atlas before it is redrawn, on a
2036    /// frame that is keeping some of the others — see
2037    /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
2038    /// for it lives.
2039    shadow_clear_pipeline: GraphicsPipelineHandle,
2040    /// The irradiance probes' reflective shadow map — see
2041    /// [`MeshModules::rsm_pipeline`]. Built only for a volume that asked for
2042    /// [`ProbeUpdate::EveryFrame`], beside [`ForwardRenderer::probe_gather`] and
2043    /// for its reason, and [`None`] everywhere else; the pass that draws the
2044    /// map is recorded only where this is `Some`.
2045    rsm_pipeline: Option<SidedPipelines>,
2046    /// The compute pass that reads that map into the probe rows, and [`None`]
2047    /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
2048    /// whole of what the default costs such a scene: no pipeline, no buffers, no
2049    /// pass and no frame time.
2050    probe_gather: Option<ProbeGather>,
2051    /// Whether cascade 0's view block and cull parameters were written for the
2052    /// frame being recorded, so the reflective shadow map can be drawn from
2053    /// them.
2054    ///
2055    /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
2056    /// *atlas*: a frame drawing without
2057    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
2058    /// cascade 0 for the map and writes no tile, and overloading that flag would
2059    /// report a cascade as redrawn when nothing drew it.
2060    rsm_cull_ready: bool,
2061    /// What the scene said fills the probe rows.
2062    ///
2063    /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
2064    /// shadow atlas's static-cache hold when the updater is on, because the map
2065    /// is that cascade's own draws — and by the pass recording below.
2066    probe_update: ProbeUpdate,
2067    /// How far cascade 0 reached on the frame being recorded, which is the
2068    /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
2069    /// reads it.
2070    ///
2071    /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
2072    /// themselves, rather than recomputed at pass-record time: a frame that
2073    /// scaled its gather by one cascade's footprint while drawing the map
2074    /// through another's would be a bounce that is uniformly wrong, and nothing
2075    /// in the frame could see it.
2076    cascade_reach: f32,
2077    /// The sun's colour premultiplied by its intensity, this frame.
2078    ///
2079    /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2080    /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2081    /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2082    /// The sun's *direction* is not carried beside it: the gather needs none, on
2083    /// `probe_gather.slang`'s own derivation.
2084    sun_color: Vec3,
2085    /// One cull and draw-argument pass **per cascade and per shadowed light**,
2086    /// which is topic 18's "one cull dispatch per cascade against the same
2087    /// instance/geometry pools" with a shadowed light counting as a cascade does.
2088    ///
2089    /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2090    /// the same indirect call the colour pass does, so it needs the same
2091    /// arguments, and there is no "cull only" constructor to reach for. The cost
2092    /// is [`DrawGen`]'s own buffers and per-instance state — see
2093    /// [`TileBuffers::group_state`], which is where that price is written down,
2094    /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2095    /// than six.
2096    ///
2097    /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2098    /// [`shadow_cull`] is where a light slot's is.
2099    shadow_draws: Vec<DrawGen>,
2100    /// The layouts and pipelines every [`DrawGen`] above and in each view
2101    /// dispatches, compiled once and shared rather than once per generator.
2102    ///
2103    /// This reference is the renderer's own, held so [`create_view`] can hand
2104    /// the set to a view built later; [`destroy`](Self::destroy) gives it back
2105    /// after every generator, and whichever reference goes last destroys it.
2106    ///
2107    /// [`create_view`]: Self::create_view
2108    draw_pipelines: Arc<DrawGenPipelines>,
2109    /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2110    /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2111    /// mesh stages rather than a second transform path.
2112    shadow_uniforms: Vec<Vec<BufferHandle>>,
2113    /// Empty between frame preparations, with capacity retained for assembly.
2114    shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2115    /// Empty between frame preparations, with capacity retained for frusta.
2116    shadow_prepare_culls: Vec<(usize, Frustum)>,
2117    /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2118    /// the survivors of the cull its slot owns.
2119    shadow_groups: Vec<Vec<BindGroupHandle>>,
2120    /// `[frame][view]`: the cut that view's amplification stage chose, one word
2121    /// per resident cluster — and empty where there is no such stage.
2122    ///
2123    /// **A buffer per view rather than the camera's**, unlike every other
2124    /// resource these passes share: the colour pass is recorded last and writes
2125    /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2126    /// so a view writing there leaves nothing behind to read. Without one of
2127    /// these the shadow pass's descent is unobservable — which is the state
2128    /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2129    /// would have stayed in.
2130    shadow_selection: Vec<Vec<BufferHandle>>,
2131    /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2132    /// in the atlas's light region its tiles are, and the memory that keeps that
2133    /// answer from flickering.
2134    ///
2135    /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2136    /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2137    /// occupied slot and a viewport per face it has, and nothing at all for the
2138    /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2139    /// "nothing stored, fully lit" wherever anything did sample it.
2140    shadow_lights: shadow::Selection,
2141    /// `[group]`: everything that group's maps would be drawn from, as
2142    /// [`ForwardRenderer::shadow_group_record`] spells it.
2143    ///
2144    /// Kept only to tell one frame's answer from the last one's: it is compared
2145    /// and then replaced, and what travels from there is the number below.
2146    ///
2147    /// **Per group rather than per atlas**, since the cadence rung: a group is a
2148    /// cascade or a light slot's whole run of tiles, and holding one map while
2149    /// redrawing another is the whole of what that rung buys.
2150    shadow_group_inputs: Vec<Vec<u8>>,
2151    /// `[group]`: a number that moves whenever that group's entry of
2152    /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2153    /// value it has had.
2154    ///
2155    /// So "the image already holds this" is one integer comparison, which is
2156    /// what lets the pass body below carry the answer out of the graph.
2157    shadow_group_id: Vec<u64>,
2158    /// `[group]`: how many instance writes that group's cull could have seen,
2159    /// over the renderer's life — the per-group stand-in for
2160    /// [`InstancePool::revision`] in
2161    /// [`ForwardRenderer::shadow_group_record`], moved by
2162    /// [`ForwardRenderer::note_caster_writes`].
2163    shadow_group_writes: Vec<u64>,
2164    /// `[element]`: where each element of the instance array could draw into a
2165    /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2166    /// which is what a write's *before* is read from. Grows to the highest
2167    /// element written; an element past its end has never been written and is
2168    /// [`shadow_inputs::CasterFootprint::Nowhere`].
2169    shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2170    /// The live elements whose mesh has a DAG, and so whose level the selection
2171    /// eye chooses — the ones that put the eye into a light group's record.
2172    shadow_dag_elements: std::collections::BTreeSet<u32>,
2173    /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2174    /// an instance does not allocate its list.
2175    shadow_written: Vec<u32>,
2176    /// This frame's written elements' footprints, before and after the write,
2177    /// from [`ForwardRenderer::note_caster_writes`] for
2178    /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2179    /// written in.
2180    shadow_moved: Vec<(
2181        shadow_inputs::CasterFootprint,
2182        shadow_inputs::CasterFootprint,
2183    )>,
2184    /// The number given to the shadow pass this renderer recorded last.
2185    ///
2186    /// Moves once per recorded pass, so the body below can say *which* pass ran
2187    /// with one integer.
2188    shadow_pass_id: u64,
2189    /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2190    /// **ran**, written by that pass's own body.
2191    ///
2192    /// By the body rather than by the call that recorded it, and that is the
2193    /// whole of why this is shared state rather than a plain field: a frame
2194    /// whose graph was refused — or built and dropped — recorded a pass that
2195    /// never executed, so the image still holds whatever the frame before it
2196    /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2197    /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2198    /// imported images uses for the same reason.
2199    ///
2200    /// Zero until a pass has run, and the ids start above it, so the first frame
2201    /// of all draws.
2202    shadow_pass_ran: Arc<AtomicU64>,
2203    /// What the shadow pass recorded last would leave the image holding, if its
2204    /// body ran.
2205    ///
2206    /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2207    /// the only place that can tell whether it did — see
2208    /// [`ForwardRenderer::shadow_pass_ran`].
2209    shadow_pending: Option<ShadowCommit>,
2210    /// `[group]`: the id, the centre that group's maps were projected from and
2211    /// how far they reach, as the record the **image** holds describes them.
2212    ///
2213    /// The id is what says a map is out of date. The centre and reach are what
2214    /// say it is about somewhere else: a map whose own centre has moved further
2215    /// than its own reach covers ground it was never drawn for, and holding
2216    /// that is worse than a shadow that lags — see
2217    /// [`ForwardRenderer::shadow_cadence_reset`].
2218    shadow_group_held: Vec<(u64, Vec3, f32)>,
2219    /// `[group]`: whether this frame redraws that group's maps.
2220    ///
2221    /// Frozen by [`ForwardRenderer::begin_frame`] for
2222    /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2223    /// `add_passes` acts on it, and a value that moved between them would skip
2224    /// a cull whose draws were recorded, or the other way about.
2225    shadow_group_redrawn: Vec<bool>,
2226    /// Where every atlas slot's map was laid out on the frame the **image** was
2227    /// drawn from, so a frame can tell whether the texels it is keeping still
2228    /// describe the layout it is about to sample through.
2229    ///
2230    /// A layout that has moved is what makes a frame clear the whole attachment
2231    /// and redraw every group: a tile left over from a different layout is
2232    /// texels nothing this frame can account for. Promoted beside
2233    /// [`ForwardRenderer::shadow_group_held`].
2234    ///
2235    /// [`None`] until a pass has drawn, which is **not** the layout a frame
2236    /// with shadows off produces: an image no pass has touched holds undefined
2237    /// memory rather than a clear, so the first frame of all has to write one
2238    /// whatever it is asked for.
2239    shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2240    /// Whether any map this frame samples is one an earlier frame drew, rather
2241    /// than one this frame did.
2242    ///
2243    /// The cadence's own readback — see
2244    /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2245    /// atlas.
2246    shadow_atlas_cached: bool,
2247    /// Whether this frame ignored the cadence because some map's region moved
2248    /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2249    shadow_cadence_reset: bool,
2250    /// How many tiles this frame redraws — see
2251    /// [`ForwardRenderer::shadow_faces_redrawn`].
2252    shadow_faces_redrawn: u32,
2253    /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2254    ///
2255    /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2256    /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2257    /// process-global, and an application that wants a tier's own pair — or a
2258    /// test that wants a frame nothing else in the process can move — needs one
2259    /// that is not.
2260    shadow_cadence_request: Option<shadow::Cadence>,
2261    /// Whether this frame's shadow pass clears the whole attachment, rather
2262    /// than loading it and resetting only the tiles it redraws.
2263    ///
2264    /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2265    /// reason: the decision is `begin_frame`'s and the recording is
2266    /// `add_shadow_pass`'s, and a value that moved between them would load an
2267    /// attachment whose tiles nothing had reset.
2268    shadow_atlas_clears: bool,
2269    /// How many frames have been opened, which is what the cadence is keyed to.
2270    ///
2271    /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2272    /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2273    /// keyed to that would repeat every few frames and bound nothing.
2274    shadow_frame: u64,
2275
2276    /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2277    /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2278    /// the latency are argued.
2279    ///
2280    /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2281    /// statistics buffer of their own and none of them is read: a cascade's
2282    /// survivor count is a different question about a different frustum, and
2283    /// added into this one it would produce a number larger than the pool holds.
2284    ///
2285    /// [`None`] on a device that would not give out the buffers, which is what
2286    /// makes the counters row degrade to `indirect` rather than fail.
2287    cull_stats: Option<CullStatsRing>,
2288
2289    tonemap_layout: BindGroupLayoutHandle,
2290    tonemap_pipeline_layout: PipelineLayoutHandle,
2291    tonemap_pipeline: GraphicsPipelineHandle,
2292    sampler: SamplerHandle,
2293    /// The multiplier the tonemap pass applies before its clamp — see
2294    /// [`set_exposure`](ForwardRenderer::set_exposure).
2295    ///
2296    /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2297    /// the only thing that writes it and it clamps.
2298    exposure: f32,
2299    /// How far auto-exposure may move in one frame — see
2300    /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2301    ///
2302    /// [`None`] until a caller says otherwise, and that is the whole distance in
2303    /// one frame: the picture the pass drew before adaptation existed.
2304    exposure_adaptation: Option<ExposureAdaptation>,
2305    /// Which operator the tonemap pass runs — see
2306    /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2307    ///
2308    /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2309    /// a caller says otherwise: this renderer shades in linear HDR, so the
2310    /// filmic roll-off is what a view that has said nothing wants. A
2311    /// display-referred view — a 2D sample, or a fixture whose assertions
2312    /// predict a code value — asks for
2313    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2314    /// which is the identity on `0..=1`.
2315    tonemap_curve: tonemap::TonemapCurve,
2316
2317    /// The format the tonemap pipeline was built for. A swapchain format change
2318    /// needs a new pipeline, which is why it is remembered rather than assumed.
2319    target_format: Format,
2320
2321    /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2322    /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2323    /// occlusion image that does not exist yet.
2324    ///
2325    /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2326    /// The shadow pass and the depth prepass name it and never sample it — a
2327    /// depth-only pipeline has no fragment stage — and **the forward pass names
2328    /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2329    /// where it is the whole of that effect's off-switch. An AO-on frame binds
2330    /// the occlusion pair's blurred output instead.
2331    ///
2332    /// **It is white because that is the value that occludes nothing**, which is
2333    /// what makes it an honest stand-in for "no occlusion was computed" rather
2334    /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2335    /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2336    /// texel is zero on every backend, so the shader clamps the coordinate to the
2337    /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2338    ///
2339    /// It is uploaded rather than cleared, so it is in
2340    /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2341    /// declare it to give it a layout.
2342    ambient_occlusion_placeholder: UploadedTexture,
2343    /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2344    /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2345    /// contact-shadow image that does not exist yet.
2346    ///
2347    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2348    /// binding along and with one difference worth stating: an unclamped `Load`
2349    /// past this one's single texel would cost the frame its **sun**, not its
2350    /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2351    contact_shadow_placeholder: UploadedTexture,
2352    /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2353    /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2354    /// has been captured — and so the console switch has something to name when
2355    /// the maps are turned off.
2356    ///
2357    /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2358    /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2359    /// against `GetDimensions`, so all four of its taps land on this image's one
2360    /// texel and every probe reads as unobstructed.
2361    probe_visibility_placeholder: UploadedTexture,
2362    /// The captured maps, one `Rg32Float` layer per probe — `None` until
2363    /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2364    /// frame drawn by a caller that never calls it.
2365    probe_visibility: Option<UploadedTexture>,
2366    /// The scene's static triangles, kept for that capture and for nothing else.
2367    ///
2368    /// Empty for a description that reserved no probes, which is what makes the
2369    /// retention cost of this rung zero for every caller that does not use it —
2370    /// see [`crate::probe_visibility`].
2371    probe_occluders: crate::probe_visibility::Occluders,
2372    /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2373    /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2374    /// by every area light's specular term.
2375    ///
2376    /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2377    /// again: it is a property of the GGX lobe rather than of a scene, a view or
2378    /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2379    /// it this is not a stand-in for anything — there is no path on which the
2380    /// table is absent, because there is no path on which the lobe is.
2381    specular_dfg: UploadedTexture,
2382    /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2383    /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2384    ///
2385    /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2386    /// terms exactly and for the same reason: it is a property of the lobe, and
2387    /// it is bound on every path because Slang's Metal backend materialises
2388    /// every global into every entry point.
2389    ltc_table: UploadedTexture,
2390    /// `crcbl_shaders::sky_prefilter`'s table as an `Rgba8Unorm` image, which
2391    /// every view's reflection march reads the sky through at a surface's
2392    /// roughness — see [`crate::ssr::Ssr::sky_prefilter_view`] — and the water
2393    /// surface beside it.
2394    ///
2395    /// Uploaded once, on [`ForwardRenderer::specular_dfg`]'s terms: the bytes
2396    /// are the same for every view, so each view's [`crate::ssr::Ssr`] borrows
2397    /// this image, and it is destroyed after the views.
2398    sky_prefilter: UploadedTexture,
2399    /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2400    /// from.
2401    ///
2402    /// Kept for one rebuild only: the pages' and their sampler's, which
2403    /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2404    /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2405    shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2406
2407    /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2408    ///
2409    /// [`None`] until a caller first switches it on with
2410    /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2411    /// keeps a sample that never asks for a grid from building a pipeline and a
2412    /// ring of blocks for a pass it does not record. Once built it is kept —
2413    /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2414    /// release, because releasing a uniform ring the frames in flight may still
2415    /// be reading is exactly what the ring exists to prevent.
2416    ground_grid: Option<GroundGrid>,
2417    /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2418    /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2419    /// every sample and every golden image predates it.
2420    ground_grid_on: bool,
2421
2422    /// The debug draw layer's immediate-mode buffer and its pass — see
2423    /// [`crate::debug_draw`].
2424    ///
2425    /// Always present and empty by default, because appending to it is what a
2426    /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2427    /// it are what stay unbuilt until a frame has both a segment and
2428    /// [`crate::debug_draw::r_debug_draw`] switched on.
2429    debug_draw: DebugDraw,
2430
2431    /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2432    /// but the one [`debug_view`](Self::debug_view) resolved to
2433    /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2434    /// [`set_atlas_view`](Self::set_atlas_view) — and that frame's
2435    /// [`begin_frame`](Self::begin_frame) is what builds it, so a renderer
2436    /// whose atlas nobody looks at holds no pipeline for it.
2437    atlas_viewer: Option<AtlasView>,
2438    /// Whether the frame [`begin_frame`](Self::begin_frame) opened draws the
2439    /// shadow atlas viewer: [`debug_view`](Self::debug_view) as that call
2440    /// resolved it, frozen on [`frame_effects`](Self::frame_effects)' terms —
2441    /// the viewer's block is written and its pipeline built there, so
2442    /// [`add_passes`](Self::add_passes) has to agree with that call.
2443    frame_atlas_view: bool,
2444    /// How large the internal render target is as a fraction of the extent a
2445    /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2446    render_scale: f32,
2447    /// [`render_scale`](Self::render_scale) as the frame
2448    /// [`begin_frame`](Self::begin_frame) opened froze it, on
2449    /// [`frame_effects`](Self::frame_effects)' terms: every view's internal
2450    /// extent this frame is taken at it, so a scale moved before
2451    /// [`add_passes`](Self::add_passes) waits for the next frame, as
2452    /// [`set_render_scale`](Self::set_render_scale) says it does.
2453    frame_render_scale: f32,
2454
2455    /// The three layers a caller supplies — see [`crate::effects`].
2456    effect_request: EffectRequest,
2457    /// The fourth layer: what this device can draw, which clamps last and
2458    /// absolutely.
2459    ///
2460    /// **Every effect, and that is a fact about the effects rather than an
2461    /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2462    /// words — "there is no device fact to gate on … inventing a capability that
2463    /// is really a performance opinion is what topic 39 exists to prevent" — and
2464    /// the reflection pair's module says it of itself. The shadow atlas is a
2465    /// `D32Float` image and a depth-only pass, which is not something a device
2466    /// that got this far can be missing either: one too small for the atlas
2467    /// fails to *build* this renderer rather than degrading past it.
2468    ///
2469    /// So the clamp is real and its rule set is empty. The first rule arrives
2470    /// with the ray-traced variants of these same three effects, which
2471    /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2472    /// builds yet.
2473    device_effects: RenderEffects,
2474    /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2475    /// draws, resolved once there.
2476    ///
2477    /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2478    /// parameter write when shadows are off and
2479    /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2480    /// changed between the two would dispatch a cull whose counters nothing
2481    /// zeroed, which is a plausible frame drawn off last frame's numbers.
2482    frame_effects: RenderEffects,
2483    /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2484    /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2485    /// read once there.
2486    ///
2487    /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2488    /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2489    /// full-screen triangles and records its passes, and a console command
2490    /// landing between the two reads would leave `counters` describing a frame
2491    /// that was never submitted.
2492    frame_ssao_blurs: u32,
2493    /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2494    /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2495    /// as submitted beside the pool's instances.
2496    ///
2497    /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2498    /// `counters` describes the frame that *was* recorded, and a request set
2499    /// after it would otherwise change the count of a frame already submitted.
2500    recorded_fullscreen: u64,
2501
2502    /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2503    /// debug draw layer's pass, as the one direct draw it costs.
2504    ///
2505    /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2506    /// a full-screen triangle: it is one line-list draw of every segment this
2507    /// frame appended. Both are direct draws of one instance, which is what
2508    /// [`ForwardRenderer::direct_draws`] adds up.
2509    recorded_debug_draw: u64,
2510    /// How many tiles of the shadow atlas the last
2511    /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2512    /// than with the attachment's own clear.
2513    ///
2514    /// Zero on every frame that clears the whole attachment, which is every
2515    /// frame until the cadence is switched on — see
2516    /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2517    /// instance each, so it joins the full-screen draws rather than the
2518    /// indirect ones.
2519    recorded_tile_clears: u64,
2520    /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2521    /// buffers every view draws them from — see [`crate::water`]. Empty until
2522    /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2523    /// pass.
2524    water: WaterBodies,
2525    /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2526    /// recorded for the primary camera: one indexed draw per body, each of one
2527    /// instance, so they join the direct draws on the debug draw layer's terms.
2528    recorded_water_draws: u64,
2529    /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2530    /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2531    /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2532    /// pass.
2533    grass: GrassScene,
2534    /// What [`ForwardRenderer::grass`]'s field draws this frame, or [`None`]
2535    /// for a frame with none, frozen by `begin_frame` so that every view's
2536    /// blocks, the grass passes it builds and the passes
2537    /// [`add_passes`](ForwardRenderer::add_passes) records are one field's —
2538    /// a field set between the two is drawn from the next frame on, as a
2539    /// body of water is.
2540    frame_grass: Option<GrassFrame>,
2541    /// The wind block every view writes into its own ring — see
2542    /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2543    wind: crcbl_shaders::wind::WindParams,
2544    /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2545    /// recorded for the primary camera: one per tile slot per look the field
2546    /// draws.
2547    ///
2548    /// **Not among the direct draws**, unlike the water surface's: every one of
2549    /// them is an indirect call whose instance count lives in a buffer a
2550    /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2551    /// nothing about how many blades came out of them.
2552    recorded_grass_draws: u64,
2553    /// Start-up uploads submitted without a wait — the build's batch, and one
2554    /// for each [`create_view`](ForwardRenderer::create_view) and
2555    /// [`set_wind_layers`](ForwardRenderer::set_wind_layers) since — whose
2556    /// staging the GPU may still be reading.
2557    ///
2558    /// Each is retired by the first `begin_frame` that finds its semaphore
2559    /// signalled, and waited for by [`destroy`](ForwardRenderer::destroy) and
2560    /// [`destroy_view`](ForwardRenderer::destroy_view) before they release
2561    /// anything the copies write. Queue order is what lets a frame read the
2562    /// uploaded resources without waiting first — see [`PendingUpload`] — so
2563    /// every one of them was submitted to the device's graphics queue.
2564    uploads_in_flight: Vec<PendingUpload>,
2565}
2566
2567/// What a partly-built [`ForwardRenderer`] has to give back.
2568///
2569/// `new` creates a dozen objects with `?` between them, and the seam's
2570/// `destroy_*` is explicit — so a failure half way through used to leak
2571/// everything created before it. The recorder's leak assertions cover the happy
2572/// path; this covers the other one.
2573#[derive(Debug, Default)]
2574struct Rollback {
2575    buffers: Vec<BufferHandle>,
2576    bind_groups: Vec<BindGroupHandle>,
2577    bind_group_layouts: Vec<BindGroupLayoutHandle>,
2578    pipeline_layouts: Vec<PipelineLayoutHandle>,
2579    pipelines: Vec<GraphicsPipelineHandle>,
2580    samplers: Vec<SamplerHandle>,
2581    /// The shadow atlas and its placeholder, which are created here rather than
2582    /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2583    /// with their views beside them.
2584    images: Vec<ImageHandle>,
2585    image_views: Vec<ImageViewHandle>,
2586    /// Uploaded images, which own a view each and so cannot be rolled back as
2587    /// one list of handles.
2588    textures: Vec<UploadedTexture>,
2589    /// The geometry pool, which owns two buffers, a semaphore and anything
2590    /// still staged — so it cannot be rolled back as a list of handles.
2591    pool: Option<MeshPool>,
2592    /// The instance pool, which owns one buffer per frame in flight.
2593    instances: Option<InstancePool>,
2594    /// The material table, which owns one buffer.
2595    materials: Option<MaterialTable>,
2596    /// The irradiance probe table, which owns one buffer.
2597    probes: Option<ProbeTable>,
2598    /// The irradiance probes' updater, which owns one pipeline,
2599    /// one layout and a ring of blocks — and only exists for a scene whose
2600    /// volume asked to be updated.
2601    probe_gather: Option<ProbeGather>,
2602    /// A view's cull and draw-argument passes, while [`View::build`] — which
2603    /// keeps a rollback of this type of its own — is still building the rest of
2604    /// that view. Only a view's rollback holds this one; the renderer's keeps
2605    /// its shadow culls' in [`shadow_draws`](Self::shadow_draws). They
2606    /// own a ring of buffers and dispatch
2607    /// [`draw_pipelines`](Self::draw_pipelines), and clean themselves up on
2608    /// their own failure path, so this only carries one that was built.
2609    draws: Option<DrawGen>,
2610    /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2611    /// `Option`, because a failure part way through the tiles has to release the
2612    /// ones already built.
2613    shadow_draws: Vec<DrawGen>,
2614    /// The draw-generation pipelines every generator shares, released after
2615    /// all of them — see [`ForwardRenderer::draw_pipelines`].
2616    draw_pipelines: Option<Arc<DrawGenPipelines>>,
2617    /// The cluster buffers, which own three buffers and are built on the
2618    /// mesh-shader path alone.
2619    clusters: Option<ClusterPool>,
2620    /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2621    /// three buffers — and which clean themselves up on their own failure path,
2622    /// so this only carries one that was built.
2623    lights: Option<LightGrid>,
2624    /// Topic 03 §3.3's farthest-depth pyramid,
2625    /// which owns one pipeline, one layout and — once a frame culled — a chain
2626    /// of level images.
2627    occlusion_pyramid: Option<OcclusionPyramid>,
2628    /// Topic 47's reflection march, which owns one
2629    /// pipeline, one layout and a ring of blocks.
2630    ssr: Option<Ssr>,
2631    /// The march's layouts and pipelines while nothing else owns them — see
2632    /// [`SsrPipelines`]. In the renderer's rollback, from the mesh batch that
2633    /// compiled them until [`View::build`] takes them; in a view's, from
2634    /// [`View::build`]'s start — the set came from that batch or from
2635    /// [`ViewPipelines::new`] — until [`Ssr::new`] takes it.
2636    ssr_pipelines: Option<SsrPipelines>,
2637    /// The froxel volume, which owns three
2638    /// pipelines, two layouts and two rings of buffers.
2639    volumetric: Option<Volumetric>,
2640    /// The volume's layouts and pipelines, on [`Rollback::ssr_pipelines`]'
2641    /// terms.
2642    volumetric_pipelines: Option<VolumetricPipelines>,
2643    /// Topic 43 §6's auto-exposure, which owns three
2644    /// pipelines, one layout and three rings of buffers.
2645    exposure: Option<Exposure>,
2646    /// The background pass, which owns one pipeline, one layout and a ring of
2647    /// blocks and groups.
2648    sky_pass: Option<SkyPass>,
2649    /// The camera, once [`View::build`] has made it whole — released as one,
2650    /// by [`View::destroy`].
2651    primary: Option<View>,
2652}
2653
2654impl Rollback {
2655    /// Releases everything, in the same dependency order as
2656    /// [`ForwardRenderer::destroy`].
2657    fn run(self, device: &dyn Device) {
2658        if let Some(view) = self.primary {
2659            view.destroy(device);
2660        }
2661        for texture in self.textures {
2662            texture.destroy(device);
2663        }
2664        for handle in self.samplers {
2665            device.destroy_sampler(handle);
2666        }
2667        for handle in self.image_views {
2668            device.destroy_image_view(handle);
2669        }
2670        for handle in self.images {
2671            device.destroy_image(handle);
2672        }
2673        for handle in self.pipelines {
2674            device.destroy_graphics_pipeline(handle);
2675        }
2676        for handle in self.pipeline_layouts {
2677            device.destroy_pipeline_layout(handle);
2678        }
2679        for handle in self.bind_groups {
2680            device.destroy_bind_group(handle);
2681        }
2682        for handle in self.bind_group_layouts {
2683            device.destroy_bind_group_layout(handle);
2684        }
2685        for handle in self.buffers {
2686            device.destroy_buffer(handle);
2687        }
2688        if let Some(clusters) = self.clusters {
2689            clusters.destroy(device);
2690        }
2691        for draws in self.shadow_draws {
2692            draws.destroy(device);
2693        }
2694        if let Some(lights) = self.lights {
2695            lights.destroy(device);
2696        }
2697        if let Some(sky_pass) = self.sky_pass {
2698            sky_pass.destroy(device);
2699        }
2700        if let Some(exposure) = self.exposure {
2701            exposure.destroy(device);
2702        }
2703        if let Some(volumetric) = self.volumetric {
2704            volumetric.destroy(device);
2705        }
2706        if let Some(pipelines) = self.volumetric_pipelines {
2707            pipelines.destroy(device);
2708        }
2709        if let Some(ssr) = self.ssr {
2710            ssr.destroy(device);
2711        }
2712        if let Some(pipelines) = self.ssr_pipelines {
2713            pipelines.destroy(device);
2714        }
2715        if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2716            occlusion_pyramid.destroy(device);
2717        }
2718        if let Some(draws) = self.draws {
2719            draws.destroy(device);
2720        }
2721        // After every generator — the camera's above and each shadow cull's —
2722        // although the reference count would hold it until the last of them
2723        // anyway.
2724        if let Some(pipelines) = self.draw_pipelines {
2725            DrawGenPipelines::release(pipelines, device);
2726        }
2727        // Before the table, because its bind groups name that table's rows.
2728        if let Some(gather) = self.probe_gather {
2729            gather.destroy(device);
2730        }
2731        if let Some(table) = self.probes {
2732            table.destroy(device);
2733        }
2734        if let Some(table) = self.materials {
2735            table.destroy(device);
2736        }
2737        if let Some(pool) = self.instances {
2738            pool.destroy(device);
2739        }
2740        if let Some(pool) = self.pool {
2741            pool.destroy(device);
2742        }
2743    }
2744}
2745
2746/// What every bind group of the mesh layout names identically.
2747///
2748/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2749/// the claim: a resource here cannot differ between the colour pass's group and
2750/// a cascade's, and one there must be looked at.
2751struct SharedBindings<'a> {
2752    vertices: BufferHandle,
2753    draw_constants: BufferHandle,
2754    mesh_table: BufferHandle,
2755    materials: BufferHandle,
2756    /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2757    /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2758    /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2759    /// beside them — as this frame slot names them, which is what
2760    /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2761    pages: PageBindings,
2762    /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2763    /// what decides whether the mesh-only bindings exist at all.
2764    clusters: Option<&'a ClusterPool>,
2765    shadow_sampler: SamplerHandle,
2766    /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2767    /// slots of the light ring.
2768    ///
2769    /// Shared rather than per-group, unlike the instance array beside them, and
2770    /// that is the claim: **a cascade shades nothing**, so it reads the same
2771    /// list and the same grid the colour pass does — the depth-only pipeline
2772    /// simply never looks. Two buffers per pass would be two clustering
2773    /// dispatches for one camera.
2774    lights: BufferHandle,
2775    light_grid: BufferHandle,
2776    /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2777    /// grid's ring.
2778    ///
2779    /// Shared across the *groups of one frame* rather than across frames, which
2780    /// is the light list's arrangement exactly: a cascade shades nothing, so it
2781    /// reads the same rows the colour pass does and the depth-only pipeline
2782    /// simply never looks. What it is not is shared across the ring — see
2783    /// [`crate::probe`] for why the table is per-frame at all.
2784    probes: BufferHandle,
2785    /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2786    ///
2787    /// Shared rather than per-group for the probe grid's reason exactly: the
2788    /// regions are written when a mesh becomes resident and never per frame, so
2789    /// a cascade and the colour pass read the same words. What varies between
2790    /// them is the *budget* the mesh stage projects against, and that rides in
2791    /// each pass's own frame block.
2792    tables: BufferHandle,
2793    /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2794    /// [`ForwardRenderer::specular_dfg`].
2795    ///
2796    /// Shared rather than per-group for the probe grid's reason and more
2797    /// strongly: it is cooked into the binary, uploaded once at build and
2798    /// identical for every view this engine will ever draw. A cascade names it
2799    /// and never looks.
2800    specular_dfg: ImageViewHandle,
2801    /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2802    /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2803    ltc_table: ImageViewHandle,
2804}
2805
2806/// The half of a mesh-layout bind group that differs between the colour pass and
2807/// each shadow cascade.
2808///
2809/// One description for both, so the two cannot drift: a cascade's group is the
2810/// colour pass's with six resources swapped, and swapping the wrong five of them
2811/// is a shadow map rendered from the camera — which looks like a shadow map.
2812struct MeshGroup {
2813    /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2814    /// `view_proj` is that cascade's matrix.
2815    uniforms: BufferHandle,
2816    /// Binding 2. This frame's slot of the instance ring.
2817    instances: BufferHandle,
2818    /// Binding 5. Whose survivors this group draws.
2819    runs: BufferHandle,
2820    /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2821    /// read as data.
2822    args: BufferHandle,
2823    /// Binding 13, where there is an amplification stage: the frustum it culls
2824    /// clusters against.
2825    cull_params: BufferHandle,
2826    /// Binding 14, likewise: what it counts survivors into.
2827    cull_stats: BufferHandle,
2828    /// Binding 18, likewise: the cut the descent chose, one word per resident
2829    /// cluster. `None` exactly where there is no amplification stage, which is
2830    /// where the layout has no CLUSTER_SELECTION_BINDING either.
2831    ///
2832    /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2833    /// so a cascade writing the camera's would leave nothing of its own to read.
2834    /// See [`ForwardRenderer::shadow_selection`].
2835    cluster_selection: Option<BufferHandle>,
2836    /// Binding 19, likewise: topic 25's hysteresis state, which the
2837    /// draw-argument pass wrote this frame and this one only reads.
2838    ///
2839    /// **A buffer per pass** as well, because the colour pass and a cascade
2840    /// judge the same groups under different budgets — see
2841    /// [`TileBuffers::group_state`].
2842    group_state: Option<BufferHandle>,
2843    /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2844    /// and the placeholder for the pass that writes it — see
2845    /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2846    shadow_map: ImageViewHandle,
2847    /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2848    /// a forward pass that computed one, and the white placeholder everywhere
2849    /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2850    ///
2851    /// **Every group built at `build` names the placeholder**, including the
2852    /// camera's: the occlusion image may be a graph transient whose view exists
2853    /// only at execute time, so the camera's group is rebuilt against whatever
2854    /// the frame bound inside the forward pass and cached — the shape
2855    /// [`View::tonemap_groups`] already has.
2856    ambient_occlusion: ImageViewHandle,
2857    /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2858    /// forward pass that marched one, and the white placeholder everywhere else
2859    /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2860    ///
2861    /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2862    /// group built at `build` names the placeholder.
2863    contact_shadow: ImageViewHandle,
2864    /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2865    /// maps for the camera's pass, and the one-texel placeholder everywhere
2866    /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2867    ///
2868    /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2869    /// is not a graph transient but an ordinary uploaded texture, so what makes
2870    /// this a per-frame swap is the console switch and whether a capture has
2871    /// happened yet — neither of which is known at `build`.
2872    probe_visibility: ImageViewHandle,
2873}
2874
2875impl MeshGroup {
2876    fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2877        let mut entries = vec![
2878            BindGroupEntry {
2879                binding: 0,
2880                array_index: 0,
2881                resource: BindingResource::whole_buffer(self.uniforms),
2882            },
2883            BindGroupEntry {
2884                binding: 1,
2885                array_index: 0,
2886                resource: BindingResource::whole_buffer(shared.vertices),
2887            },
2888            BindGroupEntry {
2889                binding: 2,
2890                array_index: 0,
2891                // **This frame's slot of the instance ring, not a shared
2892                // buffer.** Binding one buffer here for every group would undo
2893                // the ring and reintroduce the cross-submission
2894                // read-after-write hazard it exists to prevent.
2895                resource: BindingResource::whole_buffer(self.instances),
2896            },
2897            BindGroupEntry {
2898                binding: 3,
2899                array_index: 0,
2900                // **One block, not the whole buffer.** The binding is dynamic,
2901                // so the bind's offset is added on top of this one and both
2902                // Vulkan and WebGPU require `offset + dynamic + size` to stay
2903                // inside the buffer — bound whole, the very first non-zero
2904                // dynamic offset would be out of range.
2905                resource: BindingResource::Buffer {
2906                    buffer: shared.draw_constants,
2907                    offset: 0,
2908                    size: DRAW_CONSTANTS_BLOCK,
2909                },
2910            },
2911            BindGroupEntry {
2912                binding: 4,
2913                array_index: 0,
2914                // The same table in every group, unlike the instance array
2915                // above it: the pool writes an entry when a mesh is uploaded or
2916                // freed, neither of which happens between frames here.
2917                resource: BindingResource::whole_buffer(shared.mesh_table),
2918            },
2919            BindGroupEntry {
2920                binding: 5,
2921                array_index: 0,
2922                // Whose cull this group draws from. This is the binding a
2923                // cascade's group differs in most consequentially: it is what
2924                // makes the shadow pass draw what the *light* can see rather
2925                // than what the camera can.
2926                resource: BindingResource::whole_buffer(self.runs),
2927            },
2928            BindGroupEntry {
2929                binding: 6,
2930                array_index: 0,
2931                resource: BindingResource::whole_buffer(shared.materials),
2932            },
2933            BindGroupEntry {
2934                binding: BASE_COLOR_PAGE_BINDING,
2935                array_index: 0,
2936                // **One entry, `array_index: 0`**, because the page is one
2937                // image and the layer is chosen in the shader. A bindless array
2938                // would be one entry per texture at ascending array indices,
2939                // which is the write path `BindGroupEntry`'s own docs describe
2940                // and the one this pass does not take.
2941                resource: BindingResource::ImageView(
2942                    shared.pages.views[PageKind::BaseColor.index()],
2943                ),
2944            },
2945            BindGroupEntry {
2946                binding: PAGE_SAMPLER_BINDING,
2947                array_index: 0,
2948                resource: BindingResource::Sampler(shared.pages.sampler),
2949            },
2950        ];
2951        if let Some(clusters) = shared.clusters {
2952            entries.extend([
2953                BindGroupEntry {
2954                    binding: CLUSTERS_BINDING,
2955                    array_index: 0,
2956                    // The same three buffers in every group, on the mesh table's
2957                    // terms: clusters are written when the pool is built and
2958                    // never again.
2959                    resource: BindingResource::whole_buffer(clusters.clusters()),
2960                },
2961                BindGroupEntry {
2962                    binding: CLUSTER_VERTICES_BINDING,
2963                    array_index: 0,
2964                    resource: BindingResource::whole_buffer(clusters.vertices()),
2965                },
2966                BindGroupEntry {
2967                    binding: CLUSTER_CORNERS_BINDING,
2968                    array_index: 0,
2969                    resource: BindingResource::whole_buffer(clusters.corners()),
2970                },
2971                BindGroupEntry {
2972                    binding: CLUSTER_DRAW_ARGS_BINDING,
2973                    array_index: 0,
2974                    // **Arguments read as data.** The mesh path records no
2975                    // indirect draw at all; what it wants out of this buffer is
2976                    // the one word only the GPU knows — how many instances
2977                    // survived into each bucket.
2978                    resource: BindingResource::whole_buffer(self.args),
2979                },
2980            ]);
2981        }
2982        // Both mesh entry points retain these native buffer arguments even
2983        // when no amplification stage reads them.
2984        if shared.clusters.is_some() {
2985            entries.extend([
2986                BindGroupEntry {
2987                    binding: CLUSTER_CULL_BINDING,
2988                    array_index: 0,
2989                    resource: BindingResource::whole_buffer(self.cull_params),
2990                },
2991                BindGroupEntry {
2992                    binding: CLUSTER_CULL_STATS_BINDING,
2993                    array_index: 0,
2994                    resource: BindingResource::whole_buffer(self.cull_stats),
2995                },
2996            ]);
2997        }
2998        entries.push(BindGroupEntry {
2999            binding: SHADOW_ATLAS_BINDING,
3000            array_index: 0,
3001            resource: BindingResource::ImageView(self.shadow_map),
3002        });
3003        entries.push(BindGroupEntry {
3004            binding: SHADOW_SAMPLER_BINDING,
3005            array_index: 0,
3006            resource: BindingResource::Sampler(shared.shadow_sampler),
3007        });
3008        // Mesh-only buffers are sorted after the common fragment prefix below.
3009        if let Some(clusters) = shared.clusters {
3010            entries.push(BindGroupEntry {
3011                binding: CLUSTER_SELECT_BINDING,
3012                array_index: 0,
3013                // Bound with the geometry rather than with the cull, because
3014                // `vertex_base` *is* geometry: it is which level of a DAG a
3015                // cluster's vertices live in, and both mesh entry points resolve
3016                // a vertex through it.
3017                resource: BindingResource::whole_buffer(clusters.selection()),
3018            });
3019        }
3020        if let Some(selection) = self.cluster_selection {
3021            entries.push(BindGroupEntry {
3022                binding: CLUSTER_SELECTION_BINDING,
3023                array_index: 0,
3024                resource: BindingResource::whole_buffer(selection),
3025            });
3026        }
3027        if let Some(state) = self.group_state {
3028            entries.push(BindGroupEntry {
3029                binding: CLUSTER_GROUP_STATE_BINDING,
3030                array_index: 0,
3031                resource: BindingResource::whole_buffer(state),
3032            });
3033        }
3034        // Topic 18's pair, on every path and in every group — see the layout,
3035        // which has no configuration that omits them either.
3036        entries.push(BindGroupEntry {
3037            binding: LIGHT_LIST_BINDING,
3038            array_index: 0,
3039            resource: BindingResource::whole_buffer(shared.lights),
3040        });
3041        entries.push(BindGroupEntry {
3042            binding: LIGHT_GRID_BINDING,
3043            array_index: 0,
3044            resource: BindingResource::whole_buffer(shared.light_grid),
3045        });
3046        // Shared fragment textures and probes retain their raster bindings.
3047        entries.push(BindGroupEntry {
3048            binding: AMBIENT_OCCLUSION_BINDING,
3049            array_index: 0,
3050            resource: BindingResource::ImageView(self.ambient_occlusion),
3051        });
3052        // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
3053        entries.push(BindGroupEntry {
3054            binding: PROBE_TABLE_BINDING,
3055            array_index: 0,
3056            resource: BindingResource::whole_buffer(shared.probes),
3057        });
3058        // Group records are present on both mesh paths, matching the layout.
3059        if shared.clusters.is_some() {
3060            entries.push(BindGroupEntry {
3061                binding: LEVEL_GROUP_TABLE_BINDING,
3062                array_index: 0,
3063                resource: BindingResource::whole_buffer(shared.tables),
3064            });
3065        }
3066        // The DFG texture is read by the fragment stage of every path.
3067        entries.push(BindGroupEntry {
3068            binding: SPECULAR_DFG_BINDING,
3069            array_index: 0,
3070            resource: BindingResource::ImageView(shared.specular_dfg),
3071        });
3072        // And §2's normal page above that, on the same ascending terms — see
3073        // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
3074        // binding 7's reason: one image, and the layer is chosen in the shader.
3075        entries.push(BindGroupEntry {
3076            binding: NORMAL_PAGE_BINDING,
3077            array_index: 0,
3078            resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
3079        });
3080        // And the area lights' table above that, on the same ascending terms —
3081        // see [`LTC_TABLE_BINDING`].
3082        entries.push(BindGroupEntry {
3083            binding: LTC_TABLE_BINDING,
3084            array_index: 0,
3085            resource: BindingResource::ImageView(shared.ltc_table),
3086        });
3087        // And the contact-shadow channel above that, last of the set and on the
3088        // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
3089        entries.push(BindGroupEntry {
3090            binding: CONTACT_SHADOW_BINDING,
3091            array_index: 0,
3092            resource: BindingResource::ImageView(self.contact_shadow),
3093        });
3094        // And the probe visibility maps above that, on the same ascending terms
3095        // — see [`PROBE_VISIBILITY_BINDING`].
3096        entries.push(BindGroupEntry {
3097            binding: PROBE_VISIBILITY_BINDING,
3098            array_index: 0,
3099            resource: BindingResource::ImageView(self.probe_visibility),
3100        });
3101        // And §2's other two pages above that, last of the set and on the same
3102        // ascending terms — see [`MRO_PAGE_BINDING`] and
3103        // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3104        // normal page's reason: one image apiece, and the layer is chosen in
3105        // the shader.
3106        entries.push(BindGroupEntry {
3107            binding: MRO_PAGE_BINDING,
3108            array_index: 0,
3109            resource: BindingResource::ImageView(
3110                shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3111            ),
3112        });
3113        entries.push(BindGroupEntry {
3114            binding: EMISSIVE_PAGE_BINDING,
3115            array_index: 0,
3116            resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3117        });
3118        entries.sort_by_key(|entry| entry.binding);
3119        entries
3120    }
3121}
3122
3123/// The two `ArrayPages` images every group of the mesh layout names, as the
3124/// graph knows them.
3125///
3126/// One value rather than two arguments because the two travel together
3127/// everywhere: every pass that declares one declares the other, and a pass
3128/// handed them the wrong way round would order a caller's copy into the wrong
3129/// image — which is a barrier bug, and therefore one that reproduces on one
3130/// backend and not the others.
3131#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3132struct MaterialPages {
3133    /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3134    base_color: ImageId,
3135    /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3136    normal: ImageId,
3137    /// §2's metallic-roughness-occlusion page —
3138    /// [`ForwardRenderer::mro_page_import`].
3139    mro: ImageId,
3140    /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3141    emissive: ImageId,
3142}
3143
3144/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3145/// as the graph knows it.
3146///
3147/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3148/// the list grew past what an argument list should be the moment the probe rows
3149/// joined it: each of these is in every cascade's bind group and read by no
3150/// cascade, so what the pass does with them is one thing — declare them, so the
3151/// graph can order whoever writes them against these draws.
3152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3153struct ShadowReads {
3154    /// The occlusion placeholder every cascade's group stands the real channel
3155    /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3156    occlusion_placeholder: ImageId,
3157    /// §3.2's and §2's pages, which the cascades name and never sample.
3158    pages: MaterialPages,
3159    /// The skinned vertex region, where a frame has one — the cascades pull the
3160    /// same geometry the colour pass does.
3161    skinned: Option<BufferId>,
3162    /// This frame's slot of the probe ring — see [`crate::probe`].
3163    probes: BufferId,
3164}
3165
3166/// What the mesh pass's bind-group layout is called.
3167///
3168/// Named rather than written twice because a test asserts on it: the layout's
3169/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3170/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3171/// has to find this one layout among the recorder's.
3172const MESH_LAYOUT_LABEL: &str = "mesh frame";
3173
3174/// Imports a buffer a pass both reads and writes, carried from one frame on
3175/// its slot to the next: it arrives in the state the previous frame that used
3176/// the slot left it in, and that is the state it is declared to leave in.
3177///
3178/// A record of the cut or a statistics sink, which a pass writes and the next
3179/// frame on the same slot writes again — a barrier naming `Undefined` as its
3180/// source would carry no source scope and order this frame's write against
3181/// nothing.
3182fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3183    graph.import_buffer(
3184        label,
3185        ImportedBuffer {
3186            buffer,
3187            initial: ResourceState::ShaderReadWrite,
3188            final_state: ResourceState::ShaderReadWrite,
3189        },
3190    )
3191}
3192
3193/// Declares the buffers a geometry pass reads to find its draws.
3194///
3195/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3196/// struct is what the encoder is told. Three passes declare exactly this set, and
3197/// the seam calls the barrier it produces the single most important one in a
3198/// GPU-driven frame — its absence produces "sometimes nothing draws".
3199///
3200/// A caller with a cluster-selection buffer of its own appends it; that is the
3201/// one declaration that differs between the colour pass, a cascade and the depth
3202/// prepass.
3203fn read_draw_sources<'g, 'a>(
3204    pass: PassBuilder<'g, 'a>,
3205    draws: &GeneratedDraws,
3206    emit: EmitTail,
3207) -> PassBuilder<'g, 'a> {
3208    // The buffers the draws come out of. Declaring them is what makes the graph
3209    // transition them out of the compute pass's `ShaderReadWrite`.
3210    let pass = pass.read_buffer(draws.runs_id);
3211    if emit.is_mesh() {
3212        // **The same arguments, read as data rather than executed**, which is
3213        // what the stages use to bound the run of surviving instances they index.
3214        // The per-bucket draw *counts* are not read at all, because nothing here
3215        // is a draw whose count could come from memory.
3216        //
3217        // The dispatch *extents* are a real indirect read — one structure per
3218        // bucket, written by the same pass. They are in a **different buffer**
3219        // from the arguments above and that separation is load-bearing: a
3220        // resource is in exactly one state per pass and these two are in
3221        // different ones. They share a buffer with the counts instead, which
3222        // this path does not read at all — see [`GeneratedDraws::counts`].
3223        let pass = pass
3224            .read_buffer(draws.args_id)
3225            .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3226        // The amplification stage counts its survivors into the culling
3227        // statistics, which the draw-argument pass read a moment ago — so this
3228        // is a write-after-read the graph has to order, and declaring it is
3229        // the whole of how it learns to.
3230        //
3231        // Topic 25's hysteresis state is read here and written by
3232        // the draw-argument pass a moment ago. Declaring it is what orders the
3233        // two — and what puts it back into `ShaderReadWrite` at the end of the
3234        // graph, which is where the next frame's draw-argument pass expects to
3235        // find it.
3236        //
3237        // **Declared on the whole mesh path, not only where there is an
3238        // amplification stage**, because that is where the bind group now
3239        // names both — see the layout, which is where the Metal argument-table
3240        // arithmetic that forced it is argued. A buffer bound writable and
3241        // never transitioned is a descriptor in the wrong resource state, which
3242        // is what the graph exists to prevent.
3243        pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3244            .read_buffer(draws.group_state_id)
3245    } else {
3246        pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3247            .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3248    }
3249}
3250
3251/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3252///
3253/// One of these per description mesh, in description order — so a mesh's index
3254/// here is its index there, which is what lets the bucket table, the level
3255/// tables and the cluster pool all be filled in by walking one list.
3256struct ResidentMesh {
3257    /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3258    /// level for a DAG. Never empty.
3259    ///
3260    /// Every level is its own vertex range and so its own table entry. Level 0's
3261    /// id is the one the *instance* carries and the one the cull pass reads a
3262    /// bounding box out of; the coarser ones are named by the bucket table on a
3263    /// path that takes a uniform cut, and by nothing at all on the mesh path,
3264    /// where a cluster reaches its own level through
3265    /// [`vertex_bases`](Self::vertex_bases) instead.
3266    levels: Vec<u32>,
3267    /// Per level, how far that level's vertices start past level 0's — so a flat
3268    /// mesh's single entry is zero.
3269    ///
3270    /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3271    /// and the whole of what makes a DAG drawable from one instance: the mesh
3272    /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3273    /// three levels reads three different vertex ranges out of one pool.
3274    vertex_bases: Vec<u32>,
3275    /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3276    /// for a [`Geometry::Dag`].
3277    ///
3278    /// A DAG is refused because its coarser levels are separate vertex runs no
3279    /// skinning dispatch writes: an instance drawn out of a skinned region
3280    /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3281    /// to the region's base, which for anything but level 0 is memory the
3282    /// dispatch never touched.
3283    skinnable: Option<MeshHandle>,
3284}
3285
3286impl ResidentMesh {
3287    /// The table id an instance of this mesh carries: **level 0's**, whatever
3288    /// the geometry path, because it is the entry `cull.slang` reads a bounding
3289    /// box out of and the coarser levels approximate the same surface inside the
3290    /// same box.
3291    fn id(&self) -> u32 {
3292        self.levels[0]
3293    }
3294}
3295
3296/// One skinned object the renderer re-points every frame: the instance, and the
3297/// base vertex it draws out of under each parity.
3298///
3299/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3300/// so placing an object does not tie the renderer's lifetime to the caller's
3301/// reservation — the renderer never needs the region again, only the two
3302/// numbers.
3303#[derive(Clone, Copy, Debug)]
3304struct SkinnedInstance {
3305    handle: InstanceHandle,
3306    /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3307    /// indexing — so the half a frame of parity `p` draws out of is
3308    /// `bases[p & 1]` and the half the frame before it filled is
3309    /// `bases[(p ^ 1) & 1]`, which is
3310    /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3311    /// answer for the same `p`.
3312    bases: [u32; 2],
3313    /// Whether a frame has already pointed this entry at a half of the region
3314    /// it now names.
3315    ///
3316    /// **What makes the previous base meaningful.** The half a frame did not
3317    /// write holds whatever its reservation came with until a dispatch fills
3318    /// it, so an object's first frame out of a region has no previous
3319    /// deformation to point at — naming that half would give it a motion vector
3320    /// against undefined vertices. Such an entry is put at rest instead, which
3321    /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3322    /// applies to `previous_transform` for the same reason: a spawn did not
3323    /// travel from anywhere.
3324    ///
3325    /// **Cleared again by a frame whose skinning cull skipped its region**,
3326    /// whose halves then hold poses from before the skip — see
3327    /// [`ForwardRenderer::cull_skinned_regions`]. So an object coming back
3328    /// into view is at rest for one frame, exactly as a fresh one is.
3329    pointed: bool,
3330}
3331
3332/// [`SkinnedInstanceDesc::bounds`] as the record carries it: the
3333/// [`OWNS_BOUNDS`](mesh::GpuInstance::OWNS_BOUNDS) bit and the box's two
3334/// corners, or no bit and a zeroed box the culls do not read.
3335///
3336/// # Errors
3337///
3338/// [`InstancePoolError::InvalidBounds`] for a box with a non-finite corner or
3339/// with `min` past `max` on any axis — see [`SkinnedInstanceDesc::bounds`].
3340fn bounds_fields(bounds: Option<Aabb>) -> Result<(u32, [f32; 3], [f32; 3]), InstancePoolError> {
3341    let Some(bounds) = bounds else {
3342        return Ok((0, [0.0; 3], [0.0; 3]));
3343    };
3344    // `min <= max` is false for a NaN lane as well as for an inverted one, and
3345    // `is_finite` is what refuses an infinity, which orders but cannot be
3346    // carried through a transform without becoming one.
3347    if !(bounds.min.is_finite() && bounds.max.is_finite() && bounds.min.cmple(bounds.max).all()) {
3348        return Err(InstancePoolError::InvalidBounds {
3349            min: bounds.min.to_array(),
3350            max: bounds.max.to_array(),
3351        });
3352    }
3353    Ok((
3354        mesh::GpuInstance::OWNS_BOUNDS,
3355        bounds.min.to_array(),
3356        bounds.max.to_array(),
3357    ))
3358}
3359
3360/// [`bounds_fields`] for [`ForwardRenderer::set_skinned_instance`], which has
3361/// no `Result` to return it through: the renderer's answer to a description it
3362/// cannot use is a panic naming it, as for a material index past the end of the
3363/// scene.
3364fn bounds_fields_or_panic(bounds: Option<Aabb>) -> (u32, [f32; 3], [f32; 3]) {
3365    bounds_fields(bounds).unwrap_or_else(|error| panic!("{error}"))
3366}
3367
3368/// The two base vertices an object drawn out of `mesh` alternates between, in
3369/// [`SkinnedInstance::bases`]' indexing.
3370fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3371    mesh.region().halves()
3372}
3373
3374/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3375/// generator is handed to the rollback.
3376struct TileBuffers {
3377    runs: Vec<BufferHandle>,
3378    args: Vec<BufferHandle>,
3379    cull_params: Vec<BufferHandle>,
3380    cull_stats: Vec<BufferHandle>,
3381    /// This cull's own hysteresis state, and not the camera's.
3382    ///
3383    /// A shadow view selects from the camera's eye at the camera's scale, like
3384    /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3385    /// it reaches a different answer for the same group, and an answer carried
3386    /// between frames needs somewhere of its own to be carried. Sharing the
3387    /// camera's buffer would be two rules writing one history and each undoing
3388    /// the other's band every frame.
3389    ///
3390    /// One per cull rather than one for the shadow pass, even though every one of
3391    /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3392    /// between them would be several dispatches writing one element with nothing
3393    /// ordering them.
3394    ///
3395    /// **This is what a cull costs that is not a dispatch.** It is
3396    /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3397    /// resident group count words of device-local
3398    /// memory, held for the renderer's whole life whether anything is drawn
3399    /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3400    /// budget rather than "however many lights the scene has" — and the reason a
3401    /// point light's six faces share one of these rather than owning six.
3402    group_state: BufferHandle,
3403}
3404
3405impl ForwardRenderer {
3406    /// Builds both pipelines and makes [`scene::demo`] resident.
3407    ///
3408    /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3409    /// nothing else — so the frame this draws is the one the golden suite has
3410    /// always compared, and every existing caller is untouched.
3411    ///
3412    /// `target_format` must be the format the tonemap pass will render into —
3413    /// dynamic rendering checks pipeline and attachment formats against each
3414    /// other at pass-begin time, not at creation.
3415    ///
3416    /// # Errors
3417    ///
3418    /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3419    pub fn new(
3420        device: &dyn Device,
3421        queue: QueueHandle,
3422        target_format: Format,
3423    ) -> Result<Self, HalError> {
3424        Self::with_scene(device, queue, target_format, &scene::demo())
3425    }
3426
3427    /// Builds both pipelines and makes `scene` resident.
3428    ///
3429    /// Everything in the description is created here and never grows: the
3430    /// geometry pools, the cluster pool, the material table, the page, the
3431    /// instance array and the bucket table are all sized and filled once. See
3432    /// [`crate::scene`] for why that split is where the seam is, and for the
3433    /// four places a description's *order* decides what the frame looks like.
3434    ///
3435    /// `target_format` must be the format the tonemap pass will render into —
3436    /// dynamic rendering checks pipeline and attachment formats against each
3437    /// other at pass-begin time, not at creation.
3438    ///
3439    /// # No description is too small
3440    ///
3441    /// One mesh and one material row is a scene, and so is
3442    /// [`scene::demo`]'s four and three. Nothing on this type names a
3443    /// description entry by position any more — the five `set_*` demo wrappers
3444    /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3445    /// and the row a caller wrote its **own** description in.
3446    ///
3447    /// # Errors
3448    ///
3449    /// [`HalError::InvalidDescriptor`] if the description cannot be made
3450    /// resident as written: a page layer that is not its kind's extent's worth of
3451    /// RGBA8, a page kind holding layers at no extent, a material row naming a
3452    /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3453    /// levels, a cluster array with a read outside itself in it (see
3454    /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3455    /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3456    /// capacity and what the description needs, because the answer to it is to
3457    /// raise the number. Every one of those is settled **before the first device
3458    /// object exists**, so a refusal leaks nothing.
3459    ///
3460    /// [`HalError`] otherwise, from any seam call — including the geometry a
3461    /// pool refuses for itself, such as vertex bytes that are not a whole number
3462    /// of vertices. A backend that cannot build a pipeline says so here rather
3463    /// than drawing nothing later, and a failure part-way through releases
3464    /// everything already created, so a caller that retries or exits leaves
3465    /// nothing behind.
3466    pub fn with_scene(
3467        device: &dyn Device,
3468        queue: QueueHandle,
3469        target_format: Format,
3470        scene: &SceneDesc<'_>,
3471    ) -> Result<Self, HalError> {
3472        Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3473    }
3474
3475    /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3476    /// the build so the thread running it can keep its window alive.
3477    ///
3478    /// # What it is for: a build on the thread that owns the window
3479    ///
3480    /// The build needs the device, so it runs on whichever thread holds it —
3481    /// for a game that is the loop thread, which also owns the window, and a
3482    /// desktop marks a window hung when its thread takes no message for a few
3483    /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3484    /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3485    /// whole build.
3486    ///
3487    /// # Where it is called
3488    ///
3489    /// Where the time is, which was measured rather than guessed. With a cold
3490    /// driver shader cache — a player's first launch, or the first after a
3491    /// driver update — **pipeline creation is most of the build**. Measured in
3492    /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3493    /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3494    /// mesh and page uploads took about 0.1 s either way. So `service` runs
3495    /// after every mesh upload (each level of a DAG), after every page layer's
3496    /// mip chain and each page's upload, after each of the camera's
3497    /// post-processing subsystems, before every round of the mesh-pass
3498    /// pipelines, and between the build's other phases. The water and grass
3499    /// passes are not built here: the first frame with a body or a field
3500    /// builds them, unless the caller builds them first under the same kind of
3501    /// `service` with [`prepare_content`](Self::prepare_content).
3502    ///
3503    /// **The longest gap left is about one pipeline**, and a pipeline cannot be
3504    /// split: on that scene, cold, it was the forward pass's colour pipeline
3505    /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3506    /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3507    /// eight times slower under contention still calls back inside the five
3508    /// seconds Windows allows.
3509    ///
3510    /// **One condition on that bound.** The mesh-pass pipelines are compiled
3511    /// as one batch on a device that can take them from several
3512    /// threads, in rounds of a small fixed number of pipelines with `service`
3513    /// on this thread before each — see `crate::pipeline_batch`. A driver that
3514    /// compiles side by side finishes a round in about its slowest compile, so
3515    /// the bound holds. One that serialises its compiles internally takes a
3516    /// whole round's worth between two calls, which is still bounded — the
3517    /// round is capped — but leaves about a quarter of the headroom above: a
3518    /// machine twice as slow rather than eight times. On a device that cannot take
3519    /// pipelines from several threads, `service` runs before each pipeline as
3520    /// it always did.
3521    ///
3522    /// `service` sees nothing of the build and cannot touch the renderer or the
3523    /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3524    /// request — is the caller's to keep for later, as
3525    /// `crcbl_shell::Shell::keep_alive` does.
3526    ///
3527    /// # Errors
3528    ///
3529    /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3530    /// through releases everything already created.
3531    pub fn with_scene_serviced(
3532        device: &dyn Device,
3533        queue: QueueHandle,
3534        target_format: Format,
3535        scene: &SceneDesc<'_>,
3536        service: &mut dyn FnMut(),
3537    ) -> Result<Self, HalError> {
3538        Self::build_on_path(
3539            device,
3540            queue,
3541            target_format,
3542            scene,
3543            device.preferred_geometry_path(),
3544            service,
3545        )
3546    }
3547
3548    /// Builds exactly the requested geometry tail, independently of the device's
3549    /// performance preference. Capabilities remain available to other callers.
3550    ///
3551    /// # Errors
3552    ///
3553    /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3554    /// when the requested tail lacks its required feature. Other failures follow
3555    /// [`Self::with_scene`]'s rollback contract.
3556    pub fn with_scene_on_path(
3557        device: &dyn Device,
3558        queue: QueueHandle,
3559        target_format: Format,
3560        scene: &SceneDesc<'_>,
3561        geometry_path: GeometryPath,
3562    ) -> Result<Self, HalError> {
3563        Self::build_on_path(
3564            device,
3565            queue,
3566            target_format,
3567            scene,
3568            geometry_path,
3569            &mut || {},
3570        )
3571    }
3572
3573    /// The body of [`Self::with_scene_on_path`] and
3574    /// [`Self::with_scene_serviced`], calling `service` where the latter
3575    /// documents.
3576    fn build_on_path(
3577        device: &dyn Device,
3578        queue: QueueHandle,
3579        target_format: Format,
3580        scene: &SceneDesc<'_>,
3581        geometry_path: GeometryPath,
3582        service: &mut dyn FnMut(),
3583    ) -> Result<Self, HalError> {
3584        let required = match geometry_path {
3585            GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3586            GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3587            GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3588        };
3589        let missing = required.difference(device.caps().features);
3590        if !missing.is_empty() {
3591            return Err(HalError::UnsupportedFeatures { missing });
3592        }
3593        crcbl_frame::require_frame_queue(device, queue, "a forward renderer")?;
3594        let mut rollback = Rollback::default();
3595        // **One submission and no wait for the build's small uploads**: the
3596        // placeholders, the split-sum and area-light tables, and every view's
3597        // and shadow cull's start-up fills are recorded into this batch as they
3598        // are created, and submitted once the renderer is whole. Each used to
3599        // be its own submit and `wait_idle`, and on Mesa's ANV the first submit
3600        // on a fresh device costs several milliseconds and every later round
3601        // trip about half of one. The geometry pools, the pages and the probe
3602        // table still submit for themselves, all of them before this batch's
3603        // submission, and none of them reads anything it writes.
3604        //
3605        // The batch is submitted without a wait: every reader of what it
3606        // writes is a frame on this same queue, after it, which is all the
3607        // ordering the copies need — see `PendingUpload`. Its staging is
3608        // retired by the first `begin_frame` that finds its semaphore
3609        // signalled, or waited for by `destroy`.
3610        let mut uploads = UploadBatch::new(device, queue, "forward");
3611        match Self::build(
3612            device,
3613            &mut uploads,
3614            target_format,
3615            scene,
3616            geometry_path,
3617            &mut rollback,
3618            service,
3619        ) {
3620            // The submit is the build's last fallible step, so nothing can
3621            // fail between it and the renderer owning the upload: a failed
3622            // submit leaves nothing pending, and `destroy` finds an empty list.
3623            Ok(mut renderer) => match uploads.submit_deferred() {
3624                Ok(pending) => {
3625                    renderer.uploads_in_flight.push(pending);
3626                    Ok(renderer)
3627                }
3628                Err(error) => {
3629                    renderer.destroy(device);
3630                    Err(error)
3631                }
3632            },
3633            Err(error) => {
3634                // The batch first, so nothing it recorded is still pending when
3635                // the rollback destroys what it recorded into.
3636                drop(uploads);
3637                rollback.run(device);
3638                Err(error)
3639            }
3640        }
3641    }
3642
3643    /// Releases every start-up upload the GPU is known to be past, without
3644    /// blocking — the first thing each `begin_frame` does.
3645    ///
3646    /// # Errors
3647    ///
3648    /// [`HalError`] from reading a semaphore — a lost device. What was not
3649    /// released stays in the list.
3650    fn retire_uploads(&mut self, device: &dyn Device) -> Result<(), HalError> {
3651        let mut index = 0;
3652        while index < self.uploads_in_flight.len() {
3653            if self.uploads_in_flight[index].poll(device)? {
3654                // Retired, so dropping it releases nothing and logs nothing.
3655                drop(self.uploads_in_flight.swap_remove(index));
3656            } else {
3657                index += 1;
3658            }
3659        }
3660        Ok(())
3661    }
3662
3663    /// Blocks until every start-up upload has landed and releases them, before
3664    /// `caller` destroys anything their copies write.
3665    ///
3666    /// A failed wait is a lost device. What it would have released is leaked
3667    /// rather than freed under the GPU, and said so in the log; the caller goes
3668    /// on, as a destroy has nothing to hand an error to.
3669    fn wait_for_uploads(&mut self, device: &dyn Device, caller: &str) {
3670        for mut pending in self.uploads_in_flight.drain(..) {
3671            if let Err(error) = pending.wait(device) {
3672                crcbl_core::log::warn!(
3673                    "ForwardRenderer::{caller}: a start-up upload's wait failed ({error}); its \
3674                     staging buffers are leaked rather than freed under the GPU"
3675                );
3676                // Dropping it is the leak, and it logs one of its own.
3677            }
3678        }
3679    }
3680
3681    /// Everything `build` needs to be true of a description, checked **before
3682    /// the first device object exists**.
3683    ///
3684    /// That placement is the whole design of this function. `build` hands the
3685    /// geometry pool and the material table to the rollback and creates a dozen
3686    /// objects with `?` between them; a check that ran part way down that list
3687    /// would be a new early exit on the wrong side of a handover, and a rejected
3688    /// description would leak two device-local buffers. Run from the top of
3689    /// `build`, a refusal costs nothing to unwind because nothing was made.
3690    ///
3691    /// # Errors
3692    ///
3693    /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3694    /// is wrong with it.
3695    fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3696        let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3697        // A renderer draws meshes, and every table below is sized from them:
3698        // with none, the mesh table's sizing has no level to take a maximum
3699        // of. A scene that draws only the sky is one with meshes and no
3700        // instances.
3701        if scene.meshes.is_empty() {
3702            return refuse(
3703                "a scene description needs at least one mesh; one with meshes and no \
3704                 instances draws only the sky"
3705                    .to_owned(),
3706            );
3707        }
3708        // Every layer's length against its own kind's extent, and layers at no
3709        // extent at all. Checked by the type that owns the page rather than
3710        // here, because that is where a page can be built wrong and where the
3711        // check can be made to fail; see `PageDesc::check`.
3712        scene.page.check()?;
3713        // The probe grid's counts against the rows it carries, which is what
3714        // bounds the shader's fetch. Checked by the type that owns the grid, on
3715        // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3716        scene.probes.check()?;
3717        // A row naming a layer the page does not have is an out-of-range sample,
3718        // which nothing below the seam reports.
3719        //
3720        // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3721        // value: it is a sentinel rather than an index — `0xFFFF`, one past
3722        // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3723        // fragment stage never reads a page for it. Exempting it here is what
3724        // lets a material name no texture without the page having to carry a
3725        // layer for it to point at — or, since row (d), having to exist at all.
3726        //
3727        // **Per kind**, because the kinds are separate images with separate
3728        // layer lists and separate extents: a row pointed at a base-colour layer
3729        // number would pass a check that only counted one of them and then
3730        // sample past the end of the other image.
3731        for (row, material) in scene.materials.iter().enumerate() {
3732            for kind in PageKind::ALL {
3733                let names = match kind {
3734                    PageKind::BaseColor => material.base_color_texture,
3735                    PageKind::Normal => material.normal_texture,
3736                    PageKind::MetallicRoughnessOcclusion => {
3737                        material.metallic_roughness_occlusion_texture
3738                    }
3739                    PageKind::Emissive => material.emissive_texture,
3740                };
3741                if names == mesh::GpuMaterial::NO_PAGE {
3742                    continue;
3743                }
3744                let have = scene.page.layers(kind).len();
3745                if names as usize >= have {
3746                    return refuse(format!(
3747                        "material row {row} samples {} page layer {names}, and that page \
3748                         has {have}",
3749                        kind.label()
3750                    ));
3751                }
3752            }
3753        }
3754
3755        for (index, desc) in scene.meshes.iter().enumerate() {
3756            let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3757                continue;
3758            };
3759            // Zipped together at upload and again at
3760            // `ClusterDag::selection_records`, so a short list would silently
3761            // leave a level's clusters reading the level below's vertices.
3762            if levels.len() != dag.levels.len() {
3763                return refuse(format!(
3764                    "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3765                    desc.label,
3766                    levels.len(),
3767                    dag.levels.len()
3768                ));
3769            }
3770            for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3771                let want = level.positions.len() * mesh::VERTEX_STRIDE;
3772                if bytes.len() != want {
3773                    return refuse(format!(
3774                        "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3775                         position(s), which is {want}",
3776                        desc.label,
3777                        bytes.len(),
3778                        level.positions.len()
3779                    ));
3780                }
3781            }
3782        }
3783
3784        // **Every read the mesh stage makes from a cluster array lands inside
3785        // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3786        // terms exactly — see `MeshClusters::check`, which is where the reason
3787        // it cannot be checked below the seam is argued. Both variants carry
3788        // the same type beside a vertex count, so both are checked the same way.
3789        for (index, desc) in scene.meshes.iter().enumerate() {
3790            let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3791                Geometry::Flat {
3792                    vertices, clusters, ..
3793                } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3794                Geometry::Dag { dag, .. } => dag
3795                    .levels
3796                    .iter()
3797                    .map(|level| (level.positions.len(), &level.clusters))
3798                    .collect(),
3799            };
3800            for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3801                if let Err(fault) = clusters.check(vertices) {
3802                    return refuse(format!(
3803                        "mesh {index} ({}) level {depth} {fault}",
3804                        desc.label
3805                    ));
3806                }
3807            }
3808        }
3809
3810        // **Capacity, summed over the whole description**, which is the one
3811        // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3812        // do refuse their own overflow, but they refuse it part way through
3813        // filling something that already exists, and the pair of numbers
3814        // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3815        // carries to tell fragmentation from a full pool says nothing *here*:
3816        // the pool was created empty a few lines below, nothing has been freed
3817        // in it, so its free list is one block and the largest block and the
3818        // total are the same number. At build the answer is always "raise this
3819        // capacity", so it is said by name and before anything is created.
3820        let mut vertices: u64 = 0;
3821        let mut indices: u64 = 0;
3822        for desc in &scene.meshes {
3823            match &desc.geometry {
3824                Geometry::Flat {
3825                    vertices: bytes,
3826                    indices: list,
3827                    ..
3828                } => {
3829                    // Bytes that are not a whole number of vertices are the
3830                    // pool's to refuse, and it refuses before it allocates.
3831                    vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3832                    indices += list.len() as u64;
3833                }
3834                Geometry::Dag { levels, dag, .. } => {
3835                    for bytes in levels {
3836                        vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3837                    }
3838                    for level in &dag.levels {
3839                        // The call the upload itself makes, so the two cannot
3840                        // disagree about what a level costs.
3841                        indices += level.indices().len() as u64;
3842                    }
3843                }
3844            }
3845        }
3846        let entries: u64 = scene
3847            .meshes
3848            .iter()
3849            .map(|desc| desc.geometry.levels() as u64)
3850            .sum();
3851        for (pool, needed, capacity) in [
3852            ("vertex pool", vertices, scene.capacities.vertices),
3853            ("index pool", indices, scene.capacities.indices),
3854            ("mesh table", entries, scene.capacities.meshes),
3855            (
3856                "material table",
3857                scene.materials.len() as u64,
3858                scene.capacities.materials,
3859            ),
3860            (
3861                "probe table",
3862                scene.probes.probes.len() as u64,
3863                scene.capacities.probes,
3864            ),
3865        ] {
3866            if needed > u64::from(capacity) {
3867                return refuse(format!(
3868                    "the {pool} holds {capacity} and the description needs {needed}"
3869                ));
3870            }
3871        }
3872        Ok(())
3873    }
3874
3875    /// The body of [`ForwardRenderer::with_scene`], recording what it has
3876    /// created into `rollback` as it goes and calling `service` where
3877    /// [`ForwardRenderer::with_scene_serviced`] documents.
3878    ///
3879    /// The small start-up uploads go into `uploads`, which the caller submits
3880    /// once this has returned the renderer — nothing here may read them on the
3881    /// GPU first. What still submits for itself takes the batch's queue.
3882    fn build(
3883        device: &dyn Device,
3884        uploads: &mut UploadBatch<'_>,
3885        target_format: Format,
3886        scene: &SceneDesc<'_>,
3887        geometry_path: GeometryPath,
3888        rollback: &mut Rollback,
3889        service: &mut dyn FnMut(),
3890    ) -> Result<Self, HalError> {
3891        // Before anything exists, so a refused description leaks nothing — see
3892        // `check_scene`, which is where that placement is argued.
3893        Self::check_scene(scene)?;
3894        let queue = uploads.queue();
3895
3896        // Resolved before anything is created, because it decides the *shape*
3897        // of what is created — the bind group layout, which pipeline kind the
3898        // pass builds, and what a bucket's constant block says. A device on the
3899        // mesh path never builds the raster pipeline and a device on either
3900        // indirect tail never builds the mesh one, which is what makes "the
3901        // frame came out of the mesh stage" a fact about the object graph
3902        // rather than a claim about a branch.
3903        let emit = EmitTail::from_path(geometry_path);
3904        // And whether that tail draws a range of buckets per call, which only
3905        // changes what the passes record — the constant blocks carry the words
3906        // both shapes read — so it decides nothing about what is created.
3907        let range_limit = emit.range_limit(&device.caps());
3908        // **A second capability, asked separately.** `Features::TASK_SHADER` is
3909        // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3910        // amplification stage this renderer builds where the device has one and
3911        // leaves out where it does not — and a device without it keeps drawing
3912        // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3913        // nothing and emits every cluster. Same picture, more work.
3914        let culls_clusters = emit.is_mesh()
3915            && device
3916                .caps()
3917                .features
3918                .contains(crcbl_hal::Features::TASK_SHADER);
3919
3920        let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3921        // What an `InstanceDesc::mesh` index resolves through: one id per
3922        // description mesh, in description order, and each of them that mesh's
3923        // **level 0** whatever the path — because it is the entry the cull pass
3924        // reads a bounding box out of, and a DAG's coarser levels approximate
3925        // the same surface inside the same box.
3926        let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3927        // The scene's own triangles, kept for the probe-visibility capture and
3928        // for nothing else — and kept at all only when the description reserves
3929        // a probe, so a scene without one pays no memory for this rung. Taken
3930        // here because `scene` is the caller's and is read once.
3931        let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3932        // The same list one level down: what a caller reserving a skinned region
3933        // names its mesh with. Read here beside the ids rather than from
3934        // `residents` later, because the descriptions this came from are the
3935        // caller's and are read once.
3936        let skinnable_meshes: Vec<Option<MeshHandle>> =
3937            residents.iter().map(|mesh| mesh.skinnable).collect();
3938        // The handles are `Copy`, so they can be read out before the pool
3939        // becomes the rollback's — which it must be before the first `?` below,
3940        // or a failed pipeline would leak two device-local buffers. The index
3941        // pool is not named here at all: it is bound at draw time rather than
3942        // descriptor-written, so only the vertex pool and the mesh table reach a
3943        // bind group.
3944        let vertices = pool.vertex_buffer();
3945        let mesh_table = pool.table_buffer();
3946        rollback.pool = Some(pool);
3947
3948        // §3.2's texture side, before the table that indexes it: a material row
3949        // is written with a layer number, so the layer has to exist to be named.
3950        //
3951        // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3952        // three answers the kind itself owns — its format, its mip filter and
3953        // its device label — and everything else about creating a page is the
3954        // same code. Two hand-written copies were what let the normal page be
3955        // created through the colour page's filter for as long as nobody
3956        // compared the two, and rung 3 adds two more kinds to get wrong.
3957        //
3958        // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3959        // normal page, and that is the colour-space decision.** A base-colour
3960        // description's texels are sRGB-encoded, which is what glTF defines a
3961        // base-colour texture to be, so the format is what makes the sampler
3962        // decode them — and `mesh.slang` then multiplies a linear texel by a
3963        // linear `base_color` and lights in linear, exactly as it did before
3964        // there was a texture. A normal texel is a *number* and nothing decodes
3965        // it. See `PageKind::format`, and topic 44's rung 2.
3966        //
3967        // Every layer's length against its kind's extent was settled by
3968        // `check_scene` above, before this device object existed.
3969        //
3970        // **Every layer goes up with its mip chain**, built here on the host by
3971        // [`crate::mip`] — topic 43's filtering rung.
3972        // The chain is what a trilinear sampler needs to stop shimmering on a
3973        // minified surface, and it is built at upload rather than by a compute
3974        // pass because the page's format is what decodes it and a host chain is
3975        // the same bytes on every backend.
3976        //
3977        // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3978        // refuses a zero-layer image and every bind group has to fill both page
3979        // bindings, so a page nothing names is created 1×1 in its own format
3980        // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3981        // and which is magenta so that a frame says so if it ever does.
3982        //
3983        // The upload itself is [`upload_page`], shared with
3984        // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3985        // renderer is built exactly as this one was. A layer's chain is host
3986        // work proportional to its texels, so a page of many large layers is
3987        // serviced one layer at a time.
3988        let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3989        let mut page_extents = [(1, 1); PageKind::ALL.len()];
3990        let mut page_layers = [0; PageKind::ALL.len()];
3991        for kind in PageKind::ALL {
3992            let layers = scene.page.layers(kind);
3993            let (page, extent) = upload_page(
3994                device,
3995                queue,
3996                kind,
3997                scene.page.extent(kind),
3998                layers,
3999                service,
4000            )?;
4001            rollback.textures.push(page);
4002            page_extents[kind.index()] = (extent, extent);
4003            page_layers[kind.index()] = layers.len();
4004            pages[kind.index()] = Some(page);
4005            service();
4006        }
4007        let [
4008            Some(base_color_page),
4009            Some(normal_page),
4010            Some(mro_page),
4011            Some(emissive_page),
4012        ] = pages
4013        else {
4014            unreachable!("the loop above fills a slot for every PageKind::ALL entry");
4015        };
4016
4017        // The page's sampler at the device's default — see `create_page_sampler`
4018        // for what it filters, and `set_anisotropy` for how a caller moves it.
4019        let anisotropy = Self::anisotropy_for(&device.caps());
4020        let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
4021        rollback.samplers.push(base_color_sampler);
4022        // What every slot's groups are built naming, and what each moves off
4023        // only at its own frame — see `ForwardRenderer::adopt_pages`.
4024        let page_bindings = PageBindings {
4025            sampler: base_color_sampler,
4026            views: [
4027                base_color_page.view,
4028                normal_page.view,
4029                mro_page.view,
4030                emissive_page.view,
4031            ],
4032        };
4033
4034        // The material table, before the instances: an instance is written with
4035        // the material id it carries, so the row has to exist to be named.
4036        let (materials, material_ids) = Self::build_materials(device, scene)?;
4037        let material_buffer = materials.buffer();
4038        rollback.materials = Some(materials);
4039
4040        // Topic 50's irradiance grid: the table is created here once, and
4041        // `crate::probe_gather`'s compute pass rewrites its rows every frame —
4042        // see [`crate::probe`]. **Created even for a description with no probes**, because
4043        // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
4044        // honest filler for "no probes were authored" is the zeroed row the
4045        // shader's clamp lands on.
4046        let probe_table = ProbeTable::new(
4047            device,
4048            queue,
4049            &ProbeTableDesc {
4050                label: Some("forward"),
4051                capacity: scene.capacities.probes,
4052                frames: FRAMES_IN_FLIGHT,
4053            },
4054        )?;
4055        // Into the rollback before it is filled, so a copy that fails releases
4056        // the buffers rather than leaking them.
4057        rollback.probes = Some(probe_table);
4058        let probe_table = rollback.probes.as_ref().expect("just stored");
4059        probe_table.fill(device, queue, &scene.probes.probes)?;
4060        // Read out here, like the instance ring's below and for the same
4061        // reason: the handles are `Copy`, and the loop that builds the bind
4062        // groups mutates the rollback the table now lives in.
4063        let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
4064            .map(|frame| probe_table.buffer(frame))
4065            .collect();
4066        // The irradiance probes' updater, built **only** for a
4067        // description that asked for it. A volume left at
4068        // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
4069        // the default really is the frame every scene drew before this landed.
4070        let probe_gather = match scene.probes.update {
4071            ProbeUpdate::Authored => None,
4072            ProbeUpdate::EveryFrame => Some(ProbeGather::new(
4073                device,
4074                &ProbeGatherDesc {
4075                    label: Some("forward probes"),
4076                    volume: scene.probes.volume,
4077                    probes: &probe_buffers,
4078                },
4079            )?),
4080        };
4081        rollback.probe_gather = probe_gather;
4082        let probe_gather = rollback.probe_gather.take();
4083        service();
4084
4085        // **Empty.** Every object in the scene arrives through
4086        // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
4087        // renderer that inserted one of its description's meshes here would put
4088        // an object in a caller's frame that the caller never asked for.
4089        let instances = InstancePool::new(
4090            device,
4091            &InstancePoolDesc {
4092                label: Some("forward instances"),
4093                capacity: scene.capacities.instances,
4094                frames_in_flight: FRAMES_IN_FLIGHT,
4095            },
4096        )?;
4097        // Same handle-then-hand-over dance as the geometry pool above: the
4098        // buffers are `Copy` and are read out before the pool becomes the
4099        // rollback's, which it must be before the first `?` below — after which
4100        // nothing needs the pool again until `begin_frame`.
4101        let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
4102        rollback.instances = Some(instances);
4103
4104        // The two compute passes, and the buffers the draws come out of. Built
4105        // here rather than beside the pipelines below because the mesh bind
4106        // group names one of its buffers, so it has to exist first.
4107        //
4108        // The bucket table, and the one place its order is decided.
4109        //
4110        // **Built by walking the description**, which is what makes a duplicate
4111        // structurally impossible rather than refused: every bucket's mesh id is
4112        // the id of the description mesh it came from, and two description
4113        // meshes are two uploads with two table entries however alike their
4114        // geometry is. That matters because `draw_gen.slang`'s scatter takes the
4115        // *first* bucket whose mesh id matches, so a second bucket naming one
4116        // mesh would never draw anything at all.
4117        //
4118        // One bucket per mesh, except for two things. A DAG is one bucket where
4119        // an amplification stage picks its cut per cluster and one per level
4120        // where the cull pass picks a uniform one — see [`buckets_for`]. And the
4121        // whole run is repeated once per **material mode** the scene holds, so
4122        // an instance's mode picks a bucket exactly as its mesh does; see
4123        // [`ForwardRenderer::bucket_modes`].
4124        //
4125        // **Mode-major: every mesh's run for one mode, then the next mode's.**
4126        // A mode picks the pipeline a pass binds, so this makes each pipeline's
4127        // partition — [`ForwardRenderer::depth_partitions`] and
4128        // [`ForwardRenderer::sided_partitions`] — one contiguous run of
4129        // buckets, which a device with a draw index records as one ranged call
4130        // rather than a call per bucket — and which the mesh tail behind a
4131        // task stage must have, because it draws each partition as one flat
4132        // call of its run. `DEPTH_MODES` order makes a sided partition one run
4133        // too: opaque sits beside masked, and double-sided beside both.
4134        //
4135        // **Once per mode the scene holds, not once per mode that exists.** A
4136        // scene whose materials are all opaque gets exactly the table it always
4137        // had — same length, same order, same bytes — so the twin costs nothing
4138        // where nothing is masked, which is every demo and every golden here. A
4139        // bucket is not free: every pass records one indirect call per bucket
4140        // per view, and every generator holds its run start.
4141        let scene_modes: Vec<u32> = {
4142            let held: Vec<u32> = DEPTH_MODES
4143                .into_iter()
4144                .filter(|mode| {
4145                    scene
4146                        .materials
4147                        .iter()
4148                        .any(|material| material.mode() == *mode)
4149                })
4150                .collect();
4151            // A description with no materials at all still needs a bucket per
4152            // mesh, or nothing it holds can be drawn.
4153            if held.is_empty() {
4154                vec![DEPTH_MODES[0]]
4155            } else {
4156                held
4157            }
4158        };
4159        // One mode's run: every description mesh's levels, in description
4160        // order. `bucket_bases` is where each mesh starts within it, so the
4161        // tables below can be filled in mesh by mesh rather than by re-deriving
4162        // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
4163        let mut mode_run: Vec<u32> = Vec::new();
4164        let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
4165        for resident in &residents {
4166            bucket_bases.push(mode_run.len());
4167            mode_run
4168                .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
4169        }
4170        let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
4171        // The mode each of those buckets draws, in step with it.
4172        let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
4173        for mode in &scene_modes {
4174            bucket_meshes.extend_from_slice(&mode_run);
4175            bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
4176        }
4177        let bucket_count = u32::try_from(bucket_meshes.len())
4178            .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
4179
4180        // Topic 25's selection tables, and the one thing that
4181        // decides whether `draw_gen.slang` takes a uniform cut at all.
4182        //
4183        // Every mesh id gets an entry, because the shader indexes this with
4184        // `GpuInstance::mesh` and an instance can name any of them; the default
4185        // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
4186        // so a mesh with no hierarchy resolves back to itself with no branch.
4187        // **A DAG keeps that default on the mesh path**, which is how a device
4188        // already descending it per cluster avoids a second, coarser cut on top
4189        // of it — the suppression is data rather than a branch in the shader.
4190        //
4191        // **Sized by the mesh table's capacity, not by the meshes resident in
4192        // it**, because that is the invariant `draw_gen.slang`'s
4193        // `mesh_levels_of` states and indexes on: "every entry an instance can
4194        // name is filled". The read is unbounded and an instance's mesh id is a
4195        // bare table index, so a table sized to the description alone is an
4196        // out-of-range read of whatever the packer laid down next for any id the
4197        // description did not fill. What it finds there decides the frame: zeros
4198        // resolve to mesh 0 and draw another mesh's geometry, and a live
4199        // `group_count` sends `select_level`'s loop over a count no allocation
4200        // backs, which on radv is a hard GPU recovery rather than a wrong
4201        // picture. That is not a hypothetical: it is what a skinned instance
4202        // naming an alias entry did until 2026-08, before it learned to name its
4203        // source mesh instead.
4204        let table_len = usize::try_from(scene.capacities.meshes)
4205            .unwrap_or(usize::MAX)
4206            .max(
4207                usize::try_from(
4208                    residents
4209                        .iter()
4210                        .flat_map(|resident| resident.levels.iter().copied())
4211                        .max()
4212                        .unwrap_or_else(|| {
4213                            unreachable!("check_scene refused an empty description")
4214                        })
4215                        + 1,
4216                )
4217                .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
4218            );
4219        let mut level_meshes: Vec<u32> = (0..table_len)
4220            .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4221            .collect();
4222        let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4223            .iter()
4224            .map(|&id| level_select::MeshLevels {
4225                first_level: id,
4226                ..level_select::MeshLevels::FLAT
4227            })
4228            .collect();
4229        // Every DAG's groups end to end, in description order, and where each
4230        // one's run starts. `ClusterSelect` records name a group by its index in
4231        // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4232        // several DAGs concatenate without `crcbl-shaders` knowing they did.
4233        let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4234        let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4235        for (index, desc) in scene.meshes.iter().enumerate() {
4236            first_groups.push(
4237                u32::try_from(level_groups.len())
4238                    .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4239            );
4240            let Geometry::Dag { dag, .. } = &desc.geometry else {
4241                continue;
4242            };
4243            let groups = dag.level_groups();
4244            let id = residents[index].id();
4245            mesh_levels[id as usize] = level_select::MeshLevels {
4246                first_group: first_groups[index],
4247                group_count: u32::try_from(groups.len())
4248                    .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4249                // **The mesh path suppresses the uniform cut with a top level of
4250                // zero, not with a group count of zero**, and the difference is
4251                // the hysteresis state: `draw_gen.slang` judges every group it is
4252                // given whatever level it answers, and the amplification stage
4253                // reads those answers. A record naming no groups would leave the
4254                // state untouched and every cluster of the patch collapsed. A
4255                // top level of zero makes the level loop's minimum unreachable,
4256                // so the instance routes to the mesh it already names — which is
4257                // level 0.
4258                first_level: if emit.is_mesh() {
4259                    id
4260                } else {
4261                    u32::try_from(level_meshes.len())
4262                        .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4263                },
4264                top_level: if emit.is_mesh() {
4265                    0
4266                } else {
4267                    u32::try_from(residents[index].levels.len() - 1)
4268                        .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4269                },
4270            };
4271            level_groups.extend(groups);
4272            if !emit.is_mesh() {
4273                level_meshes.extend_from_slice(&residents[index].levels);
4274            }
4275        }
4276
4277        // §3.5's clusters, on the path that reads them and on no other. The
4278        // records are `crcbl-shaders`' — cooked, because the builder is
4279        // `crcbl-scene`'s and the renderer must not depend on that crate — and
4280        // they arrive in bucket-mesh order so a bucket's range is its own
4281        // index. See `crate::cluster_pool`.
4282        //
4283        // Before the draw generation below rather than after it, because the
4284        // per-bucket cluster counts are the x extent of each bucket's mesh
4285        // dispatch and that pass writes the argument structure carrying them.
4286        let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4287        let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4288        let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4289        if emit.is_mesh() {
4290            // A flat mesh is one pool entry and its clusters carry
4291            // `ClusterSelect::ALWAYS`, so the descent draws them from every
4292            // camera; a DAG is **one entry per level**, laid end to end.
4293            let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4294            // Where each description mesh's entries start, on `bucket_bases`'
4295            // terms — the two differ exactly where a DAG's levels are one bucket
4296            // and several entries.
4297            let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4298            for (index, desc) in scene.meshes.iter().enumerate() {
4299                entry_bases.push(cooked.len());
4300                match &desc.geometry {
4301                    Geometry::Flat { clusters, .. } => {
4302                        cooked.push(PooledMesh::without_lod(clusters.clone()));
4303                    }
4304                    Geometry::Dag { dag, .. } => {
4305                        let selection = dag
4306                            .selection_records(&residents[index].vertex_bases, first_groups[index]);
4307                        for (level, records) in dag.levels.iter().zip(selection) {
4308                            cooked.push(PooledMesh {
4309                                clusters: level.clusters.clone(),
4310                                selection: records,
4311                            });
4312                        }
4313                    }
4314                }
4315            }
4316
4317            let clusters = ClusterPool::new(device, "forward", &cooked)?;
4318            let range = |entry: usize| {
4319                clusters
4320                    .range(entry)
4321                    .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4322            };
4323            // **A DAG's levels are one run, not one per bucket.** `concatenate`
4324            // lays the entries down in the order it was given them, so the
4325            // levels are contiguous: the bucket starts where level 0 does and
4326            // reaches to the end of the last level. That is what lets one
4327            // dispatch cover a cut spanning several of them — and it is why a
4328            // flat mesh, whose one entry is the whole sum, needs no second case.
4329            mesh_clusters.reserve(residents.len());
4330            for (index, resident) in residents.iter().enumerate() {
4331                let entry = entry_bases[index];
4332                let base = range(entry).base;
4333                let count: u32 = (entry..entry + resident.levels.len())
4334                    .map(|entry| range(entry).count)
4335                    .sum();
4336                // **Every one of this mesh's buckets, not only the first.** A
4337                // mode twin draws the same geometry, so it dispatches over the
4338                // same clusters; a twin left at zero launches no workgroup and
4339                // its instances vanish from the frame. One bucket per mode here,
4340                // because the mesh path takes `buckets_for` of one, each a whole
4341                // mode's run past the one before.
4342                for slot in 0..scene_modes.len() {
4343                    let bucket = slot * mode_run.len() + bucket_bases[index];
4344                    bucket_cluster_bases[bucket] = base;
4345                    bucket_clusters[bucket] = count;
4346                }
4347                mesh_clusters.push(ClusterRange { base, count });
4348            }
4349
4350            rollback.clusters = Some(clusters);
4351            service();
4352        }
4353
4354        // One ring per shadow view, indexed `[view][frame]`: topic 25's
4355        // observable, one word per resident cluster holding the cut the descent
4356        // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4357        // share the camera's, which [`View::build`] allocates beside its cull.
4358        //
4359        // Allocated on the whole mesh path rather than only where there is an
4360        // amplification stage to write them, because the layout declares
4361        // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4362        let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4363        if emit.is_mesh() {
4364            let count = rollback
4365                .clusters
4366                .as_ref()
4367                .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4368                .count();
4369            let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4370                let mut buffers = Vec::with_capacity(instance_buffers.len());
4371                for frame in 0..instance_buffers.len() {
4372                    let buffer = device.create_buffer(&BufferDesc {
4373                        label: Some(&format!("{label} {frame}")),
4374                        size: u64::from(count) * 4,
4375                        usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4376                        memory: MemoryLocation::DeviceLocal,
4377                    })?;
4378                    rollback.buffers.push(buffer);
4379                    buffers.push(buffer);
4380                }
4381                Ok(buffers)
4382            };
4383            for view in 0..SHADOW_VIEWS {
4384                tile_selection.push(ring(&format!("shadow selection {view}"))?);
4385            }
4386        }
4387
4388        // --- the mesh pass ---
4389        //
4390        // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4391        // because a lit mesh is not a Tier A feature. The bindless shape — a
4392        // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4393        // texture array — is topic 03's, at P3.
4394        // **Which stage pulls the geometry**, and the only thing the two shapes
4395        // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4396        // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4397        // and every backend refuses a layout carrying it on a device without
4398        // `Features::MESH_SHADER` — which is exactly the device that never
4399        // reaches this arm.
4400        //
4401        // **`TASK` joins it when there is an amplification stage**, and the
4402        // union is deliberately over every binding rather than the eight
4403        // `taskMain` actually reads. Slang's Metal backend materialises every
4404        // global in every entry point of a module — the argument bindings 6 to
4405        // 8 already carry — so a layout that named only the task stage's own
4406        // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4407        // runner this team cannot debug on.
4408        let geometry = match (emit.is_mesh(), culls_clusters) {
4409            (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4410            (true, false) => ShaderStages::MESH,
4411            (false, _) => ShaderStages::VERTEX,
4412        };
4413        let mut mesh_entries = vec![
4414            BindGroupLayoutEntry {
4415                binding: 0,
4416                visibility: geometry.union(ShaderStages::FRAGMENT),
4417                kind: BindingKind::UniformBuffer { dynamic: false },
4418                count: 1,
4419                flags: BindingFlags::empty(),
4420            },
4421            BindGroupLayoutEntry {
4422                binding: 1,
4423                // **Both stages, and here it is the FRAGMENT half that needs
4424                // saying** — binding 6 and 7 are the mirror image, where the
4425                // fragment stage plainly reads the row and the vertex half is
4426                // the one Slang forces. Slang's Metal backend materialises
4427                // every module global into every entry point, so
4428                // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4429                // its body dereferences it or not — and Metal's debug layer
4430                // answers a declared-but-unbound fragment argument with
4431                // `missing Buffer binding at index N`, once per draw. Vulkan,
4432                // D3D12 and WebGPU all accept a visibility wider than the
4433                // shader's reads, so naming FRAGMENT costs them nothing but the
4434                // entry itself.
4435                //
4436                // **It does not cost a redundant bind on Metal either**, and
4437                // that is what makes it safe rather than a trade: `crcbl-mtl`
4438                // consults `MTLPipelineOption::BindingInfo` reflection and
4439                // issues the fragment-stage bind only where `MTLBinding::isUsed`
4440                // says the compiled function kept the argument. This entry is
4441                // the permission; the reflection is the decision.
4442                visibility: geometry.union(ShaderStages::FRAGMENT),
4443                kind: BindingKind::StorageBuffer {
4444                    // The shader says `StructuredBuffer`, not
4445                    // `RWStructuredBuffer`, so this is the truth rather than a
4446                    // hint — and it is what lets the graph merge read-after-read.
4447                    read_only: true,
4448                    dynamic: false,
4449                    stride: size_of::<u32>() as u32,
4450                },
4451                count: 1,
4452                flags: BindingFlags::empty(),
4453            },
4454            BindGroupLayoutEntry {
4455                binding: 2,
4456                // Both stages, for binding 1's reason exactly.
4457                visibility: geometry.union(ShaderStages::FRAGMENT),
4458                kind: BindingKind::StorageBuffer {
4459                    // `StructuredBuffer` again: the vertex stage reads its
4460                    // instance and writes nothing. The *host* writes this one
4461                    // every frame, which is a mapped write rather than a shader
4462                    // one and does not make it read-write here.
4463                    read_only: true,
4464                    dynamic: false,
4465                    stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4466                },
4467                count: 1,
4468                flags: BindingFlags::empty(),
4469            },
4470            BindGroupLayoutEntry {
4471                binding: 3,
4472                // Both stages, for binding 1's reason exactly.
4473                visibility: geometry.union(ShaderStages::FRAGMENT),
4474                // `dynamic: true`, and it is the whole mechanism: it is what
4475                // lets a draw say where its run of instances starts without
4476                // `draw_indexed`'s own base instance, which the module docs and
4477                // `mesh.slang`'s header explain the targets disagree about.
4478                // Same shape, for the same reason, as `crate::sprite_pass`'s.
4479                kind: BindingKind::UniformBuffer { dynamic: true },
4480                count: 1,
4481                flags: BindingFlags::empty(),
4482            },
4483            BindGroupLayoutEntry {
4484                binding: 4,
4485                // Both stages, for binding 1's reason exactly.
4486                visibility: geometry.union(ShaderStages::FRAGMENT),
4487                kind: BindingKind::StorageBuffer {
4488                    // The mesh table. `StructuredBuffer` again — the vertex
4489                    // stage looks its mesh up and writes nothing — and one
4490                    // buffer shared by every frame's group, because unlike the
4491                    // instance array nothing rewrites it between frames.
4492                    read_only: true,
4493                    dynamic: false,
4494                    stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4495                },
4496                count: 1,
4497                flags: BindingFlags::empty(),
4498            },
4499            BindGroupLayoutEntry {
4500                binding: 5,
4501                // Both stages, for binding 1's reason exactly.
4502                visibility: geometry.union(ShaderStages::FRAGMENT),
4503                kind: BindingKind::StorageBuffer {
4504                    // The per-bucket runs of surviving instances. Read-only
4505                    // here and written by the draw-argument pass, which is a
4506                    // different bind group and a different pass — the graph is
4507                    // what orders the two.
4508                    read_only: true,
4509                    dynamic: false,
4510                    stride: size_of::<u32>() as u32,
4511                },
4512                count: 1,
4513                flags: BindingFlags::empty(),
4514            },
4515            BindGroupLayoutEntry {
4516                binding: 6,
4517                // **Both stages, and the union is not belt-and-braces.** The
4518                // fragment stage is where `mesh.slang` now reads the table, so
4519                // it plainly needs it — a pipeline layout that leaves it out is
4520                // refused outright by wgpu and reported as
4521                // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4522                // The vertex half has to stay because Slang's Metal backend
4523                // materialises every global in every entry point: `vertexMain`
4524                // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4525                // whether it reads it or not, so dropping VERTEX would break
4526                // Metal alone, on a runner this team cannot debug on.
4527                visibility: geometry.union(ShaderStages::FRAGMENT),
4528                kind: BindingKind::StorageBuffer {
4529                    // The material table. One buffer in every frame's group,
4530                    // like the mesh table above and unlike the instance ring:
4531                    // a material is written when it is created, not per frame.
4532                    read_only: true,
4533                    dynamic: false,
4534                    stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4535                },
4536                count: 1,
4537                flags: BindingFlags::empty(),
4538            },
4539            BindGroupLayoutEntry {
4540                binding: BASE_COLOR_PAGE_BINDING,
4541                // Both stages, for binding 6's reason exactly: the fragment
4542                // stage samples it, and Slang's Metal backend materialises
4543                // every global in every entry point — `vertexMain` in
4544                // `msl/mesh.metal` takes the texture whether it reads it or
4545                // not, so a layout without VERTEX would break Metal alone.
4546                visibility: geometry.union(ShaderStages::FRAGMENT),
4547                // **`D2Array`, and the layout is where wgpu wants to hear it.**
4548                // The other three backends read the dimension off the bound
4549                // view and never consult this; WebGPU compares the two at
4550                // pipeline creation and refuses the pair, which is what a
4551                // layout claiming `D2` over an array view got — "expects
4552                // dimension = D2, but given a view with dimension = D2Array".
4553                kind: BindingKind::SampledImage {
4554                    view_type: ImageViewType::D2Array,
4555                    sample_type: SampleType::Float,
4556                },
4557                // **`count: 1`, and this is the binding-model decision.** One
4558                // `D2Array` image whose *layers* the material rows index is
4559                // `BindingModel::ArrayPages`; an array of `count` descriptors
4560                // indexed per fragment would be `Bindless` and would need
4561                // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4562                // So this layout is legal on every device, exactly as the six
4563                // buffers above are, and no `BindingFlags` appear anywhere in
4564                // this file yet.
4565                count: 1,
4566                flags: BindingFlags::empty(),
4567            },
4568            BindGroupLayoutEntry {
4569                binding: PAGE_SAMPLER_BINDING,
4570                visibility: geometry.union(ShaderStages::FRAGMENT),
4571                kind: BindingKind::Sampler { comparison: false },
4572                count: 1,
4573                flags: BindingFlags::empty(),
4574            },
4575        ];
4576        if emit.is_mesh() {
4577            // §3.5's four extra reads, and only on the path that has them.
4578            // Adding them unconditionally would make every device declare four
4579            // buffers `mesh.slang` does not name — and WebGPU, which checks a
4580            // bind group against its layout entry for entry, would then need
4581            // four buffers created for a path that never reads them.
4582            //
4583            // `read_only: true` on all four, which is the truth rather than a
4584            // hint: the mesh stage indexes them and writes nothing, and it is
4585            // what lets the graph merge read-after-read.
4586            //
4587            // Four different element types, so four strides, in binding order:
4588            // the clusters (`Meshlet`), the cluster vertex and corner pools
4589            // (`uint` each), and the per-cluster draw arguments
4590            // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4591            let cluster_strides = [
4592                crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4593                size_of::<u32>() as u32,
4594                size_of::<u32>() as u32,
4595                crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4596            ];
4597            mesh_entries.extend(
4598                (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4599                    .zip(cluster_strides)
4600                    .map(|(binding, stride)| {
4601                        BindGroupLayoutEntry {
4602                            binding,
4603                            // **Not the fragment stage.** These four are the geometry
4604                            // stage's alone, and `mesh_cluster.slang` has no fragment entry
4605                            // point of its own to materialise them into — its fragment
4606                            // stage is `mesh.slang`'s, which does not declare mesh-only
4607                            // buffers.
4608                            visibility: geometry,
4609                            kind: BindingKind::StorageBuffer {
4610                                read_only: true,
4611                                dynamic: false,
4612                                stride,
4613                            },
4614                            count: 1,
4615                            flags: BindingFlags::empty(),
4616                        }
4617                    }),
4618            );
4619        }
4620        // Both mesh entry points retain these declarations. Omitting unused
4621        // task buffers would shift later native buffer indices on the plain
4622        // mesh path, so the layout includes them on both paths.
4623        if emit.is_mesh() {
4624            mesh_entries.push(BindGroupLayoutEntry {
4625                binding: CLUSTER_CULL_BINDING,
4626                visibility: geometry,
4627                // **The same block the instance cull reads**, not a copy: one
4628                // camera, one frustum, and no way for the two rejections to
4629                // disagree about which. `dynamic: false` because there is one
4630                // block per frame rather than one per bucket.
4631                kind: BindingKind::UniformBuffer { dynamic: false },
4632                count: 1,
4633                flags: BindingFlags::empty(),
4634            });
4635            mesh_entries.push(BindGroupLayoutEntry {
4636                binding: CLUSTER_CULL_STATS_BINDING,
4637                visibility: geometry,
4638                kind: BindingKind::StorageBuffer {
4639                    // **The one writable binding this pass has.** The stage adds
4640                    // to a counter, so `read_only: false` is the truth rather
4641                    // than a hint, and it is what makes the graph order this
4642                    // write after the draw-argument pass's read of the same
4643                    // buffer.
4644                    read_only: false,
4645                    dynamic: false,
4646                    stride: size_of::<u32>() as u32,
4647                },
4648                count: 1,
4649                flags: BindingFlags::empty(),
4650            });
4651        }
4652        // Topic 18's cascades, read by the fragment stage and declared last —
4653        // above `mesh_cluster.slang`'s range rather than inside it, for the
4654        // reason `SHADOW_ATLAS_BINDING` gives.
4655        //
4656        // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4657        // binding 7's reason exactly: Slang's Metal backend materialises every
4658        // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4659        // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4660        // [[sampler(1)]]` whether it reads them or not.
4661        mesh_entries.push(BindGroupLayoutEntry {
4662            binding: SHADOW_ATLAS_BINDING,
4663            visibility: geometry.union(ShaderStages::FRAGMENT),
4664            kind: BindingKind::SampledImage {
4665                view_type: ImageViewType::D2,
4666                // **`Depth`, and this is the field the seam grew for this
4667                // pass.** WebGPU will only bind a `D32Float` view through a
4668                // depth sample type, and its shader side agrees — the WGSL
4669                // artifact declares `texture_depth_2d`. The other three
4670                // backends take the interpretation off the view's format and
4671                // never read this.
4672                sample_type: SampleType::Depth,
4673            },
4674            count: 1,
4675            flags: BindingFlags::empty(),
4676        });
4677        mesh_entries.push(BindGroupLayoutEntry {
4678            binding: SHADOW_SAMPLER_BINDING,
4679            visibility: geometry.union(ShaderStages::FRAGMENT),
4680            // The sampler-side twin of the line above: `sampler_comparison` in
4681            // the WGSL, `SamplerComparisonState` in the HLSL, and a
4682            // `compareEnable` on the Vulkan sampler object. The layout has to
4683            // say so on WebGPU and cannot on the other three.
4684            kind: BindingKind::Sampler { comparison: true },
4685            count: 1,
4686            flags: BindingFlags::empty(),
4687        });
4688        // DAG geometry and selection state, in the mesh-only binding range.
4689        if emit.is_mesh() {
4690            mesh_entries.push(BindGroupLayoutEntry {
4691                binding: CLUSTER_SELECT_BINDING,
4692                visibility: geometry,
4693                // Read-only and read by **both** mesh entry points, unlike the
4694                // pair below: a cluster's `vertex_base` is which level of a DAG
4695                // its geometry lives in, which an un-amplified stage needs just
4696                // as much as an amplified one.
4697                kind: BindingKind::StorageBuffer {
4698                    read_only: true,
4699                    dynamic: false,
4700                    stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4701                },
4702                count: 1,
4703                flags: BindingFlags::empty(),
4704            });
4705        }
4706        // Both on the whole mesh path, for the two above's reason exactly: the
4707        // amplification stage is the only writer and the only reader, and the
4708        // Metal argument table counts entries rather than reading binding
4709        // numbers.
4710        if emit.is_mesh() {
4711            mesh_entries.push(BindGroupLayoutEntry {
4712                binding: CLUSTER_SELECTION_BINDING,
4713                visibility: geometry,
4714                kind: BindingKind::StorageBuffer {
4715                    // The second writable binding: the amplification stage
4716                    // records the cut it chose, one word per resident cluster.
4717                    read_only: false,
4718                    dynamic: false,
4719                    stride: size_of::<u32>() as u32,
4720                },
4721                count: 1,
4722                flags: BindingFlags::empty(),
4723            });
4724            mesh_entries.push(BindGroupLayoutEntry {
4725                binding: CLUSTER_GROUP_STATE_BINDING,
4726                visibility: geometry,
4727                kind: BindingKind::StorageBuffer {
4728                    // Topic 25's hysteresis state, and read-only
4729                    // here: the draw-argument pass is its only writer, which is
4730                    // what lets a stage with one workgroup per cluster use a
4731                    // decision that has to survive a frame.
4732                    read_only: true,
4733                    dynamic: false,
4734                    stride: size_of::<u32>() as u32,
4735                },
4736                count: 1,
4737                flags: BindingFlags::empty(),
4738            });
4739        }
4740
4741        // The shared fragment light list and froxel grid are bound on every
4742        // path and in every group, unlike the four
4743        // conditional ranges above: `mesh.slang`'s fragment stage reads them
4744        // whatever geometry produced the primitive, so there is no configuration
4745        // in which the layout can omit them.
4746        //
4747        // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4748        // exactly: Slang's Metal backend materialises every global into every
4749        // entry point, so the vertex and mesh stages take these buffers whether
4750        // they read them or not.
4751        mesh_entries.push(BindGroupLayoutEntry {
4752            binding: LIGHT_LIST_BINDING,
4753            visibility: geometry.union(ShaderStages::FRAGMENT),
4754            kind: BindingKind::StorageBuffer {
4755                read_only: true,
4756                dynamic: false,
4757                stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4758            },
4759            count: 1,
4760            flags: BindingFlags::empty(),
4761        });
4762        mesh_entries.push(BindGroupLayoutEntry {
4763            binding: LIGHT_GRID_BINDING,
4764            visibility: geometry.union(ShaderStages::FRAGMENT),
4765            kind: BindingKind::StorageBuffer {
4766                // **Read-only here**, and written by the clustering pass through
4767                // a layout of its own. The graph is what orders the two.
4768                read_only: true,
4769                dynamic: false,
4770                stride: size_of::<u32>() as u32,
4771            },
4772            count: 1,
4773            flags: BindingFlags::empty(),
4774        });
4775        // Topic 46's occlusion channel, last of the set
4776        // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4777        // than tidy.
4778        //
4779        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4780        // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4781        // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4782        mesh_entries.push(BindGroupLayoutEntry {
4783            binding: AMBIENT_OCCLUSION_BINDING,
4784            visibility: geometry.union(ShaderStages::FRAGMENT),
4785            kind: BindingKind::SampledImage {
4786                view_type: ImageViewType::D2,
4787                // **`Float`, unlike the shadow atlas above.** This one is an
4788                // ordinary `R8Unorm` colour image and the WGSL artifact declares
4789                // `texture_2d<f32>` for it; `Depth` here would be a layout
4790                // claiming a depth format the view does not have.
4791                sample_type: SampleType::Float,
4792            },
4793            count: 1,
4794            flags: BindingFlags::empty(),
4795        });
4796        // The irradiance grid, past the occlusion channel — see
4797        // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4798        //
4799        // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4800        // `msl/mesh.metal` is again the proof rather than the theory: its
4801        // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4802        mesh_entries.push(BindGroupLayoutEntry {
4803            binding: PROBE_TABLE_BINDING,
4804            visibility: geometry.union(ShaderStages::FRAGMENT),
4805            kind: BindingKind::StorageBuffer {
4806                // **Read-only, and it stays read-only when the updater lands.**
4807                // The rows are device-local now — see [`crate::probe`], which is
4808                // where that is argued — so the seam no longer forces this;
4809                // what forces it is that the shading path does not write a
4810                // probe and this layout has no headroom to pretend otherwise.
4811                // The raster path is at the WebGPU per-stage storage-buffer
4812                // ceiling already, which the check at the end of the layout
4813                // holds it to, so `read_only: false` here would buy a write
4814                // nothing performs at the price of a binding budget there is
4815                // none of. The irradiance probes' gather is a
4816                // compute pass with a layout of its own, and that is where the
4817                // writable binding of these rows belongs.
4818                read_only: true,
4819                dynamic: false,
4820                stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4821            },
4822            count: 1,
4823            flags: BindingFlags::empty(),
4824        });
4825        if emit.is_mesh() {
4826            // DAG group records follow the common buffer prefix; the
4827            // remaining mesh-only buffers are sorted after them below.
4828            //
4829            // **Conditional like the mesh-only bindings**, and not for tidiness:
4830            // the raster path's layout is at the WebGPU storage-buffer ceiling
4831            // already, so a row bound unconditionally would be a renderer that
4832            // cannot be built in a browser. The mesh path's own reads sit outside
4833            // that count because `ShaderStages::MESH` is not one of the three
4834            // stages it sums.
4835            mesh_entries.push(BindGroupLayoutEntry {
4836                binding: LEVEL_GROUP_TABLE_BINDING,
4837                // Only the geometry stage reads this table: the
4838                // heatmap's colour is chosen where the cluster is known, and
4839                // `mesh.slang`'s fragment stage — which is this pipeline's —
4840                // does not declare this buffer.
4841                visibility: geometry,
4842                kind: BindingKind::StorageBuffer {
4843                    // Read-only and read by **both** mesh entry points, like
4844                    // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4845                    // `emit_cluster`, so a row present for one and absent for the
4846                    // other is a descriptor read out of an empty slot.
4847                    read_only: true,
4848                    dynamic: false,
4849                    stride: size_of::<u32>() as u32,
4850                },
4851                count: 1,
4852                flags: BindingFlags::empty(),
4853            });
4854        }
4855
4856        // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4857        //
4858        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4859        // Metal backend materialises every global into every entry point, so
4860        // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4861        // whether it reads it or not.
4862        mesh_entries.push(BindGroupLayoutEntry {
4863            binding: SPECULAR_DFG_BINDING,
4864            visibility: geometry.union(ShaderStages::FRAGMENT),
4865            kind: BindingKind::SampledImage {
4866                view_type: ImageViewType::D2,
4867                // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4868                // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4869                sample_type: SampleType::Float,
4870            },
4871            count: 1,
4872            flags: BindingFlags::empty(),
4873        });
4874
4875        // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4876        //
4877        // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4878        // Metal backend materialises every global into every entry point, so
4879        // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4880        // or not. **A sampled image and not a storage buffer**, which costs this
4881        // layout nothing at the WebGPU ceiling checked below — that limit counts
4882        // storage buffers, and this row is a texture.
4883        mesh_entries.push(BindGroupLayoutEntry {
4884            binding: NORMAL_PAGE_BINDING,
4885            visibility: geometry.union(ShaderStages::FRAGMENT),
4886            kind: BindingKind::SampledImage {
4887                view_type: ImageViewType::D2Array,
4888                // `Float`: an `Rgba8Unorm` image, declared
4889                // `texture_2d_array<f32>` by the WGSL artifact — the same
4890                // sample type the sRGB base-colour page reports, since both
4891                // decode to floats.
4892                sample_type: SampleType::Float,
4893            },
4894            count: 1,
4895            flags: BindingFlags::empty(),
4896        });
4897        // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4898        //
4899        // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4900        // `Float` because `Rgba16Float` is a filterable sampled format on every
4901        // target this engine opens, and the WGSL artifact declares it
4902        // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4903        // has to say what the module declared.
4904        mesh_entries.push(BindGroupLayoutEntry {
4905            binding: LTC_TABLE_BINDING,
4906            visibility: geometry.union(ShaderStages::FRAGMENT),
4907            kind: BindingKind::SampledImage {
4908                view_type: ImageViewType::D2,
4909                sample_type: SampleType::Float,
4910            },
4911            count: 1,
4912            flags: BindingFlags::empty(),
4913        });
4914        // Topic 45's contact-shadow channel, last of the set —
4915        // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4916        // tidy.
4917        //
4918        // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4919        // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4920        // backend materialises every global into every entry point whether that
4921        // stage reads it or not.
4922        mesh_entries.push(BindGroupLayoutEntry {
4923            binding: CONTACT_SHADOW_BINDING,
4924            visibility: geometry.union(ShaderStages::FRAGMENT),
4925            kind: BindingKind::SampledImage {
4926                view_type: ImageViewType::D2,
4927                sample_type: SampleType::Float,
4928            },
4929            count: 1,
4930            flags: BindingFlags::empty(),
4931        });
4932        // The irradiance probes' per-probe visibility maps, last
4933        // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4934        // structural.
4935        //
4936        // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4937        // dimension a layout entry claims against the view handed to it at
4938        // pipeline creation, which is the normal page's own note.
4939        // `UnfilterableFloat` for the same reason and measured the same way: the
4940        // image is `Rg32Float`, which is unfilterable without WebGPU's
4941        // `float32-filterable`, and this slot declared `Float` made Chromium
4942        // refuse the whole mesh bind group — "None of the supported sample types
4943        // (UnfilterableFloat) ... match the expected sample types (Float)" —
4944        // which took every 3D demo's frame to black. Reading it only with `Load`
4945        // does not lift that: the check is on the layout against the view's
4946        // format, not on how the shader gets at it.
4947        mesh_entries.push(BindGroupLayoutEntry {
4948            binding: PROBE_VISIBILITY_BINDING,
4949            visibility: geometry.union(ShaderStages::FRAGMENT),
4950            kind: BindingKind::SampledImage {
4951                view_type: ImageViewType::D2Array,
4952                sample_type: SampleType::UnfilterableFloat,
4953            },
4954            count: 1,
4955            flags: BindingFlags::empty(),
4956        });
4957        // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4958        // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4959        //
4960        // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4961        // page's three answers exactly, and for its reasons: Slang's Metal
4962        // backend materialises every global into every entry point, WebGPU
4963        // compares the declared dimension against the bound view, and both
4964        // images are `Rgba8Unorm`-family formats that decode to filterable
4965        // floats.
4966        for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4967            mesh_entries.push(BindGroupLayoutEntry {
4968                binding,
4969                visibility: geometry.union(ShaderStages::FRAGMENT),
4970                kind: BindingKind::SampledImage {
4971                    view_type: ImageViewType::D2Array,
4972                    sample_type: SampleType::Float,
4973                },
4974                count: 1,
4975                flags: BindingFlags::empty(),
4976            });
4977        }
4978        mesh_entries.sort_by_key(|entry| entry.binding);
4979        let mesh_desc = BindGroupLayoutDesc {
4980            label: Some(MESH_LAYOUT_LABEL),
4981            entries: &mesh_entries,
4982        };
4983        // **This layout is at the guaranteed limit with no headroom on the
4984        // raster path, in both raster stages**: the vertex stage takes every
4985        // storage buffer a WebGPU device promises, and since bindings 1 to 5
4986        // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4987        // takes the same number. A ninth in either is a renderer that cannot be
4988        // built in a browser or on SwiftShader, so it fails here rather than at
4989        // somebody else's `createPipelineLayout` — see
4990        // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4991        // mesh path's extra reads are outside the count.
4992        // `Some("mesh")`, which is the *pipeline* layout's label, not
4993        // `mesh_desc.label` — the error text reads "pipeline layout {label}
4994        // binds …", so naming the bind group layout there sends the reader to
4995        // the wrong object.
4996        check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4997        let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4998        rollback.bind_group_layouts.push(mesh_layout);
4999
5000        // A dynamic offset must be a multiple of the device's alignment, and one
5001        // block has to fit inside one stride. Read from the device rather than
5002        // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
5003        // typical desktop Vulkan driver.
5004        //
5005        // One stride for both blocks, sized for the larger — see
5006        // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
5007        // decided below.
5008        let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
5009        let draw_stride =
5010            u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
5011                HalError::InvalidDescriptor(format!(
5012                    "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
5013                         offset can express"
5014                ))
5015            })?;
5016        let draw_constants = device.create_buffer(&BufferDesc {
5017            label: Some("mesh draw constants"),
5018            // A block per bucket per draw region: a region's draws name their
5019            // own run starts, and the mesh path's block names the region's
5020            // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5021            size: u64::from(draw_stride)
5022                * u64::from(bucket_count)
5023                * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
5024            usage: BufferUsage::UNIFORM,
5025            memory: MemoryLocation::HostUpload,
5026        })?;
5027        rollback.buffers.push(draw_constants);
5028        // --- the shadow map's own resources ---
5029        //
5030        // Before the bind groups, because every one of them names the atlas or
5031        // the placeholder standing in for it.
5032        let (atlas_width, atlas_height) = shadow::atlas_extent();
5033        let shadow_atlas = device.create_image(&ImageDesc {
5034            label: Some("shadow atlas"),
5035            image_type: ImageType::D2,
5036            format: Format::D32Float,
5037            extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
5038            mip_levels: 1,
5039            samples: 1,
5040            // `TRANSFER_SRC` so a test can copy the cascades back and check
5041            // that something was written into them. A shadow map that stayed at
5042            // its clear value produces a frame that looks entirely plausible —
5043            // everything is lit — so the readback is the only thing that can
5044            // tell a working pass from one that drew nothing.
5045            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
5046                .union(ImageUsage::SAMPLED)
5047                .union(ImageUsage::TRANSFER_SRC),
5048        })?;
5049        rollback.images.push(shadow_atlas);
5050        let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
5051            label: Some("shadow atlas"),
5052            image: shadow_atlas,
5053            view_type: ImageViewType::D2,
5054            format: Format::D32Float,
5055            range: ImageSubresourceRange::all(Format::D32Float),
5056        })?;
5057        rollback.image_views.push(shadow_atlas_view);
5058
5059        let shadow_placeholder = device.create_image(&ImageDesc {
5060            label: Some("shadow placeholder"),
5061            image_type: ImageType::D2,
5062            format: Format::D32Float,
5063            extent: crcbl_hal::Extent3d::d2(1, 1),
5064            mip_levels: 1,
5065            samples: 1,
5066            usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
5067        })?;
5068        rollback.images.push(shadow_placeholder);
5069        let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
5070            label: Some("shadow placeholder"),
5071            image: shadow_placeholder,
5072            view_type: ImageViewType::D2,
5073            format: Format::D32Float,
5074            range: ImageSubresourceRange::all(Format::D32Float),
5075        })?;
5076        rollback.image_views.push(shadow_placeholder_view);
5077
5078        // The occlusion placeholder, beside the shadow one and for the same
5079        // reason: every group of this layout has to fill
5080        // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
5081        // graph has an occlusion image to name.
5082        //
5083        // **Uploaded rather than cleared**, unlike the depth placeholder above,
5084        // and the four bytes are the whole point — see
5085        // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
5086        // Left undefined this would be a random ambient scale *and* a random
5087        // direction to steer it along, on any frame that fell back to it.
5088        let ambient_occlusion_placeholder = uploads.texture(
5089            "ssao placeholder",
5090            Format::Rgba8Unorm,
5091            (1, 1),
5092            &[&[&AMBIENT_OCCLUSION_NONE]],
5093            ImageViewType::D2,
5094        )?;
5095        rollback.textures.push(ambient_occlusion_placeholder);
5096
5097        // The contact-shadow placeholder, beside the occlusion one and on its
5098        // terms exactly: every group of this layout has to fill
5099        // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
5100        // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
5101        // so a fragment that reads this one is a fragment the sun reaches
5102        // unobstructed.
5103        let contact_shadow_placeholder = uploads.texture(
5104            "contact shadow placeholder",
5105            Format::R8Unorm,
5106            (1, 1),
5107            &[&[&[CONTACT_SHADOW_NONE]]],
5108            ImageViewType::D2,
5109        )?;
5110        rollback.textures.push(contact_shadow_placeholder);
5111
5112        // The probe-visibility placeholder, on the two above it's terms: every
5113        // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
5114        // nothing has been captured when they are built. One texel of
5115        // [`probe_visibility_none`], which no surface is further away than, so a
5116        // probe read through it keeps all of its weight.
5117        let probe_visibility_placeholder = uploads.texture(
5118            "probe visibility placeholder",
5119            Format::Rg32Float,
5120            (1, 1),
5121            &[&[&probe_visibility_none()]],
5122            ImageViewType::D2Array,
5123        )?;
5124        rollback.textures.push(probe_visibility_placeholder);
5125
5126        // The split-sum `DFG` table, uploaded once and read by every frame this
5127        // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
5128        // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
5129        //
5130        // **Cooked bytes rather than a computed image**: the integrator
5131        // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
5132        // engine's goldens are compared across four backends with no tolerance.
5133        // Baking here would be four slightly different tables.
5134        //
5135        // **Every view's reflection march reads this same image** for its own
5136        // split-sum scale and bias — see `Ssr::dfg` — rather than uploading a
5137        // second copy of the same bytes per view.
5138        let specular_dfg = uploads.texture(
5139            "dfg table",
5140            // Two bytes of fixed point per channel, high byte first — see
5141            // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
5142            // not the `Rg16Float` the format's own doc anticipated.
5143            Format::Rgba8Unorm,
5144            (DFG_SIZE_U32, DFG_SIZE_U32),
5145            &[&[&dfg::pair_texels()]],
5146            ImageViewType::D2,
5147        )?;
5148        rollback.textures.push(specular_dfg);
5149
5150        // The area lights' fit, beside it and on its terms — cooked bytes for
5151        // the same reason, and `Rgba16Float` rather than fixed point because
5152        // these are matrix entries rather than shares of arriving light.
5153        // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
5154        let ltc_table = uploads.texture(
5155            "ltc table",
5156            Format::Rgba16Float,
5157            (LTC_SIZE_U32, LTC_SIZE_U32),
5158            &[&[&ltc::texels()]],
5159            ImageViewType::D2,
5160        )?;
5161        rollback.textures.push(ltc_table);
5162
5163        // The sky's prefiltered table, which only the views' reflection
5164        // marches and the water surface read — uploaded here rather than per
5165        // view, for the DFG table's reason above. Fixed point: see
5166        // `crcbl_shaders::sky_prefilter::PREFILTER_TEXEL_BYTES`.
5167        let sky_prefilter = uploads.texture(
5168            "sky prefilter table",
5169            Format::Rgba8Unorm,
5170            (SKY_PREFILTER_SIZE_U32, SKY_PREFILTER_SIZE_U32),
5171            &[&[&sky_prefilter::texels()]],
5172            ImageViewType::D2,
5173        )?;
5174        rollback.textures.push(sky_prefilter);
5175        service();
5176
5177        // **A comparison sampler, and that is the PCF.** Each
5178        // `SampleCmpLevelZero` returns the filtered fraction of four texels that
5179        // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
5180        // comparisons rather than nine raw fetches it averages itself.
5181        //
5182        // `Greater` for the engine's reversed-Z, exactly as the depth *test*
5183        // is: the receiver survives when it is nearer the light than whatever
5184        // the map stored. `SamplerDesc::compare` carries the same warning.
5185        //
5186        // Clamped on every axis so a receiver just outside a cascade's box
5187        // reads the edge rather than wrapping into the opposite corner — the
5188        // shader's own bounds check is what actually handles that case, and this
5189        // is the second line of defence one texel wide.
5190        let shadow_sampler = device.create_sampler(&SamplerDesc {
5191            label: Some("shadow comparison"),
5192            mag_filter: FilterMode::Linear,
5193            min_filter: FilterMode::Linear,
5194            mip_filter: FilterMode::Nearest,
5195            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5196            compare: Some(crcbl_hal::CompareOp::Greater),
5197            ..SamplerDesc::default()
5198        })?;
5199        rollback.samplers.push(shadow_sampler);
5200
5201        // The pipelines every generator dispatches, the camera's and each
5202        // shadow cull's, compiled once here and shared — with the occlusion
5203        // phases, because every camera's generator is built for them.
5204        let draw_pipelines = rollback
5205            .draw_pipelines
5206            .insert(DrawGenPipelines::new(device, true, service)?);
5207
5208        let mesh_set_layouts = [mesh_layout];
5209        let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5210            label: Some("mesh"),
5211            bind_group_layouts: &mesh_set_layouts,
5212            // The camera goes in the uniform buffer above rather than here:
5213            // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5214            // explicit that the substitute is a data-layout decision. So this
5215            // file needs no tier branch at all — it has been on Tier B's shape
5216            // since P1, and `crate::ui_pass` is where the split actually bites.
5217            push_constants: None,
5218        })?;
5219        rollback.pipeline_layouts.push(mesh_pipeline_layout);
5220
5221        // The colour pass's pipeline and its depth-only twin, out of one set of
5222        // modules — see [`MeshModules`], which is where the two shapes and the
5223        // reasons for them live. Both are created before either is unwrapped and
5224        // the modules are released between, so a failing creation leaks nothing.
5225        //
5226        // **Each shape has a twin per material side** — see
5227        // [`SidedPipelines`], which is where the cull modes and the reason for a
5228        // pipeline rather than a per-draw state live. The shadow tile clear is
5229        // the one exception: its triangle comes out of `SV_VertexID` and it
5230        // already culls nothing.
5231        //
5232        // Beside them: the cutout twin of the depth shape, which a frame whose
5233        // material table masks alpha is recorded with instead (see
5234        // [`MeshModules::depth_masked_pipeline`]); the one that resets a tile,
5235        // which the cadence rung needs and the attachment's load operation
5236        // cannot express ([`MeshModules::depth_clear_pipeline`]); and the
5237        // irradiance probes' reflective shadow map ([`MeshModules::rsm_pipeline`]).
5238        //
5239        // **Only what this scene can draw with is compiled.** The bucket table
5240        // above is final — nothing adds a material or changes a probe volume's
5241        // update after `build` — so `scene_modes` and the volume are the whole
5242        // of what any frame of this renderer will ask for. The single-sided
5243        // colour and depth shapes and the tile clear are built for every
5244        // scene; each `CullMode::None` twin only where a bucket is
5245        // double-sided, the cutout shape only where one masks, and the
5246        // reflective shadow map only where the probes are updated. An opaque,
5247        // single-sided scene without an updated volume, such as the demo
5248        // scene, compiles only those.
5249        //
5250        // **They are one [`pipeline_batch`], compiled side by side** where
5251        // the device allows it: on a cold driver cache each is a shader
5252        // compilation, and this is the build's longest run of them. `service`
5253        // runs before each round of the batch, or before each pipeline where the
5254        // batch is serial — see [`ForwardRenderer::with_scene_serviced`].
5255        //
5256        // **The camera's froxel volume and reflection march are members too**,
5257        // which is why this batch runs before the camera is built rather than
5258        // after it: each has one costly compile — the scatter pass and the
5259        // march — that `View::build` would otherwise make one after the other
5260        // beside nothing. Their layouts are created first and held by `pending`
5261        // until the batch has made every pipeline against them; the passes
5262        // themselves stay in the view, built eagerly — see
5263        // [`VolumetricPipelines`] and [`SsrPipelines`].
5264        let holds = |mode: u32| scene_modes.contains(&mode);
5265        // The single-sided shapes are built even where `DEPTH_MODES[0]` is not
5266        // held: they are the template the frame's draw lists are partitioned
5267        // from, and the rare scene with no opaque single-sided material pays a
5268        // compile each for them.
5269        let [_, masked, double, masked_double] = DEPTH_MODES;
5270        let any_double = holds(double) || holds(masked_double);
5271        let any_masked = holds(masked) || holds(masked_double);
5272        let updates_probes = scene.probes.update == ProbeUpdate::EveryFrame;
5273        let mut pending = Partial::new(device);
5274        let view_layouts = ViewPipelineLayouts::new(device, &mut pending)?;
5275        let modules = MeshModules::new(device, emit, culls_clusters)?;
5276        let layout = mesh_pipeline_layout;
5277        let [back, none] = MeshModules::SIDES;
5278        let raster = |made: Result<GraphicsPipelineHandle, HalError>| made.map(Pipeline::Graphics);
5279        let color = |cull| {
5280            raster(modules.color_pipeline(device, layout, PolygonMode::Fill, cull, "forward"))
5281        };
5282        let depth = |cull| raster(modules.depth_pipeline(device, layout, cull));
5283        let depth_masked = |cull| raster(modules.depth_masked_pipeline(device, layout, cull));
5284        let rsm = |cull| raster(modules.rsm_pipeline(device, layout, cull));
5285        // Each member beside whether this scene needs it, in one fixed order the
5286        // results are read back out of below.
5287        let members: [(bool, &pipeline_batch::Job<'_, _>); 9] = [
5288            (true, &|| color(back)),
5289            (any_double, &|| color(none)),
5290            (true, &|| depth(back)),
5291            (holds(double), &|| depth(none)),
5292            (any_masked, &|| depth_masked(back)),
5293            (holds(masked_double), &|| depth_masked(none)),
5294            (true, &|| {
5295                raster(modules.depth_clear_pipeline(device, layout))
5296            }),
5297            (updates_probes, &|| rsm(back)),
5298            (updates_probes && any_double, &|| rsm(none)),
5299        ];
5300        // The view passes' costly pair leads the batch, so it is in the first
5301        // round whatever a round's size, and the mesh pass's members follow it
5302        // into the earliest rounds left. Their other members, never timed alone
5303        // and taken to be cheap, trail every mesh member. A view made later
5304        // lists the same members alone — see [`ViewPipelineLayouts`].
5305        let leading = view_layouts.leading(device);
5306        let trailing = view_layouts.trailing(device);
5307        let jobs: Vec<&pipeline_batch::Job<'_, _>> = leading
5308            .iter()
5309            .map(|job| job as &pipeline_batch::Job<'_, _>)
5310            .chain(
5311                members
5312                    .iter()
5313                    .filter_map(|(needed, job)| needed.then_some(*job)),
5314            )
5315            .chain(
5316                trailing
5317                    .iter()
5318                    .map(|job| job as &pipeline_batch::Job<'_, _>),
5319            )
5320            .collect();
5321        let mut made = pipeline_batch::create_listed(device, service, &jobs).into_iter();
5322        let mut next = || {
5323            made.next()
5324                .unwrap_or_else(|| unreachable!("one result per job"))
5325        };
5326        let leading = leading.each_ref().map(|_| next());
5327        let results: [Option<Result<Pipeline, HalError>>; 9] =
5328            members.map(|(needed, _)| needed.then(&mut next));
5329        let trailing = trailing.each_ref().map(|_| next());
5330        modules.destroy(device);
5331        // Register every successful creation before propagating any error.
5332        // Results later in this batch may own pipelines even when the first
5333        // result failed; dropping an unvisited Result does not release a HAL
5334        // handle. The outer rollback owns the mesh pass's until build
5335        // succeeds, and `pending` the view passes' until each set is whole.
5336        for pipeline in results.iter().flatten().flatten() {
5337            rollback.pipelines.push(pipeline.graphics());
5338        }
5339        let ViewPipelines { volumetric, ssr } = view_layouts.finish(pending, leading, trailing)?;
5340        rollback.volumetric_pipelines = Some(volumetric);
5341        rollback.ssr_pipelines = Some(ssr);
5342        let [
5343            mesh_single,
5344            mesh_double,
5345            shadow_single,
5346            shadow_double,
5347            depth_masked_single,
5348            depth_masked_double,
5349            shadow_clear_pipeline,
5350            rsm_single,
5351            rsm_double,
5352        ] = results.map(|result| result.map(|made| made.map(Pipeline::graphics)).transpose());
5353        let built = |single: Option<GraphicsPipelineHandle>, double| {
5354            single.map(|single| SidedPipelines { single, double })
5355        };
5356        let mesh_pipeline = built(mesh_single?, mesh_double?).unwrap_or_else(|| {
5357            unreachable!("the colour pass's single-sided shape is always built")
5358        });
5359        let shadow_pipeline = built(shadow_single?, shadow_double?)
5360            .unwrap_or_else(|| unreachable!("the depth pass's single-sided shape is always built"));
5361        let depth_masked_pipeline = built(depth_masked_single?, depth_masked_double?);
5362        let shadow_clear_pipeline = shadow_clear_pipeline?
5363            .unwrap_or_else(|| unreachable!("the tile clear is always built"));
5364        let rsm_pipeline = built(rsm_single?, rsm_double?);
5365
5366        // --- the camera ---
5367        //
5368        // Everything the camera's picture needs of its own, built against the
5369        // scene resources above — see [`view`], which is where the line between
5370        // the two is drawn. Into the rollback whole as soon as it exists, so a
5371        // failure further down releases it with everything else.
5372        let slot_pages = vec![page_bindings; instance_buffers.len()];
5373        rollback.primary = Some(View::build(
5374            device,
5375            uploads,
5376            &ViewInputs {
5377                id: ViewId::PRIMARY,
5378                effects: RenderEffects::all(),
5379                // What the first frame resolves to unless a caller moves the
5380                // request before it: the default request against the device
5381                // effects this build hands the renderer below.
5382                expected: EffectRequest::default().resolve(RenderEffects::all()),
5383                // A renderer is built at full render scale; a caller that lowers
5384                // it before the first frame — a saved setting — has that
5385                // frame build the upscale.
5386                expected_upscale: false,
5387                background: ViewBackground::Scene,
5388                lighting: ViewLighting::Scene,
5389                target_format,
5390                emit,
5391                instances: &instance_buffers,
5392                mesh_table,
5393                draw_pipelines,
5394                bucket_meshes: &bucket_meshes,
5395                bucket_modes: &bucket_modes,
5396                bucket_clusters: &bucket_clusters,
5397                bucket_cluster_bases: &bucket_cluster_bases,
5398                mesh_levels: &mesh_levels,
5399                level_groups: &level_groups,
5400                level_meshes: &level_meshes,
5401                instance_capacity: scene.capacities.instances,
5402                light_capacity: scene.capacities.lights,
5403                clusters: rollback.clusters.as_ref(),
5404                task_lanes: view::task_lanes(culls_clusters),
5405                mesh_layout,
5406                vertices,
5407                draw_constants,
5408                materials: material_buffer,
5409                pages: &slot_pages,
5410                probes: &probe_buffers,
5411                specular_dfg: specular_dfg.view,
5412                ltc_table: ltc_table.view,
5413                sky_prefilter: sky_prefilter.view,
5414                shadow_map: shadow_atlas_view,
5415                shadow_sampler,
5416                ambient_occlusion: ambient_occlusion_placeholder.view,
5417                contact_shadow: contact_shadow_placeholder.view,
5418                probe_visibility: probe_visibility_placeholder.view,
5419            },
5420            // Compiled in the mesh pass's batch above, and the view's from here.
5421            ViewPipelines {
5422                volumetric: rollback
5423                    .volumetric_pipelines
5424                    .take()
5425                    .unwrap_or_else(|| unreachable!("the mesh batch made the volume's set")),
5426                ssr: rollback
5427                    .ssr_pipelines
5428                    .take()
5429                    .unwrap_or_else(|| unreachable!("the mesh batch made the march's set")),
5430            },
5431            service,
5432        )?);
5433        let primary = rollback.primary.as_ref().expect("just stored");
5434
5435        // Written here and never again: **which word holds** a bucket's run
5436        // start is fixed by the bucket table and the capacity, and both are
5437        // fixed at build. What varies per frame is where the run starts and how
5438        // much of it is filled, and the GPU writes both — the start into that
5439        // word, the count into the bucket's indirect arguments. See
5440        // `mesh.slang`'s header for why the block names a word rather than
5441        // carrying the start.
5442        //
5443        // Taken from the camera's generator and bound for every generator's
5444        // draws: the shadow culls and every secondary view are built from the
5445        // same table and the same capacity, so `bucket_start_word` answers the
5446        // same for all of them.
5447        let draws = &primary.draws;
5448        let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5449        // **Every draw region's copy**, region 0's at the offsets
5450        // `bucket_constants` records and each further region a bucket count of
5451        // strides behind the one before: a region's draw reads its own run
5452        // start and — on the mesh path — its own argument structure, and the
5453        // two are the only words a region changes. See
5454        // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5455        for (region, (bucket, index)) in
5456            (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5457                (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5458            })
5459        {
5460            let offset = (region * bucket_count + bucket) * draw_stride;
5461            if region == 0 {
5462                bucket_constants[index] = offset;
5463            }
5464            let start_at = draws.region_start_word(region, bucket);
5465            // The mesh path's block says three more things — where this
5466            // bucket's mesh's clusters are, how many it has, and which element
5467            // of the indirect arguments holds its instance count — because a
5468            // dispatch carries none of them and a `draw_indexed_indirect` does
5469            // not need them. All three are fixed when the bucket table is,
5470            // exactly like `start_at`.
5471            let block = if emit.is_mesh() {
5472                crcbl_shaders::meshlet::ClusterDrawConstants {
5473                    start_at,
5474                    cluster_base: bucket_cluster_bases[index],
5475                    cluster_count: bucket_clusters[index],
5476                    // The region's argument structure, which is where this
5477                    // region's instance count is.
5478                    bucket: region * bucket_count + bucket,
5479                    // The same number the draw-argument pass indexes the state
5480                    // with, taken from the object that owns the buffer rather
5481                    // than recomputed from the group table — the two indexing it
5482                    // differently is a cluster reading another instance's
5483                    // decision.
5484                    group_stride: draws.group_stride(),
5485                    // Where the group records are in the table buffer, from the
5486                    // object that packed it — the screen-error heatmap's one
5487                    // input that is not already in the frame block. Taken from
5488                    // `DrawGen` rather than recomputed here for `group_stride`'s
5489                    // reason: two spellings of one offset is an overlay reading
5490                    // another region's words as a group.
5491                    level_groups_at: draws.table_offsets().level_groups_at,
5492                    // The same two numbers again as words of that buffer,
5493                    // which is where a draw that is not the first of a ranged
5494                    // call reads them — `mesh_cluster.slang`'s "One call for
5495                    // a range of buckets". This bucket's, not the region's
5496                    // argument structure's: the tables hold one word a bucket.
5497                    cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5498                    cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5499                    // Where this bucket's task chunks start in this region,
5500                    // and where the region's end: what a flat call binding
5501                    // this block searches between — `mesh_cluster.slang`'s
5502                    // `taskMain`.
5503                    chunk_starts_at: draws.chunk_start_word(region, bucket),
5504                    chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5505                }
5506                .to_bytes()
5507                .to_vec()
5508            } else {
5509                // **The bucket's mesh, which is not always the drawn instance's.**
5510                // A uniform cut selects one of a DAG's levels and each level is
5511                // a mesh table entry of its own, so this is what says which
5512                // geometry the draw's index range belongs to; the instance goes
5513                // on naming level 0. See `mesh::DrawConstants::mesh`.
5514                mesh::DrawConstants {
5515                    start_at,
5516                    mesh: bucket_meshes[index],
5517                    mesh_at: draws.bucket_mesh_word(bucket),
5518                }
5519                .to_bytes()
5520                .to_vec()
5521            };
5522            device.write_buffer(draw_constants, u64::from(offset), &block)?;
5523        }
5524
5525        let region_step = RegionStep {
5526            constants: bucket_count * draw_stride,
5527            args: draws.args_region_offset(1),
5528            counts: draws.counts_region_offset(1),
5529        };
5530
5531        // §3.3's cull, once per cascade and once per shadowed light. Each gets
5532        // its own `DrawGen` and therefore its own frustum, survivor list and
5533        // indirect arguments — which is what "one cull dispatch per cascade
5534        // against the same instance/geometry pools" means, and why the instance
5535        // ring and the mesh table below are the same handles the camera's cull
5536        // was given.
5537        //
5538        // **One per light rather than one per tile**, which is topic 18's fourth
5539        // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5540        // against the light's sphere once and draw that one visible set through
5541        // six matrices.
5542        //
5543        // **Built for every slot, including the ones no light may ever hold.** A
5544        // generator's buffers are sized by the instance capacity rather than by
5545        // the scene, so building one on demand would mean allocating device
5546        // memory inside `begin_frame` — and a frame that cannot allocate is a
5547        // frame that cannot draw. The unused ones cost memory and no dispatch:
5548        // `add_shadow_pass` records passes for the occupied slots alone.
5549        for cull in 0..SHADOW_CULLS {
5550            // Into the rollback as each is built, on the same terms as the
5551            // camera's: a failure two culls in has to release the first one,
5552            // and the rollback is the only thing that knows about it.
5553            let label = if cull < shadow::CASCADES {
5554                format!("shadow cascade {cull}")
5555            } else {
5556                format!("shadow light {}", cull - shadow::CASCADES)
5557            };
5558            let draws = DrawGen::new(
5559                device,
5560                uploads,
5561                rollback
5562                    .draw_pipelines
5563                    .as_ref()
5564                    .unwrap_or_else(|| unreachable!("built ahead of the camera")),
5565                &DrawGenDesc {
5566                    label: Some(&label),
5567                    instances: &instance_buffers,
5568                    mesh_table,
5569                    bucket_meshes: &bucket_meshes,
5570                    bucket_modes: &bucket_modes,
5571                    bucket_clusters: &bucket_clusters,
5572                    bucket_cluster_bases: &bucket_cluster_bases,
5573                    mesh_levels: &mesh_levels,
5574                    level_groups: &level_groups,
5575                    level_meshes: &level_meshes,
5576                    instance_capacity: scene.capacities.instances,
5577                    // No view's: a shadow map is drawn from everything resident
5578                    // that casts, so an instance a camera hides still casts its
5579                    // shadow and one `set_instance_casts_shadow` turned off does
5580                    // not — on every geometry path, since this is the cull they
5581                    // all draw from. The reflective shadow maps draw these same
5582                    // survivors, so such an instance bounces no light either.
5583                    hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5584                    // A light slot may hold a point light, whose six faces cull
5585                    // separately into six regions of the one generator; a
5586                    // cascade never does.
5587                    mode: if cull < shadow::CASCADES {
5588                        crcbl_shaders::draw_gen::DrawMode::Plain
5589                    } else {
5590                        crcbl_shaders::draw_gen::DrawMode::Faces
5591                    },
5592                    task_lanes: view::task_lanes(culls_clusters),
5593                },
5594            )?;
5595            rollback.shadow_draws.push(draws);
5596            service();
5597        }
5598        // The handles are `Copy` and are read out here for the same reason the
5599        // camera's are above: the pool they came from is the rollback's now.
5600        let tile_buffers: Vec<TileBuffers> = rollback
5601            .shadow_draws
5602            .iter()
5603            .map(|draws| TileBuffers {
5604                runs: (0..instance_buffers.len())
5605                    .map(|frame| draws.runs(frame))
5606                    .collect(),
5607                args: (0..instance_buffers.len())
5608                    .map(|frame| draws.args(frame))
5609                    .collect(),
5610                cull_params: (0..instance_buffers.len())
5611                    .map(|frame| draws.cull_params(frame))
5612                    .collect(),
5613                cull_stats: (0..instance_buffers.len())
5614                    .map(|frame| draws.visible_count(frame))
5615                    .collect(),
5616                group_state: draws.group_state(),
5617            })
5618            .collect();
5619
5620        let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5621        let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5622        let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5623        let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5624        for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5625            // Everything a group of this layout names that is the same in all of
5626            // this frame's — the camera's list and table buffers included, which
5627            // a shadow view binds because the layout declares them and reads
5628            // nothing of. The per-group half is what `MeshGroup` below varies,
5629            // and the two exist so the colour pass's group and the shadow pass's
5630            // are one description rather than two that agree today.
5631            let shared = SharedBindings {
5632                vertices,
5633                draw_constants,
5634                mesh_table,
5635                materials: material_buffer,
5636                pages: page_bindings,
5637                clusters: rollback.clusters.as_ref(),
5638                shadow_sampler,
5639                lights: primary.lights.lights(frame),
5640                light_grid: primary.lights.grid(frame),
5641                probes: probe_buffers[frame],
5642                tables: primary.draws.tables(),
5643                specular_dfg: specular_dfg.view,
5644                ltc_table: ltc_table.view,
5645            };
5646
5647            // The same layout again, once per shadow view, differing in exactly
5648            // the things a view is: which matrix, and which cull's survivors.
5649            //
5650            // **The view's own uniforms and the cull's shared buffers**, which
5651            // is the whole of what a point light's six faces are: one visible
5652            // set, six matrices. `shadow_cull` is the map from a view to the
5653            // generator behind it, and it is a compile-time one because a bind
5654            // group names its buffers when it is created — where a face's *tile*
5655            // is decided per frame and reaches the device as a viewport.
5656            let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5657            let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5658            let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5659            let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5660            for view in 0..SHADOW_VIEWS {
5661                let buffers = &tile_buffers[if view < shadow::CASCADES {
5662                    view
5663                } else {
5664                    shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5665                }];
5666                let tile_uniforms = device.create_buffer(&BufferDesc {
5667                    label: Some("shadow view uniforms"),
5668                    size: mesh::FRAME_UNIFORMS_SIZE as u64,
5669                    usage: BufferUsage::UNIFORM,
5670                    memory: MemoryLocation::HostUpload,
5671                })?;
5672                rollback.buffers.push(tile_uniforms);
5673                let entries = MeshGroup {
5674                    uniforms: tile_uniforms,
5675                    instances: slot_instances,
5676                    runs: buffers.runs[frame],
5677                    args: buffers.args[frame],
5678                    // The amplification stage culls clusters against whatever
5679                    // frustum is in this block, and against
5680                    // `frame.camera_position` — which in a view's copy is the
5681                    // *light*. So the per-cluster cull rejects what faces away
5682                    // from the light, which is the right question for a shadow
5683                    // map and the wrong one to have asked with the camera's
5684                    // frustum.
5685                    cull_params: buffers.cull_params[frame],
5686                    cull_stats: buffers.cull_stats[frame],
5687                    // **This view's own**, and not the colour pass's: that pass
5688                    // is recorded last and would write over it. See
5689                    // `ForwardRenderer::shadow_selection`.
5690                    cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5691                    // Its cull's — see `TileBuffers::group_state`, which is
5692                    // where that budget is argued.
5693                    group_state: emit.is_mesh().then_some(buffers.group_state),
5694                    shadow_map: shadow_placeholder_view,
5695                    // A cascade shades nothing — the pipeline has no fragment
5696                    // stage — so this slot exists only because Metal
5697                    // materialises every global into every entry point.
5698                    ambient_occlusion: ambient_occlusion_placeholder.view,
5699                    contact_shadow: contact_shadow_placeholder.view,
5700                    probe_visibility: probe_visibility_placeholder.view,
5701                }
5702                .entries(&shared);
5703                let group = device.create_bind_group(&BindGroupDesc {
5704                    label: Some("shadow view"),
5705                    layout: mesh_layout,
5706                    entries: &entries,
5707                    variable_count: None,
5708                })?;
5709                rollback.bind_groups.push(group);
5710                frame_shadow_uniforms.push(tile_uniforms);
5711                frame_shadow_groups.push(group);
5712                frame_shadow_entries.push(entries);
5713                frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5714            }
5715            shadow_uniforms.push(frame_shadow_uniforms);
5716            shadow_groups.push(frame_shadow_groups);
5717            shadow_group_entries.push(frame_shadow_entries);
5718            shadow_selection.push(frame_shadow_selection);
5719            service();
5720        }
5721
5722        // --- the tonemap pass ---
5723        let tonemap_entries = [
5724            BindGroupLayoutEntry {
5725                binding: 0,
5726                visibility: ShaderStages::FRAGMENT,
5727                kind: BindingKind::SampledImage {
5728                    view_type: ImageViewType::D2,
5729                    sample_type: SampleType::Float,
5730                },
5731                count: 1,
5732                flags: BindingFlags::empty(),
5733            },
5734            BindGroupLayoutEntry {
5735                binding: 1,
5736                visibility: ShaderStages::FRAGMENT,
5737                kind: BindingKind::Sampler { comparison: false },
5738                count: 1,
5739                flags: BindingFlags::empty(),
5740            },
5741            // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5742            // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5743            // decision restated: WebGPU has no push constants at all, so a range
5744            // here would split this pass into a tier A and a tier B form —
5745            // two layouts, two buffers and, because one Slang entry point reads
5746            // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5747            // one and never both, a second copy of `tonemap.slang`. Four bytes
5748            // once a frame do not buy that.
5749            //
5750            // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5751            // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5752            // in the vertex one, because the vertex stage generates three
5753            // corners out of `SV_VertexID` and reads nothing.
5754            BindGroupLayoutEntry {
5755                binding: 2,
5756                visibility: ShaderStages::FRAGMENT,
5757                kind: BindingKind::UniformBuffer { dynamic: false },
5758                count: 1,
5759                flags: BindingFlags::empty(),
5760            },
5761            // The measured exposure — see [`crate::exposure`]. **Bound on every
5762            // frame, whether or not anything measured**, because a binding that
5763            // comes and goes is a second pipeline layout and a second group
5764            // cache keyed on which one is live, to save four bytes. The block
5765            // above carries the switch that decides whether the shader reads it.
5766            BindGroupLayoutEntry {
5767                binding: 3,
5768                visibility: ShaderStages::FRAGMENT,
5769                kind: BindingKind::StorageBuffer {
5770                    // Written by `exposure.slang`'s reduce and read here —
5771                    // `StructuredBuffer` in this shader, which is the truth
5772                    // rather than a hint.
5773                    read_only: true,
5774                    dynamic: false,
5775                    stride: size_of::<u32>() as u32,
5776                },
5777                count: 1,
5778                flags: BindingFlags::empty(),
5779            },
5780        ];
5781        let tonemap_desc = BindGroupLayoutDesc {
5782            label: Some("tonemap scene"),
5783            entries: &tonemap_entries,
5784        };
5785        check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5786        let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5787        rollback.bind_group_layouts.push(tonemap_layout);
5788        let tonemap_set_layouts = [tonemap_layout];
5789        let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5790            label: Some("tonemap"),
5791            bind_group_layouts: &tonemap_set_layouts,
5792            push_constants: None,
5793        })?;
5794        rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5795        let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5796        let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5797        let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5798            label: Some("tonemap.slang"),
5799            spirv: TONEMAP.spirv(),
5800            wgsl: TONEMAP.wgsl(),
5801            msl: TONEMAP.msl(),
5802            // A container per entry point, for the reason the mesh module above
5803            // gives.
5804            dxil: &TONEMAP.dxil_containers(),
5805        })?;
5806        let tonemap_targets = [ColorTargetState::opaque(target_format)];
5807        let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5808            label: Some("tonemap"),
5809            layout: tonemap_pipeline_layout,
5810            vertex: ShaderEntry {
5811                module: tonemap_module,
5812                entry_point: tonemap_vertex,
5813            },
5814            fragment: Some(ShaderEntry {
5815                module: tonemap_module,
5816                entry_point: tonemap_fragment,
5817            }),
5818            // The full-screen triangle is deliberately oversized, so two of its
5819            // vertices are outside the viewport and its winding is not worth
5820            // reasoning about. `CullMode::None` is the honest setting.
5821            primitive: PrimitiveState::default(),
5822            depth_stencil: None,
5823            multisample: MultisampleState::default(),
5824            color_targets: &tonemap_targets,
5825        });
5826        device.destroy_shader_module(tonemap_module);
5827        let tonemap_pipeline = tonemap_pipeline?;
5828        rollback.pipelines.push(tonemap_pipeline);
5829        service();
5830
5831        // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5832        // leave a golden image depending on two rasterisers agreeing about
5833        // texel-centre arithmetic.
5834        let sampler = device.create_sampler(&SamplerDesc {
5835            label: Some("tonemap scene"),
5836            mag_filter: FilterMode::Nearest,
5837            min_filter: FilterMode::Nearest,
5838            mip_filter: FilterMode::Nearest,
5839            address_mode: [SamplerAddressMode::ClampToEdge; 3],
5840            ..SamplerDesc::default()
5841        })?;
5842        rollback.samplers.push(sampler);
5843
5844        // No field, so no pass: the frame every caller of this type drew
5845        // before grass existed. The two calm wind layers are one texel each
5846        // and are what makes a field with no weather set still.
5847        //
5848        // **Before the literal below, not inside it**: the literal moves the
5849        // camera, the shared draw pipelines and the pools out of the rollback,
5850        // so a failure inside it would leak them. `GrassScene::new` releases
5851        // its own half on failure, and the literal then has nothing that can
5852        // fail.
5853        let grass = GrassScene::new(device, uploads, FRAMES_IN_FLIGHT)?;
5854
5855        Ok(Self {
5856            pool: rollback
5857                .pool
5858                .take()
5859                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5860            bucket_constants,
5861            region_step,
5862            bucket_modes,
5863            instances: rollback
5864                .instances
5865                .take()
5866                .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5867            mesh_ids,
5868            skinnable_meshes,
5869            skinned_instances: Vec::new(),
5870            materials: rollback
5871                .materials
5872                .take()
5873                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5874            material_ids,
5875            probes: rollback
5876                .probes
5877                .take()
5878                .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5879            probe_volume: scene.probes.volume,
5880            base_color_page,
5881            normal_page,
5882            mro_page,
5883            emissive_page,
5884            page_extents,
5885            page_layers,
5886            base_color_sampler,
5887            anisotropy,
5888            // Every slot's groups were just built naming these.
5889            slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5890            retired_pages: Vec::new(),
5891            // No frame has been recorded yet, and the counters say so rather
5892            // than reporting the count a frame *would* have.
5893            recorded_draws: 0,
5894            emit,
5895            range_limit,
5896            clusters: rollback.clusters.take(),
5897            culls_clusters,
5898            draw_constants,
5899            mesh_clusters,
5900            // One entry per description mesh, each holding one bucket per level,
5901            // where the cull pass takes a uniform cut — and nothing at all where
5902            // the amplification stage takes a per-cluster one. Read off the
5903            // bucket table that was actually built rather than re-derived from
5904            // the path.
5905            mesh_level_buckets: if emit.is_mesh() {
5906                Vec::new()
5907            } else {
5908                residents
5909                    .iter()
5910                    .enumerate()
5911                    .map(|(index, resident)| {
5912                        let base = bucket_bases[index];
5913                        (base..base + resident.levels.len())
5914                            .map(|bucket| {
5915                                u32::try_from(bucket)
5916                                    .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5917                            })
5918                            .collect()
5919                    })
5920                    .collect()
5921            },
5922            lod_error_budget: LOD_ERROR_BUDGET,
5923            lod_hold_ratio: LOD_HOLD_RATIO,
5924            // Overwritten by the first `begin_frame`, which is the only thing
5925            // that can know the viewport.
5926            shadow_lod_params: [0.0, 0.0, 0.0],
5927            extra_lights: Vec::new(),
5928            primary: rollback
5929                .primary
5930                .take()
5931                .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5932            draw_pipelines: rollback
5933                .draw_pipelines
5934                .take()
5935                .unwrap_or_else(|| unreachable!("built ahead of the camera")),
5936            views: Vec::new(),
5937            draw_tables: DrawTables {
5938                bucket_meshes,
5939                bucket_clusters,
5940                bucket_cluster_bases,
5941                mesh_levels,
5942                level_groups,
5943                level_meshes,
5944                instance_capacity: scene.capacities.instances,
5945                light_capacity: scene.capacities.lights,
5946            },
5947            frame_serial: 0,
5948            frame_scene: None,
5949            frame: 0,
5950            mesh_layout,
5951            mesh_pipeline_layout,
5952            mesh_pipeline,
5953            // Off, and unbuilt, on the ground grid's terms below: the wireframe
5954            // view is opt-in, so a caller that never asks for one draws the
5955            // frame it drew before `set_wireframe` existed.
5956            wireframe_pipeline: None,
5957            wireframe_on: false,
5958            occlusion_culling: OcclusionCulling::OFF,
5959            point_face_culls: true,
5960            skinning_culls: true,
5961            skin_shadow_reach: Vec::new(),
5962            skin_cull: skin_cull::SkinCull::default(),
5963            skinned_skipped: 0,
5964            shadow_view_tamper: None,
5965            // Off, on the line above's terms: the normals view is opt-in, so a
5966            // caller that never asks for one draws the frame it drew before
5967            // `set_normals_view` existed. It builds nothing, so there is no
5968            // second field here.
5969            normals_view: false,
5970            // Off on the same terms, and "off" here is a density of zero: the
5971            // shader's composite is exactly the identity there, so a caller who
5972            // never calls `set_fog` gets the frame byte for byte.
5973            fog: Fog::NONE,
5974            sky: Sky::NONE,
5975            atmosphere: None,
5976            sky_view: None,
5977            sky_view_build: None,
5978            lod_view: false,
5979            heatmap: false,
5980            occlusion_view: false,
5981            motion_view: false,
5982            bent_normal_view: false,
5983            cascade_view: false,
5984            atlas_view: false,
5985            // Following the camera, on the line above's terms: the selection eye
5986            // is the camera's until a caller pins it, so a renderer nobody calls
5987            // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5988            // handed before this field existed.
5989            frozen_selection_eye: None,
5990            shadow_atlas,
5991            shadow_atlas_view,
5992            shadow_placeholder,
5993            shadow_placeholder_view,
5994            shadow_sampler,
5995            shadow_pipeline,
5996            depth_masked_pipeline,
5997            shadow_clear_pipeline,
5998            rsm_pipeline,
5999            probe_gather,
6000            probe_update: scene.probes.update,
6001            // Overwritten by the first `begin_frame`, which is the only reader's
6002            // only source. Zero is the honest placeholder: no cascade has been
6003            // fitted yet, and a gather recorded against it would scale by zero
6004            // rather than by a number nobody chose.
6005            cascade_reach: 0.0,
6006            // Nothing has been fitted before the first `begin_frame`.
6007            rsm_cull_ready: false,
6008            sun_color: Vec3::ZERO,
6009            shadow_draws: std::mem::take(&mut rollback.shadow_draws),
6010            shadow_uniforms,
6011            shadow_prepare_views: Vec::new(),
6012            shadow_prepare_culls: Vec::new(),
6013            shadow_groups,
6014            shadow_selection,
6015            shadow_lights: shadow::Selection::default(),
6016            // Nothing has drawn the atlas, so the first frame draws every group
6017            // whatever it is asked for — which is also what gives the image a
6018            // defined content before anything samples it. A record is never
6019            // empty, so the first frame's is a change and takes every id past
6020            // the zero below it.
6021            shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
6022            shadow_group_id: vec![0; SHADOW_CULLS],
6023            shadow_group_writes: vec![0; SHADOW_CULLS],
6024            shadow_footprints: Vec::new(),
6025            shadow_dag_elements: std::collections::BTreeSet::new(),
6026            shadow_written: Vec::new(),
6027            shadow_moved: Vec::new(),
6028            shadow_pass_id: 0,
6029            shadow_pass_ran: Arc::new(AtomicU64::new(0)),
6030            shadow_pending: None,
6031            // A reach of zero, so every centre on the first frame is further
6032            // from what the image holds than the nothing it holds reaches —
6033            // which is the reset that frame should be.
6034            shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
6035            shadow_group_redrawn: vec![false; SHADOW_CULLS],
6036            shadow_atlas_layout: None,
6037            shadow_atlas_cached: false,
6038            shadow_cadence_reset: false,
6039            shadow_faces_redrawn: 0,
6040            shadow_cadence_request: None,
6041            shadow_atlas_clears: true,
6042            shadow_frame: 0,
6043            // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
6044            // by, so a slot has been through the whole loop before it is read.
6045            // `culls_clusters` rather than the device's feature bits: what
6046            // decides whether the cluster word is a count is whether *this
6047            // renderer* built an amplification stage.
6048            cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
6049            tonemap_layout,
6050            tonemap_pipeline_layout,
6051            tonemap_pipeline,
6052            sampler,
6053            // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
6054            // renderer nobody has called `set_exposure` on writes the frame it
6055            // wrote before the block existed.
6056            exposure: tonemap::DEFAULT_EXPOSURE,
6057            exposure_adaptation: None,
6058            // And the filmic roll-off over it: this renderer shades in linear
6059            // HDR, so a view that has asked for nothing gets the operator that
6060            // range was shaded for.
6061            tonemap_curve: tonemap::TonemapCurve::Aces,
6062            target_format,
6063            ambient_occlusion_placeholder,
6064            contact_shadow_placeholder,
6065            probe_visibility_placeholder,
6066            // Nothing has been captured, so every frame drawn before
6067            // `capture_probe_visibility` reads the placeholder and weighs every
6068            // probe at one — which is the frame this renderer drew before the
6069            // maps existed.
6070            probe_visibility: None,
6071            probe_occluders,
6072            specular_dfg,
6073            ltc_table,
6074            sky_prefilter,
6075            shadow_group_entries,
6076            // Off, and unbuilt: the grid is opt-in, so a caller that never asks
6077            // for one draws the frame it drew before this module existed.
6078            ground_grid: None,
6079            ground_grid_on: false,
6080            // Empty, and unbuilt: nothing has appended a segment, so this
6081            // renderer records the frame it recorded before the layer existed.
6082            debug_draw: DebugDraw::default(),
6083            // Unbuilt: no frame has shown the atlas — see the field.
6084            atlas_viewer: None,
6085            frame_atlas_view: false,
6086            // Full resolution, which is the frame every caller of this type drew
6087            // before there was a knob — see [`Self::set_render_scale`].
6088            render_scale: 1.0,
6089            frame_render_scale: 1.0,
6090            // The default stack the view wants, no quality clamp and no
6091            // override, which resolves to every effect this device permits but
6092            // the lens one — the frame every caller of this type drew before
6093            // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
6094            effect_request: EffectRequest::default(),
6095            device_effects: RenderEffects::all(),
6096            frame_effects: RenderEffects::DEFAULT_STACK,
6097            // What the switch says today, so a renderer built and never opened
6098            // still describes the frame it would draw. `begin_frame` reads it
6099            // again for the frame it opens.
6100            frame_ssao_blurs: crate::ssao::blur_passes(),
6101            // No frame has been recorded yet, on `recorded_draws`' terms.
6102            recorded_fullscreen: 0,
6103            // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
6104            recorded_debug_draw: 0,
6105            recorded_tile_clears: 0,
6106            // No bodies, so no pass: the frame every caller of this type drew
6107            // before water existed. Nothing is allocated until a body is set.
6108            water: WaterBodies::new(FRAMES_IN_FLIGHT),
6109            recorded_water_draws: 0,
6110            grass,
6111            // No frame has begun.
6112            frame_grass: None,
6113            wind: crcbl_shaders::wind::WindParams::default(),
6114            recorded_grass_draws: 0,
6115            // The build's own batch joins once it is submitted, which is after
6116            // this returns — see `build_on_path`.
6117            uploads_in_flight: Vec::new(),
6118        })
6119    }
6120
6121    /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
6122    /// fragment entry points.
6123    ///
6124    /// One helper because every post pass in this crate wants the same
6125    /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
6126    /// differing in the module, the layout and the target format alone. The
6127    /// tonemap's stays written out where it is: it is the one that carries the
6128    /// *why* of the shape, and this is the shape repeated.
6129    ///
6130    /// The module is destroyed before the pipeline result is unwrapped, so a
6131    /// failing creation leaks nothing.
6132    ///
6133    /// # Errors
6134    ///
6135    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6136    fn build_fullscreen(
6137        device: &dyn Device,
6138        label: &str,
6139        shader: &crcbl_shaders::Shader,
6140        layout: PipelineLayoutHandle,
6141        color_targets: &[ColorTargetState],
6142    ) -> Result<GraphicsPipelineHandle, HalError> {
6143        Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
6144    }
6145
6146    /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
6147    /// against an attachment it does not write.
6148    ///
6149    /// The state is [`DepthStencilState::equal_depth_read_only`], whose
6150    /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
6151    /// depth must equal what is already there". One caller, [`crate::sky_pass`],
6152    /// which emits its triangle at the far plane so that the test selects
6153    /// exactly the pixels no geometry covered — see that module.
6154    ///
6155    /// # Errors
6156    ///
6157    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6158    fn build_tested_fullscreen(
6159        device: &dyn Device,
6160        label: &str,
6161        shader: &crcbl_shaders::Shader,
6162        layout: PipelineLayoutHandle,
6163        color_targets: &[ColorTargetState],
6164        depth_format: Format,
6165    ) -> Result<GraphicsPipelineHandle, HalError> {
6166        Self::build_fullscreen_with(
6167            device,
6168            label,
6169            shader,
6170            layout,
6171            color_targets,
6172            Some(DepthStencilState::equal_depth_read_only(depth_format)),
6173        )
6174    }
6175
6176    /// The body of the two above, which differ in their depth state and in
6177    /// nothing else.
6178    ///
6179    /// # Errors
6180    ///
6181    /// [`HalError`] from the manifest lookup, the module or the pipeline.
6182    fn build_fullscreen_with(
6183        device: &dyn Device,
6184        label: &str,
6185        shader: &crcbl_shaders::Shader,
6186        layout: PipelineLayoutHandle,
6187        color_targets: &[ColorTargetState],
6188        depth_stencil: Option<DepthStencilState>,
6189    ) -> Result<GraphicsPipelineHandle, HalError> {
6190        let vertex = entry(shader, Stage::Vertex)?;
6191        let fragment = entry(shader, Stage::Fragment)?;
6192        let module = device.create_shader_module(&ShaderModuleDesc {
6193            label: Some(shader.source()),
6194            spirv: shader.spirv(),
6195            wgsl: shader.wgsl(),
6196            msl: shader.msl(),
6197            // A container per entry point, for the reason the mesh module gives.
6198            dxil: &shader.dxil_containers(),
6199        })?;
6200        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
6201            label: Some(label),
6202            layout,
6203            vertex: ShaderEntry {
6204                module,
6205                entry_point: vertex,
6206            },
6207            fragment: Some(ShaderEntry {
6208                module,
6209                entry_point: fragment,
6210            }),
6211            // The triangle is deliberately oversized, so two of its vertices are
6212            // outside the viewport and its winding is not worth reasoning about.
6213            primitive: PrimitiveState::default(),
6214            depth_stencil,
6215            multisample: MultisampleState::default(),
6216            color_targets,
6217        });
6218        device.destroy_shader_module(module);
6219        pipeline
6220    }
6221
6222    /// Builds a full-screen-triangle pipeline that writes a **depth**
6223    /// attachment and no colour one.
6224    ///
6225    /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
6226    /// no colour target at all, and a depth state whose comparison always
6227    /// passes so every texel of the destination takes the value the fragment
6228    /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
6229    /// in this file uses would be wrong here — this pass is not depth-testing
6230    /// anything, it is writing a reduction, and a test against the target's
6231    /// undefined contents would drop texels at random.
6232    ///
6233    /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
6234    /// a method rather than moving there because the module and the
6235    /// destroy-before-unwrap above are this file's, and both take it in exactly
6236    /// as `crate::ssao` takes the sibling.
6237    ///
6238    /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
6239    /// fragment stage per pyramid, and a stage looked up by kind would be
6240    /// ambiguous.
6241    ///
6242    /// # Errors
6243    ///
6244    /// [`HalError`] from the module or the pipeline.
6245    fn build_depth_fullscreen(
6246        device: &dyn Device,
6247        label: &str,
6248        shader: &crcbl_shaders::Shader,
6249        vertex: &str,
6250        fragment: &str,
6251        layout: PipelineLayoutHandle,
6252        format: Format,
6253    ) -> Result<GraphicsPipelineHandle, HalError> {
6254        let module = device.create_shader_module(&ShaderModuleDesc {
6255            label: Some(shader.source()),
6256            spirv: shader.spirv(),
6257            wgsl: shader.wgsl(),
6258            msl: shader.msl(),
6259            dxil: &shader.dxil_containers(),
6260        })?;
6261        let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
6262            label: Some(label),
6263            layout,
6264            vertex: ShaderEntry {
6265                module,
6266                entry_point: vertex,
6267            },
6268            fragment: Some(ShaderEntry {
6269                module,
6270                entry_point: fragment,
6271            }),
6272            primitive: PrimitiveState::default(),
6273            depth_stencil: Some(DepthStencilState {
6274                format,
6275                depth_write: true,
6276                depth_compare: CompareOp::Always,
6277                stencil: None,
6278                bias: DepthBias::default(),
6279            }),
6280            multisample: MultisampleState::default(),
6281            color_targets: &[],
6282        });
6283        device.destroy_shader_module(module);
6284        pipeline
6285    }
6286
6287    /// Creates the geometry pool and makes every mesh of `scene` resident in it.
6288    ///
6289    /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
6290    /// the pool is not the rollback's until this has returned, so a failure
6291    /// between creating it and flushing the last upload releases it here.
6292    fn build_geometry(
6293        device: &dyn Device,
6294        queue: QueueHandle,
6295        scene: &SceneDesc<'_>,
6296        service: &mut dyn FnMut(),
6297    ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
6298        let mut pool = MeshPool::new(
6299            device,
6300            &MeshPoolDesc {
6301                label: Some("forward geometry"),
6302                vertex_capacity: scene.capacities.vertices,
6303                index_capacity: scene.capacities.indices,
6304                mesh_capacity: scene.capacities.meshes,
6305            },
6306        )?;
6307        match Self::residents(device, queue, &mut pool, scene, service) {
6308            Ok(residents) => Ok((pool, residents)),
6309            Err(error) => {
6310                pool.destroy(device);
6311                Err(error)
6312            }
6313        }
6314    }
6315
6316    /// Creates the material table and fills it with `scene`'s rows, returning it
6317    /// and the id of each.
6318    ///
6319    /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
6320    /// the table is not the rollback's until this has returned.
6321    fn build_materials(
6322        device: &dyn Device,
6323        scene: &SceneDesc<'_>,
6324    ) -> Result<(MaterialTable, Vec<u32>), HalError> {
6325        let mut materials = MaterialTable::new(
6326            device,
6327            &MaterialTableDesc {
6328                label: Some("forward"),
6329                capacity: scene.capacities.materials,
6330            },
6331        )?;
6332        match Self::material_rows(device, &mut materials, &scene.materials) {
6333            Ok(ids) => Ok((materials, ids)),
6334            Err(error) => {
6335                materials.destroy(device);
6336                Err(error)
6337            }
6338        }
6339    }
6340
6341    /// Inserts `rows` **in order** and returns the id of each.
6342    ///
6343    /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6344    /// be released on a failure without the borrow that filling it takes, which
6345    /// is the same shape [`ForwardRenderer::residents`] has.
6346    ///
6347    /// **In order, because row 0 is not this function's to choose**: it is what
6348    /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6349    /// without a material id shades with. Inserting a description's rows in any
6350    /// other order would move that row under every caller — see
6351    /// [`SceneDesc::materials`], which is where it is a caller's decision.
6352    fn material_rows(
6353        device: &dyn Device,
6354        materials: &mut MaterialTable,
6355        rows: &[mesh::GpuMaterial],
6356    ) -> Result<Vec<u32>, HalError> {
6357        let mut ids = Vec::with_capacity(rows.len());
6358        for row in rows {
6359            let handle = materials.insert(device, row)?;
6360            // The id is asked for rather than assumed, because the number an
6361            // instance carries is this one and nothing else knows it.
6362            ids.push(materials.index(handle).ok_or_else(|| {
6363                HalError::Backend(
6364                    "a material inserted into an empty table did not resolve".to_string(),
6365                )
6366            })?);
6367        }
6368        Ok(ids)
6369    }
6370
6371    /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6372    /// the transfers have completed.
6373    ///
6374    /// The calls are §3.1's upload path in order: the copies are recorded and
6375    /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6376    /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6377    /// before they have.
6378    ///
6379    /// **In description order**, which is what makes a mesh's table id a
6380    /// property of the description rather than of this loop — the second mesh
6381    /// uploaded is the pool's first resident at a non-zero base vertex, which is
6382    /// what the module docs call the one thing that can tell a working base
6383    /// vertex from a cancelled one.
6384    ///
6385    /// A DAG is **one upload per level**. Every level was decimated separately,
6386    /// so a coarser level's vertices are wherever the collapses put them and
6387    /// belong to no vertex of the level below — a DAG is several vertex ranges,
6388    /// and the pool suballocates in vertices, so several ranges means several
6389    /// uploads. Level 0 goes first, so every other level starts past it and the
6390    /// offsets a cluster carries are non-negative; that is checked rather than
6391    /// assumed, because the pool's free list makes no promise about where a mesh
6392    /// lands.
6393    fn residents(
6394        device: &dyn Device,
6395        queue: QueueHandle,
6396        pool: &mut MeshPool,
6397        scene: &SceneDesc<'_>,
6398        service: &mut dyn FnMut(),
6399    ) -> Result<Vec<ResidentMesh>, HalError> {
6400        let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6401            Vec::with_capacity(scene.meshes.len());
6402        for desc in &scene.meshes {
6403            match &desc.geometry {
6404                Geometry::Flat {
6405                    vertices,
6406                    indices,
6407                    uv_range,
6408                    flags,
6409                    ..
6410                } => {
6411                    uploaded.push(vec![pool.upload(
6412                        device,
6413                        queue,
6414                        &MeshUpload {
6415                            label: &desc.label,
6416                            vertices,
6417                            indices,
6418                            uv_range: *uv_range,
6419                            flags: *flags,
6420                        },
6421                    )?]);
6422                    service();
6423                }
6424                Geometry::Dag {
6425                    levels,
6426                    dag,
6427                    uv_range,
6428                    flags,
6429                } => {
6430                    let mut handles = Vec::with_capacity(levels.len());
6431                    for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6432                        handles.push(pool.upload(
6433                            device,
6434                            queue,
6435                            &MeshUpload {
6436                                label: &format!("{} level {depth}", desc.label),
6437                                vertices,
6438                                indices: &level.indices(),
6439                                // Level 0's range for every level, which is the
6440                                // one the mesh path reads whichever level it
6441                                // draws — see `Geometry::Dag::uv_range`.
6442                                uv_range: *uv_range,
6443                                // And the description's flags for every level,
6444                                // for the same reason: the levels are one
6445                                // surface, so a tangent frame either describes
6446                                // all of them or none.
6447                                flags: *flags,
6448                            },
6449                        )?);
6450                        service();
6451                    }
6452                    uploaded.push(handles);
6453                }
6454            }
6455        }
6456
6457        pool.flush(device)?;
6458        service();
6459        // The table index is the only number that leaves here — where the
6460        // geometry actually is reaches the GPU through the mesh table, and the
6461        // draw arguments are built from that table by a shader. `MeshPool::mesh`
6462        // is still asked, because it is the call that refuses a mesh whose
6463        // upload has not completed, and an id for a mesh that is not there yet
6464        // would be a draw of nothing.
6465        let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6466            (Some(_), Some(id)) => Ok(id),
6467            _ => Err(MeshPoolError::NotResident { handle }),
6468        };
6469        let base_vertex = |handle| match pool.mesh(handle) {
6470            Some(range) => Ok(range.base_vertex),
6471            None => Err(MeshPoolError::NotResident { handle }),
6472        };
6473
6474        let mut residents = Vec::with_capacity(uploaded.len());
6475        for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6476            // **Relative to level 0's base**, because that is the base the
6477            // instance resolves through its mesh id and the one the stage adds
6478            // this on top of. A level that landed *below* level 0 would make the
6479            // sum wrap, so it is refused here rather than drawn as another
6480            // mesh's vertices. A flat mesh is one level and reads zero.
6481            let level_zero = base_vertex(handles[0])?;
6482            let mut vertex_bases = Vec::with_capacity(handles.len());
6483            for (depth, &handle) in handles.iter().enumerate() {
6484                let base = base_vertex(handle)?;
6485                vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6486                    HalError::InvalidDescriptor(format!(
6487                        "{} level {depth} landed at vertex {base}, below level 0's \
6488                         {level_zero}, so its clusters cannot name their own geometry",
6489                        desc.label
6490                    ))
6491                })?);
6492            }
6493            residents.push(ResidentMesh {
6494                levels: handles
6495                    .iter()
6496                    .map(|&handle| resolve(handle))
6497                    .collect::<Result<_, _>>()?,
6498                vertex_bases,
6499                // Matched on the description rather than counted off `handles`,
6500                // so a DAG decimated to a single level is still refused: what
6501                // makes a mesh skinnable is that every draw of it reads one
6502                // vertex run, and that is a property of the geometry rather than
6503                // of how many levels it happened to arrive with.
6504                skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6505            });
6506        }
6507        Ok(residents)
6508    }
6509
6510    /// Rotates to the next frame's uniform buffer and instance buffer, writes
6511    /// this frame's camera and light into the first, and uploads whatever
6512    /// changed into the second.
6513    ///
6514    /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6515    /// Separate from `add_passes` because the write happens on the CPU and the
6516    /// passes are recorded on the GPU timeline: fusing them would hide the ring
6517    /// rotation inside a function whose name says nothing about it.
6518    ///
6519    /// **It moves nothing.** Every object's transform is the caller's, written
6520    /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6521    /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6522    /// frame in which nothing moved uploads no instance bytes at all. The
6523    /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6524    /// spins it; a still scene is free.
6525    ///
6526    /// It also writes this frame's **cull parameters** — the camera's frustum,
6527    /// extracted from the very same view-projection the uniform block carries,
6528    /// so the pass that decides what is on screen and the pass that draws it
6529    /// cannot be looking at two different cameras — and zeroes the counters the
6530    /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6531    /// zeroes come from the host.
6532    ///
6533    /// # Errors
6534    ///
6535    /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6536    /// draw-generation buffers could not be written.
6537    pub fn begin_frame(
6538        &mut self,
6539        device: &dyn Device,
6540        camera: &Camera,
6541        light: &DirectionalLight,
6542        extent: (u32, u32),
6543    ) -> Result<(), HalError> {
6544        // First, before anything this frame could release or rewrite.
6545        self.retire_uploads(device)?;
6546        // The instance pool owns the ring, so its slot is the frame index the
6547        // uniform buffer and the bind group below are picked with.
6548        self.frame = self.instances.rotate();
6549        self.instances.flush(device)?;
6550        self.begin_frame_body(device, camera, light, extent)
6551    }
6552
6553    /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6554    /// call with the skinning plan folded into it.
6555    ///
6556    /// It does four things in the one order that is correct, which is why it is
6557    /// a call and not a note in someone's docs:
6558    ///
6559    /// 1. rotates the instance ring, so the frame slot exists;
6560    /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6561    ///    uploads the palettes and **moves the ping-pong** — the only place the
6562    ///    parity ever moves;
6563    /// 3. points every object placed by
6564    ///    [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6565    ///    region the parity now names;
6566    /// 4. uploads the instance delta, so those bases are the ones this frame
6567    ///    draws.
6568    ///
6569    /// Do those three and four in the other order and the objects carry the
6570    /// previous frame's half — a character posed one frame late, every frame,
6571    /// with nothing to report it. A caller never sees a parity or a table id, and
6572    /// so cannot get that wrong.
6573    ///
6574    /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6575    /// this frame animates. A frame with **no** skinned object still calls this
6576    /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6577    /// otherwise re-dispatch whichever frame last used it.
6578    ///
6579    /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6580    /// the one that orders the dispatch before the draws.
6581    ///
6582    /// # Errors
6583    ///
6584    /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6585    /// palette, a binding count that is not the region's vertex count, more than
6586    /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6587    /// refused, this renderer's own uniform and instance writes included.
6588    ///
6589    /// # Panics
6590    ///
6591    /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6592    /// its rings are indexed by this renderer's frame slot, and
6593    /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6594    pub fn begin_skinned_frame(
6595        &mut self,
6596        device: &dyn Device,
6597        skinning: &mut Skinning,
6598        ranges: &[SkinRange<'_>],
6599        camera: &Camera,
6600        light: &DirectionalLight,
6601        extent: (u32, u32),
6602    ) -> Result<(), SkinningError> {
6603        // First, on `begin_frame`'s terms.
6604        self.retire_uploads(device)?;
6605        self.frame = self.instances.rotate();
6606        skinning.begin_frame(device, self.frame, ranges)?;
6607        self.point_skinned_instances(skinning.parity());
6608        self.instances.flush(device)?;
6609        self.begin_frame_body(device, camera, light, extent)?;
6610        Ok(())
6611    }
6612
6613    /// Whether this frame records the irradiance probes' two
6614    /// updater passes.
6615    ///
6616    /// The scene's own answer and the console's together: the volume decides
6617    /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6618    /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6619    /// on/off pair a pricing run reads the two passes' cost off with everything
6620    /// else held still.
6621    ///
6622    /// **It is not the whole condition.** The map is cascade 0's own draws, so
6623    /// the pass is recorded only where that cascade is being drawn too — see
6624    /// `add_shadow_pass`, which is where the rest of it is.
6625    fn probe_update_runs(&self) -> bool {
6626        self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6627    }
6628
6629    /// The six side-plane sets a point light's face culls test, or `None` for
6630    /// a light that is not a point — or with the face culls switched off, which
6631    /// is one cull against the light's box drawn into all six faces.
6632    ///
6633    /// `faces` are the light's face matrices in face order, the ones its tiles
6634    /// render through.
6635    fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6636        if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6637            return None;
6638        }
6639        let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6640        Some(crate::cull::face_planes(&matrices))
6641    }
6642
6643    /// Every punctual shadow face this frame draws into the punctual reflective
6644    /// shadow map, in the order the pass draws them and the producer table lists
6645    /// them.
6646    ///
6647    /// **One list for both halves of the updater**, and that is the point:
6648    /// `add_shadow_pass` sets a viewport from a face's
6649    /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6650    /// of the matching producer row, so a face the pass drew and a row the
6651    /// gather walked have to be the same face. Building the two from separate
6652    /// filters is two things that can drift, and the drift would be a light
6653    /// bouncing another light's map.
6654    ///
6655    /// **The occupied slots this frame redraws**, which is the same set
6656    /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6657    /// block and its draws are a shadow cull's, and
6658    /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6659    /// it is holding.
6660    ///
6661    /// # Every occupied tile, and no budget of its own
6662    ///
6663    /// The producers are exactly the atlas's occupied faces — up to
6664    /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6665    /// them — rather than the highest-ranked light or some smaller count.
6666    ///
6667    /// **Because the budget already exists and is spent.**
6668    /// [`shadow::Selection`] has ranked these lights by projected screen
6669    /// influence and handed out every tile there is; a second budget on top
6670    /// would rank the same lights again, differently, and produce a light that
6671    /// casts a shadow and lends no bounce. That is a difference no picture shows
6672    /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6673    /// and it is the kind of quiet inconsistency the two halves of one light are
6674    /// worst placed to have.
6675    ///
6676    /// It is affordable at the extent that was chosen for it:
6677    /// `apps/lantern` lights seven faces, and
6678    /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6679    /// carries the sweep that priced them.
6680    ///
6681    /// **Empty where shadows are off**, for that same reason — a punctual face
6682    /// *is* a shadow view. The sun's half is not, which is what
6683    /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6684    /// sun's bounce and loses every punctual one, rather than switching the
6685    /// whole updater off with them.
6686    fn punctual_faces(&self) -> Vec<PunctualFace> {
6687        if !self.probe_update_runs() {
6688            return Vec::new();
6689        }
6690        // A frame with the shadows switched off draws no atlas, so no group of
6691        // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6692        // branch has still written every one of these views and dispatched every
6693        // one of these culls, for this pass to draw through.
6694        let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6695        let mut faces = Vec::new();
6696        for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6697            let Some(held) = *held else {
6698                continue;
6699            };
6700            if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6701                continue;
6702            }
6703            let Some(light) = self.extra_lights.get(held.light) else {
6704                continue;
6705            };
6706            // A spot draws face 0 alone and a point light all six, each through
6707            // its own matrix into its own tile — `shadow::tile_span` is the same
6708            // function `Selection` allocated the run with, so a face here and a
6709            // tile there cannot disagree about how many there are.
6710            for face in 0..shadow::tile_span(light) {
6711                let tile = rsm::punctual_tile(held.base + face);
6712                faces.push(PunctualFace {
6713                    view: shadow_view(slot, face),
6714                    cull: shadow_cull(slot),
6715                    face,
6716                    tile,
6717                    producer: producer_row(light, tile),
6718                });
6719            }
6720        }
6721        faces
6722    }
6723
6724    /// Puts an object in the scene and returns the handle that names it.
6725    ///
6726    /// An instance in the pool **is** an object in the scene: the frame records
6727    /// a fixed number of draws and the cull pass decides which instances they
6728    /// walk, so adding one costs a slot in an array and not a command. It is
6729    /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6730    /// uploads it.
6731    ///
6732    /// # The index it lands at is not decoration
6733    ///
6734    /// `draw_gen.slang` keys topic 25's hysteresis state by the
6735    /// instance's **array index**, at `instance_index * group_stride`, and
6736    /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6737    /// record of which of a DAG's groups an object had expanded belongs to the
6738    /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6739    /// handed to the next `add_instance`, which inherits it. What that costs is
6740    /// one frame selected against a history that is not this object's, and the
6741    /// next frame's own judgement replaces it; it is never a wrong picture,
6742    /// because every group is judged afresh whatever the state said.
6743    ///
6744    /// That inheritance is inert while the scene holds **one** instance of a DAG
6745    /// mesh, which is every frame the engine has drawn so far — one instance's
6746    /// run has no previous occupant, and a flat mesh's
6747    /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6748    /// nothing indexes the state for it. It stops being inert the moment an
6749    /// application places a second.
6750    ///
6751    /// [`remove_instance`]: ForwardRenderer::remove_instance
6752    ///
6753    /// # A DAG mesh needs a device that can choose a level
6754    ///
6755    /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6756    /// **no** amplification stage in front of it emits every cluster of the
6757    /// bucket, which for a DAG is every level at once — several overlapping
6758    /// copies of one surface. This does not refuse it, because it has no
6759    /// vocabulary for that refusal; a caller placing a DAG asks
6760    /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6761    /// says yes. A flat mesh is unaffected on every path.
6762    ///
6763    /// # Errors
6764    ///
6765    /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6766    /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6767    /// what a caller sizes it with.
6768    ///
6769    /// # Panics
6770    ///
6771    /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6772    /// the description this renderer was built from. Both are indices a caller
6773    /// wrote against a description it holds, so an out-of-range one is a mistake
6774    /// in the calling code rather than a condition the frame can be in — and the
6775    /// alternative is an object silently drawn as some other mesh, in some other
6776    /// colour.
6777    pub fn add_instance(
6778        &mut self,
6779        desc: &InstanceDesc,
6780    ) -> Result<InstanceHandle, InstancePoolError> {
6781        let instance = self.gpu_instance(desc);
6782        self.instances.insert(&instance)
6783    }
6784
6785    /// Rewrites the object `handle` names — its mesh, its material and its
6786    /// transform, all three.
6787    ///
6788    /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6789    /// nothing, rather than overwriting whatever took its slot.
6790    ///
6791    /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6792    /// the element and nothing else: an object that did not move costs no
6793    /// transfer at all.
6794    ///
6795    /// # Panics
6796    ///
6797    /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6798    pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6799        let mut instance = self.gpu_instance(desc);
6800        instance.flags |= self.kept_flags(handle);
6801        self.instances.set(handle, &instance);
6802    }
6803
6804    /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6805    /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6806    /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6807    /// handle, whose rewrite writes nothing anyway.
6808    fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6809        self.instances.get(handle).map_or(0, |record| {
6810            record.flags
6811                & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6812        })
6813    }
6814
6815    /// Sets whether `handle` casts a shadow. Every instance starts casting.
6816    ///
6817    /// **Every shadow map and nothing else**: an instance that casts none is
6818    /// rejected by the cull of the sun's cascades and of every shadowed light,
6819    /// on every geometry path, so it lands in no tile of the atlas — and in no
6820    /// reflective shadow map, which draws those same culls' survivors, so it
6821    /// bounces no light into the probes either. Every camera still draws it,
6822    /// and it still receives the shadows the rest of the scene casts.
6823    ///
6824    /// What a model drawn for an icon wants, placed where the scene's sun can
6825    /// see it: see [`ViewBackground::Transparent`] and
6826    /// [`set_instance_views`](Self::set_instance_views).
6827    ///
6828    /// A change redraws every shadow map whose cull the instance could be kept
6829    /// by, because it is a write [`InstancePool::take_written`] names. Not a
6830    /// move, on
6831    /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6832    /// handle is ignored.
6833    pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6834        if let Some(record) = self.instances.get(handle) {
6835            let flags = if casts {
6836                record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6837            } else {
6838                record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6839            };
6840            self.instances.set_flags(handle, flags);
6841        }
6842    }
6843
6844    /// Whether `handle` casts a shadow, or `None` for a stale handle.
6845    #[must_use]
6846    pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6847        self.instances
6848            .get(handle)
6849            .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6850    }
6851
6852    /// Takes the object `handle` names back out of the scene, freeing its slot.
6853    ///
6854    /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6855    /// no longer records a draw per object: `cull.slang` asks whether an instance
6856    /// is live before it reads anything else, so removing an object and culling
6857    /// it off screen take the same path out of the frame. An instance left in the
6858    /// pool would be drawn wherever its transform put it.
6859    ///
6860    /// A stale handle removes nothing. Takes effect at the next
6861    /// [`ForwardRenderer::begin_frame`], on
6862    /// [`ForwardRenderer::set_instance`]'s terms.
6863    pub fn remove_instance(&mut self, handle: InstanceHandle) {
6864        self.instances.remove(handle);
6865    }
6866
6867    /// Captures a visibility map for every probe, from the static geometry
6868    /// standing in the scene right now.
6869    ///
6870    /// The probe visibility rung: each probe records how far
6871    /// away the nearest surface is in every direction, and `mesh.slang`'s
6872    /// `probe_irradiance` then weighs each of a fragment's eight probes by
6873    /// whether it can *see* that fragment — so a probe on the far side of a wall
6874    /// contributes nothing and a room stops lighting the room next door.
6875    /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6876    /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6877    /// format.
6878    ///
6879    /// # Call it once, after the scene's walls are placed
6880    ///
6881    /// **A description carries no instances** — [`SceneDesc`] is meshes,
6882    /// materials, a page and the probe rows, and the objects arrive afterwards
6883    /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6884    /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6885    /// call that has the room in it, and an application makes it once its static
6886    /// geometry is placed.
6887    ///
6888    /// A caller that never makes it draws exactly the frame this renderer drew
6889    /// before the maps existed: every group names the one-texel placeholder,
6890    /// which no surface is further away than, and every probe keeps all of its
6891    /// weight.
6892    ///
6893    /// **It is a capture of geometry and not a bake of light.** Nothing about
6894    /// the lights is recorded, every one of them still moves, and the rows the
6895    /// probes carry are untouched.
6896    ///
6897    /// # What it sees, and what it does not
6898    ///
6899    /// Every instance live in the pool when it is called, at the transform it
6900    /// then has, rasterised from its mesh's level-0 triangles into six 90°
6901    /// faces per probe. Objects that move
6902    /// afterwards keep the occlusion they had here, which is the accepted limit
6903    /// this technique has everywhere it is used — a probe volume is about the
6904    /// walls. Recapturing after a wall moves is this call again.
6905    ///
6906    /// **The device must be idle.** The previous capture's image is released
6907    /// here, and a frame in flight may still be reading it.
6908    ///
6909    /// # Errors
6910    ///
6911    /// [`HalError`] from the capture. The previous maps are kept on the failing
6912    /// path, so a renderer that has captured once and then failed goes on
6913    /// drawing with what it had.
6914    pub fn capture_probe_visibility(
6915        &mut self,
6916        device: &dyn Device,
6917        queue: QueueHandle,
6918    ) -> Result<(), HalError> {
6919        let placed: Vec<crate::probe_visibility::Occluder> = self
6920            .instances
6921            .live()
6922            .into_iter()
6923            .map(|record| crate::probe_visibility::Occluder {
6924                mesh: record.mesh,
6925                transform: Mat4::from_cols_array(&record.transform),
6926            })
6927            .collect();
6928        let Some(uploaded) = crate::probe_capture::capture(
6929            device,
6930            queue,
6931            &self.probe_volume,
6932            &self.probe_occluders,
6933            &placed,
6934        )?
6935        else {
6936            // No probes, or nothing placed for a map to be about. Leaving the
6937            // placeholder bound is the honest answer, and it is what a scene
6938            // with no probes has always read.
6939            return Ok(());
6940        };
6941        // The cached groups name the view this replaces, so they go before it
6942        // does — a bind group outliving the image it names is a validation
6943        // error on every backend that checks, and a use-after-free on the ones
6944        // that do not.
6945        for slot in &mut self.primary.screen_channel_groups {
6946            if let Some((_, stale)) = slot.take() {
6947                device.destroy_bind_group(stale);
6948            }
6949        }
6950        if let Some(previous) = self.probe_visibility.replace(uploaded) {
6951            previous.destroy(device);
6952        }
6953        Ok(())
6954    }
6955
6956    /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6957    /// captures the probes the step exposed.
6958    ///
6959    /// The irradiance probes' scrolling: each level moves a whole
6960    /// number of its own probe spacings towards `point`, so the probes that stay
6961    /// inside it stand exactly where they stood and go on being addressed at the
6962    /// rows they already had — and only the slabs the step brought in are
6963    /// captured. Answers how many rows that was, which is **zero for the
6964    /// ordinary frame**: the point has to travel half a probe spacing before the
6965    /// nearest whole step changes at all.
6966    ///
6967    /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6968    /// rule and `exposed` beside it is the invalidation; this is the two of them
6969    /// plus the device work they imply — the visibility maps of the exposed
6970    /// rows, and the position table the reflective-shadow-map gather reads.
6971    ///
6972    /// # A volume authored to cover its whole world does not move
6973    ///
6974    /// The steps are the ones that centre a level on `point`, and a caller whose
6975    /// volume is already the world it is in wants none of them — so a caller
6976    /// passes the point it wants the *centre* at rather than the camera outright
6977    /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6978    /// their own modules say so.
6979    ///
6980    /// # A step stalls, and a frame that does not step costs a comparison
6981    ///
6982    /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6983    /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6984    /// one does — so a step drains the device before it rewrites anything and
6985    /// leaves it drained. That is a stall, and it is why the probe records price a step
6986    /// separately from a frame. A call that steps nothing returns before the
6987    /// wait, so the ordinary frame pays a rounding per level and per axis and
6988    /// nothing else.
6989    ///
6990    /// It may therefore be called from a frame loop, but **not after**
6991    /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6992    /// recorded: the header it moves is the one that frame's uniform block has
6993    /// already been written from.
6994    ///
6995    /// A renderer that has never captured re-centres the header and captures
6996    /// nothing: there is no image to write slabs into, every group still names
6997    /// the placeholder, and the first
6998    /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6999    /// whole.
7000    ///
7001    /// # It moves the geometry and not the light
7002    ///
7003    /// What a step re-captures is the *visibility* of the probes it exposed,
7004    /// which is what the maps are about. The **rows** are not touched, so under
7005    /// [`ProbeUpdate::Authored`] a probe
7006    /// that a step brought in keeps the irradiance the probe that left had —
7007    /// authored for somewhere else. A volume that scrolls therefore wants
7008    /// [`ProbeUpdate::EveryFrame`], whose
7009    /// gather refills every row from the scene each frame and has no such gap;
7010    /// `docs/backlog.md` carries what an authored one would need instead.
7011    ///
7012    /// # Errors
7013    ///
7014    /// [`HalError`] from the recapture or from the position rewrite. The volume
7015    /// keeps the steps it had on either failing path, so a renderer that could
7016    /// not capture a slab does not go on drawing with rows about somewhere else.
7017    pub fn follow_probe_volume(
7018        &mut self,
7019        device: &dyn Device,
7020        queue: QueueHandle,
7021        point: [f32; 3],
7022    ) -> Result<u32, HalError> {
7023        let mut moved = self.probe_volume;
7024        let rows = moved.follow(point);
7025        if rows.is_empty() && moved.steps == self.probe_volume.steps {
7026            return Ok(0);
7027        }
7028        // **Before anything is written**, so a caller may make this call from
7029        // its frame loop: the layers the recapture rewrites and the position
7030        // table beside them are read by whatever frames are still in flight, and
7031        // neither is a ring. A frame that does not step never reaches this line,
7032        // which is what keeps the ordinary frame free of it.
7033        device.wait_idle()?;
7034        if let Some(captured) = &self.probe_visibility {
7035            let placed: Vec<crate::probe_visibility::Occluder> = self
7036                .instances
7037                .live()
7038                .into_iter()
7039                .map(|record| crate::probe_visibility::Occluder {
7040                    mesh: record.mesh,
7041                    transform: Mat4::from_cols_array(&record.transform),
7042                })
7043                .collect();
7044            crate::probe_capture::recapture(
7045                device,
7046                queue,
7047                &moved,
7048                &self.probe_occluders,
7049                &placed,
7050                &rows,
7051                captured.image,
7052            )?;
7053        }
7054        // After the capture, so a volume whose slabs could not be drawn keeps
7055        // the header its maps are about.
7056        if let Some(gather) = &self.probe_gather {
7057            gather.rewrite_positions(device, &moved)?;
7058        }
7059        self.probe_volume = moved;
7060        Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
7061    }
7062
7063    /// Where the irradiance clipmap stands right now — the header the frame
7064    /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
7065    /// included.
7066    #[must_use]
7067    pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
7068        self.probe_volume
7069    }
7070
7071    /// `draws` split by the **whole** material mode, each partition under the
7072    /// depth-only pipeline that honours it — what the depth prepass and every
7073    /// shadow view record instead of one call list under one pipeline.
7074    ///
7075    /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
7076    /// split total: the opaque buckets are drawn with
7077    /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
7078    /// fragment stage — the masked ones with
7079    /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
7080    /// `discard`, and each of those has a [`CullMode::None`] twin for the
7081    /// buckets whose material is double-sided. A scene with one cutout in it
7082    /// pays a fragment stage for that mesh's draws and for no others; before
7083    /// this it paid for the whole frame, which on lavapipe roughly doubled the
7084    /// prepass and added two thirds to the shadow pass.
7085    ///
7086    /// **Both depth passes and not just the atlas.** A double-sided plate whose
7087    /// back face the prepass culled writes no depth there, so the colour pass's
7088    /// `GreaterOrEqual` test against it rejects the fragment and the surface is
7089    /// missing from the frame; and a cascade that culled it casts no shadow.
7090    fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
7091        self.partitions(
7092            draws,
7093            mesh::GpuMaterial::MODE_MASK,
7094            &[
7095                (DEPTH_MODES[0], Some(self.shadow_pipeline.single)),
7096                (
7097                    DEPTH_MODES[1],
7098                    self.depth_masked_pipeline.map(|masked| masked.single),
7099                ),
7100                (DEPTH_MODES[2], self.shadow_pipeline.double),
7101                (
7102                    DEPTH_MODES[3],
7103                    self.depth_masked_pipeline.and_then(|masked| masked.double),
7104                ),
7105            ],
7106        )
7107    }
7108
7109    /// `draws` split by the material's **side** alone, each partition under the
7110    /// matching half of `pipelines` — what the colour pass and the two
7111    /// reflective shadow maps record.
7112    ///
7113    /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
7114    /// four, and the difference is the whole of what these passes do not care
7115    /// about: their pipelines carry a fragment stage either way and cut the
7116    /// alpha mask inside it, so a masked bucket and an opaque one are the same
7117    /// draw here. What they cannot express inside the stage is the cull mode.
7118    fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
7119        self.partitions(draws, mesh::GpuMaterial::DOUBLE_SIDED, &pipelines.by_side())
7120    }
7121
7122    /// Resolves a description's mesh and material indices into the table ids the
7123    /// GPU reads.
7124    ///
7125    /// The whole record every time, because [`InstancePool::set`] writes the
7126    /// whole record: an instance that lost either id would name entry 0 of that
7127    /// table, which is a mesh and a material rather than an absence.
7128    fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
7129        mesh::GpuInstance {
7130            transform: desc.transform.to_cols_array(),
7131            mesh: self.mesh_ids[desc.mesh],
7132            material: self.material_ids[desc.material],
7133            flags: self.material_mode_bits(desc.material),
7134            ..mesh::GpuInstance::default()
7135        }
7136    }
7137
7138    /// The material mode of description material `material`, in the bits an
7139    /// instance record carries it in.
7140    ///
7141    /// **Read out of the table rather than out of the description**, because the
7142    /// table is what a `set` would move and the row is what the shader shades
7143    /// through. It is the other half of the record's routing key: `draw_gen`
7144    /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
7145    /// which is how a masked material costs a fragment stage in the depth passes
7146    /// for its own mesh alone.
7147    ///
7148    /// The mode is captured **here**, when the record is written — see
7149    /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
7150    /// for what that means for a material rewritten afterwards.
7151    fn material_mode_bits(&self, material: usize) -> u32 {
7152        self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
7153    }
7154
7155    // --- skinning: reserving the region, placing the object, ordering the
7156    // dispatch ---
7157
7158    /// The vertex pool every mesh here is resident in — what
7159    /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
7160    /// takes.
7161    ///
7162    /// The skinning pass reads a bind pose out of this buffer and writes the
7163    /// deformed vertices back into another run of it, which is what makes a
7164    /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
7165    /// [`Skinning`] built against any other writes vertices no draw here can
7166    /// reach.
7167    #[must_use]
7168    pub const fn vertex_buffer(&self) -> BufferHandle {
7169        self.pool.vertex_buffer()
7170    }
7171
7172    /// Where that pool's **attribute** region begins, in words — what
7173    /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
7174    /// takes.
7175    ///
7176    /// The buffer holds two streams, so a pass that writes it needs the
7177    /// boundary as well as the handle; a [`Skinning`] built with the wrong one
7178    /// writes a mesh's attributes over another mesh's positions. See
7179    /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
7180    #[must_use]
7181    pub const fn attribute_base(&self) -> u32 {
7182        self.pool.attribute_base()
7183    }
7184
7185    /// Reserves a skinned region for description mesh `mesh`.
7186    ///
7187    /// The whole of what a caller needs to skin something, in one value: hand
7188    /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
7189    /// frame's [`SkinRange`], hand the result to
7190    /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
7191    /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
7192    /// parity never have to be spelled by the caller at all — see
7193    /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
7194    ///
7195    /// **The mesh keeps its own entry and the region takes none**, so the same
7196    /// description mesh can be drawn skinned through this and in its bind pose
7197    /// through [`add_instance`](Self::add_instance) in the same frame, both
7198    /// resolving through the one table entry it already had.
7199    ///
7200    /// Give it back with [`release_skinned`](Self::release_skinned).
7201    ///
7202    /// # Errors
7203    ///
7204    /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
7205    /// both halves. **Two vertex runs per skinned primitive** is what a scene's
7206    /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
7207    ///
7208    /// # Panics
7209    ///
7210    /// If `mesh` is past the end of the description this renderer was built
7211    /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
7212    /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
7213    /// A DAG is refused rather than skinned wrongly: its coarser levels are
7214    /// separate vertex runs no dispatch writes, so a cut that descended past
7215    /// level 0 would draw whatever the pool happened to be holding there.
7216    pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
7217        let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
7218            panic!(
7219                "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
7220                 runs no skinning dispatch writes; only a flat mesh can be skinned"
7221            )
7222        });
7223        SkinnedMesh::reserve(&mut self.pool, source)
7224    }
7225
7226    /// Gives `skinned`'s region back to the vertex pool.
7227    ///
7228    /// The device must not still be drawing it: this records no barrier, on
7229    /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
7230    /// removed — [`remove_instance`](Self::remove_instance) is what does that,
7231    /// and an instance left behind goes on drawing its source mesh's geometry
7232    /// out of vertices the pool has handed back. Remove the objects first.
7233    pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
7234        skinned.release(&mut self.pool);
7235    }
7236
7237    /// Places a skinned object in the scene.
7238    ///
7239    /// [`add_instance`](Self::add_instance) with a reserved region in place of a
7240    /// description mesh. The renderer keeps the object in a list of its own and
7241    /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
7242    /// at the half of the region that frame's dispatch fills, so the parity is
7243    /// never something a caller writes.
7244    ///
7245    /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
7246    /// therefore left pointing wherever it last was, which after the first frame
7247    /// is the pose of the frame before — the reason the two entry points are
7248    /// separate calls rather than a flag.
7249    ///
7250    /// # Errors
7251    ///
7252    /// [`InstancePoolError::PoolFull`], on
7253    /// [`add_instance`](Self::add_instance)'s terms, and
7254    /// [`InstancePoolError::InvalidBounds`] for a
7255    /// [`SkinnedInstanceDesc::bounds`] the culls could not read, before
7256    /// anything is written.
7257    ///
7258    /// # Panics
7259    ///
7260    /// If [`SkinnedInstanceDesc::material`] is past the end of the description
7261    /// this renderer was built from, on
7262    /// [`add_instance`](Self::add_instance)'s terms.
7263    pub fn add_skinned_instance(
7264        &mut self,
7265        desc: &SkinnedInstanceDesc<'_>,
7266    ) -> Result<InstanceHandle, InstancePoolError> {
7267        let bounds = bounds_fields(desc.bounds)?;
7268        // Parity zero, and it never reaches the GPU as such: the instance pool
7269        // uploads by delta at `begin_skinned_frame`, which re-points every entry
7270        // of the list below before it flushes. What this writes is the rest of
7271        // the record.
7272        let instance = self.skinned_gpu_instance(desc, bounds, 0);
7273        let handle = self.instances.insert(&instance)?;
7274        self.skinned_instances.push(SkinnedInstance {
7275            handle,
7276            bases: skinned_bases(desc.mesh),
7277            pointed: false,
7278        });
7279        Ok(handle)
7280    }
7281
7282    /// Rewrites the skinned object `handle` names — its region, its material and
7283    /// its transform.
7284    ///
7285    /// [`set_instance`](Self::set_instance) for an object placed by
7286    /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
7287    /// character's transform changes through. A stale handle writes nothing.
7288    ///
7289    /// Passing a handle this renderer has never seen skinned adopts it: the
7290    /// object joins the re-pointed list from here on. That is what lets a caller
7291    /// swap a bind-pose instance over to a region without removing and replacing
7292    /// it.
7293    ///
7294    /// **The description's box replaces whatever box the object had**,
7295    /// including one [`set_skinned_bounds`](Self::set_skinned_bounds) wrote: the
7296    /// record is rebuilt from `desc`, and [`SkinnedInstanceDesc::bounds`] is
7297    /// part of it, so a `None` here takes the object's box away. A caller that
7298    /// both places an object and moves its box — a ragdoll — passes the box in
7299    /// this description, or calls `set_skinned_bounds` after this call.
7300    ///
7301    /// # Panics
7302    ///
7303    /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms, and on
7304    /// a [`SkinnedInstanceDesc::bounds`] that call would refuse with
7305    /// [`InstancePoolError::InvalidBounds`]: this call has no `Result`, so a
7306    /// description it cannot use is a panic naming it, as an out-of-range
7307    /// material is. A box that changes every frame belongs in
7308    /// [`set_skinned_bounds`](Self::set_skinned_bounds), which returns the
7309    /// refusal instead.
7310    pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
7311        let bounds = bounds_fields_or_panic(desc.bounds);
7312        let mut instance = self.skinned_gpu_instance(desc, bounds, 0);
7313        instance.flags |= self.kept_flags(handle);
7314        if !self.instances.set(handle, &instance) {
7315            return;
7316        }
7317        let bases = skinned_bases(desc.mesh);
7318        match self
7319            .skinned_instances
7320            .iter_mut()
7321            .find(|entry| entry.handle == handle)
7322        {
7323            // **A different region is a fresh entry.** The half this object has
7324            // never been drawn out of holds whatever its reservation came with,
7325            // so the next pointing owes it rest rather than a previous
7326            // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
7327            // is what "different" means here: two calls naming one region give
7328            // the same two runs, so rewriting an object's material or transform
7329            // is not a change of region.
7330            Some(entry) => {
7331                entry.pointed &= entry.bases == bases;
7332                entry.bases = bases;
7333            }
7334            None => self.skinned_instances.push(SkinnedInstance {
7335                handle,
7336                bases,
7337                pointed: false,
7338            }),
7339        }
7340    }
7341
7342    /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
7343    /// with the region's base vertex carried in the record and the bit that says
7344    /// to read it.
7345    ///
7346    /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
7347    /// this instance is scattered into, the levels it selects through and the
7348    /// box it is culled against are the ones the undeformed mesh already had.
7349    ///
7350    /// `bounds` is [`bounds_fields`]' answer for `desc.bounds`, which the caller
7351    /// has already checked.
7352    fn skinned_gpu_instance(
7353        &self,
7354        desc: &SkinnedInstanceDesc<'_>,
7355        (bounds_flag, bounds_min, bounds_max): (u32, [f32; 3], [f32; 3]),
7356        parity: u32,
7357    ) -> mesh::GpuInstance {
7358        let base_vertex = desc.mesh.region().base(parity);
7359        mesh::GpuInstance {
7360            transform: desc.transform.to_cols_array(),
7361            mesh: desc.mesh.mesh_id(),
7362            material: self.material_ids[desc.material],
7363            // The override bit **and** the material mode: a skinned instance is
7364            // routed by the same key as a rigid one, so a skinned cutout lands
7365            // in its mesh's masked bucket rather than in the opaque twin.
7366            flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE
7367                | self.material_mode_bits(desc.material)
7368                | bounds_flag,
7369            base_vertex,
7370            // At rest, which is what a record this call writes has to be: the
7371            // object has not been drawn out of this region yet, so the other
7372            // half holds whatever its reservation came with. A frame that runs
7373            // [`point_skinned_instances`](Self::point_skinned_instances) is
7374            // what starts pointing this at the half before.
7375            previous_base_vertex: base_vertex,
7376            bounds_min,
7377            bounds_max,
7378            ..mesh::GpuInstance::default()
7379        }
7380    }
7381
7382    /// Replaces the model-space box the skinned object `handle` names is culled
7383    /// by, and **nothing else** — see [`SkinnedInstanceDesc::bounds`], whose
7384    /// terms this writes on. `None` puts it back in every cull.
7385    ///
7386    /// The call a pose that travels makes once a frame: a ragdoll's bodies
7387    /// drift metres from the object's origin while its transform stays where it
7388    /// fell, and [`set_skinned_instance`](Self::set_skinned_instance) would
7389    /// rewrite the whole record as a move to change the box. This is not a
7390    /// move, on [`set_instance_views`](Self::set_instance_views)' terms: the
7391    /// transform history is left alone, so the motion target sees no travel the
7392    /// object did not make. It is still a write
7393    /// [`InstancePool::take_written`] names, so a shadow map the box reached
7394    /// before or after it is redrawn.
7395    ///
7396    /// Takes effect at the next [`begin_frame`](Self::begin_frame) or
7397    /// [`begin_skinned_frame`](Self::begin_skinned_frame), which uploads the
7398    /// element. A stale handle writes nothing and is not an error. On a rigid
7399    /// instance the box replaces its mesh's until the next
7400    /// [`set_instance`](Self::set_instance) rewrites the record.
7401    ///
7402    /// **A later [`set_skinned_instance`](Self::set_skinned_instance) replaces
7403    /// this box with its description's**, `None` included — the description
7404    /// is authoritative. Call this after placing the object, or pass the box in
7405    /// the description.
7406    ///
7407    /// # Errors
7408    ///
7409    /// [`InstancePoolError::InvalidBounds`] for a box with a non-finite corner
7410    /// or with `min` past `max` on any axis, and the record is left as it was.
7411    /// **An error rather than a panic**, unlike
7412    /// [`set_skinned_instance`](Self::set_skinned_instance)'s: this is the
7413    /// per-frame path a simulated pose's box takes, and a body that goes `NaN`
7414    /// for a frame is a condition a game can be in, not a mistake in its code.
7415    pub fn set_skinned_bounds(
7416        &mut self,
7417        handle: InstanceHandle,
7418        bounds: Option<Aabb>,
7419    ) -> Result<(), InstancePoolError> {
7420        let (flag, min, max) = bounds_fields(bounds)?;
7421        self.instances.set_bounds(handle, flag, min, max);
7422        Ok(())
7423    }
7424
7425    /// Points every skinned object at the half of its region a frame of this
7426    /// parity fills **and at the half the frame before it filled**, and forgets
7427    /// the ones whose instance has gone.
7428    ///
7429    /// Called between the instance ring's rotation and its upload, which is the
7430    /// whole reason those two are separate calls — see
7431    /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7432    ///
7433    /// The second base is what a skinned fragment's motion vector is subtracted
7434    /// against — see
7435    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7436    /// **A region this frame's `ranges` left out was not skinned this frame**,
7437    /// so the half this points at as the current one already holds an earlier
7438    /// frame's pose. That is pre-existing — it is what a caller driving a
7439    /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7440    /// it predates this second base — and the previous half is then no worse off
7441    /// than the current one.
7442    ///
7443    /// # What the shadow cache reads from it
7444    ///
7445    /// **Every re-point is an instance write**, whether or not the entry's
7446    /// region was in this frame's `ranges`: the parity alternates on every
7447    /// skinned frame, so each entry draws out of the other half from the frame
7448    /// before, and a region left out of the plan holds an older pose there.
7449    /// [`InstancePool::take_written`] names each element, and
7450    /// [`note_caster_writes`](Self::note_caster_writes) turns it into a
7451    /// footprint, so a skinned caster's frame redraws every shadow group its box
7452    /// reaches before or after it — and every group when it has no box, whose
7453    /// footprint is [`shadow_inputs::CasterFootprint::Everywhere`]. **A
7454    /// conservative superset**, not the exact set: the footprint carries slack,
7455    /// a point light is tested against its whole-light box rather than per face,
7456    /// and the cadence can defer a group it marks to a later frame. That
7457    /// write is the whole of what keeps a held map from showing a pose the
7458    /// object has left, so a re-point that skipped an unchanged entry would
7459    /// have to be a shadow-cache decision too.
7460    fn point_skinned_instances(&mut self, parity: u32) {
7461        let Self {
7462            instances,
7463            skinned_instances,
7464            ..
7465        } = self;
7466        skinned_instances.retain_mut(|entry| {
7467            // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7468            // applied to the entry's own copy of the pair — see
7469            // [`SkinnedInstance::bases`].
7470            let base_vertex = entry.bases[(parity & 1) as usize];
7471            let previous_base_vertex = if entry.pointed {
7472                entry.bases[((parity ^ 1) & 1) as usize]
7473            } else {
7474                // Nothing has been written into the other half for this object,
7475                // so it is put at rest — see [`SkinnedInstance::pointed`].
7476                base_vertex
7477            };
7478            entry.pointed = true;
7479            // The two bases and nothing else: the transform, the material and
7480            // the mesh the caller last set survive, and so does the transform
7481            // the record moved *from* — which
7482            // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7483            // would overwrite with this frame's, leaving a skinned object's own
7484            // travel out of the motion target. See
7485            // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7486            // Its answer is also what says the instance is still there, so an
7487            // object a caller removed drops out of the list here.
7488            instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7489        });
7490    }
7491
7492    /// The lights in the frame **beside the sun**, which
7493    /// [`begin_frame`](Self::begin_frame) still takes on its own.
7494    ///
7495    /// Topic 44's light list, minus its first row: the
7496    /// sun is row 0 of every frame's list and the ones set here follow it, in
7497    /// the order given. That order is the one a froxel keeps a prefix of when it
7498    /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7499    /// overflow counter beside it — so it is a caller's lever and not an
7500    /// accident.
7501    ///
7502    /// The sun keeps a parameter of its own because it is the light that owns
7503    /// the ambient term and the shadow cascades, neither of which a [`Light`]
7504    /// has. What it stopped being is a special case in the *shader*, which is
7505    /// what the list bought.
7506    ///
7507    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7508    /// what uploads the rows.
7509    ///
7510    /// # Panics
7511    ///
7512    /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7513    /// room for once the sun has its row. Refused rather than truncated: a light
7514    /// missing from the list is missing from every froxel, and **no counter in
7515    /// the frame would report it** — the overflow counter counts what a froxel's
7516    /// budget refused, which is a different number.
7517    pub fn set_lights(&mut self, lights: &[Light]) {
7518        assert!(
7519            lights.len() < self.primary.lights.capacity() as usize,
7520            "{} lights beside the sun, in a list of {}",
7521            lights.len(),
7522            self.primary.lights.capacity()
7523        );
7524        self.extra_lights.clear();
7525        self.extra_lights.extend_from_slice(lights);
7526    }
7527
7528    /// Rows the light list holds, the sun's included.
7529    #[must_use]
7530    pub const fn light_capacity(&self) -> u32 {
7531        self.primary.lights.capacity()
7532    }
7533
7534    /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7535    /// from the viewport and the camera.
7536    ///
7537    /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7538    /// wants to know which froxel a point was shaded out of has to use the grid
7539    /// the frame really used, and re-deriving it would be a second copy of the
7540    /// arithmetic rather than a reading of the first.
7541    #[must_use]
7542    pub const fn grid(&self) -> Grid {
7543        self.primary.grid
7544    }
7545
7546    /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7547    /// pass decided.
7548    ///
7549    /// # Panics
7550    ///
7551    /// If `frame` is not a slot this was built with.
7552    #[must_use]
7553    pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7554        self.primary.lights.grid(frame)
7555    }
7556
7557    /// The pixel budget the descent compares a group's projected error against.
7558    ///
7559    /// One pixel until this is called — see the constant this crate keeps it
7560    /// in. Larger is coarser: a group
7561    /// projecting *over* the budget is expanded and its children are drawn, so
7562    /// raising it stops the descent higher up the DAG.
7563    ///
7564    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7565    /// what writes it into the frame block.
7566    pub const fn set_lod_error_budget(&mut self, budget: f32) {
7567        self.lod_error_budget = budget;
7568    }
7569
7570    /// The budget this renderer selects under unless
7571    /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7572    /// the ratio the hold budget sits at below whichever one is in force.
7573    ///
7574    /// Public because a test that drives a camera across a level boundary has to
7575    /// know where the boundary is, and where it is depends on both numbers —
7576    /// re-deriving either in the test would be a second copy to drift.
7577    pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7578    /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7579    pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7580
7581    /// How far below the budget an already-expanded group is held before it
7582    /// collapses again — topic 25's hysteresis, as a fraction of
7583    /// the budget.
7584    ///
7585    /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7586    /// of one removes the band**, which makes the two budgets equal and the
7587    /// previous frame's answer stop mattering — the setting a test uses to show
7588    /// that the band is what stops a drifting camera flickering, on the same
7589    /// code path and one number apart.
7590    ///
7591    /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7592    /// what writes it into the two params blocks.
7593    pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7594        self.lod_hold_ratio = ratio;
7595    }
7596
7597    /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7598    /// pixels per unit at one unit from the eye, and the pixel budget.
7599    ///
7600    /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7601    /// starts expanding over, and the budget an expanded one is held down to.
7602    ///
7603    /// What `ClusterDag::expand` takes, so a caller reading
7604    /// [`cluster_selection`](Self::cluster_selection) back can run the same
7605    /// frames host-side rather than re-deriving the numbers from the camera and
7606    /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7607    #[must_use]
7608    pub const fn lod_params(&self) -> [f32; 3] {
7609        self.primary.lod_params
7610    }
7611
7612    /// The same three numbers the **shadow cascades** selected under, which is
7613    /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7614    /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7615    /// parameters it actually reaches the GPU as.
7616    ///
7617    /// The pixels-per-unit is the camera's, unchanged, because the cascades
7618    /// select from the camera's eye at the camera's scale; see
7619    /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7620    /// frame.
7621    #[must_use]
7622    pub const fn shadow_lod_params(&self) -> [f32; 3] {
7623        self.shadow_lod_params
7624    }
7625
7626    /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7627    /// level of it, as one run — or `None` off the mesh path, where there is no
7628    /// cluster pool at all.
7629    ///
7630    /// The base a reader adds a `(level, cluster)` to in order to index
7631    /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7632    /// finest first and contiguously, so level `d` cluster `c` is at
7633    /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7634    /// its run is its clusters and `c` indexes it directly.
7635    ///
7636    /// # Panics
7637    ///
7638    /// If `mesh` is past the end of the description this renderer was built
7639    /// from, on [`add_instance`](Self::add_instance)'s terms.
7640    #[must_use]
7641    pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7642        (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7643    }
7644
7645    /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7646    /// one `u32` per resident cluster, `1` where the cluster was drawn.
7647    ///
7648    /// `None` where there is no amplification stage, which is every device that
7649    /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7650    ///
7651    /// **This is topic 25's observable and nothing in the frame
7652    /// reads it.** A frame whose every cluster came from one level is a
7653    /// plausible picture and matches any golden blessed from it, so a golden
7654    /// cannot show per-cluster selection happening at all; this can. It is
7655    /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7656    ///
7657    /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7658    #[must_use]
7659    pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7660        self.primary.cluster_selection.get(frame).copied()
7661    }
7662
7663    /// The same, for `cascade`'s shadow pass: the cut that cascade's
7664    /// amplification stage chose this frame.
7665    ///
7666    /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7667    /// passed* is a parameter; the cut they reached under it is the behaviour,
7668    /// and this is the only thing that carries it out of a frame — the colour
7669    /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7670    /// cascades have run. Indexed and read exactly as that buffer is, through
7671    /// [`cluster_range`](Self::cluster_range).
7672    ///
7673    /// `None` where there is no amplification stage, and where `cascade` is not
7674    /// one of [`shadow::CASCADES`].
7675    #[must_use]
7676    pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7677        self.shadow_selection
7678            .get(frame)
7679            .and_then(|cascades| cascades.get(cascade))
7680            .copied()
7681    }
7682
7683    /// The buckets description mesh `mesh`'s levels draw through, finest first —
7684    /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7685    ///
7686    /// **This is the uniform cut's observable**, and it is the indirect
7687    /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7688    /// instance into the bucket for the level it selected, so exactly one of
7689    /// these buckets comes out of a frame with a non-zero instance count and
7690    /// which one it is *is* the chosen level. A reader takes
7691    /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7692    /// and looks at
7693    /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7694    ///
7695    /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7696    /// level is chosen per cluster instead — see
7697    /// [`cluster_selection`](Self::cluster_selection), which is that path's
7698    /// observable.
7699    ///
7700    /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7701    /// in any scene that has an opaque material, since the table is every
7702    /// mesh's levels once per mode the scene holds, mode by mode in
7703    /// `DEPTH_MODES` order. An instance of another mode selects the same level
7704    /// and lands in that level's bucket in its own mode's run, which this does
7705    /// not name; every scene in this tree that reads this accessor is all
7706    /// opaque, so "exactly one of these has a non-zero instance count" holds for
7707    /// them as it always did.
7708    ///
7709    /// # Panics
7710    ///
7711    /// If `mesh` is past the end of the description this renderer was built
7712    /// from, on [`add_instance`](Self::add_instance)'s terms.
7713    #[must_use]
7714    pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7715        if self.mesh_level_buckets.is_empty() {
7716            return &[];
7717        }
7718        &self.mesh_level_buckets[mesh]
7719    }
7720
7721    /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7722    /// bytes per bucket — what a reader of
7723    /// [`level_buckets`](Self::level_buckets) copies out.
7724    ///
7725    /// # Panics
7726    ///
7727    /// If `frame` is not a slot this renderer was built with.
7728    #[must_use]
7729    pub fn draw_args(&self, frame: usize) -> BufferHandle {
7730        self.primary.draws.args(frame)
7731    }
7732
7733    /// `frame`'s survivor list for the primary camera and the culling
7734    /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7735    /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7736    /// the first buffer, and their count in word
7737    /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7738    /// of the second — for a test holding the GPU's occlusion verdicts against
7739    /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7740    /// behind the list; see [`crate::draw_gen`].
7741    ///
7742    /// # Panics
7743    ///
7744    /// If `frame` is not a slot this renderer was built with.
7745    #[must_use]
7746    pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7747        (
7748            self.primary.draws.visible(frame),
7749            self.primary.draws.visible_count(frame),
7750        )
7751    }
7752
7753    /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7754    /// takes it: every instance slot the pool has handed out, and the whole mesh
7755    /// table — both decoded from the host's own copies of what was uploaded.
7756    #[must_use]
7757    pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7758        (self.instances.records(), self.pool.table_entries())
7759    }
7760
7761    /// The generator behind shadow cull `cull` — a cascade's below
7762    /// [`shadow::CASCADES`], a light slot's after —
7763    /// for a test reading back what a point light's face culls kept.
7764    ///
7765    /// # Panics
7766    ///
7767    /// If `cull` is not one of the renderer's shadow culls.
7768    #[must_use]
7769    pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7770        &self.shadow_draws[cull]
7771    }
7772
7773    /// The primary camera's farthest-depth pyramid — every level's image, view
7774    /// and extent, level 1 first — or empty before a frame culled by occlusion.
7775    ///
7776    /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7777    /// exactly that, and they hold the last frame's early depth once that frame
7778    /// has finished.
7779    #[must_use]
7780    pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7781        self.primary.occlusion_pyramid.level_images()
7782    }
7783
7784    /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7785    ///
7786    /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7787    /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7788    /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7789    /// are not all filled runs fewer culls, which is what makes a free tile
7790    /// free.
7791    ///
7792    /// Derived rather than written down, because a number written down is one
7793    /// that stops matching the frame the day a pass is added — which is exactly
7794    /// how the samples' hand-picked `8` came to time the first eight passes of a
7795    /// fourteen-pass frame. A caller sizing
7796    /// [`PassTimers`](crate::timing::PassTimers) wants
7797    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7798    /// what the overlay renderers record.
7799    pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7800        + DrawGen::LATE_PASSES
7801        + LightGrid::MAX_PASSES
7802        + RENDER_PASSES;
7803
7804    /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7805    /// and returns the HDR scene target they went through.
7806    ///
7807    /// `target` is normally the imported swapchain image. Everything else — the
7808    /// HDR scene colour, the depth buffer, and every barrier between them — is
7809    /// the graph's.
7810    ///
7811    /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7812    /// the scene colour **with the screen-space reflections already added**, not
7813    /// the target the forward pass wrote. A caller that wants to add a pass of
7814    /// its own after the tonemap — a debug overlay, or a readback proving the
7815    /// HDR range is real — declares a read of it and the graph works out the
7816    /// transition, exactly as it does for the tonemap.
7817    ///
7818    /// The two are the same description and different images, which is the
7819    /// design's off-switch as data rather than as a branch: a frame with
7820    /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7821    /// pass's own id, and is bit-identical.
7822    ///
7823    /// # Which passes this adds is [`effects`](Self::effects)
7824    ///
7825    /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7826    /// and read here — see [`crate::effects`] for the four layers and for what
7827    /// each toggle removes. Every effect is on by default, which is the frame
7828    /// every caller drew before the toggles existed.
7829    ///
7830    /// A switched-off effect is **fewer passes and one different bound
7831    /// descriptor**, never a shader permutation: the shadow atlas keeps its
7832    /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7833    /// to the renderer's white 1×1, and the reflection pair simply is not there.
7834    ///
7835    /// # The ground grid comes last, and after the tonemap
7836    ///
7837    /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7838    /// and it is off by default. When it is on, its pass is added **after** the
7839    /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7840    /// against the scene depth: the grid is reference chrome, and a grid drawn
7841    /// before the tonemap would be exposed and tonemapped like geometry, so its
7842    /// colour would move with how bright the scene is. See [`crate::grid`].
7843    ///
7844    /// # `pool` is where the shadow atlas's incoming state comes from
7845    ///
7846    /// It must be the same pool the caller is about to
7847    /// [`compile`](RenderGraph::compile) and
7848    /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7849    /// its placeholder are imports this renderer owns across frames and the
7850    /// pool's ledger is the record of what the last executed graph left them in
7851    /// — [`TransientPool::imported_image_use`], with [`None`] read as
7852    /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7853    /// field of our own is what keeps the declaration and the audit
7854    /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7855    /// whose `compile` fails is a frame that never ran, and a field advanced at
7856    /// build time would already have moved on without it.
7857    ///
7858    /// # Panics
7859    ///
7860    /// If `extent` is not the extent the [`begin_frame`](Self::begin_frame)
7861    /// that opened this frame was handed: the frame's internal extent, its
7862    /// blocks and the passes it builds were all decided there.
7863    pub fn add_passes<'a>(
7864        &'a mut self,
7865        graph: &mut RenderGraph<'a>,
7866        pool: &TransientPool,
7867        target: ImageId,
7868        extent: (u32, u32),
7869    ) -> ImageId {
7870        self.add_frame_passes(
7871            graph,
7872            pool,
7873            FrameTargets::primary(target, extent, None),
7874            |_, _| {},
7875        )
7876    }
7877
7878    /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7879    /// frame with `skinning`'s dispatch in front of every pass that draws.
7880    ///
7881    /// # This takes the pass rather than its [`BufferId`], and that is the point
7882    ///
7883    /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7884    /// mesh pass can declare a read of it and be ordered after the dispatch. The
7885    /// obvious seam is therefore an id parameter here — and it is the wrong one,
7886    /// because every way of getting it wrong is silent. A caller can pass the id
7887    /// of a *different* import, add the skinning pass after this one, or not add
7888    /// it at all, and in each case the graph orders nothing, the draws read the
7889    /// region before the compute write has been made visible, and what comes out
7890    /// is a mesh that flickers between two poses on hardware and looks perfect
7891    /// under a validation layer.
7892    ///
7893    /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7894    /// this renderer's own frame slot, and declares the read on the three passes
7895    /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7896    /// and the forward pass. There is no order for a caller to get right,
7897    /// because there is only one call.
7898    ///
7899    /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7900    /// handed no ranges adds no dispatch and no declarations, and is the frame
7901    /// [`add_passes`](Self::add_passes) would have built. So is one whose every
7902    /// range was dropped because nothing the frame draws can read it — see
7903    /// [`set_skinning_culls`](Self::set_skinning_culls).
7904    ///
7905    /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7906    ///
7907    /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7908    /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7909    /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7910    /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7911    ///
7912    /// # Panics
7913    ///
7914    /// If `extent` is not the extent the [`begin_skinned_frame`](Self::begin_skinned_frame)
7915    /// that opened this frame was handed: the frame's internal extent, its
7916    /// blocks and the passes it builds were all decided there.
7917    pub fn add_skinned_passes<'a>(
7918        &'a mut self,
7919        graph: &mut RenderGraph<'a>,
7920        pool: &TransientPool,
7921        target: ImageId,
7922        extent: (u32, u32),
7923        skinning: &Skinning,
7924    ) -> ImageId {
7925        self.add_frame_passes(
7926            graph,
7927            pool,
7928            FrameTargets::primary(target, extent, Some(skinning)),
7929            |_, _| {},
7930        )
7931    }
7932
7933    /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7934    /// overlay inserted after the display-space frame is complete and before
7935    /// antialiasing or render-scale reconstruction.
7936    ///
7937    /// The callback receives the display target and its matching scene depth
7938    /// attachment at the internal render extent. It may add graph passes that
7939    /// sample `display` and attach `depth` read-only; it must leave both images
7940    /// in states its declarations name. The forward renderer continues with its
7941    /// existing resolve and upscale passes after the callback returns.
7942    ///
7943    /// # Panics
7944    ///
7945    /// On [`add_skinned_passes`](Self::add_skinned_passes)' terms.
7946    pub fn add_skinned_passes_with_overlay<'a, F>(
7947        &'a mut self,
7948        graph: &mut RenderGraph<'a>,
7949        pool: &TransientPool,
7950        target: ImageId,
7951        extent: (u32, u32),
7952        skinning: &Skinning,
7953        overlay: F,
7954    ) -> ImageId
7955    where
7956        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7957    {
7958        self.add_frame_passes(
7959            graph,
7960            pool,
7961            FrameTargets::primary(target, extent, Some(skinning)),
7962            overlay,
7963        )
7964    }
7965
7966    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7967    /// for a frame that also draws secondary views — see
7968    /// [`create_view`](Self::create_view).
7969    ///
7970    /// **The scene's passes are recorded once**: one skinning dispatch (where
7971    /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7972    /// in `views` records its own cull, clustering and frame into its own
7973    /// target, and the primary camera's frame into `target` comes last — so
7974    /// `overlay` may read a view's target, which is already drawn by then.
7975    ///
7976    /// Every view named must have been begun this frame by
7977    /// [`begin_view`](Self::begin_view).
7978    ///
7979    /// # Panics
7980    ///
7981    /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7982    /// a view this renderer did not build, a view not begun this frame, or a
7983    /// view twice — or if [`FrameTargets`]' extent is not the one the frame's
7984    /// [`begin_frame`](Self::begin_frame) was handed, or a view's is not the
7985    /// one its [`begin_view`](Self::begin_view) was.
7986    pub fn add_passes_with_views<'a, F>(
7987        &'a mut self,
7988        graph: &mut RenderGraph<'a>,
7989        pool: &TransientPool,
7990        frame: FrameTargets<'_>,
7991        overlay: F,
7992    ) -> ImageId
7993    where
7994        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7995    {
7996        self.add_frame_passes(graph, pool, frame, overlay)
7997    }
7998
7999    /// The body of every `add_*passes` entry point, which differ in their
8000    /// arguments and in nothing else.
8001    fn add_frame_passes<'a, F>(
8002        &'a mut self,
8003        graph: &mut RenderGraph<'a>,
8004        pool: &TransientPool,
8005        frame: FrameTargets<'_>,
8006        overlay: F,
8007    ) -> ImageId
8008    where
8009        F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
8010    {
8011        let FrameTargets {
8012            target,
8013            extent,
8014            skinning,
8015            views,
8016        } = frame;
8017        // **From here down `extent` is the extent the frame is *drawn* at**,
8018        // which is the caller's at a render scale of `1.0` and smaller below it.
8019        // Every use of it in this function sizes a transient, and every one of
8020        // those transients belongs to the internal frame; `target` is the only
8021        // thing here at the caller's extent, and it is an id whose image already
8022        // knows how big it is. `begin_frame_body` shadows it the same way and
8023        // for the same reason, so the two halves of a frame cannot disagree.
8024        //
8025        // `upscaling` is derived from the two extents rather than from the scale
8026        // itself, which is what makes it exact: a target small enough that the
8027        // scaled extent rounds back onto it adds no pass, because there would be
8028        // nothing for the pass to do.
8029        //
8030        // **Both are the ones `begin_frame` froze** — see
8031        // [`View::frame_extent`]. A render scale moved since then is the next
8032        // frame's, on [`Self::set_render_scale`]'s word, and a target of
8033        // another size is refused rather than drawn out of blocks and passes
8034        // decided for this one.
8035        assert_eq!(
8036            extent, self.primary.frame_target_extent,
8037            "`add_passes` was handed a target of {extent:?}, and the `begin_frame` that \
8038             opened this frame one of {:?}: hand both the same extent",
8039            self.primary.frame_target_extent
8040        );
8041        let target_extent = extent;
8042        let extent = self.primary.frame_extent;
8043        let upscaling = extent != target_extent;
8044        let frame = self.frame;
8045        let instance_count = self.instances.slot_count();
8046        let emit = self.emit;
8047
8048        // Every secondary view the caller asked for, checked before anything of
8049        // theirs is recorded: a view that does not exist, or one nothing began
8050        // this frame, would draw out of blocks written for some other frame.
8051        let secondary: Vec<(ViewTarget, (u32, u32))> = views
8052            .iter()
8053            .map(|view| {
8054                assert!(
8055                    view.view != ViewId::PRIMARY,
8056                    "the primary camera draws into the target `add_passes_with_views` takes, \
8057                     not into a `ViewTarget`"
8058                );
8059                let built = self
8060                    .views
8061                    .get(view.view.index() - 1)
8062                    .and_then(Option::as_ref)
8063                    .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
8064                assert_eq!(
8065                    built.begun, self.frame_serial,
8066                    "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
8067                    view.view
8068                );
8069                assert!(
8070                    views.iter().filter(|other| other.view == view.view).count() == 1,
8071                    "{:?} was named twice in one frame",
8072                    view.view
8073                );
8074                assert_eq!(
8075                    view.extent, built.frame_target_extent,
8076                    "{:?} was handed a target of {:?} here and one of {:?} by `begin_view`: \
8077                     hand both the same extent",
8078                    view.view, view.extent, built.frame_target_extent
8079                );
8080                (*view, built.frame_extent)
8081            })
8082            .collect();
8083
8084        // **The skinning dispatch, before anything else is added.** It imports
8085        // the vertex pool and hands back that node's id; every pass below that
8086        // pulls vertices declares a read of it, and the graph is what turns the
8087        // two declarations into the barrier between the compute write and the
8088        // draws. `None` is a frame with nothing to skin, which adds no pass and
8089        // declares nothing — see `Skinning::add_pass`.
8090        //
8091        // **Less the regions nothing this frame draws**, decided here rather
8092        // than at `begin_skinned_frame` because only now has every view the
8093        // frame records been begun — see `cull_skinned_regions`.
8094        let skinned = skinning.and_then(|skinning| {
8095            self.cull_skinned_regions(skinning.planned_regions(frame), views);
8096            let cull = &self.skin_cull;
8097            skinning.add_pass_where(graph, frame, |region| !cull.skips(region))
8098        });
8099
8100        // The camera's cull dispatch and the draw-argument dispatch, and the
8101        // light clustering after them — before anything draws, and before the
8102        // shadow atlas, which is where they always ran. See [`View::add_cull`].
8103        let cull = self.primary.add_cull(graph, pool, frame, instance_count);
8104
8105        // Topic 25's record of each cascade's cut. Each is written by
8106        // exactly one mesh pass, so what the graph orders here is this frame's
8107        // write against the next frame's use of the same slot. Each arrives in
8108        // the state the previous frame left it in, which is the one declared as
8109        // final.
8110        let tile_selection: Vec<BufferId> = self
8111            .shadow_selection
8112            .get(self.frame)
8113            .into_iter()
8114            .flatten()
8115            .enumerate()
8116            .map(|(tile, &buffer)| {
8117                import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
8118            })
8119            .collect();
8120
8121        // **This frame's slot of the probe ring**, which is the buffer every
8122        // one of this frame's bind groups names — see [`crate::probe`] for why
8123        // there is more than one. Imported in `ShaderRead` and handed back in
8124        // it: the build's staging copy left it there and no pass in the frame
8125        // writes it yet.
8126        let probe_buffer = self.probes.buffer(frame);
8127        let probe_table = graph.import_buffer(
8128            "probes",
8129            ImportedBuffer {
8130                buffer: probe_buffer,
8131                initial: ResourceState::ShaderRead,
8132                final_state: ResourceState::ShaderRead,
8133            },
8134        );
8135
8136        // The occlusion placeholder, imported once and read by every pass whose
8137        // bind group names it: the shadow pass's views, the depth prepass's copy
8138        // of the camera's group, and — on a frame drawing without
8139        // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
8140        // uploaded at build, so it is already in `ShaderRead` and the graph has
8141        // nothing to transition; declaring it is what keeps that true if a later
8142        // pass wants it in some other state.
8143        let occlusion_placeholder = graph.import_image(
8144            "ssao-placeholder",
8145            ImportedImage {
8146                image: self.ambient_occlusion_placeholder.image,
8147                view: self.ambient_occlusion_placeholder.view,
8148                format: Format::R8Unorm,
8149                extent: (1, 1),
8150                initial: ResourceState::ShaderRead,
8151                claim: InitialClaim::Tracked,
8152                final_state: ResourceState::ShaderRead,
8153            },
8154        );
8155
8156        // The contact-shadow placeholder, imported beside the occlusion one and
8157        // on its terms exactly: every group of the mesh layout names this
8158        // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
8159        // it is what the forward pass binds.
8160        let contact_placeholder = graph.import_image(
8161            "contact-shadows-placeholder",
8162            ImportedImage {
8163                image: self.contact_shadow_placeholder.image,
8164                view: self.contact_shadow_placeholder.view,
8165                format: Format::R8Unorm,
8166                extent: (1, 1),
8167                initial: ResourceState::ShaderRead,
8168                claim: InitialClaim::Tracked,
8169                final_state: ResourceState::ShaderRead,
8170            },
8171        );
8172
8173        // §3.2's base-colour page, in every bind group of `mesh_layout` and so
8174        // read by all three of the passes that draw geometry. Like the
8175        // placeholder above it is already in `ShaderRead` and the graph has
8176        // nothing to transition on a frame nothing writes it — **the
8177        // declaration is for the frames something does**. A caller that copies a
8178        // render-to-texture view into one of its layers imports the same handle,
8179        // gets this same id back (`RenderGraph::import_image`), and the graph
8180        // then has an edge to order its write against these reads. Without the
8181        // declaration there is no such edge: the page is bound out of a
8182        // descriptor the graph never hears about, and a copy scheduled anywhere
8183        // but the tail of the frame leaves it in `TransferDst` for the passes
8184        // that sample it.
8185        let base_color_page =
8186            graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
8187        // §2's normal page beside it, declared for exactly the reason above: it
8188        // is in every group of `mesh_layout` too, so a caller copying into one
8189        // of its layers needs the same edge against these draws.
8190        let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
8191        // §2's other two pages beside them, declared for exactly the same
8192        // reason: both are in every group of `mesh_layout`, so a caller copying
8193        // into one of their layers needs the same edge against these draws.
8194        let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
8195        let emissive_page =
8196            graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
8197
8198        // What this frame draws, resolved by the `begin_frame` that opened it —
8199        // see [`crate::effects`]. Read once here so every conditional below is
8200        // about one value rather than about four reads of a field.
8201        let effects = self.frame_effects;
8202        // Read here for `effects`' reason and for one more: the passes below
8203        // borrow `self` field by field, and a `&self` method called between
8204        // them would borrow the whole of it.
8205        let draws_sky = self.draws_sky();
8206        // What the frame's water draws, or `None` for a frame with none — read
8207        // here for `draws_sky`'s reason, and the same value every view records
8208        // from.
8209        let water = self.water.frame(self.frame);
8210        // The same, for the grass field, as `begin_frame` froze it: the value
8211        // every view's passes were built and its blocks written for.
8212        let grass = self.frame_grass;
8213        // Whether this frame ends by drawing the shadow atlas over itself — the
8214        // resolved view rather than the switch, so a caller who left the atlas
8215        // up and then asked for normals gets normals — as `begin_frame` froze
8216        // it, because that call built the viewer and wrote its block.
8217        let draws_atlas_view = self.frame_atlas_view;
8218
8219        let pages = MaterialPages {
8220            base_color: base_color_page,
8221            normal: normal_page,
8222            mro: mro_page,
8223            emissive: emissive_page,
8224        };
8225        let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
8226            graph,
8227            pool,
8228            &tile_selection,
8229            ShadowReads {
8230                occlusion_placeholder,
8231                pages,
8232                skinned,
8233                probes: probe_table,
8234            },
8235        );
8236
8237        // The wireframe twin where a caller switched the view on, and `None`
8238        // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
8239        // terms, and the `filter` is what keeps "switched on" from outrunning
8240        // "built": the field is only `Some` after a build that succeeded.
8241        //
8242        // The depth prepass below takes the depth-only pipeline and is untouched
8243        // by this, which is the half that makes a wireframe frame legible: the
8244        // occlusion pair still reads solid depth. **It is also what makes this
8245        // one variable rather than two**: the colour pass's depth attachment
8246        // branches on it as well, because a wireframe is not the geometry the
8247        // prepass drew — see `MeshModules::color_depth_stencil`.
8248        let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
8249        let bucket_draws = BucketDraws {
8250            // Replaced per partition below, in both passes that draw this list —
8251            // see [`ForwardRenderer::sided_partitions`] and
8252            // [`ForwardRenderer::depth_partitions`]. The field is what the
8253            // partitions inherit everything else from.
8254            pipeline: self.mesh_pipeline.single,
8255            layout: self.mesh_pipeline_layout,
8256            indices: self.pool.index_buffer(),
8257            emit,
8258            calls: self
8259                .bucket_constants
8260                .iter()
8261                .enumerate()
8262                .map(|(bucket, constant_offset)| {
8263                    let bucket = u32::try_from(bucket)
8264                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8265                    (
8266                        *constant_offset,
8267                        self.primary.draws.args_offset(bucket),
8268                        self.primary.draws.count_offset(bucket),
8269                        self.primary.draws.mesh_args_offset(bucket),
8270                    )
8271                })
8272                .collect(),
8273            region_step: self.region_step,
8274            // Packed per partition, where the partition's buckets are known.
8275            ranges: None,
8276            flat: None,
8277        };
8278
8279        // Every draw this frame records: the shadow pass's, one per bucket — or
8280        // per range of buckets, or per partition behind a task stage — in
8281        // **each** of the depth prepass and the forward pass, and one full-screen
8282        // triangle per full-screen pass. Assigned before the passes below borrow
8283        // the fields they need, so it is the count for the frame being built
8284        // rather than the one before it — and off this frame's resolved effects
8285        // rather than off a constant, so a switched-off effect's triangle is not
8286        // counted as submitted.
8287        //
8288        // The ground grid is added on top rather than folded into
8289        // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
8290        // resolved by the toggle order — it is a caller's opt-in, off by
8291        // default — so what decides it is the field and not this frame's
8292        // effects.
8293        self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
8294                + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
8295                + if draws_sky { SkyPass::PASSES } else { 0 }
8296                // The composite on an atmosphere frame whose fog effect is off,
8297                // on the sky's terms: it is there for the air in front of the
8298                // scene, which the atmosphere decides and no effect bit does.
8299                // With the effect on, `fullscreen_passes` already counted it.
8300                + if self.primary.frame_aerial
8301                    && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
8302                {
8303                    u64::from(Volumetric::COMPOSITE_PASSES)
8304                } else {
8305                    0
8306                }
8307                // The water copy's triangle, on the sky's terms: content rather
8308                // than an effect bit, so the bodies decide it.
8309                + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
8310                // The atlas viewer, on the ground grid's terms: not an effect
8311                // bit and not resolved by the toggle order, so what decides it
8312                // is the debug view and not this frame's effects. It *replaces*
8313                // the tonemap `fullscreen_passes` counted and the grid above —
8314                // see `View::add_passes` — so its passes stand in for the one.
8315                + if draws_atlas_view {
8316                    u64::from(AtlasView::PASSES) - 1
8317                } else {
8318                    0
8319                };
8320        // The debug draw layer's own call, on the ground grid's terms: not an
8321        // effect bit, and decided by whether this frame's slot has a segment in
8322        // it. One direct draw of one instance covering every segment appended,
8323        // which is why it joins the full-screen triangles rather than the
8324        // indirect draws — `counters` counts both as submitted *and* drawn,
8325        // because the CPU knows what they cover.
8326        self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
8327        // The shadow pass's tile resets, on the same terms: one over-sized
8328        // triangle of one instance per tile it redrew, and none at all on a
8329        // frame that cleared the whole attachment — see
8330        // [`MeshModules::depth_clear_pipeline`].
8331        self.recorded_tile_clears = shadow_tile_clears;
8332        // One indexed draw per body the frame's water holds.
8333        self.recorded_water_draws = water
8334            .as_ref()
8335            .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
8336        // One indirect draw per tile slot the frame's field holds, per look it
8337        // draws.
8338        self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
8339            u64::from(grass.slots) * u64::from(grass.draws_per_slot())
8340        });
8341        // The late depth prepass is a third list of calls, on a frame whose
8342        // camera culls in two phases.
8343        let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
8344            == crcbl_shaders::draw_gen::DrawMode::Occlusion
8345        {
8346            3
8347        } else {
8348            2
8349        };
8350        let prepass_partitions = self.depth_partitions(&bucket_draws);
8351        // And the colour pass's own split, which is by **side** alone: its
8352        // pipeline has a fragment stage either way, so an alpha mask is nothing
8353        // it has to route around and a cull mode is. The wireframe twin pair
8354        // substitutes for the shaded one here exactly as the single pipeline
8355        // used to.
8356        let color_partitions =
8357            self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
8358        // Off the partitions the passes below record, because where a call
8359        // draws a range of buckets the two splits pack into different numbers
8360        // of ranges — see [`BucketDraws::call_count`].
8361        let calls = |partitions: &[BucketDraws]| -> u64 {
8362            partitions.iter().map(BucketDraws::call_count).sum()
8363        };
8364        self.recorded_draws = shadow_draws
8365            + (camera_passes - 1) * calls(&prepass_partitions)
8366            + calls(&color_partitions)
8367            + self.recorded_grass_draws
8368            + self.direct_draws();
8369
8370        // --- the probe gather ---
8371        //
8372        // The irradiance probes' updater, second half: the map
8373        // the pass above drew, read into every row of the table. **Here rather
8374        // than beside that pass** because the write is `&mut` — the group naming
8375        // the map's transient views is cached across frames, and a group naming a
8376        // transient cannot be built where the others are; see
8377        // [`crate::ssao::cached_group`].
8378        //
8379        // It is before the depth prepass and the forward pass, which is the
8380        // ordering that matters: both declare a read of these rows, so the graph
8381        // barriers this write against them.
8382        //
8383        // Which map layer a row is weighed against is the row's own index, so
8384        // the view is resolved exactly as the drawing passes resolve it — the
8385        // placeholder until `capture_probe_visibility` has run, and off entirely
8386        // where `r_probe_visibility` is off. A gather against the placeholder
8387        // occludes nothing, which is the honest answer for a scene that never
8388        // captured.
8389        let probe_visibility_view = match &self.probe_visibility {
8390            Some(captured) if crate::probe_visibility::enabled() => captured.view,
8391            _ => self.probe_visibility_placeholder.view,
8392        };
8393        let frame = self.frame;
8394        if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
8395            gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
8396        }
8397
8398        let passes = FramePasses {
8399            slot: frame,
8400            emit,
8401            target_format: self.target_format,
8402            ssao_blurs: self.frame_ssao_blurs,
8403            draws_sky,
8404            water,
8405            grass,
8406            skinned,
8407            probe_buffer,
8408            probe_table,
8409            occlusion_placeholder,
8410            contact_placeholder,
8411            pages,
8412            shadow_atlas,
8413            probe_visibility: probe_visibility_view,
8414            mesh_layout: self.mesh_layout,
8415            wireframe,
8416            prepass_partitions,
8417            color_partitions,
8418            tonemap: TonemapPipeline {
8419                sampler: self.sampler,
8420                layout: self.tonemap_layout,
8421                pipeline_layout: self.tonemap_pipeline_layout,
8422                pipeline: self.tonemap_pipeline,
8423            },
8424        };
8425        // From here the frame is borrowed field by field, because every view's
8426        // passes hold its own caches for the life of the graph.
8427        let Self {
8428            primary,
8429            views: built,
8430            debug_draw,
8431            ground_grid,
8432            ground_grid_on,
8433            atlas_viewer,
8434            cull_stats,
8435            ..
8436        } = self;
8437
8438        // **Every secondary view before the primary camera's frame**, so a pass
8439        // the primary records — an overlay compositing a scope's picture onto
8440        // the lens it is seen through — reads a view that is already drawn. Each
8441        // records its whole frame straight through: its own cull, its own
8442        // clustering, and every pass the primary records after them, against the
8443        // atlas and the probe rows the scene passes above left behind.
8444        for (index, slot) in built.iter_mut().enumerate() {
8445            let Some((view_target, view_extent)) = secondary
8446                .iter()
8447                .find(|(view, _)| view.view.index() == index + 1)
8448            else {
8449                continue;
8450            };
8451            let view = slot
8452                .as_mut()
8453                .unwrap_or_else(|| unreachable!("checked against the built views above"));
8454            let view_cull = view.add_cull(graph, pool, frame, instance_count);
8455            view.add_passes(
8456                graph,
8457                &passes,
8458                view_cull,
8459                ViewOutput {
8460                    target: view_target.target,
8461                    target_extent: view_target.extent,
8462                    extent: *view_extent,
8463                },
8464                Overlays::default(),
8465                |_, _| {},
8466            );
8467        }
8468
8469        // The statistics buffer's id, read before the cull moves into the pass
8470        // recording below: the copy that reads it is the frame's last pass.
8471        let stats_id = cull.generated.visible_count_id;
8472        let tonemapped = primary.add_passes(
8473            graph,
8474            &passes,
8475            cull,
8476            ViewOutput {
8477                target,
8478                target_extent,
8479                extent,
8480            },
8481            Overlays {
8482                debug_draw: Some(debug_draw),
8483                ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8484                atlas_viewer: atlas_viewer.as_mut().filter(|_| draws_atlas_view),
8485            },
8486            overlay,
8487        );
8488
8489        // **Last, and that is the point.** Three passes add to the statistics
8490        // buffer — the cull dispatch, the light grid's overflow counter and the
8491        // amplification stage inside the forward pass — so a copy scheduled any
8492        // earlier would take a total the frame had not finished writing. The
8493        // graph puts it in `TransferSrc` for this and back into the state the
8494        // next frame on this slot imports it in; there is not a barrier written
8495        // here.
8496        if let Some(stats) = cull_stats.as_mut() {
8497            stats.add_copy_pass(graph, stats_id);
8498        }
8499
8500        tonemapped
8501    }
8502
8503    /// Adds the cull dispatches and the depth-only pass that fill the shadow
8504    /// atlas, and returns the atlas as the graph knows it.
8505    ///
8506    /// Every tile is one viewport of one render pass. A pass per tile would be
8507    /// one clear of the same image and one more barrier per tile, and the graph
8508    /// would have to be told each of them only touches part of it — where one
8509    /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8510    /// place.
8511    ///
8512    /// **Only the occupied tiles get a cull and a viewport.** The cascades
8513    /// always are; a light tile is occupied when
8514    /// [`shadow::Selection`] gave it to a light. A free one keeps the
8515    /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8516    /// away as depth goes" — so anything that did sample it would come back
8517    /// fully lit rather than fully shadowed.
8518    ///
8519    /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8520    ///
8521    /// That is the whole switch, and it is the same mechanism a free tile
8522    /// already had rather than a second one: no cull is dispatched and no
8523    /// viewport is drawn, the pass records its clear and nothing else, and every
8524    /// comparison against the atlas comes back fully lit. The pass itself stays
8525    /// on the frame that switches it off — it is what *writes* that clear, and a
8526    /// frame that skipped it would leave the atlas holding the last frame that
8527    /// did draw into it, or undefined memory on the first frame of all.
8528    ///
8529    /// # A cached atlas records nothing at all
8530    ///
8531    /// Topic 45's static-caching rung. When
8532    /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8533    /// what this frame would draw, this adds **no cull and no pass**: the atlas
8534    /// is imported so the passes that sample it have an edge to the resource,
8535    /// and it keeps the contents an earlier frame left in it. That is why the
8536    /// image is a persistent one with a tracked ledger entry rather than a
8537    /// transient — nothing else in the frame can alias it, so what it holds is
8538    /// what the last pass to write it wrote.
8539    ///
8540    /// # Per group, and what pays for the tiles it keeps
8541    ///
8542    /// Topic 45's cadence rung. A **group** — a cascade, or a
8543    /// light slot's whole run of tiles — is redrawn or held on its own, and
8544    /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8545    /// that holds nothing clears the whole attachment, which is the recording
8546    /// that shipped before the rung; a frame that holds something **loads** the
8547    /// attachment instead and resets each tile it redraws with
8548    /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8549    /// a clear bounded to one tile.
8550    ///
8551    /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8552    /// every tile including the ones being kept, and the region-bounded
8553    /// alternatives are not portable — Metal's load action and WebGPU's
8554    /// `loadOp` have no render area to bound them, so a clear that covered part
8555    /// of the image on Vulkan and all of it on Metal would be a held tile that
8556    /// survives on one backend and is erased on another.
8557    fn add_shadow_pass(
8558        &self,
8559        graph: &mut RenderGraph<'_>,
8560        pool: &TransientPool,
8561        selection: &[BufferId],
8562        reads: ShadowReads,
8563    ) -> (ImageId, u64, u64, Option<RsmImages>) {
8564        let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8565        let (atlas_width, atlas_height) = shadow::atlas_extent();
8566        let atlas = graph.import_image(
8567            "shadow-atlas",
8568            ImportedImage {
8569                image: self.shadow_atlas,
8570                view: self.shadow_atlas_view,
8571                format: Format::D32Float,
8572                extent: (atlas_width, atlas_height),
8573                // What the previous executed frame left it in — `Undefined` on
8574                // the first, which is what makes the graph give it a layout at
8575                // all.
8576                initial: imported_state(pool, self.shadow_atlas),
8577                // The renderer keeps this image across frames, so the pool's
8578                // ledger is the record of what happened to it and the line above
8579                // is that record read back rather than a second copy of it.
8580                claim: InitialClaim::Tracked,
8581                final_state: ResourceState::ShaderRead,
8582            },
8583        );
8584        // The cached frame's whole answer: the image above and nothing that
8585        // touches it. It is already in `ShaderRead` — the frame that drew it
8586        // handed it back that way — so the graph has no transition to make, and
8587        // the passes that sample it read the maps an earlier frame left there.
8588        if self.shadow_atlas_cached {
8589            // **And no reflective shadow map either**, which cannot happen while
8590            // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8591            // exactly that case, so a frame reaching here has nothing to draw
8592            // the map from. See `probe_update_runs`.
8593            return (atlas, 0, 0, None);
8594        }
8595        let placeholder = graph.import_image(
8596            "shadow-placeholder",
8597            ImportedImage {
8598                image: self.shadow_placeholder,
8599                view: self.shadow_placeholder_view,
8600                format: Format::D32Float,
8601                extent: (1, 1),
8602                // **Its own ledger entry, not the atlas's.** The two move
8603                // together today — both are imported by this function on every
8604                // frame and both are handed back in `ShaderRead` — so one lookup
8605                // would answer both, and that is exactly the coincidence a
8606                // second declared state here stops depending on.
8607                initial: imported_state(pool, self.shadow_placeholder),
8608                claim: InitialClaim::Tracked,
8609                final_state: ResourceState::ShaderRead,
8610            },
8611        );
8612
8613        // Which light slots have a light this frame, resolved once: a slot's
8614        // cull is dispatched and its faces are drawn together or not at all, and
8615        // `begin_frame` filled that generator's parameters under exactly this
8616        // condition.
8617        //
8618        // **And only the ones this frame redraws**, since the cadence rung: a
8619        // held slot keeps the texels it has, so recording its cull and its
8620        // draws would be the same picture at the full price.
8621        let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8622            .shadow_lights
8623            .slots()
8624            .iter()
8625            .enumerate()
8626            .filter(|_| shadows)
8627            .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8628            .filter_map(|(slot, held)| {
8629                let held = (*held)?;
8630                Some((slot, held, self.extra_lights.get(held.light)?))
8631            })
8632            .collect();
8633
8634        // One cull dispatch per cascade and per occupied slot, before the pass
8635        // that draws from them — **not one per tile**, which is topic 18's
8636        // fourth decision: a point light's six faces draw one visible set.
8637        let cascades: Vec<usize> = if shadows {
8638            (0..shadow::CASCADES)
8639                .filter(|cascade| self.shadow_group_redrawn[*cascade])
8640                .collect()
8641        } else {
8642            Vec::new()
8643        };
8644        // **Cascade 0's cull, on a frame that is not drawing it into the
8645        // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8646        // no shadows — see `rsm_cull_ready` — so this is the case where the map
8647        // is drawn and the atlas keeps its clear. Chained **last**, because the
8648        // occupied slots' entries are indexed by `cascades.len() + index` a few
8649        // lines below and an insertion before them would hand a light's draws to
8650        // the wrong viewport.
8651        let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8652        // The punctual producer's faces, which are also the light slots'
8653        // atlas views — see `punctual_faces`, the one list both halves of the
8654        // updater walk.
8655        let punctual = self.punctual_faces();
8656        // And their culls on a frame that is not drawing the atlas, which
8657        // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8658        // because a point light's six faces draw one visible set, and chained
8659        // **after** the entries `views` indexes positionally below.
8660        let punctual_only_culls: Vec<usize> = if shadows {
8661            Vec::new()
8662        } else {
8663            punctual
8664                .iter()
8665                .map(|face| face.cull)
8666                .collect::<std::collections::BTreeSet<_>>()
8667                .into_iter()
8668                .collect()
8669        };
8670        let generated: Vec<(usize, GeneratedDraws)> = cascades
8671            .iter()
8672            .copied()
8673            .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8674            .chain(rsm_only_cull.then_some(0))
8675            .chain(punctual_only_culls)
8676            .map(|cull| {
8677                (
8678                    cull,
8679                    self.shadow_draws[cull].add_passes(
8680                        graph,
8681                        self.frame,
8682                        self.instances.slot_count(),
8683                    ),
8684                )
8685            })
8686            .collect();
8687
8688        // What the pass body records, in order: which view's bind group, which
8689        // rectangle of the atlas its viewport covers, and which of the culls
8690        // above it draws from. Paired rather than positional, because the free
8691        // slots are missing from every one of these lists and a bare index into
8692        // one would hand a light's draws to the wrong viewport the moment one
8693        // slot is free and a later one is not.
8694        //
8695        // **The rectangle rather than the slot**, resolved here: the body runs
8696        // in a closure that outlives this borrow, and asking the selection for
8697        // it there would be a second reading of an allocation that has to be the
8698        // one the frame block was written from.
8699        //
8700        // **And which draw region of that cull**: region 0, every survivor, for
8701        // a cascade and a spot; and for a point light whose cull tagged its
8702        // casters by face, the region of the face being drawn — see
8703        // `set_point_face_culls`.
8704        let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8705            .iter()
8706            .enumerate()
8707            .map(|(position, cascade)| {
8708                (
8709                    *cascade,
8710                    self.shadow_lights.atlas_rect(*cascade),
8711                    position,
8712                    0,
8713                )
8714            })
8715            .collect();
8716        for (index, (slot, held, light)) in occupied.iter().enumerate() {
8717            // A spot draws face 0 alone; a point light draws all six, each
8718            // through its own matrix into its own tile. `shadow::tile_span` is
8719            // the same function `Selection` allocated the run with, so a face
8720            // here and a tile there cannot disagree about how many there are.
8721            let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8722                == crcbl_shaders::draw_gen::DrawMode::Faces;
8723            for face in 0..shadow::tile_span(light) {
8724                views.push((
8725                    shadow_view(*slot, face),
8726                    self.shadow_lights
8727                        .atlas_rect(shadow::light_tile(held.base + face)),
8728                    cascades.len() + index,
8729                    face_region(by_face, face),
8730                ));
8731            }
8732        }
8733
8734        let mut pass = graph
8735            .add_render_pass("shadow")
8736            // **Stored, unlike the scene's depth.** This is the one depth buffer
8737            // in the engine that something downstream reads, which is what
8738            // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8739            // day a prepass existed.
8740            .depth(
8741                atlas,
8742                // **Loaded on a frame that is keeping a tile**, which is the
8743                // cadence rung's whole seam: a clear here covers the image, so
8744                // the tiles this frame *does* redraw are reset one at a time by
8745                // the pipeline below instead. A frame keeping nothing clears,
8746                // which is what shipped.
8747                if self.shadow_atlas_clears {
8748                    LoadOp::Clear
8749                } else {
8750                    LoadOp::Load
8751                },
8752                StoreOp::Store,
8753                crcbl_hal::ClearValue {
8754                    depth: crcbl_hal::depth::CLEAR,
8755                    ..crcbl_hal::ClearValue::default()
8756                },
8757            )
8758            // Declared so the graph gives it a shader-read layout: it is in
8759            // every cascade's bind group, standing in for the atlas this pass is
8760            // writing. See `ForwardRenderer::shadow_placeholder`.
8761            .read_image(placeholder)
8762            // Likewise, and it is in every one of those groups too — see
8763            // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8764            // it here either: the depth-only pipeline has no fragment stage.
8765            .read_image(reads.occlusion_placeholder)
8766            // And §3.2's page, which `mesh_layout` names in every group — a
8767            // cascade's included. See `ForwardRenderer::base_color_page_import`
8768            // for what the declaration buys a caller that writes the page.
8769            .read_image(reads.pages.base_color)
8770            // And §2's other three pages beside it, in those same groups and
8771            // sampled by no cascade — see
8772            // `ForwardRenderer::normal_page_import`.
8773            .read_image(reads.pages.normal)
8774            .read_image(reads.pages.mro)
8775            .read_image(reads.pages.emissive)
8776            // And the probe rows, which are in those groups too and which no
8777            // cascade reads — declared on the placeholder's and the pages'
8778            // terms, plus one of their own: the rows are device-local and a copy
8779            // destination so the irradiance probes' gather can
8780            // write them, and a pass that binds a buffer it has not declared is
8781            // one the graph cannot order that write against.
8782            .read_buffer(reads.probes);
8783        // Each tile's mesh pass records the cut it descended to, into a buffer
8784        // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8785        // there is no amplification stage to descend anything.
8786        //
8787        // Declared for every tile rather than for the occupied ones: the state
8788        // is what the buffer is *in*, which does not depend on whether this
8789        // frame happened to write it, and a free tile's buffer still has to
8790        // arrive in the state the next frame's import claims.
8791        for &buffer in selection {
8792            pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8793        }
8794        // The skinned vertices this pass may pull, and the reason it is declared
8795        // here as well as on the colour passes: a cascade draws the same
8796        // geometry out of the same pool, so a shadow that fell before the
8797        // dispatch was visible would be cast by the previous pose — a shadow
8798        // that does not match its caster, on a frame whose picture is otherwise
8799        // right.
8800        if let Some(vertices) = reads.skinned {
8801            pass = pass.read_buffer(vertices);
8802        }
8803        for (_, draws) in &generated {
8804            pass = read_draw_sources(pass, draws, self.emit);
8805        }
8806
8807        let groups = self.shadow_groups[self.frame].clone();
8808        // **What the reflective shadow map is drawn from**, read out here rather
8809        // than reconstructed by the caller: cascade 0's bind group — whose
8810        // uniform block already holds that cascade's `view_proj`, which is what
8811        // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8812        // produced a moment ago. Both are `Copy`, so recording a second pass
8813        // from them costs no second cull and no second matrix.
8814        //
8815        // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8816        // or a `r_shadow_cadence` past one that held the group anyway. The rows
8817        // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8818        // which says so.
8819        let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8820            .rsm_cull_ready
8821            .then(|| {
8822                generated
8823                    .iter()
8824                    .find(|(cull, _)| *cull == 0)
8825                    .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8826            })
8827            .flatten();
8828        // **What the punctual reflective shadow map is drawn from**, resolved
8829        // here for `cascade_zero`'s reason and on its terms: each face's own
8830        // bind group — whose uniform block already holds that face's
8831        // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8832        // moment ago. Both are `Copy`, so the second pass costs no second cull
8833        // and no second matrix.
8834        //
8835        // Found by cull id rather than by position, so this list and the atlas's
8836        // cannot be knocked out of step by a slot the other one skipped.
8837        //
8838        // And the face's draw region, on the atlas's terms: a point light whose
8839        // cull tagged its casters draws each face from that face's region.
8840        let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8841            punctual
8842                .iter()
8843                .filter_map(|face| {
8844                    let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8845                    let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8846                        == crcbl_shaders::draw_gen::DrawMode::Faces;
8847                    Some((
8848                        groups[face.view],
8849                        face.tile,
8850                        *draws,
8851                        face_region(by_face, face.face),
8852                    ))
8853                })
8854                .collect();
8855        // The culls those faces draw from, **once each**: a point light's six
8856        // faces draw one visible set, so declaring a face's sources would
8857        // declare the same buffers six times in one pass.
8858        let punctual_sources: Vec<GeneratedDraws> = punctual
8859            .iter()
8860            .map(|face| face.cull)
8861            .collect::<std::collections::BTreeSet<_>>()
8862            .into_iter()
8863            .filter_map(|cull| {
8864                let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8865                Some(*draws)
8866            })
8867            .collect();
8868        let bucket_draws = BucketDraws {
8869            // Replaced per partition below; the field is what the tile clears
8870            // and the reflective shadow map inherit, and neither binds it.
8871            pipeline: self.shadow_pipeline.single,
8872            layout: self.mesh_pipeline_layout,
8873            indices: self.pool.index_buffer(),
8874            emit: self.emit,
8875            calls: self
8876                .bucket_constants
8877                .iter()
8878                .enumerate()
8879                .map(|(bucket, constant_offset)| {
8880                    let bucket = u32::try_from(bucket)
8881                        .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8882                    (
8883                        *constant_offset,
8884                        self.primary.draws.args_offset(bucket),
8885                        self.primary.draws.count_offset(bucket),
8886                        self.primary.draws.mesh_args_offset(bucket),
8887                    )
8888                })
8889                .collect(),
8890            region_step: self.region_step,
8891            // Packed per partition, where the partition's buckets are known.
8892            ranges: None,
8893            flat: None,
8894        };
8895        // Kept back for the reflective shadow map below, which is the same
8896        // per-bucket call list under a different pipeline — the depth prepass
8897        // plays exactly this trick with the camera's. Cloned before the pass
8898        // body takes the original.
8899        let bucket_calls = bucket_draws.clone();
8900        // The atlas's own split by material mode: an opaque bucket's tile is
8901        // drawn with no fragment stage in a scene that has a cutout in it. Every
8902        // view draws every partition — one call per bucket, per range of
8903        // buckets, or behind a task stage one flat call, per view, under a
8904        // pipeline per mode.
8905        let tile_partitions = self.depth_partitions(&bucket_draws);
8906
8907        // Counted off the two loops the body below runs, before it takes them:
8908        // every partition's calls per occupied view. `ForwardRenderer::counters`
8909        // is what reports it, and reading it back off the same `Vec`s is what
8910        // makes it move when the tile allocation does.
8911        let recorded = views.len() as u64
8912            * tile_partitions
8913                .iter()
8914                .map(BucketDraws::call_count)
8915                .sum::<u64>();
8916        // And the tile resets beside them, which are direct draws of one
8917        // instance rather than indirect ones: a frame that cleared the whole
8918        // attachment records none, and a frame that loaded it records one per
8919        // tile it redraws.
8920        let clears = if self.shadow_atlas_clears {
8921            0
8922        } else {
8923            views.len() as u64
8924        };
8925
8926        // What the image will hold once this body has run, carried into it so
8927        // that *recording* the pass is not what claims the atlas was drawn — see
8928        // [`ForwardRenderer::shadow_atlas_drawn`].
8929        let ran = Arc::clone(&self.shadow_pass_ran);
8930        let pass_id = self.shadow_pass_id;
8931        // The tiles this pass redraws have to be reset before anything is drawn
8932        // into them, and on a frame that loaded the attachment there is nothing
8933        // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8934        // that cleared has already had every tile reset by the attachment, so
8935        // this is `None` and the recording is the one that shipped.
8936        let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8937        // **The reset draw has to bind a group, and only a browser says so.**
8938        // `MeshModules::depth_clear_pipeline` builds this pipeline from
8939        // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8940        // the one triangle's vertex shader reads a byte of it — and WebGPU
8941        // refuses a draw with any group the *layout* declares left unset, where
8942        // Vulkan and the others only care about what the shader dereferences. An
8943        // unbound reset therefore fails no native run and rejects the whole
8944        // browser frame: `No bind group set at group index 0` arrives when the
8945        // encoder is finished, so every pass recorded after it is thrown away
8946        // with it and the canvas stays at the clear colour.
8947        //
8948        // Any bucket's offset does: the block is what the mesh draws index and
8949        // this draw reads none of it, so what matters is that the offset is one
8950        // the layout accepts rather than which bucket it names.
8951        let clear_layout = bucket_draws.layout;
8952        let clear_offset = bucket_draws
8953            .calls
8954            .first()
8955            .map_or(0, |(constant_offset, ..)| *constant_offset);
8956        pass.execute(move |ctx| {
8957            ran.store(pass_id, Ordering::Relaxed);
8958            let encoder = ctx.encoder();
8959            if let Some(clear) = clear {
8960                encoder.bind_graphics_pipeline(clear);
8961                for (view, tile, _, _) in &views {
8962                    set_shadow_tile(encoder, *tile);
8963                    encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8964                    encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8965                }
8966            }
8967            for partition in &tile_partitions {
8968                partition.open(encoder);
8969                for (view, tile, cull, region) in &views {
8970                    set_shadow_tile(encoder, *tile);
8971                    partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8972                }
8973            }
8974        });
8975
8976        // --- the reflective shadow map ---
8977        //
8978        // The irradiance probes' updater, first half, recorded
8979        // here because this is where cascade 0's bind group and its
8980        // already-generated draws are. **A pass of its own at its own extent**,
8981        // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8982        // one colour attachment there spans the whole 3072² image for data only
8983        // one 768² tile is read from, and it would give all fourteen light tiles
8984        // a fragment stage.
8985        //
8986        // No viewport is set: the graph opens a pass with a full-target viewport
8987        // and scissor already, and every attachment here is the map's own square.
8988        // Both or nothing: the map is drawn with pipelines `build` made only
8989        // for a volume that is updated, so a renderer without them has no map
8990        // to record and no gather to feed.
8991        let (Some((cascade_group, cascade_draws)), Some(rsm_pipeline)) =
8992            (cascade_zero, self.rsm_pipeline)
8993        else {
8994            return (atlas, recorded, clears, None);
8995        };
8996        let extent = rsm::extent();
8997        let sun = RsmTargets {
8998            albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8999            normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
9000            world: graph.create_image("rsm-world", rsm::world_target(extent)),
9001        };
9002        // Its own depth, cleared and discarded: it resolves which surface a
9003        // texel of the map holds and nothing reads it afterwards.
9004        let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
9005        let mut rsm = graph
9006            .add_render_pass("rsm")
9007            // **Cleared, and the world target's clear is load-bearing**: `w` is
9008            // the coverage flag `RsmOutput::world` writes, so a texel the pass
9009            // draws nothing into reads back zero there and the gather skips it.
9010            // Without the clear the world origin would stand in for every part
9011            // of the cascade the geometry does not cover.
9012            .clear_color(sun.albedo, [0.0; 4])
9013            .clear_color(sun.normal, [0.0; 4])
9014            .clear_color(sun.world, [0.0; 4])
9015            .clear_depth(rsm_depth)
9016            // The same declarations the cascade above makes, for the same
9017            // reason: every group of the mesh layout names these, and this pass
9018            // binds one of those groups. Unlike the cascade, this one has a
9019            // fragment stage — so the pages really are sampled here.
9020            .read_image(placeholder)
9021            .read_image(reads.occlusion_placeholder)
9022            .read_image(reads.pages.base_color)
9023            .read_image(reads.pages.normal)
9024            .read_image(reads.pages.mro)
9025            .read_image(reads.pages.emissive)
9026            .read_buffer(reads.probes);
9027        if let Some(vertices) = reads.skinned {
9028            rsm = rsm.read_buffer(vertices);
9029        }
9030        // Cascade 0's cluster-selection buffer, which the mesh path's stages
9031        // write — declared on the atlas pass's terms, and only for the one view
9032        // this pass draws.
9033        if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
9034            rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
9035        }
9036        rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
9037        // Split by side, on the colour pass's terms: this stage cuts the alpha
9038        // mask itself, so the only thing it cannot say inside the fragment stage
9039        // is which faces the rasteriser keeps.
9040        let rsm_partitions = self.sided_partitions(&bucket_calls, rsm_pipeline);
9041        let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
9042        rsm.execute(move |ctx| {
9043            let encoder = ctx.encoder();
9044            for partition in &rsm_partitions {
9045                partition.open(encoder);
9046                partition.record(encoder, cascade_group, &cascade_draws);
9047            }
9048        });
9049
9050        // --- the punctual reflective shadow map ---
9051        //
9052        // The irradiance probes' punctual producer: the same
9053        // pipeline and the same per-bucket call list as the pass above, under
9054        // one viewport per shadowed light face instead of one whole map. A spot
9055        // is a tile and a point light is six, which is `shadow::tile_span` — so
9056        // this is the atlas pass's own view loop drawn into a second, much
9057        // smaller set of targets.
9058        //
9059        // **Recorded whether or not the frame lights a punctual face**, unlike
9060        // the map above. The clear is a legitimate answer — a frame with no
9061        // shadowed punctual light has no punctual bounce, and the coverage flag
9062        // in `w` says so at every texel — and a pass that came and went with the
9063        // lights would be a pass list that changes shape with the scene, which
9064        // is what `RENDER_PASSES` and every timing reader are written against.
9065        let punctual_extent = rsm::punctual_extent();
9066        let punctual_targets = RsmTargets {
9067            albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
9068            normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
9069            world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
9070        };
9071        let punctual_depth =
9072            graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
9073        let mut punctual_pass = graph
9074            .add_render_pass("rsm-punctual")
9075            // Cleared on the map above's terms, and the world target's clear is
9076            // load-bearing for its reason as well as for one of this map's own:
9077            // the tiles the cascades would hold are drawn into by nothing at
9078            // all, and a coverage flag of zero is what keeps the gather out of
9079            // them.
9080            .clear_color(punctual_targets.albedo, [0.0; 4])
9081            .clear_color(punctual_targets.normal, [0.0; 4])
9082            .clear_color(punctual_targets.world, [0.0; 4])
9083            .clear_depth(punctual_depth)
9084            .read_image(placeholder)
9085            .read_image(reads.occlusion_placeholder)
9086            .read_image(reads.pages.base_color)
9087            .read_image(reads.pages.normal)
9088            .read_image(reads.pages.mro)
9089            .read_image(reads.pages.emissive)
9090            .read_buffer(reads.probes);
9091        if let Some(vertices) = reads.skinned {
9092            punctual_pass = punctual_pass.read_buffer(vertices);
9093        }
9094        // Each face's own cluster-selection buffer, which the mesh path's stages
9095        // write — declared on the atlas pass's terms, and only for the views
9096        // this pass draws.
9097        for face in &punctual {
9098            if let Some(&buffer) = selection.get(face.view) {
9099                punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
9100            }
9101        }
9102        for draws in &punctual_sources {
9103            punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
9104        }
9105        let punctual_partitions = self.sided_partitions(&bucket_calls, rsm_pipeline);
9106        let punctual_recorded = punctual_views.len() as u64
9107            * punctual_partitions
9108                .iter()
9109                .map(BucketDraws::call_count)
9110                .sum::<u64>();
9111        punctual_pass.execute(move |ctx| {
9112            let encoder = ctx.encoder();
9113            // The partition is **outside** the view loop, on the shadow atlas's
9114            // terms: one pipeline bind covers every face of that side.
9115            for partition in &punctual_partitions {
9116                partition.open(encoder);
9117                for (group, tile, draws, region) in &punctual_views {
9118                    set_shadow_tile(encoder, *tile);
9119                    partition.record_region(encoder, *group, draws, *region);
9120                }
9121            }
9122        });
9123
9124        let images = RsmImages {
9125            sun,
9126            punctual: punctual_targets,
9127        };
9128        (
9129            atlas,
9130            recorded + rsm_recorded + punctual_recorded,
9131            clears,
9132            Some(images),
9133        )
9134    }
9135
9136    /// Which lights hold the atlas's light tiles this frame, and where each
9137    /// map was laid out.
9138    ///
9139    /// **The observable topic 45's priority rung otherwise has
9140    /// none for.** A map's *size* leaves no trace in the picture that a golden
9141    /// can hold anyone to: a light demoted to a quarter of a cell draws a
9142    /// slightly softer shadow, which is a perfectly plausible frame and one a
9143    /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
9144    /// off this is what says which level the allocator actually handed out, and
9145    /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
9146    ///
9147    /// Named for the selection's own subject rather than for its type, because
9148    /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
9149    /// descended to — and two accessors of one name is a caller reaching for
9150    /// the wrong one.
9151    ///
9152    /// It is this frame's answer, written by [`Self::begin_frame`]: before the
9153    /// first frame every slot is free.
9154    /// Whether this frame took the shadow atlas as an earlier frame left it,
9155    /// rather than drawing it again.
9156    ///
9157    /// Topic 45's static-caching rung, read back. True means
9158    /// this frame recorded **no** shadow cull and no shadow pass, and every map
9159    /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
9160    /// frame that did draw put there — so a caller comparing two frames' pass
9161    /// lists, draw counts or GPU timings has to know which of them redrew.
9162    ///
9163    /// Decided by [`Self::begin_frame`] out of everything each group of the
9164    /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
9165    /// and it answers `false` before the first frame, because no frame has been
9166    /// opened and so none of them has held anything.
9167    ///
9168    /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
9169    /// frame that redraws one map and holds another answers `false` here and
9170    /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
9171    /// together are what say which.
9172    #[must_use]
9173    pub const fn shadow_atlas_cached(&self) -> bool {
9174        self.shadow_atlas_cached
9175    }
9176
9177    /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
9178    /// the one an earlier frame put there.
9179    ///
9180    /// Topic 45's cadence rung, read back. **The observable
9181    /// that rung otherwise has none for**: a held map draws a shadow lagging its
9182    /// caster by a frame or two, which is a perfectly plausible picture and one
9183    /// a golden accepts — so nothing but this distinguishes a cadence that is
9184    /// working from one that is not running at all.
9185    ///
9186    /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
9187    /// frame, which is the same answer for the same reason: no map was drawn
9188    /// there.
9189    #[must_use]
9190    pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
9191        cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
9192    }
9193
9194    /// Whether this frame redrew the maps of light slot `slot` —
9195    /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
9196    /// earlier frame put there.
9197    ///
9198    /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
9199    /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
9200    /// once and draw one visible set, so they are redrawn or held as one.
9201    #[must_use]
9202    pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
9203        slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
9204    }
9205
9206    /// How many tiles of the atlas this frame redrew.
9207    ///
9208    /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
9209    /// say the budget bound rather than that it was configured. A cascade costs
9210    /// one and a point light's cube costs [`shadow::POINT_FACES`].
9211    #[must_use]
9212    pub const fn shadow_faces_redrawn(&self) -> u32 {
9213        self.shadow_faces_redrawn
9214    }
9215
9216    /// Pins the shadow cadence for this renderer, or hands it back to the
9217    /// console.
9218    ///
9219    /// [`Self::set_effect_request`]'s shape at this knob:
9220    /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
9221    /// process-global, so they are the *default* rather than the only answer —
9222    /// an application drawing two views at two qualities, or a test that needs a
9223    /// frame nothing else in the process can move, pins its own.
9224    ///
9225    /// [`None`] hands it back, which is what a renderer starts at.
9226    ///
9227    /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
9228    /// terms: this call decides it and `add_passes` acts on it.
9229    pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
9230        self.shadow_cadence_request = cadence;
9231    }
9232
9233    /// Whether this frame ignored the cadence for at least one map because the
9234    /// region that map covers had moved out from under it.
9235    ///
9236    /// Topic 45's "a moving light or camera cut resets it",
9237    /// made precise: a map is *reset* rather than merely out of date when the
9238    /// centre it is projected from has moved further than the map's own reach —
9239    /// a light further than its own radius, or a cascade's eye further than the
9240    /// sphere that cascade was fitted to. Holding such a map is not a shadow
9241    /// that lags; it is a shadow of somewhere else.
9242    ///
9243    /// A frame whose atlas was **relaid** — a light gained, lost or resized a
9244    /// tile, or shadows were switched on or off — answers `true` as well, and
9245    /// that frame redraws every map it has: the only clear this seam can make
9246    /// covers the whole image, so there is nothing left to hold.
9247    #[must_use]
9248    pub const fn shadow_cadence_reset(&self) -> bool {
9249        self.shadow_cadence_reset
9250    }
9251
9252    #[must_use]
9253    pub const fn shadow_lights(&self) -> &shadow::Selection {
9254        &self.shadow_lights
9255    }
9256
9257    /// The shadow atlas, for a caller that wants to read it back.
9258    ///
9259    /// **The observable this whole slice can otherwise hide behind.** A shadow
9260    /// pass that renders nothing leaves every texel at
9261    /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
9262    /// everything is lit — which is a perfectly plausible picture and matches
9263    /// any golden blessed from it. Copying this image back and finding a texel
9264    /// that is not the clear value is what distinguishes the two.
9265    ///
9266    /// It is created with
9267    /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
9268    /// exactly that, and its extent is [`shadow::atlas_extent`].
9269    #[must_use]
9270    pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
9271        self.shadow_atlas
9272    }
9273
9274    /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
9275    /// through, for a reader importing the atlas into a graph of its own.
9276    #[must_use]
9277    pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
9278        self.shadow_atlas_view
9279    }
9280
9281    /// The base-colour page every material row samples through
9282    /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
9283    /// as the image and the view [`crate::texture`] uploaded.
9284    ///
9285    /// **What a render-to-texture view copies into.** A second camera drawing
9286    /// into an image is only half of a monitor: the surface that *shows* it
9287    /// samples a page layer, and nothing above this crate can name the image
9288    /// that layer lives in.
9289    ///
9290    /// A caller that wants to *write* it wants
9291    /// [`base_color_page_import`](Self::base_color_page_import) instead: the
9292    /// graph can only order a copy against the draws that sample the page while
9293    /// both are declared, and the two declarations have to agree field for
9294    /// field. This one is the raw handles, for a caller that binds or reads them
9295    /// outside a graph.
9296    ///
9297    /// It is created with
9298    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
9299    /// because the upload that filled it is a copy, so a per-frame copy into it
9300    /// needs no new usage flag. Its extent is
9301    /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
9302    /// [`PageKind::BaseColor`] squared and it has one layer per
9303    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
9304    /// the description is the caller's, so the caller already knows both. A
9305    /// description naming no base-colour layer gets a 1×1 placeholder instead —
9306    /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
9307    #[must_use]
9308    pub const fn base_color_page(&self) -> UploadedTexture {
9309        self.base_color_page
9310    }
9311
9312    /// What [`add_passes`](Self::add_passes) names the base-colour page in the
9313    /// graph.
9314    ///
9315    /// [`RenderGraph::import_image`] keeps the label of whichever import ran
9316    /// first, so a caller importing the page too passes this rather than a
9317    /// string of its own — otherwise every barrier record and
9318    /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
9319    /// depending on which subsystem got there first.
9320    pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
9321
9322    /// The base-colour page **as this renderer declares it to a graph**.
9323    ///
9324    /// [`add_passes`](Self::add_passes) imports exactly this value under
9325    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
9326    /// of it on every pass whose bind group names the page, so a caller that
9327    /// writes the page — a render-to-texture view copied into one layer — gets
9328    /// the graph to order its write against those draws.
9329    ///
9330    /// **A caller that writes it imports this value rather than one of its
9331    /// own.** [`RenderGraph::import_image`] hands the second importer the id the
9332    /// first got, which is what puts the write and the reads on one state
9333    /// tracker, and it does that only while the two declarations agree in every
9334    /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
9335    /// [`compile`](RenderGraph::compile). Reading the declaration off the
9336    /// renderer that owns the page is what makes them one answer instead of two
9337    /// constants that have to be kept equal by hand.
9338    ///
9339    /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
9340    /// [`crate::texture`] leaves an uploaded page in that state, and the
9341    /// trailing barrier the `final_state` asks for puts it back there at the end
9342    /// of every frame — so the pool's ledger and this declaration are the same
9343    /// answer, which is what `Tracked` has the graph check.
9344    ///
9345    /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
9346    #[must_use]
9347    pub const fn base_color_page_import(&self) -> ImportedImage {
9348        ImportedImage {
9349            image: self.base_color_page.image,
9350            view: self.base_color_page.view,
9351            format: BASE_COLOR_PAGE_FORMAT,
9352            extent: self.page_extents[PageKind::BaseColor.index()],
9353            initial: ResourceState::ShaderRead,
9354            claim: InitialClaim::Tracked,
9355            final_state: ResourceState::ShaderRead,
9356        }
9357    }
9358
9359    /// Topic 43 §2's **normal** page, the raw handles.
9360    ///
9361    /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
9362    /// its terms: one `D2Array` image, one layer per
9363    /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
9364    /// [`PageKind::Normal`], at **that kind's own extent**, and created with
9365    /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
9366    /// per-frame copy into a layer needs no new usage flag. What it is *not* is
9367    /// the same format: it is `Rgba8Unorm`, where the base-colour page is
9368    /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
9369    /// is argued.
9370    #[must_use]
9371    pub const fn normal_page(&self) -> UploadedTexture {
9372        self.normal_page
9373    }
9374
9375    /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
9376    /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9377    pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
9378
9379    /// The normal page **as this renderer declares it to a graph**, on
9380    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
9381    /// — including that a caller writing a layer imports *this* value rather
9382    /// than one of its own, so the write and the draws land on one state
9383    /// tracker.
9384    #[must_use]
9385    pub const fn normal_page_import(&self) -> ImportedImage {
9386        ImportedImage {
9387            image: self.normal_page.image,
9388            view: self.normal_page.view,
9389            format: NORMAL_PAGE_FORMAT,
9390            extent: self.page_extents[PageKind::Normal.index()],
9391            initial: ResourceState::ShaderRead,
9392            claim: InitialClaim::Tracked,
9393            final_state: ResourceState::ShaderRead,
9394        }
9395    }
9396
9397    /// Topic 43 §2's packed
9398    /// **metallic-roughness-occlusion** page, the raw handles.
9399    ///
9400    /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
9401    /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
9402    /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
9403    /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
9404    #[must_use]
9405    pub const fn mro_page(&self) -> UploadedTexture {
9406        self.mro_page
9407    }
9408
9409    /// What [`add_passes`](Self::add_passes) names the
9410    /// metallic-roughness-occlusion page in the graph, on
9411    /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9412    pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
9413
9414    /// The metallic-roughness-occlusion page **as this renderer declares it to a
9415    /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
9416    /// terms exactly.
9417    #[must_use]
9418    pub const fn mro_page_import(&self) -> ImportedImage {
9419        ImportedImage {
9420            image: self.mro_page.image,
9421            view: self.mro_page.view,
9422            format: MRO_PAGE_FORMAT,
9423            extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
9424            initial: ResourceState::ShaderRead,
9425            claim: InitialClaim::Tracked,
9426            final_state: ResourceState::ShaderRead,
9427        }
9428    }
9429
9430    /// Topic 43 §2's **emissive** page, the raw
9431    /// handles.
9432    ///
9433    /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
9434    /// format: an emissive texel is a colour, so this image is
9435    /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
9436    /// `EMISSIVE_PAGE_FORMAT`.
9437    #[must_use]
9438    pub const fn emissive_page(&self) -> UploadedTexture {
9439        self.emissive_page
9440    }
9441
9442    /// What [`add_passes`](Self::add_passes) names the emissive page in the
9443    /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
9444    pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
9445
9446    /// The emissive page **as this renderer declares it to a graph**, on
9447    /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
9448    #[must_use]
9449    pub const fn emissive_page_import(&self) -> ImportedImage {
9450        ImportedImage {
9451            image: self.emissive_page.image,
9452            view: self.emissive_page.view,
9453            format: EMISSIVE_PAGE_FORMAT,
9454            extent: self.page_extents[PageKind::Emissive.index()],
9455            initial: ResourceState::ShaderRead,
9456            claim: InitialClaim::Tracked,
9457            final_state: ResourceState::ShaderRead,
9458        }
9459    }
9460
9461    /// The model matrix for a cube spinning at `seconds` into the run.
9462    ///
9463    /// Two axes at incommensurable rates, so the animation never repeats and
9464    /// every face comes into view — which is what makes "the cube is spinning"
9465    /// observable rather than a claim about a matrix.
9466    #[must_use]
9467    pub fn spin(seconds: f32) -> Mat4 {
9468        Mat4::from_quat(
9469            Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
9470                * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
9471        )
9472    }
9473
9474    /// The format the tonemap pass renders into.
9475    #[must_use]
9476    pub const fn target_format(&self) -> Format {
9477        self.target_format
9478    }
9479
9480    /// Switches the infinite ground grid on with `style`, or off with [`None`].
9481    ///
9482    /// **Off by default.** Every sample and every golden image predates the
9483    /// grid, so a renderer nobody has called this on records exactly the passes
9484    /// it always did — see [`crate::grid`] for what the pass is and
9485    /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9486    ///
9487    /// The first `Some` builds the pipeline and the uniform ring; later calls
9488    /// only replace the style, and a `None` leaves both built. Releasing them
9489    /// here would mean releasing blocks the frames in flight may still be
9490    /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9491    /// one call that already requires an idle device.
9492    ///
9493    /// # Errors
9494    ///
9495    /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9496    /// Nothing is left switched on when that happens: the grid stays as it was.
9497    pub fn set_ground_grid(
9498        &mut self,
9499        device: &dyn Device,
9500        style: Option<GridStyle>,
9501    ) -> Result<(), HalError> {
9502        let Some(style) = style else {
9503            self.ground_grid_on = false;
9504            return Ok(());
9505        };
9506        let grid = match self.ground_grid.as_mut() {
9507            Some(grid) => grid,
9508            None => {
9509                // Built for the tonemap's target and the scene depth, because
9510                // those are the two attachments the pass is given — see
9511                // `add_passes`. Both are pipeline state, so a renderer whose
9512                // target format changed would need a new `Grid`; nothing in this
9513                // crate changes it after `build`, and `target_format` is kept
9514                // for exactly that reason.
9515                let grid = GroundGrid::new(
9516                    device,
9517                    self.primary.uniforms.len(),
9518                    self.target_format,
9519                    SCENE_DEPTH_FORMAT,
9520                )?;
9521                self.ground_grid.insert(grid)
9522            }
9523        };
9524        grid.set_style(style);
9525        self.ground_grid_on = true;
9526        Ok(())
9527    }
9528
9529    /// The debug draw layer's immediate-mode buffer, to append to.
9530    ///
9531    /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9532    /// spheres and frusta during the frame, and
9533    /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9534    /// a segment lives exactly the frame it was appended in and nothing has to
9535    /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9536    /// for the console switch that has to be on before anything is drawn.
9537    ///
9538    /// **Appending is free while the layer is off**, but building the geometry
9539    /// is the caller's: a system whose overlay costs something to compute asks
9540    /// [`DebugDraw::enabled`] first.
9541    pub fn debug_draw(&mut self) -> &mut DebugDraw {
9542        &mut self.debug_draw
9543    }
9544
9545    /// How the ground grid is drawn, or [`None`] where it is switched off.
9546    ///
9547    /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9548    /// observable a test asking "is the grid on" wants: a renderer that built
9549    /// the grid and then switched it off answers [`None`], because what it draws
9550    /// is what the question is about.
9551    #[must_use]
9552    pub fn ground_grid(&self) -> Option<&GridStyle> {
9553        self.ground_grid
9554            .as_ref()
9555            .filter(|_| self.ground_grid_on)
9556            .map(GroundGrid::style)
9557    }
9558
9559    /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9560    ///
9561    /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9562    /// [`set_sky`](Self::set_sky) or
9563    /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9564    /// here rather than left to the shader for the reason [`crate::sky_pass`]
9565    /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9566    /// frames, where adding no pass leaves them exactly as they were.
9567    fn draws_sky(&self) -> bool {
9568        self.sky != Sky::NONE || self.atmosphere.is_some()
9569    }
9570
9571    /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9572    /// per frame.
9573    ///
9574    /// Called once per [`Self::begin_frame`]. The comparison is on the
9575    /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9576    /// over, so re-setting the same sun spelled a different length is not a
9577    /// rebuild — and a caller that sets the same value every frame, which is
9578    /// the ordinary shape of a scene's update, pays the comparison and nothing
9579    /// else.
9580    ///
9581    /// # The first LUT is marched whole; every later one is marched in stripes
9582    ///
9583    /// A renderer that has no LUT has no sky to draw, so the first march after
9584    /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9585    /// call and a caller that draws a single frame gets that frame's sky. After
9586    /// that there is always a finished LUT to show, so a sun that moved starts
9587    /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9588    /// frame — the frames in between keep drawing the LUT the last completed
9589    /// march produced, and no frame pays the whole march.
9590    ///
9591    /// # A sun that moves again restarts the march rather than finishing it
9592    ///
9593    /// The build in flight is kept only while its own sun is still the one the
9594    /// caller wants; a sun that moved during it is a new build from row zero,
9595    /// because finishing the old one would swap in a LUT for a sun that is
9596    /// already wrong and then immediately start marching again. **A sun that
9597    /// moves every frame therefore never completes a build and goes on showing
9598    /// the last one it finished** — a sky frozen at the sun it last caught up
9599    /// with, rather than a sky that stutters at whatever the march last passed.
9600    /// That is the trade this makes: the frame cost is bounded and the sky
9601    /// lags, where the whole-march rebuild it replaced had the sky exact and
9602    /// the frame cost unbounded. A caller that wants the sky exact stops the
9603    /// sun on a value and leaves it there: the march then completes, and the
9604    /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9605    ///
9606    /// **The aerial-perspective LUT is marched in the same steps** — see
9607    /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9608    /// frame as the sky and lags the sun by the same frames, never a sun apart
9609    /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9610    /// on the same terms, since it is part of the parameters compared.
9611    fn refresh_sky_view(&mut self) {
9612        let Some(atmosphere) = self.atmosphere else {
9613            self.sky_view = None;
9614            self.sky_view_build = None;
9615            return;
9616        };
9617        let parameters = atmosphere.parameters();
9618        if self
9619            .sky_view
9620            .as_ref()
9621            .is_some_and(|presented| presented.parameters == parameters)
9622        {
9623            self.sky_view_build = None;
9624            return;
9625        }
9626        if self.sky_view.is_none() {
9627            self.sky_view_build = None;
9628            self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(&parameters)));
9629            return;
9630        }
9631        let mut build = match self.sky_view_build.take() {
9632            Some(build) if build.atmosphere() == parameters => build,
9633            _ => SkyViewBuild::start(&parameters),
9634        };
9635        if build.step(SKY_VIEW_BUILD_ROWS) {
9636            self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9637        } else {
9638            self.sky_view_build = Some(build);
9639        }
9640    }
9641
9642    /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9643    /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9644    ///
9645    /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9646    /// the value `tonemap.slang` held as a compile-time constant until this
9647    /// became a runtime one — so a renderer nobody calls this on draws the frame
9648    /// it always drew, and every golden image is untouched.
9649    ///
9650    /// It takes effect on the next
9651    /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9652    /// frame already recorded reads the value it was recorded with.
9653    ///
9654    /// **The clamp is here rather than at the call site** so that no caller can
9655    /// reach a picture it cannot get back from, and so that a control which
9656    /// steps by reading this back and setting a multiple of it — which is what
9657    /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9658    /// then need as many presses to come back.
9659    pub const fn set_exposure(&mut self, exposure: f32) {
9660        // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9661        // and a NaN reaching the block is a frame of NaN pixels with no key to
9662        // press to get out of it. `f32::max` returns the bound instead, so a NaN
9663        // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9664        self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9665    }
9666
9667    /// How far auto-exposure may travel toward its measurement in one frame.
9668    ///
9669    /// **[`None`] is the whole distance**, which is what a renderer nobody
9670    /// calls this on does and what the pass did before adaptation existed — so
9671    /// no golden moved when this arrived. A view that wants the roll asks, and
9672    /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9673    /// own delta: this crate has no clock, and the frame time lives where the
9674    /// frame loop is.
9675    ///
9676    /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9677    /// what writes the block, and it does nothing at all on a frame that did not
9678    /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9679    /// the ones that bit adds.
9680    pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9681        self.exposure_adaptation = adaptation;
9682    }
9683
9684    /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9685    /// handed.
9686    #[must_use]
9687    pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9688        self.exposure_adaptation
9689    }
9690
9691    /// Which operator the tonemap pass runs on the exposed scene colour.
9692    ///
9693    /// **The ACES fit by default**, because this renderer shades in linear HDR
9694    /// and the roll-off is what that range is for. What a caller asks *for* here
9695    /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9696    /// identity on `0..=1`, so display-referred content reaches the swapchain
9697    /// exactly, and a fixture that predicts a code value from a host model of
9698    /// the shading needs the frame to stay scene-referred. Every 2D sample in
9699    /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9700    /// instead, so none of them reaches this pass at all.
9701    ///
9702    /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9703    /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9704    /// there, and a frame already recorded reads the value it was recorded
9705    /// with.
9706    ///
9707    /// **There is nothing to refuse and no `supports_` probe beside it.** The
9708    /// selector is a lane of a uniform block read by a branch every device
9709    /// already runs, so unlike the wireframe there is no second pipeline for a
9710    /// device to decline to build.
9711    pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9712        self.tonemap_curve = curve;
9713    }
9714
9715    /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9716    /// value the next frame will be drawn with.
9717    #[must_use]
9718    pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9719        self.tonemap_curve
9720    }
9721
9722    /// How large the internal render target is as a fraction of the extent
9723    /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9724    /// `MIN_RENDER_SCALE..=1.0`.
9725    ///
9726    /// **This is the largest performance knob this renderer has.** Every pass
9727    /// before the upscale costs what its extent costs, so a scale of `0.7` is
9728    /// roughly half the shading work of `1.0`; the UI is composited onto the
9729    /// target afterwards at native resolution, so text stays sharp while the 3D
9730    /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9731    /// 48-post-processing plan left behind_) is where that trade is written down.
9732    ///
9733    /// **`1.0` is not a special case with a fast path, it is the absence of the
9734    /// feature.** At full scale the internal extent *is* the caller's, the post
9735    /// chain writes the target directly, and no upscale pass is recorded — which
9736    /// is what makes a renderer nobody has called this on draw the frame it drew
9737    /// before the knob existed, bit for bit.
9738    ///
9739    /// **Above `1.0` is clamped away rather than supported.** Supersampling
9740    /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9741    /// *reconstruction*; running it as a minification filter would alias, which
9742    /// is the opposite of what a caller asking for it wants. A non-finite scale
9743    /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9744    /// the failure it produces is a zero-sized target somewhere downstream.
9745    ///
9746    /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9747    /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9748    /// recorded is drawn at the scale it was recorded with.
9749    pub fn set_render_scale(&mut self, scale: f32) {
9750        self.render_scale = if scale.is_finite() {
9751            scale.clamp(MIN_RENDER_SCALE, 1.0)
9752        } else {
9753            1.0
9754        };
9755    }
9756
9757    /// The render scale in force, after the clamp
9758    /// [`set_render_scale`](Self::set_render_scale) applied.
9759    ///
9760    /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9761    #[must_use]
9762    pub const fn render_scale(&self) -> f32 {
9763        self.render_scale
9764    }
9765
9766    /// The anisotropy the base-colour page is sampled with, in force from the
9767    /// next [`begin_frame`](Self::begin_frame).
9768    ///
9769    /// Topic 43's filtering rung, the player's half:
9770    /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9771    /// called this on samples with, and this is what a settings row moves it
9772    /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9773    /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9774    /// was not — the row can turn the filter off or push it to the device's
9775    /// ceiling, and nothing it asks reaches a `create_sampler` that would
9776    /// refuse it. A value that is not a number is the default, on
9777    /// [`set_render_scale`](Self::set_render_scale)'s terms.
9778    ///
9779    /// **A sampler is a resource a bind group holds by handle**, so a new
9780    /// anisotropy is a new sampler, and every group of the mesh layout has to
9781    /// be rebuilt to name it. That happens per frame slot, at the slot's own
9782    /// `begin_frame`, which is the moment the ring guarantees the slot's
9783    /// previous submission has retired — the guarantee every host write in
9784    /// that call already leans on — so a frame in flight goes on naming the
9785    /// sampler it was recorded with, and the replaced sampler is destroyed once
9786    /// no slot names it. This call creates the sampler and nothing else, and
9787    /// asking for the anisotropy already in force creates nothing.
9788    ///
9789    /// # Errors
9790    ///
9791    /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9792    /// stays in force.
9793    pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9794        let caps = device.caps();
9795        let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9796            caps.limits.max_sampler_anisotropy
9797        } else {
9798            1.0
9799        };
9800        let wanted = if anisotropy.is_finite() {
9801            anisotropy.clamp(1.0, ceiling)
9802        } else {
9803            Self::anisotropy_for(&caps)
9804        };
9805        // Bit-equal rather than within an epsilon: both sides came out of the
9806        // same clamp, and a row that lands on the value in force must not
9807        // rebuild every group for it.
9808        if wanted.to_bits() == self.anisotropy.to_bits() {
9809            return Ok(());
9810        }
9811        let sampler = Self::create_page_sampler(device, wanted)?;
9812        self.retired_pages
9813            .push(RetiredPage::Sampler(std::mem::replace(
9814                &mut self.base_color_sampler,
9815                sampler,
9816            )));
9817        self.anisotropy = wanted;
9818        Ok(())
9819    }
9820
9821    /// The anisotropy in force, after the clamp
9822    /// [`set_anisotropy`](Self::set_anisotropy) applied.
9823    ///
9824    /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9825    #[must_use]
9826    pub const fn anisotropy(&self) -> f32 {
9827        self.anisotropy
9828    }
9829
9830    /// The anisotropy the base-colour page's sampler is created with on a
9831    /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9832    /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9833    /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9834    /// not.
9835    ///
9836    /// **Granted, not supported.** The feature is optional at every open site
9837    /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9838    /// without asking refuses a sampler above one even on hardware that has
9839    /// it, which is the shape every backend's `create_sampler` documents. So
9840    /// the question is what this device was opened *with*, and a caller that
9841    /// wants the plan's default has to name the feature beside the others it
9842    /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9843    /// one, so a browser samples isotropically until `docs/backlog.md`'s
9844    /// ceiling decision is taken.
9845    #[must_use]
9846    pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9847        if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9848            DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9849        } else {
9850            1.0
9851        }
9852    }
9853
9854    /// The base-colour page's sampler at `anisotropy`, which the caller has
9855    /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9856    /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9857    ///
9858    /// **Trilinear over the whole chain, anisotropic where the device is** —
9859    /// topic 43's filtering rung: a minified surface
9860    /// reads the level its footprint matches instead of shimmering through
9861    /// level 0, a magnified one blends four texels instead of stepping between
9862    /// them, and a surface at a grazing angle keeps its detail along the long
9863    /// axis of its footprint rather than blurring to the short one. A second
9864    /// sampler object rather than sharing the tonemap's, so a capture names
9865    /// each for what it filters.
9866    ///
9867    /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9868    /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9869    /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9870    /// wrapping address mode makes the page tile across it rather than
9871    /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9872    /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9873    /// clamped read return the same nearest texel for it.
9874    fn create_page_sampler(
9875        device: &dyn Device,
9876        anisotropy: f32,
9877    ) -> Result<SamplerHandle, HalError> {
9878        device.create_sampler(&SamplerDesc {
9879            label: Some("material base colour"),
9880            mag_filter: FilterMode::Linear,
9881            min_filter: FilterMode::Linear,
9882            mip_filter: FilterMode::Linear,
9883            address_mode: [SamplerAddressMode::Repeat; 3],
9884            anisotropy,
9885            ..SamplerDesc::default()
9886        })
9887    }
9888
9889    /// The extent the next frame handed `target` is actually drawn at, at the
9890    /// render scale in force.
9891    ///
9892    /// Test-only: a frame takes its extents at the scale its `begin_frame`
9893    /// froze, through [`scaled_extent`](Self::scaled_extent), and this is the
9894    /// prediction a test checks that against.
9895    #[cfg(all(test, not(target_arch = "wasm32")))]
9896    fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9897        Self::scaled_extent(self.render_scale, target)
9898    }
9899
9900    /// The extent a frame handed `target` is drawn at under `scale` — what a
9901    /// frame's own extents are taken at, with
9902    /// [`frame_render_scale`](Self::frame_render_scale).
9903    ///
9904    /// Rounds rather than truncates, and floors at one texel in each dimension:
9905    /// a zero here would reach a transient image description, and an image of
9906    /// zero extent is a device error rather than a small frame. A caller who
9907    /// minimised the window already hands a zero extent through, and that path
9908    /// is unchanged — `max(1)` on a zero is one either way.
9909    fn scaled_extent(scale: f32, target: (u32, u32)) -> (u32, u32) {
9910        if scale >= 1.0 {
9911            return target;
9912        }
9913        let scale = f64::from(scale);
9914        (
9915            ((f64::from(target.0) * scale).round() as u32).max(1),
9916            ((f64::from(target.1) * scale).round() as u32).max(1),
9917        )
9918    }
9919
9920    /// The exposure in force, after the clamp
9921    /// [`set_exposure`](Self::set_exposure) applied.
9922    ///
9923    /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9924    /// caller wants is the number the frame is drawn with, not the one it asked
9925    /// for — which is also what makes a multiplicative step land on the end of
9926    /// the range rather than run past it.
9927    #[must_use]
9928    pub const fn exposure(&self) -> f32 {
9929        self.exposure
9930    }
9931
9932    /// Whether `device` can draw the wireframe view at all.
9933    ///
9934    /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9935    /// error, asked **before** anything is switched on — so an application can
9936    /// tell its user that this device has no wireframe rather than binding a key
9937    /// that fails, and can say so once at start-up instead of on every press.
9938    /// WebGPU has no line fill mode at all, so the browser is the case this
9939    /// exists for and not a hypothetical.
9940    ///
9941    /// An associated function rather than a method: it is a fact about the
9942    /// device, and a caller wants it before it has decided anything.
9943    #[must_use]
9944    pub fn supports_wireframe(device: &dyn Device) -> bool {
9945        device.caps().supports(Features::POLYGON_MODE_LINE)
9946    }
9947
9948    /// Asks every camera's cull to drop what is hidden or too small to see —
9949    /// topic 03 §3.3's occlusion cull and its
9950    /// small-feature test. See [`crate::occlusion_cull`].
9951    ///
9952    /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9953    /// guesses from the previous frame's depth, the second tests every rejected
9954    /// instance against this frame's, and only the second's rejections are
9955    /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9956    /// and is off unless a threshold is named.
9957    ///
9958    /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9959    /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9960    /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9961    /// alone, because a wireframe shows the edges a depth test would hide.
9962    pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9963        self.occlusion_culling = culling;
9964    }
9965
9966    /// Whether a skinned frame skips the dispatch of a region nothing this
9967    /// frame can draw — **on** by default.
9968    ///
9969    /// A region is skipped only when every object drawn out of it carries a
9970    /// [`SkinnedInstanceDesc::bounds`] box, and that box is outside the camera
9971    /// of every view the frame records and outside every shadow cull it
9972    /// redraws — a map the cadence holds draws nothing this frame — and every
9973    /// cull the probe updater draws through with shadows off.
9974    /// An object with no box keeps its region dispatched, and so does a region
9975    /// no object is drawn out of. The host asks the device cull's question with
9976    /// slack in the safe direction, so a skipped object is one no cull draws.
9977    ///
9978    /// **An object that comes back into view is at rest for one frame**: its
9979    /// region's halves hold the poses of the last frame that skinned it, so the
9980    /// frame it returns on writes its current half into both base lanes, as an
9981    /// object's first frame out of a region does. Its own travel is still
9982    /// reported. [`skinned_regions_skipped`](Self::skinned_regions_skipped)
9983    /// says how many regions a frame skipped.
9984    ///
9985    /// **Off is the opt-out for a caller that reads a region back**: a skipped
9986    /// region's halves keep an older pose, which nothing in this renderer reads,
9987    /// and which a readback of [`vertex_buffer`](Self::vertex_buffer) would. It
9988    /// is also the other half of a price. Both settings draw the same colour;
9989    /// the motion target differs on the frame a skipped object returns, which
9990    /// reads no deformation motion with the cull on and the motion its pose
9991    /// made since the frame before with it off.
9992    ///
9993    /// Read by the next call that records a frame's passes —
9994    /// [`add_skinned_passes`](Self::add_skinned_passes),
9995    /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
9996    /// or [`add_passes_with_views`](Self::add_passes_with_views) — and moot for
9997    /// one handed no [`Skinning`].
9998    pub fn set_skinning_culls(&mut self, on: bool) {
9999        self.skinning_culls = on;
10000    }
10001
10002    /// Whether a point light's shadow cull tags each caster with the faces of
10003    /// its cube it reaches, so each face draws only those — **on** by default.
10004    ///
10005    /// Off is the cull this replaced: one test against the light's box, and
10006    /// every caster in it drawn into all six faces for the rasteriser to clip.
10007    /// The two write the same atlas, texel for texel — the six faces' pyramids
10008    /// tile the box, so a caster a face drops has no texel in that face's tile —
10009    /// and the switch exists so a test can hold them against each other and a
10010    /// price can be read off both.
10011    pub fn set_point_face_culls(&mut self, on: bool) {
10012        self.point_face_culls = on;
10013    }
10014
10015    /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
10016    /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
10017    /// on its way to the GPU, or stops doing so with [`None`] — the default,
10018    /// and the only value a frame outside a test runs under.
10019    ///
10020    /// Applied **after** the atlas cache has read the blocks, so the rewrite is
10021    /// invisible to the decision whether to redraw a map and visible only to the
10022    /// depth pass that draws it. That is what makes it a probe of the shaders:
10023    /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
10024    /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
10025    /// perturbed through here and holds the depth to the untampered frame's, bit
10026    /// for bit. It reaches the atlas's views alone — not the probe updater's
10027    /// shadows-off writes, which draw nothing into the atlas.
10028    pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
10029        self.shadow_view_tamper = tamper;
10030    }
10031
10032    /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
10033    /// for, before the console switches and the wireframe are applied.
10034    #[must_use]
10035    pub const fn occlusion_culling(&self) -> OcclusionCulling {
10036        self.occlusion_culling
10037    }
10038
10039    /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
10040    /// with the console switches applied, and nothing on a wireframe frame.
10041    #[must_use]
10042    pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
10043        if self.wireframe_on {
10044            return OcclusionCulling::OFF;
10045        }
10046        let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
10047        OcclusionCulling {
10048            occlusion: self.occlusion_culling.occlusion
10049                || crate::occlusion_cull::r_occlusion_cull.get_bool(),
10050            small_feature_pixels: self
10051                .occlusion_culling
10052                .small_feature_pixels
10053                .or((console_pixels > 0.0).then_some(console_pixels)),
10054        }
10055    }
10056
10057    /// Draws the scene's triangles as lines, or goes back to filling them.
10058    ///
10059    /// **Off by default.** Every sample and every golden image predates the
10060    /// view, so a renderer nobody has called this on records exactly the frame
10061    /// it always did.
10062    ///
10063    /// # What it is, and what it is not
10064    ///
10065    /// The **colour pass** alone changes fill mode. The depth prepass and the
10066    /// shadow cascades keep drawing filled triangles, because they are what the
10067    /// occlusion pair and the shadow lookups read and depth drawn as lines is
10068    /// depth with holes in it. So a wireframe frame is the same geometry, the
10069    /// same shading and the same lights, rasterised as edges: what was inside a
10070    /// triangle becomes the clear colour, and what was on its edge stays lit.
10071    ///
10072    /// # It is built on the first `true`
10073    ///
10074    /// The pipeline is compiled here rather than beside the filled one at
10075    /// [`with_scene`](Self::with_scene), and that is the trade this
10076    /// call makes: one pipeline compile on the first press — a hitch, in a view
10077    /// the user just asked for — against a second compile in the start-up of
10078    /// every sample, golden run and headless test that never asks for one. Later
10079    /// calls only flip the switch, and a `false` leaves the pipeline built, for
10080    /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
10081    /// the frames in flight may still be recording against is what
10082    /// [`destroy`](Self::destroy) — which already requires an idle device — is
10083    /// for.
10084    ///
10085    /// # Errors
10086    ///
10087    /// [`HalError::UnsupportedFeatures`] naming
10088    /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
10089    /// when `on` is `true` on a device that has not got it — ask
10090    /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
10091    /// than quietly filled: a caller who asked for a wireframe and got a solid
10092    /// frame back with no error has no way to tell that from a wireframe of a
10093    /// solid-looking model.
10094    ///
10095    /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
10096    /// when either happens**: the view stays as it was.
10097    pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
10098        if !on {
10099            self.wireframe_on = false;
10100            return Ok(());
10101        }
10102        if self.wireframe_pipeline.is_none() {
10103            if !Self::supports_wireframe(device) {
10104                return Err(HalError::UnsupportedFeatures {
10105                    missing: Features::POLYGON_MODE_LINE,
10106                });
10107            }
10108            let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
10109            let line = |cull| {
10110                modules.color_pipeline(
10111                    device,
10112                    self.mesh_pipeline_layout,
10113                    PolygonMode::Line,
10114                    cull,
10115                    "wireframe",
10116                )
10117            };
10118            let [back, none] = MeshModules::SIDES;
10119            // The twin only where the shaded pass has one — see
10120            // [`SidedPipelines`] — so a wireframe covers exactly the buckets
10121            // the shaded frame beside it draws.
10122            let single = line(back);
10123            let double = self.mesh_pipeline.double.map(|_| line(none)).transpose();
10124            modules.destroy(device);
10125            // **Both or neither.** A caller that got one twin back would draw a
10126            // frame missing every double-sided surface and nothing would say
10127            // so; released here rather than kept, because `destroy` is what
10128            // releases what this field holds and it holds nothing yet.
10129            let pipelines = match (single, double) {
10130                (Ok(single), Ok(double)) => SidedPipelines { single, double },
10131                (Ok(built), Err(error)) | (Err(error), Ok(Some(built))) => {
10132                    device.destroy_graphics_pipeline(built);
10133                    return Err(error);
10134                }
10135                (Err(error), Ok(None) | Err(_)) => return Err(error),
10136            };
10137            self.wireframe_pipeline = Some(pipelines);
10138        }
10139        self.wireframe_on = true;
10140        Ok(())
10141    }
10142
10143    /// Whether the colour pass draws lines instead of filled triangles.
10144    ///
10145    /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
10146    /// observable a test asking "is this frame a wireframe" wants: a renderer
10147    /// that built the pipeline and then switched it off answers `false`, because
10148    /// what it draws is what the question is about.
10149    #[must_use]
10150    pub const fn wireframe(&self) -> bool {
10151        self.wireframe_on
10152    }
10153
10154    /// Draws each surface's **world-space** normal instead of shading it, so a
10155    /// modeller can see whether the normals a document carries are sane.
10156    ///
10157    /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
10158    /// is a tool's view of a document, and every sample and every golden image
10159    /// predates it. It takes effect on the next
10160    /// [`begin_frame`](Self::begin_frame), which is what writes the block.
10161    ///
10162    /// # What the colours mean
10163    ///
10164    /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
10165    /// green, +Z blue, and a face whose winding was inverted reads the
10166    /// **complement** of the colour it should have. A missing or degenerate
10167    /// normal reads as whatever the vertex data actually holds rather than as the
10168    /// plausible shading a light would have given it, which is the point.
10169    ///
10170    /// # World space, not view space
10171    ///
10172    /// The two diagnose different things and this one is world space, so a face
10173    /// keeps its colour while the camera orbits: "is this face inverted" is then
10174    /// something a modeller *sees*, instead of inferring it from a picture that
10175    /// re-colours whenever they move. View-space normals answer the other
10176    /// question — is this normal smooth, is this seam split — by re-colouring on
10177    /// purpose, and they are not a thing this block could express anyway: it
10178    /// carries `view_proj` and no separate view matrix, so there is no rotation in
10179    /// the shader to take a normal into eye space with.
10180    ///
10181    /// # It builds nothing and adds no pass
10182    ///
10183    /// Unlike the wireframe, which needs a second pipeline and so a device that
10184    /// can build one: this is one lane of the frame's uniform block — see
10185    /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
10186    /// stage every device already runs. There is nothing to refuse and nothing to
10187    /// release, which is why it cannot fail and there is no `supports_` probe
10188    /// beside it.
10189    ///
10190    /// The tonemap still applies: at
10191    /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
10192    /// is the identity on `0..=1` and the encoded normal reaches the swapchain
10193    /// exactly, and at any other exposure the picture is scaled per channel — so
10194    /// which channel dominates a face never changes, but a caller reading exact
10195    /// values wants [`set_exposure`](Self::set_exposure) left alone.
10196    ///
10197    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
10198    pub const fn set_normals_view(&mut self, on: bool) {
10199        self.normals_view = on;
10200    }
10201
10202    /// Sets the exponential height fog the colour pass composites over every
10203    /// shaded surface.
10204    ///
10205    /// Topic 43 §4's cheapest large win: distance
10206    /// reads as distance, a valley fills while a hilltop stays clear, and it
10207    /// costs four numbers in a block every pipeline already binds.
10208    ///
10209    /// # It adds no pass and cannot fail
10210    ///
10211    /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
10212    /// rows of the frame's uniform block, read by arithmetic in the fragment
10213    /// stage every device already runs. There is nothing to build, so there is
10214    /// nothing to refuse and no `supports_` probe beside it.
10215    ///
10216    /// # Off is exactly off
10217    ///
10218    /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
10219    /// not an approximate one: the optical depth is zero, its transmittance is
10220    /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
10221    /// rather than as a `lerp`, which at `t == 1` would return
10222    /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
10223    /// the fog colour. So this feature moves no frame it is not switched on
10224    /// for.
10225    ///
10226    /// # What it does not fog
10227    ///
10228    /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
10229    /// which arrive unfogged onto an already-fogged surface — see
10230    /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
10231    /// the reflection composite is one pass later.
10232    pub const fn set_fog(&mut self, fog: Fog) {
10233        self.fog = fog;
10234    }
10235
10236    /// Lights the scene with a gradient sky, on top of whatever ambient and
10237    /// irradiance grid it already has.
10238    ///
10239    /// Topic 43 §8's rung. [`Sky`] is three
10240    /// radiances — zenith, horizon, ground — and what reaches a surface is that
10241    /// gradient projected onto the L1 basis the probe grid already uses, so a
10242    /// surface facing up receives the sky and one facing down the ground's
10243    /// bounce. Three colours, no extra pass.
10244    ///
10245    /// # It adds no pass and cannot fail
10246    ///
10247    /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
10248    /// frame's uniform block and three dot products in a fragment stage every
10249    /// device already runs. Nothing to build, so nothing to refuse and no
10250    /// `supports_` probe beside it.
10251    ///
10252    /// # Off is exactly off
10253    ///
10254    /// [`Sky::NONE`] is the default and a black gradient projects to every
10255    /// coefficient zero — each is a product with a zero factor — so the
10256    /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
10257    /// before this existed, bit for bit.
10258    ///
10259    /// # What it does not do
10260    ///
10261    /// **Draw anything.** The background is still the scene target's clear
10262    /// colour, and a scene lit by a sky it cannot see is what this rung leaves
10263    /// behind until the pass that draws the gradient lands. The environment
10264    /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
10265    /// a mirror under a sky still reflects whatever the probes hold.
10266    pub const fn set_sky(&mut self, sky: Sky) {
10267        self.sky = sky;
10268    }
10269
10270    /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
10271    /// gradient back.
10272    ///
10273    /// Topic 43 §8. A frame with an atmosphere takes
10274    /// it for all three of the things a sky is: the background the sky pass
10275    /// draws, the L1 ambient term `mesh.slang` adds, and the environment
10276    /// `ssr.slang` falls back to when a ray hits nothing. The
10277    /// [`Sky`] a caller may also have set is not read on those frames.
10278    ///
10279    /// # What it costs
10280    ///
10281    /// **A march on the host, not on the device.** The first
10282    /// [`begin_frame`](Self::begin_frame) after this is called marches
10283    /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
10284    /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
10285    /// paid where it is asked for. Every later move of the sun is marched
10286    /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
10287    /// drawn, so no frame after the first pays the whole march;
10288    /// `refresh_sky_view` is where that is written down, including what a sun
10289    /// that moves *every* frame gets. A frame whose
10290    /// sun has not moved costs the comparison that finds nothing to do and
10291    /// nothing else: the LUT's two projections are cached beside it. The device
10292    /// pays four buffer loads and a blend, which is what the gradient pays.
10293    ///
10294    /// # Off is exactly off
10295    ///
10296    /// `None` is the default, and a renderer nobody calls this on writes the
10297    /// same block, adds the same passes and draws the same frame it did before
10298    /// this existed — `sky.slang`'s arm is
10299    /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
10300    ///
10301    /// # What it does not do
10302    ///
10303    /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
10304    /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
10305    /// pass already shades with, and pointing the two the same way is the
10306    /// caller's job.
10307    ///
10308    /// **Put the air in front of a surface.** That is the paper's third LUT and
10309    /// this engine's froxel column, and neither reads this.
10310    pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
10311        self.atmosphere = atmosphere;
10312    }
10313
10314    /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
10315    /// and this crate's `water` module for how.
10316    ///
10317    /// Replaces whatever was set before. Each body is meshed here, by
10318    /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
10319    /// slot as that slot next begins, so the call touches no device and a frame
10320    /// still in flight keeps the buffers it was submitted with. The first frame
10321    /// with a body builds each view's water passes — a hitch, cold, on that
10322    /// frame, which [`prepare_content`](Self::prepare_content) moves under a
10323    /// loading screen.
10324    ///
10325    /// # Off is exactly off
10326    ///
10327    /// An empty slice is the default, and a renderer with no bodies records no
10328    /// water pass at all: the frame it draws is the one it drew before this
10329    /// existed, bit for bit. Water is content, not a
10330    /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
10331    ///
10332    /// # Errors
10333    ///
10334    /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
10335    /// too few points, a non-finite coordinate, an outline that crosses itself,
10336    /// a negative coefficient — and then **nothing is replaced**: the bodies set
10337    /// before this call go on drawing.
10338    pub fn set_water(
10339        &mut self,
10340        bodies: &[crcbl_water::WaterBody],
10341    ) -> Result<(), crcbl_water::BodyError> {
10342        self.water.set(bodies)
10343    }
10344
10345    /// The bodies of water this renderer draws, as they were last set.
10346    #[must_use]
10347    pub fn water(&self) -> &[crcbl_water::WaterBody] {
10348        self.water.bodies()
10349    }
10350
10351    /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
10352    /// and G3, and this crate's `grass` module for how.
10353    ///
10354    /// Replaces whatever was set before. The field's ground, cover map, blade
10355    /// table and per-tile blocks are uploaded here, and the buffers a dispatch
10356    /// writes are created here; a field replaced while a frame is in flight
10357    /// leaves its resources alive until the ring has come round, so the call is
10358    /// safe at any point between frames. The field is drawn from the next
10359    /// [`begin_frame`](Self::begin_frame) on, which builds each view's grass
10360    /// passes the first time it sees one — a hitch, cold, on that frame, which
10361    /// [`prepare_content`](Self::prepare_content) moves under a loading screen.
10362    ///
10363    /// # Off is exactly off
10364    ///
10365    /// [`None`] is the default, and a renderer with no field records no grass
10366    /// pass at all: the frame it draws is the one it drew before this existed,
10367    /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
10368    /// [`set_water`](Self::set_water)'s terms.
10369    ///
10370    /// # Errors
10371    ///
10372    /// [`crate::grass::SetError::Field`] for a description the field itself
10373    /// refuses — no tiles, a zero texel scale, an empty blade table — and then
10374    /// **nothing is replaced**: the field set before this call goes on drawing.
10375    /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
10376    /// terms.
10377    pub fn set_grass(
10378        &mut self,
10379        device: &dyn Device,
10380        queue: QueueHandle,
10381        field: Option<&crate::grass::GrassField>,
10382    ) -> Result<(), crate::grass::SetError> {
10383        self.grass.set(device, queue, field)
10384    }
10385
10386    /// The field of grass this renderer draws, as it was last set.
10387    #[must_use]
10388    pub fn grass(&self) -> Option<&crate::grass::GrassField> {
10389        self.grass.field()
10390    }
10391
10392    /// Builds every view's water and grass passes for the bodies and the field
10393    /// set now, so the first frame that draws them does not.
10394    ///
10395    /// **Optional, and for a loading screen.** Without it the first frame with
10396    /// a body or a field builds them — a hitch, cold, on that frame. Called
10397    /// after [`set_water`](Self::set_water) and
10398    /// [`set_grass`](Self::set_grass) while a game is still loading, it pays
10399    /// the same compiles with `service` between them, on
10400    /// [`with_scene_serviced`](Self::with_scene_serviced)'s terms. A view that
10401    /// holds a pass already keeps it, and a view made after this call builds
10402    /// its own on its first frame with them.
10403    ///
10404    /// Between frames, on [`create_view`](Self::create_view)'s terms: it
10405    /// creates objects and records nothing.
10406    ///
10407    /// # Errors
10408    ///
10409    /// [`HalError`] from the device. The view that failed holds what it held
10410    /// before; the views before it keep what this call built them, which is
10411    /// what their next frame would have built.
10412    pub fn prepare_content(
10413        &mut self,
10414        device: &dyn Device,
10415        service: &mut dyn FnMut(),
10416    ) -> Result<(), HalError> {
10417        let water = !self.water.bodies().is_empty();
10418        let grass = self.grass.field().is_some();
10419        for view in std::iter::once(&mut self.primary).chain(self.views.iter_mut().flatten()) {
10420            view.build_content(device, water, grass, service)?;
10421        }
10422        Ok(())
10423    }
10424
10425    /// The two buffers the grass generation pass writes, or [`None`] for a
10426    /// renderer with no field.
10427    ///
10428    /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
10429    /// blade and to read each slot's instance count, on
10430    /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
10431    /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
10432    /// last frame that generated left there, which for a field nobody has drawn
10433    /// yet is undefined rather than empty.
10434    #[must_use]
10435    pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
10436        self.grass.buffers()
10437    }
10438
10439    /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
10440    /// as the GPU copy of the field samples them.
10441    ///
10442    /// [`None`] restores the calm placeholder: one texel of no deflection and
10443    /// one of zero intensity, which is what makes a field with no weather set
10444    /// stand still. A replaced pair waits for the ring exactly as a replaced
10445    /// field does, and like a field it is drawn from the next `begin_frame` on:
10446    /// the frame freezes its layers with its field.
10447    ///
10448    /// The new pair is uploaded in one batch that is **not waited for**, on
10449    /// the build's terms: `queue` must be the device's graphics queue, and
10450    /// the batch's staging is retired by a later `begin_frame`.
10451    ///
10452    /// # Errors
10453    ///
10454    /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
10455    /// texel of the grid it came with, a `queue` that is not the device's
10456    /// graphics queue, or a seam call that failed.
10457    pub fn set_wind_layers(
10458        &mut self,
10459        device: &dyn Device,
10460        queue: QueueHandle,
10461        layers: Option<&crate::grass::WindLayers>,
10462    ) -> Result<(), crate::grass::WindLayerError> {
10463        crcbl_frame::require_frame_queue(device, queue, "a forward renderer's wind layers")?;
10464        let pending = self.grass.set_wind_layers(device, queue, layers)?;
10465        self.uploads_in_flight.push(pending);
10466        Ok(())
10467    }
10468
10469    /// The wind's uniform block for the frames from here on —
10470    /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
10471    /// `f64` formula is narrowed to `f32`.
10472    ///
10473    /// Everything in it is camera-relative or already wrapped, so a caller
10474    /// writes it once per frame from the field's own state and never from a
10475    /// world-scale coordinate. The default is a base speed of zero, which is
10476    /// calm.
10477    pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
10478        self.wind = params;
10479    }
10480
10481    /// The wind block this renderer writes, as it was last set.
10482    #[must_use]
10483    pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
10484        self.wind
10485    }
10486
10487    /// The atmosphere this renderer draws, if it has one.
10488    #[must_use]
10489    pub const fn atmosphere(&self) -> Option<Atmosphere> {
10490        self.atmosphere
10491    }
10492
10493    /// Draws each cluster tinted by the DAG level it was decimated to, instead
10494    /// of shading it.
10495    ///
10496    /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
10497    /// several levels across its own surface is a statement a test can assert
10498    /// and nobody can see, and this is what makes it visible. The mesh path
10499    /// tints per cluster; the two indirect paths select one level per instance
10500    /// and have no per-cluster level at all, so they draw one flat grey — which
10501    /// is the comparison rather than a shortfall.
10502    ///
10503    /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
10504    /// of the frame's uniform block, read by a branch every device already runs.
10505    /// Nothing to build, nothing to refuse, nothing to release.
10506    ///
10507    /// **Wins over the normals view when both are on**, because the two share a
10508    /// lane and the fragment stage tests this one first.
10509    pub const fn set_lod_view(&mut self, on: bool) {
10510        self.lod_view = on;
10511    }
10512
10513    /// Whether the colour pass tints clusters by their DAG level.
10514    ///
10515    /// **What was asked for, not what is drawn.** The three debug views share
10516    /// one lane and resolve in one order, so a renderer with this and
10517    /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
10518    /// answers `true` here — the caller's setting is what a caller's toggle has
10519    /// to read back, and [`debug_view`](Self::debug_view) is what says which one
10520    /// the frame actually took.
10521    #[must_use]
10522    pub const fn lod_view(&self) -> bool {
10523        self.lod_view
10524    }
10525
10526    /// Shades each cluster by the **projected screen-space error** the LOD
10527    /// selection judged it on, instead of shading it.
10528    ///
10529    /// The LOD tint's sibling, and the other half of topic 25's
10530    /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
10531    /// looking at", and this answers "how close to the budget is this, and where
10532    /// is the selection about to switch". The number is the one
10533    /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
10534    /// cluster's *producing* group's error, projected from this frame's eye at
10535    /// this frame's pixels per unit.
10536    ///
10537    /// # What the colours mean
10538    ///
10539    /// A ramp that climbs in luminance from a cold floor to white, with a hue
10540    /// break at each of the two budgets: the hold budget where the hysteresis
10541    /// band starts, and the expand budget at the top, which is white. So the two
10542    /// budgets draw themselves as contour lines across the surface, and
10543    /// "brighter is closer to switching" reads even in a greyscale screenshot.
10544    /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
10545    /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
10546    /// to being readable as an ordering.
10547    ///
10548    /// A cluster nothing simplified — the original surface, at the bottom of the
10549    /// DAG — costs exactly zero and takes the ramp's floor.
10550    ///
10551    /// # Mesh path only, and that is the capability rather than a shortfall
10552    ///
10553    /// A per-cluster error exists only where selection is per cluster.
10554    /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
10555    /// choose one level per *instance*, so there is no per-cluster number for
10556    /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
10557    /// the LOD tint gets. Standing the two beside each other is the comparison.
10558    ///
10559    /// # It builds nothing and adds no pass
10560    ///
10561    /// One lane of the frame's uniform block, on
10562    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
10563    /// storage-buffer read in the mesh stage, which the mesh path's layout
10564    /// already carries. Nothing to build, nothing to refuse, nothing to release.
10565    ///
10566    /// **Wins over both the LOD tint and the normals view when several are on**;
10567    /// see [`debug_view`](Self::debug_view), which is that order stated once.
10568    ///
10569    /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
10570    /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
10571    pub const fn set_heatmap(&mut self, on: bool) {
10572        self.heatmap = on;
10573    }
10574
10575    /// Whether the colour pass shades clusters by their projected error.
10576    ///
10577    /// **What was asked for, not what is drawn**, on
10578    /// [`lod_view`](Self::lod_view)'s terms.
10579    #[must_use]
10580    pub const fn heatmap(&self) -> bool {
10581        self.heatmap
10582    }
10583
10584    /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10585    ///
10586    /// One is white and fully occluded is black — the buffer the forward pass
10587    /// multiplies its ambient term by, shown as itself. **This is how the AO
10588    /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10589    /// composited frame shows occlusion times albedo times ambient, and a
10590    /// difference in the first is not separable from a difference in the other
10591    /// two by looking at the result.
10592    ///
10593    /// # What it draws with occlusion switched off
10594    ///
10595    /// White, everywhere. A frame without
10596    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10597    /// a computed channel, and this view shows that image rather than pretending
10598    /// to a channel nothing computed — "no occlusion was computed" and "nothing
10599    /// occludes here" are the same value to the shading, and the view does not
10600    /// get to disagree with the shading about it.
10601    ///
10602    /// # It builds nothing and adds no pass
10603    ///
10604    /// One lane of the frame's uniform block, on
10605    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10606    /// tint and the heatmap it needs nothing from the geometry stage, so it
10607    /// draws on every [`GeometryPath`] rather than on
10608    /// the mesh-shader one alone.
10609    ///
10610    /// **Wins over every other view when several are on**; see
10611    /// [`debug_view`](Self::debug_view), which is that order stated once.
10612    pub const fn set_occlusion_view(&mut self, on: bool) {
10613        self.occlusion_view = on;
10614    }
10615
10616    /// Whether the colour pass draws the occlusion channel instead of shading.
10617    ///
10618    /// **What was asked for, not what is drawn**, on
10619    /// [`lod_view`](Self::lod_view)'s terms.
10620    #[must_use]
10621    pub const fn occlusion_view(&self) -> bool {
10622        self.occlusion_view
10623    }
10624
10625    /// Draws each fragment's motion vector instead of shading it.
10626    ///
10627    /// The two components are stretched by
10628    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10629    /// on grey, into red and green, with blue left at zero. A pixel at rest is
10630    /// grey in both channels to within one half-float step —
10631    /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10632    /// not exactly — and a surface travelling right and down the screen
10633    /// brightens both.
10634    ///
10635    /// # It is the motion-vector target's only reader today
10636    ///
10637    /// The forward pass writes a motion vector into a third colour attachment on
10638    /// every frame — see [`crate::targets::motion`] — and no pass reads it
10639    /// yet; TAA (`docs/backlog.md`) is the first that will. This
10640    /// view is therefore what says the subtraction behind it is the right one,
10641    /// which is why it exists ahead of a consumer.
10642    ///
10643    /// # It builds nothing and adds no pass
10644    ///
10645    /// One lane of the frame's uniform block, on
10646    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10647    /// the occlusion view it needs nothing from the geometry stage that a
10648    /// shaded frame does not already produce — so it draws on every
10649    /// [`GeometryPath`].
10650    ///
10651    /// **Wins over every other view when several are on**; see
10652    /// [`debug_view`](Self::debug_view), which is that order stated once.
10653    pub const fn set_motion_view(&mut self, on: bool) {
10654        self.motion_view = on;
10655    }
10656
10657    /// Whether the colour pass draws the motion vector instead of shading.
10658    ///
10659    /// **What was asked for, not what is drawn**, on
10660    /// [`lod_view`](Self::lod_view)'s terms.
10661    #[must_use]
10662    pub const fn motion_view(&self) -> bool {
10663        self.motion_view
10664    }
10665
10666    /// Draws the occlusion channel's **bent direction** instead of shading.
10667    ///
10668    /// The three channels beside the visibility scalar, passed through as the
10669    /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10670    /// +Z blue, which is the mapping
10671    /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10672    /// normal. A fragment the occlusion pass had no direction for reads as the
10673    /// mid grey the zero sentinel encodes to.
10674    ///
10675    /// # What it is for
10676    ///
10677    /// The bent direction is what the ambient term is sampled *along*, and a
10678    /// composited frame cannot show it: ambient times albedo times a
10679    /// direction-dependent irradiance is one colour, and a direction that is
10680    /// subtly wrong looks like a lighting choice. This draws the direction
10681    /// alone, which is how a corner that leans the wrong way out of its own
10682    /// wall is a thing a reviewer sees rather than infers.
10683    ///
10684    /// # What it draws with occlusion switched off
10685    ///
10686    /// Mid grey, everywhere. A frame without
10687    /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10688    /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10689    /// three channels, and this view shows that image rather than pretending to
10690    /// a direction nothing computed — which is the same answer the shading
10691    /// takes, since `mesh.slang` reads that sentinel as "use the shading
10692    /// normal".
10693    ///
10694    /// # It builds nothing and adds no pass
10695    ///
10696    /// One lane of the frame's uniform block, on
10697    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10698    /// the occlusion view it needs nothing from the geometry stage — so it
10699    /// draws on every [`GeometryPath`].
10700    ///
10701    /// **Wins over every other view when several are on**; see
10702    /// [`debug_view`](Self::debug_view), which is that order stated once.
10703    pub const fn set_bent_normal_view(&mut self, on: bool) {
10704        self.bent_normal_view = on;
10705    }
10706
10707    /// Whether the colour pass draws the bent direction instead of shading.
10708    ///
10709    /// **What was asked for, not what is drawn**, on
10710    /// [`lod_view`](Self::lod_view)'s terms.
10711    #[must_use]
10712    pub const fn bent_normal_view(&self) -> bool {
10713        self.bent_normal_view
10714    }
10715
10716    /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10717    /// shadow was sampled from.
10718    ///
10719    /// Topic 45's eighth decision made the cascade switch a
10720    /// band rather than a step, and this is the picture that band is judged in:
10721    /// each fragment's shading multiplied by
10722    /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10723    /// selected, and inside the band by the *blend* of the two — the same weight
10724    /// the visibility itself was mixed with. So the boundary reads as a
10725    /// gradient, and a seam where two cascades disagree shows up as a step in
10726    /// the gradient rather than as a ring somebody has to already suspect.
10727    ///
10728    /// # It keeps the shaded picture, which is why it loses to every other view
10729    ///
10730    /// Every other view replaces the frame; this one multiplies it, so the geometry
10731    /// stays readable underneath and the shadow the cascades produced is still
10732    /// in the picture being coloured. That is also what puts it last in
10733    /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10734    /// is no shading left for a tint to reach.
10735    ///
10736    /// # What it draws where no cascade covers a fragment
10737    ///
10738    /// Nothing at all —
10739    /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10740    /// A surface facing away from the sun and one past the last cascade's reach
10741    /// are both that, because neither was sampled through a cascade, and a
10742    /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10743    /// white everywhere for the same reason. Colouring those would be inventing
10744    /// a cascade for a pixel no map covers.
10745    ///
10746    /// # It builds nothing and adds no pass
10747    ///
10748    /// One lane of the frame's uniform block, on
10749    /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10750    /// the occlusion view it needs nothing from the geometry stage — so it draws
10751    /// on every [`GeometryPath`].
10752    pub const fn set_cascade_view(&mut self, on: bool) {
10753        self.cascade_view = on;
10754    }
10755
10756    /// Whether the colour pass tints the picture by the sun's cascades.
10757    ///
10758    /// **What was asked for, not what is drawn**, on
10759    /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10760    /// case rather than the corner one: this view loses to every other one, so a
10761    /// renderer with any of them also on answers `true` here and draws that one.
10762    #[must_use]
10763    pub const fn cascade_view(&self) -> bool {
10764        self.cascade_view
10765    }
10766
10767    /// Draws the **shadow atlas itself** over the finished frame: the
10768    /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10769    /// each texel's stored depth as a grey and a border round every occupied
10770    /// slot.
10771    ///
10772    /// Sundial's atlas viewer, and the answer to a
10773    /// question no other view can be asked: which slot holds which map, and
10774    /// which slots hold nothing. A tile that was never rendered into, or
10775    /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10776    /// produces is plausible and every golden blessed from it passes. Here it is
10777    /// a rectangle that is visibly empty.
10778    ///
10779    /// # It is a pass, and it is the only debug view that is
10780    ///
10781    /// Every other view rides in one lane of the frame's uniform block and is a
10782    /// branch in `mesh.slang`, because every other view is a function of the
10783    /// fragment being shaded. The atlas is not: it is one image the whole frame
10784    /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10785    /// the frame instead — after the tonemap, in display space, for that
10786    /// module's reason — and the frame block is byte-identical either way.
10787    ///
10788    /// # Where it resolves, and what it costs when it is off
10789    ///
10790    /// Below every replacing view and above
10791    /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10792    /// [`debug_view`](Self::debug_view), which is that order stated once. A
10793    /// frame that resolved anything else records **no pass**, no pipeline bind
10794    /// and no block read, which is what makes the off position bit-identical on
10795    /// `crate::sky_pass`'s terms.
10796    pub const fn set_atlas_view(&mut self, on: bool) {
10797        self.atlas_view = on;
10798    }
10799
10800    /// Whether the frame draws the shadow atlas over the picture.
10801    ///
10802    /// **What was asked for, not what is drawn**, on
10803    /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10804    /// also on answers `true` here and draws that one.
10805    #[must_use]
10806    pub const fn atlas_view(&self) -> bool {
10807        self.atlas_view
10808    }
10809
10810    /// Pins the eye topic 25's selection is projected from, so the
10811    /// cut stops following the camera.
10812    ///
10813    /// [`None`] is the default and means "the camera's own eye", which is what
10814    /// every frame before this existed did. `Some(eye)` selects detail for a
10815    /// viewer standing at `eye` while the frame is still drawn, culled and lit
10816    /// from wherever the camera actually is.
10817    ///
10818    /// # What it is for
10819    ///
10820    /// Per-cluster LOD is only checkable from somewhere other than the point
10821    /// that chose it. Looked at from the selecting eye, a cut that is far too
10822    /// coarse and a cut that is exactly right produce the same silhouette —
10823    /// that is what a screen-space error budget *means* — so the one viewpoint
10824    /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10825    /// judged from. Pin the eye and fly away from it, and the boundaries between
10826    /// levels become geometry a reviewer can walk up to and look at edge-on.
10827    ///
10828    /// # Only the selection freezes
10829    ///
10830    /// The frame has three places a viewer position is read, and this moves
10831    /// exactly one of them:
10832    ///
10833    /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10834    ///   `DrawGenParams::camera_position` and is the only thing that decides the
10835    ///   cut. It writes the group hysteresis state that the mesh path's
10836    ///   amplification stage then descends, so freezing this one field freezes
10837    ///   the cut on the per-cluster path and the two indirect paths alike. This
10838    ///   is what moves.
10839    /// * **the frustum culls** — `cull.slang`'s instance test and
10840    ///   `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10841    ///   the frame's own view-projection and never read a camera position at
10842    ///   all. Unaffected, and it has to be: a frame culled against a frustum the
10843    ///   reviewer has flown out of would draw nothing.
10844    /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10845    ///   reads [`FrameUniforms::camera_position`] and asks which way a cluster
10846    ///   faces *relative to the viewer*. That question is about the eye the
10847    ///   picture is drawn from, not the eye it was selected for; frozen, a
10848    ///   reviewer who flew round to the other side of the face would have every
10849    ///   cluster now facing them rejected for facing away from a viewpoint
10850    ///   nobody is standing at. It stays live.
10851    ///
10852    /// The split is not new. `DrawGenParams::camera_position` and
10853    /// [`FrameUniforms::camera_position`] are already separate fields carrying
10854    /// different values on a shadow cascade — that one holds the sun while this
10855    /// one stays the camera, because detail is denominated in the camera's
10856    /// pixels and facing is asked about the light. This freezes the same seam
10857    /// from the other side, and needs no new binding, no new shader input and no
10858    /// shader change of any kind.
10859    ///
10860    /// # It freezes the cascades' selection too
10861    ///
10862    /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10863    /// cascade's draw generator, because a cascade selects detail for the
10864    /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10865    /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10866    /// is a difference in the picture that belongs to neither.
10867    ///
10868    /// # The heatmap reads the live eye, and says so
10869    ///
10870    /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10871    /// group's projected error, computed in the mesh stage from
10872    /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10873    /// frozen selection the two overlays answer different questions: the cut is
10874    /// the one chosen at the pinned eye, and the heat is what the error would be
10875    /// if it were chosen from here now. That is readable — flying towards the
10876    /// face brightens the clusters the frozen cut is not refining, which is the
10877    /// selection's sensitivity made visible — but it does mean the ramp's
10878    /// contours stop coinciding with the level boundaries while frozen.
10879    /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10880    /// unconditionally: a cluster's level is a property of the cut and of
10881    /// nothing else.
10882    ///
10883    /// Carrying the pinned eye into the mesh stage as well would need a second
10884    /// position in the frame block, which is a new shader input in every backend
10885    /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10886    ///
10887    /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10888    pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10889        self.frozen_selection_eye = eye;
10890    }
10891
10892    /// Where the selection is pinned, or [`None`] while it follows the camera.
10893    ///
10894    /// The read-back half of
10895    /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10896    /// debug panel says "frozen at" out of — "frozen" without the position is a
10897    /// row nobody can act on.
10898    #[must_use]
10899    pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10900        self.frozen_selection_eye
10901    }
10902
10903    /// Which of the debug views the next frame will actually draw.
10904    ///
10905    /// **The one place the precedence is decided**, and every other statement of
10906    /// it in this crate reads it back from here. The switches ride in one float
10907    /// lane of the frame block — see
10908    /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10909    /// — and the shaders test the outermost threshold first, so a sentinel for
10910    /// an outer view clears every threshold below it. Resolving here rather than
10911    /// letting each caller guess is what stops "which view is on" being answered
10912    /// differently by a menu row, a debug panel and the picture.
10913    #[must_use]
10914    pub const fn debug_view(&self) -> DebugView {
10915        if self.bent_normal_view {
10916            DebugView::BentNormal
10917        } else if self.motion_view {
10918            DebugView::Motion
10919        } else if self.occlusion_view {
10920            DebugView::AmbientOcclusion
10921        } else if self.heatmap {
10922            DebugView::Heatmap
10923        } else if self.lod_view {
10924            DebugView::LodTint
10925        } else if self.normals_view {
10926            DebugView::Normals
10927        } else if self.atlas_view {
10928            // **Below every view above it, and above the tint below.**
10929            //
10930            // Below, because every branch before this one is a question about
10931            // the *picture* — a cluster's error, a surface's normal, the
10932            // occlusion channel — and this one is not a picture of the scene at
10933            // all. A caller who left the atlas up and then asked for normals has
10934            // asked to look at the frame again, and the frame is what the branch
10935            // above draws; the atlas is one keystroke away and is not lost by
10936            // being deferred to.
10937            //
10938            // Above, because the cascade tint multiplies the shaded picture and
10939            // this replaces it: a tint on a frame the atlas overwrote would be a
10940            // tint on the atlas, which is a colour standing for nothing.
10941            DebugView::ShadowAtlas
10942        } else if self.cascade_view {
10943            // **Innermost, and the only view that sits below the others rather
10944            // than above them.** Every branch before this one draws something
10945            // *instead of* the shaded picture and returns before the shading; a
10946            // cascade tint is a multiply on that shading, so there is nothing
10947            // for it to modulate while one of them is showing and a caller with
10948            // both on has asked for the picture the outer one draws. The lane
10949            // says the same thing from the other end — the cascade sentinel is
10950            // negative, so it clears none of the shaders' thresholds — and
10951            // `crcbl_shaders`'
10952            // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10953            // what holds that half.
10954            DebugView::Cascades
10955        } else {
10956            DebugView::Shaded
10957        }
10958    }
10959
10960    /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10961    /// carries.
10962    const fn debug_view_lane(&self) -> f32 {
10963        match self.debug_view() {
10964            DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10965            DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10966            DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10967            DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10968            DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10969            DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10970            DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10971            // **The off sentinel, and it is not an omission.** This view is a
10972            // pass rather than a branch in `mesh.slang` — see
10973            // [`crate::atlas_view`] — so the colour pass draws exactly the
10974            // shaded picture it always drew and the pass afterwards replaces it.
10975            // A lane of its own would be a threshold no shader tests.
10976            DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10977        }
10978    }
10979
10980    /// Whether the colour pass draws world-space normals instead of shading.
10981    ///
10982    /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10983    /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10984    /// is about.
10985    #[must_use]
10986    pub const fn normals_view(&self) -> bool {
10987        self.normals_view
10988    }
10989
10990    /// The cull and draw-argument passes, and the buffers they produce.
10991    ///
10992    /// What a caller reads the culling statistics out of — topic 03 §3.6's
10993    /// delayed readback ring is [`DrawGen::visible_count`] — and what
10994    /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10995    /// arguments against the draws this pass used to record itself.
10996    #[must_use]
10997    pub const fn draws(&self) -> &DrawGen {
10998        &self.primary.draws
10999    }
11000
11001    /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
11002    /// and the exposure the reduce wrote out of them.
11003    ///
11004    /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
11005    /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
11006    /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
11007    /// there, so a frame drawn without
11008    /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
11009    /// hands back the frame before it rather than nothing.
11010    ///
11011    /// # Panics
11012    ///
11013    /// If `frame` is not a slot this renderer was built with.
11014    #[must_use]
11015    pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
11016        self.primary.auto_exposure.buffers(frame)
11017    }
11018
11019    /// `frame`'s froxel column: the buffers the froxel volume's
11020    /// three passes write, and the block they read.
11021    ///
11022    /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
11023    /// froxel against `crcbl_shaders::volumetric`, on
11024    /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
11025    ///
11026    /// # Panics
11027    ///
11028    /// If `frame` is not a slot this renderer was built with.
11029    #[must_use]
11030    pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
11031        self.primary.volumetric.buffers(frame)
11032    }
11033
11034    /// The three layers a caller supplies to the toggle resolution order — see
11035    /// [`crate::effects`].
11036    ///
11037    /// Read back rather than only written, so a caller changing one layer does
11038    /// not have to remember the other two: take this, edit the field it owns,
11039    /// hand it back to [`set_effect_request`](Self::set_effect_request).
11040    #[must_use]
11041    pub const fn effect_request(&self) -> EffectRequest {
11042        self.effect_request
11043    }
11044
11045    /// Replaces all three requested layers, and resolves them at the next
11046    /// [`begin_frame`](Self::begin_frame).
11047    ///
11048    /// **The frame in flight does not move.** `begin_frame` freezes what it
11049    /// resolved and [`add_passes`](Self::add_passes) records that, because the
11050    /// two halves of a frame have to agree about which culls were parametrised:
11051    /// `begin_frame` skips a shadow cull's parameter write when shadows are off
11052    /// and `add_passes` skips its dispatch, and a request landing between the two
11053    /// would dispatch a cull against numbers nothing zeroed.
11054    pub const fn set_effect_request(&mut self, request: EffectRequest) {
11055        self.effect_request = request;
11056    }
11057
11058    /// Replaces the **camera** layer with what `stack` asks for, and leaves the
11059    /// other three where they are.
11060    ///
11061    /// The file half of [`crate::stack`] reaching the renderer: a view that has
11062    /// a render stack writes it here, and the player's `[engine.video]` clamp,
11063    /// the antialiasing rung they picked and any programmatic override are
11064    /// untouched — which is the property that makes the four layers four rather
11065    /// than one. A caller that wants to move more than this layer builds an
11066    /// [`EffectRequest`] and uses
11067    /// [`set_effect_request`](Self::set_effect_request).
11068    ///
11069    /// **The frame in flight does not move**, on `set_effect_request`'s terms
11070    /// and for its reason: this writes the request and
11071    /// [`begin_frame`](Self::begin_frame) is what resolves it.
11072    pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
11073        self.effect_request.camera = stack.compile();
11074    }
11075
11076    /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
11077    ///
11078    /// The resolved set, not a layer: every effect in it has survived the
11079    /// camera's stack, the player's quality clamp, any programmatic override and
11080    /// the device — which is the one question a test asking "did this frame have
11081    /// shadows in it" wants answered.
11082    ///
11083    /// [`RenderEffects::all`] before the first frame, which is what a renderer
11084    /// nobody has changed would draw.
11085    #[must_use]
11086    pub const fn effects(&self) -> RenderEffects {
11087        self.frame_effects
11088    }
11089
11090    /// What a frame begun **now** would draw: the whole order applied to the
11091    /// current request.
11092    ///
11093    /// [`effects`](Self::effects)' question one frame earlier, and the one a
11094    /// caller reporting its own configuration wants — a debug panel built at
11095    /// startup has no frame behind it yet, and printing what the last one drew
11096    /// would print a default.
11097    ///
11098    /// **A debug view takes the antialiasing resolve off** — either tier of it
11099    /// — whatever the four layers said. Those views are readouts rather than
11100    /// pictures — a pixel's colour *is* the cluster's projected error or its
11101    /// DAG level, read back against a legend — and a filter that blends two
11102    /// clusters' shades invents a ramp position no cluster occupies.
11103    /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
11104    /// frame's distinct colours.
11105    #[must_use]
11106    pub fn resolved_effects(&self) -> RenderEffects {
11107        let resolved = self.effect_request.resolve(self.device_effects);
11108        if matches!(self.debug_view(), DebugView::Shaded) {
11109            resolved
11110        } else {
11111            // **Both tiers**, because the slot is what a readout cannot have
11112            // rather than one filter in particular.
11113            resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
11114        }
11115    }
11116
11117    /// Which tonemap operator the next frame runs:
11118    /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
11119    /// the clamp for a readout.
11120    ///
11121    /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
11122    /// operator instead of to the resolve.** A debug view's pixels *are* data —
11123    /// an encoded normal, an occlusion channel, a cascade's colour code — and a
11124    /// curve is a monotone remapping of every one of them. `apps/alcove`'s
11125    /// `--bent-view` reads a normal back and compares it against the geometry's
11126    /// own, which under ACES is 49 code values out; the clamp is the identity on
11127    /// `0..=1`, so it is the operator that leaves a readout readable. A caller
11128    /// that wants a curved readout has none, deliberately: there is no reading
11129    /// it would make easier.
11130    #[must_use]
11131    pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
11132        if matches!(self.debug_view(), DebugView::Shaded) {
11133            self.tonemap_curve
11134        } else {
11135            tonemap::TonemapCurve::Clamp
11136        }
11137    }
11138
11139    /// Which effects this **device** permits, which is the fourth layer and
11140    /// clamps last.
11141    ///
11142    /// Every one of them today — see [`ForwardRenderer::device_effects`], which
11143    /// is where that is argued per effect rather than asserted.
11144    #[must_use]
11145    pub const fn device_effects(&self) -> RenderEffects {
11146        self.device_effects
11147    }
11148
11149    /// Which [`GeometryPath`] this renderer was **built for** — not what the
11150    /// device reports, but what it actually built.
11151    ///
11152    /// The device may prefer a path below its capability ceiling when a higher
11153    /// one uses emulation. This reports the preference actually built, rather
11154    /// than the ceiling: [`GeometryPath::MeshShader`] here means
11155    /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
11156    /// cluster buffers, and created **no** raster pipeline for the pass to fall
11157    /// back to. So a frame this renderer drew came out of a mesh stage, and a
11158    /// silent degradation is not a state it has — which is the claim a golden
11159    /// image on its own could never make, because a fall-through draws the same
11160    /// picture.
11161    #[must_use]
11162    pub const fn geometry_path(&self) -> GeometryPath {
11163        match self.emit {
11164            EmitTail::Mesh => GeometryPath::MeshShader,
11165            EmitTail::Count => GeometryPath::IndirectCount,
11166            EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
11167        }
11168    }
11169
11170    /// Whether this renderer **built** §3.5's per-cluster cull — an
11171    /// amplification stage in front of the mesh stage, rejecting a surviving
11172    /// instance's back-facing and off-screen clusters.
11173    ///
11174    /// `false` on the two indirect tails, which draw index ranges and have no
11175    /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
11176    /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
11177    /// that device draws every cluster of every surviving instance and the
11178    /// picture is the same one.
11179    ///
11180    /// The instance cull runs on every path either way, and is unaffected by
11181    /// this.
11182    ///
11183    /// It is asked of the renderer rather than of the device for
11184    /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
11185    /// built, so `true` means
11186    /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
11187    /// cluster word is a number the frame produced rather than the zero the
11188    /// clearing pass left.
11189    #[must_use]
11190    pub const fn culls_clusters(&self) -> bool {
11191        self.culls_clusters
11192    }
11193
11194    /// Whether this renderer can choose **which level** of a
11195    /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
11196    /// [`ForwardRenderer::add_instance`] may be given one at all.
11197    ///
11198    /// Topic 25's selection happens in the amplification stage where
11199    /// there is one, and in the cull pass where the tail is indirect and a level
11200    /// is an ordinary index range. **One device shape has neither**: a mesh stage
11201    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
11202    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
11203    /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
11204    /// of the bucket — and a DAG's bucket is every level end to end, so the frame
11205    /// is several overlapping copies of one surface. That is a real and supported
11206    /// device state rather than a degradation, so this reports it instead of
11207    /// refusing to build.
11208    ///
11209    /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
11210    /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
11211    /// which is why this is asked only before placing a DAG.
11212    ///
11213    /// Asked of the renderer rather than of the device for
11214    /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
11215    ///
11216    /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
11217    #[must_use]
11218    pub const fn selects_levels(&self) -> bool {
11219        !self.emit.is_mesh() || self.culls_clusters
11220    }
11221
11222    /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
11223    /// rotated to, which is the slot every per-frame buffer is indexed by.
11224    #[must_use]
11225    pub const fn frame(&self) -> usize {
11226        self.frame
11227    }
11228
11229    /// What the last [`add_passes`](Self::add_passes) recorded, and what it
11230    /// cannot know.
11231    ///
11232    /// Zero draws until a frame has been built: this reports what was recorded,
11233    /// not what a frame would record.
11234    ///
11235    /// # The triangles are [`None`] here, on every geometry path
11236    ///
11237    /// Every draw this renderer records except the full-screen passes' and the
11238    /// debug draw layer's is **indirect**:
11239    /// the instance count and the index range live in the argument buffer
11240    /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
11241    /// about what it covered. That is true of
11242    /// [`GeometryPath::MeshShader`] and of
11243    /// both indirect tails alike — the three differ in which call is recorded,
11244    /// not in who decides the counts — so
11245    /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
11246    /// is [`None`] whatever the device supports. Nothing counts a triangle on
11247    /// the GPU either, and a cluster count times a nominal triangles-per-cluster
11248    /// would read as authoritative and be neither.
11249    ///
11250    /// # The instances drawn come back off the GPU, a few frames late
11251    ///
11252    /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
11253    /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
11254    /// plus the frame's direct draws — the ones here whose instance the CPU
11255    /// knows about, and the ones that are also in
11256    /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
11257    /// comparable: the same quantity submitted and kept.
11258    ///
11259    /// **The camera's cull alone.** The shadow culls test other frustums and
11260    /// their survivors are counted into buffers of their own; adding them here
11261    /// would give a "drawn" larger than "submitted" on any frame with a shadow
11262    /// in it.
11263    ///
11264    /// It is [`None`] — the row says `indirect` — for the first few frames of a
11265    /// renderer's life, while the ring has not come round, and for good on a
11266    /// device that would not give out a readback.
11267    /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
11268    /// the number is about whenever there is one.
11269    ///
11270    /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
11271    /// is known and is the plan's "submitted" half: the live instances
11272    /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
11273    /// frame's direct draws — every full-screen pass's triangle and the debug
11274    /// draw layer's line list.
11275    #[must_use]
11276    pub fn counters(&self) -> FrameCounters {
11277        if self.recorded_draws == 0 {
11278            return FrameCounters::default();
11279        }
11280        let stats = self.cull_stats();
11281        let direct = self.direct_draws();
11282        FrameCounters {
11283            draws: self.recorded_draws,
11284            instances: self.instances.len() as u64 + direct,
11285            // Each direct draw is submitted and drawn, and none of them is in
11286            // the cull's count — they are draws of one instance, added on both
11287            // sides so the two halves of the row measure the same thing. Off the
11288            // frame that *was* recorded rather than off a constant, so a frame
11289            // with an effect switched off does not count a triangle it never
11290            // submitted.
11291            // Less what the occlusion cull's second phase rejected, which were
11292            // survivors of the frustum and were not drawn.
11293            drawn: stats
11294                .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
11295            triangles: None,
11296            // The survivors alone: the panel row is "clusters drawn", and the
11297            // frustum and cone rejection counts beside them are a different
11298            // question — `CullStats::clusters` carries all three for a caller
11299            // that wants the split, which `apps/quarry`'s own panel row is.
11300            clusters: stats
11301                .and_then(|stats| stats.clusters)
11302                .map(|cull| cull.survivors),
11303            cull_frame: stats.map(|stats| stats.frame),
11304        }
11305    }
11306
11307    /// The draws this renderer records **directly** — the ones whose instance
11308    /// the CPU knows about, as opposed to the indirect calls whose counts live
11309    /// in a buffer a shader wrote.
11310    ///
11311    /// Every full-screen pass's over-sized triangle, plus the debug draw
11312    /// layer's line list on a frame that has one. One instance each, which is
11313    /// why [`counters`](Self::counters) adds this to both halves of its
11314    /// submitted/drawn pair.
11315    fn direct_draws(&self) -> u64 {
11316        self.recorded_fullscreen * FULLSCREEN_DRAWS
11317            + self.recorded_debug_draw
11318            + self.recorded_tile_clears
11319            + self.recorded_water_draws
11320    }
11321
11322    /// What the camera's cull kept, on the frame the ring has reached.
11323    ///
11324    /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
11325    /// round — see [`crate::cull_stats`] for the latency and for what makes it
11326    /// free of any wait. [`counters`](Self::counters) is where this reaches the
11327    /// panel; it is exposed on its own because the frame number and the cluster
11328    /// word are both things a test asserts about directly.
11329    #[must_use]
11330    pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
11331        self.cull_stats.as_ref().and_then(CullStatsRing::latest)
11332    }
11333
11334    /// Describes the imported swapchain image the frame ends in.
11335    ///
11336    /// A helper rather than something every caller writes, because getting
11337    /// `initial`/`final_state` wrong is exactly the hand-written barrier this
11338    /// slice removed: an acquired image's contents are undefined, and the
11339    /// compositor may only be handed one in [`ResourceState::Present`].
11340    #[must_use]
11341    pub fn present_target(
11342        image: crcbl_hal::ImageHandle,
11343        view: ImageViewHandle,
11344        format: Format,
11345        extent: (u32, u32),
11346    ) -> ImportedImage {
11347        ImportedImage {
11348            image,
11349            view,
11350            format,
11351            extent,
11352            initial: ResourceState::Undefined,
11353            // The acquire's semaphore, not a barrier, is what orders this frame
11354            // after the last use of the image — which is what makes `Undefined`
11355            // honest here and what makes it uncheckable. See `InitialClaim`.
11356            claim: InitialClaim::Acquired,
11357            final_state: ResourceState::Present,
11358        }
11359    }
11360
11361    /// Releases everything, in dependency order. The device must be idle.
11362    ///
11363    /// The start-up uploads are waited for first all the same: a renderer
11364    /// destroyed before any frame has a build batch nothing else has waited
11365    /// for, and its copies write the placeholders and fills released below.
11366    pub fn destroy(mut self, device: &dyn Device) {
11367        self.wait_for_uploads(device, "destroy");
11368        if let Some(stats) = self.cull_stats {
11369            stats.destroy(device);
11370        }
11371        // The cameras first: their groups name the scene's buffers, pages and
11372        // atlas below, and they own nothing the scene's groups name.
11373        for view in self.views.into_iter().flatten() {
11374            view.destroy(device);
11375        }
11376        self.primary.destroy(device);
11377        // After every view, whose grass and water groups name these buffers.
11378        self.grass.destroy(device);
11379        self.water.destroy(device);
11380        device.destroy_sampler(self.sampler);
11381        device.destroy_graphics_pipeline(self.tonemap_pipeline);
11382        device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
11383        device.destroy_bind_group_layout(self.tonemap_layout);
11384
11385        let depth_and_rsm = [
11386            Some(self.shadow_pipeline),
11387            self.depth_masked_pipeline,
11388            self.rsm_pipeline,
11389        ];
11390        for pipeline in depth_and_rsm
11391            .into_iter()
11392            .flatten()
11393            .flat_map(SidedPipelines::handles)
11394        {
11395            device.destroy_graphics_pipeline(pipeline);
11396        }
11397        device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
11398        for groups in self.shadow_groups {
11399            for group in groups {
11400                device.destroy_bind_group(group);
11401            }
11402        }
11403        for buffers in self.shadow_uniforms {
11404            for buffer in buffers {
11405                device.destroy_buffer(buffer);
11406            }
11407        }
11408        for buffers in self.shadow_selection {
11409            for buffer in buffers {
11410                device.destroy_buffer(buffer);
11411            }
11412        }
11413        for draws in self.shadow_draws {
11414            draws.destroy(device);
11415        }
11416        // After every generator: the cameras' above and the shadow culls'.
11417        DrawGenPipelines::release(self.draw_pipelines, device);
11418        device.destroy_sampler(self.shadow_sampler);
11419        device.destroy_image_view(self.shadow_atlas_view);
11420        device.destroy_image(self.shadow_atlas);
11421        device.destroy_image_view(self.shadow_placeholder_view);
11422        device.destroy_image(self.shadow_placeholder);
11423
11424        if let Some(grid) = self.ground_grid {
11425            grid.destroy(device);
11426        }
11427        // Nothing to release on a renderer nobody drew a segment through — see
11428        // [`crate::debug_draw`], whose pipeline is built on first use.
11429        self.debug_draw.destroy(device);
11430        if let Some(atlas_viewer) = self.atlas_viewer {
11431            atlas_viewer.destroy(device);
11432        }
11433        self.ambient_occlusion_placeholder.destroy(device);
11434        self.contact_shadow_placeholder.destroy(device);
11435        self.probe_visibility_placeholder.destroy(device);
11436        if let Some(captured) = self.probe_visibility {
11437            captured.destroy(device);
11438        }
11439        self.specular_dfg.destroy(device);
11440        self.ltc_table.destroy(device);
11441        self.sky_prefilter.destroy(device);
11442        self.normal_page.destroy(device);
11443        self.mro_page.destroy(device);
11444        self.emissive_page.destroy(device);
11445
11446        // The wireframe pair is released here and nowhere else —
11447        // `set_wireframe(.., false)` deliberately is not, because this call is
11448        // the one that requires an idle device.
11449        let colour = [Some(self.mesh_pipeline), self.wireframe_pipeline];
11450        for pipeline in colour
11451            .into_iter()
11452            .flatten()
11453            .flat_map(SidedPipelines::handles)
11454        {
11455            device.destroy_graphics_pipeline(pipeline);
11456        }
11457        device.destroy_pipeline_layout(self.mesh_pipeline_layout);
11458        device.destroy_bind_group_layout(self.mesh_layout);
11459        self.base_color_page.destroy(device);
11460        device.destroy_sampler(self.base_color_sampler);
11461        for retired in self.retired_pages {
11462            retired.destroy(device);
11463        }
11464        device.destroy_buffer(self.draw_constants);
11465        if let Some(clusters) = self.clusters {
11466            clusters.destroy(device);
11467        }
11468        // Before the probe table, because its bind groups name that table's
11469        // rows — the same ordering the light grid is under above.
11470        if let Some(gather) = self.probe_gather {
11471            gather.destroy(device);
11472        }
11473        self.probes.destroy(device);
11474        self.materials.destroy(device);
11475        self.instances.destroy(device);
11476        self.pool.destroy(device);
11477    }
11478}
11479
11480/// What the shadow pass a frame recorded would leave the image holding, held
11481/// until the frame after can say whether its body ran.
11482///
11483/// Topic 45's static-caching rung, per group: recording a pass
11484/// is not drawing one, so nothing here is believed until
11485/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
11486/// out of the graph.
11487#[derive(Clone, Debug)]
11488struct ShadowCommit {
11489    /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
11490    id: u64,
11491    /// `[group]`: what the group's entry of
11492    /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
11493    /// redraws, and [`None`] for the groups it holds.
11494    groups: Vec<Option<(u64, Vec3, f32)>>,
11495    /// The layout the pass draws under, where it clears the whole attachment —
11496    /// and [`None`] where it loads, because a loading pass leaves every tile it
11497    /// does not redraw exactly as it found it.
11498    layout: Option<Vec<shadow::TileRect>>,
11499}
11500
11501/// The shader modules a mesh pipeline is built from, with its entry points
11502/// already resolved.
11503///
11504/// **A type rather than a run of locals in `build`** because there are now two
11505/// callers: `build`, which makes the colour pipeline and its depth-only twin,
11506/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
11507/// in [`PolygonMode::Line`] long after `build` released its modules. The
11508/// alternative was a second copy of a descriptor that names two modules, their
11509/// entry points, the colour targets and a depth state — the pair that drifts.
11510///
11511/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
11512/// in the same function. A module is not needed once the pipeline exists.
11513struct MeshModules {
11514    /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
11515    /// fragment stage on both.
11516    mesh: ShaderModuleHandle,
11517    /// `vertexMain`, unused on the mesh-shader path.
11518    vertex: &'static str,
11519    /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
11520    /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
11521    /// vertex pool and no attribute region at all. Unused on the mesh-shader
11522    /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
11523    depth_vertex: &'static str,
11524    /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
11525    /// builds the tile clear from: three corners off `SV_VertexID` and no input
11526    /// at all, so it resets one tile of the atlas without reading a vertex.
11527    ///
11528    /// **The same stage on every path**, unlike the two above: a device with a
11529    /// mesh stage still has a vertex stage, and a clear that produced no
11530    /// geometry is a primitive, not a cluster.
11531    depth_clear_vertex: &'static str,
11532    fragment: &'static str,
11533    /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
11534    /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
11535    /// all.
11536    ///
11537    /// **The same stage on both paths**, unlike the two vertex entry points
11538    /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
11539    /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
11540    /// mesh stage writes on the mesh one. So the cutout is one comparison in one
11541    /// place rather than one per geometry path.
11542    depth_masked_fragment: &'static str,
11543    /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
11544    /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
11545    /// describing the surface rather than shading it.
11546    ///
11547    /// **The reason the shaded stage above is looked up by name.** A module with
11548    /// two fragment entry points has no unambiguous one, which is what `entry`
11549    /// answers `None` for.
11550    rsm_fragment: &'static str,
11551    /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
11552    cluster: Option<ClusterStages>,
11553}
11554
11555/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
11556/// and the stages taken out of it.
11557struct ClusterStages {
11558    /// The module the mesh stage is built from, and the one the task stage is,
11559    /// which are **two modules rather than one**.
11560    ///
11561    /// `mesh_cluster.slang` compiles to a combined module carrying every entry
11562    /// point and to one module per stage, and these are the per-stage ones. A
11563    /// module holding a task entry point and its mesh partner carries two
11564    /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
11565    /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
11566    /// which draws cluster 0 of instance slot 0 of every bucket and nothing
11567    /// else. See `crcbl_shaders::EntryPoint`.
11568    mesh_module: ShaderModuleHandle,
11569    /// The task stage's own module, on the same terms. [`None`] exactly when
11570    /// [`task`](Self::task) is.
11571    task_module: Option<ShaderModuleHandle>,
11572    /// Which of the module's two mesh entry points this path builds — the
11573    /// amplified one where the device has a task stage to feed it.
11574    mesh: &'static str,
11575    /// §3.5's per-cluster cull, where the device has the stage to run it in.
11576    /// [`None`] is not a degradation: `meshMain` draws the same picture out of
11577    /// the same clusters, having rejected none of them, which is what a device
11578    /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
11579    /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
11580    task: Option<&'static str>,
11581}
11582
11583impl MeshModules {
11584    /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
11585    /// writes the shaded colour, then topic 47's
11586    /// reflectivity channel, then topic 43 §9's motion
11587    /// vector — and both pipeline shapes name that same entry point, so each
11588    /// target is one more element of this array and not a second pipeline, a
11589    /// second entry point or a new interpolant. The refusal the AO section
11590    /// records was about the depth prepass, which has no fragment stage and no
11591    /// colour target at all; it does not reach this array.
11592    ///
11593    /// Element order is `SV_Target` order, and each format is the one the
11594    /// matching `TransientImageDesc` creates: a pipeline built for a format the
11595    /// attachment is not in is a validation error on WebGPU and a silent
11596    /// reinterpretation elsewhere.
11597    const COLOR_TARGETS: [ColorTargetState; 3] = [
11598        ColorTargetState::opaque(Format::Rgba16Float),
11599        ColorTargetState::opaque(Format::Rgba8Unorm),
11600        ColorTargetState::opaque(MOTION_FORMAT),
11601    ];
11602
11603    /// **Three targets again, and a different three.** `mesh.slang`'s
11604    /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11605    /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11606    /// which is what the irradiance probes' gather needs of a
11607    /// texel and nothing more.
11608    ///
11609    /// Element order is `SV_Target` order and each format is the one the
11610    /// matching description in [`crate::rsm`] creates: a pipeline built for a
11611    /// format the attachment is not in is a validation error on WebGPU and a
11612    /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11613    /// in that module is the other half of the pair.
11614    const RSM_TARGETS: [ColorTargetState; 3] = [
11615        ColorTargetState::opaque(Format::Rgba16Float),
11616        ColorTargetState::opaque(Format::Rgba8Unorm),
11617        ColorTargetState::opaque(Format::Rgba32Float),
11618    ];
11619
11620    /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11621    /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11622    /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11623    ///
11624    /// Taken from the crate that owns the shader source rather than written
11625    /// out, as
11626    /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11627    /// requires: only Metal reads this field, so a literal that disagreed with
11628    /// the shader would launch the wrong number of threads on one backend and
11629    /// nowhere else.
11630    const MESH_WORKGROUP_SIZE: [u32; 3] =
11631        [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11632
11633    /// Invocations per task workgroup: `taskMain` is
11634    /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11635    /// pair of its chunk. Taken from the crate that owns the shader, on
11636    /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11637    const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11638
11639    /// The two cull modes a sided shape is built with, in
11640    /// [`SidedPipelines`]' order: [`single`](SidedPipelines::single) culls
11641    /// back faces, [`double`](SidedPipelines::double) culls nothing.
11642    const SIDES: [CullMode; 2] = [CullMode::Back, CullMode::None];
11643
11644    /// Loads whichever modules `emit` needs and resolves their entry points.
11645    ///
11646    /// # Errors
11647    ///
11648    /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11649    /// entry point, and [`HalError`] from either module. A failure after the
11650    /// first module was created releases it rather than leaking it.
11651    fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11652        // Entry points resolved before the module exists: a manifest that
11653        // disagreed with the SPIR-V would otherwise fail inside the descriptor
11654        // literal, with the module already created and nothing holding it.
11655        //
11656        // **The vertex stage is named rather than looked up by stage**, for
11657        // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11658        // this module has two vertex entry points, and a stage lookup answers
11659        // `None` for two matches. Which of the two a pipeline names is the whole
11660        // of what the split-stream vertex pool bought.
11661        let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11662        let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11663        let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11664        // **Named rather than looked up by stage, on the vertex entry points'
11665        // terms exactly.** Since the irradiance probes' updater
11666        // landed, this module has *two* fragment entry points — the shaded one
11667        // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11668        // a stage lookup here refuses the build outright with "exposes no
11669        // unambiguous Fragment entry point".
11670        let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11671        let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11672        let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11673        // **Named rather than looked up by stage**, because the module has two
11674        // mesh entry points and a stage lookup would refuse an ambiguous one —
11675        // see `named_entry`. Which of the two this names is the whole of the
11676        // amplification decision.
11677        let cluster_stages = emit
11678            .is_mesh()
11679            .then(|| {
11680                let mesh = named_entry(
11681                    &MESH_CLUSTER,
11682                    if culls_clusters {
11683                        "amplifiedMeshMain"
11684                    } else {
11685                        "meshMain"
11686                    },
11687                    Stage::Mesh,
11688                )?;
11689                let task = culls_clusters
11690                    .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11691                    .transpose()?;
11692                Ok::<_, HalError>((mesh, task))
11693            })
11694            .transpose()?;
11695
11696        let mesh = device.create_shader_module(&ShaderModuleDesc {
11697            label: Some("mesh.slang"),
11698            spirv: MESH.spirv(),
11699            wgsl: MESH.wgsl(),
11700            msl: MESH.msl(),
11701            // **Both containers, and still one module.** A DXIL container holds
11702            // exactly one entry point, so this is a list where its three
11703            // neighbours are single artifacts; the backend that consumes it
11704            // picks the container named by the stage it is building. Nothing
11705            // here branches on a backend, and the three that ignore DXIL see
11706            // the same module they always did.
11707            dxil: &MESH.dxil_containers(),
11708        })?;
11709        let cluster = match cluster_stages {
11710            None => None,
11711            Some((cluster_mesh, task)) => {
11712                // **The mesh stage's module is `mesh_cluster.slang`; the
11713                // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11714                // module per stage, so the shading — Lambert, the GGX lobe, the
11715                // material row, the page sample — is the same code both paths
11716                // run rather than a copy that agrees today.
11717                // `mesh_cluster.slang`'s header carries the argument, and its
11718                // `VertexOutput` is what the two agree through.
11719                // **One module per stage, each carrying that stage's own
11720                // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11721                // artifact per source whatever the stage, and a DXIL container
11722                // is already per entry point, so both are handed over unchanged
11723                // and the backends that read them see what they always did.
11724                let stage_module = |entry_point: &str| {
11725                    device.create_shader_module(&ShaderModuleDesc {
11726                        label: Some("mesh_cluster.slang"),
11727                        // The combined module where this stage has none of its
11728                        // own, which is every stage of every other shader.
11729                        spirv: MESH_CLUSTER
11730                            .spirv_for(entry_point)
11731                            .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11732                        // `None`, and it is the whole reason this is a second
11733                        // file: WGSL cannot express a mesh stage at all.
11734                        wgsl: MESH_CLUSTER.wgsl(),
11735                        msl: MESH_CLUSTER.msl(),
11736                        dxil: &MESH_CLUSTER.dxil_containers(),
11737                    })
11738                };
11739                let mesh_module = match stage_module(cluster_mesh) {
11740                    Ok(module) => module,
11741                    Err(error) => {
11742                        device.destroy_shader_module(mesh);
11743                        return Err(error);
11744                    }
11745                };
11746                let task_module = match task.map(stage_module).transpose() {
11747                    Ok(module) => module,
11748                    Err(error) => {
11749                        device.destroy_shader_module(mesh);
11750                        device.destroy_shader_module(mesh_module);
11751                        return Err(error);
11752                    }
11753                };
11754                Some(ClusterStages {
11755                    mesh_module,
11756                    task_module,
11757                    mesh: cluster_mesh,
11758                    task,
11759                })
11760            }
11761        };
11762        Ok(Self {
11763            mesh,
11764            vertex,
11765            depth_vertex,
11766            depth_clear_vertex,
11767            fragment,
11768            depth_masked_fragment,
11769            rsm_fragment,
11770            cluster,
11771        })
11772    }
11773
11774    /// The rasteriser state every pipeline shape here shares, because the only
11775    /// things that differ between them are which stage produces the geometry and
11776    /// which side of it survives.
11777    ///
11778    /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11779    /// been on from the first mesh. The cube's winding is asserted by
11780    /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11781    /// failure rather than a debugging session — and a mesh drawn without
11782    /// culling would let a winding mistake survive into P7's geometry pool. The
11783    /// mesh stage emits its corner triples in the index buffer's own order, so
11784    /// the winding it produces is the same one.
11785    ///
11786    /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11787    /// §3.9.6's first half — and the twin built with it is the only way a back
11788    /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11789    fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11790        PrimitiveState {
11791            cull_mode,
11792            polygon_mode,
11793            ..PrimitiveState::default()
11794        }
11795    }
11796
11797    /// What a pipeline built with `cull` adds to its label, so a capture and
11798    /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11799    /// the [`SidedPipelines::single`] it was built beside.
11800    ///
11801    /// Empty for the culling modes, because those pipelines' labels are the ones
11802    /// every existing capture and every test lookup already names.
11803    fn side_label(cull: CullMode) -> &'static str {
11804        match cull {
11805            CullMode::None => " double-sided",
11806            CullMode::Front | CullMode::Back => "",
11807        }
11808    }
11809
11810    /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11811    /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11812    /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11813    /// matrix that agrees with **both** comes from [`crate::camera`].
11814    fn depth_stencil() -> Option<DepthStencilState> {
11815        Some(DepthStencilState::default())
11816    }
11817
11818    /// The colour pass's depth state, which is not the same shape as
11819    /// [`MeshModules::depth_stencil`] because the depth prepass has already
11820    /// drawn this geometry.
11821    ///
11822    /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11823    /// paid for once per pixel.** The prepass runs the same draws through
11824    /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11825    /// stage — so the depth already in the attachment is this pass's own answer,
11826    /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11827    /// that would have won the write. What it removes is the clustered-forward
11828    /// shading of every fragment a nearer one goes on to cover.
11829    ///
11830    /// **Lines: the writing default, because a wireframe is not the geometry the
11831    /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11832    /// and an edge pixel's depth is interpolated along the line rather than
11833    /// across the face, so testing it for equality against a filled prepass
11834    /// rejects most of the wireframe. That frame keeps the pass shape this pass
11835    /// had before the prepass existed — see the colour pass's depth attachment,
11836    /// which branches on the same condition.
11837    fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11838        match polygon_mode {
11839            PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11840            _ => Self::depth_stencil(),
11841        }
11842    }
11843
11844    /// The colour pass's pipeline, filled or wireframe, culling back faces or
11845    /// nothing.
11846    ///
11847    /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11848    /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11849    /// names the side, so a capture tells all four apart.
11850    fn color_pipeline(
11851        &self,
11852        device: &dyn Device,
11853        layout: PipelineLayoutHandle,
11854        polygon_mode: PolygonMode,
11855        cull: CullMode,
11856        label: &str,
11857    ) -> Result<GraphicsPipelineHandle, HalError> {
11858        let primitive = Self::primitive(polygon_mode, cull);
11859        let depth_stencil = Self::color_depth_stencil(polygon_mode);
11860        let side = Self::side_label(cull);
11861        let fragment = Some(ShaderEntry {
11862            module: self.mesh,
11863            entry_point: self.fragment,
11864        });
11865        match self.cluster.as_ref() {
11866            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11867                label: Some(&format!("{label}{side} mesh cluster")),
11868                layout,
11869                task: cluster
11870                    .task
11871                    .zip(cluster.task_module)
11872                    .map(|(entry_point, module)| ShaderEntry {
11873                        module,
11874                        entry_point,
11875                    }),
11876                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11877                mesh: ShaderEntry {
11878                    module: cluster.mesh_module,
11879                    entry_point: cluster.mesh,
11880                },
11881                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11882                fragment,
11883                primitive,
11884                depth_stencil,
11885                multisample: MultisampleState::default(),
11886                color_targets: &Self::COLOR_TARGETS,
11887            }),
11888            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11889                label: Some(&format!("{label}{side} mesh")),
11890                layout,
11891                vertex: ShaderEntry {
11892                    module: self.mesh,
11893                    entry_point: self.vertex,
11894                },
11895                fragment,
11896                primitive,
11897                depth_stencil,
11898                multisample: MultisampleState::default(),
11899                color_targets: &Self::COLOR_TARGETS,
11900            }),
11901        }
11902    }
11903
11904    /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11905    /// same modules and the same layout: no fragment stage, no colour target,
11906    /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11907    ///
11908    /// **The transform is identical and the fetch is not, which is the point.**
11909    /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11910    /// depth pass plus whatever emit tail the device selected", and what makes
11911    /// that work is a frame block whose `view_proj` is the cascade's matrix
11912    /// rather than a second transform path: a cascade that disagreed with the
11913    /// colour pass about where a vertex is would produce shadows that do not
11914    /// line up with their casters, which is indistinguishable from a bias
11915    /// problem. `depthVertexMain` is that same clip position written the same
11916    /// way, with everything the discarded varyings needed — the attribute
11917    /// region and the previous frame's position — left unread;
11918    /// topic 43 §2 split the pool for exactly this
11919    /// pass, and this is where it is spent.
11920    ///
11921    /// **The mesh-shader path still runs the colour pipeline's geometry
11922    /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11923    /// mesh stage is a second entry point in that module and its own rung; a
11924    /// device with a mesh stage goes on reading whole vertices here.
11925    ///
11926    /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11927    /// prepass, and depth drawn as lines is depth with holes in it — which the
11928    /// occlusion pair would read as geometry that is not there.
11929    fn depth_pipeline(
11930        &self,
11931        device: &dyn Device,
11932        layout: PipelineLayoutHandle,
11933        cull: CullMode,
11934    ) -> Result<GraphicsPipelineHandle, HalError> {
11935        let primitive = Self::primitive(PolygonMode::Fill, cull);
11936        let side = Self::side_label(cull);
11937        match self.cluster.as_ref() {
11938            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11939                label: Some(&format!("shadow cascade{side} mesh cluster")),
11940                layout,
11941                task: cluster
11942                    .task
11943                    .zip(cluster.task_module)
11944                    .map(|(entry_point, module)| ShaderEntry {
11945                        module,
11946                        entry_point,
11947                    }),
11948                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11949                mesh: ShaderEntry {
11950                    module: cluster.mesh_module,
11951                    entry_point: cluster.mesh,
11952                },
11953                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11954                fragment: None,
11955                primitive,
11956                depth_stencil: Self::depth_stencil(),
11957                multisample: MultisampleState::default(),
11958                color_targets: &[],
11959            }),
11960            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11961                label: Some(&format!("shadow cascade{side}")),
11962                layout,
11963                vertex: ShaderEntry {
11964                    module: self.mesh,
11965                    entry_point: self.depth_vertex,
11966                },
11967                fragment: None,
11968                primitive,
11969                depth_stencil: Self::depth_stencil(),
11970                multisample: MultisampleState::default(),
11971                color_targets: &[],
11972            }),
11973        }
11974    }
11975
11976    /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11977    /// state and the same absent colour targets, `depthMaskedFragmentMain`
11978    /// behind the geometry stage, and [`MeshModules::vertex`] in
11979    /// [`MeshModules::depth_vertex`]'s place.
11980    ///
11981    /// Topic 43 §3's cutout, in the two passes that
11982    /// write depth without shading. A masked instance drawn through the pipeline
11983    /// above writes its full silhouette: it occludes itself through the hole it
11984    /// can see through, and it casts the shadow of a leaf that has none.
11985    ///
11986    /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11987    /// needs the UV, which lives in the attribute region `depthVertexMain`
11988    /// exists not to read — so this stage reads a whole vertex, exactly as
11989    /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11990    /// What that buys is one fragment entry point for both geometry paths: the
11991    /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11992    /// compared in one place rather than once per path.
11993    ///
11994    /// **Which draws are recorded with it is the bucket's own material mode**,
11995    /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11996    /// masks nothing has no bucket in this partition, records through the
11997    /// pipeline above with no fragment stage anywhere, and is never compiled
11998    /// this pipeline at all; a scene that masks one mesh pays the fragment stage
11999    /// for that mesh's draws alone.
12000    fn depth_masked_pipeline(
12001        &self,
12002        device: &dyn Device,
12003        layout: PipelineLayoutHandle,
12004        cull: CullMode,
12005    ) -> Result<GraphicsPipelineHandle, HalError> {
12006        let primitive = Self::primitive(PolygonMode::Fill, cull);
12007        let side = Self::side_label(cull);
12008        let fragment = Some(ShaderEntry {
12009            module: self.mesh,
12010            entry_point: self.depth_masked_fragment,
12011        });
12012        match self.cluster.as_ref() {
12013            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
12014                label: Some(&format!("shadow cascade masked{side} mesh cluster")),
12015                layout,
12016                task: cluster
12017                    .task
12018                    .zip(cluster.task_module)
12019                    .map(|(entry_point, module)| ShaderEntry {
12020                        module,
12021                        entry_point,
12022                    }),
12023                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
12024                mesh: ShaderEntry {
12025                    module: cluster.mesh_module,
12026                    entry_point: cluster.mesh,
12027                },
12028                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
12029                fragment,
12030                primitive,
12031                depth_stencil: Self::depth_stencil(),
12032                multisample: MultisampleState::default(),
12033                color_targets: &[],
12034            }),
12035            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
12036                label: Some(&format!("shadow cascade masked{side}")),
12037                layout,
12038                vertex: ShaderEntry {
12039                    module: self.mesh,
12040                    entry_point: self.vertex,
12041                },
12042                fragment,
12043                primitive,
12044                depth_stencil: Self::depth_stencil(),
12045                multisample: MultisampleState::default(),
12046                color_targets: &[],
12047            }),
12048        }
12049    }
12050
12051    /// The reflective shadow map's pipeline: the colour pipeline's geometry
12052    /// stage, `rsmFragmentMain` in the shaded stage's place, and
12053    /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
12054    ///
12055    /// The irradiance probes' updater draws the sun's near
12056    /// cascade a second time through this — see [`crate::rsm`], which owns the
12057    /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
12058    /// pass out of that cascade's own bind group and its own already-generated
12059    /// draws.
12060    ///
12061    /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
12062    /// the cascade this rides beside: a fragment stage that writes a world
12063    /// position, a normal and an albedo needs the varyings `depthVertexMain`
12064    /// exists to leave unread. On the mesh path it is the very same geometry
12065    /// stage the colour pass runs, for the reason `depth_pipeline` gives.
12066    ///
12067    /// **Its own depth, written**, rather than the colour pass's read-only
12068    /// equality test: nothing has drawn this view's depth before it, and the
12069    /// pass is what decides which surface a texel of the map holds.
12070    fn rsm_pipeline(
12071        &self,
12072        device: &dyn Device,
12073        layout: PipelineLayoutHandle,
12074        cull: CullMode,
12075    ) -> Result<GraphicsPipelineHandle, HalError> {
12076        let primitive = Self::primitive(PolygonMode::Fill, cull);
12077        let side = Self::side_label(cull);
12078        let fragment = Some(ShaderEntry {
12079            module: self.mesh,
12080            entry_point: self.rsm_fragment,
12081        });
12082        match self.cluster.as_ref() {
12083            Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
12084                label: Some(&format!("rsm{side} mesh cluster")),
12085                layout,
12086                task: cluster
12087                    .task
12088                    .zip(cluster.task_module)
12089                    .map(|(entry_point, module)| ShaderEntry {
12090                        module,
12091                        entry_point,
12092                    }),
12093                task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
12094                mesh: ShaderEntry {
12095                    module: cluster.mesh_module,
12096                    entry_point: cluster.mesh,
12097                },
12098                mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
12099                fragment,
12100                primitive,
12101                depth_stencil: Self::depth_stencil(),
12102                multisample: MultisampleState::default(),
12103                color_targets: &Self::RSM_TARGETS,
12104            }),
12105            None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
12106                label: Some(&format!("rsm{side}")),
12107                layout,
12108                vertex: ShaderEntry {
12109                    module: self.mesh,
12110                    entry_point: self.vertex,
12111                },
12112                fragment,
12113                primitive,
12114                depth_stencil: Self::depth_stencil(),
12115                multisample: MultisampleState::default(),
12116                color_targets: &Self::RSM_TARGETS,
12117            }),
12118        }
12119    }
12120
12121    /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
12122    /// some tiles and redraw others.
12123    ///
12124    /// Topic 45's cadence rung needs a tile cleared on its own,
12125    /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
12126    /// whole image, and the region-bounded forms are not portable. This is the
12127    /// portable statement of the same thing: `mesh.slang`'s
12128    /// `depthClearVertexMain` covers the viewport the shadow pass has already
12129    /// set over the tile, and the depth state below writes
12130    /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
12131    ///
12132    /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
12133    /// clear rather than a draw: the tile holds the previous frame's depths, and
12134    /// under the engine's [`CompareOp::Greater`] a clear value of zero would
12135    /// fail against every one of them and leave the tile exactly as it was.
12136    ///
12137    /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
12138    /// is generated from `SV_VertexID` rather than wound by an artist, so a
12139    /// culling rule meant for scene geometry would decide whether the clear
12140    /// happens at all.
12141    ///
12142    /// **A vertex pipeline on every path**, including the mesh-shader one: a
12143    /// device with a mesh stage still has a vertex stage, and the clear has no
12144    /// clusters to descend.
12145    fn depth_clear_pipeline(
12146        &self,
12147        device: &dyn Device,
12148        layout: PipelineLayoutHandle,
12149    ) -> Result<GraphicsPipelineHandle, HalError> {
12150        device.create_graphics_pipeline(&GraphicsPipelineDesc {
12151            label: Some("shadow tile clear"),
12152            // The mesh layout, so binding this pipeline in the middle of the
12153            // shadow pass does not disturb the bind group the draws around it
12154            // are recorded with. The stage reads none of it.
12155            layout,
12156            vertex: ShaderEntry {
12157                module: self.mesh,
12158                entry_point: self.depth_clear_vertex,
12159            },
12160            fragment: None,
12161            primitive: PrimitiveState {
12162                cull_mode: CullMode::None,
12163                polygon_mode: PolygonMode::Fill,
12164                ..PrimitiveState::default()
12165            },
12166            depth_stencil: Some(DepthStencilState {
12167                depth_compare: CompareOp::Always,
12168                ..DepthStencilState::default()
12169            }),
12170            multisample: MultisampleState::default(),
12171            color_targets: &[],
12172        })
12173    }
12174
12175    /// Releases every module. The pipelines built from them stay valid.
12176    fn destroy(self, device: &dyn Device) {
12177        device.destroy_shader_module(self.mesh);
12178        if let Some(cluster) = self.cluster {
12179            device.destroy_shader_module(cluster.mesh_module);
12180            if let Some(task) = cluster.task_module {
12181                device.destroy_shader_module(task);
12182            }
12183        }
12184    }
12185}
12186
12187/// The entry point for `stage`, or an error naming the shader.
12188///
12189/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
12190/// expose both stages — but the alternative is an `expect` in engine code.
12191fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
12192    shader.entry_point(stage).ok_or_else(|| {
12193        HalError::ShaderCompilation(format!(
12194            "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
12195             manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
12196            shader.name()
12197        ))
12198    })
12199}
12200
12201/// The entry point called `name`, checked to be `stage`'s.
12202///
12203/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
12204/// points — one behind the amplification stage and one without it — and a
12205/// lookup by stage answers `None` for two matches rather than picking one, for
12206/// the good reason that picking one would draw the wrong geometry.
12207///
12208/// The stage is still checked rather than taken on trust: a name that resolved
12209/// to the wrong stage would be a pipeline built with an amplification stage in
12210/// its mesh slot, and the failure would arrive as a driver error rather than as
12211/// this sentence.
12212pub(crate) fn named_entry(
12213    shader: &crcbl_shaders::Shader,
12214    name: &'static str,
12215    stage: Stage,
12216) -> Result<&'static str, HalError> {
12217    let found = shader
12218        .entry_points()
12219        .iter()
12220        .find(|entry| entry.name() == name && entry.stage() == stage);
12221    found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
12222        HalError::ShaderCompilation(format!(
12223            "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
12224             its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
12225            shader.name()
12226        ))
12227    })
12228}
12229
12230// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
12231#[cfg(all(test, not(target_arch = "wasm32")))]
12232mod tests {
12233    mod draw_pipelines;
12234    mod frame_extents;
12235    mod instance_upload;
12236    pub(super) mod lazy_content;
12237    mod lazy_passes;
12238    mod load_service;
12239    mod mesh_variants;
12240    mod page_reload;
12241    mod partial_builds;
12242    mod shadow_reach;
12243    mod skin_cull;
12244    mod upload_waits;
12245    mod view_pipelines;
12246
12247    use super::*;
12248    use crate::effects::{Antialiasing, EffectOverride};
12249    use crate::scene::{
12250        DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
12251        DEMO_UNTINTED,
12252    };
12253    use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
12254    use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
12255
12256    #[test]
12257    fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
12258        let recorder = Recorder::new();
12259        let mut limits = crcbl_hal::Limits::desktop();
12260        limits.max_color_attachments = 2;
12261        let features = Features::COMPUTE | Features::MESH_SHADER;
12262        let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
12263            .with_recorder(recorder.clone());
12264        let device = instance
12265            .create_device(&DeviceDesc {
12266                label: None,
12267                adapter: crcbl_hal::AdapterId(0),
12268                required_features: features,
12269                optional_features: Features::empty(),
12270                compatible_surface: None,
12271            })
12272            .unwrap();
12273        let queue = device.queue(QueueKind::Graphics).unwrap();
12274        let before = recorder.total_live_objects();
12275        let error = ForwardRenderer::with_scene_on_path(
12276            device.as_ref(),
12277            queue,
12278            Format::Rgba8UnormSrgb,
12279            &scene::demo(),
12280            GeometryPath::MeshShader,
12281        )
12282        .expect_err("three-target color pipelines must be refused");
12283        assert!(
12284            error
12285                .to_string()
12286                .contains("3 colour targets exceeds max_color_attachments 2"),
12287            "{error}"
12288        );
12289        assert!(
12290            recorder.events().iter().any(|event| matches!(
12291                event,
12292                Event::Created {
12293                    kind: ObjectKind::GraphicsPipeline,
12294                    ..
12295                }
12296            )),
12297            "the refusal must exercise cleanup of successful pipelines"
12298        );
12299        assert_eq!(
12300            recorder.total_live_objects(),
12301            before,
12302            "partial pipeline construction leaked resources"
12303        );
12304        recorder.assert_valid();
12305    }
12306
12307    #[test]
12308    fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
12309        let recorder = Recorder::new();
12310        let instance = NullInstance::gpu_driven()
12311            .with_geometry_preference(GeometryPath::IndirectPerBatch)
12312            .with_recorder(recorder.clone());
12313        let device = instance
12314            .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
12315            .unwrap();
12316        let queue = device.queue(QueueKind::Graphics).unwrap();
12317        assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
12318        let default = ForwardRenderer::with_scene(
12319            device.as_ref(),
12320            queue,
12321            Format::Rgba8UnormSrgb,
12322            &scene::demo(),
12323        )
12324        .unwrap();
12325        assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
12326        default.destroy(device.as_ref());
12327        recorder.clear();
12328        let mut exact = ForwardRenderer::with_scene_on_path(
12329            device.as_ref(),
12330            queue,
12331            Format::Rgba8UnormSrgb,
12332            &scene::demo(),
12333            GeometryPath::IndirectCount,
12334        )
12335        .unwrap();
12336        assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
12337        let rendered = frame(device.as_ref(), &mut exact, queue);
12338        let commands = commands_in_pass(&recorder, "forward");
12339        assert!(commands.iter().any(|command| matches!(
12340            command,
12341            crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
12342        )));
12343        assert!(
12344            !commands
12345                .iter()
12346                .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
12347        );
12348        rendered.finish(device.as_ref(), exact);
12349    }
12350
12351    /// **A device with a draw index draws a range of buckets per call, and one
12352    /// without it a call per bucket** — both indirect tails, read off the
12353    /// recorded stream of a whole frame.
12354    ///
12355    /// The ranged frame records one bind and one multi-draw per range in the
12356    /// depth prepass, whose draws together cover every bucket exactly once,
12357    /// and no count draw anywhere; the per-bucket frame records the call per
12358    /// bucket it always did. Both frames' counters are what they recorded.
12359    #[test]
12360    fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
12361        use crcbl_hal::null::Command;
12362
12363        let _seam = ssao_split_switch();
12364        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
12365            for ranged in [false, true] {
12366                let optional = if ranged {
12367                    Features::GPU_DRIVEN | Features::DRAW_INDEX
12368                } else {
12369                    DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
12370                };
12371                let (recorder, device, queue) = open_with(optional);
12372                let mut renderer = ForwardRenderer::with_scene_on_path(
12373                    device.as_ref(),
12374                    queue,
12375                    Format::Rgba8UnormSrgb,
12376                    &scene::demo(),
12377                    path,
12378                )
12379                .expect("the demo scene builds");
12380                assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
12381                let buckets = renderer.bucket_modes.len();
12382                assert!(buckets > 1, "one bucket packs into one call either way");
12383                let rendered = frame(device.as_ref(), &mut renderer, queue);
12384
12385                let commands = commands_in_pass(&recorder, "depth-prepass");
12386                let binds = commands
12387                    .iter()
12388                    .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
12389                    .count();
12390                let draws: Vec<u32> = commands
12391                    .iter()
12392                    .filter_map(|command| match command {
12393                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
12394                        Command::DrawIndexedIndirectCount(draw) => {
12395                            assert!(!ranged, "{path:?}: a ranged pass records no count draw");
12396                            assert_eq!(draw.max_draw_count, 1);
12397                            Some(1)
12398                        }
12399                        _ => None,
12400                    })
12401                    .collect();
12402                assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
12403                assert_eq!(
12404                    draws.iter().sum::<u32>() as usize,
12405                    buckets,
12406                    "{path:?}: every bucket drawn once"
12407                );
12408                if ranged {
12409                    assert!(
12410                        draws.len() < buckets,
12411                        "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
12412                    );
12413                } else {
12414                    assert_eq!(draws, vec![1; buckets], "{path:?}");
12415                }
12416                assert!(
12417                    !recorder
12418                        .commands()
12419                        .iter()
12420                        .any(|command| ranged
12421                            && matches!(command, Command::DrawIndexedIndirectCount(_))),
12422                    "{path:?}: a ranged frame records no count draw"
12423                );
12424                assert_eq!(
12425                    renderer.counters().draws,
12426                    recorded_draws(&recorder) as u64,
12427                    "{path:?}, ranged {ranged}"
12428                );
12429                rendered.finish(device.as_ref(), renderer);
12430                recorder.assert_valid();
12431            }
12432        }
12433    }
12434
12435    /// **A scene holding every material mode draws each pipeline's buckets as
12436    /// one ranged call**, because the bucket table is numbered mode-major: the
12437    /// depth prepass records one call per depth pipeline and the colour pass
12438    /// one per sided pipeline, on both indirect tails.
12439    ///
12440    /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
12441    /// and every partition's runs are one bucket long, so the prepass would
12442    /// record a call per bucket — the counts below are what tell the two
12443    /// numberings apart, and the sums are what say every bucket still drew.
12444    #[test]
12445    fn every_mode_partition_of_a_ranged_frame_is_one_call() {
12446        use crcbl_hal::null::Command;
12447        use crcbl_shaders::mesh::GpuMaterial;
12448
12449        let scene = {
12450            let mut scene = crate::scene::demo();
12451            while scene.materials.len() < 4 {
12452                scene.materials.push(GpuMaterial::UNTINTED);
12453            }
12454            let rows = [
12455                0,
12456                GpuMaterial::ALPHA_MODE_MASK,
12457                GpuMaterial::DOUBLE_SIDED,
12458                GpuMaterial::MODE_MASK,
12459            ];
12460            for (row, flags) in scene.materials.iter_mut().zip(rows) {
12461                row.flags = flags;
12462            }
12463            scene
12464        };
12465        for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
12466            let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
12467            let mut renderer = ForwardRenderer::with_scene_on_path(
12468                device.as_ref(),
12469                queue,
12470                Format::Rgba8UnormSrgb,
12471                &scene,
12472                path,
12473            )
12474            .expect("the four-mode demo builds");
12475            assert!(renderer.range_limit.is_some(), "{path:?}");
12476            let buckets = renderer.bucket_modes.len();
12477            let per_mode = buckets / DEPTH_MODES.len();
12478            assert_eq!(
12479                per_mode * DEPTH_MODES.len(),
12480                buckets,
12481                "{path:?}: four twins"
12482            );
12483            assert!(
12484                per_mode > 1,
12485                "{path:?}: a mode of one bucket is one call under either numbering"
12486            );
12487            let rendered = frame(device.as_ref(), &mut renderer, queue);
12488
12489            let draws = |label: &str| -> Vec<u32> {
12490                commands_in_pass(&recorder, label)
12491                    .iter()
12492                    .filter_map(|command| match command {
12493                        Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
12494                        _ => None,
12495                    })
12496                    .collect()
12497            };
12498            let prepass = draws("depth-prepass");
12499            assert_eq!(
12500                prepass,
12501                vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
12502                "{path:?}: one call per depth pipeline, each a whole mode"
12503            );
12504            let forward = draws("forward");
12505            assert_eq!(
12506                forward,
12507                vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
12508                "{path:?}: one call per sided pipeline, each two adjacent modes"
12509            );
12510            rendered.finish(device.as_ref(), renderer);
12511            recorder.assert_valid();
12512        }
12513    }
12514
12515    /// **Behind an amplification stage the mesh tail records one flat call per
12516    /// partition, and without one a range of buckets per call on a device with
12517    /// a draw index and a call per bucket without** — read off the recorded
12518    /// stream of a whole frame.
12519    ///
12520    /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
12521    /// colour pass's sided segments in region 0, under the segment's first
12522    /// bucket's block — whatever the bucket count, and whether or not the
12523    /// device granted a draw index, which the flat call does not read. Without
12524    /// the stage the colour pass's calls, unrolled a structure at a time, are
12525    /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
12526    /// bucket's own extents, each once. Either way the counters are what the
12527    /// frame recorded.
12528    #[test]
12529    fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
12530        use crcbl_hal::null::Command;
12531
12532        let _seam = ssao_split_switch();
12533        // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
12534        // bucket each, in one material mode — so one run of `n` buckets.
12535        for cubes in [None, Some(4), Some(33)] {
12536            for task in [Features::TASK_SHADER, Features::empty()] {
12537                for ranged in [false, true] {
12538                    let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
12539                    let recorder = Recorder::new();
12540                    let optional = if ranged {
12541                        task | Features::DRAW_INDEX
12542                    } else {
12543                        task
12544                    };
12545                    let (device, queue) = open_mesh_path(&recorder, optional);
12546                    let mut scene = scene::demo();
12547                    if let Some(cubes) = cubes {
12548                        scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
12549                        scene.capacities.meshes = cubes;
12550                        scene.capacities.vertices =
12551                            cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
12552                        scene.capacities.indices =
12553                            cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
12554                    }
12555                    let mut renderer = ForwardRenderer::with_scene_on_path(
12556                        device.as_ref(),
12557                        queue,
12558                        Format::Rgba8UnormSrgb,
12559                        &scene,
12560                        GeometryPath::MeshShader,
12561                    )
12562                    .expect("the mesh renderer builds");
12563                    assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
12564                    assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
12565                    let buckets = renderer.bucket_constants.len();
12566                    assert!(buckets > 1, "one bucket packs into one call either way");
12567                    let rendered = frame(device.as_ref(), &mut renderer, queue);
12568
12569                    let commands = commands_in_pass(&recorder, "forward");
12570                    let bound: Vec<u32> = commands
12571                        .iter()
12572                        .filter_map(|command| match command {
12573                            Command::BindGroup {
12574                                slot: 0,
12575                                dynamic_offsets,
12576                                ..
12577                            } => Some(dynamic_offsets[0]),
12578                            _ => None,
12579                        })
12580                        .collect();
12581                    let calls: Vec<DrawIndirect> = commands
12582                        .iter()
12583                        .filter_map(|command| match command {
12584                            Command::DrawMeshTasksIndirect(draw) => Some(*draw),
12585                            Command::DrawMeshTasks { .. }
12586                            | Command::DrawIndexedIndirect(_)
12587                            | Command::DrawIndexedIndirectCount(_) => {
12588                                panic!("{case}: the mesh tail recorded {command:?}")
12589                            }
12590                            _ => None,
12591                        })
12592                        .collect();
12593                    assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12594                    assert!(
12595                        calls
12596                            .iter()
12597                            .all(|call| call.stride
12598                                == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12599                        "{case}: one structure a bucket, or a flat call's one"
12600                    );
12601                    if task.is_empty() {
12602                        // Each call a structure at a time: what a call per
12603                        // bucket would have recorded for the buckets it
12604                        // stands for.
12605                        let mut unrolled: Vec<DrawIndirect> = calls
12606                            .iter()
12607                            .flat_map(|call| {
12608                                (0..call.draw_count).map(|draw| DrawIndirect {
12609                                    offset: call.offset + u64::from(draw) * u64::from(call.stride),
12610                                    draw_count: 1,
12611                                    ..*call
12612                                })
12613                            })
12614                            .collect();
12615                        unrolled.sort_by_key(|draw| draw.offset);
12616                        assert_eq!(
12617                            unrolled,
12618                            mesh_dispatch_calls(&renderer),
12619                            "{case}: every bucket's own extents, each once"
12620                        );
12621                        let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12622                        match (ranged, cubes) {
12623                            (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12624                            (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12625                            (true, None) => assert!(
12626                                calls.len() < buckets,
12627                                "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12628                            ),
12629                        }
12630                    } else {
12631                        let (expected, firsts) = flat_dispatch_calls(
12632                            &renderer,
12633                            crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12634                        );
12635                        assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12636                        assert_eq!(
12637                            bound,
12638                            firsts
12639                                .iter()
12640                                .map(|&bucket| renderer.bucket_constants[bucket as usize])
12641                                .collect::<Vec<_>>(),
12642                            "{case}: each under its segment's first bucket's block"
12643                        );
12644                    }
12645                    assert_eq!(
12646                        renderer.counters().draws,
12647                        recorded_draws(&recorder) as u64,
12648                        "{case}"
12649                    );
12650                    rendered.finish(device.as_ref(), renderer);
12651                    recorder.assert_valid();
12652                }
12653            }
12654        }
12655    }
12656
12657    /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12658    /// block carries**, in every draw region.
12659    ///
12660    /// The host half of `mesh_cluster.slang`'s "One call for a range of
12661    /// buckets": a ranged call binds its first bucket's block alone, and the
12662    /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12663    /// the two table words it names. So each bucket's block has to sit one word
12664    /// past the one before in all four, and the table words have to hold the
12665    /// bucket's own cluster base and count — read out of the bytes that reached
12666    /// the device, since a block written wrong leaves the renderer's fields
12667    /// right.
12668    #[test]
12669    fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12670        let recorder = Recorder::new();
12671        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12672        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12673            .expect("the mesh renderer builds");
12674        let blocks = recorder
12675            .buffer_bytes(renderer.draw_constants)
12676            .expect("the blocks are live");
12677        let tables = recorder
12678            .buffer_bytes(renderer.primary.draws.tables())
12679            .expect("the tables are live");
12680        let word = |bytes: &[u8], at: usize| {
12681            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12682        };
12683        let buckets = renderer.bucket_constants.len();
12684        assert!(buckets > 1, "a range needs two buckets to step between");
12685        let bucket_count = u32::try_from(buckets).expect("a few buckets");
12686        let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12687        let block = |region: u32, bucket: u32| {
12688            let at = ((region * bucket_count + bucket) * stride) as usize;
12689            let field = |index: usize| word(&blocks, at + index * 4);
12690            crcbl_shaders::meshlet::ClusterDrawConstants {
12691                start_at: field(0),
12692                cluster_base: field(1),
12693                cluster_count: field(2),
12694                bucket: field(3),
12695                group_stride: field(4),
12696                level_groups_at: field(5),
12697                cluster_base_at: field(6),
12698                cluster_count_at: field(7),
12699                chunk_starts_at: field(8),
12700                chunk_starts_end: field(9),
12701            }
12702        };
12703        let mut bases = Vec::new();
12704        for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12705            let first = block(region, 0);
12706            for bucket in 0..bucket_count {
12707                let own = block(region, bucket);
12708                assert_eq!(
12709                    word(&tables, own.cluster_base_at as usize * 4),
12710                    own.cluster_base,
12711                    "region {region} bucket {bucket}: the base word holds the base"
12712                );
12713                assert_eq!(
12714                    word(&tables, own.cluster_count_at as usize * 4),
12715                    own.cluster_count,
12716                    "region {region} bucket {bucket}: the count word holds the count"
12717                );
12718                // What draw `bucket` of a call bound at bucket 0's block reads
12719                // — and a flat call's workgroup that found bucket `bucket` by
12720                // searching the chunk starts from bucket 0's word to the
12721                // region's end.
12722                assert_eq!(
12723                    (
12724                        first.start_at + bucket,
12725                        first.bucket + bucket,
12726                        first.cluster_base_at + bucket,
12727                        first.cluster_count_at + bucket,
12728                        first.group_stride,
12729                        first.level_groups_at,
12730                        first.chunk_starts_at + bucket,
12731                        first.chunk_starts_end,
12732                    ),
12733                    (
12734                        own.start_at,
12735                        own.bucket,
12736                        own.cluster_base_at,
12737                        own.cluster_count_at,
12738                        own.group_stride,
12739                        own.level_groups_at,
12740                        own.chunk_starts_at,
12741                        own.chunk_starts_end,
12742                    ),
12743                    "region {region} bucket {bucket}"
12744                );
12745                assert_eq!(
12746                    own.chunk_starts_at,
12747                    crcbl_shaders::draw_gen::chunk_start_word(
12748                        renderer.primary.draws.visible_capacity(),
12749                        bucket_count,
12750                        region,
12751                        bucket,
12752                    ),
12753                    "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12754                );
12755                assert_eq!(
12756                    own.chunk_starts_end - own.chunk_starts_at,
12757                    bucket_count - bucket,
12758                    "region {region} bucket {bucket}: the search ends at the region's end word"
12759                );
12760                if region == 0 {
12761                    bases.push(own.cluster_base);
12762                }
12763            }
12764        }
12765        assert!(
12766            bases.windows(2).any(|pair| pair[0] != pair[1]),
12767            "the buckets' meshes start at different clusters, so a range reading its \
12768             first bucket's base for every draw would be seen: {bases:?}"
12769        );
12770        renderer.destroy(device.as_ref());
12771        recorder.assert_valid();
12772    }
12773
12774    #[test]
12775    fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12776    {
12777        for features in [
12778            Features::GPU_DRIVEN,
12779            Features::COMPUTE | Features::MESH_SHADER,
12780        ] {
12781            let recorder = Recorder::new();
12782            let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12783                features,
12784                limits: crcbl_hal::Limits::desktop(),
12785            })
12786            .with_recorder(recorder.clone());
12787            let device = instance
12788                .create_device(&DeviceDesc {
12789                    label: None,
12790                    adapter: crcbl_hal::AdapterId(0),
12791                    required_features: Features::COMPUTE,
12792                    optional_features: features,
12793                    compatible_surface: None,
12794                })
12795                .expect("null device opens");
12796            let queue = device.queue(QueueKind::Graphics).unwrap();
12797            for (path, required) in [
12798                (GeometryPath::IndirectPerBatch, Features::empty()),
12799                (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12800                (GeometryPath::MeshShader, Features::MESH_SHADER),
12801            ] {
12802                recorder.clear();
12803                let result = ForwardRenderer::with_scene_on_path(
12804                    device.as_ref(),
12805                    queue,
12806                    Format::Rgba8UnormSrgb,
12807                    &scene::demo(),
12808                    path,
12809                );
12810                if features.contains(required) {
12811                    let renderer = result.expect("supported exact tail builds");
12812                    assert_eq!(renderer.geometry_path(), path);
12813                    renderer.destroy(device.as_ref());
12814                } else {
12815                    assert!(
12816                        matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12817                    );
12818                    assert!(
12819                        recorder.events().is_empty(),
12820                        "unsupported selection must not touch device objects"
12821                    );
12822                }
12823                recorder.assert_valid();
12824            }
12825        }
12826    }
12827
12828    pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12829        open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12830    }
12831
12832    /// [`open`] asking for `optional_features` instead of
12833    /// [`DeviceDesc::for_adapter`]'s.
12834    ///
12835    /// The null preset *has* more than the default request asks for, and a
12836    /// granted feature set is the intersection of the two — so this is how a test
12837    /// reaches a device with something the ordinary one lacks. What it exists for
12838    /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12839    /// device has no line fill mode, which is the other half of the wireframe
12840    /// pair of tests below.
12841    fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12842        let recorder = Recorder::new();
12843        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12844        let adapter = instance.adapters().remove(0);
12845        let device = instance
12846            .create_device(&DeviceDesc {
12847                optional_features,
12848                ..DeviceDesc::for_adapter(adapter.id)
12849            })
12850            .expect("the null backend always opens");
12851        let queue = device.queue(QueueKind::Graphics).expect("always present");
12852        (recorder, device, queue)
12853    }
12854
12855    /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12856    ///
12857    /// **Insertion order is what the caller decides**, and it is load-bearing:
12858    /// the slot an object lands in is topic 25's hysteresis key. So
12859    /// every test below places its objects in the order the frame used to hold
12860    /// them — the cube first, wherever there is one.
12861    /// The label of every graphics pipeline `recorder`'s device has created, in
12862    /// creation order — so `labels[handle.index()]` names the pipeline a bind
12863    /// of `handle` bound.
12864    ///
12865    /// What lets two renderers' bind streams be compared: `build` compiles only
12866    /// the mesh pipelines its scene draws with, so two scenes' renderers hand
12867    /// out different handle values for the same pipeline, and a label is what
12868    /// stays the same. Valid only while no graphics pipeline was destroyed,
12869    /// since the pool reuses a freed slot — which this asserts.
12870    fn graphics_pipeline_labels(recorder: &Recorder) -> Vec<String> {
12871        let events = recorder.events();
12872        assert!(
12873            !events.iter().any(|event| matches!(
12874                event,
12875                Event::Destroyed {
12876                    kind: ObjectKind::GraphicsPipeline
12877                }
12878            )),
12879            "a graphics pipeline was destroyed, so a handle's index is no longer its creation \
12880             order"
12881        );
12882        events
12883            .into_iter()
12884            .filter_map(|event| match event {
12885                Event::Created {
12886                    kind: ObjectKind::GraphicsPipeline,
12887                    label,
12888                } => Some(label.unwrap_or_default()),
12889                _ => None,
12890            })
12891            .collect()
12892    }
12893
12894    fn place_demo(
12895        renderer: &mut ForwardRenderer,
12896        mesh: usize,
12897        material: usize,
12898        transform: Mat4,
12899    ) -> InstanceHandle {
12900        renderer
12901            .add_instance(&InstanceDesc {
12902                mesh,
12903                material,
12904                transform,
12905            })
12906            .expect("a pool of thousands has room for a handful of objects")
12907    }
12908
12909    /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12910    /// always had.
12911    ///
12912    /// `begin_frame` used to write this object for every caller; the tests below
12913    /// that are about a frame with something in it place it themselves now.
12914    pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12915        place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12916    }
12917
12918    /// The whole renderer builds and tears down against a backend with no
12919    /// driver, which is what makes it testable on every CI leg.
12920    #[test]
12921    fn the_forward_renderer_builds_and_leaks_nothing() {
12922        let (recorder, device, queue) = open();
12923        let before = recorder.total_live_objects();
12924        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12925            .expect("the null backend accepts every descriptor");
12926        assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12927        assert!(recorder.total_live_objects() > before);
12928        renderer.destroy(device.as_ref());
12929        assert_eq!(
12930            recorder.total_live_objects(),
12931            before,
12932            "every object created must be destroyed"
12933        );
12934        recorder.assert_valid();
12935    }
12936
12937    /// The uniform ring really rotates, or a spinning cube is a
12938    /// read-after-write hazard across submissions.
12939    #[test]
12940    fn the_uniform_ring_rotates() {
12941        let (_, device, queue) = open();
12942        let mut renderer =
12943            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12944        let camera = Camera::default();
12945        let light = DirectionalLight::default();
12946
12947        let mut seen = Vec::new();
12948        for _ in 0..FRAMES_IN_FLIGHT * 2 {
12949            renderer
12950                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12951                .expect("write");
12952            seen.push(renderer.primary.uniforms[renderer.frame]);
12953        }
12954        assert_ne!(
12955            seen[0], seen[1],
12956            "consecutive frames must not share a buffer"
12957        );
12958        assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12959        renderer.destroy(device.as_ref());
12960    }
12961
12962    /// **The tonemap's block is a ring too, and it carries the exposure the
12963    /// caller set.**
12964    ///
12965    /// The bytes are the observable rather than the field, because the field is
12966    /// what a renderer that never wired the block up would also have: the claim
12967    /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12968    /// null recorder's write log can say so.
12969    ///
12970    /// The default is checked first — a renderer nobody has called
12971    /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12972    /// `EXPOSURE` constant held, under
12973    /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12974    #[test]
12975    fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12976        let (recorder, device, queue) = open();
12977        let mut renderer =
12978            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12979        let camera = Camera::default();
12980        let light = DirectionalLight::default();
12981
12982        renderer
12983            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12984            .expect("write");
12985        assert_eq!(
12986            recorder
12987                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12988                .expect("begin_frame wrote the block"),
12989            crcbl_shaders::tonemap::TonemapParams {
12990                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12991                curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12992                auto_exposure: false,
12993                coverage_alpha: false,
12994            }
12995            .to_bytes(),
12996            "an untouched renderer must write the exposure the constant used to hold, \
12997             under the operator this renderer starts on",
12998        );
12999
13000        // A value that is neither the default nor a bound, so a block left at
13001        // either would fail.
13002        renderer.set_exposure(3.5);
13003        let mut slots = Vec::new();
13004        for _ in 0..FRAMES_IN_FLIGHT * 2 {
13005            renderer
13006                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13007                .expect("write");
13008            slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
13009            assert_eq!(
13010                recorder
13011                    .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13012                    .expect("begin_frame wrote the block"),
13013                crcbl_shaders::tonemap::TonemapParams {
13014                    exposure: 3.5,
13015                    curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
13016                    auto_exposure: false,
13017                    coverage_alpha: false,
13018                }
13019                .to_bytes(),
13020                "the frame's own block must carry the exposure in force",
13021            );
13022        }
13023        assert_ne!(
13024            slots[0], slots[1],
13025            "consecutive frames must not share a block"
13026        );
13027        assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
13028
13029        renderer.destroy(device.as_ref());
13030    }
13031
13032    /// **The curve reaches the block, and a caller can move it off the
13033    /// default.**
13034    ///
13035    /// The selector is a lane of the same ring the exposure rides in, and a lane
13036    /// nothing wrote would read as
13037    /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
13038    /// whatever a caller asked for — a setter that compiles, a frame that looks
13039    /// right, and a curve that never runs. Since the renderer now *starts* on
13040    /// the fit, that failure would read as a working default, so the check runs
13041    /// in both directions: the untouched block carries the fit, and asking for
13042    /// the clamp changes the bytes on every frame of the ring.
13043    #[test]
13044    fn the_tonemap_block_carries_the_curve_a_caller_selected() {
13045        use crcbl_shaders::tonemap::TonemapCurve;
13046
13047        let (recorder, device, queue) = open();
13048        let mut renderer =
13049            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13050        let camera = Camera::default();
13051        let light = DirectionalLight::default();
13052
13053        assert_eq!(
13054            renderer.tonemap_curve(),
13055            TonemapCurve::Aces,
13056            "a renderer nobody configured must run the operator the goldens were blessed under",
13057        );
13058        renderer
13059            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13060            .expect("write");
13061        let by_default = recorder
13062            .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13063            .expect("begin_frame wrote the block");
13064
13065        renderer.set_tonemap_curve(TonemapCurve::Clamp);
13066        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
13067        for _ in 0..FRAMES_IN_FLIGHT * 2 {
13068            renderer
13069                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13070                .expect("write");
13071            let written = recorder
13072                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13073                .expect("begin_frame wrote the block");
13074            assert_eq!(
13075                written,
13076                crcbl_shaders::tonemap::TonemapParams {
13077                    exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
13078                    curve: TonemapCurve::Clamp,
13079                    auto_exposure: false,
13080                    coverage_alpha: false,
13081                }
13082                .to_bytes(),
13083                "every frame of the ring must carry the selected curve",
13084            );
13085            assert_ne!(
13086                written, by_default,
13087                "and it must differ from the block a default renderer writes",
13088            );
13089        }
13090
13091        // **A readout runs the clamp whatever was selected**, and the selection
13092        // survives it: the caller's curve is still the caller's, the frame's is
13093        // the identity, and the shaded frame after gets the curve back. Asked of
13094        // the fit, which is the selection a readout has something to lose under.
13095        renderer.set_tonemap_curve(TonemapCurve::Aces);
13096        renderer.set_normals_view(true);
13097        assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
13098        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
13099        renderer
13100            .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13101            .expect("write");
13102        assert_eq!(
13103            recorder
13104                .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
13105                .expect("begin_frame wrote the block"),
13106            crcbl_shaders::tonemap::TonemapParams {
13107                exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
13108                curve: TonemapCurve::Clamp,
13109                auto_exposure: false,
13110                coverage_alpha: false,
13111            }
13112            .to_bytes(),
13113            "a debug view's block must carry the clamp, since its pixels are data",
13114        );
13115        renderer.set_normals_view(false);
13116        assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
13117
13118        renderer.destroy(device.as_ref());
13119    }
13120
13121    /// **The exposure is clamped where it is set**, so no caller can reach a
13122    /// frame it cannot get back from.
13123    ///
13124    /// Each case is a different way of leaving the range, and the NaN one is the
13125    /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
13126    /// propagates a NaN into the block, which is a frame of NaN pixels with no
13127    /// key to press to escape it.
13128    #[test]
13129    fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
13130        let (_, device, queue) = open();
13131        let mut renderer =
13132            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13133        assert!(
13134            (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
13135            "the default is {}",
13136            renderer.exposure(),
13137        );
13138
13139        for (asked, expected) in [
13140            (2.0, 2.0),
13141            (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
13142            (f32::INFINITY, EXPOSURE_MAX),
13143            (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
13144            (0.0, EXPOSURE_MIN),
13145            (-8.0, EXPOSURE_MIN),
13146            (f32::NEG_INFINITY, EXPOSURE_MIN),
13147            (f32::NAN, EXPOSURE_MIN),
13148        ] {
13149            renderer.set_exposure(asked);
13150            assert!(
13151                (renderer.exposure() - expected).abs() < f32::EPSILON,
13152                "{asked} was clamped to {}, not {expected}",
13153                renderer.exposure(),
13154            );
13155        }
13156
13157        renderer.destroy(device.as_ref());
13158    }
13159
13160    /// **The debug views resolve in one order, however they are set.**
13161    ///
13162    /// Every one of them rides in one float lane and the shaders test the
13163    /// outermost threshold first, so a renderer with two switches on draws
13164    /// exactly one picture — and which one has to be a rule rather than
13165    /// whichever branch a caller's setter happened to run last. Every
13166    /// combination of the switches is walked, because a precedence written as an
13167    /// `if` chain is right for most of them by accident: a chain in the wrong
13168    /// order agrees with this one on every combination where at most one switch
13169    /// is set.
13170    ///
13171    /// **The two innermost views are the exception the walk is worth most for.**
13172    /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
13173    /// it, so it resolves *last* and its sentinel runs the other way down the
13174    /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
13175    /// *off* sentinel, because it is a pass rather than a branch. Every
13176    /// combination where either is set beside a replacing view is a combination
13177    /// an order written any other way answers differently, and there is no
13178    /// single-switch case that could tell them apart.
13179    ///
13180    /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
13181    /// a panel reads back and the value the shader branches on cannot drift —
13182    /// they are the same function.
13183    #[test]
13184    fn the_debug_views_resolve_in_one_order_however_they_are_set() {
13185        // `w` of the second `float4` of the block — the lane
13186        // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
13187        // spells out, and for its reason.
13188        const AMBIENT_W: usize = 64 + 16 + 12;
13189
13190        let (recorder, device, queue) = open();
13191        let mut renderer =
13192            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13193        let camera = Camera::default();
13194        let light = DirectionalLight::default();
13195
13196        for bent in [false, true] {
13197            for motion in [false, true] {
13198                for occlusion in [false, true] {
13199                    for heatmap in [false, true] {
13200                        for lod in [false, true] {
13201                            for normals in [false, true] {
13202                                for (atlas, cascades) in
13203                                    [false, true].into_iter().flat_map(|atlas| {
13204                                        [false, true].map(|cascades| (atlas, cascades))
13205                                    })
13206                                {
13207                                    renderer.set_bent_normal_view(bent);
13208                                    renderer.set_motion_view(motion);
13209                                    renderer.set_occlusion_view(occlusion);
13210                                    renderer.set_heatmap(heatmap);
13211                                    renderer.set_lod_view(lod);
13212                                    renderer.set_normals_view(normals);
13213                                    renderer.set_atlas_view(atlas);
13214                                    renderer.set_cascade_view(cascades);
13215                                    let set = format!(
13216                                        "bent={bent} motion={motion} occlusion={occlusion} \
13217                                 heatmap={heatmap} lod={lod} normals={normals} \
13218                                 atlas={atlas} cascades={cascades}"
13219                                    );
13220                                    // Each switch reads back what it was set to, whatever
13221                                    // the others are: a caller's toggle is about the
13222                                    // caller's setting, and only `debug_view` is about the
13223                                    // picture.
13224                                    assert_eq!(renderer.bent_normal_view(), bent);
13225                                    assert_eq!(renderer.motion_view(), motion);
13226                                    assert_eq!(renderer.occlusion_view(), occlusion);
13227                                    assert_eq!(renderer.heatmap(), heatmap);
13228                                    assert_eq!(renderer.lod_view(), lod);
13229                                    assert_eq!(renderer.normals_view(), normals);
13230                                    assert_eq!(renderer.atlas_view(), atlas);
13231                                    assert_eq!(renderer.cascade_view(), cascades);
13232
13233                                    let expected = if bent {
13234                                        DebugView::BentNormal
13235                                    } else if motion {
13236                                        DebugView::Motion
13237                                    } else if occlusion {
13238                                        DebugView::AmbientOcclusion
13239                                    } else if heatmap {
13240                                        DebugView::Heatmap
13241                                    } else if lod {
13242                                        DebugView::LodTint
13243                                    } else if normals {
13244                                        DebugView::Normals
13245                                    } else if atlas {
13246                                        // **Below every replacing view above and
13247                                        // above the tint below**, which is the
13248                                        // half of this order no single-switch
13249                                        // case reaches: with a replacing view
13250                                        // also set the frame is that view's, and
13251                                        // with the tint also set the frame is the
13252                                        // atlas.
13253                                        DebugView::ShadowAtlas
13254                                    } else if cascades {
13255                                        // **Last, which is the half of this order a
13256                                        // chain in any other arrangement would get
13257                                        // right by accident.** The cascade tint is a
13258                                        // multiply on the shaded picture, so every
13259                                        // combination that also names a replacing
13260                                        // view has to resolve to *that* view — and
13261                                        // those are exactly the combinations an
13262                                        // `if cascades` written one line higher
13263                                        // would answer differently.
13264                                        DebugView::Cascades
13265                                    } else {
13266                                        DebugView::Shaded
13267                                    };
13268                                    assert_eq!(renderer.debug_view(), expected, "{set}");
13269
13270                                    renderer
13271                                        .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13272                                        .expect("write");
13273                                    let block = recorder
13274                                        .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13275                                        .expect("begin_frame wrote the block");
13276                                    let sentinel = match expected {
13277                                        DebugView::BentNormal => {
13278                                            mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
13279                                        }
13280                                        DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
13281                                        DebugView::AmbientOcclusion => {
13282                                            mesh::FrameUniforms::OCCLUSION_VIEW_ON
13283                                        }
13284                                        DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
13285                                        DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
13286                                        DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
13287                                        DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
13288                                        // **The atlas view carries the *off*
13289                                        // sentinel**, which is what makes this
13290                                        // assertion say something rather than
13291                                        // restate `debug_view_lane`: the colour
13292                                        // pass draws the shaded picture and
13293                                        // `crate::atlas_view`'s pass replaces
13294                                        // it, so a lane of its own here would be
13295                                        // a threshold no shader tests.
13296                                        DebugView::ShadowAtlas | DebugView::Shaded => {
13297                                            mesh::FrameUniforms::NORMALS_VIEW_OFF
13298                                        }
13299                                    };
13300                                    assert_eq!(
13301                                        &block[AMBIENT_W..AMBIENT_W + 4],
13302                                        &sentinel.to_le_bytes(),
13303                                        "{set} resolved to {expected:?}, and the lane says otherwise"
13304                                    );
13305                                    // And the resolve comes off for every one of them:
13306                                    // these frames are read back as data, so their colours
13307                                    // have to stay the ones the shader wrote — see
13308                                    // `resolved_effects`. The whole slot rather than one
13309                                    // tier of it, because which tier the default carries
13310                                    // is not what this is about.
13311                                    assert_eq!(
13312                                        renderer.effects().intersects(Antialiasing::SLOT),
13313                                        expected == DebugView::Shaded,
13314                                        "{set}"
13315                                    );
13316                                }
13317                            }
13318                        }
13319                    }
13320                }
13321            }
13322        }
13323
13324        renderer.destroy(device.as_ref());
13325    }
13326
13327    /// **The atlas viewer records one pass, and only on the frame it is the view
13328    /// showing.**
13329    ///
13330    /// The mechanism no other check in this file can see. Every other debug view
13331    /// is a lane of the frame block, so
13332    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
13333    /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
13334    /// is a claim about the command stream and about nothing else. A switch that
13335    /// resolved correctly and recorded nothing would satisfy every other
13336    /// assertion in this module and draw the frame unchanged.
13337    ///
13338    /// Three arms, and the third is the one that makes the first two mean
13339    /// something:
13340    ///
13341    /// * off — no pass at all, which is what makes the off position
13342    ///   bit-identical for every golden in this workspace;
13343    /// * on — the pass, with the full-screen triangle in it;
13344    /// * on **beside a replacing view** — no pass, because
13345    ///   [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
13346    ///   not what this frame draws. That is the half a `self.atlas_view` read at
13347    ///   the recording site would get wrong while passing both arms above.
13348    ///
13349    /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
13350    /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
13351    /// the draw count follows.**
13352    ///
13353    /// The viewer fills every display pixel with a `DontCare` load, so a
13354    /// tonemapped frame or a grid recorded under it is stored and discarded.
13355    /// The pass counts go red if either comes back; the counter goes red if
13356    /// `counters` still charges the frame for the triangles it no longer
13357    /// records.
13358    #[test]
13359    fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
13360        let _seam = ssao_split_switch();
13361        let (recorder, device, queue) = open();
13362        let mut renderer =
13363            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13364        renderer
13365            .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
13366            .expect("the null backend builds every pipeline");
13367        renderer.set_atlas_view(true);
13368        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
13369
13370        let viewing = frame(device.as_ref(), &mut renderer, queue);
13371        let opened = |label: &str| {
13372            recorder
13373                .commands()
13374                .iter()
13375                .filter(|command| {
13376                    matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
13377                })
13378                .count()
13379        };
13380        assert_eq!(opened(crate::atlas_view::LABEL), 1);
13381        assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
13382        assert_eq!(opened("grid"), 0, "and the grid drawn over it");
13383        assert_eq!(
13384            renderer.counters().draws,
13385            recorded_draws(&recorder) as u64,
13386            "the counter charges the frame for exactly the draws it recorded"
13387        );
13388        viewing.finish(device.as_ref(), renderer);
13389    }
13390
13391    #[test]
13392    fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
13393        use crcbl_hal::null::Command;
13394
13395        let (recorder, device, queue) = open();
13396        let device = device.as_ref();
13397        let mut renderer =
13398            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
13399        let (camera, sun) = (Camera::default(), DirectionalLight::default());
13400
13401        // How many times the viewer's pass was opened since `from`, which is
13402        // where the previous arm's commands ended.
13403        let opened = |from: usize| {
13404            recorder.commands()[from..]
13405                .iter()
13406                .filter(|command| {
13407                    matches!(
13408                        command.opens_pass(),
13409                        Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
13410                    )
13411                })
13412                .count()
13413        };
13414
13415        let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13416        assert_eq!(
13417            opened(0),
13418            0,
13419            "a frame drawing the shaded picture recorded the atlas viewer's pass"
13420        );
13421        let after_shaded = recorder.commands().len();
13422        shaded.release(device);
13423
13424        renderer.set_atlas_view(true);
13425        assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
13426        let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13427        assert_eq!(
13428            opened(after_shaded),
13429            1,
13430            "the atlas viewer is on and its pass was not recorded exactly once"
13431        );
13432        // And what it recorded is the over-sized triangle and nothing else: a
13433        // pass that bound a pipeline and drew no vertices would open above and
13434        // leave the frame the tonemap wrote.
13435        let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
13436            .into_iter()
13437            .filter_map(|command| match command {
13438                Command::Draw {
13439                    vertices,
13440                    instances,
13441                } => Some((
13442                    vertices.end - vertices.start,
13443                    instances.end - instances.start,
13444                )),
13445                _ => None,
13446            })
13447            .collect();
13448        assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
13449        let after_viewing = recorder.commands().len();
13450        viewing.release(device);
13451
13452        // The switch left on, and a replacing view asked for over the top of it.
13453        renderer.set_normals_view(true);
13454        assert_eq!(
13455            renderer.debug_view(),
13456            DebugView::Normals,
13457            "the atlas view does not lose to a replacing view, so the arm below asks nothing"
13458        );
13459        let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
13460        assert_eq!(
13461            opened(after_viewing),
13462            0,
13463            "the frame resolved to the normals view and still recorded the atlas viewer's \
13464             pass over the top of it"
13465        );
13466        normals.release(device);
13467
13468        renderer.destroy(device);
13469    }
13470
13471    /// **The heatmap moves the ambient's last lane and no other byte**, and
13472    /// switching it off puts the block back.
13473    ///
13474    /// The normals view's assertion below, for the outermost of the three: the
13475    /// overlay costs one lane, so every golden image ever blessed is untouched
13476    /// by the feature existing. The `lod_params` row the heatmap reads is
13477    /// written every frame whether it is on or not — it is the numbers the
13478    /// selection used — so this compares two frames of the *same* camera and
13479    /// budget, where that row is equal on both sides and any byte outside the
13480    /// lane is a real difference.
13481    #[test]
13482    fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
13483        const AMBIENT_W: usize = 64 + 16 + 12;
13484
13485        // Held for the whole comparison, and it is not this check's own knob:
13486        // `r_shadow_filter` and `r_shadow_split` land in the block's
13487        // `shadow_filter` row on every `begin_frame`, and the filter checks in
13488        // this module move them under this lock while `cargo test` runs the
13489        // module's checks as threads of one process. Two frames read either side
13490        // of such a move differ at that row, which is outside every lane below —
13491        // one run in twelve, measured 2026-09-04.
13492        let _filter = shadow_filter_switch();
13493        let (recorder, device, queue) = open();
13494        let mut renderer =
13495            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13496        let camera = Camera::default();
13497        let light = DirectionalLight::default();
13498        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
13499            renderer
13500                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13501                .expect("write");
13502            recorder
13503                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13504                .expect("begin_frame wrote the block")
13505        };
13506
13507        assert!(
13508            !renderer.heatmap(),
13509            "the heatmap has to be off in a renderer nobody has asked",
13510        );
13511        let shaded = block(&mut renderer);
13512        assert_eq!(
13513            &shaded[AMBIENT_W..AMBIENT_W + 4],
13514            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
13515            "an untouched renderer must write the value every golden image was blessed with",
13516        );
13517
13518        renderer.set_heatmap(true);
13519        let heatmap = block(&mut renderer);
13520        assert_eq!(
13521            &heatmap[AMBIENT_W..AMBIENT_W + 4],
13522            &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
13523            "the switch has to reach the lane the mesh stage branches on",
13524        );
13525        let outside: Vec<usize> = shaded
13526            .iter()
13527            .zip(heatmap.iter())
13528            .enumerate()
13529            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13530            .map(|(at, _)| at)
13531            .collect();
13532        assert!(
13533            outside.is_empty(),
13534            "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
13535        );
13536
13537        renderer.set_heatmap(false);
13538        assert_eq!(
13539            block(&mut renderer),
13540            shaded,
13541            "switching the view off has to put the block back, not just stop reporting it",
13542        );
13543
13544        renderer.destroy(device.as_ref());
13545    }
13546
13547    /// **The normals view moves one lane of the frame block and nothing else.**
13548    ///
13549    /// The mechanism, at the level a null device can observe it: which bytes of
13550    /// the buffer `mesh.slang` reads changed. A field on the renderer would say
13551    /// only that a flag moved; the block is what the shader actually branches on.
13552    ///
13553    /// Four claims, and each rules out a different way of passing wrongly:
13554    ///
13555    /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
13556    ///   is what makes every golden image untouched by this feature;
13557    /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
13558    ///   shader reads, at the offset `std140` puts it at rather than at one this
13559    ///   test picked;
13560    /// * **those four bytes are the only ones that moved**, so the switch did not
13561    ///   come at the cost of the ambient colour beside it or of any matrix;
13562    /// * and switching off puts the block back exactly, so the view is a toggle
13563    ///   rather than a one-way door.
13564    ///
13565    /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
13566    /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
13567    #[test]
13568    fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
13569        // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
13570        // then three floats of ambient colour. Spelled as the sum rather than as
13571        // `92` so that a member arriving before it is a compile-time question
13572        // about `FrameUniforms`' own layout and not a silent read of a matrix.
13573        const AMBIENT_W: usize = 64 + 16 + 12;
13574
13575        // Held for the whole comparison, and it is not this check's own knob:
13576        // `r_shadow_filter` and `r_shadow_split` land in the block's
13577        // `shadow_filter` row on every `begin_frame`, and the filter checks in
13578        // this module move them under this lock while `cargo test` runs the
13579        // module's checks as threads of one process. Two frames read either side
13580        // of such a move differ at that row, which is outside every lane below —
13581        // one run in twelve, measured 2026-09-04.
13582        let _filter = shadow_filter_switch();
13583        let (recorder, device, queue) = open();
13584        let mut renderer =
13585            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13586        let camera = Camera::default();
13587        let light = DirectionalLight::default();
13588        let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
13589            renderer
13590                .begin_frame(device.as_ref(), &camera, &light, (64, 48))
13591                .expect("write");
13592            recorder
13593                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
13594                .expect("begin_frame wrote the block")
13595        };
13596
13597        assert!(
13598            !renderer.normals_view(),
13599            "the normals view has to be off in a renderer nobody has asked",
13600        );
13601        let shaded = block(&mut renderer);
13602        assert_eq!(
13603            &shaded[AMBIENT_W..AMBIENT_W + 4],
13604            &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
13605            "an untouched renderer must write the value every golden image was blessed with",
13606        );
13607
13608        renderer.set_normals_view(true);
13609        assert!(renderer.normals_view());
13610        let normals = block(&mut renderer);
13611        assert_eq!(
13612            &normals[AMBIENT_W..AMBIENT_W + 4],
13613            &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
13614            "the switch has to reach the lane the fragment stage branches on",
13615        );
13616        // The bytes that moved, and they all have to be inside the lane — not
13617        // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
13618        // and an equality against the whole range would be a test about IEEE 754
13619        // rather than about the block.
13620        let outside: Vec<usize> = shaded
13621            .iter()
13622            .zip(normals.iter())
13623            .enumerate()
13624            .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13625            .map(|(at, _)| at)
13626            .collect();
13627        assert!(
13628            outside.is_empty(),
13629            "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13630        );
13631
13632        renderer.set_normals_view(false);
13633        assert!(!renderer.normals_view());
13634        assert_eq!(
13635            block(&mut renderer),
13636            shaded,
13637            "switching the view off has to put the block back, not just stop reporting it",
13638        );
13639
13640        renderer.destroy(device.as_ref());
13641    }
13642
13643    /// **A frame uploads the instances a caller moved, and a frame nobody moved
13644    /// anything in uploads nothing at all.**
13645    ///
13646    /// The second half is the stronger claim and it is the one that needed the
13647    /// cube to become an ordinary instance: `begin_frame` used to take the
13648    /// cube's transform as an argument and write it into the pool every frame,
13649    /// so that slot was dirty in every ring slot forever and a motionless scene
13650    /// paid a spinning one's transfer. The bytes were identical, so no golden
13651    /// image could ever have shown it — the recorder's write log is the only
13652    /// place the difference is visible.
13653    ///
13654    /// The pyramid is here so that "only the one that moved" is a claim about a
13655    /// choice: with one instance in the array, uploading it and uploading
13656    /// everything are the same event.
13657    #[test]
13658    fn only_the_instance_that_moved_is_uploaded() {
13659        let (recorder, device, queue) = open();
13660        let mut renderer =
13661            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13662        let instance_buffers = renderer.instances.buffers().to_vec();
13663        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13664        place_demo(
13665            &mut renderer,
13666            DEMO_PYRAMID,
13667            DEMO_UNTINTED,
13668            Mat4::from_translation(Vec3::X),
13669        );
13670
13671        // Both instances are dirty in *every* slot when they are inserted, so
13672        // the first frames upload both however well delta upload works. The ring
13673        // has to be walked right through before an upload is evidence about the
13674        // delta rather than about initialisation.
13675        let frame = |renderer: &mut ForwardRenderer| {
13676            renderer
13677                .begin_frame(
13678                    device.as_ref(),
13679                    &Camera::default(),
13680                    &DirectionalLight::default(),
13681                    (64, 48),
13682                )
13683                .expect("write");
13684        };
13685        for _ in 0..FRAMES_IN_FLIGHT {
13686            frame(&mut renderer);
13687        }
13688        let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13689            recorder
13690                .events()
13691                .into_iter()
13692                .skip(from)
13693                .filter_map(|event| match event {
13694                    crcbl_hal::null::Event::BufferWritten {
13695                        buffer,
13696                        offset,
13697                        len,
13698                    } if instance_buffers.contains(&buffer) => Some((offset, len)),
13699                    _ => None,
13700                })
13701                .collect()
13702        };
13703
13704        let before = recorder.events().len();
13705        frame(&mut renderer);
13706        assert_eq!(
13707            instance_writes(before),
13708            [],
13709            "a frame in which nothing moved must upload no instance bytes at all"
13710        );
13711
13712        let before = recorder.events().len();
13713        let model = ForwardRenderer::spin(1.25);
13714        renderer.set_instance(
13715            cube,
13716            &InstanceDesc {
13717                mesh: DEMO_CUBE,
13718                material: DEMO_UNTINTED,
13719                transform: model,
13720            },
13721        );
13722        frame(&mut renderer);
13723        assert_eq!(
13724            renderer
13725                .instances
13726                .get(cube)
13727                .expect("the cube is live")
13728                .transform,
13729            model.to_cols_array(),
13730            "the model matrix must land in the instance, not the uniform block"
13731        );
13732        let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13733            * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13734        assert_eq!(
13735            instance_writes(before),
13736            [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13737            "a steady-state frame must upload exactly the one instance that changed"
13738        );
13739
13740        renderer.destroy(device.as_ref());
13741        recorder.assert_valid();
13742    }
13743
13744    /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13745    /// it back for the next object to reuse.**
13746    ///
13747    /// The three-call bookkeeping every caller of the instance API depends on,
13748    /// checked on the pool rather than on the recorder. A `set_instance` that
13749    /// inserted instead would take a fresh slot per call — the pool exhausted in
13750    /// a few thousand frames of a caller that writes a transform per frame, which
13751    /// is what every sample does — and every slot it abandoned would stay
13752    /// **live**, so the frame would draw a copy of the object at each transform
13753    /// it had ever been given. Neither is something a golden image would show
13754    /// until the pool ran out.
13755    ///
13756    /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13757    /// reads the recorder; this is the bookkeeping half and reads the pool, which
13758    /// is where an abandoned slot would still be counted.
13759    ///
13760    /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13761    /// slot carries topic 25's hysteresis state — the reuse below is
13762    /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13763    /// previous occupant's expanded groups.
13764    #[test]
13765    fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13766        for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13767            let (recorder, device, queue) = open();
13768            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13769                .expect("built");
13770            // The null backend takes an indirect tail, so the DAG is placeable
13771            // here; the arm that cannot select a level refuses before an
13772            // application ever calls this.
13773            assert!(
13774                renderer.selects_levels(),
13775                "an indirect tail chooses a level for every mesh, DAG included"
13776            );
13777            // What the pool holds before anything is placed, which is nothing: a
13778            // renderer places no object of its own any more.
13779            let resident = renderer.instances.len();
13780            assert_eq!(resident, 0, "a fresh renderer holds no objects");
13781
13782            let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13783            let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13784            assert_eq!(
13785                renderer.instances.len(),
13786                resident + 1,
13787                "mesh {mesh}: add_instance takes one slot"
13788            );
13789
13790            // The rewrite is the whole test: the same handle, the same slot
13791            // count, and the new transform in it.
13792            let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13793            renderer.set_instance(
13794                handle,
13795                &InstanceDesc {
13796                    mesh,
13797                    material: DEMO_UNTINTED,
13798                    transform: second,
13799                },
13800            );
13801            assert_eq!(
13802                renderer.instances.len(),
13803                resident + 1,
13804                "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13805            );
13806            assert_eq!(
13807                renderer.instances.slot_count(),
13808                u32::try_from(resident + 1).expect("a handful of instances"),
13809                "mesh {mesh}: set_instance must not have reached past the slot it holds"
13810            );
13811            assert_eq!(
13812                renderer
13813                    .instances
13814                    .get(handle)
13815                    .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13816                    .transform,
13817                second.to_cols_array(),
13818                "mesh {mesh}: set_instance must have written the second transform"
13819            );
13820
13821            // And a removal gives the slot back, so a caller toggling an object
13822            // is not a leak either.
13823            renderer.remove_instance(handle);
13824            assert_eq!(
13825                renderer.instances.len(),
13826                resident,
13827                "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13828            );
13829            place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13830            assert_eq!(
13831                renderer.instances.slot_count(),
13832                u32::try_from(resident + 1).expect("a handful of instances"),
13833                "mesh {mesh}: the object after a removal must reuse the freed slot"
13834            );
13835
13836            renderer.destroy(device.as_ref());
13837            recorder.assert_valid();
13838        }
13839    }
13840
13841    /// **The description resolves to the ids the renderer used to hand itself**:
13842    /// one table entry per description mesh, in description order, with the DAG
13843    /// occupying one per level after them — and every level's vertex base
13844    /// measured from level 0's, which is zero.
13845    ///
13846    /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13847    /// box out of the entry the *instance* names. So a description walked in
13848    /// another order, or a DAG whose levels landed among the flat meshes, would
13849    /// leave every instance naming a mesh that is not its own: the cube culled
13850    /// against the pyramid's box, the dunes patch drawn as an open box. Every
13851    /// one of those is a frame that still looks like a frame.
13852    ///
13853    /// The bases are asserted against the table bytes rather than against
13854    /// `ResidentMesh`, because the table is what the GPU reads.
13855    #[test]
13856    fn the_description_resolves_to_the_ids_it_was_written_in() {
13857        let (recorder, device, queue) = open();
13858        let renderer =
13859            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13860
13861        assert_eq!(
13862            renderer.mesh_ids,
13863            [0, 1, 2, 3],
13864            "the four description meshes take the first four table entries, in order"
13865        );
13866
13867        // The DAG's coarser levels follow level 0, so a cut that spans them
13868        // reads entries the flat meshes never occupied.
13869        let scene = scene::demo();
13870        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13871            panic!("the demo description's fourth mesh is the DAG");
13872        };
13873        let level_ids: Vec<u32> = (0..dag.levels.len())
13874            .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13875            .collect();
13876        assert!(
13877            level_ids
13878                .iter()
13879                .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13880            "every dunes level is past the flat residents: {level_ids:?}"
13881        );
13882
13883        // **Level 0 is at the pool's own first vertex**, which is what makes
13884        // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13885        // sum the mesh stage forms with the instance's own base.
13886        let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13887            .iter()
13888            .map(|&id| mesh_entry(&recorder, &renderer, id))
13889            .collect();
13890        let level_zero = entries[0].base_vertex;
13891        assert_eq!(
13892            level_zero,
13893            mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13894                + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13895            "the DAG starts where the last flat resident ends"
13896        );
13897        let bases: Vec<u32> = entries
13898            .iter()
13899            .map(|entry| {
13900                entry
13901                    .base_vertex
13902                    .checked_sub(level_zero)
13903                    .expect("a level below level 0 would wrap the offset a cluster carries")
13904            })
13905            .collect();
13906        assert_eq!(
13907            bases[0], 0,
13908            "level 0 is the base every other is measured from"
13909        );
13910        assert!(
13911            bases.windows(2).all(|pair| pair[0] < pair[1]),
13912            "each level starts past the one below it: {bases:?}"
13913        );
13914
13915        renderer.destroy(device.as_ref());
13916        recorder.assert_valid();
13917    }
13918
13919    /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13920    ///
13921    /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13922    /// number of DAGs, and until this nothing had put either through it — every
13923    /// golden image and every end-to-end run is `scene::demo()`, whose four
13924    /// meshes hold one DAG between them.
13925    ///
13926    /// What only a second DAG exercises is the **concatenation**: `level_groups`
13927    /// is every DAG's groups laid end to end and a DAG reaches its own run
13928    /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13929    /// which is zero for the first one and therefore invisible while there is
13930    /// only one. A second DAG whose records still named the first's groups would
13931    /// descend a hierarchy belonging to another surface — a cut that is a
13932    /// plausible picture and matches no assertion the CPU makes about the frame.
13933    ///
13934    /// On the mesh path, because that is where the offset is *used*: an indirect
13935    /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13936    ///
13937    /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13938    #[test]
13939    fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13940        use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13941
13942        let recorder = Recorder::new();
13943        let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13944
13945        // The engine has one DAG, so a second one is a second copy of it. That
13946        // is the whole point: two DAGs whose *groups* are alike is the case
13947        // where reaching the wrong run still produces a cut, and so the case a
13948        // frame comparison could never catch.
13949        let mut scene = scene::demo();
13950        let mut again = scene.meshes[DEMO_DUNES].clone();
13951        again.label = "dunes again".into();
13952        scene.meshes.push(again);
13953        // Room for the second copy. Doubling rather than measuring, because the
13954        // number that matters is that the description carries its own sizes at
13955        // all — see `Capacities`, which is the caller's to choose.
13956        scene.capacities.vertices *= 2;
13957        scene.capacities.indices *= 2;
13958        let second_dag = scene.meshes.len() - 1;
13959
13960        let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13961            panic!("the demo description's fourth mesh is the DAG");
13962        };
13963        let levels = dag.levels.len();
13964        let groups = dag.level_groups().len();
13965        assert!(groups > 0, "a DAG with no groups would select nothing");
13966
13967        let mut renderer =
13968            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13969                .expect("a five-mesh description with two DAGs is one this can make resident");
13970
13971        // Every level of both is its own table entry, laid down in description
13972        // order, so the second DAG's level 0 is a whole hierarchy past the
13973        // first's.
13974        assert_eq!(
13975            renderer.mesh_ids.len(),
13976            scene.meshes.len(),
13977            "one id per description mesh, whatever the count"
13978        );
13979        assert_eq!(
13980            renderer.mesh_ids[second_dag],
13981            renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13982            "the second DAG's level 0 starts past every level of the first"
13983        );
13984
13985        // **The hysteresis state is per instance per resident group**, and
13986        // `group_stride` is what says how many groups that is. One DAG made this
13987        // number a single hierarchy's; two is what tells a stride that sums from
13988        // one that took the first answer it found.
13989        assert_eq!(
13990            renderer.primary.draws.group_stride(),
13991            u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13992            "every resident DAG's groups are in the stride, not just the first's"
13993        );
13994
13995        // The records themselves: which group each cluster produces and which
13996        // contains it, as the amplification stage reads them.
13997        let clusters = renderer
13998            .clusters
13999            .as_ref()
14000            .expect("the mesh path builds a cluster pool");
14001        let selection = recorder
14002            .buffer_bytes(clusters.selection())
14003            .expect("the selection records are live");
14004        // Entries are laid down in description order, a flat mesh taking one and
14005        // a DAG one per level — so the second DAG's start a hierarchy past the
14006        // first's, which start past the three flat residents.
14007        let first_entry = DEMO_DUNES;
14008        let record = |entry: usize| -> Vec<ClusterSelect> {
14009            let range = clusters.range(entry).expect("one range per entry");
14010            (range.base..range.base + range.count)
14011                .map(|cluster| {
14012                    let at = cluster as usize * CLUSTER_SELECT_STRIDE;
14013                    ClusterSelect::from_bytes(
14014                        selection[at..at + CLUSTER_SELECT_STRIDE]
14015                            .try_into()
14016                            .expect("one whole record"),
14017                    )
14018                })
14019                .collect()
14020        };
14021        // The named group of every record that has one, per DAG — and the count,
14022        // because a comparison over an empty set is a check that cannot fail.
14023        let named = |base: usize| -> Vec<u32> {
14024            (base..base + levels)
14025                .flat_map(record)
14026                .flat_map(|select| {
14027                    let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
14028                        .then_some(select.producer_group);
14029                    let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
14030                        .then_some(select.container_group);
14031                    producer.into_iter().chain(container)
14032                })
14033                .collect()
14034        };
14035        let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
14036        let first = named(first_entry);
14037        let second = named(first_entry + levels);
14038        assert!(
14039            !first.is_empty() && first.len() == second.len(),
14040            "the two copies must name the same number of groups: {} against {}",
14041            first.len(),
14042            second.len()
14043        );
14044        assert!(
14045            first.iter().all(|&group| group < boundary),
14046            "the first DAG's records stay inside its own run: {first:?}"
14047        );
14048        assert!(
14049            second
14050                .iter()
14051                .all(|&group| (boundary..boundary * 2).contains(&group)),
14052            "the second DAG's records must name the groups past the first's, and \
14053             `first_group` is the only thing that puts them there: {second:?}"
14054        );
14055
14056        // And both are placeable through the runtime API, which is what a
14057        // description of a shape no `set_*` method names is *for*.
14058        let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
14059            renderer
14060                .add_instance(&InstanceDesc {
14061                    mesh,
14062                    material: DEMO_UNTINTED,
14063                    transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
14064                })
14065                .expect("the pool has room")
14066        };
14067        let near = place(&mut renderer, DEMO_DUNES, -64.0);
14068        let far = place(&mut renderer, second_dag, 64.0);
14069        let index = |handle| {
14070            renderer
14071                .instances
14072                .index(handle)
14073                .expect("a just-added instance is live")
14074        };
14075        assert_ne!(
14076            index(near),
14077            index(far),
14078            "two instances take two slots, and the index is the hysteresis key"
14079        );
14080        assert_eq!(
14081            renderer.instances.get(far).expect("live").mesh,
14082            renderer.mesh_ids[second_dag],
14083            "an InstanceDesc's mesh index resolves through the description, not through \
14084             a table id the caller cannot know"
14085        );
14086
14087        renderer.destroy(device.as_ref());
14088        recorder.assert_valid();
14089    }
14090
14091    /// **A description the renderer cannot make resident is refused before the
14092    /// first device object exists**, so a rejection leaks nothing.
14093    ///
14094    /// `build` hands the geometry pool and the material table to the rollback
14095    /// and then creates a dozen objects with `?` between them. A check that ran
14096    /// part way down that list would be a new early exit on the wrong side of a
14097    /// handover, and the pool would go with it — which is exactly the leak
14098    /// `Rollback` exists to prevent and which
14099    /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
14100    /// only walks the happy path.
14101    ///
14102    /// Each arm below is a *different* refusal, so a check that stopped running
14103    /// would show up as one arm leaking rather than as all of them — and each
14104    /// names a fragment of the message it must be refused *with*, or an arm
14105    /// would pass on some other check's answer.
14106    /// **A description with no meshes is refused by name**, before anything
14107    /// is created, rather than reaching the mesh table's sizing with nothing
14108    /// to size it from.
14109    #[test]
14110    fn a_scene_with_no_meshes_is_refused_by_name() {
14111        let (recorder, device, queue) = open();
14112        let before = recorder.total_live_objects();
14113        let mut scene = scene::demo();
14114        scene.meshes.clear();
14115        let error =
14116            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14117                .expect_err("a scene of no meshes must be refused");
14118        assert!(
14119            error.to_string().contains("at least one mesh"),
14120            "the refusal says what is missing: {error}"
14121        );
14122        assert_eq!(
14123            recorder.total_live_objects(),
14124            before,
14125            "the refusal created something"
14126        );
14127    }
14128
14129    #[test]
14130    fn a_refused_description_creates_nothing_at_all() {
14131        /// One way of writing a description the renderer cannot build, and the
14132        /// words that say it was this refusal rather than another.
14133        type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
14134
14135        let cases: [Break; 9] = [
14136            (
14137                "a row naming a layer the page has not got",
14138                |scene| {
14139                    scene.materials[DEMO_TEXTURED].base_color_texture = 7;
14140                },
14141                "material row 2 samples base-colour page layer 7",
14142            ),
14143            // And the same on the two kinds rung 3 added, because `check_scene`
14144            // reads a different column of the row for each: a check written per
14145            // kind is only worth what its arms cover, and a column nobody broke
14146            // here could be read out of the wrong material field for ever.
14147            // `demo` names no layer of either, so any index at all is past the
14148            // end.
14149            (
14150                "a row naming a packed-page layer the page has not got",
14151                |scene| {
14152                    scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
14153                },
14154                "material row 2 samples metallic-roughness-occlusion page layer 3",
14155            ),
14156            (
14157                "a row naming an emissive layer the page has not got",
14158                |scene| {
14159                    scene.materials[DEMO_TEXTURED].emissive_texture = 3;
14160                },
14161                "material row 2 samples emissive page layer 3",
14162            ),
14163            // The one page refusal a caller can actually spell: `push_layer`
14164            // takes bytes it cannot measure against the extent.
14165            (
14166                "a page layer of the wrong length",
14167                |scene| {
14168                    scene.page = scene::PageDesc::empty();
14169                    scene
14170                        .page
14171                        .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
14172                    scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
14173                    scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
14174                },
14175                "base-colour page layer 0 carries 4 bytes",
14176            ),
14177            (
14178                "a DAG level with no vertices",
14179                |scene| {
14180                    let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
14181                    else {
14182                        panic!("the demo description's fourth mesh is the DAG");
14183                    };
14184                    levels.pop();
14185                },
14186                "vertex array(s) for a DAG of",
14187            ),
14188            // The four capacities, each of which is a pool a caller sized and
14189            // a description outgrew. Written as a capacity the description is
14190            // too large for rather than as a description too large for the
14191            // default, because that is the shape of the mistake: the numbers on
14192            // `Capacities` are the ones an application picks.
14193            (
14194                "more vertices than the pool holds",
14195                |scene| {
14196                    scene.capacities.vertices = 1;
14197                },
14198                "the vertex pool holds 1 and the description needs",
14199            ),
14200            (
14201                "more indices than the pool holds",
14202                |scene| {
14203                    scene.capacities.indices = 1;
14204                },
14205                "the index pool holds 1 and the description needs",
14206            ),
14207            (
14208                "more meshes than the table holds",
14209                |scene| {
14210                    scene.capacities.meshes = 1;
14211                },
14212                "the mesh table holds 1 and the description needs",
14213            ),
14214            (
14215                "more material rows than the table holds",
14216                |scene| {
14217                    scene.capacities.materials = 2;
14218                },
14219                "the material table holds 2 and the description needs 3",
14220            ),
14221        ];
14222
14223        for (what, break_it, says) in cases {
14224            let (recorder, device, queue) = open();
14225            let before = recorder.total_live_objects();
14226            let mut scene = scene::demo();
14227            break_it(&mut scene);
14228            let error =
14229                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14230                    .expect_err(&format!("{what} must be refused"));
14231            assert!(
14232                matches!(error, HalError::InvalidDescriptor(_)),
14233                "{what} must be refused as an invalid descriptor, not as {error:?}"
14234            );
14235            assert!(
14236                error.to_string().contains(says),
14237                "{what} must be refused with a message saying so, and this one says {error}"
14238            );
14239            assert_eq!(
14240                recorder.total_live_objects(),
14241                before,
14242                "{what} was refused after something had been created, and the rollback \
14243                 is the only thing that could have released it"
14244            );
14245            recorder.assert_valid();
14246        }
14247
14248        // **And the refusal that is not free**, which is the half of the
14249        // handover every arm above walks past: `check_scene` settles what the
14250        // whole description says, and what one mesh's *bytes* say is the pool's,
14251        // which only sees them one upload at a time. Vertex bytes that are not a
14252        // whole number of vertices reach `MeshPool::upload` — so the third of
14253        // the four meshes is refused with the pool created, two device-local
14254        // buffers in it and the first two meshes already staged into them.
14255        // `build_geometry` is what releases that, and it can only do so because
14256        // the pool is not the rollback's until it has returned.
14257        let (recorder, device, queue) = open();
14258        let before = recorder.total_live_objects();
14259        // So the count below is this build's and not `open`'s.
14260        recorder.clear();
14261        let mut scene = scene::demo();
14262        let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
14263            panic!("the demo description's third mesh is flat");
14264        };
14265        vertices.to_mut().push(0);
14266        let error =
14267            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14268                .expect_err("a mesh of part of a vertex must be refused");
14269        assert!(
14270            error.to_string().contains("is not a whole number of"),
14271            "the pool's own refusal reaches the caller with its numbers, and this \
14272             one says {error}"
14273        );
14274        assert!(
14275            recorder
14276                .events()
14277                .iter()
14278                .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
14279            "this arm is evidence about the rollback only if the refusal came after \
14280             something had been created"
14281        );
14282        assert_eq!(
14283            recorder.total_live_objects(),
14284            before,
14285            "a mesh refused part way through the list left the geometry pool behind, \
14286             which is exactly what `build_geometry` being self-cleaning is for"
14287        );
14288        recorder.assert_valid();
14289    }
14290
14291    /// **The one capacity a description cannot be checked against, and the one
14292    /// an application is expected to handle while it runs.**
14293    ///
14294    /// Every other number on [`scene::Capacities`] sizes something the
14295    /// description fills once, so `check_scene` refuses an over-large one before
14296    /// a device object exists. Objects are placed at any point in a renderer's
14297    /// life, so the only honest answer for that one is the error
14298    /// [`ForwardRenderer::add_instance`] returns — and it returns
14299    /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
14300    /// what is in it survive to the caller that chose them.
14301    ///
14302    /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
14303    /// value of its own rather than the default, which is what makes the pool
14304    /// fillable at all: a renderer that ignored the number the description
14305    /// carries and reserved the default would draw every frame in the tree
14306    /// identically and refuse nothing here.
14307    #[test]
14308    fn a_full_instance_pool_reaches_the_application_that_sized_it() {
14309        let (recorder, device, queue) = open();
14310        let mut scene = scene::demo();
14311        scene.capacities.instances = 2;
14312        let mut renderer =
14313            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14314                .expect("a scene with room for two objects builds");
14315        let place = |renderer: &mut ForwardRenderer| {
14316            renderer.add_instance(&InstanceDesc {
14317                mesh: DEMO_CUBE,
14318                material: DEMO_UNTINTED,
14319                transform: Mat4::IDENTITY,
14320            })
14321        };
14322        place(&mut renderer).expect("the first of two");
14323        place(&mut renderer).expect("the second of two");
14324        let error = place(&mut renderer).expect_err("a third object has no slot to go in");
14325        assert!(
14326            matches!(
14327                error,
14328                InstancePoolError::PoolFull {
14329                    capacity: 2,
14330                    in_use: 2
14331                }
14332            ),
14333            "a full pool must reach the caller as a full pool, with the capacity it \
14334             chose; this arrived as {error}"
14335        );
14336        renderer.destroy(device.as_ref());
14337        recorder.assert_valid();
14338    }
14339
14340    /// **One mesh and one material row is a scene, and it draws.**
14341    ///
14342    /// The floor is gone. `with_scene` used to refuse anything shorter than
14343    /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
14344    /// demo wrappers named those entries by position, and the renderer's own
14345    /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
14346    /// `DEMO_DUNES` besides. So an application's own description was not merely
14347    /// refused: with the check removed it would have panicked out of `build`.
14348    ///
14349    /// A frame is recorded rather than only a build, because that is where the
14350    /// positional indexing was: the bucket table, the cluster ranges and the
14351    /// draw-argument blocks are all one-per-description-mesh, and a renderer that
14352    /// still assumed four would come apart here rather than at `with_scene`.
14353    #[test]
14354    fn a_description_smaller_than_the_demo_is_a_scene() {
14355        use std::borrow::Cow;
14356
14357        let scene = SceneDesc {
14358            meshes: vec![scene::MeshDesc {
14359                label: Cow::Borrowed("the only mesh"),
14360                geometry: Geometry::Flat {
14361                    vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
14362                    uv_range: crcbl_shaders::mesh::demo_uv_range(),
14363                    indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
14364                    clusters: crcbl_shaders::meshlet::cube_clusters(),
14365                    flags: 0,
14366                },
14367            }],
14368            materials: vec![mesh::GpuMaterial::UNTINTED],
14369            page: scene::PageDesc::empty(),
14370            probes: scene::ProbeGrid::default(),
14371            capacities: scene::Capacities::default(),
14372        };
14373        assert!(
14374            scene.meshes.len() < scene::demo().meshes.len()
14375                && scene.materials.len() < scene::demo().materials.len(),
14376            "this description must be smaller than the demo's in both, or it says nothing \
14377             about the floor"
14378        );
14379
14380        let (recorder, device, queue) = open();
14381        let mut renderer =
14382            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14383                .expect("one mesh and one row is a description the renderer can hold");
14384        assert_eq!(
14385            renderer.mesh_ids,
14386            [0],
14387            "the one description mesh takes the one table entry"
14388        );
14389        assert_eq!(
14390            renderer.bucket_constants.len(),
14391            1,
14392            "one bucket per description mesh, and there is one"
14393        );
14394        renderer
14395            .add_instance(&InstanceDesc {
14396                mesh: 0,
14397                material: 0,
14398                transform: Mat4::IDENTITY,
14399            })
14400            .expect("an empty pool has room for the only object");
14401        let recorded = frame(device.as_ref(), &mut renderer, queue);
14402        assert_eq!(
14403            commands_in_pass(&recorder, "forward")
14404                .into_iter()
14405                .filter(|command| matches!(
14406                    command,
14407                    crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
14408                ))
14409                .count(),
14410            1,
14411            "a one-mesh scene records the one bucket's indirect call"
14412        );
14413        recorded.finish(device.as_ref(), renderer);
14414    }
14415
14416    /// **A description that exactly fills what it reserved is built, not
14417    /// refused.**
14418    ///
14419    /// The other side of the capacity check, and the side nothing else in the
14420    /// tree can fail on: every other scene reserves far more than it holds, so a
14421    /// comparison written `>=` instead of `>` would pass the whole suite and
14422    /// refuse only the application that had sized its pools exactly right.
14423    ///
14424    /// The two capacities asserted here are the two a caller can size without
14425    /// re-deriving anything the renderer knows: one mesh table entry per
14426    /// [`Geometry::levels`], which is what that method is documented to answer,
14427    /// and one row per material. The four rows share one comparison, so they
14428    /// stand or fall together.
14429    #[test]
14430    fn a_description_that_exactly_fits_its_capacities_is_built() {
14431        let (recorder, device, queue) = open();
14432        let mut scene = scene::demo();
14433        scene.capacities.meshes = scene
14434            .meshes
14435            .iter()
14436            .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
14437            .sum();
14438        scene.capacities.materials =
14439            u32::try_from(scene.materials.len()).expect("a few material rows");
14440        let renderer =
14441            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14442                .expect("a description that fits exactly is not too large for itself");
14443        renderer.destroy(device.as_ref());
14444        recorder.assert_valid();
14445    }
14446
14447    /// **The level tables cover every mesh-table slot an instance can name**,
14448    /// not only the slots the description filled.
14449    ///
14450    /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
14451    /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
14452    /// "every entry an instance can name is filled". An instance's mesh id is a
14453    /// bare table index, so a table sized to the description alone makes that
14454    /// read land in whatever the packer put next for any slot the description
14455    /// left empty.
14456    ///
14457    /// Growing the capacity by a known number of slots grows the tables buffer
14458    /// by exactly what those slots occupy: one `MeshLevels` record and one
14459    /// `level_meshes` word each. The arithmetic is the assertion, so nothing
14460    /// here is a number to keep in step by hand.
14461    #[test]
14462    fn the_level_tables_cover_every_slot_the_mesh_table_has() {
14463        const EXTRA: u32 = 4;
14464
14465        let sized = |extra: u32| {
14466            let (recorder, device, queue) = open();
14467            let mut scene = scene::demo();
14468            scene.capacities.meshes += extra;
14469            let renderer =
14470                ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14471                    .expect("a description with room to spare");
14472            let size = recorder
14473                .buffer_bytes(renderer.primary.draws.tables())
14474                .expect("the table buffer is live")
14475                .len();
14476            renderer.destroy(device.as_ref());
14477            recorder.assert_valid();
14478            size
14479        };
14480
14481        let grown = sized(EXTRA) - sized(0);
14482        let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
14483        assert_eq!(
14484            grown, want,
14485            "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
14486             level words, and added {grown} bytes"
14487        );
14488    }
14489
14490    /// The property the whole arrangement exists for: the pool's second
14491    /// resident is **not** at base vertex zero, so a frame containing it is a
14492    /// frame that fails if the base is lost between the pool and the shader.
14493    ///
14494    /// Read out of the **mesh table** rather than out of a renderer field,
14495    /// because the table is where a generated draw's index range comes from:
14496    /// `draw_gen.slang` builds every argument structure out of these bytes and
14497    /// nothing on the CPU is consulted.
14498    ///
14499    /// Without this the pass is back where it started — one mesh, base 0, and a
14500    /// base-vertex bug that no picture can show.
14501    #[test]
14502    fn the_second_mesh_lands_past_the_first() {
14503        let (recorder, device, queue) = open();
14504        let renderer =
14505            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14506        let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
14507        let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
14508
14509        assert_eq!(cube.base_vertex, 0, "the cube is first");
14510        assert_eq!(
14511            pyramid.base_vertex as usize,
14512            crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
14513            "the pyramid must start where the cube ends, or the pools are not \
14514             suballocating at all"
14515        );
14516        assert_eq!(
14517            pyramid.index_count as usize,
14518            crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
14519            "and the entry carries the whole range, which is what the draw-argument \
14520             pass builds its arguments out of"
14521        );
14522        // And the two buckets read different constant blocks, or both would walk
14523        // the same run of instances.
14524        assert_ne!(
14525            renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
14526            "each bucket needs a block of its own"
14527        );
14528        renderer.destroy(device.as_ref());
14529    }
14530
14531    /// **Each bucket's block points at that bucket's own run**, and the runs do
14532    /// not overlap.
14533    ///
14534    /// This is what replaced "the block names an instance": a draw covers
14535    /// however many instances survived culling, so what it can say for itself is
14536    /// only where to find its slice of the survivors. Two buckets naming one
14537    /// start word would draw each other's objects — with the *right* geometry,
14538    /// because the index range comes from the arguments, which is exactly the
14539    /// kind of plausible wrong picture a golden image struggles with.
14540    ///
14541    /// Read out of the bytes that reached the device rather than out of the
14542    /// renderer's own fields, because the failure is a block written wrong and
14543    /// the field would still be right.
14544    #[test]
14545    fn each_bucket_walks_its_own_run_of_survivors() {
14546        let (recorder, device, queue) = open();
14547        let renderer =
14548            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14549        let blocks = recorder
14550            .buffer_bytes(renderer.draw_constants)
14551            .expect("the blocks are live");
14552        let start_word_at = |offset: u32| {
14553            let at = offset as usize;
14554            u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
14555        };
14556
14557        let draws = &renderer.primary.draws;
14558        let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
14559        let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
14560        // **Behind the survivors, their routes and the runs**, which share the
14561        // buffer: a block naming a word inside the runs would have the draw read
14562        // an instance index as its start, and one inside the survivor list or
14563        // the routes a start that is the same instances in a different order, or
14564        // a bucket number — both of which draw a plausible picture.
14565        assert_eq!(
14566            cube,
14567            draws.runs_at() + draws.visible_capacity(),
14568            "the first bucket's start word is the first word past one capacity of runs"
14569        );
14570        assert_eq!(
14571            pyramid,
14572            cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
14573            "and the second's is a word later — a start per bucket, not a run per bucket"
14574        );
14575        assert_eq!(
14576            cube,
14577            draws.bucket_start_word(DEMO_CUBE as u32),
14578            "the block carries what `DrawGen::bucket_start_word` says, because a reader \
14579             copying a run back uses that accessor and the shader uses this block"
14580        );
14581        renderer.destroy(device.as_ref());
14582    }
14583
14584    /// **An instance's record carries its material's mode**, in the bits
14585    /// `draw_gen.slang` routes by.
14586    ///
14587    /// The host half of the per-bucket split, and the half no picture and no
14588    /// pipeline bind can show: the bucket table can be perfectly twinned and
14589    /// every partition bound to the right pipeline while every instance still
14590    /// answers mode zero, in which case the masked twins are empty, the cutout
14591    /// partition draws nothing, and a cutout casts a solid shadow. The record is
14592    /// where that is decided.
14593    ///
14594    /// Both directions, so the check is shown to discriminate: the opaque
14595    /// instance's mode bits have to be **clear**, or a writer that set them
14596    /// unconditionally would satisfy a one-sided assertion. And the two records
14597    /// are asserted to differ in `flags` and nothing else, so this is about the
14598    /// mode rather than about two unrelated instances.
14599    #[test]
14600    fn an_instances_record_carries_its_materials_mode() {
14601        let masked_scene = {
14602            let mut scene = crate::scene::demo();
14603            scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
14604            scene
14605        };
14606        let (recorder, device, queue) = open();
14607        let device = device.as_ref();
14608        let mut renderer =
14609            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
14610                .expect("the null backend accepts the demo description");
14611        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14612        let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14613        let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14614
14615        let record = |handle: InstanceHandle| {
14616            renderer
14617                .instances
14618                .get(handle)
14619                .expect("the instance was inserted and is live")
14620        };
14621        let opaque = record(opaque);
14622        let masked = record(masked);
14623        assert_eq!(
14624            opaque.material_mode(),
14625            0,
14626            "an opaque material's instance carries no mode bits, or every instance in the tree \
14627             routes to a cutout bucket"
14628        );
14629        assert_eq!(
14630            masked.material_mode(),
14631            crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14632            "and a masked material's instance carries its mode, or it scatters into the opaque \
14633             twin and the depth passes write its full silhouette"
14634        );
14635        assert_eq!(
14636            mesh::GpuInstance {
14637                flags: opaque.flags,
14638                material: opaque.material,
14639                ..masked
14640            },
14641            opaque,
14642            "the two records differ in the mode bits and the material id and in nothing else"
14643        );
14644
14645        renderer.destroy(device);
14646        recorder.assert_valid();
14647    }
14648
14649    /// **A scene whose materials are all opaque gets exactly the bucket table
14650    /// it had before material modes existed** — one bucket per (mesh, level),
14651    /// and no twin.
14652    ///
14653    /// The zero-cost half of the per-bucket split, and the one a null device can
14654    /// state exactly. A bucket is not free: every pass records one indirect call
14655    /// per bucket per view, and every generator holds a run start per bucket. So
14656    /// a table that twinned unconditionally would double the recorded draws of
14657    /// every demo and every golden in this tree, none of which mask anything.
14658    ///
14659    /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14660    /// built from a mesh's own level count rather than from the table's length —
14661    /// so a build that emitted a twin per mesh has more buckets than levels and
14662    /// this says so. And the twinned scenes below are asserted to be exactly as
14663    /// many times as long as they hold modes, or the comparison would pass on a
14664    /// renderer that had stopped twinning at all.
14665    ///
14666    /// # A twin per mode the scene **holds**, not per mode that exists
14667    ///
14668    /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14669    /// records one indirect call per bucket — so the rule that matters is which
14670    /// values the description's own materials carry. Two rows of two modes are
14671    /// two twins whichever two they are, and the pair below says so both ways:
14672    /// three modes across three rows is three, and three rows collapsed onto two
14673    /// *values* is two even though between them they set both mode bits.
14674    #[test]
14675    fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14676        use crcbl_shaders::mesh::GpuMaterial;
14677
14678        let (recorder, device, queue) = open();
14679        let device = device.as_ref();
14680        let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14681        // The uniform-cut path, where a DAG is one bucket per level. The mesh
14682        // path folds a DAG into one bucket and reports no level buckets at all,
14683        // which would leave the oracle below empty.
14684        assert!(
14685            !renderer.emit.is_mesh(),
14686            "this preset built a mesh-shader path, whose level buckets are empty"
14687        );
14688        let levels: usize = (0..crate::scene::demo().meshes.len())
14689            .map(|mesh| renderer.level_buckets(mesh).len())
14690            .sum();
14691        assert!(levels > 0, "the demo has meshes, so it has levels");
14692        assert_eq!(
14693            renderer.bucket_constants.len(),
14694            levels,
14695            "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14696             twin: {levels} level(s) against {} bucket(s)",
14697            renderer.bucket_constants.len()
14698        );
14699        assert_eq!(
14700            renderer.bucket_modes,
14701            vec![0; levels],
14702            "and every one of them draws the OPAQUE mode"
14703        );
14704        let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14705        let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14706            .map(|mesh| renderer.level_buckets(mesh).to_vec())
14707            .collect();
14708        renderer.destroy(device);
14709        recorder.assert_valid();
14710
14711        // Every arrangement worth stating, as the modes its material rows carry
14712        // and the number of twins that has to produce. The demo has three rows;
14713        // a fourth is appended where four distinct modes are wanted, which
14714        // nothing instances and which therefore changes nothing but the mode
14715        // set.
14716        for (rows, modes, what) in [
14717            (
14718                vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14719                2,
14720                "one masked row beside two opaque ones",
14721            ),
14722            (
14723                vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14724                2,
14725                "one double-sided row beside two opaque ones",
14726            ),
14727            (
14728                vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14729                3,
14730                "a masked row, a double-sided one and an opaque one",
14731            ),
14732            (
14733                vec![
14734                    GpuMaterial::ALPHA_MODE_MASK,
14735                    GpuMaterial::DOUBLE_SIDED,
14736                    GpuMaterial::ALPHA_MODE_MASK,
14737                ],
14738                2,
14739                "three rows carrying two mode values between them — both mode bits are set \
14740                 somewhere and neither row is opaque, so a rule counting bits rather than \
14741                 values would say three",
14742            ),
14743            (
14744                vec![
14745                    0,
14746                    GpuMaterial::ALPHA_MODE_MASK,
14747                    GpuMaterial::DOUBLE_SIDED,
14748                    GpuMaterial::MODE_MASK,
14749                ],
14750                4,
14751                "one row of each mode, which is the only arrangement that pays for four",
14752            ),
14753        ] {
14754            let scene = {
14755                let mut scene = crate::scene::demo();
14756                while scene.materials.len() < rows.len() {
14757                    scene.materials.push(GpuMaterial::UNTINTED);
14758                }
14759                for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14760                    row.flags = *flags;
14761                }
14762                scene
14763            };
14764            let (recorder, device, queue) = open();
14765            let device = device.as_ref();
14766            let twinned =
14767                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14768                    .expect("the null backend accepts the demo description");
14769            assert_eq!(
14770                twinned.bucket_constants.len(),
14771                modes * levels,
14772                "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14773                 has {}",
14774                modes * levels,
14775                twinned.bucket_constants.len()
14776            );
14777            // The modes present, as a set — which is the claim, since the order
14778            // is `DEPTH_MODES`' and the count above already pins the length.
14779            let held: std::collections::BTreeSet<u32> =
14780                twinned.bucket_modes.iter().copied().collect();
14781            let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14782            assert_eq!(
14783                held, want,
14784                "{what}: the table twins the modes its materials carry and no others"
14785            );
14786            for mode in &held {
14787                assert_eq!(
14788                    twinned
14789                        .bucket_modes
14790                        .iter()
14791                        .filter(|held| *held == mode)
14792                        .count(),
14793                    levels,
14794                    "{what}: every mode present gets every mesh's levels once"
14795                );
14796            }
14797            // **Mode-major**: each held mode is one contiguous run of the
14798            // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14799            // partition is one range of buckets.
14800            let held_in_order: Vec<u32> = DEPTH_MODES
14801                .into_iter()
14802                .filter(|mode| held.contains(mode))
14803                .collect();
14804            assert_eq!(
14805                twinned.bucket_modes,
14806                held_in_order
14807                    .iter()
14808                    .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14809                    .collect::<Vec<_>>(),
14810                "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14811            );
14812            assert_eq!(
14813                twinned.draw_tables.bucket_meshes,
14814                opaque_meshes.repeat(held_in_order.len()),
14815                "{what}: each mode's run is the all-opaque table, mesh by mesh"
14816            );
14817            for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14818                assert_eq!(
14819                    twinned.level_buckets(mesh),
14820                    opaque.as_slice(),
14821                    "{what}: mesh {mesh}'s level buckets are the first mode's run"
14822                );
14823            }
14824            // And the `(mesh, mode) → bucket` lookup the scatter routes through
14825            // sends every key to its mode's run, at the mesh's own offset.
14826            let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14827                &twinned.draw_tables.bucket_meshes,
14828                &twinned.bucket_modes,
14829            )
14830            .expect("a small lookup");
14831            for (slot, mode) in held_in_order.iter().enumerate() {
14832                for (offset, mesh) in opaque_meshes.iter().enumerate() {
14833                    let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14834                    assert_eq!(
14835                        lookup[key as usize] as usize,
14836                        slot * levels + offset,
14837                        "{what}: mesh {mesh} in mode {mode}"
14838                    );
14839                }
14840            }
14841            twinned.destroy(device);
14842            recorder.assert_valid();
14843        }
14844    }
14845
14846    /// **The two pyramids differ in exactly one field, and it is the material
14847    /// id — which names a row holding a different colour and a different
14848    /// roughness.**
14849    ///
14850    /// The whole of what §3.2's table buys, stated as the two things that have
14851    /// to be true at once. Placed at the *same* transform, so "differ only in
14852    /// material" is literal rather than nearly: same mesh id, same matrix, same
14853    /// flags, and a `GpuInstance` comparison that would fail on any other
14854    /// field. And the ids they carry name rows the device actually holds —
14855    /// asserted on the bytes in the buffer, because a table the renderer agrees
14856    /// with itself about is not a table a shader can read.
14857    ///
14858    /// The two rows are asserted to differ, or the pair would be evidence of
14859    /// nothing: two instances naming two rows of the same colour draw the same
14860    /// picture whether or not either id was ever used.
14861    #[test]
14862    fn the_two_pyramids_differ_only_in_their_material() {
14863        let (recorder, device, queue) = open();
14864        let mut renderer =
14865            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14866        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14867        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14868        let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14869
14870        let instance = |handle: InstanceHandle| {
14871            renderer
14872                .instances
14873                .get(handle)
14874                .expect("the instance was inserted and is live")
14875        };
14876        let plain = instance(plain_handle);
14877        let tinted = instance(tinted_handle);
14878        assert_ne!(
14879            plain.material, tinted.material,
14880            "the two pyramids must not share a material row"
14881        );
14882        assert_eq!(
14883            mesh::GpuInstance {
14884                material: tinted.material,
14885                ..plain
14886            },
14887            tinted,
14888            "the two instances must differ in the material id and in nothing else"
14889        );
14890
14891        let bytes = recorder
14892            .buffer_bytes(renderer.materials.buffer())
14893            .expect("the table is live");
14894        let row = |index: u32| {
14895            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14896            mesh::GpuMaterial::from_bytes(
14897                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14898                    .try_into()
14899                    .expect("one row"),
14900            )
14901        };
14902        assert_eq!(
14903            row(plain.material),
14904            mesh::GpuMaterial::UNTINTED,
14905            "the plain pyramid's row must be the factor that changes nothing"
14906        );
14907        assert_eq!(
14908            row(tinted.material),
14909            mesh::GpuMaterial {
14910                base_color: scene::PYRAMID_TINT,
14911                roughness: scene::PYRAMID_ROUGHNESS,
14912                ..mesh::GpuMaterial::UNTINTED
14913            },
14914            "the tinted pyramid's row must be the tint and the tighter lobe"
14915        );
14916        // The shading half of that row, on its own: a roughness equal to the
14917        // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14918        // against itself, and that test would go green on a shader that had
14919        // never read the column.
14920        assert_ne!(
14921            row(plain.material).roughness,
14922            row(tinted.material).roughness,
14923            "the two rows must differ in roughness, or the highlight the render e2e measures \
14924             is not attributable to the material"
14925        );
14926        assert_ne!(
14927            row(plain.material),
14928            row(tinted.material),
14929            "two rows holding the same colour would make the pair prove nothing"
14930        );
14931        // And the tint is the *only* thing that differs between them: a row that
14932        // also changed its page layer would make this pair evidence about two
14933        // columns at once, which is what the third pyramid exists to avoid.
14934        assert_eq!(
14935            row(plain.material).base_color_texture,
14936            row(tinted.material).base_color_texture,
14937            "the factor pair must sample the same page layer"
14938        );
14939
14940        // And the second pyramid leaves the frame the way the first does: the
14941        // instance is removed, not a draw skipped.
14942        renderer.remove_instance(tinted_handle);
14943        assert!(
14944            renderer.instances.get(tinted_handle).is_none(),
14945            "the instance must be given back, or an object nobody asked for stays in the scene"
14946        );
14947
14948        renderer.destroy(device.as_ref());
14949    }
14950
14951    /// **The same claim one column along: the plain and textured pyramids
14952    /// differ in exactly one field, and the rows it names differ in exactly one
14953    /// column — the base-colour page layer.**
14954    ///
14955    /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14956    /// *texture indices* rather than its *factors*. The factors of the two rows
14957    /// are asserted **equal** here, which is the half that makes the pair
14958    /// evidence about the texture at all: a textured row that also carried a
14959    /// tint would draw a different picture for a reason the frame could not
14960    /// distinguish from the tinted pyramid's.
14961    ///
14962    /// The layer numbers are asserted against the page the renderer actually
14963    /// uploaded, so a row naming a layer that does not exist is caught here
14964    /// rather than as an out-of-range sample on a device.
14965    #[test]
14966    fn the_textured_pyramid_differs_only_in_its_page_layer() {
14967        let (recorder, device, queue) = open();
14968        let mut renderer =
14969            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14970        let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14971        let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14972        let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14973
14974        let instance = |handle: InstanceHandle| {
14975            renderer
14976                .instances
14977                .get(handle)
14978                .expect("the instance was inserted and is live")
14979        };
14980        let plain = instance(plain_handle);
14981        let textured = instance(textured_handle);
14982        assert_ne!(
14983            plain.material, textured.material,
14984            "the two pyramids must not share a material row"
14985        );
14986        assert_eq!(
14987            mesh::GpuInstance {
14988                material: textured.material,
14989                ..plain
14990            },
14991            textured,
14992            "the two instances must differ in the material id and in nothing else"
14993        );
14994
14995        let bytes = recorder
14996            .buffer_bytes(renderer.materials.buffer())
14997            .expect("the table is live");
14998        let row = |index: u32| {
14999            let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
15000            mesh::GpuMaterial::from_bytes(
15001                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
15002                    .try_into()
15003                    .expect("one row"),
15004            )
15005        };
15006        assert_eq!(
15007            row(plain.material).base_color,
15008            row(textured.material).base_color,
15009            "the texture pair must share a factor, or the pair is evidence about both columns"
15010        );
15011        assert_eq!(
15012            row(plain.material).base_color_texture,
15013            mesh::GpuMaterial::NO_PAGE
15014        );
15015        assert_eq!(
15016            row(textured.material).base_color_texture,
15017            scene::CHECKER_LAYER
15018        );
15019        assert_ne!(
15020            row(plain.material),
15021            row(textured.material),
15022            "two rows naming the same layer would make the pair prove nothing"
15023        );
15024        // The layer that number names is a layer the page has, and it is not
15025        // one flat colour — a checker of one repeated texel would pass every
15026        // assertion above and draw the picture the untextured row draws.
15027        let page = scene::demo().page;
15028        let layers = page.layers(PageKind::BaseColor);
15029        assert!(
15030            (scene::CHECKER_LAYER as usize) < layers.len(),
15031            "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
15032             nothing below the seam would report",
15033            scene::CHECKER_LAYER,
15034            layers.len()
15035        );
15036        let checker = &layers[scene::CHECKER_LAYER as usize];
15037        assert!(
15038            checker
15039                .as_chunks::<4>()
15040                .0
15041                .iter()
15042                .any(|texel| texel != &checker[..4]),
15043            "a flat checker layer would shade the textured row exactly as the untextured \
15044             one shades, and the pair would prove nothing"
15045        );
15046
15047        renderer.remove_instance(textured_handle);
15048        assert!(
15049            renderer.instances.get(textured_handle).is_none(),
15050            "the instance must be given back, or an object nobody asked for stays in the scene"
15051        );
15052
15053        renderer.destroy(device.as_ref());
15054    }
15055
15056    /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
15057    /// and a third again for its chain.
15058    ///
15059    /// This is what row (d) bought, and it is the half of it no picture can
15060    /// show: the frame a scene with no normal map draws is byte-identical either
15061    /// way, because `mesh.slang` returns before it fetches. What changes is the
15062    /// image the renderer created, and the copies into it are where that is
15063    /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
15064    /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
15065    /// is the device-side half saying the frame did not move.
15066    ///
15067    /// [`scene::demo`] is the scene: every one of its rows carries
15068    /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
15069    /// the description every golden in this tree is a variation of.
15070    ///
15071    /// # Sabotage
15072    ///
15073    /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
15074    /// and its chain instead of the placeholder — the shape this replaced. Red
15075    /// on 2026-09-06 with `"a description with no normal map must upload the
15076    /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
15077    /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
15078    /// extent² × 4 bytes and a third again for its chain, on every scene in the
15079    /// tree"`.
15080    #[test]
15081    fn a_page_kind_nothing_names_costs_one_texel() {
15082        use crcbl_hal::null::Command;
15083
15084        let scene = scene::demo();
15085        assert!(
15086            scene
15087                .materials
15088                .iter()
15089                .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
15090            "a row naming a normal layer would make the description one that *does* name \
15091             the page, and this test would be about the other case"
15092        );
15093        assert!(
15094            scene.page.layers(PageKind::Normal).is_empty()
15095                && scene.page.extent(PageKind::BaseColor) > 1,
15096            "the description must name no normal layer while naming base-colour ones, or \
15097             a placeholder-sized copy says nothing about which page it landed in"
15098        );
15099
15100        let (recorder, device, queue) = open();
15101        let renderer =
15102            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
15103                .expect("a description naming no normal page is one this can make resident");
15104
15105        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
15106            .commands()
15107            .into_iter()
15108            .filter_map(|command| match command {
15109                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
15110                    Some(copy)
15111                }
15112                _ => None,
15113            })
15114            .collect();
15115        let extents: Vec<crcbl_hal::Extent3d> =
15116            copies.iter().map(|copy| copy.image_extent).collect();
15117        assert_eq!(
15118            extents,
15119            vec![crcbl_hal::Extent3d::d2(1, 1)],
15120            "a description with no normal map must upload the one-texel placeholder, and \
15121             this copied {} level(s) at {extents:?} — a burned neutral layer costs \
15122             extent² × 4 bytes and a third again for its chain, on every scene in the tree",
15123            copies.len()
15124        );
15125
15126        // The placeholder is one layer, and the graph declaration says so: a
15127        // caller importing this page to write a layer of its own would get
15128        // `ImportDeclarationConflict` against an extent that was not 1×1.
15129        assert_eq!(
15130            renderer.normal_page_import().extent,
15131            (1, 1),
15132            "the declaration names the placeholder's extent, not the base-colour page's"
15133        );
15134        renderer.destroy(device.as_ref());
15135    }
15136
15137    /// **A page and a material table that are the caller's own, not
15138    /// [`scene::demo`]'s**: a different extent per kind, more layers than the
15139    /// demo page holds, a normal page the demo does not have at all, and rows
15140    /// past the three the demo writes.
15141    ///
15142    /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
15143    /// at most — so until this nothing had put an app-supplied *layer* or an
15144    /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
15145    /// build that uploaded the demo's two layers and stopped, or that inserted
15146    /// its three rows and stopped, would leave every golden byte-identical and
15147    /// pass every other assertion in this module: the demo scene cannot tell a
15148    /// table filled from the description from one filled up to the description's
15149    /// third row.
15150    ///
15151    /// Read off the recorder rather than off the description, because the
15152    /// description is the input. The copies are what reached the image and the
15153    /// table buffer is what the shader indexes, and neither is a restatement of
15154    /// what was handed in.
15155    #[test]
15156    fn an_app_page_and_table_reach_the_device_whole() {
15157        use crcbl_hal::null::Command;
15158
15159        /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
15160        /// rather than read off the page shows up as a copy of the wrong size.
15161        const APP_EXTENT: u32 = 4;
15162
15163        /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
15164        /// extent bought: a renderer that still sized the normal page from the
15165        /// base-colour page's number would copy this layer at 4² and the copy
15166        /// list below would say so.
15167        const APP_NORMAL_EXTENT: u32 = 2;
15168        let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
15169
15170        // Three base-colour layers, each flat and each a value of its own: a
15171        // build that uploaded one layer twice, or that stopped short, is a
15172        // different sequence of copies. Then one normal layer at the other
15173        // extent, which the demo scene has no page for at all.
15174        let mut page = scene::PageDesc::empty();
15175        page.set_extent(PageKind::BaseColor, APP_EXTENT);
15176        page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
15177        let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
15178            .into_iter()
15179            .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
15180            .collect();
15181        let app_normal = page.push_layer(
15182            PageKind::Normal,
15183            scene::PageDesc::NEUTRAL_NORMAL
15184                .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
15185        );
15186
15187        let mut scene = scene::demo();
15188        scene.page = page;
15189        // One row per appended layer, and each with a factor of its own as well,
15190        // so a row that landed at another row's id is not a row that happens to
15191        // look like it. The last of them names the normal layer too, so the
15192        // table carries a row through both pages.
15193        for (nth, &layer) in app_layers.iter().enumerate() {
15194            let shade = 0.25 * (nth as f32 + 1.0);
15195            let last = nth + 1 == app_layers.len();
15196            scene.materials.push(mesh::GpuMaterial {
15197                base_color: [shade, shade, shade, 1.0],
15198                base_color_texture: layer,
15199                normal_texture: if last {
15200                    app_normal
15201                } else {
15202                    mesh::GpuMaterial::NO_PAGE
15203                },
15204                ..mesh::GpuMaterial::UNTINTED
15205            });
15206        }
15207        assert!(
15208            scene.materials.len() > scene::demo().materials.len()
15209                && scene.page.layers(PageKind::BaseColor).len()
15210                    > scene::demo().page.layers(PageKind::BaseColor).len(),
15211            "the description under test must exceed the demo's in both, or this is a \
15212             demo test wearing another name"
15213        );
15214        assert_eq!(
15215            scene::demo().page.extent(PageKind::Normal),
15216            0,
15217            "the demo scene must name no normal page, or the normal copies below are \
15218             evidence about the demo's page rather than the caller's"
15219        );
15220
15221        let (recorder, device, queue) = open();
15222        let mut renderer =
15223            ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
15224                .expect("a page and a table of the caller's own are ones this can make resident");
15225
15226        // The page, layer by layer. Filtered by image because the build uploads
15227        // the ambient-occlusion placeholder through the same path.
15228        let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
15229            .commands()
15230            .into_iter()
15231            .filter_map(|command| match command {
15232                Command::CopyBufferToImage(copy)
15233                    if copy.image == renderer.base_color_page.image =>
15234                {
15235                    Some(copy)
15236                }
15237                _ => None,
15238            })
15239            .collect();
15240        // Every layer goes up with its chain — three levels for this extent —
15241        // so the copies are layer-major, level-minor, each at its level's own
15242        // extent.
15243        let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
15244            .full_mip_levels(crcbl_hal::ImageType::D2);
15245        assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
15246        let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
15247            .expect("a page of a few layers");
15248        assert_eq!(
15249            copies
15250                .iter()
15251                .map(|copy| (
15252                    copy.image_subresource.base_layer,
15253                    copy.image_subresource.mip
15254                ))
15255                .collect::<Vec<(u32, u32)>>(),
15256            (0..layer_count)
15257                .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
15258                .collect::<Vec<(u32, u32)>>(),
15259            "every level of every layer the description carries must be copied into the page, \
15260             in order"
15261        );
15262        assert!(
15263            copies.iter().all(|copy| {
15264                let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
15265                copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
15266            }),
15267            "the page is the extent the caller wrote, not the demo's, halved per level: \
15268             {copies:?}"
15269        );
15270
15271        // The normal page, at **its own** extent. One layer, two levels for a
15272        // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
15273        // that carried one extent for both kinds would put this layer up at 4².
15274        let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
15275            .commands()
15276            .into_iter()
15277            .filter_map(|command| match command {
15278                Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
15279                    Some(copy)
15280                }
15281                _ => None,
15282            })
15283            .collect();
15284        let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
15285            .full_mip_levels(crcbl_hal::ImageType::D2);
15286        assert_eq!(
15287            normal_copies
15288                .iter()
15289                .map(|copy| (
15290                    copy.image_subresource.base_layer,
15291                    copy.image_subresource.mip,
15292                    copy.image_extent
15293                ))
15294                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
15295            (0..normal_levels)
15296                .map(|level| {
15297                    let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
15298                    (0, level, crcbl_hal::Extent3d::d2(side, side))
15299                })
15300                .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
15301            "the normal page is the extent the caller wrote for *that* kind, halved per \
15302             level: {normal_copies:?}"
15303        );
15304        assert_eq!(
15305            renderer.normal_page_import().extent,
15306            (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
15307            "the graph declaration names the normal page's own extent, or a caller \
15308             importing it to write a layer gets ImportDeclarationConflict"
15309        );
15310        assert_eq!(
15311            renderer.base_color_page_import().extent,
15312            (APP_EXTENT, APP_EXTENT),
15313            "and the base-colour declaration names its own, which is a different number"
15314        );
15315
15316        // The table, row by row, out of the buffer `mesh.slang` indexes.
15317        let bytes = recorder
15318            .buffer_bytes(renderer.materials.buffer())
15319            .expect("the table is live");
15320        let row = |id: u32| {
15321            let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
15322            mesh::GpuMaterial::from_bytes(
15323                bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
15324                    .try_into()
15325                    .expect("one row"),
15326            )
15327        };
15328        assert_eq!(
15329            renderer.material_ids.len(),
15330            scene.materials.len(),
15331            "one id per description row, whatever the count"
15332        );
15333        for (index, wrote) in scene.materials.iter().enumerate() {
15334            assert_eq!(
15335                &row(renderer.material_ids[index]),
15336                wrote,
15337                "description row {index} must be the row its id names"
15338            );
15339        }
15340
15341        // And a caller can place an object through a row only its own
15342        // description has, which is the whole point of the rows being the
15343        // caller's.
15344        let last = scene.materials.len() - 1;
15345        let handle = renderer
15346            .add_instance(&InstanceDesc {
15347                mesh: DEMO_CUBE,
15348                material: last,
15349                transform: Mat4::IDENTITY,
15350            })
15351            .expect("an empty pool of thousands has room for one object");
15352        assert_eq!(
15353            renderer
15354                .instances
15355                .get(handle)
15356                .expect("a just-added instance is live")
15357                .material,
15358            renderer.material_ids[last],
15359            "an InstanceDesc's material index resolves through the description, not \
15360             through a table id the caller cannot know"
15361        );
15362
15363        renderer.destroy(device.as_ref());
15364        recorder.assert_valid();
15365    }
15366
15367    /// **The frame records two compute dispatches and exactly one indirect draw
15368    /// per bucket — whatever is in the scene.**
15369    ///
15370    /// The property topic 03 opens with, checked on the recorded command stream:
15371    /// adding the pyramid adds an instance and changes no command. A pass that
15372    /// had kept a draw per object would record one command here and two there,
15373    /// which is what this used to assert and what the indirect path replaced.
15374    ///
15375    /// It also pins the arguments each call names: bucket `n` reads the `n`-th
15376    /// argument structure and the `n`-th count, at the stride every API fixed.
15377    /// Two calls pointing at one structure is a frame that draws one object
15378    /// twice.
15379    #[test]
15380    fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
15381        use crcbl_hal::null::Command;
15382
15383        for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
15384            let (recorder, device, queue) = open();
15385            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15386                .expect("built");
15387            // The cube in both scenes, so the difference between them is the
15388            // pyramid alone. It also keeps both frames non-empty, and an empty
15389            // one would be a weaker comparison than this claims: `cull`'s
15390            // dispatch covers no workgroups when the pool is empty, and the pass
15391            // records nothing rather than a dispatch of zero — see
15392            // [`DrawGen::add_passes`].
15393            place_cube(&mut renderer, Mat4::IDENTITY);
15394            if let Some(at) = pyramid {
15395                place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
15396            }
15397            let frame = frame(device.as_ref(), &mut renderer, queue);
15398
15399            let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
15400            let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
15401                .map(|bucket| {
15402                    (
15403                        renderer.bucket_constants[bucket],
15404                        bucket as u64 * u64::from(stride),
15405                        bucket as u64 * 4,
15406                    )
15407                })
15408                .collect();
15409
15410            // The dynamic offset last bound before each draw, paired with the
15411            // offsets that draw read its arguments and its count from.
15412            let mut offset = None;
15413            let mut seen: Vec<(u32, u64, u64)> = Vec::new();
15414            let mut dispatches = 0;
15415            for command in recorder.commands() {
15416                if matches!(command, Command::Dispatch { .. }) {
15417                    dispatches += 1;
15418                }
15419            }
15420            for command in commands_in_pass(&recorder, "forward") {
15421                match command {
15422                    Command::BindGroup {
15423                        slot: 0,
15424                        dynamic_offsets,
15425                        ..
15426                    } => offset = dynamic_offsets.first().copied(),
15427                    Command::DrawIndexedIndirectCount(draw) => {
15428                        assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
15429                        assert_eq!(
15430                            draw.max_draw_count, 1,
15431                            "one argument structure per bucket, so one is the ceiling"
15432                        );
15433                        seen.push((
15434                            offset.expect("a draw is preceded by its constant block"),
15435                            draw.args_offset,
15436                            draw.count_offset,
15437                        ));
15438                    }
15439                    Command::DrawIndexed { .. } => {
15440                        panic!("the forward pass must not record a CPU-counted draw any more")
15441                    }
15442                    _ => {}
15443                }
15444            }
15445            assert_eq!(
15446                dispatches,
15447                DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
15448                "the clearing pass, the cull pass and the draw-argument pass's three, in \
15449                 front of the draws — once for the camera and once per shadow cascade — plus \
15450                 topic 18's one clustering dispatch, which is the camera's alone because a \
15451                 cascade shades nothing, plus the resolve's own"
15452            );
15453            assert_eq!(
15454                seen, expected,
15455                "with pyramid = {pyramid:?}, the pass must record one indirect call per \
15456                 bucket, each pointing at its own arguments, its own count and its own \
15457                 block"
15458            );
15459
15460            frame.finish(device.as_ref(), renderer);
15461        }
15462    }
15463
15464    /// **The two `GeometryPath` arms record different calls and nothing else
15465    /// differs.**
15466    ///
15467    /// A device with a GPU-side count takes it from GPU memory; one without —
15468    /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
15469    /// bucket's one argument structure unconditionally. Same buckets, same
15470    /// arguments, same block: the tail is the only thing that moves, which is
15471    /// what topic 03 means by "the lesser path is
15472    /// a constraint on data layout, not a separate renderer".
15473    ///
15474    /// Both presets are run here rather than only the one this machine has,
15475    /// because the arm a device never selects is the arm nothing tests.
15476    #[test]
15477    fn each_geometry_path_records_its_own_indirect_call() {
15478        use crcbl_hal::null::Command;
15479
15480        for (preset, path, counted) in [
15481            (
15482                NullInstance::gpu_driven(),
15483                GeometryPath::IndirectCount,
15484                true,
15485            ),
15486            (
15487                NullInstance::portable(),
15488                GeometryPath::IndirectPerBatch,
15489                false,
15490            ),
15491        ] {
15492            let recorder = Recorder::new();
15493            let instance = preset.with_recorder(recorder.clone());
15494            let adapter = instance.adapters().remove(0);
15495            assert_eq!(
15496                instance
15497                    .adapter_caps(adapter.id)
15498                    .expect("the null backend describes its adapter")
15499                    .geometry_path(),
15500                path,
15501                "the preset must select the path this arm is about"
15502            );
15503            // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
15504            // portable preset does not have; the forward pass does not need one
15505            // either, so this asks for what it uses. The optional set matters:
15506            // a device is opened with the features it *asked* for, and the path
15507            // is derived from those rather than from the adapter's.
15508            let device = instance
15509                .create_device(&DeviceDesc {
15510                    label: None,
15511                    adapter: adapter.id,
15512                    required_features: Features::COMPUTE,
15513                    optional_features: Features::GPU_DRIVEN,
15514                    compatible_surface: None,
15515                })
15516                .expect("the null backend always opens");
15517            assert_eq!(
15518                device.caps().geometry_path(),
15519                path,
15520                "and the opened device still selects it"
15521            );
15522            let queue = device.queue(QueueKind::Graphics).expect("always present");
15523            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15524                .expect("built");
15525            let frame = frame(device.as_ref(), &mut renderer, queue);
15526
15527            let mut counted_calls = 0;
15528            let mut per_batch_calls = 0;
15529            for command in commands_in_pass(&recorder, "forward") {
15530                match command {
15531                    Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
15532                    Command::DrawIndexedIndirect(draw) => {
15533                        assert_eq!(
15534                            draw.draw_count, 1,
15535                            "one argument structure per bucket, read unconditionally"
15536                        );
15537                        per_batch_calls += 1;
15538                    }
15539                    _ => {}
15540                }
15541            }
15542            let buckets = renderer.bucket_constants.len();
15543            let (expected_counted, expected_per_batch) =
15544                if counted { (buckets, 0) } else { (0, buckets) };
15545            assert_eq!(
15546                (counted_calls, per_batch_calls),
15547                (expected_counted, expected_per_batch),
15548                "{path:?} must record one call of its own kind per bucket and none of the other"
15549            );
15550
15551            frame.finish(device.as_ref(), renderer);
15552        }
15553    }
15554
15555    /// Serialises the two checks that move
15556    /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
15557    /// afterwards.
15558    ///
15559    /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
15560    /// `cargo test` runs a crate's tests as threads of *one* process: two checks
15561    /// that move the switch are then two writers to one cell, which shows up as
15562    /// a flake rather than as a failure anybody can read.
15563    /// `crcbl::debug_view::for_test` is the same shape one crate up and there
15564    /// for the same reason; this one is smaller because nothing outside these
15565    /// two tests ever writes the cell.
15566    fn debug_draw_switch() -> DebugDrawSwitch {
15567        let guard = DEBUG_DRAW_SWITCH
15568            .lock()
15569            .unwrap_or_else(std::sync::PoisonError::into_inner);
15570        let switch = DebugDrawSwitch { _guard: guard };
15571        switch.set(false);
15572        switch
15573    }
15574
15575    /// What [`debug_draw_switch`] hands back: the switch is this thread's until
15576    /// it drops, and it goes back off when it does.
15577    struct DebugDrawSwitch {
15578        _guard: std::sync::MutexGuard<'static, ()>,
15579    }
15580
15581    impl DebugDrawSwitch {
15582        /// Moves the switch.
15583        fn set(&self, on: bool) {
15584            crate::debug_draw::r_debug_draw
15585                .set(&crcbl_console::Value::Bool(on))
15586                .expect("`r_debug_draw` is a writable bool");
15587        }
15588    }
15589
15590    impl Drop for DebugDrawSwitch {
15591        fn drop(&mut self) {
15592            // Off at both ends, so a check that panicked mid-way does not hand
15593            // the next holder a switched-on layer.
15594            self.set(false);
15595        }
15596    }
15597
15598    /// [`debug_draw_switch`]'s lock.
15599    ///
15600    /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
15601    /// both — see that function for what the opposite order cost.
15602    static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15603
15604    /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
15605    /// default when the guard drops.
15606    ///
15607    /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
15608    /// `cargo test` run shares one process between tests, and a variable this
15609    /// one left moved is a frame the next test did not ask for.
15610    ///
15611    /// **Every test whose assertion depends on the shape of a frame takes this,
15612    /// not only the one that moves the count.** The variable is a process
15613    /// global and `cargo test` runs this module's tests on threads that share
15614    /// it, so a frame built while
15615    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
15616    /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
15617    /// that the test building it never asked for. Taking the guard both
15618    /// serialises against that test and pins the count for the frames this one
15619    /// builds.
15620    ///
15621    /// Two shapes need it, and the second is easy to miss. A test comparing a
15622    /// frame against a **literal pass list** breaks whenever the count is two.
15623    /// A test comparing **two frames it built itself** — a difference in draws,
15624    /// an equality between pass lists, a "one pass longer" claim — breaks only
15625    /// when the count *moves between them*, which is a narrower window and why
15626    /// this reproduced at roughly one run in eight rather than every run.
15627    ///
15628    /// Both were established by experiment on 2026-09-01 rather than by
15629    /// reading: pinning the count at two reddens the first shape, and making
15630    /// `crate::ssao::blur_passes` alternate reddens the second.
15631    ///
15632    /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15633    /// These are two plain mutexes with no ordering between them, so two tests
15634    /// acquiring both in opposite orders deadlock — which is not a hazard this
15635    /// comment is guessing at: adding the guard to the two debug-draw tests
15636    /// above their existing one did exactly that on 2026-09-01, and turned a
15637    /// 0.2 second suite into one that had not finished in ten minutes. It is
15638    /// invisible in a single-threaded run, where the same suite passes in a
15639    /// second, so `--test-threads=1` is not a check for it.
15640    ///
15641    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15642    pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15643        let guard = SSAO_BLUR_SWITCH
15644            .lock()
15645            .unwrap_or_else(std::sync::PoisonError::into_inner);
15646        let switch = SsaoBlurSwitch { _guard: guard };
15647        switch.set(1);
15648        switch
15649    }
15650
15651    /// What [`ssao_blur_switch`] hands back.
15652    pub(super) struct SsaoBlurSwitch {
15653        _guard: std::sync::MutexGuard<'static, ()>,
15654    }
15655
15656    impl SsaoBlurSwitch {
15657        /// Asks for `passes` of them.
15658        fn set(&self, passes: i64) {
15659            crate::ssao::r_ssao_blur_passes
15660                .set(&crcbl_console::Value::Int(passes))
15661                .expect("`r_ssao_blur_passes` is a writable int in range");
15662        }
15663    }
15664
15665    impl Drop for SsaoBlurSwitch {
15666        fn drop(&mut self) {
15667            // Back to the shipping count at both ends, so a check that panicked
15668            // mid-way does not hand the next holder a three-pass frame.
15669            self.set(1);
15670        }
15671    }
15672
15673    /// [`ssao_blur_switch`]'s lock.
15674    static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15675
15676    /// Takes `r_ssao_split` for this thread and puts it back when the guard
15677    /// drops.
15678    ///
15679    /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15680    /// makes the occlusion chain record its second march, so a test about the
15681    /// widest frame a renderer can produce has to hold this as well as the blur
15682    /// count — see `crate::ssao`'s `r_ssao_split`.
15683    ///
15684    /// **Every test comparing [`ForwardRenderer::counters`]' draws with
15685    /// [`recorded_draws`] takes this too**, because that march is a draw the
15686    /// counters leave out (`Ssao::passes` says why): a frame built while
15687    /// another test holds a seam records one draw more than it counts. Found
15688    /// on 2026-11-01 by the mesh-tail test reading 13 against 14 under a
15689    /// threaded `cargo test`, and confirmed by a seam on by default reddening
15690    /// every such test that did not hold this.
15691    pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15692        let guard = SSAO_SPLIT_SWITCH
15693            .lock()
15694            .unwrap_or_else(std::sync::PoisonError::into_inner);
15695        let switch = SsaoSplitSwitch { _guard: guard };
15696        switch.set(0.0);
15697        switch
15698    }
15699
15700    /// What [`ssao_split_switch`] hands back.
15701    pub(super) struct SsaoSplitSwitch {
15702        _guard: std::sync::MutexGuard<'static, ()>,
15703    }
15704
15705    impl SsaoSplitSwitch {
15706        /// Asks for a seam at `at`, or for none at zero.
15707        fn set(&self, at: f32) {
15708            crate::ssao::r_ssao_split
15709                .set(&crcbl_console::Value::Float(at))
15710                .expect("`r_ssao_split` is a writable float in range");
15711        }
15712    }
15713
15714    impl Drop for SsaoSplitSwitch {
15715        fn drop(&mut self) {
15716            // Back to the default at both ends, so a check that panicked
15717            // mid-way does not hand the next holder a comparing frame.
15718            self.set(0.0);
15719        }
15720    }
15721
15722    /// [`ssao_split_switch`]'s lock.
15723    ///
15724    /// **Third in the lock order**: after [`DEBUG_DRAW_SWITCH`] and
15725    /// [`SSAO_BLUR_SWITCH`], and before [`SSAO_SLICE_SWITCH`],
15726    /// `crate::ssao::TECHNIQUE_SWITCH` and `crate::shadow::FILTER_SWITCH`.
15727    static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15728
15729    /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15730    /// them both back at their defaults when the guard drops.
15731    ///
15732    /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15733    /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15734    /// is where that is argued, and why the lock lives there rather than beside
15735    /// this function: `crate::shadow`'s own tests move the same two.
15736    fn shadow_filter_switch() -> ShadowFilterSwitch {
15737        let guard = crate::shadow::FILTER_SWITCH
15738            .lock()
15739            .unwrap_or_else(std::sync::PoisonError::into_inner);
15740        let switch = ShadowFilterSwitch { _guard: guard };
15741        switch.reset();
15742        switch
15743    }
15744
15745    /// What [`shadow_filter_switch`] hands back.
15746    struct ShadowFilterSwitch {
15747        _guard: std::sync::MutexGuard<'static, ()>,
15748    }
15749
15750    impl ShadowFilterSwitch {
15751        /// Asks for `filter` on the near side of the seam.
15752        fn filter(&self, filter: shadow::Filter) {
15753            crate::shadow::r_shadow_filter
15754                .set(&crcbl_console::Value::Enum(filter.label()))
15755                .expect("`r_shadow_filter` is a writable enum in the set");
15756        }
15757
15758        /// Asks for a seam at `at`, or for none at zero.
15759        fn seam(&self, at: f32) {
15760            crate::shadow::r_shadow_split
15761                .set(&crcbl_console::Value::Float(at))
15762                .expect("`r_shadow_split` is a writable float in range");
15763        }
15764
15765        /// Asks for `texels` of constant bias.
15766        fn bias(&self, texels: f32) {
15767            crate::shadow::r_shadow_bias
15768                .set(&crcbl_console::Value::Float(texels))
15769                .expect("`r_shadow_bias` is a writable float in range");
15770        }
15771
15772        /// Asks for `texels` of normal offset.
15773        fn offset(&self, texels: f32) {
15774            crate::shadow::r_shadow_normal_offset
15775                .set(&crcbl_console::Value::Float(texels))
15776                .expect("`r_shadow_normal_offset` is a writable float in range");
15777        }
15778
15779        /// Back to the frame every golden was blessed as.
15780        fn reset(&self) {
15781            self.filter(shadow::shipped_filter());
15782            self.seam(0.0);
15783            self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15784            self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15785        }
15786    }
15787
15788    /// The float `var` declares as its default — what a frame nobody typed at
15789    /// is drawn with, read off the variable rather than written down here.
15790    fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15791        match var.default() {
15792            crcbl_console::Value::Float(shipped) => *shipped,
15793            other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15794        }
15795    }
15796
15797    impl Drop for ShadowFilterSwitch {
15798        fn drop(&mut self) {
15799            // Back to the defaults at both ends, so a check that panicked
15800            // mid-way does not hand the next holder a comparing frame.
15801            self.reset();
15802        }
15803    }
15804
15805    /// Takes `r_ssao_slices` for this thread and puts it back at its default
15806    /// when the guard drops.
15807    ///
15808    /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15809    /// `cargo test` run shares one process between tests, and a variable this
15810    /// one left moved is a frame the next test did not ask for.
15811    fn ssao_slice_switch() -> SsaoSliceSwitch {
15812        let guard = SSAO_SLICE_SWITCH
15813            .lock()
15814            .unwrap_or_else(std::sync::PoisonError::into_inner);
15815        let switch = SsaoSliceSwitch { _guard: guard };
15816        switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15817        switch
15818    }
15819
15820    /// What [`ssao_slice_switch`] hands back.
15821    struct SsaoSliceSwitch {
15822        _guard: std::sync::MutexGuard<'static, ()>,
15823    }
15824
15825    impl SsaoSliceSwitch {
15826        /// Asks each pixel for `slices` of them.
15827        fn set(&self, slices: i64) {
15828            crate::ssao::r_ssao_slices
15829                .set(&crcbl_console::Value::Int(slices))
15830                .expect("`r_ssao_slices` is a writable int in range");
15831        }
15832    }
15833
15834    impl Drop for SsaoSliceSwitch {
15835        fn drop(&mut self) {
15836            // Back to the shipping count at both ends, so a check that panicked
15837            // mid-way does not hand the next holder a four-slice frame — which
15838            // is a frame every golden in this workspace was blessed without.
15839            self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15840        }
15841    }
15842
15843    /// [`ssao_slice_switch`]'s lock.
15844    static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15845
15846    /// Takes `r_ssao_technique` for this thread and puts it back at its default
15847    /// when the guard drops.
15848    ///
15849    /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15850    /// a **pipeline** rather than a lane of a uniform block, so a frame that
15851    /// picked it up from another thread's test gathers through a shader that
15852    /// test never selected.
15853    ///
15854    /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15855    /// it is the one switch here whose does: `ssao`'s own
15856    /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15857    /// variable, and a second mutex would serialise neither against the other.
15858    /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15859    fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15860        let guard = crate::ssao::TECHNIQUE_SWITCH
15861            .lock()
15862            .unwrap_or_else(std::sync::PoisonError::into_inner);
15863        let switch = SsaoTechniqueSwitch { _guard: guard };
15864        switch.set(shipped_technique_name());
15865        switch
15866    }
15867
15868    /// The technique name the chain ships, and the one
15869    /// [`ssao_technique_switch`] restores.
15870    ///
15871    /// **Read off the variable rather than written down**, which is
15872    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15873    /// rule about the slice count and for its reason: which value ships is a
15874    /// thing that moves, and a test naming the wrong one would be comparing the
15875    /// shipped configuration against itself.
15876    ///
15877    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15878    fn shipped_technique_name() -> &'static str {
15879        match crate::ssao::r_ssao_technique.default() {
15880            crcbl_console::Value::Enum(name) => name,
15881            other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15882        }
15883    }
15884
15885    /// A name from the variable's own set that is **not** the one it ships.
15886    ///
15887    /// [`shipped_technique_name`]'s clause from the other side: the tests below
15888    /// need a technique to move the console to, and picking it out of the
15889    /// declared set is what keeps them from naming one the variable does not
15890    /// offer — or, if a third arrived, from silently going on comparing the
15891    /// same two.
15892    fn other_technique_name() -> &'static str {
15893        let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15894            panic!("`r_ssao_technique` is an enum variable");
15895        };
15896        let ships = shipped_technique_name();
15897        names
15898            .iter()
15899            .copied()
15900            .find(|name| *name != ships)
15901            .expect("`r_ssao_technique` offers a technique other than the one it ships")
15902    }
15903
15904    /// What [`ssao_technique_switch`] hands back.
15905    struct SsaoTechniqueSwitch {
15906        _guard: std::sync::MutexGuard<'static, ()>,
15907    }
15908
15909    impl SsaoTechniqueSwitch {
15910        /// Asks for the gather `name` selects.
15911        fn set(&self, name: &'static str) {
15912            crate::ssao::r_ssao_technique
15913                .set(&crcbl_console::Value::Enum(name))
15914                .expect("`r_ssao_technique` is a writable enum in the set");
15915        }
15916    }
15917
15918    impl Drop for SsaoTechniqueSwitch {
15919        fn drop(&mut self) {
15920            // Back to what ships at both ends, so a check that panicked mid-way
15921            // does not hand the next holder a frame gathered through the cheap
15922            // tier — which is a frame no golden in this workspace was blessed
15923            // on.
15924            self.set(shipped_technique_name());
15925        }
15926    }
15927
15928    /// Every draw the recorded stream holds, whichever call recorded it.
15929    ///
15930    /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15931    /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15932    /// the thing to compare it against is the whole frame.
15933    fn recorded_draws(recorder: &Recorder) -> usize {
15934        use crcbl_hal::null::Command;
15935
15936        recorder
15937            .commands()
15938            .into_iter()
15939            .filter(|command| {
15940                matches!(
15941                    command,
15942                    Command::Draw { .. }
15943                        | Command::DrawIndexed { .. }
15944                        | Command::DrawIndirect(_)
15945                        | Command::DrawIndexedIndirect(_)
15946                        | Command::DrawIndirectCount(_)
15947                        | Command::DrawIndexedIndirectCount(_)
15948                        | Command::DrawMeshTasks { .. }
15949                        | Command::DrawMeshTasksIndirect(_)
15950                )
15951            })
15952            .count()
15953    }
15954
15955    /// **The draw count is what the frame recorded, and the two GPU-side
15956    /// counters are `None` rather than a guess.**
15957    ///
15958    /// Both halves matter and both are checked here against something that
15959    /// moves. The draws are compared with the recorded stream, so a count that
15960    /// forgot the shadow pass's share or the tonemap's triangle fails. The
15961    /// instances are read before and after a pyramid is put in the pool, so a
15962    /// counter wired to a constant — or to the pool's *capacity*, which does not
15963    /// move — fails too.
15964    ///
15965    /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15966    /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15967    /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15968    /// number invented before any readback landed. That is the assertion that
15969    /// catches the tempting version of this method: an instance count taken from
15970    /// the pool and reported as "drawn" would read as a culling win of exactly
15971    /// zero on every frame, which is the number the whole cull exists to change.
15972    /// What happens once the ring *has* come round is the test below.
15973    #[test]
15974    fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15975        let _blurs = ssao_blur_switch();
15976        let _seam = ssao_split_switch();
15977        let (recorder, device, queue) = open();
15978        let mut renderer =
15979            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15980
15981        // Before any frame: nothing recorded, and said as a known zero.
15982        assert_eq!(renderer.counters(), FrameCounters::default());
15983
15984        let first = frame(device.as_ref(), &mut renderer, queue);
15985        let counters = renderer.counters();
15986        assert_eq!(
15987            counters.draws,
15988            recorded_draws(&recorder) as u64,
15989            "the counter and the frame's recorded draws disagree",
15990        );
15991        // Derived from what the frame resolved rather than from a constant, so
15992        // this is still the every-effect frame's count and would follow a frame
15993        // that switched one off.
15994        let fullscreen = fullscreen_passes(
15995            renderer.effects(),
15996            TEST_EXTENT,
15997            false,
15998            renderer.frame_ssao_blurs,
15999        ) * FULLSCREEN_DRAWS;
16000        assert!(
16001            counters.draws > fullscreen,
16002            "a frame that recorded only its full-screen passes drew no scene",
16003        );
16004        assert_eq!(
16005            counters.instances,
16006            renderer.instances.len() as u64 + fullscreen,
16007        );
16008        assert_eq!(
16009            counters.drawn, None,
16010            "the ring has not come round, so there is no survivor count yet",
16011        );
16012        assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
16013        assert_eq!(counters.triangles, None);
16014        first.release(device.as_ref());
16015
16016        // A second scene: one more instance in the pool, and the counter moves
16017        // with it. The draws do not — one call per bucket whatever the scene
16018        // holds is what §3.3 is about, and this is where that shows.
16019        place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
16020        recorder.clear();
16021        let second = frame(device.as_ref(), &mut renderer, queue);
16022        let richer = renderer.counters();
16023        assert_eq!(
16024            richer.instances,
16025            counters.instances + 1,
16026            "an instance added to the pool must move the counter",
16027        );
16028        assert_eq!(
16029            richer.draws, counters.draws,
16030            "the recorded call count is independent of what the scene holds",
16031        );
16032        assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
16033
16034        second.finish(device.as_ref(), renderer);
16035    }
16036
16037    /// **Once the ring has come round, `drawn` is a number and it says which
16038    /// frame it is from.**
16039    ///
16040    /// The other half of the test above: `indirect` while the readback is in
16041    /// flight, a count afterwards, and a `cull_frame` naming a frame several
16042    /// behind the one just recorded. The null backend executes no copy, so the
16043    /// *value* here is the full-screen passes' own draws and nothing else — what the cull
16044    /// really kept is asserted against a real GPU, in the umbrella crate's
16045    /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
16046    ///
16047    /// The frame number is the assertion with teeth here: a ring that read the
16048    /// slot it had just written would report the frame it is on, and a
16049    /// `cull_frame` left at `None` would put a latent number on the panel with
16050    /// nothing to say how old it is.
16051    #[test]
16052    fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
16053        let (_recorder, device, queue) = open();
16054        let mut renderer =
16055            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16056
16057        let mut frames = Vec::new();
16058        for _ in 0..CULL_STATS_FLOOR {
16059            frames.push(frame(device.as_ref(), &mut renderer, queue));
16060            assert_eq!(
16061                renderer.counters().drawn,
16062                None,
16063                "no readback has even been polled yet, so there is nothing back",
16064            );
16065        }
16066
16067        frames.push(frame(device.as_ref(), &mut renderer, queue));
16068        let counters = renderer.counters();
16069        assert_eq!(
16070            counters.drawn,
16071            Some(
16072                fullscreen_passes(
16073                    renderer.effects(),
16074                    TEST_EXTENT,
16075                    false,
16076                    renderer.frame_ssao_blurs,
16077                ) * FULLSCREEN_DRAWS,
16078            ),
16079            "the survivor count the null backend produced is zero, plus one instance per \
16080             full-screen pass — which is on both sides of the row",
16081        );
16082        assert_eq!(
16083            counters.cull_frame,
16084            Some(1),
16085            "the report is the frame whose copy answered, not the frame just recorded",
16086        );
16087        assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
16088
16089        for frame in frames {
16090            frame.release(device.as_ref());
16091        }
16092        renderer.destroy(device.as_ref());
16093    }
16094
16095    /// The frames a culling counter cannot possibly have arrived in.
16096    ///
16097    /// Two: the copy is recorded on one frame and the readback for it requested
16098    /// on the next, so the earliest frame that can poll anything is the third.
16099    /// A device that answers its first poll — the null backend, and every native
16100    /// one — reports there; a browser answers later, which is why this is a
16101    /// floor rather than a latency. See [`crate::cull_stats`].
16102    const CULL_STATS_FLOOR: usize = 2;
16103
16104    /// **A light that takes a shadow tile moves the draw count**, because the
16105    /// shadow pass records one call per bucket per occupied view.
16106    ///
16107    /// The observable a `recorded_draws` comparison alone would miss: a
16108    /// `counters` that counted only the colour pass and the tonemap agrees with
16109    /// nothing here, and one that hard-coded the cascades agrees with the first
16110    /// frame and not the second.
16111    #[test]
16112    fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
16113        let _seam = ssao_split_switch();
16114        let (recorder, device, queue) = open();
16115        let mut renderer =
16116            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16117
16118        let dark = frame(device.as_ref(), &mut renderer, queue);
16119        let without = renderer.counters().draws;
16120        assert_eq!(without, recorded_draws(&recorder) as u64);
16121        dark.release(device.as_ref());
16122
16123        renderer.set_lights(&[shadowable_spot(0.0)]);
16124        recorder.clear();
16125        let lit = frame(device.as_ref(), &mut renderer, queue);
16126        let with = renderer.counters().draws;
16127        assert!(
16128            with > without,
16129            "a shadow-casting light adds a view and therefore draws: {with} against {without}",
16130        );
16131        assert_eq!(
16132            with,
16133            recorded_draws(&recorder) as u64,
16134            "and the counter still matches the stream",
16135        );
16136        lit.finish(device.as_ref(), renderer);
16137    }
16138
16139    /// Opens a null device offering `optional` on top of the mesh path, and
16140    /// asserts it really selected that path.
16141    ///
16142    /// Asked for rather than merely reported, because a device grants what it
16143    /// enabled: leaving mesh shaders out of the optional set opens a device on
16144    /// an indirect tail and tests nothing.
16145    ///
16146    /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
16147    /// only where `optional` asks for it — so a test that does not gets the
16148    /// mesh tail's call per bucket.
16149    fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
16150        let caps = crcbl_hal::DeviceCaps {
16151            features: Features::GPU_DRIVEN
16152                | Features::MESH_SHADER
16153                | Features::TASK_SHADER
16154                | Features::DRAW_INDEX,
16155            limits: crcbl_hal::Limits::desktop(),
16156        };
16157        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
16158        let adapter = instance.adapters().remove(0);
16159        assert_eq!(
16160            instance
16161                .adapter_caps(adapter.id)
16162                .expect("the null backend describes its adapter")
16163                .geometry_path(),
16164            GeometryPath::MeshShader,
16165            "a device with mesh shaders selects them, which is the case this is about"
16166        );
16167        let device = instance
16168            .create_device(&DeviceDesc {
16169                label: None,
16170                adapter: adapter.id,
16171                required_features: Features::COMPUTE,
16172                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
16173                compatible_surface: None,
16174            })
16175            .expect("the null backend always opens");
16176        assert_eq!(
16177            device.caps().geometry_path(),
16178            GeometryPath::MeshShader,
16179            "and the opened device still selects it"
16180        );
16181        let queue = device.queue(QueueKind::Graphics).expect("always present");
16182        (device, queue)
16183    }
16184
16185    /// **The four material pages are created with the format their contents
16186    /// call for, and it is only a *colour* that is sRGB.**
16187    ///
16188    /// Topic 44's rung 2 calls this the classic PBR bug and
16189    /// says why it survives review: a base-colour texel and an emissive one are
16190    /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
16191    /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
16192    /// decoding either of those through the sRGB curve is wrong by a gamma and
16193    /// looks merely like a surface bumpier or shinier than the author drew.
16194    /// Nothing in a frame reports it, no golden comparison can name it, and the
16195    /// four constants sit a few lines apart with the wrong one compiling.
16196    ///
16197    /// So this is the whole guard, and it is three claims rather than one: that
16198    /// each constant is the one it should be, that
16199    /// [`PageKind::format`] — which is what the upload loop actually calls —
16200    /// answers with it, and, the half that would otherwise be a check that
16201    /// cannot fail, that the format each page is *created* with is the format
16202    /// its `ImportedImage` declares. A declaration naming a format the image is
16203    /// not in picks the wrong aspects in a barrier.
16204    #[test]
16205    fn the_page_formats_split_colour_from_number() {
16206        assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
16207        assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
16208        assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
16209        assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
16210        // Through the dispatch the upload loop actually calls, rather than the
16211        // constants alone: one loop creates every image now, and a `format` arm
16212        // pointed at the wrong constant is the way that loop gets it wrong.
16213        assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
16214        assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
16215        assert_eq!(
16216            PageKind::MetallicRoughnessOcclusion.format(),
16217            MRO_PAGE_FORMAT
16218        );
16219        assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
16220        assert_ne!(
16221            BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
16222            "a normal page created sRGB decodes every texel through a gamma it never had"
16223        );
16224        assert_ne!(
16225            EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
16226            "a packed roughness page created sRGB shades every surface smoother than authored"
16227        );
16228
16229        let (recorder, device, queue) = open();
16230        let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16231            .expect("the forward renderer builds on the null backend");
16232        assert_eq!(
16233            renderer.base_color_page_import().format,
16234            BASE_COLOR_PAGE_FORMAT
16235        );
16236        assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
16237        assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
16238        assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
16239        // And they really are four images, not one bound four times — which is
16240        // the other way a page could be "linear" and still be sampled through
16241        // the sRGB one.
16242        let created = [
16243            renderer.base_color_page(),
16244            renderer.normal_page(),
16245            renderer.mro_page(),
16246            renderer.emissive_page(),
16247        ];
16248        for (at, page) in created.iter().enumerate() {
16249            for other in &created[at + 1..] {
16250                assert_ne!(page.image, other.image, "two page kinds share one image");
16251                assert_ne!(page.view, other.view, "two page kinds share one view");
16252            }
16253        }
16254        // The labels come off the recorder rather than off the handles, so this
16255        // is evidence about what the device was asked to create.
16256        let images: Vec<String> = recorder
16257            .events()
16258            .into_iter()
16259            .filter_map(|event| match event {
16260                Event::Created {
16261                    kind: ObjectKind::Image,
16262                    label: Some(label),
16263                } => Some(label),
16264                _ => None,
16265            })
16266            .collect();
16267        for kind in PageKind::ALL {
16268            let page = kind.upload_label();
16269            assert!(
16270                images.iter().any(|label| label == page),
16271                "no image was created for the {page} page, and it is {images:?} that were"
16272            );
16273        }
16274        renderer.destroy(device.as_ref());
16275    }
16276
16277    /// Compare native argument indices from the shipped entry points with the
16278    /// actual renderer layout. A shared fragment buffer must have the same index
16279    /// even when geometry introduces additional resources in another module.
16280    #[test]
16281    fn mesh_pipeline_buffers_match_native_shader_arguments() {
16282        for optional in [Features::TASK_SHADER, Features::empty()] {
16283            let recorder = Recorder::new();
16284            let (device, queue) = open_mesh_path(&recorder, optional);
16285            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16286                .expect("the mesh renderer builds");
16287            let (_, entries) = recorder
16288                .bind_group_layouts_created()
16289                .into_iter()
16290                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
16291                .expect("the actual mesh layout");
16292            let mut buffers: Vec<_> = entries
16293                .iter()
16294                .filter(|entry| {
16295                    matches!(
16296                        entry.kind,
16297                        BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
16298                    )
16299                })
16300                .collect();
16301            buffers.sort_by_key(|entry| entry.binding);
16302            assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
16303            for (source, shader, names) in [
16304                (
16305                    include_str!("../../crcbl-shaders/shaders/mesh.slang"),
16306                    &MESH,
16307                    &["fragmentMain"][..],
16308                ),
16309                (
16310                    include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
16311                    &MESH_CLUSTER,
16312                    &["meshMain", "taskMain", "amplifiedMeshMain"][..],
16313                ),
16314            ] {
16315                let declarations: Vec<_> = source.lines().collect();
16316                let bindings: Vec<_> = declarations
16317                    .windows(2)
16318                    .filter_map(|lines| {
16319                        let binding = lines[0]
16320                            .trim()
16321                            .strip_prefix("[[vk::binding(")?
16322                            .split(',')
16323                            .next()?
16324                            .parse::<u32>()
16325                            .ok()?;
16326                        // The name is the last word before the D3D12 register.
16327                        let name = lines[1]
16328                            .split(" D3D12_REGISTER(")
16329                            .next()?
16330                            .split_whitespace()
16331                            .last()?
16332                            .trim_end_matches(';');
16333                        Some((name, binding))
16334                    })
16335                    .collect();
16336                for name in names {
16337                    let signature = shader
16338                        .msl()
16339                        .expect("committed native shader")
16340                        .lines()
16341                        .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
16342                        .expect("native entry signature");
16343                    let mut checked = 0;
16344                    for argument in signature.split(", ") {
16345                        let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
16346                            continue;
16347                        };
16348                        let native: usize = tail.split(')').next().unwrap().parse().unwrap();
16349                        let variable = declaration.split_whitespace().last().unwrap();
16350                        let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
16351                        let binding = bindings
16352                            .iter()
16353                            .find(|(candidate, _)| *candidate == variable)
16354                            .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
16355                            .1;
16356                        let expected = buffers
16357                            .iter()
16358                            .position(|entry| entry.binding == binding)
16359                            .expect("shader binding exists in the renderer layout");
16360                        assert_eq!(
16361                            native, expected,
16362                            "{name}: {variable}, logical binding {binding}, native shader vs global layout"
16363                        );
16364                        checked += 1;
16365                    }
16366                    assert!(
16367                        checked >= 10,
16368                        "entry parsing must cover the complete buffer interface"
16369                    );
16370                }
16371            }
16372            renderer.destroy(device.as_ref());
16373        }
16374    }
16375
16376    #[test]
16377    fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
16378        let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
16379        for optional in [Features::TASK_SHADER, Features::empty()] {
16380            let recorder = Recorder::new();
16381            let (device, queue) = open_mesh_path(&recorder, optional);
16382            let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16383                .expect("the forward renderer builds on both device shapes");
16384            assert_eq!(
16385                renderer.culls_clusters(),
16386                optional.contains(Features::TASK_SHADER),
16387                "the two arms must actually differ, or this compares a device with itself"
16388            );
16389            let (label, entries) = recorder
16390                .bind_group_layouts_created()
16391                .into_iter()
16392                .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
16393                .expect("the mesh pass declares its layout by name");
16394            assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
16395            declared.push(
16396                entries
16397                    .iter()
16398                    .map(|entry| (entry.binding, entry.kind))
16399                    .collect(),
16400            );
16401        }
16402
16403        let [amplified, plain] = declared
16404            .try_into()
16405            .unwrap_or_else(|_| unreachable!("two arms were run"));
16406        assert_eq!(
16407            amplified, plain,
16408            "the mesh layout's bindings changed with the task stage, which moves every Metal \
16409             argument-table index above the difference"
16410        );
16411        // These mesh declarations remain present without a task stage.
16412        for binding in [
16413            CLUSTER_CULL_BINDING,
16414            CLUSTER_CULL_STATS_BINDING,
16415            CLUSTER_SELECT_BINDING,
16416            CLUSTER_SELECTION_BINDING,
16417            CLUSTER_GROUP_STATE_BINDING,
16418        ] {
16419            assert!(
16420                plain.iter().any(|(number, _)| *number == binding),
16421                "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
16422            );
16423        }
16424        // Logical gaps consume no native slots. The complete shader union must
16425        // remain sorted, and every mesh-only buffer follows the fragment prefix.
16426        let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
16427        let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
16428        assert_eq!(
16429            numbers, expected,
16430            "the complete sparse shader binding union"
16431        );
16432    }
16433
16434    /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
16435    /// is built, and a device without it still draws.**
16436    ///
16437    /// The two capabilities are separate, and the adapter above offers both — so
16438    /// asking for one and not the other is a device state a real driver has and
16439    /// this can reach. Neither arm is a skip:
16440    ///
16441    /// * With the task stage, the renderer builds the amplification stage and
16442    ///   [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
16443    ///   task stage on a device without the flag, so an arm that computed this
16444    ///   wrongly would fail to build rather than pass quietly. It records one
16445    ///   flat call per partition — [`flat_dispatch_calls`].
16446    /// * Without it, the renderer builds `meshMain` — the un-amplified entry
16447    ///   point — and draws every cluster of every surviving instance, one
16448    ///   indirect dispatch per bucket reading its own extents.
16449    #[test]
16450    fn the_task_stage_is_built_only_where_the_device_has_one() {
16451        use crcbl_hal::null::Command;
16452
16453        for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
16454            let recorder = Recorder::new();
16455            let (device, queue) = open_mesh_path(&recorder, optional);
16456            let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
16457                .expect("the forward renderer builds on both device shapes");
16458            assert_eq!(
16459                device.caps().supports(Features::TASK_SHADER),
16460                expected,
16461                "the device must actually differ between the arms, or both test the same thing"
16462            );
16463            assert_eq!(
16464                renderer.culls_clusters(),
16465                expected,
16466                "the amplification stage is built exactly where the device has one"
16467            );
16468            assert_eq!(
16469                renderer.geometry_path(),
16470                GeometryPath::MeshShader,
16471                "both arms are the mesh path; only the stage in front of it differs"
16472            );
16473
16474            let frame = frame(device.as_ref(), &mut renderer, queue);
16475            // After the frame, because the buffer named is the slot the frame
16476            // rotated to — asking before it names the previous slot's ring
16477            // entry and the comparison is against a buffer nothing drew from.
16478            let expected = if expected {
16479                flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
16480            } else {
16481                mesh_dispatch_calls(&renderer)
16482            };
16483
16484            let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
16485                .into_iter()
16486                .filter_map(|command| match command {
16487                    Command::DrawMeshTasksIndirect(draw) => Some(draw),
16488                    _ => None,
16489                })
16490                .collect();
16491            assert_eq!(
16492                dispatched, expected,
16493                "a flat call per partition behind the stage, and a dispatch per bucket reading \
16494                 its own extents without it"
16495            );
16496
16497            frame.finish(device.as_ref(), renderer);
16498        }
16499    }
16500
16501    /// The flat calls a pass splitting the bucket table by the material-mode
16502    /// bits `key` records behind a task stage, in region 0, in partition order
16503    /// — one per segment the table holds buckets of — and each segment's first
16504    /// bucket, whose block the call binds.
16505    ///
16506    /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
16507    /// camera generator's own region count rather than from
16508    /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
16509    fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
16510        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
16511        let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
16512        let regions = renderer.primary.draws.mode().regions();
16513        let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
16514        let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
16515            vec![0, key]
16516        } else {
16517            DEPTH_MODES.to_vec()
16518        };
16519        values
16520            .into_iter()
16521            .filter(|value| {
16522                renderer
16523                    .bucket_modes
16524                    .iter()
16525                    .any(|mode| mode & key == *value)
16526            })
16527            .map(|value| {
16528                let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
16529                    .expect("a split every pass makes");
16530                (
16531                    DrawIndirect {
16532                        args: renderer.primary.draws.mesh_args(renderer.frame),
16533                        offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
16534                            buckets, regions, 0, segment, 0,
16535                        )) * 4,
16536                        draw_count: 1,
16537                        stride,
16538                    },
16539                    segments[segment as usize].0,
16540                )
16541            })
16542            .unzip()
16543    }
16544
16545    /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
16546    /// order.
16547    ///
16548    /// Built from the buffer the draw-argument pass writes and the stride the
16549    /// APIs fixed, so a test comparing against it is asserting that the call
16550    /// reads *this frame's* arguments at *this bucket's* offset — the two ways
16551    /// an indirect dispatch goes wrong while still dispatching something.
16552    ///
16553    /// **The offsets are multiplied out here rather than asked of
16554    /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
16555    /// comparison and a tautology: an offset function that returned zero for
16556    /// every bucket would agree with itself, and three calls onto one structure
16557    /// is a frame that draws one bucket's geometry three times.
16558    fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
16559        let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
16560        // The extents share a buffer with the one draw count per bucket that
16561        // precedes them, so every offset is that far in. Written out from the
16562        // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
16563        // for the reason above: a base of zero is exactly the mistake this
16564        // comparison exists to catch, and it would agree with itself.
16565        let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
16566        (0..renderer.bucket_constants.len())
16567            .map(|bucket| DrawIndirect {
16568                args: renderer.primary.draws.mesh_args(renderer.frame),
16569                offset: counts_bytes + bucket as u64 * u64::from(stride),
16570                draw_count: 1,
16571                stride,
16572            })
16573            .collect()
16574    }
16575
16576    /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
16577    /// pipeline, and records no indirect draw and no index-buffer bind at all.**
16578    ///
16579    /// The three halves are one claim. That it dispatched says the path is
16580    /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
16581    /// did not quietly fall through to a tail that draws the same picture; and
16582    /// that it bound no index buffer says the geometry really came out of the
16583    /// cluster records rather than out of the index pool. Until 2026-08 this
16584    /// device degraded and logged that it had, which is exactly the shape —
16585    /// "not implemented" arriving as a passing frame — the three together rule
16586    /// out.
16587    ///
16588    /// **The extents are not here to be checked, and that is the point.** They
16589    /// are three words the draw-argument pass writes, so what this can pin is
16590    /// the call reading *this* bucket's structure out of *this* frame's buffer
16591    /// — and the CPU-side half of the x extent, the per-bucket cluster table
16592    /// the host uploaded, which the null backend keeps the bytes of. What the
16593    /// GPU then makes of it needs a GPU: `crcbl-vk`'s
16594    /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
16595    /// arguments back.
16596    #[test]
16597    fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
16598        use crcbl_hal::null::Command;
16599
16600        let recorder = Recorder::new();
16601        let caps = crcbl_hal::DeviceCaps {
16602            features: Features::GPU_DRIVEN | Features::MESH_SHADER,
16603            limits: crcbl_hal::Limits::desktop(),
16604        };
16605        let instance = NullInstance::new(caps).with_recorder(recorder.clone());
16606        let adapter = instance.adapters().remove(0);
16607        assert_eq!(
16608            instance
16609                .adapter_caps(adapter.id)
16610                .expect("the null backend describes its adapter")
16611                .geometry_path(),
16612            GeometryPath::MeshShader,
16613            "a device with mesh shaders selects them, which is the case this is about"
16614        );
16615        let device = instance
16616            .create_device(&DeviceDesc {
16617                label: None,
16618                adapter: adapter.id,
16619                required_features: Features::COMPUTE,
16620                // Asked for, because a device reports what it enabled: leaving
16621                // mesh shaders out of the optional set would open a device that
16622                // selects an indirect path outright and test nothing.
16623                optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
16624                compatible_surface: None,
16625            })
16626            .expect("the null backend always opens");
16627        assert_eq!(
16628            device.caps().geometry_path(),
16629            GeometryPath::MeshShader,
16630            "and the opened device still selects it"
16631        );
16632        let queue = device.queue(QueueKind::Graphics).expect("always present");
16633        let mut renderer =
16634            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16635        assert_eq!(
16636            renderer.geometry_path(),
16637            GeometryPath::MeshShader,
16638            "the renderer must have *built* the mesh path, not merely been offered it"
16639        );
16640        let frame = frame(device.as_ref(), &mut renderer, queue);
16641        let expected = mesh_dispatch_calls(&renderer);
16642        // The table is written once at build, into a host-visible buffer the
16643        // null backend keeps the bytes of — so it is readable whether or not a
16644        // shader ever ran. It shares that buffer with the four other tables the
16645        // draw-argument pass reads, so the region has to be cut out at the
16646        // offset the renderer told the shader about rather than at zero.
16647        let table_bytes = recorder
16648            .buffer_bytes(renderer.primary.draws.tables())
16649            .expect("the table buffer is one of this recorder's buffers");
16650        let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16651        let clusters: Vec<u32> = table_bytes[clusters_at..]
16652            .as_chunks::<4>()
16653            .0
16654            .iter()
16655            .take(renderer.bucket_constants.len())
16656            .map(|word| u32::from_le_bytes(*word))
16657            .collect();
16658
16659        let mut dispatched = Vec::new();
16660        let mut index_binds = 0;
16661        for command in commands_in_pass(&recorder, "forward") {
16662            match command {
16663                Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16664                Command::DrawMeshTasks { .. } => panic!(
16665                    "the mesh path recorded a CPU-sized dispatch, which is the extent \
16666                     the instance cull is supposed to have taken over"
16667                ),
16668                Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16669                    panic!(
16670                        "the mesh path recorded an indirect draw, which is the silent \
16671                         fall-through this test exists to rule out"
16672                    )
16673                }
16674                Command::BindIndexBuffer { .. } => index_binds += 1,
16675                _ => {}
16676            }
16677        }
16678        assert_eq!(
16679            dispatched, expected,
16680            "one indirect dispatch per bucket, each reading its own argument structure \
16681             out of this frame's buffer"
16682        );
16683        assert_eq!(
16684            clusters.len(),
16685            renderer.bucket_constants.len(),
16686            "one x extent per bucket: {clusters:?}"
16687        );
16688        assert!(
16689            clusters.iter().all(|&count| count > 0),
16690            "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16691             {clusters:?}"
16692        );
16693        // **The x extents are not all the same number**, which is what makes
16694        // the table a statement about each bucket's own mesh. Two
16695        // single-cluster meshes would let a table hard-coded to one cluster
16696        // pass; the open box is five, one per face.
16697        assert_eq!(
16698            clusters[DEMO_OPEN_BOX] as usize,
16699            crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16700            "the open box dispatches one workgroup per face, and that is the only \
16701             resident whose cluster count is not one: {clusters:?}"
16702        );
16703        assert_eq!(
16704            index_binds, 0,
16705            "a mesh pipeline has no index buffer; binding one would mean the geometry \
16706             came from the index pool after all"
16707        );
16708
16709        frame.finish(device.as_ref(), renderer);
16710    }
16711
16712    /// **The cull pass is told the camera the frame is drawn with**, and how
16713    /// many array elements to walk.
16714    ///
16715    /// Both halves fail silently: a frustum from a different aspect ratio culls
16716    /// geometry that is on screen, and an instance count short of the pool's
16717    /// high-water mark stops testing the instances above a freed slot. Neither
16718    /// is visible in a picture until something disappears from an edge.
16719    #[test]
16720    fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16721        let (recorder, device, queue) = open();
16722        let mut renderer =
16723            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16724        // The cube first and the pyramid above it, because the second half of
16725        // this test frees the lower slot and asks what the walk still covers.
16726        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16727        place_demo(
16728            &mut renderer,
16729            DEMO_PYRAMID,
16730            DEMO_UNTINTED,
16731            Mat4::from_translation(Vec3::X),
16732        );
16733
16734        let camera = Camera {
16735            eye: Vec3::new(1.6, 1.2, 2.2),
16736            ..Camera::default()
16737        };
16738        let extent = (256u32, 192u32);
16739        renderer
16740            .begin_frame(
16741                device.as_ref(),
16742                &camera,
16743                &DirectionalLight::default(),
16744                extent,
16745            )
16746            .expect("write");
16747
16748        let aspect = extent.0 as f32 / extent.1 as f32;
16749        let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16750        let written = recorder
16751            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16752            .expect("this frame's cull parameters are live");
16753        assert_eq!(
16754            &written[..crcbl_shaders::cull::PARAMS_SIZE],
16755            &crcbl_shaders::cull::Params {
16756                planes: expected.planes.map(|plane| plane.to_array()),
16757                instance_count: 2,
16758                capacity: scene::Capacities::default().instances,
16759                hidden_view: ViewId::PRIMARY.hidden_bit(),
16760                ..crcbl_shaders::cull::Params::default()
16761            }
16762            .to_bytes()[..],
16763            "the cull block must carry this frame's own frustum, the pool's whole \
16764             occupied range, and the visible list's capacity"
16765        );
16766
16767        // And the high-water mark is what is written, not the live count: remove
16768        // the cube and the pyramid above it still has to be tested.
16769        renderer.remove_instance(cube);
16770        renderer
16771            .begin_frame(
16772                device.as_ref(),
16773                &camera,
16774                &DirectionalLight::default(),
16775                extent,
16776            )
16777            .expect("write");
16778        let written = recorder
16779            .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16780            .expect("live");
16781        assert_eq!(
16782            u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16783            2,
16784            "one live instance, two occupied slots — a walk of one would never \
16785             reach the pyramid"
16786        );
16787
16788        renderer.destroy(device.as_ref());
16789        recorder.assert_valid();
16790    }
16791
16792    /// **Every counter both compute passes add to is zeroed by a pass of its
16793    /// own, before either of them runs.**
16794    ///
16795    /// The two shaders only ever increment, so a counter carrying the previous
16796    /// frame's total makes a bucket's argument structure claim more instances
16797    /// than its run holds — which draws whatever the run's stale tail happens to
16798    /// name.
16799    ///
16800    /// # This once read the bytes back, and no longer can
16801    ///
16802    /// It used to poison every counter with `0xAB` and assert `begin_frame`
16803    /// had written zeroes over them — the poison being the whole test, because
16804    /// the null backend runs no shader and a counter nothing wrote reads as the
16805    /// zero it was created with. The counters are device-local now, so nothing
16806    /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16807    /// them: the zero is a dispatch inside the frame, and a backend that runs no
16808    /// shader cannot observe it at all.
16809    ///
16810    /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16811    /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16812    /// generated arguments — and what is checkable *here* is the schedule: that
16813    /// the frame contains the clearing pass, that it writes exactly those
16814    /// buffers, and that the graph orders the two accumulating passes after it.
16815    /// Each of the counts below goes red if a buffer is dropped from the
16816    /// clearing pass, and the pass list goes red if the pass leaves the frame.
16817    #[test]
16818    fn every_frame_starts_from_zeroed_counters() {
16819        let (recorder, device, queue) = open();
16820        let mut renderer =
16821            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16822        place_cube(&mut renderer, Mat4::IDENTITY);
16823        let imported = swapchain_image(device.as_ref());
16824        // Twice round the ring, because a slot cleared only on its first use is
16825        // exactly the failure this is about.
16826        for round in 0..FRAMES_IN_FLIGHT * 2 {
16827            renderer
16828                .begin_frame(
16829                    device.as_ref(),
16830                    &Camera::default(),
16831                    &DirectionalLight::default(),
16832                    (64, 48),
16833                )
16834                .expect("write");
16835            let mut graph = crate::RenderGraph::new(queue);
16836            let target = graph.import_image("target", imported);
16837            let pool = crate::TransientPool::new();
16838            renderer.add_passes(&mut graph, &pool, target, (64, 48));
16839            let compiled = graph.compile(&pool).expect("a legal frame");
16840
16841            let clear = &compiled.passes()[0];
16842            assert_eq!(
16843                clear.label(),
16844                "clear-counters",
16845                "round {round}: the zero has to be written before anything adds to it"
16846            );
16847            let barriers = &clear.barriers().buffers;
16848            assert_eq!(
16849                barriers.len(),
16850                3,
16851                "round {round}: the survivor count, the draw arguments, and the buffer \
16852                 holding both the draw counts and the mesh-dispatch arguments, and \
16853                 nothing else: {barriers:?}"
16854            );
16855            assert!(
16856                barriers
16857                    .iter()
16858                    .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16859                "round {round}: every one of them is written by this pass: {barriers:?}"
16860            );
16861            // The ones the frame leaves as indirect arguments are the two a
16862            // driver reads; the survivor count rests in a shader read. That
16863            // split is what names them without a handle to compare.
16864            assert_eq!(
16865                barriers
16866                    .iter()
16867                    .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16868                    .count(),
16869                2,
16870                "round {round}: out of the state a draw read them in: {barriers:?}"
16871            );
16872
16873            let after = |label: &str| {
16874                compiled
16875                    .passes()
16876                    .iter()
16877                    .find(|pass| pass.label() == label)
16878                    .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16879                    .barriers()
16880                    .buffers
16881                    .iter()
16882                    .filter(|barrier| {
16883                        barrier.from == ResourceState::ShaderReadWrite
16884                            && barrier.to == ResourceState::ShaderReadWrite
16885                    })
16886                    .count()
16887            };
16888            assert_eq!(
16889                after("cull"),
16890                1,
16891                "round {round}: the survivor count reaches the cull pass's atomic behind a \
16892                 barrier on the write that zeroed it"
16893            );
16894            assert_eq!(
16895                after("draw-args"),
16896                4,
16897                "round {round}: and so do the draw arguments and the buffer holding the \
16898                 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16899                 which the cull pass has just written and this pass reads through the same \
16900                 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16901                 hysteresis state, which the clearing pass does *not* zero and which is \
16902                 behind the same kind of barrier for the opposite reason: it is the one \
16903                 buffer here carrying a value out of the previous frame, so what it needs \
16904                 ordering against is that frame rather than this one's clear"
16905            );
16906            // **And the prefix sum and the scatter behind barriers of their own**,
16907            // on every buffer the stage before them wrote. This is what orders
16908            // them on a device that runs undeclared commands in any order — see
16909            // `DrawGen::add_passes` — and what three dispatches in one pass
16910            // silently lacked.
16911            for label in ["draw-starts", "draw-scatter"] {
16912                assert_eq!(
16913                    after(label),
16914                    4,
16915                    "round {round}: `{label}` reads what the pass before it wrote, so every \
16916                     buffer they share is ordered behind a barrier"
16917                );
16918            }
16919
16920            // The compiled graph borrows the renderer's pass bodies, so it has
16921            // to go before the next frame borrows the renderer again.
16922            drop(compiled);
16923        }
16924        renderer.destroy(device.as_ref());
16925        device.destroy_image_view(imported.view);
16926        device.destroy_image(imported.image);
16927        recorder.assert_valid();
16928    }
16929
16930    /// **A frame with no instances leaves out every generator's cull and
16931    /// scatter passes**, and keeps the clear and the two stages that write each
16932    /// bucket's arguments.
16933    ///
16934    /// An empty pass is not a harmless no-op on Metal: the backend opens an
16935    /// encoder for every graph pass and strict validation rejects ending one
16936    /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16937    /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16938    #[test]
16939    fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16940        let (recorder, device, queue) = open();
16941        let mut renderer =
16942            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16943        renderer
16944            .begin_frame(
16945                device.as_ref(),
16946                &Camera::default(),
16947                &DirectionalLight::default(),
16948                (64, 48),
16949            )
16950            .expect("write");
16951        let imported = swapchain_image(device.as_ref());
16952        let mut graph = crate::RenderGraph::new(queue);
16953        let target = graph.import_image("target", imported);
16954        let pool = crate::TransientPool::new();
16955        renderer.add_passes(&mut graph, &pool, target, (64, 48));
16956        let compiled = graph.compile(&pool).expect("a legal frame");
16957
16958        let count = |label: &str| {
16959            compiled
16960                .passes()
16961                .iter()
16962                .filter(|pass| pass.label() == label)
16963                .count()
16964        };
16965        // The camera's generator and one per shadow cascade.
16966        let generators = 1 + shadow::CASCADES;
16967        for label in ["clear-counters", "draw-args", "draw-starts"] {
16968            assert_eq!(
16969                count(label),
16970                generators,
16971                "`{label}` still has work with nothing to draw: the clear erases the \
16972                 previous frame's counts and the argument stages write zero draws"
16973            );
16974        }
16975        for label in ["cull", "draw-scatter"] {
16976            assert_eq!(
16977                count(label),
16978                0,
16979                "`{label}` has no workgroups to dispatch with no instances"
16980            );
16981        }
16982
16983        drop(compiled);
16984        renderer.destroy(device.as_ref());
16985        device.destroy_image_view(imported.view);
16986        device.destroy_image(imported.image);
16987        recorder.assert_valid();
16988    }
16989
16990    /// **The graph transitions the generated arguments into
16991    /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16992    /// runs into a shader read.
16993    ///
16994    /// The seam calls this the single most important barrier in a GPU-driven
16995    /// frame and says its absence produces "sometimes nothing draws" — which is
16996    /// exactly the failure a golden image on one driver would not catch. It is
16997    /// asserted on the compiled graph, which is pure and needs no device.
16998    #[test]
16999    fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
17000        let _blurs = ssao_blur_switch();
17001        let (recorder, device, queue) = open();
17002        let mut renderer =
17003            ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
17004        place_cube(&mut renderer, Mat4::IDENTITY);
17005        renderer
17006            .begin_frame(
17007                device.as_ref(),
17008                &Camera::default(),
17009                &DirectionalLight::default(),
17010                (64, 48),
17011            )
17012            .expect("write");
17013
17014        let imported = swapchain_image(device.as_ref());
17015        let mut graph = crate::RenderGraph::new(queue);
17016        let target = graph.import_image("target", imported);
17017        let pool = crate::TransientPool::new();
17018        renderer.add_passes(&mut graph, &pool, target, (64, 48));
17019        let compiled = graph.compile(&pool).expect("a legal frame");
17020
17021        let passes: Vec<String> = compiled
17022            .passes()
17023            .iter()
17024            .map(|pass| pass.label().to_string())
17025            .collect();
17026        // The camera's five compute passes and topic 18's clustering dispatch,
17027        // then five per shadow cascade, then the depth-only pass they feed and
17028        // the colour pass that samples it.
17029        //
17030        // **The clustering pass is after the camera's clearing dispatch**, and
17031        // that is the ordering the overflow counter depends on: the clearing
17032        // pass zeroes the statistics word this one adds to, and both declare
17033        // the same buffer, so the graph is what puts the barrier between them.
17034        let mut expected: Vec<String> = Vec::new();
17035        for cascade in 0..=shadow::CASCADES {
17036            expected.extend(
17037                [
17038                    "clear-counters",
17039                    "cull",
17040                    "draw-args",
17041                    "draw-starts",
17042                    "draw-scatter",
17043                ]
17044                .into_iter()
17045                .map(str::to_string),
17046            );
17047            if cascade == 0 {
17048                expected.push("light-cluster".to_string());
17049            }
17050        }
17051        // And the culling-statistics copy **last**, after every pass that adds
17052        // to the buffer it reads — the cull dispatch, the clustering pass and
17053        // the amplification stage inside the colour pass.
17054        expected.extend(
17055            [
17056                "shadow",
17057                "depth-prepass",
17058                "ssao",
17059                "ssao-blur",
17060                // The reconstruction that ends the occlusion chain, between the
17061                // blur it reads and the pass that binds what it wrote — see
17062                // [`crate::ssao`]'s header on why the first two run smaller than
17063                // the frame and this one does not.
17064                "ssao-upsample",
17065                "forward",
17066                // The pyramid the march climbs, between the pass that wrote
17067                // level 0 and the pass that reads the chain. Two levels at this
17068                // extent, written out for the reason `crate::bloom`'s chain is
17069                // in the toggle test below: a table generated from
17070                // `crate::hiz::levels_for` could not fail.
17071                "hiz-1",
17072                "hiz-2",
17073                "ssr",
17074                "ssr-blur",
17075                "tonemap",
17076                // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
17077                // CMAA2's three rather than FXAA's one —
17078                // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
17079                // where the swap between the two tiers is pinned.
17080                "cmaa2-edges",
17081                "cmaa2-shapes",
17082                "cmaa2-apply",
17083                "cull-stats-readback",
17084            ]
17085            .into_iter()
17086            .map(str::to_string),
17087        );
17088        assert_eq!(
17089            passes, expected,
17090            "each cull's five compute passes come first, and in that order"
17091        );
17092
17093        // **The depth prepass, not the colour pass**, and that is what says the
17094        // prepass really is the first thing to draw from the camera's cull: it is
17095        // where the draw buffers leave the compute pass's writes. The colour pass
17096        // below then needs none of these, because they are already in the state it
17097        // wants — which is the assertion after it.
17098        let prepass = compiled
17099            .passes()
17100            .iter()
17101            .find(|pass| pass.label() == "depth-prepass")
17102            .expect("the pass list above");
17103        let into_indirect = prepass
17104            .barriers()
17105            .buffers
17106            .iter()
17107            .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
17108            .count();
17109        assert_eq!(
17110            into_indirect,
17111            2,
17112            "the arguments and the count, out of the compute pass's writes and into \
17113             the state a draw reads them in: {:?}",
17114            prepass.barriers().buffers
17115        );
17116        assert!(
17117            prepass.barriers().buffers.iter().any(|barrier| {
17118                barrier.from == ResourceState::ShaderReadWrite
17119                    && barrier.to == ResourceState::ShaderRead
17120            }),
17121            "and the runs, which the vertex stage reads: {:?}",
17122            prepass.barriers().buffers
17123        );
17124
17125        let forward = compiled
17126            .passes()
17127            .iter()
17128            .find(|pass| pass.label() == "forward")
17129            .expect("the pass list above");
17130        assert!(
17131            forward
17132                .barriers()
17133                .buffers
17134                .iter()
17135                .all(|barrier| barrier.to != ResourceState::IndirectArgument),
17136            "the prepass draws from the same arguments, so the colour pass finds them \
17137             already in the state it wants — a barrier here would mean something between \
17138             the two put them back: {:?}",
17139            forward.barriers().buffers
17140        );
17141        // What the colour pass *does* still have to be given: the froxel grid,
17142        // which no earlier pass reads.
17143        assert!(
17144            forward.barriers().buffers.iter().any(|barrier| {
17145                barrier.from == ResourceState::ShaderReadWrite
17146                    && barrier.to == ResourceState::ShaderRead
17147            }),
17148            "and the froxel grid, which its fragment stage reads: {:?}",
17149            forward.barriers().buffers
17150        );
17151
17152        let draw_args = compiled
17153            .passes()
17154            .iter()
17155            .find(|pass| pass.label() == "draw-args")
17156            .expect("the pass list above");
17157        assert!(
17158            draw_args.barriers().buffers.iter().any(|barrier| {
17159                barrier.from == ResourceState::ShaderReadWrite
17160                    && barrier.to == ResourceState::ShaderRead
17161            }),
17162            "and the visible list is ordered after the cull pass wrote it: {:?}",
17163            draw_args.barriers().buffers
17164        );
17165
17166        // The compiled graph borrows the renderer's pass bodies, so it has to go
17167        // before the renderer does.
17168        drop(compiled);
17169        renderer.destroy(device.as_ref());
17170        device.destroy_image_view(imported.view);
17171        device.destroy_image(imported.image);
17172        recorder.assert_valid();
17173    }
17174
17175    /// One more frame than the uniform ring is deep, so at least one lap both
17176    /// reuses a slot and follows a lap that already sampled the atlas.
17177    const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
17178
17179    /// **Every frame's first barrier on the shadow atlas names what the previous
17180    /// frame left it in**, and the same for its placeholder.
17181    ///
17182    /// # Why this cannot be read off one frame
17183    ///
17184    /// The atlas is neither a transient nor a swapchain image. The pool never
17185    /// hands one out and has no description to size it from, and no acquire
17186    /// semaphore sits between one frame's use of it and the next — so
17187    /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
17188    /// makes the transition true.
17189    ///
17190    /// What it declares is [`imported_state`], the pool's record of what the
17191    /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
17192    /// can only ever find the two agreeing for this one import — deliberately,
17193    /// because a declaration and an audit reading one value cannot drift apart
17194    /// the way a renderer-held copy of it could. The audit still has teeth
17195    /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
17196    /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
17197    /// what shows it fires on those.
17198    ///
17199    /// So neither mechanism says anything about the barriers on either side of
17200    /// the declaration — whether the frame that ran actually reached the state
17201    /// the ledger now claims, and whether the next frame's first barrier comes
17202    /// out of it — which is what the stream below is for.
17203    ///
17204    /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
17205    /// failure this catches. It expands to `srcStageMask = NONE,
17206    /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
17207    /// into the depth-only pass's attachment state orders against nothing — while
17208    /// the previous frame's colour pass is still sampling the very same image.
17209    /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
17210    /// `read_barriers: 0`; every other backend resolves it however the driver
17211    /// likes.
17212    ///
17213    /// # Why the command stream is the observable
17214    ///
17215    /// Nothing above the seam can see a wrong declaration: the frame still
17216    /// renders, the golden still matches, and no state is ever read back. So this
17217    /// replays the recorded stream with a tracker, which is the same check a
17218    /// validation layer performs and needs no GPU at all — the shape
17219    /// `crcbl::screenshot`'s
17220    /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
17221    /// One difference: `Undefined` is **not** waved through after the first
17222    /// touch. It is true for a swapchain image because the acquire's semaphore
17223    /// makes it true, and there is no such semaphore here.
17224    #[test]
17225    fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
17226        use crcbl_hal::null::Command;
17227
17228        let (recorder, device, queue) = open();
17229        let device = device.as_ref();
17230        let mut renderer =
17231            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17232        let atlas = renderer.shadow_atlas();
17233        let placeholder = renderer.shadow_placeholder;
17234        let mut pool = crate::TransientPool::new();
17235        let imported = swapchain_image(device);
17236        let mut recorded = Vec::with_capacity(SHADOW_LAPS);
17237
17238        for lap in 0..SHADOW_LAPS {
17239            renderer
17240                .begin_frame(
17241                    device,
17242                    &Camera::default(),
17243                    // **A different sun each lap**, so every lap redraws the
17244                    // atlas: this is a test about the barrier a frame that
17245                    // writes the image declares, and a lap that cached would
17246                    // record no pass and no transition at all. See
17247                    // [`moving_sun`].
17248                    &moving_sun(u32::try_from(lap).expect("a handful of laps")),
17249                    (64, 48),
17250                )
17251                .expect("write");
17252            let mut graph = crate::RenderGraph::new(queue);
17253            let target = graph.import_image("target", imported);
17254            renderer.add_passes(&mut graph, &pool, target, (64, 48));
17255            let compiled = graph.compile(&pool).expect("a legal frame");
17256            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17257                label: Some("shadow lap"),
17258                queue,
17259            });
17260            compiled
17261                .execute(device, &mut pool, encoder.as_mut(), None)
17262                .expect("the graph executed");
17263            recorded.push(encoder.finish().expect("recording succeeded"));
17264        }
17265
17266        // The two images the renderer owns across frames. A transient's state is
17267        // the pool's business and the fake swapchain image's is the acquire's, so
17268        // neither belongs in here.
17269        let mut tracked = [
17270            (atlas, ResourceState::Undefined),
17271            (placeholder, ResourceState::Undefined),
17272        ];
17273        let mut atlas_writes = 0usize;
17274        let mut named = 0usize;
17275        for command in recorder.commands() {
17276            let Command::Barrier { images, .. } = command else {
17277                continue;
17278            };
17279            for barrier in images {
17280                let Some((_, state)) = tracked
17281                    .iter_mut()
17282                    .find(|(handle, _)| *handle == barrier.image)
17283                else {
17284                    continue;
17285                };
17286                assert_eq!(
17287                    barrier.from, *state,
17288                    "a barrier declared {:?} -> {:?} on an image the frame before it left in \
17289                     {:?}. `Undefined` carries no source scope, so a transition declaring it \
17290                     orders against nothing and the previous frame's sampled read is still in \
17291                     flight underneath it.",
17292                    barrier.from, barrier.to, *state
17293                );
17294                if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
17295                    atlas_writes += 1;
17296                }
17297                *state = barrier.to;
17298                named += 1;
17299            }
17300        }
17301
17302        // Both halves of the loop above are silent on an empty stream, so the
17303        // shape it walked is asserted rather than assumed: one transition into
17304        // the depth-only pass's attachment state per lap, the last one included.
17305        assert_eq!(
17306            atlas_writes, SHADOW_LAPS,
17307            "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
17308             {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
17309             the sun, so every lap redraws the atlas, and anything else means the loop above \
17310             asserted on a stream that does not contain the transition it is about"
17311        );
17312        let (_, ended) = tracked[0];
17313        assert_eq!(
17314            ended,
17315            ResourceState::ShaderRead,
17316            "the import promises to hand the atlas back in the state the next frame declares"
17317        );
17318
17319        renderer.destroy(device);
17320        for commands in recorded {
17321            device.destroy_command_buffer(commands);
17322        }
17323        pool.destroy(device);
17324        device.destroy_image_view(imported.view);
17325        device.destroy_image(imported.image);
17326        recorder.assert_valid();
17327    }
17328
17329    /// A renderer with a shadowed spot beside the sun's cascades and a caster
17330    /// for both to draw, which is the smallest scene the atlas cache has
17331    /// anything to say about: without a light tile the only maps are the
17332    /// cascades, and without a caster every tile is a clear.
17333    fn shadow_cache_scene(
17334        device: &dyn Device,
17335        queue: QueueHandle,
17336    ) -> (ForwardRenderer, InstanceHandle) {
17337        let mut renderer =
17338            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17339        // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
17340        // are process-global and `the_console_moves_both_limits` holds them at
17341        // a four-frame hold and three faces a frame for the length of its
17342        // check. A cache test reading the console inside that window reports
17343        // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
17344        // holding both limits at those values inside the arm's own process,
17345        // which the pin makes harmless.
17346        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17347        let cube = place_cube(&mut renderer, Mat4::IDENTITY);
17348        renderer.set_lights(&[shadowable_spot(-1.0)]);
17349        (renderer, cube)
17350    }
17351
17352    /// Draws one frame and answers whether it drew the shadow atlas, **read two
17353    /// ways that have to agree**.
17354    ///
17355    /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
17356    /// the recorded stream is what the device was actually told; either on its
17357    /// own would be satisfied by a renderer that reported one thing and did the
17358    /// other, which is precisely the failure a cache has. `seen` is the cursor
17359    /// into the cumulative recorder, so each call reads its own frame.
17360    fn drew_the_atlas(
17361        recorder: &Recorder,
17362        seen: &mut usize,
17363        device: &dyn Device,
17364        renderer: &mut ForwardRenderer,
17365        queue: QueueHandle,
17366        camera: &Camera,
17367        sun: &DirectionalLight,
17368    ) -> bool {
17369        let drawn = frame_seen_from(device, renderer, queue, camera, sun);
17370        let claimed = renderer.shadow_atlas_cached();
17371        let commands = recorder.commands();
17372        let opened = commands[*seen..].iter().any(|command| {
17373            command
17374                .opens_pass()
17375                .is_some_and(|(_, label)| label == Some("shadow"))
17376        });
17377        *seen = commands.len();
17378        drawn.release(device);
17379        assert_eq!(
17380            opened,
17381            !claimed,
17382            "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
17383            if opened { "opened" } else { "opened no" }
17384        );
17385        opened
17386    }
17387
17388    #[test]
17389    fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
17390        let (recorder, device, queue) = open();
17391        let device = device.as_ref();
17392        let (mut renderer, _) = shadow_cache_scene(device, queue);
17393        let camera = Camera::default();
17394        let sun = DirectionalLight::default();
17395        let mut seen = 0;
17396        assert!(drew_the_atlas(
17397            &recorder,
17398            &mut seen,
17399            device,
17400            &mut renderer,
17401            queue,
17402            &camera,
17403            &sun
17404        ));
17405        let capacity = (
17406            renderer.shadow_prepare_views.capacity(),
17407            renderer.shadow_prepare_culls.capacity(),
17408        );
17409        assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
17410        assert!(renderer.shadow_prepare_views.is_empty());
17411        assert!(renderer.shadow_prepare_culls.is_empty());
17412        for _ in 0..FRAMES_IN_FLIGHT {
17413            assert!(!drew_the_atlas(
17414                &recorder,
17415                &mut seen,
17416                device,
17417                &mut renderer,
17418                queue,
17419                &camera,
17420                &sun
17421            ));
17422            assert!(renderer.shadow_prepare_views.is_empty());
17423            assert!(renderer.shadow_prepare_culls.is_empty());
17424            assert_eq!(
17425                (
17426                    renderer.shadow_prepare_views.capacity(),
17427                    renderer.shadow_prepare_culls.capacity()
17428                ),
17429                capacity
17430            );
17431        }
17432        for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
17433            // The spot moves for its own view and the camera for the cascades',
17434            // which are fitted to it: a moved spot alone is no input of theirs.
17435            renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
17436            let camera = Camera {
17437                eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
17438                ..camera
17439            };
17440            let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
17441            let short = device
17442                .create_buffer(&BufferDesc {
17443                    label: Some("refused shadow scratch test upload"),
17444                    size: std::mem::size_of::<f32>() as u64,
17445                    usage: BufferUsage::UNIFORM,
17446                    memory: MemoryLocation::HostUpload,
17447                })
17448                .unwrap();
17449            let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
17450            let before = recorder.buffer_bytes(short).unwrap();
17451            let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
17452            renderer.shadow_uniforms[slot][view] = original;
17453            assert!(
17454                matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
17455                "observe a refused shadow uniform: {result:?}"
17456            );
17457            assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
17458            assert!(!recorder.events().iter().any(
17459                |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
17460            ));
17461            assert!(renderer.shadow_prepare_views.is_empty());
17462            assert!(renderer.shadow_prepare_culls.is_empty());
17463            assert_eq!(
17464                (
17465                    renderer.shadow_prepare_views.capacity(),
17466                    renderer.shadow_prepare_culls.capacity()
17467                ),
17468                capacity
17469            );
17470            let refused_inputs = renderer.shadow_group_inputs.clone();
17471            device.destroy_buffer(short);
17472            recorder.assert_valid();
17473            assert!(drew_the_atlas(
17474                &recorder,
17475                &mut seen,
17476                device,
17477                &mut renderer,
17478                queue,
17479                &camera,
17480                &sun
17481            ));
17482            assert_eq!(renderer.shadow_group_inputs, refused_inputs);
17483            assert!(renderer.shadow_prepare_views.is_empty());
17484            assert!(renderer.shadow_prepare_culls.is_empty());
17485            assert_eq!(
17486                (
17487                    renderer.shadow_prepare_views.capacity(),
17488                    renderer.shadow_prepare_culls.capacity()
17489                ),
17490                capacity
17491            );
17492            assert!(!drew_the_atlas(
17493                &recorder,
17494                &mut seen,
17495                device,
17496                &mut renderer,
17497                queue,
17498                &camera,
17499                &sun
17500            ));
17501        }
17502        renderer.destroy(device);
17503        recorder.assert_valid();
17504        assert_eq!(recorder.total_live_objects(), 0);
17505    }
17506
17507    /// **A frame over a scene nothing moved in does not draw the shadow atlas
17508    /// again**, and what it saves is the whole of the atlas's work.
17509    ///
17510    /// Topic 45's static-caching rung, and the observable it
17511    /// otherwise has none for: the map a cached frame samples is byte for byte
17512    /// the map the frame before it sampled, so no golden image and no readback
17513    /// can tell the two frames apart. The recorded command stream can — and the
17514    /// dispatch count is the half that says the *culls* went with the pass,
17515    /// rather than the frame still paying for the draws it decided not to
17516    /// record.
17517    #[test]
17518    fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
17519        use crcbl_hal::null::Command;
17520
17521        // The blur count is a process-global console variable, and the frame's
17522        // draw count below includes the full-screen triangle each blur records
17523        // — so a concurrent test holding `r_ssao_blur_passes` at two would move
17524        // it under this one. Held rather than merely read, which is the
17525        // convention that variable's own test set.
17526        let _blurs = ssao_blur_switch();
17527        let (recorder, device, queue) = open();
17528        let device = device.as_ref();
17529        let (mut renderer, _) = shadow_cache_scene(device, queue);
17530        let camera = Camera::default();
17531        let sun = DirectionalLight::default();
17532
17533        let mut seen = 0usize;
17534        let dispatches = |recorder: &Recorder, from: usize| {
17535            recorder.commands()[from..]
17536                .iter()
17537                .filter(|command| matches!(command, Command::Dispatch { .. }))
17538                .count()
17539        };
17540
17541        let at = seen;
17542        assert!(
17543            drew_the_atlas(
17544                &recorder,
17545                &mut seen,
17546                device,
17547                &mut renderer,
17548                queue,
17549                &camera,
17550                &sun
17551            ),
17552            "the first frame of all has to draw the atlas: nothing has put anything in it"
17553        );
17554        let first = dispatches(&recorder, at);
17555        let drawing_draws = renderer.counters().draws;
17556        let buckets = renderer.bucket_constants.len() as u64;
17557        assert!(
17558            renderer.shadow_lights().base_of(0).is_some(),
17559            "the spot must hold a run for the count below to include a light slot's cull"
17560        );
17561        // The camera's own draw generation and topic 18's clustering dispatch,
17562        // plus a generation per cascade and one for the spot's slot.
17563        assert_eq!(
17564            first,
17565            DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
17566            "the drawing frame did not record the culls this test is about skipping"
17567        );
17568
17569        for round in 0..3 {
17570            let at = seen;
17571            assert!(
17572                !drew_the_atlas(
17573                    &recorder,
17574                    &mut seen,
17575                    device,
17576                    &mut renderer,
17577                    queue,
17578                    &camera,
17579                    &sun
17580                ),
17581                "round {round} redrew an atlas nothing had changed"
17582            );
17583            assert_eq!(
17584                dispatches(&recorder, at),
17585                DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
17586                "round {round} kept a shadow cull it had no pass to feed"
17587            );
17588            assert_eq!(
17589                drawing_draws - renderer.counters().draws,
17590                (shadow::CASCADES + 1) as u64 * buckets,
17591                "round {round}: the frame's own draw count did not lose exactly the atlas's \
17592                 calls — one per bucket per cascade, and one per bucket for the spot's tile"
17593            );
17594        }
17595
17596        renderer.destroy(device);
17597        recorder.assert_valid();
17598    }
17599
17600    /// A cadence that holds every map one rung down for a frame, with the whole
17601    /// atlas's worth of tiles to spend.
17602    ///
17603    /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
17604    /// the console: [`shadow::r_shadow_cadence`] is process-global and the
17605    /// shadow pass is in every frame's pass list, so a test that moved it would
17606    /// change the frame every other test in this module draws.
17607    const HOLD_TWO: shadow::Cadence = shadow::Cadence {
17608        hold: 2,
17609        faces: shadow::TILES,
17610    };
17611
17612    /// How the shadow pass loaded its depth attachment, over the commands from
17613    /// `from` on, and [`None`] where the frame recorded no such pass.
17614    ///
17615    /// **The observable the tile clear otherwise has none for.** A frame that
17616    /// kept a tile and a frame that redrew every one of them sample maps that
17617    /// may be identical, so nothing in the picture separates them; this is the
17618    /// declaration that says which the device was told.
17619    fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
17620        use crcbl_hal::null::Command;
17621
17622        recorder.commands()[from..].iter().find_map(|command| {
17623            let Command::BeginRenderPass {
17624                label,
17625                depth_stencil_attachment,
17626                ..
17627            } = command
17628            else {
17629                return None;
17630            };
17631            if label.as_deref() != Some("shadow") {
17632                return None;
17633            }
17634            depth_stencil_attachment
17635                .as_ref()
17636                .map(|attachment| attachment.depth_load)
17637        })
17638    }
17639
17640    /// Direct draws recorded inside the shadow pass, over the commands from
17641    /// `from` on — which is one per tile the pass reset itself, the atlas's
17642    /// geometry being drawn indirectly.
17643    fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
17644        use crcbl_hal::null::Command;
17645
17646        let mut inside = false;
17647        let mut clears = 0;
17648        for command in &recorder.commands()[from..] {
17649            if let Some((_, label)) = command.opens_pass() {
17650                inside = label == Some("shadow");
17651                continue;
17652            }
17653            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17654                inside = false;
17655                continue;
17656            }
17657            if inside && matches!(command, Command::Draw { .. }) {
17658                clears += 1;
17659            }
17660        }
17661        clears
17662    }
17663
17664    /// **The far cascade is redrawn every second frame and the near one every
17665    /// frame**, on a scene where the eye moves and so every map is out of date.
17666    ///
17667    /// Topic 45's cadence rung, and the observable it otherwise
17668    /// has none for: a held map draws a shadow one frame behind its caster,
17669    /// which is a plausible picture and one a golden accepts.
17670    ///
17671    /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17672    /// reset — that is asserted rather than assumed, because a reset would make
17673    /// every frame redraw everything and this test would pass by having
17674    /// switched the cadence off.
17675    #[test]
17676    fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17677        let _blurs = ssao_blur_switch();
17678        let (recorder, device, queue) = open();
17679        let device = device.as_ref();
17680        let (mut renderer, _) = shadow_cache_scene(device, queue);
17681        let sun = DirectionalLight::default();
17682        renderer.set_shadow_cadence(Some(HOLD_TWO));
17683
17684        const FRAMES: usize = 8;
17685        let mut near = 0;
17686        let mut far = 0;
17687        for step in 0..FRAMES {
17688            #[expect(
17689                clippy::cast_precision_loss,
17690                reason = "a handful of frames, and the step is what is wanted"
17691            )]
17692            let camera = Camera {
17693                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17694                ..Camera::default()
17695            };
17696            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17697            assert_eq!(
17698                renderer.shadow_cadence_reset(),
17699                step == 0,
17700                "frame {step}: only the first frame has an atlas to lay out, and a reset \
17701                 after it would redraw everything and leave nothing for the cadence to hold"
17702            );
17703            near += usize::from(renderer.shadow_cascade_redrawn(0));
17704            far += usize::from(renderer.shadow_cascade_redrawn(1));
17705            drawn.release(device);
17706        }
17707        assert_eq!(
17708            near, FRAMES,
17709            "the near cascade is fitted to the eye and is on the top rung: every frame"
17710        );
17711        assert_eq!(
17712            far,
17713            FRAMES / 2,
17714            "the far cascade is one rung down, so every second frame"
17715        );
17716
17717        renderer.destroy(device);
17718        recorder.assert_valid();
17719    }
17720
17721    /// **A frame that keeps a tile loads the attachment and resets the tiles it
17722    /// redraws itself**, and a frame that keeps none clears it — which is what
17723    /// shipped.
17724    ///
17725    /// The half of the cadence a redraw count cannot see: holding a tile is only
17726    /// worth anything if the tile survives, and the one clear this seam has
17727    /// covers the whole image. A frame that loaded and reset nothing would draw
17728    /// into tiles still holding the last frame's depths, and under reversed-Z a
17729    /// caster that moved away would go on occluding.
17730    #[test]
17731    fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17732        let _blurs = ssao_blur_switch();
17733        let (recorder, device, queue) = open();
17734        let device = device.as_ref();
17735        let (mut renderer, _) = shadow_cache_scene(device, queue);
17736        let sun = DirectionalLight::default();
17737
17738        // The first frame lays the atlas out, so it clears and redraws
17739        // everything whatever the console says.
17740        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17741        first.release(device);
17742        assert_eq!(
17743            shadow_pass_depth_load(&recorder, 0),
17744            Some(LoadOp::Clear),
17745            "the frame that lays the atlas out has nothing to keep"
17746        );
17747        assert_eq!(
17748            tile_clears_in_the_shadow_pass(&recorder, 0),
17749            0,
17750            "and so resets no tile of its own"
17751        );
17752
17753        renderer.set_shadow_cadence(Some(HOLD_TWO));
17754        let mut seen = recorder.commands().len();
17755        let mut loaded = 0;
17756        for step in 1..4 {
17757            #[expect(
17758                clippy::cast_precision_loss,
17759                reason = "a handful of frames, and the step is what is wanted"
17760            )]
17761            let camera = Camera {
17762                eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17763                ..Camera::default()
17764            };
17765            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17766            let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17767            let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17768            let faces = renderer.shadow_faces_redrawn() as usize;
17769            if load == LoadOp::Load {
17770                loaded += 1;
17771                assert_eq!(
17772                    clears, faces,
17773                    "frame {step} loaded the attachment and reset {clears} of the {faces} \
17774                     tiles it redrew"
17775                );
17776                assert!(
17777                    faces < shadow::TILES,
17778                    "frame {step} loaded an attachment while redrawing every tile"
17779                );
17780            } else {
17781                assert_eq!(
17782                    clears, 0,
17783                    "frame {step} cleared the attachment and reset {clears} tiles again"
17784                );
17785            }
17786            seen = recorder.commands().len();
17787            drawn.release(device);
17788        }
17789        assert!(
17790            loaded > 0,
17791            "no frame kept a tile, so nothing here is about the load path"
17792        );
17793
17794        renderer.destroy(device);
17795        recorder.assert_valid();
17796    }
17797
17798    /// A point light costs the budget every face it draws, not one.
17799    ///
17800    /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17801    /// a sum over the groups a frame redrew of the maps each of them owns, and
17802    /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17803    /// here is built on the sun and a spot, which own one map each — so a face
17804    /// count that answered `1` for every group would satisfy all of them, and
17805    /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17806    /// suite. This is what binds on the difference.
17807    #[test]
17808    fn a_point_light_costs_the_budget_every_face_it_draws() {
17809        let _blurs = ssao_blur_switch();
17810        let (_recorder, device, queue) = open();
17811        let device = device.as_ref();
17812        let mut renderer =
17813            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17814        let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17815        renderer.set_lights(&[shadowable_point(-1.0)]);
17816        let sun = DirectionalLight::default();
17817
17818        // Every group is forced on the first frame — the image has held none of
17819        // them — so this counts what a full redraw actually costs.
17820        renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17821        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17822        first.release(device);
17823        let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17824        assert!(
17825            renderer.shadow_lights().base_of(0).is_some(),
17826            "the point must hold a run of tiles, or there is no multi-face group to count"
17827        );
17828        assert!(
17829            renderer.shadow_faces_redrawn() >= point_faces,
17830            "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17831             {point_faces} it owns — so the budget is counting groups rather than the maps they \
17832             draw, and a cube would slip past a budget of one",
17833            renderer.shadow_faces_redrawn()
17834        );
17835    }
17836
17837    /// **A frame never redraws more tiles than the budget allows**, and every
17838    /// map still gets its turn.
17839    ///
17840    /// The starvation half is what makes this more than an inequality: a
17841    /// schedule that spent the budget on the same maps every frame would satisfy
17842    /// the bound and never draw the rest at all.
17843    #[test]
17844    fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17845        let _blurs = ssao_blur_switch();
17846        let (recorder, device, queue) = open();
17847        let device = device.as_ref();
17848        let (mut renderer, _) = shadow_cache_scene(device, queue);
17849        let sun = DirectionalLight::default();
17850
17851        let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17852        first.release(device);
17853        assert!(
17854            renderer.shadow_lights().base_of(0).is_some(),
17855            "the spot must hold a run, or the budget has only the cascades to bind on"
17856        );
17857
17858        // One tile a frame: the two cascades and the spot's map cannot all fit,
17859        // so something is held on every frame of the run below.
17860        const BUDGET: u32 = 1;
17861        renderer.set_shadow_cadence(Some(shadow::Cadence {
17862            hold: 1,
17863            faces: BUDGET as usize,
17864        }));
17865        const FRAMES: usize = 12;
17866        let mut drew = [0usize; 3];
17867        for step in 1..=FRAMES {
17868            #[expect(
17869                clippy::cast_precision_loss,
17870                reason = "a handful of frames, and the step is what is wanted"
17871            )]
17872            let camera = Camera {
17873                eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17874                ..Camera::default()
17875            };
17876            // The spot drifts too: its map is not fitted to the camera, so a
17877            // moving eye alone leaves it up to date and asking for nothing.
17878            #[expect(
17879                clippy::cast_precision_loss,
17880                reason = "a handful of frames, and the step is what is wanted"
17881            )]
17882            renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17883            let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17884            assert!(
17885                renderer.shadow_faces_redrawn() <= BUDGET,
17886                "frame {step} redrew {} tiles against a budget of {BUDGET}",
17887                renderer.shadow_faces_redrawn()
17888            );
17889            drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17890            drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17891            drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17892            drawn.release(device);
17893        }
17894        for (map, count) in drew.iter().enumerate() {
17895            assert!(
17896                *count > 0,
17897                "map {map} was never redrawn in {FRAMES} frames under a budget of \
17898                 {BUDGET}: {drew:?}"
17899            );
17900        }
17901
17902        renderer.destroy(device);
17903        recorder.assert_valid();
17904    }
17905
17906    /// **A light that jumps further than its own radius resets the cadence**,
17907    /// and one that drifts inside it does not.
17908    ///
17909    /// Topic 45's "a moving light or camera cut resets it",
17910    /// made precise: a map whose centre has moved past the map's own reach is
17911    /// not a frame out of date, it is about somewhere else — so it is redrawn on
17912    /// the frame that notices rather than when its turn comes round. Both arms,
17913    /// because a reset that fired on every move would be the cadence switched
17914    /// off.
17915    #[test]
17916    fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17917        let _blurs = ssao_blur_switch();
17918        let (recorder, device, queue) = open();
17919        let device = device.as_ref();
17920        let (mut renderer, _) = shadow_cache_scene(device, queue);
17921        let sun = DirectionalLight::default();
17922        let camera = Camera::default();
17923        // The coarsest hold there is, so a redraw of the spot's map on the
17924        // frames below is the reset and not its turn.
17925        renderer.set_shadow_cadence(Some(shadow::Cadence {
17926            hold: 8,
17927            faces: shadow::TILES,
17928        }));
17929
17930        let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17931        settle.release(device);
17932        for _ in 0..2 {
17933            settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17934            settle.release(device);
17935        }
17936        assert!(
17937            !renderer.shadow_cadence_reset(),
17938            "the scene has settled, so nothing is about somewhere else"
17939        );
17940
17941        // A drift well inside the light's own radius: out of date, not moved.
17942        renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17943        let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17944        drifted.release(device);
17945        assert!(
17946            !renderer.shadow_cadence_reset(),
17947            "a light that moved a sixteenth of its radius is a map a frame out of date"
17948        );
17949
17950        // And a jump past it. `shadowable_spot`'s radius is what the reach is
17951        // taken from, so this is a light standing where its own map says
17952        // nothing.
17953        renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17954        let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17955        jumped.release(device);
17956        assert!(
17957            renderer.shadow_cadence_reset(),
17958            "a light that jumped five times its own radius must not hold its map"
17959        );
17960        assert!(
17961            renderer.shadow_slot_redrawn(0),
17962            "and the reset is only a reset if the map is actually redrawn"
17963        );
17964
17965        renderer.destroy(device);
17966        recorder.assert_valid();
17967    }
17968
17969    /// **A console knob about *sampling* the atlas does not redraw it.**
17970    ///
17971    /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17972    /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17973    /// receiver it reads — and not one byte of what the depth pass writes into
17974    /// it is any of theirs. Yet the
17975    /// shadow views' blocks are the frame's block spread, and the cache record
17976    /// is those blocks' bytes — so until the views zeroed the row, a person
17977    /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17978    /// and in this crate's own test process the filter tests moving that cell
17979    /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17980    /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17981    /// here is what makes the move below the only one in flight.
17982    #[test]
17983    fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17984        let switch = shadow_filter_switch();
17985        let (recorder, device, queue) = open();
17986        let device = device.as_ref();
17987        let (mut renderer, _) = shadow_cache_scene(device, queue);
17988        let camera = Camera::default();
17989        let sun = DirectionalLight::default();
17990        let mut seen = 0usize;
17991        assert!(
17992            drew_the_atlas(
17993                &recorder,
17994                &mut seen,
17995                device,
17996                &mut renderer,
17997                queue,
17998                &camera,
17999                &sun
18000            ),
18001            "the first frame of all draws the atlas"
18002        );
18003        assert!(
18004            !drew_the_atlas(
18005                &recorder,
18006                &mut seen,
18007                device,
18008                &mut renderer,
18009                queue,
18010                &camera,
18011                &sun
18012            ),
18013            "a still second frame has to hold it, or the move below proves nothing"
18014        );
18015
18016        switch.filter(shadow::Filter::Box);
18017        switch.seam(0.5);
18018        assert!(
18019            !drew_the_atlas(
18020                &recorder,
18021                &mut seen,
18022                device,
18023                &mut renderer,
18024                queue,
18025                &camera,
18026                &sun
18027            ),
18028            "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
18029             sampling knob reached the record of what the maps were drawn from"
18030        );
18031
18032        // The bias pair sits in a different row of the same block, and the
18033        // second row it reaches is `Cascades::params`, which is rebuilt every
18034        // frame — so this is the arm that says the *whole* row is kept out of
18035        // the record rather than the one lane the filter is in.
18036        switch.bias(8.0);
18037        switch.offset(8.0);
18038        assert!(
18039            !drew_the_atlas(
18040                &recorder,
18041                &mut seen,
18042                device,
18043                &mut renderer,
18044                queue,
18045                &camera,
18046                &sun
18047            ),
18048            "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
18049             the bias row reached the record of what the maps were drawn from"
18050        );
18051
18052        renderer.destroy(device);
18053        recorder.assert_valid();
18054    }
18055
18056    /// **Every input the atlas is drawn from redraws it**, one at a time.
18057    ///
18058    /// The half that stops "cached everything, for ever" from passing every
18059    /// assertion above. Each arm moves exactly one thing and asserts the next
18060    /// frame draws again — and then holds still and asserts it stops, so an arm
18061    /// cannot pass by having broken the cache outright.
18062    ///
18063    /// The camera is in here because it is not obvious: a shadow map is drawn
18064    /// from a light, not from the eye. But a cascade is fitted to the camera's
18065    /// own frustum, and every shadow cull selects a DAG's detail at the camera's
18066    /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
18067    /// different light map wherever a DAG is in the light's cull.
18068    /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
18069    /// caster must *not* redraw.
18070    ///
18071    /// `settles` is how many still frames it takes to go quiet again, and it is
18072    /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
18073    /// instance's `previous_transform` back at rest on the frame *after* the
18074    /// move, and that is a write, which is a change this record cannot tell
18075    /// from any other. See `InstancePool::take_written`, which says so.
18076    #[test]
18077    fn each_thing_the_atlas_is_drawn_from_redraws_it() {
18078        let camera = Camera::default();
18079        let sun = DirectionalLight::default();
18080        let moved_camera = Camera {
18081            eye: camera.eye + Vec3::X * 4.0,
18082            ..camera
18083        };
18084        type Change = fn(&mut ForwardRenderer, InstanceHandle);
18085        let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
18086            (
18087                "a caster moved",
18088                |renderer, cube| {
18089                    renderer.set_instance(
18090                        cube,
18091                        &InstanceDesc {
18092                            mesh: DEMO_CUBE,
18093                            material: DEMO_UNTINTED,
18094                            transform: Mat4::from_translation(Vec3::X),
18095                        },
18096                    );
18097                },
18098                &camera,
18099                &sun,
18100                2,
18101            ),
18102            (
18103                "a caster removed",
18104                |renderer, cube| renderer.remove_instance(cube),
18105                &camera,
18106                &sun,
18107                1,
18108            ),
18109            (
18110                "the light moved",
18111                |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
18112                &camera,
18113                &sun,
18114                1,
18115            ),
18116            ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
18117        ];
18118
18119        for (what, change, camera, sun, settles) in arms {
18120            let (recorder, device, queue) = open();
18121            let device = device.as_ref();
18122            let (mut renderer, cube) = shadow_cache_scene(device, queue);
18123            let mut seen = 0usize;
18124            // Two frames, so the atlas is drawn and then held: the arm's own
18125            // assertion is about a frame that would otherwise have cached.
18126            for round in 0..2 {
18127                let drew = drew_the_atlas(
18128                    &recorder,
18129                    &mut seen,
18130                    device,
18131                    &mut renderer,
18132                    queue,
18133                    &Camera::default(),
18134                    &DirectionalLight::default(),
18135                );
18136                assert_eq!(
18137                    drew,
18138                    round == 0,
18139                    "{what}: the still frames before the change did not settle"
18140                );
18141            }
18142
18143            change(&mut renderer, cube);
18144            assert!(
18145                drew_the_atlas(
18146                    &recorder,
18147                    &mut seen,
18148                    device,
18149                    &mut renderer,
18150                    queue,
18151                    camera,
18152                    sun
18153                ),
18154                "{what} and the atlas was not drawn again"
18155            );
18156            // And it goes quiet again in exactly `settles` frames, so the arm
18157            // cannot pass by having broken the cache rather than by having
18158            // invalidated it — and a change that started redrawing for ever
18159            // fails here rather than going unnoticed.
18160            for round in 0..settles {
18161                assert_eq!(
18162                    drew_the_atlas(
18163                        &recorder,
18164                        &mut seen,
18165                        device,
18166                        &mut renderer,
18167                        queue,
18168                        camera,
18169                        sun
18170                    ),
18171                    round + 1 < settles,
18172                    "{what}: the still frames after the change did not settle in {settles}"
18173                );
18174            }
18175
18176            renderer.destroy(device);
18177            recorder.assert_valid();
18178        }
18179    }
18180
18181    /// **A frame skinning an object with no box always redraws the atlas**,
18182    /// and that is a limit written down rather than a gap.
18183    ///
18184    /// A skinned caster's vertices are produced by a compute dispatch into the
18185    /// pool, so there is nothing on the host to compare: the palette a caller
18186    /// hands over is not the geometry, and the geometry is never read back. The
18187    /// honest answer is to redraw, and the dishonest one is a map of a pose the
18188    /// character has left. Without [`SkinnedInstanceDesc::bounds`] nothing says
18189    /// which maps the pose is in, so it is every one — see `shadow_reach`'s
18190    /// skinned tests for an object that has a box.
18191    #[test]
18192    fn a_frame_skinning_an_unboxed_object_never_caches_the_atlas() {
18193        let (recorder, device, queue) = open();
18194        let device = device.as_ref();
18195        let mut fixture = SkinnedFixture::build(device, queue);
18196        // Pinned, on `shadow_cache_scene`'s terms: a console hold would make a
18197        // lap cache for a reason that is not the one asked about.
18198        fixture
18199            .renderer
18200            .set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
18201        fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
18202        fixture
18203            .renderer
18204            .add_skinned_instance(&SkinnedInstanceDesc {
18205                mesh: &fixture.skinned,
18206                material: DEMO_UNTINTED,
18207                transform: Mat4::IDENTITY,
18208                bounds: None,
18209            })
18210            .expect("room for one object");
18211        let imported = swapchain_image_at(device, TEST_EXTENT);
18212        let mut pool = crate::TransientPool::new();
18213
18214        // The same palette and the same plan every lap, so nothing a host-side
18215        // comparison could see has moved.
18216        for lap in 0..3 {
18217            fixture.begin(device);
18218            let mut graph = crate::RenderGraph::new(queue);
18219            let target = graph.import_image("target", imported);
18220            fixture.renderer.add_skinned_passes(
18221                &mut graph,
18222                &pool,
18223                target,
18224                TEST_EXTENT,
18225                &fixture.skinning,
18226            );
18227            let compiled = graph.compile(&pool).expect("a legal frame");
18228            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18229                label: Some("skinned lap"),
18230                queue,
18231            });
18232            compiled
18233                .execute(device, &mut pool, encoder.as_mut(), None)
18234                .expect("the graph executed");
18235            device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
18236            assert!(
18237                !fixture.renderer.shadow_atlas_cached(),
18238                "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
18239            );
18240            assert!(
18241                fixture.renderer.shadow_lights().base_of(0).is_some(),
18242                "the spot must hold a slot for its group to be asked about"
18243            );
18244            assert_eq!(
18245                [
18246                    fixture.renderer.shadow_cascade_redrawn(0),
18247                    fixture.renderer.shadow_cascade_redrawn(1),
18248                    fixture.renderer.shadow_slot_redrawn(0),
18249                ],
18250                [true; 3],
18251                "lap {lap}: an object with no box held a group its pose could be in"
18252            );
18253        }
18254
18255        fixture.destroy(device);
18256        pool.destroy(device);
18257        device.destroy_image_view(imported.view);
18258        device.destroy_image(imported.image);
18259        recorder.assert_valid();
18260    }
18261
18262    /// **Switching the shadows off clears the atlas once, and then holds the
18263    /// clear**, which is the same cache answering a frame that draws nothing.
18264    ///
18265    /// The switched-off frame is not itself a cached frame: the pass has to run
18266    /// to write the reversed-Z clear that makes every comparison come back lit,
18267    /// and the image holds the last drawn maps until it does. What *is* cached
18268    /// is every frame after it, and the record for a switched-off frame is
18269    /// deliberately blind to the camera and the casters, because nothing about
18270    /// them reaches an atlas nothing draws into.
18271    #[test]
18272    fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
18273        let (recorder, device, queue) = open();
18274        let device = device.as_ref();
18275        let (mut renderer, cube) = shadow_cache_scene(device, queue);
18276        let camera = Camera::default();
18277        let sun = DirectionalLight::default();
18278        let mut seen = 0usize;
18279
18280        assert!(
18281            drew_the_atlas(
18282                &recorder,
18283                &mut seen,
18284                device,
18285                &mut renderer,
18286                queue,
18287                &camera,
18288                &sun
18289            ),
18290            "the first frame draws the maps"
18291        );
18292        renderer.set_effect_request(EffectRequest {
18293            programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
18294            ..EffectRequest::default()
18295        });
18296        assert!(
18297            drew_the_atlas(
18298                &recorder,
18299                &mut seen,
18300                device,
18301                &mut renderer,
18302                queue,
18303                &camera,
18304                &sun
18305            ),
18306            "the frame that switched the shadows off has to run the pass that clears the maps \
18307             out of the image"
18308        );
18309        assert!(
18310            !drew_the_atlas(
18311                &recorder,
18312                &mut seen,
18313                device,
18314                &mut renderer,
18315                queue,
18316                &camera,
18317                &sun
18318            ),
18319            "a second switched-off frame cleared an atlas that was already clear"
18320        );
18321        // And nothing about the scene reaches a frame that draws no map: the
18322        // caster moves and the atlas is still the clear it was.
18323        renderer.set_instance(
18324            cube,
18325            &InstanceDesc {
18326                mesh: DEMO_CUBE,
18327                material: DEMO_UNTINTED,
18328                transform: Mat4::from_translation(Vec3::X),
18329            },
18330        );
18331        assert!(
18332            !drew_the_atlas(
18333                &recorder,
18334                &mut seen,
18335                device,
18336                &mut renderer,
18337                queue,
18338                &camera,
18339                &sun
18340            ),
18341            "a caster moved with the shadows off, and the frame cleared the atlas over again"
18342        );
18343
18344        renderer.set_effect_request(EffectRequest::default());
18345        assert!(
18346            drew_the_atlas(
18347                &recorder,
18348                &mut seen,
18349                device,
18350                &mut renderer,
18351                queue,
18352                &camera,
18353                &sun
18354            ),
18355            "switching the shadows back on has to draw the maps the clear replaced"
18356        );
18357
18358        renderer.destroy(device);
18359        recorder.assert_valid();
18360    }
18361
18362    /// **A frame the graph refuses leaves the shadow atlas where it was.**
18363    ///
18364    /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
18365    /// described in full and then thrown away, and
18366    /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
18367    /// thing that writes the pool's ledger — never runs. That is the case a
18368    /// renderer-held `ResourceState`, stepped forward while the passes were
18369    /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
18370    /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
18371    /// object, because with nothing recorded there is nothing to contradict. The
18372    /// guard would be silent on precisely the drift it exists to find, which is
18373    /// why [`imported_state`] reads the ledger instead of a second copy of it.
18374    ///
18375    /// The observable is the first barrier the *next* frame records on the
18376    /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
18377    /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
18378    /// layout the image was never in, which is a layout mismatch on every
18379    /// backend and a discarded image on some.
18380    #[test]
18381    fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
18382        use crcbl_hal::null::Command;
18383
18384        let (recorder, device, queue) = open();
18385        let device = device.as_ref();
18386        let mut renderer =
18387            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18388        let atlas = renderer.shadow_atlas();
18389        let placeholder = renderer.shadow_placeholder;
18390        let mut pool = crate::TransientPool::new();
18391        let imported = swapchain_image(device);
18392
18393        // The refused frame: every pass a real frame declares, and beside them
18394        // one transient nothing reads or writes. `compile` answers
18395        // `UnusedTransient` and the whole description — the shadow atlas's
18396        // import included — is dropped without a command being recorded.
18397        renderer
18398            .begin_frame(
18399                device,
18400                &Camera::default(),
18401                &DirectionalLight::default(),
18402                (64, 48),
18403            )
18404            .expect("write");
18405        {
18406            let mut graph = crate::RenderGraph::new(queue);
18407            let target = graph.import_image("target", imported);
18408            renderer.add_passes(&mut graph, &pool, target, (64, 48));
18409            graph.create_image("orphan", crate::targets::scene_color((64, 48)));
18410            let refused = graph
18411                .compile(&pool)
18412                .expect_err("a transient no pass declares");
18413            assert!(
18414                matches!(refused, crate::GraphError::UnusedTransient { .. }),
18415                "the frame has to be refused for the reason this test is about — a graph that \
18416                 compiled would go on to execute and the ledger would be written after all: \
18417                 {refused:?}"
18418            );
18419        }
18420        assert_eq!(
18421            pool.imported_image_use(atlas),
18422            None,
18423            "nothing executed, so the ledger has nothing to say about the atlas — this is the \
18424             emptiness `InitialClaim::Tracked` cannot check against"
18425        );
18426
18427        // And the frame after it, which does run.
18428        renderer
18429            .begin_frame(
18430                device,
18431                &Camera::default(),
18432                &DirectionalLight::default(),
18433                (64, 48),
18434            )
18435            .expect("write");
18436        let mut graph = crate::RenderGraph::new(queue);
18437        let target = graph.import_image("target", imported);
18438        renderer.add_passes(&mut graph, &pool, target, (64, 48));
18439        let compiled = graph.compile(&pool).expect("a legal frame");
18440        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18441            label: Some("frame after a refusal"),
18442            queue,
18443        });
18444        compiled
18445            .execute(device, &mut pool, encoder.as_mut(), None)
18446            .expect("the graph executed");
18447        let commands = encoder.finish().expect("recording succeeded");
18448
18449        // The first barrier each of the two images gets. Only the refused frame
18450        // ran before this one and it recorded nothing, so these are the frame's
18451        // opening transitions.
18452        let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
18453        for command in recorder.commands() {
18454            let Command::Barrier { images, .. } = command else {
18455                continue;
18456            };
18457            for barrier in images {
18458                if barrier.image != atlas && barrier.image != placeholder {
18459                    continue;
18460                }
18461                if opened.iter().any(|(image, _, _)| *image == barrier.image) {
18462                    continue;
18463                }
18464                opened.push((barrier.image, barrier.from, barrier.to));
18465            }
18466        }
18467        for (image, from, to) in &opened {
18468            assert_eq!(
18469                *from,
18470                ResourceState::Undefined,
18471                "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
18472                 layout to. The declaration is what makes the transition true, so one that has \
18473                 moved on without an executed frame behind it names a source scope and an old \
18474                 layout the image was never in — and the ledger is empty, so nothing refuses it \
18475                 either. Image {image:?}"
18476            );
18477        }
18478        // The loop above is silent on an empty list and on a short one, and a
18479        // wrong declaration shortens it: an image declared in the state it is
18480        // wanted in needs no transition, so it drops out of the stream
18481        // altogether rather than appearing with the wrong source.
18482        assert_eq!(
18483            opened.len(),
18484            2,
18485            "the atlas and its placeholder are both imported every frame and both are wanted in a \
18486             state they are not in, so both have to be barriered: {opened:?}"
18487        );
18488        assert!(
18489            opened
18490                .iter()
18491                .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
18492            "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
18493        );
18494
18495        renderer.destroy(device);
18496        device.destroy_command_buffer(commands);
18497        pool.destroy(device);
18498        device.destroy_image_view(imported.view);
18499        device.destroy_image(imported.image);
18500        recorder.assert_valid();
18501    }
18502
18503    /// **The import audit still refuses an engine site whose declaration is
18504    /// wrong**, now that the shadow atlas's is read out of the same ledger it is
18505    /// checked against.
18506    ///
18507    /// That pair is deliberately circular and this test is what keeps it from
18508    /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
18509    /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
18510    /// ever find them agreeing — their safety comes from there being one answer
18511    /// rather than from the check. Every *other* import in the frame declares a
18512    /// constant, and `ssao-placeholder` is the one this drives a ledger entry
18513    /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
18514    /// declared so on every frame, so a graph that leaves it somewhere else is a
18515    /// declaration the next `compile` has to refuse.
18516    #[test]
18517    fn the_guard_still_catches_an_engine_import_that_lies() {
18518        let (recorder, device, queue) = open();
18519        let device = device.as_ref();
18520        let mut renderer =
18521            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18522        let mut pool = crate::TransientPool::new();
18523        let imported = swapchain_image(device);
18524        let occlusion = renderer.ambient_occlusion_placeholder.image;
18525
18526        // A graph of this test's own, which moves the renderer's occlusion
18527        // placeholder somewhere `add_passes` does not expect. Same image handle,
18528        // so the entry it leaves in the ledger is the one the next `compile`
18529        // reads for `ssao-placeholder`.
18530        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
18531            label: Some("move the placeholder"),
18532            queue,
18533        });
18534        {
18535            let mut graph = crate::RenderGraph::new(queue);
18536            let moved = graph.import_image(
18537                "moved-placeholder",
18538                ImportedImage {
18539                    image: occlusion,
18540                    view: renderer.ambient_occlusion_placeholder.view,
18541                    format: Format::Rgba8Unorm,
18542                    extent: (1, 1),
18543                    initial: ResourceState::ShaderRead,
18544                    claim: InitialClaim::Tracked,
18545                    final_state: ResourceState::TransferSrc,
18546                },
18547            );
18548            graph
18549                .add_copy_pass("read the placeholder")
18550                .use_image(moved, ResourceState::TransferSrc)
18551                .execute(|_| {});
18552            graph
18553                .compile(&pool)
18554                .expect("a legal frame")
18555                .execute(device, &mut pool, encoder.as_mut(), None)
18556                .expect("the graph executed");
18557        }
18558        let commands = encoder.finish().expect("recording succeeded");
18559        assert_eq!(
18560            pool.imported_image_use(occlusion),
18561            Some(ResourceState::TransferSrc),
18562            "the ledger has to have moved for the frame below to have anything to disagree with"
18563        );
18564
18565        renderer
18566            .begin_frame(
18567                device,
18568                &Camera::default(),
18569                &DirectionalLight::default(),
18570                (64, 48),
18571            )
18572            .expect("write");
18573        let mut graph = crate::RenderGraph::new(queue);
18574        let target = graph.import_image("target", imported);
18575        renderer.add_passes(&mut graph, &pool, target, (64, 48));
18576        let refused = graph
18577            .compile(&pool)
18578            .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
18579        let crate::GraphError::ImportStateMismatch {
18580            resource,
18581            declared,
18582            left,
18583        } = &refused
18584        else {
18585            panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
18586        };
18587        assert_eq!(resource, "ssao-placeholder");
18588        assert_eq!(*declared, ResourceState::ShaderRead);
18589        assert_eq!(*left, ResourceState::TransferSrc);
18590
18591        renderer.destroy(device);
18592        device.destroy_command_buffer(commands);
18593        pool.destroy(device);
18594        device.destroy_image_view(imported.view);
18595        device.destroy_image(imported.image);
18596        recorder.assert_valid();
18597    }
18598
18599    /// Compiles one frame and names the passes it turned out to be, in order.
18600    ///
18601    /// Compiled and not executed: what a pass costs is not the question here,
18602    /// only which of them the frame declared. Names rather than a count since
18603    /// the toggles landed — a count says a frame lost two passes and a list says
18604    /// *which* two, which is the difference between "the switch did something"
18605    /// and "the switch did the thing it is for".
18606    fn passes_in_a_frame(
18607        device: &dyn Device,
18608        queue: QueueHandle,
18609        renderer: &mut ForwardRenderer,
18610        imported: ImportedImage,
18611        pool: &crate::TransientPool,
18612        extent: (u32, u32),
18613    ) -> Vec<String> {
18614        renderer
18615            .begin_frame(
18616                device,
18617                &Camera::default(),
18618                &DirectionalLight::default(),
18619                extent,
18620            )
18621            .expect("write");
18622        let mut graph = crate::RenderGraph::new(queue);
18623        let target = graph.import_image("target", imported);
18624        renderer.add_passes(&mut graph, pool, target, extent);
18625        graph
18626            .compile(pool)
18627            .expect("a legal frame")
18628            .passes()
18629            .iter()
18630            .map(|pass| pass.label().to_string())
18631            .collect()
18632    }
18633
18634    /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
18635    /// radius, a direction and a cone well inside the widest one allowed.
18636    /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
18637    /// than one.
18638    ///
18639    /// The spot beside it is one tile and one face, so a scene built only from
18640    /// spots cannot tell a budget counting **faces** from one counting groups —
18641    /// which is what this exists to give a check something to bind on.
18642    fn shadowable_point(x: f32) -> Light {
18643        Light::Point(crate::light::PointLight {
18644            position: Vec3::new(x, 2.0, 0.0),
18645            radius: 8.0,
18646            color: Vec3::ONE,
18647            fill: false,
18648        })
18649    }
18650
18651    fn shadowable_spot(x: f32) -> Light {
18652        Light::Spot(crate::light::SpotLight {
18653            position: Vec3::new(x, 2.0, 0.0),
18654            radius: 8.0,
18655            color: Vec3::ONE,
18656            direction: -Vec3::Y,
18657            inner_angle: 0.3,
18658            outer_angle: 0.6,
18659            fill: false,
18660        })
18661    }
18662
18663    /// The page's anisotropy is the plan's default clamped to the device, and
18664    /// one on a device that was not granted the feature — whatever its limit
18665    /// says.
18666    ///
18667    /// The last arm is the one worth having: `gate_limits_on_features` narrows
18668    /// a declined feature's limit on `crcbl-vk`, but a backend that did not
18669    /// would report sixteen beside an absent feature, and a clamp that read the
18670    /// limit alone would ask for a sampler the device refuses.
18671    #[test]
18672    fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
18673        let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
18674            features,
18675            limits: crcbl_hal::Limits {
18676                max_sampler_anisotropy,
18677                ..crcbl_hal::Limits::desktop()
18678            },
18679        };
18680        let granted = Features::SAMPLER_ANISOTROPY;
18681        assert!(
18682            (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18683                < f32::EPSILON,
18684            "a device above the default gets the default"
18685        );
18686        assert!(
18687            (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18688            "a device below the default gets its own limit"
18689        );
18690        assert!(
18691            (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18692                < f32::EPSILON,
18693            "a device that was not granted the feature gets one, whatever its limit says"
18694        );
18695    }
18696
18697    /// A new anisotropy is a new sampler, and every slot moves onto it at its
18698    /// own frame — the old one living until the last slot has left it.
18699    ///
18700    /// Counted on the null recorder rather than looked at: the sampler count
18701    /// rises by one at the call, holds through every slot's frame but the
18702    /// last, and falls back there, while the live group count never moves at
18703    /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18704    /// destroyed a group a slot in flight still held, and one that never
18705    /// happened each move one of those counts; a second lap of the ring
18706    /// creating any group at all would be a rebuild that did not know it was
18707    /// done.
18708    #[test]
18709    fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18710        let (recorder, device, queue) =
18711            open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18712        let device = device.as_ref();
18713        let mut renderer =
18714            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18715        assert!(
18716            (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18717            "a renderer nobody has called the setter on samples at the default"
18718        );
18719        let samplers = recorder.live_objects(ObjectKind::Sampler);
18720        let groups = recorder.live_objects(ObjectKind::BindGroup);
18721        let groups_created = || {
18722            recorder
18723                .events()
18724                .iter()
18725                .filter(|event| {
18726                    matches!(
18727                        event,
18728                        Event::Created {
18729                            kind: ObjectKind::BindGroup,
18730                            ..
18731                        }
18732                    )
18733                })
18734                .count()
18735        };
18736
18737        renderer
18738            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18739            .expect("the device allows it");
18740        assert_eq!(
18741            recorder.live_objects(ObjectKind::Sampler),
18742            samplers,
18743            "the value in force creates nothing"
18744        );
18745
18746        renderer
18747            .set_anisotropy(device, 4.0)
18748            .expect("the device allows it");
18749        assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18750        assert_eq!(
18751            recorder.live_objects(ObjectKind::Sampler),
18752            samplers + 1,
18753            "the new sampler stands beside the one every slot still names"
18754        );
18755        assert_eq!(
18756            recorder.live_objects(ObjectKind::BindGroup),
18757            groups,
18758            "no group moves until its slot's frame"
18759        );
18760
18761        for round in 0..FRAMES_IN_FLIGHT {
18762            renderer
18763                .begin_frame(
18764                    device,
18765                    &Camera::default(),
18766                    &DirectionalLight::default(),
18767                    (64, 48),
18768                )
18769                .expect("write");
18770            let expected = if round + 1 < FRAMES_IN_FLIGHT {
18771                samplers + 1
18772            } else {
18773                samplers
18774            };
18775            assert_eq!(
18776                recorder.live_objects(ObjectKind::Sampler),
18777                expected,
18778                "round {round}: the replaced sampler lives until the last slot has left it"
18779            );
18780            assert_eq!(
18781                recorder.live_objects(ObjectKind::BindGroup),
18782                groups,
18783                "round {round}: every rebuilt group replaced one"
18784            );
18785        }
18786        let created = groups_created();
18787        for _ in 0..FRAMES_IN_FLIGHT {
18788            renderer
18789                .begin_frame(
18790                    device,
18791                    &Camera::default(),
18792                    &DirectionalLight::default(),
18793                    (64, 48),
18794                )
18795                .expect("write");
18796        }
18797        assert_eq!(
18798            groups_created(),
18799            created,
18800            "a slot already on the sampler in force rebuilds nothing"
18801        );
18802
18803        // The clamp: the device's ceiling above it, off below one, the default
18804        // for a value that is not a number.
18805        let ceiling = device.caps().limits.max_sampler_anisotropy;
18806        renderer
18807            .set_anisotropy(device, ceiling * 4.0)
18808            .expect("clamped to what the device allows");
18809        assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18810        renderer
18811            .set_anisotropy(device, 0.0)
18812            .expect("one is the value that turns it off");
18813        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18814        renderer
18815            .set_anisotropy(device, f32::NAN)
18816            .expect("the default is a sampler the device allows");
18817        assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18818
18819        recorder.assert_valid();
18820        renderer.destroy(device);
18821        assert_eq!(
18822            recorder.live_objects(ObjectKind::Sampler),
18823            0,
18824            "the samplers no slot ever adopted went with the renderer"
18825        );
18826    }
18827
18828    /// A device without the feature samples isotropically whatever is asked:
18829    /// the ceiling is one, so the clamp lands on the value already in force and
18830    /// no sampler is created that `create_sampler` would refuse.
18831    #[test]
18832    fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18833        let (recorder, device, queue) = open();
18834        let device = device.as_ref();
18835        assert!(
18836            !device
18837                .caps()
18838                .features
18839                .contains(Features::SAMPLER_ANISOTROPY),
18840            "the default request does not name the feature"
18841        );
18842        let mut renderer =
18843            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18844        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18845        let samplers = recorder.live_objects(ObjectKind::Sampler);
18846
18847        renderer
18848            .set_anisotropy(device, DEFAULT_ANISOTROPY)
18849            .expect("asks for nothing the device lacks");
18850        assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18851        assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18852        renderer.destroy(device);
18853    }
18854
18855    /// The knob clamps to the range it documents, in both directions and on a
18856    /// value that is neither.
18857    ///
18858    /// **The `NaN` arm is the one worth having.** A slider that divided by a
18859    /// zero, or a settings file that carried a nonsense string, reaches this
18860    /// with a value that fails every comparison it is put through — so a naive
18861    /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18862    /// `as u32` below would produce a zero extent and a device error a long way
18863    /// from here.
18864    #[test]
18865    fn the_render_scale_is_clamped_to_the_range_it_documents() {
18866        let (recorder, device, queue) = open();
18867        let device = device.as_ref();
18868        let mut renderer =
18869            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18870
18871        assert!(
18872            (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18873            "a renderer nobody has called the setter on draws at full scale"
18874        );
18875
18876        renderer.set_render_scale(0.5);
18877        assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18878
18879        // Above one is supersampling, which this filter is the wrong one for.
18880        renderer.set_render_scale(2.0);
18881        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18882
18883        renderer.set_render_scale(0.01);
18884        assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18885
18886        renderer.set_render_scale(f32::NAN);
18887        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18888        renderer.set_render_scale(f32::INFINITY);
18889        assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18890
18891        renderer.destroy(device);
18892        recorder.assert_valid();
18893    }
18894
18895    /// The internal extent is the target rounded, never zero, and is the target
18896    /// itself at full scale.
18897    ///
18898    /// **The floor is not decoration.** A transient image of zero extent is a
18899    /// device error rather than a small frame, and a 4×3 target at the minimum
18900    /// scale is exactly the arithmetic that would produce one.
18901    #[test]
18902    fn the_internal_extent_rounds_and_never_reaches_zero() {
18903        let (recorder, device, queue) = open();
18904        let device = device.as_ref();
18905        let mut renderer =
18906            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18907
18908        assert_eq!(
18909            renderer.internal_extent((1920, 1080)),
18910            (1920, 1080),
18911            "full scale is the absence of the feature, not a resize by one"
18912        );
18913
18914        renderer.set_render_scale(0.5);
18915        assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18916
18917        // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18918        // 756 — both exact — so a target that does *not* divide evenly is what
18919        // shows the rounding. 1281 * 0.7 = 896.7.
18920        renderer.set_render_scale(0.7);
18921        assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18922
18923        renderer.set_render_scale(MIN_RENDER_SCALE);
18924        assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18925        assert_eq!(
18926            renderer.internal_extent((0, 0)),
18927            (1, 1),
18928            "a minimised window is the caller's zero extent, and this may not \
18929             pass it through as one"
18930        );
18931
18932        renderer.destroy(device);
18933        recorder.assert_valid();
18934    }
18935
18936    /// **The upscale is a pass below full scale and is not there above it**, and
18937    /// the frame is otherwise the same list.
18938    ///
18939    /// This is the observable the knob is: everything else about it — the
18940    /// clamps, the rounding — is arithmetic that could be right while the frame
18941    /// went on being drawn at the caller's extent. What says the feature works
18942    /// is that the pass appears, that it appears **last**, and that switching it
18943    /// off leaves the frame that was there before it existed.
18944    #[test]
18945    fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18946        let _blurs = ssao_blur_switch();
18947        let (recorder, device, queue) = open();
18948        let device = device.as_ref();
18949        let mut renderer =
18950            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18951        let imported = swapchain_image_at(device, TEST_EXTENT);
18952        let pool = crate::TransientPool::new();
18953
18954        let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18955        assert!(
18956            !full.contains(&"upscale".to_string()),
18957            "a frame at full scale has no upscale in it: {full:?}"
18958        );
18959
18960        renderer.set_render_scale(0.5);
18961        let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18962        assert_eq!(
18963            scaled.iter().filter(|label| *label == "upscale").count(),
18964            1,
18965            "a scaled frame records exactly one upscale: {scaled:?}"
18966        );
18967        // Last of the passes that draw. The statistics copy is genuinely after
18968        // it and says so — see the comment on `add_copy_pass`'s placement.
18969        let upscale = scaled
18970            .iter()
18971            .position(|label| label == "upscale")
18972            .expect("the assertion above");
18973        let tonemap = scaled
18974            .iter()
18975            .position(|label| label == "tonemap")
18976            .expect("every frame tonemaps");
18977        assert!(
18978            upscale > tonemap,
18979            "the upscale carries what the post chain ended with: {scaled:?}"
18980        );
18981
18982        // **The pyramid gets shorter, and that is the evidence the rest of the
18983        // frame really is smaller.** Everything above this is about the last
18984        // pass; a knob that added an upscale while going on rendering at the
18985        // caller's extent would pass every one of those assertions and save
18986        // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18987        // level count is a number read out of the frame that can only be the
18988        // internal extent's.
18989        let levels = |passes: &[String]| {
18990            passes
18991                .iter()
18992                .filter(|label| label.starts_with("hiz-"))
18993                .count()
18994        };
18995        let internal = renderer.internal_extent(TEST_EXTENT);
18996        assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18997        assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18998        assert!(
18999            levels(&scaled) < levels(&full),
19000            "at this extent the halved frame has to lose a level, or this \
19001             assertion is not looking at anything: {scaled:?}"
19002        );
19003
19004        // And nothing else moved: an upscale is a pass added to the frame, not a
19005        // frame rebuilt around one. The pyramid is the one part that is a
19006        // function of the extent, so it is compared by the count above and
19007        // dropped from the list here.
19008        let without_hiz = |passes: &[String]| -> Vec<String> {
19009            passes
19010                .iter()
19011                .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
19012                .cloned()
19013                .collect()
19014        };
19015        assert_eq!(
19016            without_hiz(&scaled),
19017            without_hiz(&full),
19018            "the scaled frame is the full-scale frame, one pass longer and one \
19019             pyramid shorter"
19020        );
19021
19022        renderer.set_render_scale(1.0);
19023        let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19024        assert_eq!(
19025            back, full,
19026            "the knob goes back, which is what a settings slider does"
19027        );
19028
19029        renderer.destroy(device);
19030        device.destroy_image_view(imported.view);
19031        device.destroy_image(imported.image);
19032        recorder.assert_valid();
19033    }
19034
19035    /// **A skinned-frame overlay receives the display and depth images at the
19036    /// internal extent, before either resolve reconstructs the target.**
19037    ///
19038    /// The callback's own pass attaches the display and depth it received. That
19039    /// makes matching dimensions a graph invariant rather than a comparison of
19040    /// numbers the callback could have been handed without ever using the
19041    /// images; changing either id to a target-sized image makes compilation
19042    /// refuse the mismatched attachments.
19043    #[test]
19044    fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
19045        let (recorder, device, queue) = open();
19046        let device = device.as_ref();
19047        let mut fixture = SkinnedFixture::build(device, queue);
19048        fixture.renderer.set_render_scale(0.5);
19049        fixture.renderer.set_effect_request(EffectRequest {
19050            antialiasing: Some(Antialiasing::Fxaa),
19051            ..EffectRequest::default()
19052        });
19053        fixture.begin(device);
19054        let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
19055
19056        let imported = swapchain_image_at(device, TEST_EXTENT);
19057        let mut pool = crate::TransientPool::new();
19058        {
19059            let mut graph = crate::RenderGraph::new(queue);
19060            let target = graph.import_image("target", imported);
19061            let mut received = None;
19062            fixture.renderer.add_skinned_passes_with_overlay(
19063                &mut graph,
19064                &pool,
19065                target,
19066                TEST_EXTENT,
19067                &fixture.skinning,
19068                |graph, targets| {
19069                    received = Some(targets);
19070                    graph
19071                        .add_render_pass("overlay-probe")
19072                        .color(
19073                            targets.display,
19074                            LoadOp::Load,
19075                            StoreOp::Store,
19076                            crcbl_hal::ClearValue::default(),
19077                        )
19078                        .depth_read(targets.depth)
19079                        .execute(|_| {});
19080                },
19081            );
19082            let received = received.expect("the overlay callback runs while the frame is built");
19083            assert_eq!(
19084                received.internal_extent, internal_extent,
19085                "the overlay receives the extent its display and depth attachments have"
19086            );
19087
19088            let compiled = graph.compile(&pool).expect("the shared attachments match");
19089            let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
19090            let overlay = labels
19091                .iter()
19092                .position(|label| *label == "overlay-probe")
19093                .expect("the callback's pass is part of the frame");
19094            let fxaa = labels
19095                .iter()
19096                .position(|label| *label == "fxaa")
19097                .expect("the requested resolve is part of the frame");
19098            let upscale = labels
19099                .iter()
19100                .position(|label| *label == "upscale")
19101                .expect("the half-scale frame reconstructs its target");
19102            assert!(
19103                overlay < fxaa && overlay < upscale,
19104                "the overlay must write display before its resolve and upscale: {labels:?}"
19105            );
19106        }
19107
19108        fixture.destroy(device);
19109        pool.destroy(device);
19110        device.destroy_image_view(imported.view);
19111        device.destroy_image(imported.image);
19112        recorder.assert_valid();
19113    }
19114
19115    /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
19116    ///
19117    /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
19118    /// halves matter: a bound under the widest frame times part of it and drops
19119    /// the rest, and a bound well over it buys query sets nothing ever writes.
19120    /// A shadowable spot per light slot fills every one of them, which is the
19121    /// most culls a frame can run and so the widest frame there is — it must land
19122    /// exactly on the constant, and the frame with no shadowed light at all must
19123    /// be short of it by exactly the culls those slots would have added.
19124    ///
19125    /// The ground grid is switched on for **both** frames, because the widest
19126    /// frame is the one that has it: it is off by default and not a
19127    /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
19128    /// debug draw layer is on for both frames for the same reason, and it needs
19129    /// a segment appended before each rather than one switch, because
19130    /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
19131    ///
19132    /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
19133    /// [`TEST_EXTENT`], with every effect forced on and the render scale off
19134    /// full.** The bloom chain's length is a function of the extent the frame is
19135    /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
19136    /// records is a *large* one, and a bound checked against a 64×48 frame would
19137    /// sit six passes above what that frame runs and this assertion would have
19138    /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
19139    /// frame buys query sets nothing writes, and only an exact comparison
19140    /// notices.
19141    ///
19142    /// **The render scale is what makes those two requirements compose.** The
19143    /// upscale is a pass only below full scale, and below full scale the chain
19144    /// runs at the *internal* extent — so a frame with both is one whose
19145    /// internal extent is the longest chain's, and whose target is larger than
19146    /// that. Halving a target of 2048×1024 is what arranges it, and the two
19147    /// assertions below check the arrangement rather than trusting it.
19148    ///
19149    /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
19150    #[test]
19151    fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
19152        /// The extent whose bloom chain is the longest [`crate::bloom`] will
19153        /// build: six halvings of 512 leave sixteen by eight, which is still at
19154        /// or above that module's floor. The widest frame is drawn at this,
19155        /// which is why it is the internal one and not the target.
19156        const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
19157        /// Half, so the frame records an upscale and draws at
19158        /// [`WIDEST_INTERNAL`].
19159        const WIDEST_SCALE: f32 = 0.5;
19160        /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
19161        const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
19162
19163        let (recorder, device, queue) = open();
19164        let device = device.as_ref();
19165        // **A scene whose probes ask to be updated**, because the widest frame
19166        // is the one with every pass in it and
19167        // the irradiance probes' two are recorded by a volume
19168        // rather than by an effect bit — the ground grid's argument exactly. A
19169        // renderer built on the demo's empty grid records neither, and the bound
19170        // would then be checked against a frame that could not reach it.
19171        let mut scene = scene::demo();
19172        scene.capacities.probes = 1;
19173        scene.probes = scene::ProbeGrid {
19174            volume: crcbl_shaders::probe::ProbeVolume {
19175                origin: [0.0; 3],
19176                inv_spacing: [1.0; 3],
19177                counts: [1, 1, 1],
19178                levels: 1,
19179                steps: crcbl_shaders::probe::ProbeSteps::default(),
19180            },
19181            probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
19182            update: ProbeUpdate::EveryFrame,
19183        };
19184        let mut renderer =
19185            ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
19186                .expect("built");
19187        // A maximum-width graph must include actual instances to cull.
19188        place_cube(&mut renderer, Mat4::IDENTITY);
19189        renderer
19190            .set_ground_grid(device, Some(GridStyle::default()))
19191            .expect("the null backend builds every pipeline");
19192        // **And the occlusion cull**, whose late prepass, farthest pyramid and
19193        // three late compute passes are the ground grid's kind of pass: off
19194        // unless a caller asks, and in the widest frame when one does.
19195        renderer.set_occlusion_culling(OcclusionCulling {
19196            occlusion: true,
19197            small_feature_pixels: None,
19198        });
19199        // **A body of water**, on the ground grid's terms: content rather than
19200        // an effect bit, so the widest frame is one a caller gave water to, and
19201        // `Water::PASSES` is in the bound for it.
19202        renderer
19203            .set_water(&[crcbl_water::WaterBody {
19204                outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
19205                level: 0.0,
19206                medium: crcbl_water::Medium {
19207                    absorption: [0.4, 0.1, 0.05],
19208                    scattering: [0.01, 0.01, 0.01],
19209                },
19210            }])
19211            .expect("a square meshes");
19212        // **A field of grass**, on the water body's terms exactly: content
19213        // rather than an effect bit, so the widest frame is one a caller gave a
19214        // field to and `Grass::PASSES` is in the bound for it.
19215        renderer
19216            .set_grass(
19217                device,
19218                queue,
19219                Some(
19220                    &crate::grass::GrassField::new(
19221                        [1, 1],
19222                        4.0,
19223                        [-2.0, -2.0],
19224                        50.0,
19225                        crate::grass::Heightfield {
19226                            texels: [4, 4],
19227                            metres_per_texel: 1.0,
19228                            origin: [-2.0, -2.0],
19229                            heights: vec![0.0; 16],
19230                        },
19231                        crate::grass::CoverMap {
19232                            texels: [4, 4],
19233                            metres_per_texel: 1.0,
19234                            origin: [-2.0, -2.0],
19235                            cover: vec![[255, 0]; 16],
19236                        },
19237                        // A shell row and a mesh blade row, so the widest
19238                        // frame records every look's draw the grass pass has.
19239                        [
19240                            crate::grass::BladeLook::Shells,
19241                            crate::grass::BladeLook::Blades,
19242                        ]
19243                        .map(|look| crate::grass::BladeType {
19244                            root_color: [0.05, 0.1, 0.02],
19245                            tip_color: [0.3, 0.5, 0.1],
19246                            height: 0.3,
19247                            half_width: 0.03,
19248                            height_spread: 0.3,
19249                            width_spread: 0.2,
19250                            look,
19251                            style: crate::grass::BladeStyle::PLAIN,
19252                            shape: crate::grass::BladeShape::STRAIGHT,
19253                            clumping: crate::grass::Clumping::NONE,
19254                        })
19255                        .to_vec(),
19256                    )
19257                    .expect("a real field"),
19258                ),
19259            )
19260            .expect("the null backend uploads every map");
19261        renderer.set_render_scale(WIDEST_SCALE);
19262        assert_eq!(
19263            renderer.internal_extent(WIDEST_EXTENT),
19264            WIDEST_INTERNAL,
19265            "the scale has to take the target to the extent whose chain is the \
19266             longest one, or the bound below is checked against a frame that \
19267             could not reach it"
19268        );
19269        // **Both post effects forced on.** Neither is in the default camera
19270        // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
19271        // for one reason and the resolve out for another — and the widest frame
19272        // is the one that has every effect in it, the ground grid's argument
19273        // exactly.
19274        renderer.set_effect_request(EffectRequest {
19275            programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
19276            ..EffectRequest::default()
19277        });
19278        let imported = swapchain_image_at(device, WIDEST_EXTENT);
19279        let mut pool = crate::TransientPool::new();
19280
19281        // The debug draw layer on for both frames below, because it is a pass
19282        // the bound counts and no effect bit switches on — the ground grid's
19283        // argument again. A segment before each, since `begin_frame` clears the
19284        // buffer: the layer is immediate mode.
19285        let switch = debug_draw_switch();
19286        switch.set(true);
19287        // And the occlusion pair's second blur, for exactly that reason: it is a
19288        // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
19289        // frame at the shipping count comes one short of the bound and this test
19290        // would be asserting the bound against a frame that could not reach it.
19291        let blurs = ssao_blur_switch();
19292        blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
19293        // And the comparison seam, which is the occlusion chain's other
19294        // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
19295        // same reason the blur count is: the bound counts a frame that compares,
19296        // so a frame that does not could never reach it.
19297        let split = ssao_split_switch();
19298        split.set(0.5);
19299        renderer
19300            .debug_draw()
19301            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
19302        let bare =
19303            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
19304        assert_eq!(
19305            crate::bloom::mips_for(WIDEST_INTERNAL),
19306            crate::bloom::MAX_MIPS,
19307            "the widest frame has to be one whose chain is the longest one there \
19308             is, or the bound below is checked against a frame that could not \
19309             reach it"
19310        );
19311        assert!(
19312            bare < ForwardRenderer::MAX_PASSES as usize,
19313            "a frame with no shadowed light runs {bare} passes, which is already the \
19314             bound of {} — then the bound does not cover the slots this scene left free",
19315            ForwardRenderer::MAX_PASSES
19316        );
19317
19318        // One spot per slot, spaced so no two of them share an influence — the
19319        // list has to fill every slot or the bound below is checked against a
19320        // frame that could not reach it.
19321        #[expect(
19322            clippy::cast_precision_loss,
19323            reason = "a handful of slots, and the value is only a position"
19324        )]
19325        let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
19326            .map(|slot| shadowable_spot(1.0 + slot as f32))
19327            .collect();
19328        renderer.set_lights(&spots);
19329        renderer
19330            .debug_draw()
19331            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
19332        let widest =
19333            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
19334        assert_eq!(
19335            renderer.shadow_lights.slots().iter().flatten().count(),
19336            shadow::LIGHT_SLOTS,
19337            "the spots must actually hold every slot, or this is the bare frame again \
19338             under another name"
19339        );
19340        assert_eq!(
19341            widest,
19342            ForwardRenderer::MAX_PASSES as usize,
19343            "the widest frame is what the bound is for"
19344        );
19345        assert_eq!(
19346            widest - bare,
19347            DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
19348            "a filled slot costs a cull's passes and nothing else"
19349        );
19350
19351        renderer.destroy(device);
19352        pool.destroy(device);
19353        device.destroy_image_view(imported.view);
19354        device.destroy_image(imported.image);
19355        recorder.assert_valid();
19356    }
19357
19358    /// **A toggle reaches the recorded frame, and takes exactly its own passes
19359    /// with it.**
19360    ///
19361    /// The observable is the compiled pass list, because the thing that could
19362    /// otherwise be true is that the switch is stored and read by nothing: a
19363    /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
19364    /// draws a frame that looks right, reports the right effect set, and has not
19365    /// switched anything off.
19366    ///
19367    /// So each arm compares the whole list rather than its length. Two passes
19368    /// fewer is satisfied by removing the wrong two, and it is satisfied by a
19369    /// frame that lost its tonemap.
19370    ///
19371    /// The shadow arm is the one that cannot be written by name — a cascade's
19372    /// cull passes are labelled exactly as the camera's are — so it is written as
19373    /// its two halves instead: the count moves by a cull's worth per cascade and
19374    /// per filled light slot, and everything from the `shadow` pass onwards is
19375    /// unchanged. The `shadow` pass itself **stays**, because it is what writes
19376    /// the clear that reads as "fully lit".
19377    #[test]
19378    fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
19379        let _blurs = ssao_blur_switch();
19380        let (recorder, device, queue) = open();
19381        let device = device.as_ref();
19382        let mut renderer =
19383            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19384        place_cube(&mut renderer, Mat4::IDENTITY);
19385        // One shadowed light beside the cascades, so the shadow arm below covers
19386        // a light slot's cull as well as a cascade's.
19387        renderer.set_lights(&[shadowable_spot(-1.0)]);
19388        let imported = swapchain_image(device);
19389        let mut pool = crate::TransientPool::new();
19390
19391        // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
19392        // [`frame_switching_off`]'s terms exactly: the default camera stack
19393        // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
19394        // control built on the default alone would have nothing for their arms
19395        // to remove. `force` clears the other side, so an arm whose `off` is one
19396        // of them still resolves to off.
19397        //
19398        // [`frame_switching_off`]: fn@frame_switching_off
19399        let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
19400            renderer.set_effect_request(EffectRequest {
19401                programmatic: EffectOverride::none()
19402                    .force(OUTSIDE_THE_DEFAULT, Some(true))
19403                    .force(off, Some(false)),
19404                ..EffectRequest::default()
19405            });
19406            passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
19407        };
19408
19409        let all_on = without(&mut renderer, RenderEffects::empty());
19410        assert_eq!(
19411            renderer.effects(),
19412            RenderEffects::all(),
19413            "the control frame has to be the every-effect one"
19414        );
19415        assert_eq!(
19416            renderer.shadow_lights.slots().iter().flatten().count(),
19417            1,
19418            "the spot must actually hold a slot, or the shadow arm below is only about cascades"
19419        );
19420
19421        // **None of the three leaves anything behind it**, and for the same
19422        // reason: nothing reads what it would have written. The occlusion pair's
19423        // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
19424        // its `Load` into it — and the reflection pair's and the chain's readers
19425        // both tonemap whatever image they would have read anyway.
19426        //
19427        // The chain's labels are written out rather than built from
19428        // `crate::bloom`'s arithmetic, because a table generated from the code
19429        // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
19430        // downsamples, the one upsample between them, and the composite — and if
19431        // that extent moves this is the assertion that says so.
19432        for (off, gone) in [
19433            (
19434                RenderEffects::AMBIENT_OCCLUSION,
19435                ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
19436            ),
19437            (
19438                RenderEffects::CONTACT_SHADOWS,
19439                // One pass and no blur — `crate::contact_shadows`'s header says
19440                // why the occlusion pair's second pass has no counterpart here.
19441                ["contact-shadows"].as_slice(),
19442            ),
19443            (
19444                RenderEffects::REFLECTIONS,
19445                // **The pyramid goes with the march**, which is the whole of
19446                // what makes it an optimisation rather than a resource: it is
19447                // recorded on the frames that reflect and on no others. Two
19448                // levels at `TEST_EXTENT`, written out on the chain's terms
19449                // above.
19450                ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
19451            ),
19452            (
19453                RenderEffects::BLOOM,
19454                [
19455                    "bloom-down-1",
19456                    "bloom-down-2",
19457                    "bloom-up-1",
19458                    "bloom-composite",
19459                ]
19460                .as_slice(),
19461            ),
19462            (
19463                RenderEffects::AUTO_EXPOSURE,
19464                // All three go together and the tonemap stays: the pass reads
19465                // the measurement only when the block says to, and the block
19466                // says so on exactly the frames these three ran on.
19467                ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
19468            ),
19469        ] {
19470            let labels = without(&mut renderer, off);
19471            assert_eq!(
19472                renderer.effects(),
19473                RenderEffects::all().difference(off),
19474                "{off:?}: the frame must have resolved to the set the request asked for"
19475            );
19476            // **The control frame has to contain what this arm removes**, and
19477            // that is not a restatement of the comparison below: the comparison
19478            // builds `expected` by filtering `gone` out of `all_on`, so an arm
19479            // naming a pass the control never recorded filters nothing, matches,
19480            // and passes whether the effect draws anything or not. Removing the
19481            // resolve pass entirely left this loop green until this assertion
19482            // existed.
19483            for label in gone {
19484                assert!(
19485                    all_on.iter().any(|recorded| recorded == label),
19486                    "{off:?}: the every-effect frame does not record `{label}`, so removing it \
19487                     below proves nothing: {all_on:#?}"
19488                );
19489            }
19490            let expected: Vec<String> = all_on
19491                .iter()
19492                .filter(|label| !gone.contains(&label.as_str()))
19493                .cloned()
19494                .collect();
19495            assert_eq!(
19496                labels, expected,
19497                "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
19498                 every other pass"
19499            );
19500        }
19501
19502        // **The two antialiasing tiers share one resolve slot**, so neither is
19503        // a plain removal and neither belongs in the loop above: switching
19504        // CMAA2 off while FXAA stays on swaps three passes for one rather than
19505        // losing three, and the loop's "gain nothing in their place" comparison
19506        // is exactly what that violates. Three frames say it instead.
19507        let both = all_on.clone();
19508        let cheap = without(&mut renderer, RenderEffects::CMAA2);
19509        let neither = without(
19510            &mut renderer,
19511            RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
19512        );
19513        const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
19514        let resolve_of = |labels: &[String]| -> Vec<String> {
19515            labels
19516                .iter()
19517                .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
19518                .cloned()
19519                .collect()
19520        };
19521        let without_resolve = |labels: &[String]| -> Vec<String> {
19522            labels
19523                .iter()
19524                .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
19525                .cloned()
19526                .collect()
19527        };
19528        assert_eq!(
19529            resolve_of(&both),
19530            CMAA2_PASSES.map(str::to_string).to_vec(),
19531            "with both bits set the higher tier takes the slot and the cheap one \
19532             records nothing"
19533        );
19534        assert_eq!(
19535            resolve_of(&cheap),
19536            vec!["fxaa".to_string()],
19537            "with only the cheap bit set the slot is FXAA's"
19538        );
19539        assert!(
19540            resolve_of(&neither).is_empty(),
19541            "with neither bit set the frame has no resolve at all: {neither:#?}"
19542        );
19543        // And nothing else moved: the tiers swap in one slot rather than
19544        // rebuilding the frame around themselves.
19545        assert_eq!(without_resolve(&both), without_resolve(&cheap));
19546        assert_eq!(without_resolve(&both), without_resolve(&neither));
19547        // The slot is where the ordering argument puts it — directly after the
19548        // last pass that writes the display image, which at this extent is the
19549        // tonemap.
19550        for labels in [&both, &cheap] {
19551            let at = labels
19552                .iter()
19553                .position(|label| label == "tonemap")
19554                .expect("a frame has to reach the swapchain");
19555            assert_eq!(
19556                &labels[at + 1..=at + resolve_of(labels).len()],
19557                resolve_of(labels).as_slice(),
19558                "the resolve must follow the tonemap: {labels:#?}"
19559            );
19560        }
19561
19562        let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
19563        assert_eq!(
19564            renderer.effects(),
19565            RenderEffects::all().difference(RenderEffects::SHADOWS),
19566        );
19567        assert_eq!(
19568            all_on.len() - no_shadows.len(),
19569            DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
19570            "shadows off must drop a cull's passes per cascade and per filled slot"
19571        );
19572        let from_the_atlas = |labels: &[String]| {
19573            let at = labels
19574                .iter()
19575                .position(|label| label == "shadow")
19576                .expect("the atlas pass is recorded whether or not anything draws into it");
19577            labels[at..].to_vec()
19578        };
19579        assert_eq!(
19580            from_the_atlas(&no_shadows),
19581            from_the_atlas(&all_on),
19582            "only the culls go: the atlas pass and everything after it are unchanged"
19583        );
19584
19585        renderer.destroy(device);
19586        pool.destroy(device);
19587        device.destroy_image_view(imported.view);
19588        device.destroy_image(imported.image);
19589        recorder.assert_valid();
19590    }
19591
19592    /// **The contact march is a pass a frame records only when it was asked
19593    /// for, and the mask it writes is what the forward pass then reads.**
19594    ///
19595    /// Two observables, because either alone is satisfied by a mistake the other
19596    /// one catches:
19597    ///
19598    /// * **The compiled pass list.** `contact-shadows` appears between the
19599    ///   prepass whose depth it marches and the forward pass that binds it, and
19600    ///   appears at all only on the frame that asked. The toggle test above
19601    ///   already says a frame loses this pass and nothing else; what is added
19602    ///   here is *where* it sits, which is the half a set comparison cannot see
19603    ///   — a march recorded after the pass that reads it compiles and draws a
19604    ///   mask nothing ever looks at.
19605    /// * **The forward pass's own barriers.** On the frame that marched, one
19606    ///   more image is transitioned into [`ResourceState::ShaderRead`] before
19607    ///   the forward pass opens than on the frame that did not — which is the
19608    ///   mask leaving the colour attachment it was written as. That is what says
19609    ///   the pass's output reaches the shading, rather than being written into a
19610    ///   transient and dropped while the shader goes on reading the 1×1
19611    ///   placeholder. The placeholder is imported in `ShaderRead` already and
19612    ///   needs no transition, so it contributes nothing to this count and the
19613    ///   difference is exactly the mask.
19614    ///
19615    /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
19616    /// while its re-bless is pending — see that constant — so the `on` frame has
19617    /// to force it and the `off` frame is what a view saying nothing draws.
19618    #[test]
19619    fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
19620        let (recorder, device, queue) = open();
19621        let device = device.as_ref();
19622        let mut renderer =
19623            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19624        let imported = swapchain_image(device);
19625        let mut pool = crate::TransientPool::new();
19626
19627        let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
19628            renderer.set_effect_request(EffectRequest {
19629                programmatic: EffectOverride::none()
19630                    .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
19631                ..EffectRequest::default()
19632            });
19633            renderer
19634                .begin_frame(
19635                    device,
19636                    &Camera::default(),
19637                    &DirectionalLight::default(),
19638                    TEST_EXTENT,
19639                )
19640                .expect("write");
19641            let mut graph = crate::RenderGraph::new(queue);
19642            let target = graph.import_image("target", imported);
19643            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19644            let compiled = graph.compile(&pool).expect("a legal frame");
19645            let labels: Vec<String> = compiled
19646                .passes()
19647                .iter()
19648                .map(|pass| pass.label().to_string())
19649                .collect();
19650            let readable = compiled
19651                .passes()
19652                .iter()
19653                .find(|pass| pass.label() == "forward")
19654                .expect("every frame draws its geometry")
19655                .barriers()
19656                .images
19657                .iter()
19658                .filter(|barrier| barrier.to == ResourceState::ShaderRead)
19659                .count();
19660            (labels, readable)
19661        };
19662
19663        let (marched, marched_reads) = frame(&mut renderer, true);
19664        assert!(
19665            renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19666            "the forced frame has to have resolved with the bit set"
19667        );
19668        let (bare, bare_reads) = frame(&mut renderer, false);
19669        assert!(
19670            !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19671            "and the control frame without it"
19672        );
19673
19674        assert!(
19675            !bare.iter().any(|label| label == "contact-shadows"),
19676            "a frame that did not ask must record no march at all: {bare:#?}"
19677        );
19678        let at = |labels: &[String], wanted: &str| {
19679            labels
19680                .iter()
19681                .position(|label| label == wanted)
19682                .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19683        };
19684        let march = at(&marched, "contact-shadows");
19685        assert!(
19686            march > at(&marched, "depth-prepass"),
19687            "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19688        );
19689        assert!(
19690            march < at(&marched, "forward"),
19691            "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19692        );
19693
19694        assert_eq!(
19695            marched_reads,
19696            bare_reads + 1,
19697            "the forward pass has to take one more image into `ShaderRead` on the frame that \
19698             marched — the mask. Equal counts mean the pass wrote a transient the shading \
19699             never reads."
19700        );
19701
19702        renderer.destroy(device);
19703        pool.destroy(device);
19704        device.destroy_image_view(imported.view);
19705        device.destroy_image(imported.image);
19706        recorder.assert_valid();
19707    }
19708
19709    /// **The ground grid is off until a caller asks, and then it is the last
19710    /// pass of the frame — after the tonemap.**
19711    ///
19712    /// Three claims and each is a separate way to get this wrong. Off by default
19713    /// is what keeps every sample and every golden image where they were. *After
19714    /// the tonemap* is the placement decision: added a line earlier it would
19715    /// draw into the HDR scene colour and be tonemapped like geometry, which
19716    /// compiles, draws a grid, and gives it a colour that moves with the
19717    /// exposure. And switching it off again has to remove the pass, not merely
19718    /// stop reporting it.
19719    ///
19720    /// The whole list is compared rather than its length, for the reason the
19721    /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19722    /// one.
19723    #[test]
19724    fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19725        let _blurs = ssao_blur_switch();
19726        let (recorder, device, queue) = open();
19727        let device = device.as_ref();
19728        let mut renderer =
19729            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19730        let imported = swapchain_image(device);
19731        let mut pool = crate::TransientPool::new();
19732
19733        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19734        assert!(
19735            renderer.ground_grid().is_none(),
19736            "a renderer nobody asked has no grid"
19737        );
19738        assert!(
19739            !off.contains(&"grid".to_string()),
19740            "the grid must not be in a frame nobody asked for it in: {off:#?}"
19741        );
19742
19743        renderer
19744            .set_ground_grid(device, Some(GridStyle::default()))
19745            .expect("the null backend builds every pipeline");
19746        assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19747        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19748
19749        let mut expected = off.clone();
19750        // The statistics copy is added after every render pass and stays last —
19751        // see `add_passes`. So the grid goes in front of it, which is directly
19752        // after the tonemap.
19753        let tonemap = expected
19754            .iter()
19755            .position(|label| label == "tonemap")
19756            .expect("a frame has to reach the swapchain");
19757        expected.insert(tonemap + 1, "grid".to_string());
19758        assert_eq!(
19759            on, expected,
19760            "the grid must be the one pass gained, and it must sit after the tonemap"
19761        );
19762
19763        renderer
19764            .set_ground_grid(device, None)
19765            .expect("switching off builds nothing");
19766        assert!(renderer.ground_grid().is_none());
19767        assert_eq!(
19768            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19769            off,
19770            "switching the grid off has to remove its pass, not just stop reporting it"
19771        );
19772
19773        renderer.destroy(device);
19774        pool.destroy(device);
19775        device.destroy_image_view(imported.view);
19776        device.destroy_image(imported.image);
19777        recorder.assert_valid();
19778    }
19779
19780    /// **A second occlusion blur is a pass the frame records, an image it takes
19781    /// out of the pool, and a triangle its counter reports** — or it is a switch
19782    /// that does nothing.
19783    ///
19784    /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19785    /// by driving the pipelines itself, so nothing there would notice that a
19786    /// real frame never records it. The three things below are what a frame has
19787    /// to do differently, and each of them fails silently on its own: a missing
19788    /// pass draws a slightly rougher picture, a missing image is a bind of the
19789    /// wrong one, and a counter short by one is a number nobody reads until it
19790    /// is quoted.
19791    ///
19792    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19793    /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19794    /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19795    /// whichever blur ran into it.
19796    ///
19797    /// **The one thing about that chain no other check can see.** The pass list
19798    /// is identical either way, the graph accepts a written-and-never-read
19799    /// transient without complaint, and every golden is at one blur where the
19800    /// two blur answers coincide — so a frame bound to the wrong image draws
19801    /// something nobody would question, which is exactly what the function's
19802    /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19803    /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19804    /// suites and lantern's golden all stayed green.
19805    ///
19806    /// **Since the halving it is a second silent failure and a louder one.**
19807    /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19808    /// returned working id is not merely a rougher channel — it is an image a
19809    /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19810    /// which its clamp turns into occlusion smeared over the top-left quarter of
19811    /// the frame rather than into an error.
19812    #[test]
19813    fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19814        let (_recorder, device, queue) = open();
19815        let device = device.as_ref();
19816        let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19817        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19818
19819        let one = {
19820            let mut graph = crate::RenderGraph::new(queue);
19821            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19822            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19823            let blurred =
19824                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19825            let upsampled = graph.create_image(
19826                "ssao-upsampled",
19827                crate::targets::ambient_occlusion(TEST_EXTENT),
19828            );
19829            let got = ssao.add_passes(
19830                &mut graph,
19831                0,
19832                TEST_EXTENT,
19833                depth,
19834                crate::ssao::OcclusionImages {
19835                    raw,
19836                    blurred,
19837                    again: None,
19838                    upsampled,
19839                },
19840            );
19841            (got == upsampled, got == blurred || got == raw)
19842        };
19843        assert!(one.0, "one blur finishes in the reconstruction's image");
19844        assert!(
19845            !one.1,
19846            "and never in one of the half-extent images the chain worked in"
19847        );
19848
19849        let two = {
19850            let mut graph = crate::RenderGraph::new(queue);
19851            let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19852            let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19853            let blurred =
19854                graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19855            let again = graph.create_image(
19856                "ssao-blurred-2",
19857                crate::targets::ambient_occlusion(gathered),
19858            );
19859            let upsampled = graph.create_image(
19860                "ssao-upsampled",
19861                crate::targets::ambient_occlusion(TEST_EXTENT),
19862            );
19863            let got = ssao.add_passes(
19864                &mut graph,
19865                0,
19866                TEST_EXTENT,
19867                depth,
19868                crate::ssao::OcclusionImages {
19869                    raw,
19870                    blurred,
19871                    again: Some(again),
19872                    upsampled,
19873                },
19874            );
19875            (got == upsampled, got == again || got == blurred)
19876        };
19877        assert!(
19878            two.0,
19879            "two blurs finish in the reconstruction's image as well, which is the id the forward \
19880             pass binds"
19881        );
19882        assert!(
19883            !two.1,
19884            "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19885             would question"
19886        );
19887    }
19888
19889    /// **The gather runs at half the frame and the reconstruction runs at all
19890    /// of it** — or the halving is a description nobody rendered into.
19891    ///
19892    /// The pass list cannot see this: three passes with the right labels in the
19893    /// right order is exactly what a chain that halved nothing would record. The
19894    /// **render area** is where the halving is observable, and the graph derives
19895    /// it from each pass's colour attachment — so this is the check that the
19896    /// transients [`ForwardRenderer::add_passes`] created are the ones
19897    /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19898    /// the frame-sized one.
19899    ///
19900    /// Neither mistake is an error anywhere else. Working images at the frame's
19901    /// extent are four times the march and a reconstruction reading the corner
19902    /// of its input; a frame-sized image handed to the march and a half-sized
19903    /// one to the forward pass is occlusion smeared over a quarter of the
19904    /// picture by `mesh.slang`'s clamp. Both are pictures.
19905    ///
19906    /// **This test owns `r_ssao_blur_passes` for its duration**, through
19907    /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19908    /// occlusion chain's passes up by name, and a second blur arriving from
19909    /// another thread's switch is a pass this frame did not ask for.
19910    #[test]
19911    fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19912        let _switch = ssao_blur_switch();
19913
19914        let (recorder, device, queue) = open();
19915        let device = device.as_ref();
19916        let mut renderer =
19917            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19918        let imported = swapchain_image(device);
19919        let mut pool = crate::TransientPool::new();
19920        renderer
19921            .begin_frame(
19922                device,
19923                &Camera::default(),
19924                &DirectionalLight::default(),
19925                TEST_EXTENT,
19926            )
19927            .expect("write");
19928        let mut graph = crate::RenderGraph::new(queue);
19929        let target = graph.import_image("target", imported);
19930        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19931        let compiled = graph.compile(&pool).expect("a legal frame");
19932        let area_of = |label: &str| {
19933            let pass = compiled
19934                .passes()
19935                .iter()
19936                .find(|pass| pass.label() == label)
19937                .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19938            let area = pass.render_area();
19939            (area.width, area.height)
19940        };
19941
19942        let gathered = crate::ssao::half_extent(TEST_EXTENT);
19943        assert_ne!(
19944            gathered, TEST_EXTENT,
19945            "the fixture extent has to halve to something else, or every assertion below holds \
19946             of a chain that halved nothing"
19947        );
19948        assert_eq!(
19949            area_of("ssao"),
19950            gathered,
19951            "the march has to run over the gather extent"
19952        );
19953        assert_eq!(
19954            area_of("ssao-blur"),
19955            gathered,
19956            "and so does the blur over what the march wrote"
19957        );
19958        assert_eq!(
19959            area_of("ssao-upsample"),
19960            TEST_EXTENT,
19961            "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19962             runs at the frame's own extent"
19963        );
19964
19965        drop(compiled);
19966        renderer.destroy(device);
19967        pool.destroy(device);
19968        device.destroy_image_view(imported.view);
19969        device.destroy_image(imported.image);
19970        recorder.assert_valid();
19971    }
19972
19973    /// [`ssr_resolution_switch`]'s lock.
19974    static SSR_RESOLUTION_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
19975
19976    /// Takes `r_ssr_resolution` for this thread and puts full resolution back
19977    /// when the guard drops, on [`ssao_blur_switch`]'s terms.
19978    fn ssr_resolution_switch() -> std::sync::MutexGuard<'static, ()> {
19979        SSR_RESOLUTION_SWITCH
19980            .lock()
19981            .unwrap_or_else(std::sync::PoisonError::into_inner)
19982    }
19983
19984    /// **The reflection march runs at its share of the frame and the composite
19985    /// at all of it**, at every share a quality tier writes.
19986    ///
19987    /// On the occlusion chain's terms just above: the pass list is the same at
19988    /// every share, so the **render area** is where the scale is observable. A
19989    /// march image left at the frame's extent would be a march that saved
19990    /// nothing, and a composite at the march's extent would tonemap a truncated
19991    /// frame.
19992    #[test]
19993    fn the_reflection_march_runs_at_its_share_and_composites_at_the_frame() {
19994        let _switch = ssr_resolution_switch();
19995
19996        let (recorder, device, queue) = open();
19997        let device = device.as_ref();
19998        let mut renderer =
19999            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20000        let imported = swapchain_image(device);
20001        let mut pool = crate::TransientPool::new();
20002        for share in [1.0, 0.75, 0.5, 0.25] {
20003            crate::ssr::r_ssr_resolution
20004                .set(&crcbl_console::Value::Float(share))
20005                .expect("every tier's share is in the variable's range");
20006            renderer
20007                .begin_frame(
20008                    device,
20009                    &Camera::default(),
20010                    &DirectionalLight::default(),
20011                    TEST_EXTENT,
20012                )
20013                .expect("write");
20014            let mut graph = crate::RenderGraph::new(queue);
20015            let target = graph.import_image("target", imported);
20016            renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
20017            let compiled = graph.compile(&pool).expect("a legal frame");
20018            let area_of = |label: &str| {
20019                let pass = compiled
20020                    .passes()
20021                    .iter()
20022                    .find(|pass| pass.label() == label)
20023                    .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
20024                let area = pass.render_area();
20025                (area.width, area.height)
20026            };
20027            let marched = crate::ssr::march_extent(TEST_EXTENT, share);
20028            assert_eq!(
20029                area_of("ssr"),
20030                marched,
20031                "at {share} the march has to run over its own share of the frame"
20032            );
20033            assert_eq!(
20034                area_of("ssr-blur"),
20035                TEST_EXTENT,
20036                "at {share} the composite replaces the scene colour, so it runs at the frame's \
20037                 own extent"
20038            );
20039            drop(compiled);
20040        }
20041        crate::ssr::r_ssr_resolution
20042            .set(&crcbl_console::Value::Float(1.0))
20043            .expect("full resolution is in range");
20044
20045        renderer.destroy(device);
20046        pool.destroy(device);
20047        device.destroy_image_view(imported.view);
20048        device.destroy_image(imported.image);
20049        recorder.assert_valid();
20050    }
20051
20052    /// **The comparison seam records a second march, scissored to the columns
20053    /// the first one was kept off.**
20054    ///
20055    /// `crate::split`'s geometry, read off the encoder rather than off the code
20056    /// that drove it: two passes, and two `SetScissor` rectangles that tile the
20057    /// gather extent between them.
20058    ///
20059    /// **What this cannot see is which block each march bound.** The reference
20060    /// backend records a bind group as a handle and a layout, not as the
20061    /// resources behind it, so pointing both marches at one buffer leaves this
20062    /// test green — measured, by doing exactly that. The group inequality below
20063    /// is kept because it is free and would catch the two marches sharing a
20064    /// cache, which is a different fault; what covers the blocks is
20065    /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
20066    /// is not covered at all is the wiring between them. `docs/backlog.md`
20067    /// carries that gap.
20068    ///
20069    /// **The control is the same frame without a seam**, and it is what makes
20070    /// the assertions mean anything: a chain that scissored unconditionally
20071    /// would satisfy every claim below and change every golden in the workspace,
20072    /// so the frame nobody asked to compare has to record one march and set no
20073    /// rectangle at all.
20074    ///
20075    /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
20076    /// is process-wide state and a frame that picked one up from another
20077    /// thread's test is a frame with a pass this one did not ask for.
20078    #[test]
20079    fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
20080        use crcbl_hal::null::Command;
20081
20082        let _blurs = ssao_blur_switch();
20083        let split = ssao_split_switch();
20084        // Third, after the two above: the only other test that takes this one
20085        // takes it alone, so this is the whole order and there is no cycle in
20086        // it. Moved below, because two blocks holding the same scalars are
20087        // equal whatever the seam did.
20088        let slices = ssao_slice_switch();
20089        // The count the seam's far side reads, and one that is not it. Read off
20090        // the variable rather than written down: which end of the range ships
20091        // has changed once already, and a test naming the wrong end would be
20092        // comparing the shipped configuration against itself.
20093        let ships = match crate::ssao::r_ssao_slices.default() {
20094            crcbl_console::Value::Int(count) => *count,
20095            other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
20096        };
20097        let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
20098            i64::from(ssao::SLICE_COUNT_DEFAULT)
20099        } else {
20100            i64::from(ssao::SLICE_COUNT_MAX)
20101        };
20102        assert_ne!(
20103            ships, moved,
20104            "the two slice counts this compares are one count, so the blocks below would differ \
20105             by nothing whatever the seam did"
20106        );
20107        slices.set(ships);
20108
20109        let gathered = crate::ssao::half_extent(TEST_EXTENT);
20110        // One entry per march the frame recorded: the last rectangle that pass
20111        // left the scissor at, and the group it bound.
20112        //
20113        // **The last and not the only one.** The graph opens every pass with a
20114        // scissor over the whole render area, so a march that sets none of its
20115        // own still records one — which is why "did it scissor at all" is not
20116        // the question and "what did it end up cropped to" is.
20117        let marches = |recorder: &Recorder, from: usize| {
20118            let mut inside = false;
20119            let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
20120            let mut rect = None;
20121            let mut group = None;
20122            for command in &recorder.commands()[from..] {
20123                if let Some((_, label)) = command.opens_pass() {
20124                    inside = matches!(label, Some("ssao" | "ssao-shipped"));
20125                    (rect, group) = (None, None);
20126                    continue;
20127                }
20128                if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
20129                    if let (true, Some(rect), Some(group)) = (inside, rect, group) {
20130                        found.push((rect, group));
20131                    }
20132                    inside = false;
20133                    continue;
20134                }
20135                if !inside {
20136                    continue;
20137                }
20138                match command {
20139                    Command::SetScissor(at) => rect = Some(*at),
20140                    Command::BindGroup { group: bound, .. } => group = Some(*bound),
20141                    _ => {}
20142                }
20143            }
20144            found
20145        };
20146
20147        let (recorder, device, queue) = open();
20148        let device = device.as_ref();
20149        let mut renderer =
20150            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20151
20152        split.set(0.0);
20153        let alone = frame_seen_from(
20154            device,
20155            &mut renderer,
20156            queue,
20157            &Camera::default(),
20158            &DirectionalLight::default(),
20159        );
20160        let plain = marches(&recorder, 0);
20161        let after = recorder.commands().len();
20162        let (console, shipped) = renderer
20163            .primary
20164            .ssao
20165            .as_ref()
20166            .expect("the default stack builds the occlusion pair")
20167            .blocks(renderer.frame);
20168        let (uncompared_console, uncompared_shipped) = (
20169            recorder.buffer_bytes(console).expect("the console's block"),
20170            recorder.buffer_bytes(shipped).expect("the seam's block"),
20171        );
20172        alone.release(device);
20173
20174        split.set(0.5);
20175        slices.set(moved);
20176        let frame = frame_seen_from(
20177            device,
20178            &mut renderer,
20179            queue,
20180            &Camera::default(),
20181            &DirectionalLight::default(),
20182        );
20183        let compared = marches(&recorder, after);
20184        let (console, shipped) = renderer
20185            .primary
20186            .ssao
20187            .as_ref()
20188            .expect("the default stack builds the occlusion pair")
20189            .blocks(renderer.frame);
20190        let (compared_console, compared_shipped) = (
20191            recorder.buffer_bytes(console).expect("the console's block"),
20192            recorder.buffer_bytes(shipped).expect("the seam's block"),
20193        );
20194        frame.finish(device, renderer);
20195
20196        assert_eq!(
20197            plain.len(),
20198            1,
20199            "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
20200            plain.len()
20201        );
20202        assert_eq!(
20203            (
20204                plain[0].0.x,
20205                plain[0].0.y,
20206                plain[0].0.width,
20207                plain[0].0.height
20208            ),
20209            (0, 0, gathered.0, gathered.1),
20210            "a frame comparing nothing left its march cropped to something other than the whole \
20211             gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
20212             and every golden in this workspace was blessed on a frame that does not"
20213        );
20214
20215        assert_eq!(
20216            compared.len(),
20217            2,
20218            "a frame comparing two configurations recorded {} march(es)",
20219            compared.len()
20220        );
20221        let (left, right) = (compared[0].0, compared[1].0);
20222        assert_eq!(
20223            (left.x, left.y, right.y),
20224            (0, 0, 0),
20225            "both halves start at the top and the left one at the edge"
20226        );
20227        assert_eq!(
20228            i64::from(right.x),
20229            i64::from(left.width),
20230            "the second march starts where the first one ended, or a column is drawn twice"
20231        );
20232        assert_eq!(
20233            (left.width + right.width, left.height, right.height),
20234            (gathered.0, gathered.1, gathered.1),
20235            "the two rectangles have to cover the gather extent {gathered:?} exactly"
20236        );
20237        assert!(
20238            left.width < gathered.0 && right.width < gathered.0,
20239            "one half covers the whole extent, so the other draws over it and the seam is a \
20240             rectangle that crops nothing"
20241        );
20242        assert_ne!(
20243            compared[0].1, compared[1].1,
20244            "the two marches bound one group, so they cannot be reading two blocks"
20245        );
20246
20247        // How far the reference backend can follow the far side. It will say
20248        // what bytes a buffer holds and it will not say which buffer a group
20249        // names, so the two together are "there are two blocks, and they differ
20250        // by the knob that was moved" — not "the right march read the right
20251        // one". Pointing both marches at one buffer still passes; see this
20252        // module's entry in `docs/backlog.md`.
20253        assert_eq!(
20254            uncompared_console, uncompared_shipped,
20255            "the console sat at its defaults and the two blocks still differ, so the seam's far \
20256             side is not this frame with the shipped scalars — it is another frame"
20257        );
20258        assert_ne!(
20259            compared_console, compared_shipped,
20260            "one slice count was moved off the shipped one and both blocks still hold the same \
20261             bytes, so a comparison shows the same picture twice"
20262        );
20263
20264        recorder.assert_valid();
20265    }
20266
20267    /// Every gather pipeline the frame bound, in the order the marches ran.
20268    ///
20269    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
20270    /// `marches` closure asking the other question of the same stream: that one
20271    /// reads the scissor and the group, and this one reads the pipeline. Only
20272    /// the `ssao` and `ssao-shipped` passes are looked at, because every other
20273    /// pass in the chain binds a pipeline too and a filter over the whole stream
20274    /// would be counting blurs.
20275    ///
20276    /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
20277    fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
20278        use crcbl_hal::null::Command;
20279
20280        let mut inside = false;
20281        let mut found = Vec::new();
20282        for command in &recorder.commands()[from..] {
20283            if let Some((_, label)) = command.opens_pass() {
20284                inside = matches!(label, Some("ssao" | "ssao-shipped"));
20285                continue;
20286            }
20287            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
20288                inside = false;
20289                continue;
20290            }
20291            if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
20292                found.push(*pipeline);
20293            }
20294        }
20295        found
20296    }
20297
20298    /// **`r_ssao_technique` decides which shader the gather runs**, read off the
20299    /// pipeline the `ssao` pass bound.
20300    ///
20301    /// The observable `docs/backlog.md` says the uniform block cannot have. The
20302    /// reference backend records a bind group as a handle and a layout rather
20303    /// than as the resources behind it, so nothing can ask which *block* a march
20304    /// read — but a pipeline is recorded as itself, so which *technique* a march
20305    /// ran is a question this backend answers. `Ssao::gathers` is what names the
20306    /// two, so this is an equality against the pipeline built from each shader
20307    /// rather than an inequality that any two handles would satisfy.
20308    ///
20309    /// **The default arm is the load-bearing half.** A selector that read the
20310    /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
20311    /// change the frame when the console moved; what would go with it is every
20312    /// golden in this workspace, which is blessed on the technique that ships.
20313    ///
20314    /// Holds [`ssao_blur_switch`] for its own reason and
20315    /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
20316    /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
20317    #[test]
20318    fn the_occlusion_technique_picks_the_gathers_pipeline() {
20319        let _blurs = ssao_blur_switch();
20320        let _seam = ssao_split_switch();
20321        let technique = ssao_technique_switch();
20322        // The name to move to, taken out of the variable's own set — see
20323        // `other_technique_name`.
20324        let other = other_technique_name();
20325
20326        let (recorder, device, queue) = open();
20327        let device = device.as_ref();
20328        let mut renderer =
20329            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20330        let (ships, cheap) = renderer
20331            .primary
20332            .ssao
20333            .as_ref()
20334            .expect("the default stack builds the occlusion pair")
20335            .gathers();
20336        assert_ne!(
20337            ships, cheap,
20338            "the renderer built one gather pipeline for both techniques, so nothing below can \
20339             tell them apart"
20340        );
20341
20342        let shipped = frame_seen_from(
20343            device,
20344            &mut renderer,
20345            queue,
20346            &Camera::default(),
20347            &DirectionalLight::default(),
20348        );
20349        let by_default = gathers_bound(&recorder, 0);
20350        let after = recorder.commands().len();
20351        shipped.release(device);
20352
20353        technique.set(other);
20354        let moved_frame = frame_seen_from(
20355            device,
20356            &mut renderer,
20357            queue,
20358            &Camera::default(),
20359            &DirectionalLight::default(),
20360        );
20361        let moved = gathers_bound(&recorder, after);
20362        moved_frame.finish(device, renderer);
20363
20364        assert_eq!(
20365            by_default,
20366            vec![ships],
20367            "a frame nobody has touched the console on gathered through something other than \
20368             `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
20369        );
20370        assert_eq!(
20371            moved,
20372            vec![cheap],
20373            "`r_ssao_technique {other}` left the frame gathering through the pipeline \
20374             it gathered through before, so the selector reaches nothing"
20375        );
20376        recorder.assert_valid();
20377    }
20378
20379    /// **The comparison seam's two marches run two techniques**, which is what
20380    /// the seam was built for.
20381    ///
20382    /// Alcove's second milestone is SSAO and GTAO in
20383    /// one frame, and this is that claim as a pair of pipeline handles: with the
20384    /// technique moved the near side runs the cheap tier and the far side the
20385    /// one that ships, and with it at its default both marches run the same
20386    /// shader and the seam separates nothing.
20387    ///
20388    /// **The control is the frame at the default**, and it is what makes the
20389    /// first half mean anything: a far side that always ran `ssao.slang` would
20390    /// satisfy the inequality below whatever `shipped_technique` did, and a
20391    /// chain that had simply forgotten to pass the far side a pipeline of its
20392    /// own would too.
20393    #[test]
20394    fn the_comparison_seam_marches_through_two_techniques() {
20395        let _blurs = ssao_blur_switch();
20396        let seam = ssao_split_switch();
20397        let technique = ssao_technique_switch();
20398        let other = other_technique_name();
20399
20400        let (recorder, device, queue) = open();
20401        let device = device.as_ref();
20402        let mut renderer =
20403            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20404        let (ships, cheap) = renderer
20405            .primary
20406            .ssao
20407            .as_ref()
20408            .expect("the default stack builds the occlusion pair")
20409            .gathers();
20410
20411        seam.set(0.5);
20412        let compared = frame_seen_from(
20413            device,
20414            &mut renderer,
20415            queue,
20416            &Camera::default(),
20417            &DirectionalLight::default(),
20418        );
20419        let one_technique = gathers_bound(&recorder, 0);
20420        let after = recorder.commands().len();
20421        compared.release(device);
20422
20423        technique.set(other);
20424        let frame = frame_seen_from(
20425            device,
20426            &mut renderer,
20427            queue,
20428            &Camera::default(),
20429            &DirectionalLight::default(),
20430        );
20431        let two_techniques = gathers_bound(&recorder, after);
20432        frame.finish(device, renderer);
20433
20434        assert_eq!(
20435            one_technique,
20436            vec![ships, ships],
20437            "a seam with the technique at its default has to march the shipped gather twice — \
20438             both sides read `shipped`'s configuration, and the picture is one technique either \
20439             side of a line"
20440        );
20441        assert_eq!(
20442            two_techniques,
20443            vec![cheap, ships],
20444            "with `r_ssao_technique {other}` the near side has to run the cheap tier \
20445             and the far side what ships; the far side follows the variable's *default*, exactly \
20446             as the four scalars do"
20447        );
20448        recorder.assert_valid();
20449    }
20450
20451    /// **The frame block carries the console's shadow filter on the near side
20452    /// of the seam, the shipped one on the far side, and the column
20453    /// [`crate::split::halves`] counted.**
20454    ///
20455    /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
20456    /// other seam, and it has to be a claim about *bytes* rather than about
20457    /// pass handles: the occlusion chain compares two pipelines and this
20458    /// compares two arms of one, so there is nothing in the pass list to look
20459    /// at. What a person sees is decided entirely by the row this asserts.
20460    ///
20461    /// **The frame at the default is the control**, and it is what makes the
20462    /// rest mean anything: a block that always wrote the shipped filter into
20463    /// both lanes would satisfy the third case's far side whatever
20464    /// `shipped_filter` did, and one that copied the near lane into the far one
20465    /// would satisfy the first two.
20466    ///
20467    /// The column is compared against `halves`' own answer rather than against
20468    /// a number written here, which is the seam module's whole point: a test
20469    /// that multiplied the fraction by the width itself would be a second
20470    /// opinion about the rounding, and the floor is exactly what that module's
20471    /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
20472    ///
20473    /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
20474    #[test]
20475    fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
20476        let switch = shadow_filter_switch();
20477
20478        let (recorder, device, queue) = open();
20479        let device = device.as_ref();
20480        let mut renderer =
20481            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20482
20483        // The seam is counted over the extent the scene is *drawn* at, which is
20484        // what `SV_Position.x` is denominated in — not the caller's window.
20485        let internal = renderer.internal_extent(TEST_EXTENT);
20486        let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
20487        assert!(
20488            left.width > 0,
20489            "a seam with no columns on one side would make every assertion below hold of a \
20490             frame that compares nothing"
20491        );
20492
20493        let ships = shadow::shipped_filter();
20494        let other = shadow::Filter::Box;
20495        assert_ne!(
20496            other.mode(),
20497            ships.mode(),
20498            "the filter this test moves the console to is the one that ships, so the seam it \
20499             asks for compares one kernel against itself"
20500        );
20501
20502        let draw = |renderer: &mut ForwardRenderer| {
20503            renderer
20504                .begin_frame(
20505                    device,
20506                    &Camera::default(),
20507                    &DirectionalLight::default(),
20508                    TEST_EXTENT,
20509                )
20510                .expect("write");
20511            let bytes = recorder
20512                .buffer_bytes(renderer.primary.uniforms[renderer.frame])
20513                .expect("this frame's uniform block is live");
20514            let at = mesh::FRAME_UNIFORMS_SIZE - 16;
20515            core::array::from_fn(|lane| {
20516                u32::from_le_bytes(
20517                    bytes[at + lane * 4..at + lane * 4 + 4]
20518                        .try_into()
20519                        .expect("four bytes"),
20520                )
20521            })
20522        };
20523
20524        let shipped: [u32; 4] = draw(&mut renderer);
20525        assert_eq!(
20526            shipped,
20527            [ships.mode(), ships.mode(), 0, 0],
20528            "a frame nobody has touched the console on must carry the shipped filter in both \
20529             lanes and no column, which is the row every golden in this workspace was blessed \
20530             under"
20531        );
20532
20533        switch.filter(other);
20534        let unsplit: [u32; 4] = draw(&mut renderer);
20535        assert_eq!(
20536            unsplit,
20537            [other.mode(), other.mode(), 0, 0],
20538            "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
20539            other.label()
20540        );
20541
20542        switch.seam(0.5);
20543        let compared: [u32; 4] = draw(&mut renderer);
20544        assert_eq!(
20545            compared,
20546            [other.mode(), ships.mode(), left.width, 0],
20547            "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
20548             shipped one right of it; the far side follows the variable's *default*, exactly \
20549             as the occlusion chain's does"
20550        );
20551
20552        renderer.destroy(device);
20553        recorder.assert_valid();
20554    }
20555
20556    #[test]
20557    fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
20558        let switch = ssao_blur_switch();
20559
20560        let (recorder, device, queue) = open();
20561        let device = device.as_ref();
20562        let mut renderer =
20563            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20564        let imported = swapchain_image(device);
20565        let pool = crate::TransientPool::new();
20566
20567        let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20568        let counted_once = renderer.counters().instances;
20569        assert!(
20570            once.contains(&"ssao-blur".to_string()),
20571            "the shipping frame has to blur once, or the arm below is about a frame with no \
20572             occlusion in it at all: {once:#?}"
20573        );
20574        assert!(
20575            !once.contains(&"ssao-blur-2".to_string()),
20576            "a frame nobody moved the switch for must record one blur: {once:#?}"
20577        );
20578
20579        switch.set(2);
20580        let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20581        let counted_twice = renderer.counters().instances;
20582        assert!(
20583            twice.contains(&"ssao-blur-2".to_string()),
20584            "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
20585        );
20586        assert_eq!(
20587            twice.len(),
20588            once.len() + 1,
20589            "the second blur is the only pass that may join the frame: {twice:#?}"
20590        );
20591        assert_eq!(
20592            counted_twice,
20593            counted_once + FULLSCREEN_DRAWS,
20594            "the frame recorded a full-screen triangle its counter did not report"
20595        );
20596
20597        // The pass has to write somewhere the forward pass then reads, and the
20598        // graph is what would refuse a frame that bound an image nothing wrote.
20599        // `passes_in_a_frame` compiles rather than executes, so this is the
20600        // check that the third transient was requested at all.
20601        assert!(
20602            twice.iter().any(|pass| pass == "forward"),
20603            "the frame still has to reach its forward pass: {twice:#?}"
20604        );
20605        recorder.assert_valid();
20606    }
20607
20608    /// Every host-written buffer at the end of a whole ring of frames, keyed by
20609    /// the handle written and holding what that handle last held.
20610    ///
20611    /// A whole ring rather than one frame, because the blocks a frame writes are
20612    /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
20613    /// so one frame touches one slot of each and two single-frame batches would
20614    /// be comparing different buffers. A ring writes every slot, so two batches'
20615    /// keys line up and a difference between them is a difference in *bytes*.
20616    ///
20617    /// Only the events this call appends are read, so a caller can take one
20618    /// batch after another off the same recorder.
20619    fn host_buffers_over_a_ring(
20620        recorder: &Recorder,
20621        device: &dyn Device,
20622        renderer: &mut ForwardRenderer,
20623        queue: QueueHandle,
20624    ) -> std::collections::BTreeMap<u64, Vec<u8>> {
20625        let from = recorder.events().len();
20626        for _ in 0..FRAMES_IN_FLIGHT {
20627            frame(device, renderer, queue).release(device);
20628        }
20629        recorder.events()[from..]
20630            .iter()
20631            .filter_map(|event| match event {
20632                Event::BufferWritten { buffer, .. } => Some(*buffer),
20633                _ => None,
20634            })
20635            .map(|buffer| {
20636                let bytes = recorder
20637                    .buffer_bytes(buffer)
20638                    .expect("the stream only names buffers this recorder created");
20639                (buffer.to_bits(), bytes)
20640            })
20641            .collect()
20642    }
20643
20644    /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
20645    /// the ring, and moves nothing else in the frame.**
20646    ///
20647    /// The device test drives the two occlusion pipelines directly and
20648    /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
20649    /// count, so until this the slice count was a variable with a `get_i64` and
20650    /// no evidence that a rendered frame ever carried it: `slice_count` could
20651    /// have returned its default unconditionally and every check in this
20652    /// workspace would still be green.
20653    ///
20654    /// So the observable is the bytes, taken off the null recorder's write log
20655    /// after a whole ring of frames at each setting and compared **by handle**.
20656    /// Two claims come out of that comparison and both are load-bearing:
20657    ///
20658    /// * **Some block moved** — every ring slot, in fact, which is what says the
20659    ///   count reaches the frame at all rather than only the slot the last frame
20660    ///   happened to land in.
20661    /// * **Every block that moved, moved only there.** A frame is a few dozen
20662    ///   host writes and the slice count has business with exactly one word of
20663    ///   one of them; a setting that perturbed a matrix, an instance or a shadow
20664    ///   view would be drawing a different frame for a reason nobody asked for,
20665    ///   and the "at least one differs" half alone would pass on it happily.
20666    ///
20667    /// **Holds every switch whose row is in a block it compares**, in the lock
20668    /// order: the two batches are compared byte for byte over every host
20669    /// buffer the frame writes, so any console row another test moves between
20670    /// them — the blur count, the seam, the technique, the shadow filter, or
20671    /// `crate::ssao`'s own mover of the params block — reads here as "some
20672    /// other write moving". [`ssao_technique_switch`] is the one that
20673    /// serialises against that mover.
20674    #[test]
20675    fn four_slices_reach_the_frame_the_shader_reads() {
20676        let _blurs = ssao_blur_switch();
20677        let _seam = ssao_split_switch();
20678        let switch = ssao_slice_switch();
20679        let _technique = ssao_technique_switch();
20680        let _filter = shadow_filter_switch();
20681
20682        let (recorder, device, queue) = open();
20683        let device = device.as_ref();
20684        let mut renderer =
20685            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20686
20687        // A ring rendered before either batch is taken, because the two below
20688        // are compared by handle and the renderer's opening frame writes blocks
20689        // no later frame writes again: it fills a cold shadow atlas, so the
20690        // shadow views' uniform blocks and the draw-generation blocks of the
20691        // cascades that were drawn are written once and never again while the
20692        // cache holds. Those would be in the first batch and missing from the
20693        // second, and a key that is only in one of them is a difference this
20694        // test cannot say anything about.
20695        for _ in 0..FRAMES_IN_FLIGHT {
20696            frame(device, &mut renderer, queue).release(device);
20697        }
20698        let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20699        switch.set(i64::from(ssao::SLICE_COUNT_MAX));
20700        let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
20701        assert_eq!(
20702            shipping.keys().collect::<Vec<_>>(),
20703            asked.keys().collect::<Vec<_>>(),
20704            "the two batches must write the same buffers, or they are not comparable",
20705        );
20706
20707        // Which bytes moving the count alone is allowed to move, asked of
20708        // `SsaoParams::to_bytes` rather than written here as an offset: the
20709        // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
20710        // of the count would leave a number spelled here pointing at the radius.
20711        let block_of = |slices| {
20712            ssao::SsaoParams {
20713                inv_proj: [0.0; 16],
20714                proj: [0.0; 16],
20715                inv_view: [0.0; 16],
20716                radius: 0.0,
20717                slices,
20718                intensity: ssao::INTENSITY_DEFAULT,
20719                bent_normals: crate::ssao::bent_normals(),
20720            }
20721            .to_bytes()
20722        };
20723        let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
20724        let at_max = block_of(ssao::SLICE_COUNT_MAX);
20725        let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
20726            .filter(|at| at_shipping[*at] != at_max[*at])
20727            .collect();
20728
20729        let mut moved = 0;
20730        for (handle, before) in &shipping {
20731            let after = &asked[handle];
20732            if before == after {
20733                continue;
20734            }
20735            moved += 1;
20736            let mut only_the_count = before.clone();
20737            for at in &count_word {
20738                assert_eq!(
20739                    before[*at], at_shipping[*at],
20740                    "buffer {handle} differs between the batches but did not go in holding the \
20741                     shipping slice count, so this is some other write moving",
20742                );
20743                only_the_count[*at] = at_max[*at];
20744            }
20745            assert_eq!(
20746                after, &only_the_count,
20747                "buffer {handle} moved somewhere other than the slice count's word: the setting \
20748                 is perturbing a block it has no business in",
20749            );
20750        }
20751        assert_eq!(
20752            moved, FRAMES_IN_FLIGHT,
20753            "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
20754             none of them is a console variable no rendered frame reads",
20755        );
20756
20757        renderer.destroy(device);
20758        recorder.assert_valid();
20759    }
20760
20761    /// **The debug draw layer costs a frame nothing until something is appended
20762    /// *and* the console switch is on, and then it is the pass immediately
20763    /// before the tonemap.**
20764    ///
20765    /// Four claims, and each is a separate way to get this wrong.
20766    ///
20767    /// * **Off by default** is what keeps every golden image in the workspace
20768    ///   where it was blessed.
20769    /// * **A segment appended while the switch is off records nothing**, so a
20770    ///   system may append unconditionally.
20771    /// * **The switch on with an empty buffer records nothing either** — this is
20772    ///   the "costs nothing when empty" claim as a check rather than a sentence:
20773    ///   the compiled pass list is compared whole against the frame drawn before
20774    ///   the layer was switched on, so a pass that clears, blits or barriers
20775    ///   anything would show up here.
20776    /// * **Before the tonemap**, which is
20777    ///   `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20778    ///   the ground grid above. Recorded a line later it would draw into the
20779    ///   display-space target and be free of the exposure, which compiles and
20780    ///   draws lines and is the wrong picture.
20781    ///
20782    /// And the fifth, which is what "immediate mode" means: the frame *after*
20783    /// the one that appended records nothing again, because
20784    /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20785    ///
20786    /// The whole list is compared rather than its length, for the ground grid
20787    /// test's reason: one more pass is satisfied by gaining the wrong one.
20788    ///
20789    /// **This test owns `r_debug_draw` for its duration**, through
20790    /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20791    /// between tests, so the two checks here that move it have to take turns.
20792    /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20793    /// none of it.
20794    #[test]
20795    fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20796        let switch = debug_draw_switch();
20797        let _blurs = ssao_blur_switch();
20798
20799        let (recorder, device, queue) = open();
20800        let device = device.as_ref();
20801        let mut renderer =
20802            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20803        let imported = swapchain_image(device);
20804        let mut pool = crate::TransientPool::new();
20805
20806        assert!(
20807            !crate::DebugDraw::enabled(),
20808            "the layer must be off before anything switches it on, or every claim below is \
20809             about a different default"
20810        );
20811        let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20812        assert!(
20813            !off.contains(&"debug-draw".to_string()),
20814            "the layer must not be in a frame nobody switched it on for: {off:#?}"
20815        );
20816
20817        renderer
20818            .debug_draw()
20819            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20820        assert_eq!(
20821            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20822            off,
20823            "a segment appended while the switch is off must record no pass"
20824        );
20825
20826        switch.set(true);
20827        assert_eq!(
20828            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20829            off,
20830            "the switch on with an empty buffer must record the frame the layer's absence would"
20831        );
20832
20833        renderer
20834            .debug_draw()
20835            .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20836        let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20837        let mut expected = off.clone();
20838        let tonemap = expected
20839            .iter()
20840            .position(|label| label == "tonemap")
20841            .expect("a frame has to reach the swapchain");
20842        expected.insert(tonemap, "debug-draw".to_string());
20843        assert_eq!(
20844            on, expected,
20845            "the layer must be the one pass gained, and it must sit before the tonemap"
20846        );
20847
20848        assert_eq!(
20849            passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20850            off,
20851            "the buffer is immediate mode: the frame after the one that appended must record \
20852             nothing"
20853        );
20854
20855        switch.set(false);
20856        renderer.destroy(device);
20857        pool.destroy(device);
20858        device.destroy_image_view(imported.view);
20859        device.destroy_image(imported.image);
20860        recorder.assert_valid();
20861    }
20862
20863    /// **The debug draw layer's own call is counted in the frame's draws.**
20864    ///
20865    /// [`ForwardRenderer::counters`]' draw count is compared against the
20866    /// commands the null backend actually recorded, which is the same instrument
20867    /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20868    /// uses — so a layer whose line list was recorded and not counted fails here
20869    /// rather than quietly making every panel's draw row one short.
20870    ///
20871    /// Both directions are asserted: the frame that drew a segment records one
20872    /// more draw than the frame before it, *and* the counter moved by the same
20873    /// one. A count wired to a constant satisfies neither.
20874    ///
20875    /// It owns `r_debug_draw` for its duration, on
20876    /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20877    /// terms.
20878    #[test]
20879    fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20880        let switch = debug_draw_switch();
20881        let _blurs = ssao_blur_switch();
20882        let _seam = ssao_split_switch();
20883
20884        let (recorder, device, queue) = open();
20885        let device = device.as_ref();
20886        let mut renderer =
20887            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20888
20889        // A different sun in each of the two frames, so both of them redraw the
20890        // shadow atlas: the claim below is that the layer's own call is the one
20891        // draw the second frame gained, and a second frame that cached its
20892        // atlas would have lost the atlas's draws at the same time. See
20893        // [`moving_sun`].
20894        let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20895        let without = renderer.counters().draws;
20896        assert_eq!(
20897            without,
20898            recorded_draws(&recorder) as u64,
20899            "the counter and the frame's recorded draws disagree before the layer draws at all"
20900        );
20901        quiet.release(device);
20902
20903        switch.set(true);
20904        renderer
20905            .debug_draw()
20906            .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20907        let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20908        let with = renderer.counters().draws;
20909        assert_eq!(
20910            with,
20911            without + 1,
20912            "the layer records one draw, so the count has to move by one"
20913        );
20914        assert_eq!(
20915            recorded_draws(&recorder) as u64,
20916            without + with,
20917            "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20918             counted somewhere it was not recorded or recorded somewhere it was not counted"
20919        );
20920
20921        switch.set(false);
20922        drawn.finish(device, renderer);
20923        recorder.assert_valid();
20924    }
20925
20926    /// **The depth-only passes run the depth-only entry point, and the colour
20927    /// pass does not.**
20928    ///
20929    /// Topic 43 §2 split the vertex pool so a pass
20930    /// that wants a clip position and no more could fetch stream 0 alone, and
20931    /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20932    /// is the whole of how that split is spent. **Nothing else in the tree sees
20933    /// it.** `crcbl_shaders::mesh`'s
20934    /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20935    /// compiled artifact and would pass with the entry point built and unused;
20936    /// no golden moves, because the two stages compute the same clip position on
20937    /// purpose; the render graph records a legal frame either way; and the
20938    /// measured price says nothing — pointing this pipeline back at `vertexMain`
20939    /// cost the depth prepass about a tenth more on lavapipe and nothing to
20940    /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20941    /// asserted here, against the reference backend, which records the entry
20942    /// point a pipeline names precisely so this question has an answer.
20943    ///
20944    /// **Both halves, so the check is shown to discriminate.** A lookup that
20945    /// answered `depthVertexMain` for every pipeline would satisfy the first
20946    /// assertion alone, and the colour pipeline is the one that must *not* have
20947    /// moved. The labels are the descriptors' own and are what the two are told
20948    /// apart by, so a renamed pipeline fails at the `expect` rather than
20949    /// silently matching nothing.
20950    #[test]
20951    fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20952        let (recorder, device, queue) = open();
20953        let device = device.as_ref();
20954        // A masked row, so the build compiles the cutout shape the third
20955        // assertion reads — a scene that masks nothing gets none.
20956        let mut scene = scene::demo();
20957        scene.materials[DEMO_UNTINTED].flags = mesh::GpuMaterial::ALPHA_MODE_MASK;
20958        let renderer = ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
20959            .expect("built");
20960        // A mesh stage has no vertex entry point to name, and this whole rung is
20961        // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20962        // preset reports no `Features::MESH_SHADER`, so this is what it built;
20963        // asserted rather than assumed, because a preset that grew the feature
20964        // would leave every assertion below looking for pipelines that do not
20965        // exist.
20966        assert_ne!(
20967            renderer.geometry_path(),
20968            crcbl_hal::GeometryPath::MeshShader,
20969            "this device built a mesh-shader path, whose geometry stage names no vertex \
20970             entry point at all"
20971        );
20972
20973        let pipelines = recorder.graphics_pipeline_vertex_entries();
20974        let entry_of = |label: &str| -> String {
20975            let found: Vec<&str> = pipelines
20976                .iter()
20977                .filter(|(name, _)| name.as_deref() == Some(label))
20978                .map(|(_, entry)| entry.as_str())
20979                .collect();
20980            assert_eq!(
20981                found.len(),
20982                1,
20983                "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20984                found.len()
20985            );
20986            found[0].to_owned()
20987        };
20988
20989        assert_eq!(
20990            entry_of("shadow cascade"),
20991            "depthVertexMain",
20992            "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20993             that reads the position stream alone"
20994        );
20995        assert_eq!(
20996            entry_of("forward mesh"),
20997            "vertexMain",
20998            "the colour pass needs every attribute the depth pass skips, so it is the entry \
20999             point that reads a whole vertex"
21000        );
21001        assert_eq!(
21002            entry_of("shadow cascade masked"),
21003            "vertexMain",
21004            "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
21005             in the attribute region `depthVertexMain` exists not to read"
21006        );
21007
21008        renderer.destroy(device);
21009        recorder.assert_valid();
21010    }
21011
21012    /// **A masked material moves that mesh's depth draws onto the cutout
21013    /// pipeline, and moves nothing else.**
21014    ///
21015    /// The mechanism is which pipeline handle the recorded stream binds and
21016    /// which buckets' indirect calls follow each bind — the wireframe test's
21017    /// observable, for the same reason: a field saying a mode was read would
21018    /// prove the flag was read, not that the frame changed.
21019    ///
21020    /// Four claims, and each rules out a different way of passing wrongly:
21021    ///
21022    /// * a scene with nothing masked binds the vertex-only pipeline and
21023    ///   **never** the cutout one, which is the "an opaque frame costs what it
21024    ///   always did" claim at the level a null device can see it;
21025    /// * a scene with one masked row binds **both** in the depth prepass and
21026    ///   both in the shadow atlas — a per-frame choice binds one or the other,
21027    ///   never the pair;
21028    /// * the calls following each bind are exactly that mode's buckets, in
21029    ///   bucket order, read off the argument offsets the draws name. A split
21030    ///   that bound both pipelines and drew every bucket under each would
21031    ///   satisfy the claim above and double the frame's draws;
21032    /// * and folding the two handles together — then collapsing the runs of
21033    ///   equal binds the fold creates — leaves the two frames' bind streams
21034    ///   **equal**, so the colour pass, the tile clears and the reflective
21035    ///   shadow map are all where they were. A change that had also moved the
21036    ///   colour pass would satisfy the first three and fail this.
21037    ///
21038    /// The two scenes differ in one flags word and nothing else.
21039    #[test]
21040    fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
21041        use crcbl_hal::null::Command;
21042
21043        // The occlusion blur count is a process-global console variable and a
21044        // frame binds one pipeline per blur, so a concurrent test moving it
21045        // would put a bind in one of these frames and not the other — the
21046        // wireframe test's hazard exactly.
21047        let _blurs = ssao_blur_switch();
21048
21049        let masked_scene = {
21050            let mut scene = crate::scene::demo();
21051            scene.materials[DEMO_UNTINTED].flags =
21052                crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
21053            scene
21054        };
21055
21056        /// What one scene's frame reveals: the bucket count and each bucket's
21057        /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
21058        /// pairs the depth prepass and the shadow atlas recorded, and the whole
21059        /// bind stream with the two depth handles folded into one.
21060        struct Recorded {
21061            modes: Vec<u32>,
21062            cutouts: usize,
21063            plains: usize,
21064            prepass: Vec<(bool, u32)>,
21065            atlas: Vec<(bool, u32)>,
21066            folded: Vec<String>,
21067        }
21068
21069        // One frame each, from two renderers rather than two frames from one:
21070        // a bucket table is fixed at build, and two builds keep the frames'
21071        // shadow-atlas state identical — both are a first frame.
21072        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
21073            let (recorder, device, queue) = open();
21074            let device = device.as_ref();
21075            let mut renderer =
21076                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
21077                    .expect("the null backend accepts the demo description");
21078            place_cube(&mut renderer, Mat4::IDENTITY);
21079            let imported = swapchain_image(device);
21080            let mut pool = crate::TransientPool::new();
21081            renderer
21082                .begin_frame(
21083                    device,
21084                    &Camera::default(),
21085                    &DirectionalLight::default(),
21086                    (64, 48),
21087                )
21088                .expect("write");
21089            let mut graph = crate::RenderGraph::new(queue);
21090            let target = graph.import_image("target", imported);
21091            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21092            let compiled = graph.compile(&pool).expect("a legal frame");
21093            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21094                label: Some("alpha mask lap"),
21095                queue,
21096            });
21097            compiled
21098                .execute(device, &mut pool, encoder.as_mut(), None)
21099                .expect("the graph executed");
21100            encoder.finish().expect("recording succeeded");
21101            let plain = renderer.shadow_pipeline.single;
21102            // `None` for the opaque scene, which builds no cutout shape at all
21103            // and so can bind none — the comparisons below read it as such.
21104            let cutout = renderer.depth_masked_pipeline.map(|masked| masked.single);
21105            assert_ne!(
21106                Some(plain),
21107                cutout,
21108                "the two depth pipelines have to be two objects, or nothing below discriminates"
21109            );
21110            // Which bucket a draw is, recovered from the argument offset it
21111            // names — the offsets are the renderer's own accessor, so a call
21112            // pointing at the wrong bucket has no entry here at all.
21113            let bucket_of = |args_offset: u64| -> u32 {
21114                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
21115                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
21116                    .unwrap_or_else(|| {
21117                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
21118                    })
21119            };
21120            // Per depth pass: the pipeline in force at each indirect call and
21121            // the bucket that call drew, in the order they were recorded.
21122            let pass_calls = |label: &str| -> Vec<(bool, u32)> {
21123                let mut current = None;
21124                let mut out = Vec::new();
21125                for command in commands_in_pass(&recorder, label) {
21126                    match command {
21127                        Command::BindGraphicsPipeline(handle) => current = Some(handle),
21128                        Command::DrawIndexedIndirectCount(draw) => {
21129                            let handle = current.expect("a draw follows a pipeline bind");
21130                            assert!(
21131                                handle == plain || Some(handle) == cutout,
21132                                "a depth pass drew under a pipeline that is neither depth one"
21133                            );
21134                            out.push((Some(handle) == cutout, bucket_of(draw.args_offset)));
21135                        }
21136                        _ => {}
21137                    }
21138                }
21139                out
21140            };
21141            let prepass = pass_calls("depth-prepass");
21142            let atlas = pass_calls("shadow");
21143            let binds: Vec<GraphicsPipelineHandle> = recorder
21144                .commands()
21145                .iter()
21146                .filter_map(|command| match command {
21147                    Command::BindGraphicsPipeline(handle) => Some(*handle),
21148                    _ => None,
21149                })
21150                .collect();
21151            let cutouts = binds
21152                .iter()
21153                .filter(|handle| Some(**handle) == cutout)
21154                .count();
21155            let plains = binds.iter().filter(|handle| **handle == plain).count();
21156            let labels = graphics_pipeline_labels(&recorder);
21157            let mut folded: Vec<String> = Vec::with_capacity(binds.len());
21158            for handle in binds {
21159                let handle = if Some(handle) == cutout {
21160                    plain
21161                } else {
21162                    handle
21163                };
21164                let handle = labels[handle.index() as usize].clone();
21165                // The fold turns the masked frame's `plain, cutout` pair into
21166                // `plain, plain`; collapsing a run of equal binds is what makes
21167                // the two streams comparable without hiding a bind of anything
21168                // else, since no pass in either frame binds two *different*
21169                // pipelines that the fold could bring together.
21170                if folded.last() != Some(&handle) {
21171                    folded.push(handle);
21172                }
21173            }
21174            let modes = renderer.bucket_modes.clone();
21175            renderer.destroy(device);
21176            recorder.assert_valid();
21177            Recorded {
21178                modes,
21179                cutouts,
21180                plains,
21181                prepass,
21182                atlas,
21183                folded,
21184            }
21185        };
21186
21187        let opaque = bound(&crate::scene::demo());
21188        let masked = bound(&masked_scene);
21189
21190        assert_eq!(
21191            opaque.cutouts, 0,
21192            "a scene with nothing masked must never bind the cutout pipeline"
21193        );
21194        assert!(
21195            opaque.plains > 0,
21196            "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
21197             above is about a frame with no depth pass in it"
21198        );
21199        assert!(
21200            opaque.modes.iter().all(|mode| *mode == 0),
21201            "and every one of its buckets is opaque: {:?}",
21202            opaque.modes
21203        );
21204        assert_eq!(
21205            opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
21206            0,
21207            "so no opaque draw is recorded under the cutout pipeline"
21208        );
21209
21210        assert!(
21211            masked.cutouts > 0 && masked.plains > 0,
21212            "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
21213             the choice is still per frame",
21214            masked.cutouts,
21215            masked.plains
21216        );
21217        // What each depth pass should have recorded: every opaque bucket under
21218        // the plain pipeline in bucket order, then every masked one under the
21219        // cutout, which is the partition order `depth_partitions` lays down.
21220        let want: Vec<(bool, u32)> = [false, true]
21221            .into_iter()
21222            .flat_map(|cutout| {
21223                masked
21224                    .modes
21225                    .iter()
21226                    .enumerate()
21227                    .filter(move |(_, mode)| {
21228                        (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
21229                    })
21230                    .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
21231            })
21232            .collect();
21233        assert!(
21234            want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
21235            "the masked demo has to hold buckets of both modes, or this compares one partition \
21236             against itself: {:?}",
21237            masked.modes
21238        );
21239        assert_eq!(
21240            masked.prepass, want,
21241            "the depth prepass must record each bucket once, under the pipeline its own mode \
21242             asked for"
21243        );
21244        // The atlas draws every bucket once per occupied view, and the
21245        // partition is **outside** the view loop — one pipeline bind covers
21246        // every view of that mode — so its stream is each partition's bucket
21247        // list repeated once per view.
21248        let views = masked.atlas.len() / want.len();
21249        assert!(
21250            views > 0 && masked.atlas.len() % want.len() == 0,
21251            "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
21252             of views",
21253            masked.atlas.len(),
21254            want.len()
21255        );
21256        let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
21257        for cutout in [false, true] {
21258            let partition: Vec<(bool, u32)> = want
21259                .iter()
21260                .copied()
21261                .filter(|(mode, _)| *mode == cutout)
21262                .collect();
21263            for _ in 0..views {
21264                atlas_want.extend_from_slice(&partition);
21265            }
21266        }
21267        assert_eq!(
21268            masked.atlas, atlas_want,
21269            "and every shadow view draws both partitions, each under its own pipeline"
21270        );
21271
21272        assert_eq!(
21273            masked.folded, opaque.folded,
21274            "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
21275        );
21276    }
21277
21278    /// **A double-sided material moves every pass's draws for its own buckets
21279    /// onto the `CullMode::None` twins, and moves nothing else.**
21280    ///
21281    /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
21282    /// claim for glTF's other mode, and it is wider by construction: an alpha
21283    /// mask is cut inside a fragment stage, so only the two depth-only passes
21284    /// route around it, while a cull mode is a pipeline state and **every** pass
21285    /// that draws the surface has to route around it — the colour pass, both
21286    /// depth passes and the two reflective shadow maps.
21287    ///
21288    /// So this walks the whole recorded stream rather than two named passes:
21289    /// every render pass that recorded an indirect draw is read back as the
21290    /// (side, bucket) pairs it recorded, and each of the four claims below is
21291    /// about all of them at once.
21292    ///
21293    /// * a scene with nothing double-sided binds **no** cull-none twin
21294    ///   anywhere, which is the "an all-single-sided frame costs what it always
21295    ///   did" claim at the level a null device can see it;
21296    /// * a scene with one double-sided row binds a twin in every pass that
21297    ///   draws — a frame that had only routed the colour pass would satisfy
21298    ///   nothing below, and one that had only routed the depth passes would
21299    ///   draw a surface the prepass wrote no depth for;
21300    /// * the calls following each bind are exactly that side's buckets, in
21301    ///   bucket order. A split that bound both pipelines and drew every bucket
21302    ///   under each would satisfy the claim above and double the frame's draws;
21303    /// * and folding each twin onto the pipeline it is a twin of — then
21304    ///   collapsing the runs of equal binds the fold creates — leaves the two
21305    ///   frames' bind streams **equal**, so nothing else in the frame moved.
21306    ///
21307    /// The two scenes differ in one flags word and nothing else.
21308    ///
21309    /// [`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
21310    #[test]
21311    fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
21312        use crcbl_hal::null::Command;
21313
21314        // The occlusion blur count is a process-global console variable and a
21315        // frame binds one pipeline per blur — the masked test's hazard exactly.
21316        let _blurs = ssao_blur_switch();
21317
21318        // **A scene whose probes ask to be updated**, because the reflective
21319        // shadow maps are recorded by a volume rather than by an effect bit —
21320        // and they are two of the five passes this claim is about. The demo's
21321        // empty grid records neither, which would leave the widest half of the
21322        // routing unchecked.
21323        let scene_with_probes = || {
21324            let mut scene = crate::scene::demo();
21325            scene.capacities.probes = 1;
21326            scene.probes = crate::scene::ProbeGrid {
21327                volume: crcbl_shaders::probe::ProbeVolume {
21328                    origin: [0.0; 3],
21329                    inv_spacing: [1.0; 3],
21330                    counts: [1, 1, 1],
21331                    levels: 1,
21332                    steps: crcbl_shaders::probe::ProbeSteps::default(),
21333                },
21334                probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
21335                update: ProbeUpdate::EveryFrame,
21336            };
21337            scene
21338        };
21339        let single_scene = scene_with_probes();
21340        let double_scene = {
21341            let mut scene = scene_with_probes();
21342            scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
21343            scene
21344        };
21345
21346        /// What one scene's frame reveals: each bucket's mode, how often a
21347        /// cull-none twin was bound at all, every drawing pass's (side, bucket)
21348        /// pairs in record order, and the whole bind stream with each twin
21349        /// folded onto the pipeline it twins.
21350        struct Recorded {
21351            modes: Vec<u32>,
21352            twins_bound: usize,
21353            passes: Vec<(String, Vec<(bool, u32)>)>,
21354            folded: Vec<String>,
21355        }
21356
21357        // One frame each, from two renderers rather than two frames from one, on
21358        // the masked test's terms: a bucket table is fixed at build, and two
21359        // builds keep both frames a first frame.
21360        let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
21361            let (recorder, device, queue) = open();
21362            let device = device.as_ref();
21363            let mut renderer =
21364                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
21365                    .expect("the null backend accepts the demo description");
21366            assert!(
21367                !renderer.emit.is_mesh(),
21368                "this preset built a mesh-shader path, whose draws carry no argument offset to \
21369                 recover a bucket from"
21370            );
21371            place_cube(&mut renderer, Mat4::IDENTITY);
21372            // **One shadowed spot**, so the punctual reflective shadow map has a
21373            // face to draw into: the pass is recorded on every frame but its
21374            // view loop is empty without one, and an empty loop records no draw
21375            // for the claim below to be about.
21376            renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
21377                position: Vec3::new(0.0, 2.0, 0.0),
21378                radius: 8.0,
21379                color: Vec3::splat(4.0),
21380                direction: Vec3::NEG_Y,
21381                inner_angle: 0.3,
21382                outer_angle: 0.6,
21383                fill: false,
21384            })]);
21385            let imported = swapchain_image(device);
21386            let mut pool = crate::TransientPool::new();
21387            renderer
21388                .begin_frame(
21389                    device,
21390                    &Camera::default(),
21391                    &DirectionalLight::default(),
21392                    (64, 48),
21393                )
21394                .expect("write");
21395            let mut graph = crate::RenderGraph::new(queue);
21396            let target = graph.import_image("target", imported);
21397            renderer.add_passes(&mut graph, &pool, target, (64, 48));
21398            let compiled = graph.compile(&pool).expect("a legal frame");
21399            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21400                label: Some("double sided lap"),
21401                queue,
21402            });
21403            compiled
21404                .execute(device, &mut pool, encoder.as_mut(), None)
21405                .expect("the graph executed");
21406            encoder.finish().expect("recording succeeded");
21407
21408            // Every twin and the pipeline it twins, so a bind can be reported as
21409            // a side and folded back. Asserted distinct, or nothing here
21410            // discriminates.
21411            // The scene masks nothing, so it built no cutout shape to twin.
21412            assert_eq!(renderer.depth_masked_pipeline, None);
21413            let sided: Vec<SidedPipelines> = [
21414                Some(renderer.mesh_pipeline),
21415                Some(renderer.shadow_pipeline),
21416                renderer.rsm_pipeline,
21417            ]
21418            .into_iter()
21419            .flatten()
21420            .collect();
21421            for pair in &sided {
21422                assert_ne!(
21423                    Some(pair.single),
21424                    pair.double,
21425                    "a pipeline and its cull-none twin have to be two objects"
21426                );
21427            }
21428            let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
21429                sided
21430                    .iter()
21431                    .find(|pair| pair.double == Some(handle))
21432                    .map(|pair| pair.single)
21433            };
21434            let bucket_of = |args_offset: u64| -> u32 {
21435                (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
21436                    .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
21437                    .unwrap_or_else(|| {
21438                        panic!("a draw read its arguments at {args_offset}, which is no bucket's")
21439                    })
21440            };
21441
21442            let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
21443            let labels = graphics_pipeline_labels(&recorder);
21444            let mut folded: Vec<String> = Vec::new();
21445            let mut twins_bound = 0usize;
21446            let mut current: Option<GraphicsPipelineHandle> = None;
21447            let mut label: Option<String> = None;
21448            let mut calls: Vec<(bool, u32)> = Vec::new();
21449            let commands = recorder.commands();
21450            for command in &commands {
21451                match command {
21452                    Command::BeginRenderPass { label: name, .. } => {
21453                        label = name.clone();
21454                        calls = Vec::new();
21455                    }
21456                    Command::EndRenderPass => {
21457                        if !calls.is_empty() {
21458                            passes.push((
21459                                label.clone().expect("every pass here is labelled"),
21460                                std::mem::take(&mut calls),
21461                            ));
21462                        }
21463                    }
21464                    Command::BindGraphicsPipeline(handle) => {
21465                        current = Some(*handle);
21466                        if twin_of(*handle).is_some() {
21467                            twins_bound += 1;
21468                        }
21469                        // The fold turns a `single, double` pair into
21470                        // `single, single`; collapsing a run of equal binds is
21471                        // what makes the two streams comparable without hiding
21472                        // a bind of anything else.
21473                        let folded_handle = twin_of(*handle).unwrap_or(*handle);
21474                        let folded_label = &labels[folded_handle.index() as usize];
21475                        if folded.last() != Some(folded_label) {
21476                            folded.push(folded_label.clone());
21477                        }
21478                    }
21479                    Command::DrawIndexedIndirectCount(draw) => {
21480                        let handle = current.expect("a draw follows a pipeline bind");
21481                        calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
21482                    }
21483                    Command::DrawIndexedIndirect(draw) => {
21484                        let handle = current.expect("a draw follows a pipeline bind");
21485                        calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
21486                    }
21487                    _ => {}
21488                }
21489            }
21490            let modes = renderer.bucket_modes.clone();
21491            renderer.destroy(device);
21492            pool.destroy(device);
21493            device.destroy_image_view(imported.view);
21494            device.destroy_image(imported.image);
21495            recorder.assert_valid();
21496            Recorded {
21497                modes,
21498                twins_bound,
21499                passes,
21500                folded,
21501            }
21502        };
21503
21504        let single = bound(&single_scene);
21505        let double = bound(&double_scene);
21506
21507        assert_eq!(
21508            single.twins_bound, 0,
21509            "a scene with nothing double-sided must never bind a cull-none twin"
21510        );
21511        // Named rather than counted, because the claim is that **every** pass
21512        // that draws the surface routes: a frame that had quietly stopped
21513        // recording one of them would satisfy a count and leave that pass's
21514        // routing unchecked for ever.
21515        let drawing: Vec<&str> = single
21516            .passes
21517            .iter()
21518            .map(|(name, _)| name.as_str())
21519            .collect();
21520        for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
21521            assert!(
21522                drawing.contains(&pass),
21523                "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
21524            );
21525        }
21526        assert!(
21527            double.twins_bound > 0,
21528            "a double-sided scene must bind the cull-none twins"
21529        );
21530        assert_eq!(
21531            double
21532                .passes
21533                .iter()
21534                .map(|(name, _)| name)
21535                .collect::<Vec<_>>(),
21536            single
21537                .passes
21538                .iter()
21539                .map(|(name, _)| name)
21540                .collect::<Vec<_>>(),
21541            "the two frames must draw in the same passes, or they are not comparable"
21542        );
21543
21544        // What each drawing pass should have recorded: every single-sided bucket
21545        // under the plain pipeline in bucket order, then every double-sided one
21546        // under the twin — the partition order `sided_partitions` lays down —
21547        // repeated once per view for a pass that draws several.
21548        let want: Vec<(bool, u32)> = [false, true]
21549            .into_iter()
21550            .flat_map(|twin| {
21551                double
21552                    .modes
21553                    .iter()
21554                    .enumerate()
21555                    .filter(move |(_, mode)| {
21556                        (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
21557                    })
21558                    .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
21559            })
21560            .collect();
21561        assert!(
21562            want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
21563            "the double-sided demo has to hold buckets of both sides, or this compares one \
21564             partition against itself: {:?}",
21565            double.modes
21566        );
21567        for (name, calls) in &double.passes {
21568            let views = calls.len() / want.len();
21569            assert!(
21570                views > 0 && calls.len() % want.len() == 0,
21571                "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
21572                 views",
21573                calls.len(),
21574                want.len()
21575            );
21576            // The partition is **outside** any view loop — one pipeline bind
21577            // covers every view of that side — so the stream is each partition's
21578            // bucket list repeated once per view.
21579            let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
21580            for twin in [false, true] {
21581                let partition: Vec<(bool, u32)> = want
21582                    .iter()
21583                    .copied()
21584                    .filter(|(side, _)| *side == twin)
21585                    .collect();
21586                for _ in 0..views {
21587                    expected.extend_from_slice(&partition);
21588                }
21589            }
21590            assert_eq!(
21591                *calls, expected,
21592                "`{name}` must record each bucket once per view, under the pipeline its own \
21593                 side asked for"
21594            );
21595        }
21596
21597        assert_eq!(
21598            double.folded, single.folded,
21599            "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
21600             pipeline it twins"
21601        );
21602    }
21603
21604    /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
21605    ///
21606    /// The mechanism, at the level a null device can observe it: which pipeline
21607    /// handle each pass of the recorded stream binds. A field on the renderer
21608    /// would say only that a flag moved — this says the *frame* moved, and says
21609    /// which part of it did.
21610    ///
21611    /// Four claims, and each rules out a different way of passing wrongly:
21612    ///
21613    /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
21614    ///   one does not exist;
21615    /// * switching on **removes** the filled pipeline from the stream — a second
21616    ///   pipeline that was built and never bound would still leave it there;
21617    /// * every other pipeline the frame binds is unchanged, so the depth prepass
21618    ///   and the shadow cascades are still filling triangles;
21619    /// * and switching off puts the stream back exactly, so the view is a toggle
21620    ///   rather than a one-way door.
21621    #[test]
21622    fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
21623        use crcbl_hal::null::Command;
21624
21625        // The pipelines a frame binds include one per occlusion blur, and the
21626        // blur count is a process-global console variable — so a concurrent
21627        // test holding `r_ssao_blur_passes` at two adds a bind to one of the
21628        // frames below and not to the others. It reddened this assertion on
21629        // 2026-08-31 under a workspace `cargo test`.
21630        let _blurs = ssao_blur_switch();
21631        let (recorder, device, queue) =
21632            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21633        let device = device.as_ref();
21634        assert!(
21635            ForwardRenderer::supports_wireframe(device),
21636            "this test needs the line fill mode, and asked the device for it",
21637        );
21638        let mut renderer =
21639            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21640        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21641        let imported = swapchain_image(device);
21642        let mut pool = crate::TransientPool::new();
21643
21644        // The pipelines one frame binds, in record order. Cumulative recorder,
21645        // so each call takes the tail its own frame added.
21646        let mut seen = 0usize;
21647        // A different sun each lap, so the shadow atlas is redrawn in every one
21648        // of them: the comparison below is "which pipelines did this frame
21649        // bind", and a lap that cached its atlas would bind the depth-only
21650        // pipeline one fewer time for a reason that has nothing to do with the
21651        // wireframe. See [`moving_sun`].
21652        let mut lap = 0u32;
21653        let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
21654            lap += 1;
21655            renderer
21656                .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
21657                .expect("write");
21658            let mut graph = crate::RenderGraph::new(queue);
21659            let target = graph.import_image("target", imported);
21660            renderer.add_passes(&mut graph, pool, target, (64, 48));
21661            let compiled = graph.compile(pool).expect("a legal frame");
21662            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21663                label: Some("wireframe lap"),
21664                queue,
21665            });
21666            compiled
21667                .execute(device, pool, encoder.as_mut(), None)
21668                .expect("the graph executed");
21669            encoder.finish().expect("recording succeeded");
21670            let commands = recorder.commands();
21671            let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
21672                .iter()
21673                .filter_map(|command| match command {
21674                    Command::BindGraphicsPipeline(handle) => Some(*handle),
21675                    _ => None,
21676                })
21677                .collect();
21678            seen = commands.len();
21679            bound
21680        };
21681
21682        let filled = renderer.mesh_pipeline.single;
21683        let off = pipelines_in_a_frame(&mut renderer, &mut pool);
21684        assert!(
21685            off.contains(&filled),
21686            "a frame nobody asked has to bind the filled pipeline: {off:?}",
21687        );
21688        assert!(!renderer.wireframe());
21689        assert!(
21690            renderer.wireframe_pipeline.is_none(),
21691            "the wireframe pipeline must not be built until it is asked for",
21692        );
21693
21694        renderer
21695            .set_wireframe(device, true)
21696            .expect("a device with the line fill mode builds it");
21697        assert!(renderer.wireframe());
21698        let lines = renderer
21699            .wireframe_pipeline
21700            .expect("switching on is what builds it")
21701            .single;
21702        let on = pipelines_in_a_frame(&mut renderer, &mut pool);
21703        assert!(
21704            !on.contains(&filled),
21705            "the colour pass still bound the filled pipeline: {on:?}",
21706        );
21707        assert_eq!(
21708            on.iter().filter(|handle| **handle == lines).count(),
21709            1,
21710            "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
21711        );
21712        let substituted: Vec<GraphicsPipelineHandle> = on
21713            .iter()
21714            .map(|handle| if *handle == lines { filled } else { *handle })
21715            .collect();
21716        assert_eq!(
21717            substituted, off,
21718            "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
21719             {off:?}",
21720        );
21721
21722        renderer
21723            .set_wireframe(device, false)
21724            .expect("switching off builds nothing");
21725        assert!(!renderer.wireframe());
21726        assert_eq!(
21727            pipelines_in_a_frame(&mut renderer, &mut pool),
21728            off,
21729            "switching the view off has to put the filled pipeline back, not just stop reporting \
21730             it",
21731        );
21732
21733        renderer.destroy(device);
21734        pool.destroy(device);
21735        device.destroy_image_view(imported.view);
21736        device.destroy_image(imported.image);
21737        recorder.assert_valid();
21738    }
21739
21740    /// **The colour pass tests against the prepass's depth instead of clearing
21741    /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
21742    /// does the opposite, because lines do not reproduce a filled prepass.
21743    ///
21744    /// Both halves have to hold together or the frame is wrong in one of two
21745    /// ways, so both are asserted here. The attachment alone read-only while the
21746    /// pipeline still wrote would be a pipeline writing to a read-only
21747    /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
21748    /// this pass had just *cleared* would reject every fragment and draw a black
21749    /// frame. Neither shows up as an error — the first is a validation message
21750    /// on one backend and undefined behaviour on the rest, the second is a
21751    /// picture — which is why the observable is read off the compiled graph and
21752    /// off the pipeline state rather than off a screenshot.
21753    #[test]
21754    fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
21755        let (recorder, device, queue) =
21756            open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
21757        let device = device.as_ref();
21758        let mut renderer =
21759            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21760        place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
21761        let imported = swapchain_image(device);
21762        let mut pool = crate::TransientPool::new();
21763
21764        // Each pass's depth attachment, off the graph's own dump: the label it
21765        // was declared under, and the `load`/`store`/`write` triple the backend
21766        // is handed. A pass with no depth attachment contributes nothing, which
21767        // is what makes the lookup below a search rather than an index.
21768        let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
21769            renderer
21770                .begin_frame(
21771                    device,
21772                    &Camera::default(),
21773                    &DirectionalLight::default(),
21774                    (64, 48),
21775                )
21776                .expect("write");
21777            let mut graph = crate::RenderGraph::new(queue);
21778            let target = graph.import_image("target", imported);
21779            renderer.add_passes(&mut graph, pool, target, (64, 48));
21780            let dump = graph.compile(pool).expect("a legal frame").dump();
21781            let mut pass = String::new();
21782            let mut found = None;
21783            for line in dump.lines() {
21784                if let Some(rest) = line.split(" pass \"").nth(1) {
21785                    pass = rest.trim_end_matches('"').to_string();
21786                    if let Some((name, _)) = pass.split_once('"') {
21787                        pass = name.to_string();
21788                    }
21789                }
21790                if pass == label
21791                    && let Some(at) = line.find("depth load=")
21792                {
21793                    // Without the slot note the dump appends: which physical
21794                    // image the transient landed on is aliasing's business, not
21795                    // this assertion's.
21796                    let role = &line[at..];
21797                    let role = role.split_once(" [").map_or(role, |(head, _)| head);
21798                    found = Some(role.trim().to_string());
21799                }
21800            }
21801            found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21802        };
21803
21804        assert_eq!(
21805            depth_of(&mut renderer, &mut pool, "depth-prepass"),
21806            "depth load=Clear store=Store write=yes",
21807            "the prepass is what puts the depth there, so it clears, writes and keeps it",
21808        );
21809        assert_eq!(
21810            depth_of(&mut renderer, &mut pool, "forward"),
21811            "depth load=Load store=Store write=no",
21812            "and the colour pass reads it: a clear here would throw away the prepass and \
21813             pay for the overdraw again, and a write would be a second pass writing the \
21814             same values",
21815        );
21816        assert_eq!(
21817            MeshModules::color_depth_stencil(PolygonMode::Fill),
21818            Some(DepthStencilState {
21819                format: Format::D32Float,
21820                depth_write: false,
21821                depth_compare: CompareOp::GreaterOrEqual,
21822                stencil: None,
21823                bias: DepthBias::default(),
21824            }),
21825            "and the pipeline agrees with the attachment: equality against the prepass, \
21826             reachable only through the `OrEqual` under reversed-Z",
21827        );
21828
21829        renderer
21830            .set_wireframe(device, true)
21831            .expect("this device was asked for the line fill mode");
21832        assert_eq!(
21833            depth_of(&mut renderer, &mut pool, "forward"),
21834            "depth load=Clear store=Store write=yes",
21835            "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21836             along the edge rather than across the face, so testing it against a filled \
21837             prepass rejects most of the wireframe — and *loading* that depth under the \
21838             writing default's `Greater` would reject all of it",
21839        );
21840        assert_eq!(
21841            MeshModules::color_depth_stencil(PolygonMode::Line),
21842            MeshModules::depth_stencil(),
21843            "which is the writing default, the same state the depth-only twin uses",
21844        );
21845
21846        renderer.destroy(device);
21847        pool.destroy(device);
21848        device.destroy_image_view(imported.view);
21849        device.destroy_image(imported.image);
21850        recorder.assert_valid();
21851    }
21852
21853    /// **A device with no line fill mode is refused, not quietly filled.**
21854    ///
21855    /// The failure this rules out is the silent one: a caller who binds a key to
21856    /// this, presses it, and gets the solid frame back with nothing anywhere
21857    /// saying why — which on a model whose silhouette hides its interior is
21858    /// indistinguishable from a wireframe that worked. WebGPU is the real device
21859    /// this happens on; `open`'s null device stands in for it, because
21860    /// [`DeviceDesc::for_adapter`] asks for
21861    /// [`Features::GPU_DRIVEN`] and nothing else.
21862    #[test]
21863    fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21864        let (recorder, device, queue) = open();
21865        let device = device.as_ref();
21866        assert!(
21867            !ForwardRenderer::supports_wireframe(device),
21868            "this device was not asked for the line fill mode, so it must not report it",
21869        );
21870        let mut renderer =
21871            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21872
21873        let refused = renderer
21874            .set_wireframe(device, true)
21875            .expect_err("a device without the feature has to say so");
21876        assert!(
21877            matches!(
21878                refused,
21879                HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21880            ),
21881            "the refusal has to name the feature to go and look up, and is {refused:?}",
21882        );
21883        assert!(
21884            !renderer.wireframe(),
21885            "a refused request must leave the view off rather than half on",
21886        );
21887        assert!(
21888            renderer.wireframe_pipeline.is_none(),
21889            "nothing may be left behind by a refusal",
21890        );
21891        // And switching *off* is still fine on such a device: it builds nothing.
21892        renderer
21893            .set_wireframe(device, false)
21894            .expect("switching off asks the device for nothing");
21895
21896        renderer.destroy(device);
21897        recorder.assert_valid();
21898    }
21899
21900    /// The grid's own full-screen triangle is counted as submitted, and only
21901    /// while it is on.
21902    ///
21903    /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21904    /// row, and every full-screen pass in the frame contributes one — so a grid
21905    /// that drew and was not counted makes that row disagree with the frame by
21906    /// exactly one triangle, silently.
21907    #[test]
21908    fn the_grids_triangle_is_counted_only_while_it_is_on() {
21909        let _blurs = ssao_blur_switch();
21910        let (recorder, device, queue) = open();
21911        let device = device.as_ref();
21912        let mut renderer =
21913            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21914        let imported = swapchain_image(device);
21915        let mut pool = crate::TransientPool::new();
21916
21917        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21918        let off = renderer.counters();
21919
21920        renderer
21921            .set_ground_grid(device, Some(GridStyle::default()))
21922            .expect("the null backend builds every pipeline");
21923        passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21924        let on = renderer.counters();
21925
21926        assert_eq!(
21927            on.draws - off.draws,
21928            FULLSCREEN_DRAWS,
21929            "the grid records exactly one draw"
21930        );
21931        assert_eq!(
21932            on.instances - off.instances,
21933            FULLSCREEN_DRAWS,
21934            "and exactly one submitted instance"
21935        );
21936
21937        renderer.destroy(device);
21938        pool.destroy(device);
21939        device.destroy_image_view(imported.view);
21940        device.destroy_image(imported.image);
21941        recorder.assert_valid();
21942    }
21943
21944    /// One frame on a device of its own, under an override switching `off`.
21945    ///
21946    /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21947    /// device's whole life: asking "did the atlas pass draw" of a recorder that
21948    /// has seen two frames answers about both of them, and the arm that matters
21949    /// most here is the one whose answer must be zero.
21950    ///
21951    /// Returns what the frame reported and what its atlas pass actually drew.
21952    fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21953        use crcbl_hal::null::Command;
21954
21955        let recorder = Recorder::new();
21956        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21957        let adapter = instance.adapters().remove(0);
21958        let opened = instance
21959            .create_device(&DeviceDesc::for_adapter(adapter.id))
21960            .expect("the null backend always opens");
21961        let device = opened.as_ref();
21962        let queue = opened.queue(QueueKind::Graphics).expect("always present");
21963        let mut renderer =
21964            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21965        // A shadowed light beside the cascades, so the atlas pass has draws to
21966        // lose rather than being empty either way.
21967        renderer.set_lights(&[shadowable_spot(-1.0)]);
21968        // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21969        // camera stack leaves both of them out — see
21970        // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21971        // default alone would be measuring three effects and calling it five,
21972        // and their arms below would be switching off something already off.
21973        // `force` clears the other side, so an arm whose `off` is one of them
21974        // still resolves to off.
21975        renderer.set_effect_request(EffectRequest {
21976            programmatic: EffectOverride::none()
21977                .force(OUTSIDE_THE_DEFAULT, Some(true))
21978                .force(off, Some(false)),
21979            ..EffectRequest::default()
21980        });
21981
21982        let recorded = frame(device, &mut renderer, queue);
21983        assert_eq!(
21984            renderer.effects(),
21985            RenderEffects::all().difference(off),
21986            "the frame must have resolved to the set the request asked for"
21987        );
21988        let counters = renderer.counters();
21989        let instances = renderer.instances.len() as u64;
21990        let atlas_draws = commands_in_pass(&recorder, "shadow")
21991            .into_iter()
21992            .filter(|command| {
21993                matches!(
21994                    command,
21995                    Command::DrawIndexedIndirect(_)
21996                        | Command::DrawIndexedIndirectCount(_)
21997                        | Command::DrawMeshTasksIndirect(_)
21998                )
21999            })
22000            .count();
22001        assert_eq!(
22002            counters.draws,
22003            recorded_draws(&recorder) as u64,
22004            "the counter and the frame's own recorded stream must agree, whatever is switched off"
22005        );
22006        recorded.finish(device, renderer);
22007        recorder.assert_valid();
22008        (counters, instances, atlas_draws)
22009    }
22010
22011    /// **A switched-off effect is work the frame did not record**, and a frame
22012    /// that still executes with the placeholder bound in place of what it lost.
22013    ///
22014    /// The other half of the pass-list test above, and the half a pass list
22015    /// cannot make: the `shadow` pass is still *there* with shadows off, so the
22016    /// question is whether it drew. That answer comes off the recorded command
22017    /// stream, which is a different instrument from `recorded_draws` — the number
22018    /// under test.
22019    ///
22020    /// Executed rather than only compiled, because the occlusion switch changes
22021    /// which image the forward pass has bound. A frame that declared a read of a
22022    /// transient it never created, or bound a view the graph never realised,
22023    /// fails here and compiles perfectly.
22024    #[test]
22025    fn a_switched_off_effect_is_work_the_frame_did_not_record() {
22026        let _blurs = ssao_blur_switch();
22027        let _seam = ssao_split_switch();
22028        let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
22029        assert!(
22030            atlas_draws > 0,
22031            "with shadows on the atlas pass has to draw something, or turning it off means \
22032             nothing"
22033        );
22034        assert_eq!(
22035            control.instances,
22036            instances
22037                + fullscreen_passes(
22038                    RenderEffects::all(),
22039                    TEST_EXTENT,
22040                    false,
22041                    crate::ssao::blur_passes(),
22042                ) * FULLSCREEN_DRAWS,
22043            "the control frame submits one triangle per full-screen pass"
22044        );
22045
22046        // Each pair is one full-screen triangle per pass, and the atlas is
22047        // untouched by either.
22048        for (off, fewer) in [
22049            (
22050                RenderEffects::AMBIENT_OCCLUSION,
22051                u64::from(Ssao::passes(crate::ssao::blur_passes())),
22052            ),
22053            // The contact march's one pass, and a constant rather than a
22054            // function of anything: it has no blur behind it and no chain.
22055            (
22056                RenderEffects::CONTACT_SHADOWS,
22057                u64::from(ContactShadows::PASSES),
22058            ),
22059            // The march's two passes and the reductions that feed them, which
22060            // is what makes this arm's number a function of the extent the way
22061            // the chain's below is.
22062            (
22063                RenderEffects::REFLECTIONS,
22064                u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
22065            ),
22066            // Not a constant, unlike the occlusion pair above: the chain's
22067            // length is a function of the extent, and this is what it is at
22068            // `TEST_EXTENT`.
22069            (
22070                RenderEffects::BLOOM,
22071                u64::from(Bloom::passes_for(TEST_EXTENT)),
22072            ),
22073        ] {
22074            let (counters, instances, atlas) = frame_switching_off(off);
22075            assert_eq!(
22076                counters.draws,
22077                control.draws - fewer * FULLSCREEN_DRAWS,
22078                "{off:?}: the frame must record one draw fewer per pass it did not add"
22079            );
22080            assert_eq!(
22081                counters.instances,
22082                instances
22083                    + fullscreen_passes(
22084                        RenderEffects::all().difference(off),
22085                        TEST_EXTENT,
22086                        false,
22087                        crate::ssao::blur_passes(),
22088                    ) * FULLSCREEN_DRAWS,
22089                "{off:?}: and must not report as submitted a triangle it never submitted"
22090            );
22091            assert_eq!(
22092                atlas, atlas_draws,
22093                "{off:?}: a screen-space effect must not touch the shadow atlas"
22094            );
22095        }
22096
22097        // Shadows: the atlas pass survives and draws nothing at all, which is
22098        // the mechanism — a cleared reversed-Z atlas reads as fully lit.
22099        let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
22100        assert_eq!(
22101            atlas, 0,
22102            "with shadows off the atlas pass must record its clear and no draw"
22103        );
22104        assert_eq!(
22105            counters.draws,
22106            control.draws - atlas_draws as u64,
22107            "and the frame must record exactly the atlas pass's draws fewer"
22108        );
22109    }
22110
22111    /// **Every pass the frame records gets a row in the report, except the ones
22112    /// that open no scope.**
22113    ///
22114    /// The observable the bound exists for: the samples' hand-picked capacity
22115    /// timed the first eight passes of a fourteen-pass frame and reported eight
22116    /// rows, which reads exactly like a frame that has eight passes. Sized from
22117    /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
22118    /// pass the graph compiled, in order — so a bound one short of the frame
22119    /// makes this list short too.
22120    ///
22121    /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
22122    /// expectation rather than expected to be missing by accident. The seam
22123    /// takes a timestamp only where a pass opens and closes and a copy opens
22124    /// nothing, so `PassTimers` gives it no query pair and no row — a row
22125    /// reading 0.000 ms would be a measurement nobody made.
22126    #[test]
22127    fn every_pass_of_the_frame_gets_a_timing_row() {
22128        let _blurs = ssao_blur_switch();
22129        // And the comparison seam, so the frame this checks carries the
22130        // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
22131        // for a *per-technique* cost, and what makes that true is this test's
22132        // own claim — every pass that opens a scope gets a row — applied to a
22133        // frame that compares. See `crate::ssao`'s `r_ssao_split`.
22134        let split = ssao_split_switch();
22135        split.set(0.5);
22136        let recorder = Recorder::new();
22137        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
22138        let adapter = instance.adapters().remove(0);
22139        // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
22140        // may lack it — so a device that wants timers has to ask for it, and
22141        // `open` above, which uses `DeviceDesc::for_adapter`, does not.
22142        let opened = instance
22143            .create_device(&DeviceDesc {
22144                label: Some("timed frame"),
22145                adapter: adapter.id,
22146                required_features: Features::GPU_DRIVEN,
22147                optional_features: Features::TIMESTAMP_QUERY,
22148                compatible_surface: None,
22149            })
22150            .expect("the null backend always opens");
22151        let queue = opened.queue(QueueKind::Graphics).expect("always present");
22152        let device = opened.as_ref();
22153        let mut renderer =
22154            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
22155        renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
22156        let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
22157            .expect("the tier A null adapter has timestamp queries");
22158        let imported = swapchain_image(device);
22159        let mut pool = crate::TransientPool::new();
22160        let mut recorded = Vec::new();
22161        let mut compiled_labels = Vec::new();
22162
22163        // The ring is one slot longer than the frames in flight and resolves a
22164        // slot only when it comes round again, so the first frame's report is
22165        // that many frames behind it — see the [`timing`](crate::timing) docs.
22166        for _ in 0..FRAMES_IN_FLIGHT + 2 {
22167            renderer
22168                .begin_frame(
22169                    device,
22170                    &Camera::default(),
22171                    &DirectionalLight::default(),
22172                    (64, 48),
22173                )
22174                .expect("write");
22175            let mut graph = crate::RenderGraph::new(queue);
22176            let target = graph.import_image("target", imported);
22177            renderer.add_passes(&mut graph, &pool, target, (64, 48));
22178            let compiled = graph.compile(&pool).expect("a legal frame");
22179            if compiled_labels.is_empty() {
22180                compiled_labels = compiled
22181                    .passes()
22182                    .iter()
22183                    .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
22184                    .map(|pass| pass.label().to_string())
22185                    .collect();
22186            }
22187            let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22188                label: Some("timed frame"),
22189                queue,
22190            });
22191            compiled
22192                .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
22193                .expect("the graph executed");
22194            recorded.push(encoder.finish().expect("recording succeeded"));
22195        }
22196
22197        let reported: Vec<&str> = timers
22198            .latest()
22199            .passes
22200            .iter()
22201            .map(|timing| timing.label.as_str())
22202            .collect();
22203        // Anti-vacuity for the seam held above: a frame that did not compare
22204        // would satisfy the equality below and say nothing about a
22205        // per-technique cost, because there would be one technique in it.
22206        for label in ["ssao", "ssao-shipped"] {
22207            assert!(
22208                compiled_labels.iter().any(|pass| pass == label),
22209                "the frame compiled no `{label}` pass, so the seam did not reach it and this \
22210                 test says nothing about a comparison having a cost per side. Its passes: \
22211                 {compiled_labels:?}"
22212            );
22213        }
22214        assert_eq!(
22215            reported,
22216            compiled_labels,
22217            "the report must name every pass the frame compiled that opens a scope, in order \
22218             — {} of {} timed with a capacity of {}",
22219            reported.len(),
22220            compiled_labels.len(),
22221            timers.capacity()
22222        );
22223
22224        timers.destroy(device);
22225        renderer.destroy(device);
22226        for commands in recorded {
22227            device.destroy_command_buffer(commands);
22228        }
22229        pool.destroy(device);
22230        device.destroy_image_view(imported.view);
22231        device.destroy_image(imported.image);
22232        recorder.assert_valid();
22233    }
22234
22235    /// One mesh-table entry, decoded from the bytes that reached the device.
22236    fn mesh_entry(
22237        recorder: &Recorder,
22238        renderer: &ForwardRenderer,
22239        id: u32,
22240    ) -> crcbl_shaders::mesh::GpuMesh {
22241        let table = recorder
22242            .buffer_bytes(renderer.pool.table_buffer())
22243            .expect("the table is live");
22244        let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
22245        crcbl_shaders::mesh::GpuMesh::from_bytes(
22246            table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
22247                .try_into()
22248                .expect("one whole entry"),
22249        )
22250    }
22251
22252    // --- skinning: the seam a caller draws a skinned mesh through -----------
22253
22254    /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
22255    /// [`Skinning`] built against that renderer's own vertex pool.
22256    struct SkinnedFixture {
22257        renderer: ForwardRenderer,
22258        skinning: Skinning,
22259        skinned: SkinnedMesh,
22260        palette: Vec<Mat4>,
22261        bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
22262    }
22263
22264    impl SkinnedFixture {
22265        fn build(device: &dyn Device, queue: QueueHandle) -> Self {
22266            Self::build_with_scene(device, queue, &scene::demo())
22267        }
22268
22269        /// [`SkinnedFixture::build`] over `scene` in place of
22270        /// [`scene::demo`], which must hold [`DEMO_CUBE`].
22271        fn build_with_scene(
22272            device: &dyn Device,
22273            queue: QueueHandle,
22274            scene: &SceneDesc<'_>,
22275        ) -> Self {
22276            let mut renderer =
22277                ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
22278                    .expect("the null backend accepts every descriptor");
22279            let skinned = renderer
22280                .reserve_skinned(DEMO_CUBE)
22281                .expect("a default pool has room for two halves of a cube");
22282            let skinning = Skinning::new(
22283                device,
22284                &crate::skinning::SkinningDesc {
22285                    label: Some("skinned fixture"),
22286                    frames: FRAMES_IN_FLIGHT,
22287                    ranges: 1,
22288                    joints: 1,
22289                    bindings: skinned.vertex_count(),
22290                    // The renderer's own pool, which is the whole of what makes
22291                    // the dispatch's output reachable by its draws.
22292                    vertices: renderer.vertex_buffer(),
22293                    attribute_base: renderer.attribute_base(),
22294                },
22295            )
22296            .expect("the null backend accepts every descriptor");
22297            let bindings = vec![
22298                crcbl_shaders::skinning::SkinBinding {
22299                    joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
22300                    weights: [1.0, 0.0, 0.0, 0.0],
22301                };
22302                skinned.vertex_count() as usize
22303            ];
22304            Self {
22305                renderer,
22306                skinning,
22307                skinned,
22308                palette: vec![Mat4::IDENTITY],
22309                bindings,
22310            }
22311        }
22312
22313        /// One skinned frame's `begin_skinned_frame`, with this fixture's single
22314        /// range.
22315        fn begin(&mut self, device: &dyn Device) {
22316            let range = self.skinned.skin_range(&self.palette, &self.bindings);
22317            self.renderer
22318                .begin_skinned_frame(
22319                    device,
22320                    &mut self.skinning,
22321                    &[range],
22322                    &Camera::default(),
22323                    &DirectionalLight::default(),
22324                    TEST_EXTENT,
22325                )
22326                .expect("a legal skinning plan");
22327        }
22328
22329        fn destroy(mut self, device: &dyn Device) {
22330            self.renderer.release_skinned(self.skinned);
22331            self.skinning.destroy(device);
22332            self.renderer.destroy(device);
22333        }
22334    }
22335
22336    /// How many times the host wrote the mesh-table entry `id` names.
22337    fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
22338        let table = renderer.pool.table_buffer();
22339        let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
22340        recorder
22341            .events()
22342            .into_iter()
22343            .filter(|event| {
22344                matches!(
22345                    event,
22346                    crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
22347                        if *buffer == table && *offset == at
22348                )
22349            })
22350            .count()
22351    }
22352
22353    /// The record `handle` names, out of the ring buffer **this frame draws
22354    /// from** rather than out of the pool's host mirror.
22355    ///
22356    /// A mirror and a buffer that disagree is exactly the defect a re-pointing
22357    /// design can have, so every claim about a skinned instance's bases is read
22358    /// off the bytes a shader would.
22359    fn instance_record(
22360        recorder: &Recorder,
22361        renderer: &ForwardRenderer,
22362        handle: InstanceHandle,
22363    ) -> mesh::GpuInstance {
22364        let buffer = renderer.instances.buffers()[renderer.frame()];
22365        let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
22366        let index = renderer
22367            .instances
22368            .index(handle)
22369            .expect("the object is live") as usize;
22370        let at = index * mesh::INSTANCE_STRIDE;
22371        mesh::GpuInstance::from_bytes(
22372            bytes[at..at + mesh::INSTANCE_STRIDE]
22373                .try_into()
22374                .expect("one whole instance"),
22375        )
22376    }
22377
22378    /// **A skinned primitive takes no mesh-table entry of its own, and nothing
22379    /// rewrites the one it draws through.**
22380    ///
22381    /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
22382    /// precisely because nothing rewrites an entry between frames, so a design
22383    /// that re-pointed an entry at the half a frame writes would be wrong only
22384    /// on the frames that overlap — which is to say invisibly. What alternates
22385    /// instead is a field of the *instance*, and instances go through a ring.
22386    ///
22387    /// So a skinned object draws through the source mesh's own entry: the same
22388    /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
22389    /// carrying the bind pose's base vertex, still written exactly once after
22390    /// four skinned frames. That shared entry is also what lets one mesh be
22391    /// drawn skinned and unskinned in the same frame.
22392    #[test]
22393    fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
22394        let (recorder, device, queue) = open();
22395        let device = device.as_ref();
22396        let mut fixture = SkinnedFixture::build(device, queue);
22397
22398        let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
22399        assert_eq!(
22400            fixture.skinned.mesh_id(),
22401            bind_pose_id,
22402            "a skinned instance names the mesh it was deformed from, so the bucket, the level \
22403             tables and the bounding box all resolve as the bind pose's"
22404        );
22405
22406        let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
22407        assert_eq!(
22408            bind_pose.base_vertex,
22409            fixture.skinned.input_base(),
22410            "the entry goes on naming the bind pose the dispatch reads, not either half it \
22411             writes"
22412        );
22413        for parity in 0..2 {
22414            assert_ne!(
22415                fixture.skinned.region().base(parity),
22416                bind_pose.base_vertex,
22417                "half {parity} must not be the bind pose, which the kernel reads while it \
22418                 writes them"
22419            );
22420        }
22421        assert_ne!(
22422            fixture.skinned.region().base(0),
22423            fixture.skinned.region().base(1),
22424            "the two halves are separate reservations, or the ping-pong is one buffer"
22425        );
22426
22427        // Counted before the frames rather than compared against a literal:
22428        // `MeshPool::new` clears the whole table with one write at offset zero,
22429        // which lands on this entry too, so the number here is the pool's
22430        // start-up and not this test's business. What the loop below has to
22431        // leave alone is whatever it is.
22432        let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
22433        assert!(
22434            writes_before > 0,
22435            "the entry was written at least once before any frame ran, or the counter below \
22436             is counting nothing and the comparison after the frames is vacuous"
22437        );
22438
22439        // Four frames, which is two of each parity: enough that a design
22440        // rewriting an entry per frame would have written four more times.
22441        let imported = swapchain_image_at(device, TEST_EXTENT);
22442        let mut pool = crate::TransientPool::new();
22443        for _ in 0..4 {
22444            fixture.begin(device);
22445            let mut graph = crate::RenderGraph::new(queue);
22446            let target = graph.import_image("target", imported);
22447            fixture.renderer.add_skinned_passes(
22448                &mut graph,
22449                &pool,
22450                target,
22451                TEST_EXTENT,
22452                &fixture.skinning,
22453            );
22454            graph.compile(&pool).expect("a legal frame");
22455        }
22456
22457        assert_eq!(
22458            table_writes(&recorder, &fixture.renderer, bind_pose_id),
22459            writes_before,
22460            "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
22461             table is one buffer rather than a ring is that nothing rewrites an entry between \
22462             frames"
22463        );
22464
22465        fixture.destroy(device);
22466        pool.destroy(device);
22467        device.destroy_image_view(imported.view);
22468        device.destroy_image(imported.image);
22469        recorder.assert_valid();
22470    }
22471
22472    /// **A skinned object's recorded base vertex follows the parity of the frame
22473    /// it is drawn in**, and it carries the bit that makes a shader read it.
22474    ///
22475    /// The other half of the design: the table entry never moves, so what has to
22476    /// alternate is a field of the *instance* — and it has to alternate in the
22477    /// buffer the frame actually draws from, which is why this reads the
22478    /// instance ring's bytes rather than the host's mirror.
22479    ///
22480    /// Three claims, and the last two are what stop the first being vacuous. The
22481    /// base must be the one this frame's parity names; the record must carry
22482    /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
22483    /// without which the raster stages read the mesh entry and the field is
22484    /// decoration; and two consecutive frames must have named **different**
22485    /// halves, without which a renderer ignoring the parity entirely would pass.
22486    #[test]
22487    fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
22488        let (recorder, device, queue) = open();
22489        let device = device.as_ref();
22490        let mut fixture = SkinnedFixture::build(device, queue);
22491        let handle = fixture
22492            .renderer
22493            .add_skinned_instance(&SkinnedInstanceDesc {
22494                mesh: &fixture.skinned,
22495                material: DEMO_UNTINTED,
22496                transform: Mat4::IDENTITY,
22497                bounds: None,
22498            })
22499            .expect("a pool of thousands has room for one object");
22500
22501        let mut carried = Vec::new();
22502        for _ in 0..2 {
22503            fixture.begin(device);
22504            let parity = fixture.skinning.parity();
22505            let instance = instance_record(&recorder, &fixture.renderer, handle);
22506            assert_eq!(
22507                instance.base_vertex,
22508                fixture.skinned.region().base(parity),
22509                "the buffer this frame draws from must carry the base parity {parity} writes"
22510            );
22511            assert_eq!(
22512                instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
22513                mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
22514                "without the bit the raster stages resolve the mesh entry's base and this \
22515                 field is never read"
22516            );
22517            assert_eq!(
22518                instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
22519                "and the record still names the source mesh, which is what its bucket, its \
22520                 levels and its bounding box resolve through"
22521            );
22522            carried.push(instance.base_vertex);
22523        }
22524        assert_ne!(
22525            carried[0], carried[1],
22526            "two consecutive frames must have drawn different halves, or a renderer that \
22527             ignored the parity entirely would pass this"
22528        );
22529
22530        fixture.destroy(device);
22531        recorder.assert_valid();
22532    }
22533
22534    /// **A skinned object's own box reaches the buffer a frame draws from, and
22535    /// [`ForwardRenderer::set_skinned_bounds`] moves it without moving the
22536    /// object.**
22537    ///
22538    /// Read out of the instance ring rather than the host mirror, and put to
22539    /// [`crate::cull::visible_instances`] — the CPU reference the device's cull
22540    /// is held to — so what is asserted is that reference's decision on the
22541    /// bytes a frame uploads: kept while the box is around the origin the
22542    /// camera looks at, culled once the setter moves it thirty metres away,
22543    /// and kept again — in every cull, as a boxless skinned object always is —
22544    /// once the setter takes the box away.
22545    ///
22546    /// **And the box is not a move.** The object is moved a metre first, and
22547    /// the box set after the move and before the frame: the record must still
22548    /// say it travelled from where it was, which a box written through
22549    /// [`InstancePool::set`] would overwrite with the transform it already
22550    /// carries.
22551    #[test]
22552    fn a_skinned_box_is_carried_and_moved_without_a_move() {
22553        let (recorder, device, queue) = open();
22554        let device = device.as_ref();
22555        let mut fixture = SkinnedFixture::build(device, queue);
22556        let near = Aabb {
22557            min: Vec3::splat(-0.5),
22558            max: Vec3::splat(0.5),
22559        };
22560        let handle = fixture
22561            .renderer
22562            .add_skinned_instance(&SkinnedInstanceDesc {
22563                mesh: &fixture.skinned,
22564                material: DEMO_UNTINTED,
22565                transform: Mat4::IDENTITY,
22566                bounds: Some(near),
22567            })
22568            .expect("a pool of thousands has room for one object");
22569        let frustum = Frustum::from_view_projection(Camera::default().view_projection(1.0));
22570        let meshes = fixture.renderer.pool.table_entries();
22571        let kept = |record: mesh::GpuInstance| {
22572            !crate::cull::visible_instances(&frustum, &[record], &meshes, 0).is_empty()
22573        };
22574
22575        fixture.begin(device);
22576        let first = instance_record(&recorder, &fixture.renderer, handle);
22577        assert_ne!(first.flags & mesh::GpuInstance::OWNS_BOUNDS, 0);
22578        assert_eq!(
22579            (first.bounds_min, first.bounds_max),
22580            (near.min.to_array(), near.max.to_array())
22581        );
22582        assert!(kept(first), "a box around the origin is in view");
22583
22584        let stepped = Mat4::from_translation(Vec3::X);
22585        fixture.renderer.set_skinned_instance(
22586            handle,
22587            &SkinnedInstanceDesc {
22588                mesh: &fixture.skinned,
22589                material: DEMO_UNTINTED,
22590                transform: stepped,
22591                bounds: Some(near),
22592            },
22593        );
22594        let far = Aabb {
22595            min: Vec3::new(29.5, -0.5, -0.5),
22596            max: Vec3::new(30.5, 0.5, 0.5),
22597        };
22598        fixture
22599            .renderer
22600            .set_skinned_bounds(handle, Some(far))
22601            .expect("a finite, ordered box");
22602        fixture.begin(device);
22603        let moved = instance_record(&recorder, &fixture.renderer, handle);
22604        assert_eq!(
22605            (moved.bounds_min, moved.bounds_max),
22606            (far.min.to_array(), far.max.to_array())
22607        );
22608        assert!(
22609            !kept(moved),
22610            "the moved box is off screen, so the object is culled"
22611        );
22612        assert_eq!(moved.transform, stepped.to_cols_array());
22613        assert_eq!(
22614            moved.previous_transform, first.transform,
22615            "the box was set after the move, and the record must still say where the \
22616             object moved from"
22617        );
22618        assert_ne!(
22619            moved.base_vertex, first.base_vertex,
22620            "the frame still re-pointed the object, and the box survived it"
22621        );
22622
22623        fixture
22624            .renderer
22625            .set_skinned_bounds(handle, None)
22626            .expect("no box is always accepted");
22627        fixture.begin(device);
22628        let cleared = instance_record(&recorder, &fixture.renderer, handle);
22629        assert_eq!(cleared.flags & mesh::GpuInstance::OWNS_BOUNDS, 0);
22630        assert!(
22631            kept(cleared),
22632            "without a box the object is in every cull again"
22633        );
22634
22635        fixture.destroy(device);
22636        recorder.assert_valid();
22637    }
22638
22639    /// **A replace takes its description's box**: a box
22640    /// [`ForwardRenderer::set_skinned_bounds`] wrote is gone after a
22641    /// [`ForwardRenderer::set_skinned_instance`] whose description says
22642    /// `None`, and replaced by the description's when it says `Some`. The
22643    /// description is authoritative, which is what a caller placing an object
22644    /// every frame has to know — see `set_skinned_instance`'s docs.
22645    #[test]
22646    fn a_skinned_replace_takes_its_descriptions_box() {
22647        let (recorder, device, queue) = open();
22648        let device = device.as_ref();
22649        let mut fixture = SkinnedFixture::build(device, queue);
22650        let desc = |bounds| SkinnedInstanceDesc {
22651            mesh: &fixture.skinned,
22652            material: DEMO_UNTINTED,
22653            transform: Mat4::IDENTITY,
22654            bounds,
22655        };
22656        let handle = fixture
22657            .renderer
22658            .add_skinned_instance(&desc(None))
22659            .expect("a pool of thousands has room for one object");
22660        let set = Aabb {
22661            min: Vec3::splat(-2.0),
22662            max: Vec3::splat(2.0),
22663        };
22664        let given = Aabb {
22665            min: Vec3::splat(-1.0),
22666            max: Vec3::splat(1.0),
22667        };
22668        let record = |renderer: &ForwardRenderer| {
22669            renderer.instances.get(handle).expect("the object is live")
22670        };
22671
22672        fixture
22673            .renderer
22674            .set_skinned_bounds(handle, Some(set))
22675            .expect("a finite, ordered box");
22676        assert_ne!(
22677            record(&fixture.renderer).flags & mesh::GpuInstance::OWNS_BOUNDS,
22678            0
22679        );
22680        fixture.renderer.set_skinned_instance(handle, &desc(None));
22681        assert_eq!(
22682            record(&fixture.renderer).flags & mesh::GpuInstance::OWNS_BOUNDS,
22683            0,
22684            "a description with no box takes the set box away"
22685        );
22686
22687        fixture
22688            .renderer
22689            .set_skinned_bounds(handle, Some(set))
22690            .expect("a finite, ordered box");
22691        fixture
22692            .renderer
22693            .set_skinned_instance(handle, &desc(Some(given)));
22694        let replaced = record(&fixture.renderer);
22695        assert_ne!(replaced.flags & mesh::GpuInstance::OWNS_BOUNDS, 0);
22696        assert_eq!(
22697            (replaced.bounds_min, replaced.bounds_max),
22698            (given.min.to_array(), given.max.to_array()),
22699            "a description with a box replaces the set one with its own"
22700        );
22701
22702        fixture.begin(device);
22703        fixture.destroy(device);
22704        recorder.assert_valid();
22705    }
22706
22707    /// **A box the culls could not read is refused at the boundary**: an
22708    /// inverted one and one with a `NaN` or an infinite corner are
22709    /// [`InstancePoolError::InvalidBounds`] from
22710    /// [`ForwardRenderer::add_skinned_instance`] and from
22711    /// [`ForwardRenderer::set_skinned_bounds`], neither of which writes
22712    /// anything, and a panic naming the box from
22713    /// [`ForwardRenderer::set_skinned_instance`], which has no `Result` — while
22714    /// a degenerate box, a single point, is a box and is accepted.
22715    #[test]
22716    fn an_unusable_skinned_box_is_refused() {
22717        let (recorder, device, queue) = open();
22718        let device = device.as_ref();
22719        let mut fixture = SkinnedFixture::build(device, queue);
22720        let desc = |bounds| SkinnedInstanceDesc {
22721            mesh: &fixture.skinned,
22722            material: DEMO_UNTINTED,
22723            transform: Mat4::IDENTITY,
22724            bounds: Some(bounds),
22725        };
22726        let unusable = [
22727            Aabb {
22728                min: Vec3::new(1.0, -1.0, -1.0),
22729                max: Vec3::new(-1.0, 1.0, 1.0),
22730            },
22731            Aabb {
22732                min: Vec3::new(-1.0, f32::NAN, -1.0),
22733                max: Vec3::ONE,
22734            },
22735            Aabb {
22736                min: Vec3::splat(-1.0),
22737                max: Vec3::new(1.0, 1.0, f32::INFINITY),
22738            },
22739        ];
22740        let live = fixture.renderer.instances.live().len();
22741        for bounds in unusable {
22742            let refused = fixture.renderer.add_skinned_instance(&desc(bounds));
22743            assert!(
22744                matches!(refused, Err(InstancePoolError::InvalidBounds { .. })),
22745                "{bounds:?} was not refused by name: {refused:?}"
22746            );
22747        }
22748        assert_eq!(
22749            fixture.renderer.instances.live().len(),
22750            live,
22751            "a refused object takes no slot"
22752        );
22753
22754        let point = Aabb {
22755            min: Vec3::ONE,
22756            max: Vec3::ONE,
22757        };
22758        let handle = fixture
22759            .renderer
22760            .add_skinned_instance(&desc(point))
22761            .expect("a single point is a box");
22762        for bounds in unusable {
22763            let refused = fixture.renderer.set_skinned_bounds(handle, Some(bounds));
22764            assert!(
22765                matches!(refused, Err(InstancePoolError::InvalidBounds { .. })),
22766                "set_skinned_bounds did not refuse {bounds:?} by name: {refused:?}"
22767            );
22768            let skinned = &fixture.skinned;
22769            let renderer = &mut fixture.renderer;
22770            let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
22771                renderer.set_skinned_instance(
22772                    handle,
22773                    &SkinnedInstanceDesc {
22774                        mesh: skinned,
22775                        material: DEMO_UNTINTED,
22776                        transform: Mat4::IDENTITY,
22777                        bounds: Some(bounds),
22778                    },
22779                );
22780            }));
22781            assert!(panicked.is_err(), "set_skinned_instance wrote {bounds:?}");
22782        }
22783        let kept = fixture
22784            .renderer
22785            .instances
22786            .get(handle)
22787            .expect("the object is live");
22788        assert_eq!(
22789            (kept.bounds_min, kept.bounds_max),
22790            (point.min.to_array(), point.max.to_array()),
22791            "a refused box leaves the one before it in place"
22792        );
22793
22794        fixture.begin(device);
22795        fixture.destroy(device);
22796        recorder.assert_valid();
22797    }
22798
22799    /// **A skinned object's record names the half the frame before it filled**,
22800    /// and it starts at rest.
22801    ///
22802    /// The other half of a skinned motion vector. The base above is where a
22803    /// fragment *is*; this is where it *was*, and without it the geometry stages
22804    /// put the previous transform through this frame's deformed vertex — so a
22805    /// limb that swung reports the motion of the body it hangs off. See
22806    /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
22807    ///
22808    /// Four claims, and the first and last are what stop the middle two being a
22809    /// restatement of the parity:
22810    ///
22811    /// * the **first** frame of a fresh object writes the base it draws out of,
22812    ///   because the other half holds whatever its reservation came with and a
22813    ///   motion vector against undefined vertices is worse than no motion;
22814    /// * the frames after it write
22815    ///   [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
22816    ///   which must also **differ** from the base they draw out of — a renderer
22817    ///   that wrote the current base into both lanes would satisfy every "it is
22818    ///   a legal base" reading of this and leave every skinned instance at rest;
22819    /// * and moving the object onto a **different region** puts it back at rest
22820    ///   for one frame, because the halves it now names are two runs it has
22821    ///   never been drawn out of.
22822    #[test]
22823    fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
22824        let (recorder, device, queue) = open();
22825        let device = device.as_ref();
22826        let mut fixture = SkinnedFixture::build(device, queue);
22827        let handle = fixture
22828            .renderer
22829            .add_skinned_instance(&SkinnedInstanceDesc {
22830                mesh: &fixture.skinned,
22831                material: DEMO_UNTINTED,
22832                transform: Mat4::IDENTITY,
22833                bounds: None,
22834            })
22835            .expect("a pool of thousands has room for one object");
22836
22837        for frame in 1..=3u32 {
22838            fixture.begin(device);
22839            let parity = fixture.skinning.parity();
22840            let instance = instance_record(&recorder, &fixture.renderer, handle);
22841            assert_eq!(
22842                instance.base_vertex,
22843                fixture.skinned.region().base(parity),
22844                "frame {frame} must draw out of the half parity {parity} fills"
22845            );
22846            if frame == 1 {
22847                assert_eq!(
22848                    instance.previous_base_vertex, instance.base_vertex,
22849                    "a fresh object has no previous deformation, so its first frame owes rest \
22850                     rather than a half no dispatch has written"
22851                );
22852            } else {
22853                assert_eq!(
22854                    instance.previous_base_vertex,
22855                    fixture.skinned.region().previous_base(parity),
22856                    "frame {frame} must subtract against the half the frame before it filled"
22857                );
22858                assert_ne!(
22859                    instance.previous_base_vertex, instance.base_vertex,
22860                    "frame {frame} named one half twice, which is every skinned fragment at \
22861                     rest however far its surface moved"
22862                );
22863            }
22864        }
22865
22866        // The same object, moved onto a region it has never been drawn out of:
22867        // both halves are runs no dispatch of this object's has filled, so the
22868        // rule that put the first frame at rest applies again.
22869        let second = fixture
22870            .renderer
22871            .reserve_skinned(DEMO_CUBE)
22872            .expect("a default pool has room for two more halves of a cube");
22873        assert_ne!(
22874            second.region().base(0),
22875            fixture.skinned.region().base(0),
22876            "the second reservation is the same two runs as the first, so nothing below is \
22877             about a change of region at all"
22878        );
22879        fixture.renderer.set_skinned_instance(
22880            handle,
22881            &SkinnedInstanceDesc {
22882                mesh: &second,
22883                material: DEMO_UNTINTED,
22884                transform: Mat4::IDENTITY,
22885                bounds: None,
22886            },
22887        );
22888
22889        for frame in 1..=2u32 {
22890            fixture.begin(device);
22891            let parity = fixture.skinning.parity();
22892            let instance = instance_record(&recorder, &fixture.renderer, handle);
22893            assert_eq!(
22894                instance.base_vertex,
22895                second.region().base(parity),
22896                "frame {frame} after the move must draw out of the new region"
22897            );
22898            if frame == 1 {
22899                assert_eq!(
22900                    instance.previous_base_vertex, instance.base_vertex,
22901                    "the first frame on a new region owes rest, exactly as a fresh object does"
22902                );
22903            } else {
22904                assert_eq!(
22905                    instance.previous_base_vertex,
22906                    second.region().previous_base(parity),
22907                    "and the frame after it is subtracting against the new region's other half"
22908                );
22909            }
22910        }
22911
22912        fixture.renderer.release_skinned(second);
22913        fixture.destroy(device);
22914        recorder.assert_valid();
22915    }
22916
22917    /// **A skinned object that moves carries the transform it moved from**, and
22918    /// the frame after it is back at rest.
22919    ///
22920    /// The transform half of a skinned motion vector, and the half the
22921    /// per-frame re-point used to erase: it rewrote the record through
22922    /// [`InstancePool::set`], which fills the previous transform out of the
22923    /// record it overwrites — and that record already held this frame's
22924    /// transform, because
22925    /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
22926    /// it there. Every skinned instance then read `previous_transform ==
22927    /// transform` on every frame, so a character that walked contributed
22928    /// nothing to the motion target from the walk, only from its deformation.
22929    /// [`InstancePool::set_bases`] is what the re-point goes through instead.
22930    ///
22931    /// Both frames are the claim. Without the second, a re-point that wrote
22932    /// some *other* stale transform into the field would pass; and the second
22933    /// is the pool's own rest rule reaching a skinned object at all, which a
22934    /// re-point that kept enrolling the element every frame would suppress
22935    /// for ever.
22936    ///
22937    /// Read out of the ring buffer the frame draws from, on
22938    /// [`instance_record`]'s terms.
22939    #[test]
22940    fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
22941        let (recorder, device, queue) = open();
22942        let device = device.as_ref();
22943        let mut fixture = SkinnedFixture::build(device, queue);
22944        let handle = fixture
22945            .renderer
22946            .add_skinned_instance(&SkinnedInstanceDesc {
22947                mesh: &fixture.skinned,
22948                material: DEMO_UNTINTED,
22949                transform: Mat4::IDENTITY,
22950                bounds: None,
22951            })
22952            .expect("a pool of thousands has room for one object");
22953
22954        // Two frames standing still, so the history the move is measured
22955        // against is a settled record rather than a fresh one.
22956        fixture.begin(device);
22957        fixture.begin(device);
22958
22959        let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
22960        fixture.renderer.set_skinned_instance(
22961            handle,
22962            &SkinnedInstanceDesc {
22963                mesh: &fixture.skinned,
22964                material: DEMO_UNTINTED,
22965                transform: moved,
22966                bounds: None,
22967            },
22968        );
22969        fixture.begin(device);
22970        let instance = instance_record(&recorder, &fixture.renderer, handle);
22971        assert_eq!(
22972            instance.transform,
22973            moved.to_cols_array(),
22974            "the frame that moved the object must draw it where it arrived"
22975        );
22976        assert_eq!(
22977            instance.previous_transform,
22978            Mat4::IDENTITY.to_cols_array(),
22979            "and it must say where from — a previous transform equal to the current one is \
22980             the re-point having overwritten the move"
22981        );
22982
22983        fixture.begin(device);
22984        let settled = instance_record(&recorder, &fixture.renderer, handle);
22985        assert_eq!(
22986            settled.transform,
22987            moved.to_cols_array(),
22988            "nothing moved it again"
22989        );
22990        assert_eq!(
22991            settled.previous_transform, settled.transform,
22992            "so the frame after the move owes rest; a re-point that enrolled the element \
22993             every frame would keep it reporting the move for ever"
22994        );
22995
22996        fixture.destroy(device);
22997        recorder.assert_valid();
22998    }
22999
23000    /// **The graph barriers the skinning dispatch's write before every pass that
23001    /// pulls vertices**, and it does so because `add_skinned_passes` added the
23002    /// dispatch itself rather than trusting a caller to.
23003    ///
23004    /// Pass order alone would not settle it — a dispatch that ran first and was
23005    /// never barriered is the exact defect, and it produces a correct-looking
23006    /// frame on a desktop driver. So the transition out of
23007    /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
23008    /// it must sit after the dispatch, and it must sit at or before the first of
23009    /// the three passes that draw.
23010    #[test]
23011    fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
23012        let (recorder, device, queue) = open();
23013        let device = device.as_ref();
23014        let mut fixture = SkinnedFixture::build(device, queue);
23015        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
23016        fixture
23017            .renderer
23018            .add_skinned_instance(&SkinnedInstanceDesc {
23019                mesh: &fixture.skinned,
23020                material: DEMO_UNTINTED,
23021                transform: Mat4::IDENTITY,
23022                bounds: None,
23023            })
23024            .expect("room for one object");
23025        fixture.begin(device);
23026
23027        let imported = swapchain_image_at(device, TEST_EXTENT);
23028        let mut pool = crate::TransientPool::new();
23029        let mut graph = crate::RenderGraph::new(queue);
23030        let target = graph.import_image("target", imported);
23031        // The same node `Skinning::add_pass` imports — one handle is one node —
23032        // so the barriers below can be named rather than guessed at.
23033        let vertices = graph.import_buffer(
23034            "vertex-pool",
23035            ImportedBuffer {
23036                buffer: fixture.renderer.vertex_buffer(),
23037                initial: ResourceState::ShaderRead,
23038                final_state: ResourceState::ShaderRead,
23039            },
23040        );
23041        fixture.renderer.add_skinned_passes(
23042            &mut graph,
23043            &pool,
23044            target,
23045            TEST_EXTENT,
23046            &fixture.skinning,
23047        );
23048        let compiled = graph.compile(&pool).expect("a legal frame");
23049        let labels: Vec<&str> = compiled
23050            .passes()
23051            .iter()
23052            .map(crate::graph::CompiledPass::label)
23053            .collect();
23054
23055        let dispatch = labels
23056            .iter()
23057            .position(|label| *label == "skinning")
23058            .expect("add_skinned_passes adds the dispatch itself");
23059        let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
23060            .into_iter()
23061            .map(|wanted| {
23062                labels
23063                    .iter()
23064                    .position(|label| *label == wanted)
23065                    .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
23066            })
23067            .collect();
23068        for (label, at) in ["shadow", "depth-prepass", "forward"]
23069            .into_iter()
23070            .zip(&drawing)
23071        {
23072            assert!(
23073                dispatch < *at,
23074                "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
23075            );
23076        }
23077
23078        // Each drawing pass declares the read for itself, and this is asserted
23079        // per pass rather than left to the single barrier below. The graph
23080        // transitions the region once, before the first reader, and a later
23081        // pass that never declared the read finds it already in the state it
23082        // wanted — so dropping the declaration from `forward` alone changes no
23083        // barrier and moves no label, and every assertion in this test still
23084        // passes. What it does drop is that pass's *dependency* on the
23085        // dispatch, which is the only thing keeping the two in this order.
23086        for (label, at) in ["shadow", "depth-prepass", "forward"]
23087            .into_iter()
23088            .zip(&drawing)
23089        {
23090            assert!(
23091                compiled.passes()[*at].reads_buffer(vertices),
23092                "{label} draws skinned vertices and must declare that it reads them, or \
23093                 nothing but declaration order keeps it after the dispatch"
23094            );
23095        }
23096
23097        let released: Vec<usize> = compiled
23098            .passes()
23099            .iter()
23100            .enumerate()
23101            .filter(|(_, pass)| {
23102                pass.barriers().buffers.iter().any(|barrier| {
23103                    barrier.buffer == vertices
23104                        && barrier.from == ResourceState::ShaderReadWrite
23105                        && barrier.to == ResourceState::ShaderRead
23106                })
23107            })
23108            .map(|(at, _)| at)
23109            .collect();
23110        assert_eq!(
23111            released.len(),
23112            1,
23113            "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
23114        );
23115        let barrier = released[0];
23116        let first_draw = *drawing.iter().min().expect("three passes");
23117        assert!(
23118            dispatch < barrier && barrier <= first_draw,
23119            "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
23120             draws at {first_draw} — a draw that reads the region before the write is made \
23121             visible is the whole defect this seam exists to prevent"
23122        );
23123
23124        drop(compiled);
23125        fixture.destroy(device);
23126        pool.destroy(device);
23127        device.destroy_image_view(imported.view);
23128        device.destroy_image(imported.image);
23129        recorder.assert_valid();
23130    }
23131
23132    /// A frame with nothing to skin adds no dispatch and declares no read, and
23133    /// is the frame [`ForwardRenderer::add_passes`] would have built.
23134    #[test]
23135    fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
23136        let _blurs = ssao_blur_switch();
23137        let (recorder, device, queue) = open();
23138        let device = device.as_ref();
23139        let mut fixture = SkinnedFixture::build(device, queue);
23140        place_cube(&mut fixture.renderer, Mat4::IDENTITY);
23141
23142        let imported = swapchain_image_at(device, TEST_EXTENT);
23143        let pool = crate::TransientPool::new();
23144        let mut skinned_labels = Vec::new();
23145        for _ in 0..1 {
23146            fixture
23147                .renderer
23148                .begin_skinned_frame(
23149                    device,
23150                    &mut fixture.skinning,
23151                    &[],
23152                    &Camera::default(),
23153                    &DirectionalLight::default(),
23154                    TEST_EXTENT,
23155                )
23156                .expect("an empty plan is a legal one");
23157            let mut graph = crate::RenderGraph::new(queue);
23158            let target = graph.import_image("target", imported);
23159            fixture.renderer.add_skinned_passes(
23160                &mut graph,
23161                &pool,
23162                target,
23163                TEST_EXTENT,
23164                &fixture.skinning,
23165            );
23166            skinned_labels = graph
23167                .compile(&pool)
23168                .expect("a legal frame")
23169                .passes()
23170                .iter()
23171                .map(|pass| pass.label().to_string())
23172                .collect();
23173        }
23174        let plain = passes_in_a_frame(
23175            device,
23176            queue,
23177            &mut fixture.renderer,
23178            imported,
23179            &pool,
23180            TEST_EXTENT,
23181        );
23182        assert_eq!(
23183            skinned_labels, plain,
23184            "a frame with nothing to skin must cost the vertex pool no barrier at all"
23185        );
23186
23187        fixture.destroy(device);
23188        let mut pool = pool;
23189        pool.destroy(device);
23190        device.destroy_image_view(imported.view);
23191        device.destroy_image(imported.image);
23192        recorder.assert_valid();
23193    }
23194
23195    /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
23196    /// the commands land in.
23197    ///
23198    /// Returned rather than cleaned up here because the caller reads the
23199    /// recorder afterwards, and everything below must outlive that.
23200    struct Frame {
23201        imported: ImportedImage,
23202        pool: crate::TransientPool,
23203        commands: crcbl_hal::CommandBufferHandle,
23204    }
23205
23206    impl Frame {
23207        /// Releases the frame and the image it drew into, leaving the renderer
23208        /// alive for another one.
23209        fn release(self, device: &dyn Device) {
23210            device.destroy_command_buffer(self.commands);
23211            let mut pool = self.pool;
23212            pool.destroy(device);
23213            device.destroy_image_view(self.imported.view);
23214            device.destroy_image(self.imported.image);
23215        }
23216
23217        /// Releases the frame, the renderer and the image it drew into.
23218        fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
23219            self.release(device);
23220            renderer.destroy(device);
23221        }
23222    }
23223
23224    /// Everything one labelled pass recorded, and nothing any other pass did.
23225    ///
23226    /// **Every draw assertion below is scoped through this**, and the reason is
23227    /// topic 18: the frame now records the same indirect call the colour pass
23228    /// records once per shadow cascade as well, out of that cascade's own
23229    /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
23230    /// would see one per cascade as well as the colour pass's, and could not
23231    /// say which pass any of them belonged to — so "the forward pass records one
23232    /// call per bucket" would become a claim about a total, which a shadow pass
23233    /// recording the wrong thing could satisfy.
23234    /// The compute dispatches a default frame's **resolve** records, which
23235    /// every dispatch count in this module sees and none of them is about.
23236    ///
23237    /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
23238    /// shape classification are dispatches; its apply is a draw and does not
23239    /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
23240    /// what pins the resolve's pass list itself, so a tier that grew a dispatch
23241    /// fails there first and arrives here as a second red rather than as a
23242    /// silent skew.
23243    const RESOLVE_DISPATCHES: usize = 2;
23244
23245    fn commands_in_pass(
23246        recorder: &crcbl_hal::null::Recorder,
23247        label: &str,
23248    ) -> Vec<crcbl_hal::null::Command> {
23249        use crcbl_hal::null::Command;
23250
23251        let mut inside = false;
23252        let mut out = Vec::new();
23253        for command in recorder.commands() {
23254            if let Some((_, recorded)) = command.opens_pass() {
23255                inside = recorded == Some(label);
23256                continue;
23257            }
23258            if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
23259                inside = false;
23260                continue;
23261            }
23262            if inside {
23263                out.push(command);
23264            }
23265        }
23266        assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
23267        out
23268    }
23269
23270    /// The extent every helper frame in this module is drawn at.
23271    ///
23272    /// Named since the bloom chain, whose length is a function of it — see
23273    /// [`crate::bloom`] — so a test comparing a pass count against
23274    /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
23275    /// at. Small on purpose: two chain levels is enough for every arm here, and
23276    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
23277    /// test that needs a frame large enough for six.
23278    ///
23279    /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
23280    const TEST_EXTENT: (u32, u32) = (64, 48);
23281
23282    /// The effects a caller has to ask for, because the default stack leaves
23283    /// them out — see [`RenderEffects::DEFAULT_STACK`].
23284    ///
23285    /// Named rather than written out at each of the three sites that force them
23286    /// on, because the point of those sites is "every effect there is" and the
23287    /// bug they exist to catch is a new effect joining the set and one site
23288    /// still measuring the old one while calling it the whole stack. They are
23289    /// held out of the default for different reasons — [`crate::effects`] gives
23290    /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
23291    /// pending re-bless rather than a decision — and share only that a test
23292    /// wanting the widest frame must ask.
23293    ///
23294    /// **Named for what it is rather than for what most of it is**: the set held
23295    /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
23296    /// march is neither.
23297    const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
23298        .union(RenderEffects::ANTIALIASING)
23299        .union(RenderEffects::VOLUMETRIC_FOG)
23300        .union(RenderEffects::AUTO_EXPOSURE)
23301        .union(RenderEffects::CMAA2)
23302        .union(RenderEffects::CONTACT_SHADOWS);
23303
23304    /// Every effect this renderer draws is either in the default stack or in
23305    /// [`OUTSIDE_THE_DEFAULT`].
23306    ///
23307    /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
23308    /// call the result "every effect", which is only true while nothing else is
23309    /// held out. An effect added outside the default stack and not added
23310    /// here makes this red before it makes a pass-list assertion red — which is
23311    /// the useful order, since a pass list going red says a label moved and this
23312    /// says what actually happened.
23313    #[test]
23314    fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
23315        assert_eq!(
23316            RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
23317            RenderEffects::all(),
23318            "an effect outside the default stack that no test forces on is an effect \
23319             the every-effect frames below have never drawn"
23320        );
23321    }
23322
23323    /// The default sun, turned a little further round for each `lap`.
23324    ///
23325    /// Topic 45's static-caching rung means a second frame over
23326    /// a scene nothing moved in records **no shadow pass at all** — see
23327    /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
23328    /// a difference that every A/B drawing two frames from one renderer would
23329    /// otherwise be measuring on top of the one it is about. Turning the sun is
23330    /// the smallest input the atlas depends on: the cascades are refitted, so
23331    /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
23332    /// with it.
23333    ///
23334    /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
23335    /// frame is the ordinary one keeps the frame every other test draws.
23336    fn moving_sun(lap: u32) -> DirectionalLight {
23337        let sun = DirectionalLight::default();
23338        // A degree a lap, about the axis the default direction is not parallel
23339        // to. Small enough that every cascade still sees the scene, and large
23340        // enough that the snapped cascade origin actually moves.
23341        let turn = Mat4::from_rotation_y(
23342            f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
23343                / 180.0,
23344        );
23345        DirectionalLight {
23346            direction: turn.transform_vector3(sun.direction).normalize(),
23347            ..sun
23348        }
23349    }
23350
23351    /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
23352    /// not the one the lap before it left in the image.
23353    fn frame_moving_the_sun(
23354        device: &dyn Device,
23355        renderer: &mut ForwardRenderer,
23356        queue: QueueHandle,
23357        lap: u32,
23358    ) -> Frame {
23359        frame_lit_by(device, renderer, queue, &moving_sun(lap))
23360    }
23361
23362    fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
23363        frame_lit_by(device, renderer, queue, &DirectionalLight::default())
23364    }
23365
23366    fn frame_lit_by(
23367        device: &dyn Device,
23368        renderer: &mut ForwardRenderer,
23369        queue: QueueHandle,
23370        sun: &DirectionalLight,
23371    ) -> Frame {
23372        frame_seen_from(device, renderer, queue, &Camera::default(), sun)
23373    }
23374
23375    fn frame_seen_from(
23376        device: &dyn Device,
23377        renderer: &mut ForwardRenderer,
23378        queue: QueueHandle,
23379        camera: &Camera,
23380        sun: &DirectionalLight,
23381    ) -> Frame {
23382        renderer
23383            .begin_frame(device, camera, sun, TEST_EXTENT)
23384            .expect("write");
23385        let imported = swapchain_image(device);
23386        let mut graph = crate::RenderGraph::new(queue);
23387        let target = graph.import_image("target", imported);
23388        let mut pool = crate::TransientPool::new();
23389        renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
23390        let compiled = graph.compile(&pool).expect("a legal frame");
23391        let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
23392            label: Some("forward frame"),
23393            queue,
23394        });
23395        compiled
23396            .execute(device, &mut pool, encoder.as_mut(), None)
23397            .expect("the graph executed");
23398        let commands = encoder.finish().expect("recording succeeded");
23399        Frame {
23400            imported,
23401            pool,
23402            commands,
23403        }
23404    }
23405
23406    /// A stand-in for the acquired swapchain image the frame normally ends in,
23407    /// at [`TEST_EXTENT`].
23408    fn swapchain_image(device: &dyn Device) -> ImportedImage {
23409        swapchain_image_at(device, TEST_EXTENT)
23410    }
23411
23412    /// The same, at an extent of the caller's choosing.
23413    ///
23414    /// A frame's attachments must all be one size — the graph refuses a pass
23415    /// whose colour target and depth disagree — so a test drawing at anything
23416    /// but [`TEST_EXTENT`] has to import a target of that size too.
23417    pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
23418        let format = Format::Rgba8UnormSrgb;
23419        let image = device
23420            .create_image(&crcbl_hal::ImageDesc {
23421                label: Some("fake swapchain image"),
23422                image_type: crcbl_hal::ImageType::D2,
23423                extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
23424                format,
23425                mip_levels: 1,
23426                samples: 1,
23427                usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
23428            })
23429            .expect("an image");
23430        let view = device
23431            .create_image_view(&crcbl_hal::ImageViewDesc {
23432                label: Some("fake swapchain view"),
23433                image,
23434                view_type: crcbl_hal::ImageViewType::D2,
23435                format,
23436                range: crcbl_hal::ImageSubresourceRange::all(format),
23437            })
23438            .expect("a view");
23439        ForwardRenderer::present_target(image, view, format, extent)
23440    }
23441
23442    /// The spin is a rotation: no scale, no shear, so the cube neither grows
23443    /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
23444    /// picture of one cube.
23445    ///
23446    /// That is also what keeps those goldens insensitive to `mesh.slang`'s
23447    /// `normal_basis`. A matrix with orthonormal rows and a positive
23448    /// determinant is its own cofactor matrix, to within a rounding step, so
23449    /// the vertex stage writes the normals it wrote when it multiplied by the
23450    /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
23451    /// longer requires a caller to be rigid at all.
23452    #[test]
23453    fn the_spin_matrix_stays_rigid() {
23454        for seconds in [0.0f32, 0.5, 3.25, 100.0] {
23455            let model = ForwardRenderer::spin(seconds);
23456            let basis = glam::Mat3::from_mat4(model);
23457            let product = basis * basis.transpose();
23458            for (row, expected) in [
23459                (product.x_axis, Vec3::X),
23460                (product.y_axis, Vec3::Y),
23461                (product.z_axis, Vec3::Z),
23462            ] {
23463                assert!(
23464                    (row - expected).length() < 1e-5,
23465                    "the spin at {seconds}s is not orthonormal: {product:?}"
23466                );
23467            }
23468            assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
23469        }
23470        // And it actually moves.
23471        assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
23472    }
23473
23474    /// The swapchain import says what a swapchain image actually needs, which is
23475    /// the knowledge the hand-written barriers used to carry.
23476    #[test]
23477    fn the_present_target_starts_undefined_and_ends_presentable() {
23478        let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
23479        let image = pool.insert(0).cast();
23480        let view = pool.insert(0).cast();
23481        let imported =
23482            ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
23483        assert_eq!(imported.initial, ResourceState::Undefined);
23484        assert_eq!(imported.final_state, ResourceState::Present);
23485        assert_eq!(imported.extent, (1280, 720));
23486    }
23487
23488    /// The scene target is `Rgba16Float`, and the depth target is the
23489    /// reversed-Z format. Both are locked decisions and both are cheap to pin.
23490    #[test]
23491    fn the_scene_targets_are_hdr_and_reversed_z() {
23492        let color = crate::targets::scene_color((64, 48));
23493        assert_eq!(color.format, Format::Rgba16Float);
23494        assert!(color.format.is_hdr_capable());
23495        assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
23496
23497        let depth = crate::targets::scene_depth((64, 48));
23498        assert_eq!(depth.format, Format::D32Float);
23499        assert_eq!(
23500            DepthStencilState::default().depth_compare,
23501            crcbl_hal::CompareOp::Greater
23502        );
23503    }
23504
23505    /// A sun ten degrees or so above the horizon, and one further round: two
23506    /// atmospheres whose LUTs are nowhere near each other, so a comparison
23507    /// between them cannot pass by the two skies being alike.
23508    ///
23509    /// Spelled as directions rather than as angles for
23510    /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
23511    /// own — and normalised by `Atmosphere::parameters` on the way in.
23512    const MOVED_SUN: Atmosphere = Atmosphere {
23513        sun_direction: Vec3::new(1.0, 0.2, 0.0),
23514        ..Atmosphere::NOON
23515    };
23516
23517    /// [`MOVED_SUN`] again, further round and lower.
23518    const MOVED_AGAIN: Atmosphere = Atmosphere {
23519        sun_direction: Vec3::new(1.0, 0.05, 0.5),
23520        ..Atmosphere::NOON
23521    };
23522
23523    /// Frames the striped march takes to cross the LUT.
23524    const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
23525
23526    /// The bytes the most recent sky-view LUT upload put on the device.
23527    ///
23528    /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
23529    /// that has an atmosphere, into the slot that frame is using — so the last
23530    /// write to any of the ring's buffers is the LUT the frame just recorded
23531    /// would draw. That is the only place the presented LUT is observable: the
23532    /// renderer's own copy is what a test could assert about instead, and it
23533    /// would then be asserting about the thing rather than about what reached
23534    /// the device.
23535    fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
23536        recorder
23537            .events()
23538            .into_iter()
23539            .rev()
23540            .find_map(|event| match event {
23541                crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
23542                    recorder.buffer_bytes(buffer)
23543                }
23544                _ => None,
23545            })
23546            .expect("a frame with an atmosphere uploads a sky-view LUT")
23547    }
23548
23549    /// A renderer with an atmosphere set and its first LUT marched, and the
23550    /// buffers that LUT reaches the device through.
23551    ///
23552    /// The three tests below all start here: the first march is synchronous, so
23553    /// one frame is what it takes to have a sky to be stale about.
23554    fn with_marched_atmosphere(
23555        device: &dyn Device,
23556        queue: QueueHandle,
23557        atmosphere: Atmosphere,
23558    ) -> (ForwardRenderer, Vec<BufferHandle>) {
23559        let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
23560            .expect("the null backend builds a renderer");
23561        let luts = renderer.primary.sky_pass.luts().to_vec();
23562        renderer.set_atmosphere(Some(atmosphere));
23563        atmosphere_frame(&mut renderer, device);
23564        (renderer, luts)
23565    }
23566
23567    /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
23568    /// is what writes the blocks and steps the march.
23569    fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
23570        renderer
23571            .begin_frame(
23572                device,
23573                &Camera::default(),
23574                &DirectionalLight::default(),
23575                (64, 48),
23576            )
23577            .expect("the frame's blocks are written");
23578    }
23579
23580    /// A sun that moved is marched a stripe per frame, and every frame until it
23581    /// is finished still uploads the LUT of the sun before it.
23582    ///
23583    /// **The amortisation, from the device's side.** Before this, one
23584    /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
23585    /// tens of milliseconds of CPU in every frame. The claim now is three
23586    /// things at once, and only the middle one is about performance: the march
23587    /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
23588    /// device meanwhile are the *previous* sun's rather than a half-marched
23589    /// sky, and the new sun's LUT arrives whole on the frame the march ends.
23590    ///
23591    /// **And the aerial-perspective LUT keeps the same pace**: it rides the
23592    /// same stripes, so it too uploads the previous sun's air on every frame
23593    /// of the march and the new sun's on the frame that ends it — the lag
23594    /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
23595    /// reach the device a sun apart.
23596    #[test]
23597    fn a_moving_sun_is_marched_a_stripe_per_frame() {
23598        let (recorder, device, queue) = open();
23599        let (mut renderer, luts) =
23600            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23601        let aerials = renderer.primary.sky_pass.aerials().to_vec();
23602
23603        let before_view = SkyView::build(&Atmosphere::NOON.parameters());
23604        let after_view = SkyView::build(&MOVED_SUN.parameters());
23605        let before = before_view.rows();
23606        let after = after_view.rows();
23607        let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
23608        assert_ne!(
23609            before, after,
23610            "the two suns march to the same LUT, so nothing below distinguishes them"
23611        );
23612        assert_ne!(
23613            air_before, air_after,
23614            "the two suns march to the same air, so nothing below distinguishes them"
23615        );
23616        assert!(
23617            renderer.sky_view_build.is_none(),
23618            "the first march is synchronous, so no build is left in flight"
23619        );
23620        assert_eq!(
23621            presented_lut(&recorder, &luts),
23622            before,
23623            "the frame after `set_atmosphere` did not upload that sun's LUT"
23624        );
23625        assert_eq!(
23626            presented_lut(&recorder, &aerials),
23627            air_before,
23628            "the frame after `set_atmosphere` did not upload that sun's air"
23629        );
23630
23631        renderer.set_atmosphere(Some(MOVED_SUN));
23632        for step in 1..MARCH_FRAMES {
23633            atmosphere_frame(&mut renderer, device.as_ref());
23634            assert_eq!(
23635                renderer
23636                    .sky_view_build
23637                    .as_ref()
23638                    .map(SkyViewBuild::rows_done),
23639                Some(step * SKY_VIEW_BUILD_ROWS),
23640                "frame {step} of the march is not a stripe further along than frame {} was",
23641                step - 1
23642            );
23643            assert_eq!(
23644                presented_lut(&recorder, &luts),
23645                before,
23646                "frame {step} of the march uploaded something other than the sky it is still \
23647                 drawing"
23648            );
23649            assert_eq!(
23650                presented_lut(&recorder, &aerials),
23651                air_before,
23652                "frame {step} of the march uploaded air other than the sky it is still drawing's"
23653            );
23654        }
23655
23656        atmosphere_frame(&mut renderer, device.as_ref());
23657        assert!(
23658            renderer.sky_view_build.is_none(),
23659            "the march did not finish in the frames its own stripe says it takes"
23660        );
23661        assert_eq!(
23662            presented_lut(&recorder, &luts),
23663            after,
23664            "the frame that finished the march did not upload the new sun's LUT"
23665        );
23666        assert_eq!(
23667            presented_lut(&recorder, &aerials),
23668            air_after,
23669            "the frame that finished the march did not upload the new sun's air"
23670        );
23671    }
23672
23673    /// An atmosphere adds the composite for its air whether or not the fog
23674    /// effect is on, and the block tells the composite which halves to read.
23675    ///
23676    /// **The seam between the two volumes, on the renderer's side.** Three
23677    /// frames of one renderer: no atmosphere and the default stack, which has
23678    /// no fog effect in it — no composite at all, the frame drawn before the
23679    /// air existed; an atmosphere and the same stack — the composite and
23680    /// nothing of the column, and a block saying so; and an atmosphere with
23681    /// the fog effect forced on — all three passes, and a block saying both.
23682    /// The counters are held to the frame on the second: the composite is a
23683    /// full-screen triangle, and a frame that drew it and did not count it
23684    /// makes the debug panel's row disagree with the frame by one.
23685    #[test]
23686    fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
23687        let _blurs = ssao_blur_switch();
23688        let (recorder, device, queue) = open();
23689        let device = device.as_ref();
23690        let mut renderer =
23691            ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
23692        let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
23693            .map(|frame| renderer.primary.volumetric.buffers(frame).params)
23694            .collect();
23695        let imported = swapchain_image(device);
23696        let mut pool = crate::TransientPool::new();
23697        let block = |recorder: &Recorder| {
23698            let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
23699                presented_lut(recorder, &blocks)
23700                    .try_into()
23701                    .expect("the block is its own size");
23702            crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
23703        };
23704        let column = ["volumetric-scatter", "volumetric-integrate"];
23705
23706        let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23707        let before = renderer.counters();
23708        assert!(
23709            !bare.iter().any(|pass| pass.starts_with("volumetric")),
23710            "a frame with neither fog nor an atmosphere records {bare:?}"
23711        );
23712        let off = block(&recorder);
23713        assert_eq!(
23714            off.aerial_params,
23715            [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
23716            "a frame with no atmosphere writes something into the aerial row"
23717        );
23718
23719        renderer.set_atmosphere(Some(Atmosphere::NOON));
23720        let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23721        assert!(
23722            air.iter().any(|pass| pass == "volumetric-composite")
23723                && !air.iter().any(|pass| column.contains(&pass.as_str())),
23724            "an atmosphere with the fog effect off records {air:?}, where it should composite its \
23725             air and run nothing of the column"
23726        );
23727        let after = renderer.counters();
23728        assert_eq!(
23729            after.draws - before.draws,
23730            (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
23731            "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
23732        );
23733        let aerial_only = block(&recorder);
23734        let sun = Atmosphere::NOON.parameters().sun_direction;
23735        assert_eq!(
23736            aerial_only.aerial_params,
23737            [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
23738            "the aerial row does not carry the atmosphere's sun and its switch"
23739        );
23740        assert_eq!(
23741            aerial_only.fog_params[3],
23742            crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
23743            "the block tells the composite to read a column no pass filled"
23744        );
23745
23746        renderer.set_effect_request(EffectRequest {
23747            programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
23748            ..EffectRequest::default()
23749        });
23750        let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
23751        assert!(
23752            column
23753                .iter()
23754                .chain(&["volumetric-composite"])
23755                .all(|name| both.iter().any(|pass| pass == name)),
23756            "an atmosphere with the fog effect on records {both:?}"
23757        );
23758        assert_eq!(
23759            block(&recorder).fog_params[3],
23760            crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
23761            "the block tells the composite to skip a column the frame filled"
23762        );
23763
23764        renderer.destroy(device);
23765        pool.destroy(device);
23766        device.destroy_image_view(imported.view);
23767        device.destroy_image(imported.image);
23768        recorder.assert_valid();
23769    }
23770
23771    /// A sun that moves while a march is in flight restarts it from row zero.
23772    ///
23773    /// **The decision `refresh_sky_view` writes down**, and the reason a sun
23774    /// that moves every frame shows a frozen sky rather than a stuttering one:
23775    /// finishing a march for a sun that has already moved would swap in a LUT
23776    /// that is wrong on arrival. What is observable is the progress counter —
23777    /// a build that kept its rows would be two stripes along here rather than
23778    /// one — and the sun the build in flight names.
23779    #[test]
23780    fn a_sun_that_moves_mid_march_restarts_it() {
23781        let (recorder, device, queue) = open();
23782        let (mut renderer, luts) =
23783            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23784        let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
23785
23786        renderer.set_atmosphere(Some(MOVED_SUN));
23787        atmosphere_frame(&mut renderer, device.as_ref());
23788        atmosphere_frame(&mut renderer, device.as_ref());
23789        assert_eq!(
23790            renderer
23791                .sky_view_build
23792                .as_ref()
23793                .map(SkyViewBuild::rows_done),
23794            Some(2 * SKY_VIEW_BUILD_ROWS),
23795            "two frames of marching did not leave two stripes marched"
23796        );
23797
23798        renderer.set_atmosphere(Some(MOVED_AGAIN));
23799        atmosphere_frame(&mut renderer, device.as_ref());
23800        assert_eq!(
23801            renderer
23802                .sky_view_build
23803                .as_ref()
23804                .map(SkyViewBuild::rows_done),
23805            Some(SKY_VIEW_BUILD_ROWS),
23806            "the march kept the rows it had marched for a sun that has since moved"
23807        );
23808        assert_eq!(
23809            renderer
23810                .sky_view_build
23811                .as_ref()
23812                .map(SkyViewBuild::atmosphere),
23813            Some(MOVED_AGAIN.parameters()),
23814            "the build in flight is marching a sun the caller has moved away from"
23815        );
23816        assert_eq!(
23817            presented_lut(&recorder, &luts),
23818            before,
23819            "a restart uploaded something other than the last LUT that finished"
23820        );
23821    }
23822
23823    /// A frame whose sun has not moved marches nothing and re-takes neither
23824    /// projection.
23825    ///
23826    /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
23827    /// be taken from the LUT in every `begin_frame`, which is host work a still
23828    /// sun has no reason to pay. Both are now taken once, where the march
23829    /// finishes — so a sentinel written over the cached gradient survives a
23830    /// frame if and only if that frame took neither the march nor the
23831    /// projection again, and the same sentinel's bytes turn up in what the
23832    /// frame wrote, which is what says the cache is the thing being read.
23833    #[test]
23834    fn a_still_sun_marches_nothing_and_reprojects_nothing() {
23835        let (recorder, device, queue) = open();
23836        let (mut renderer, _luts) =
23837            with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
23838
23839        let sentinel = crcbl_shaders::sky::SkyGradient {
23840            zenith: [0.125, 0.25, 0.375],
23841            horizon: [0.5, 0.625, 0.75],
23842            ground: [0.875, 1.125, 1.375],
23843        };
23844        let presented = renderer
23845            .sky_view
23846            .as_mut()
23847            .expect("the first frame marched a LUT");
23848        assert_ne!(
23849            presented.gradient, sentinel,
23850            "the sentinel is what the real projection already returns, so it proves nothing"
23851        );
23852        presented.gradient = sentinel;
23853
23854        let before = recorder.events().len();
23855        atmosphere_frame(&mut renderer, device.as_ref());
23856        assert_eq!(
23857            renderer
23858                .sky_view
23859                .as_ref()
23860                .map(|presented| presented.gradient),
23861            Some(sentinel),
23862            "a frame under a sun that has not moved re-took the projections"
23863        );
23864        assert!(
23865            renderer.sky_view_build.is_none(),
23866            "a frame under a sun that has not moved started a march"
23867        );
23868
23869        let wanted: Vec<u8> = sentinel
23870            .rows()
23871            .iter()
23872            .flatten()
23873            .flat_map(|value| value.to_le_bytes())
23874            .collect();
23875        let used = recorder
23876            .events()
23877            .into_iter()
23878            .skip(before)
23879            .filter_map(|event| match event {
23880                crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
23881                    recorder.buffer_bytes(buffer)
23882                }
23883                _ => None,
23884            })
23885            .any(|bytes| {
23886                bytes
23887                    .windows(wanted.len())
23888                    .any(|window| window == wanted.as_slice())
23889            });
23890        assert!(
23891            used,
23892            "the cached gradient reached no block this frame wrote, so the frame is not reading \
23893             the cache at all"
23894        );
23895    }
23896
23897    /// **The frame block's ambient rows carry the marched LUT's own L1
23898    /// projection**, and not the three-band fit's.
23899    ///
23900    /// `begin_frame` writes [`PresentedSky::irradiance`] into
23901    /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
23902    /// test nothing read them back. The only reader of those rows is arithmetic
23903    /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
23904    /// surface under an atmosphere — `crcbl`'s
23905    /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
23906    /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
23907    /// instead, the three-band fit's projection rather than the LUT's, was a
23908    /// swap `docs/backlog.md` recorded passing every suite in the tree on
23909    /// 2026-09-06.
23910    ///
23911    /// **Both halves are needed and the second is the sabotage's.** The rows
23912    /// equalling the LUT's projection is the wiring; the rows *differing* from
23913    /// the fit's is what makes the equality a claim about which projection
23914    /// arrived rather than about two numbers that happen to agree. The
23915    /// `assert_ne` above them is the anti-vacuity: a sun for which the two
23916    /// projections coincide would make this test pass under the swap.
23917    ///
23918    /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
23919    #[test]
23920    fn an_atmosphere_writes_the_luts_own_ambient_term() {
23921        /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
23922        /// puts in the block.
23923        fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
23924            [probe.sh_r, probe.sh_g, probe.sh_b]
23925                .iter()
23926                .flatten()
23927                .flat_map(|value| value.to_le_bytes())
23928                .collect()
23929        }
23930
23931        let (recorder, device, queue) = open();
23932        let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
23933
23934        let view = SkyView::build(&MOVED_SUN.parameters());
23935        let marched = rows(&view.irradiance());
23936        let fitted = rows(&view.gradient_fit().irradiance());
23937        assert_ne!(
23938            marched, fitted,
23939            "this sun's LUT and its three-band fit project to the same rows, so a block \
23940             carrying either would satisfy the check below and the swap it exists for would \
23941             pass"
23942        );
23943
23944        let block = recorder
23945            .buffer_bytes(renderer.primary.uniforms[renderer.frame])
23946            .expect("a frame with an atmosphere writes its uniform block");
23947        let at = mesh::SKY_SH_R_OFFSET;
23948        assert_eq!(
23949            &block[at..at + marched.len()],
23950            marched.as_slice(),
23951            "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
23952             marched, so the ambient term the fragment stage evaluates comes from somewhere \
23953             else"
23954        );
23955        assert_ne!(
23956            &block[at..at + fitted.len()],
23957            fitted.as_slice(),
23958            "the frame block's sky rows are the gradient fit's projection — the LUT was \
23959             marched and then thrown away for the three-band approximation of it"
23960        );
23961
23962        renderer.destroy(device.as_ref());
23963    }
23964}