crcbl_render/forward.rs
1//! The frame milestones 3, 4 and 5 draw: a lit mesh into an HDR target, then a
2//! tonemap into whatever the caller is presenting to.
3//!
4//! ```text
5//! ┌ cull ───────────┐ ┌ draw-args ──────┐ ┌ forward ──────────┐ ┌ tonemap ──────┐
6//! │ instances ─────▶│ │ visible ───────▶│ │ scene-color Clear │ │ reads it │
7//! │ visible list │ │ per-bucket runs │ │ scene-depth Clear │ │ writes the │
8//! │ + a GPU count │ │ + indirect args │ │ one indirect call │ │ target │
9//! │ │ │ + a draw count │ │ per bucket │ │ │
10//! └─────────────────┘ └─────────────────┘ └───────────────────┘ └───────────────┘
11//! ```
12//!
13//! Two passes and one graph. Everything that makes them ordered, everything that
14//! transitions `scene-color` from a colour attachment into a sampled texture,
15//! and everything that returns the target to [`ResourceState::Present`] is
16//! computed by [`crate::graph`] — **there is not one hand-written barrier in
17//! this file, or anywhere above the seam.**
18//!
19//! # Scope
20//!
21//! Stage 2's ladder rungs 3–5, and nothing beyond:
22//!
23//! * **3** — depth-tested spinning mesh, perspective camera in a uniform buffer.
24//! * **4** — one directional light (in `mesh.slang`). The rung's own wording is
25//! "Lambert+Blinn"; what shipped is Lambert plus a Cook-Torrance GGX lobe over
26//! a glTF metallic-roughness row, which is that rung's "real material model"
27//! arriving early rather than a different rung.
28//! * **5** — orthographic mode, which is [`Camera::projection`] and *nothing
29//! else*: no second pipeline, no branch in this file, no shader permutation.
30//!
31//! Explicitly not here: bindless at scale (P3), shadows and real post (P7),
32//! material authoring (topic 37), asset loading (P9). The mesh is a constant in
33//! `crcbl-shaders` because rung 3 says "hardcoded cube/sphere".
34//!
35//! What *is* here since 2026-08 is [`crate::material_table`]: §3.2's material
36//! table, holding **both** halves of "texture indices + factors", with
37//! [`mesh::GpuInstance::material`] selecting a row. Three rows are resident and
38//! two of them exist to be seen: [`scene::DEMO_TINTED`] differs from the default
39//! row in its factor and its roughness, and [`scene::DEMO_TEXTURED`] in its
40//! base-colour page layer alone. Which rows those are is [`crate::scene::demo`]'s
41//! to say, and so is why the shading factor rides on that row rather than on a
42//! fourth.
43//!
44//! The page is the texture side, and it is one `D2Array` image rather than an
45//! array of descriptors — `BindingModel::ArrayPages` rather than `Bindless`.
46//! That is the whole of the binding-model decision §3.2 leaves open, taken
47//! here because a layer index needs nothing of a device where a descriptor
48//! array needs `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws. So
49//! there is one lookup, one layout and one artifact rather than a permutation,
50//! and a device that reports the feature runs the same declaration. What
51//! bindless buys later is capacity, not a second path — see [`crate::scene::PageDesc`]
52//! and the layout entry for binding 7.
53//!
54//! What *was* on that list until 2026-08 is GPU culling and the indirect draw
55//! count, and both are here now: [`crate::draw_gen`] runs `cull.slang` and
56//! `draw_gen.slang` in front of this pass, and the draws below come out of the
57//! arguments they wrote. See that module for what a bucket is and why the
58//! arguments are per bucket rather than per surviving instance.
59//!
60//! # The CPU records a fixed number of draws
61//!
62//! One per bucket, whatever the scene holds — topic 03's
63//! headline goal, "10 objects and 10,000 objects record roughly the same
64//! commands". Adding an object is an instance in the pool and nothing else;
65//! removing one is [`InstancePool::remove`] and nothing else. Neither changes a
66//! single command this file records, because what varies — how many instances a
67//! bucket draws, and which — is written by a compute pass into a buffer the
68//! draw reads.
69//!
70//! Which *call* those draws are is the one branch: [`GeometryPath::IndirectCount`]
71//! takes the count from GPU memory too, and [`GeometryPath::IndirectPerBatch`] —
72//! Metal, whose API has multi-draw-indirect and no GPU-side count — reads each
73//! bucket's one argument structure unconditionally and leans on its instance
74//! count being zero.
75//!
76//! What *is* here, since 2026-08, is [`crate::mesh_pool`]: the cube is the first
77//! resident of the global vertex and index pools rather than owning two buffers
78//! of its own, so it is `{base_vertex, base_index, index_count}` like everything
79//! P7 will draw. Same geometry, different residence.
80//!
81//! And since the same month, [`crate::instance_pool`]: the cube's model matrix
82//! is a `GpuInstance` in a storage buffer rather than a field of the frame's
83//! uniform block, uploaded by delta. It holds the same matrix `begin_frame` used
84//! to write into the uniform, which is why the golden images did not move.
85//!
86//! # A second resident, and how it finds its own vertices
87//!
88//! A pool whose only mesh is at base vertex 0 cannot tell a base vertex that
89//! works from one that is silently cancelled out, and `mesh.slang`'s header
90//! shows the four targets disagreeing about exactly that: the SPIR-V subtracts
91//! `BaseVertex` back out of `SV_VertexID`, so the pool's base — passed through
92//! `draw_indexed`'s own argument — reached the shader as zero, while WGSL and
93//! MSL kept it. The same disagreement covers `SV_InstanceID`, which is what
94//! [`crate::sprite_pass`] paid for first.
95//!
96//! So **every draw this pass records passes zero for both of its bases**, and
97//! the real ones arrive as data. The base vertex comes from
98//! [`MeshPool`]'s mesh table, indexed by the drawn instance's
99//! [`mesh::GpuInstance::mesh`] — so it is resolved per instance, by the GPU,
100//! and one draw could cover instances of different meshes. The instance comes
101//! from the bucket's run of survivors, walked with `SV_InstanceID`, which counts
102//! from zero on every target *because* the first instance is zero. All a draw
103//! says for itself is which word holds its run's start — the start is the GPU's,
104//! per frame — in a [`mesh::DrawConstants`] block reached through a dynamic
105//! offset: one block per bucket, written once at build.
106//!
107//! That is what makes the pool's *second* resident,
108//! [`mesh::pyramid_vertices`], draw its own geometry rather than the cube's.
109//!
110//! The pyramid is in the pools from `new` but has no *instance* until a caller
111//! places one with [`ForwardRenderer::add_instance`] — an instance in the pool
112//! is an object in the scene now that culling decides what draws. The frame the
113//! samples draw is still the cube alone, which is why their golden images did
114//! not move either.
115//!
116//! # A third resident, and how it finds its own clusters
117//!
118//! The same argument one layer down. A mesh that fits **one** cluster cannot
119//! tell a per-cluster offset that works from one that is lost, and the cube and
120//! the pyramid fit one each — 24 and 16 vertices against a bound of 64. So the
121//! pool's third resident is [`mesh::open_box_vertices`], five clusters of one
122//! flat face each, four of them at a `Meshlet::vertex_offset` that is not zero.
123//! It is [`crate::cluster_pool`]'s counterpart to what the pyramid is for
124//! [`crate::mesh_pool`], and it is what §3.5's per-cluster culling will need
125//! before a surviving-cluster count can mean anything.
126//!
127//! It arrives on the pyramid's terms exactly: resident from `new`, in the scene
128//! only when a caller places it, so no golden moved for it either.
129//!
130//! # Uniforms are a ring, and they have to be
131//!
132//! The camera spins, so the uniform block is rewritten every frame — and the
133//! previous frame may still be reading it. One buffer would be a
134//! read-after-write hazard *across* submissions, which is precisely what
135//! `CRCBL_VK_SYNC_VALIDATION=1` exists to find and precisely what
136//! stage 2 called its headline risk. So there
137//! is one uniform buffer and one bind group per frame in flight, and
138//! [`ForwardRenderer::begin_frame`] rotates them.
139
140use crcbl_hal::{
141 BindGroupDesc, BindGroupEntry, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutEntry,
142 BindGroupLayoutHandle, BindingFlags, BindingKind, BindingResource, BufferDesc, BufferHandle,
143 BufferUsage, ColorTargetState, CompareOp, CullMode, DepthBias, DepthStencilState, Device,
144 DeviceCaps, Features, FilterMode, Format, GeometryPath, GraphicsPipelineDesc,
145 GraphicsPipelineHandle, HalError, ImageDesc, ImageHandle, ImageSubresourceRange, ImageType,
146 ImageUsage, ImageViewDesc, ImageViewHandle, ImageViewType, LoadOp, MemoryLocation,
147 MeshPipelineDesc, MultisampleState, PipelineLayoutDesc, PipelineLayoutHandle, PolygonMode,
148 PrimitiveState, QueueHandle, Rect2d, ResourceState, SampleType, SamplerAddressMode,
149 SamplerDesc, SamplerHandle, ShaderEntry, ShaderModuleDesc, ShaderModuleHandle, ShaderStages,
150 StoreOp, Viewport, check_portable_storage_buffers,
151};
152use crcbl_shaders::meshlet::MeshClusters;
153use crcbl_shaders::probe_gather::PunctualProducer;
154use crcbl_shaders::{
155 MESH, MESH_CLUSTER, Stage, TONEMAP, contact_shadows, dfg, level_select, ltc, mesh, ssao, ssr,
156 tonemap,
157};
158use glam::{Mat4, Quat, Vec3};
159use std::sync::Arc;
160use std::sync::atomic::{AtomicU64, Ordering};
161
162use crate::camera::{Atmosphere, Camera, DirectionalLight, Fog, Sky};
163use crate::cluster_pool::{ClusterPool, ClusterRange, PooledMesh};
164use crate::contact_shadows::ContactShadows;
165use crate::counters::FrameCounters;
166use crate::cull::Frustum;
167use crate::cull_stats::CullStatsRing;
168use crate::debug_draw::DebugDraw;
169use crate::draw_gen::{DrawGen, DrawGenDesc, FrameCull, GeneratedDraws};
170use crate::effects::{EffectRequest, RenderEffects};
171use crate::graph::{
172 BufferId, ImageId, ImportedBuffer, ImportedImage, InitialClaim, PassBuilder, RenderGraph,
173};
174// Renamed on the way in, because [`crate::light_grid::Grid`] already holds the
175// bare name here and means the froxel grid — the collision [`crate::grid`]'s
176// header predicted.
177use crate::atlas_view::AtlasView;
178use crate::bloom::Bloom;
179use crate::cmaa2::Cmaa2;
180use crate::exposure::{Exposure, ExposureAdaptation, ExposureBuffers};
181use crate::fxaa::Fxaa;
182use crate::grass::{Grass, GrassFrame, GrassScene};
183use crate::grid::{Grid as GroundGrid, GridStyle};
184use crate::hiz::Hiz;
185use crate::instance_pool::{InstanceHandle, InstancePool, InstancePoolDesc, InstancePoolError};
186use crate::light::{Light, sun_row};
187use crate::light_grid::{FROXEL_CAPACITY, FrameView, Grid, LightGrid, LightGridDesc};
188use crate::material_table::{MaterialTable, MaterialTableDesc};
189use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolDesc, MeshPoolError, MeshUpload};
190use crate::occlusion_cull::{OcclusionCulling, OcclusionPyramid};
191use crate::probe::{ProbeTable, ProbeTableDesc};
192use crate::probe_gather::{ProbeGather, ProbeGatherDesc, RsmImages, RsmTargets};
193use crate::rsm;
194use crate::scene::{self, Geometry, InstanceDesc, PageKind, ProbeUpdate, SceneDesc};
195use crate::shadow::{self, Cascades};
196use crate::skinning::{SkinRange, SkinnedMesh, Skinning, SkinningError};
197use crate::sky_pass::SkyPass;
198use crate::ssao::{Ssao, cached_group};
199use crate::ssr::{Ssr, SsrEnvironment, SsrImages};
200use crate::stack::CameraStack;
201use crate::texture::{
202 UploadedTexture, upload_texture, upload_texture_layers, upload_texture_mip_layers,
203};
204use crate::transient::TransientPool;
205use crate::upscale::Upscale;
206use crate::volumetric::{FroxelBuffers, Medium, Volumetric, VolumetricImages, VolumetricReads};
207use crate::water::{Water, WaterBodies, WaterFrame, WaterImages, WaterInputs};
208use crcbl_shaders::atmosphere::{SKY_VIEW_BUILD_ROWS, SkyView, SkyViewBuild};
209
210mod bucket_draws;
211mod frame_prepare;
212mod pages;
213mod shadow_inputs;
214mod view;
215
216use pages::{PageBindings, RetiredPage, upload_page};
217
218pub use shadow_inputs::{FRAME_UNIFORMS_READERS, UniformsField, UniformsReader};
219
220use bucket_draws::{BucketDraws, EmitTail, RegionStep};
221
222use view::{FramePasses, Overlays, TonemapPipeline, View, ViewInputs, ViewOutput};
223pub use view::{
224 FrameTargets, MAX_VIEWS, ViewBackground, ViewDesc, ViewId, ViewLighting, ViewMask, ViewTarget,
225};
226
227/// The clear behind the mesh, in **linear** light.
228///
229/// The scene target is `Rgba16Float`, so this is a linear value and the tonemap
230/// pass plus the swapchain's sRGB encode are what turn it into pixels. Writing a
231/// display-referred colour here would come out visibly paler, which is the
232/// classic HDR-pipeline mistake and worth a sentence rather than a surprise.
233pub const SCENE_CLEAR: [f32; 4] = [0.012, 0.016, 0.030, 1.0];
234
235/// How many frames of uniform buffers to keep. Matches the frame loop's
236/// frames-in-flight.
237pub const FRAMES_IN_FLIGHT: usize = 2;
238
239// The UI pass this renderer draws its HUD through keeps a ring of its own,
240// built at `crcbl_frame`'s default depth; held equal here, where both are in
241// scope, so the HUD cannot fall a frame behind the ring it shares a submit with.
242const _: () = assert!(crcbl_frame::ui_pass::FRAMES_IN_FLIGHT == FRAMES_IN_FLIGHT);
243
244/// The darkest exposure [`ForwardRenderer::set_exposure`] will accept: **five
245/// stops below** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`].
246///
247/// The floor exists so that the control cannot be driven somewhere it cannot be
248/// driven back from. The operator clamps its own *output* to `[0, 1]`, so an
249/// unclamped input has two dead ends: far enough down and every pixel rounds to
250/// the same black byte, far enough up and every pixel saturates to white — and
251/// in both the picture stops carrying the information a user would need to see
252/// which way to go. Five stops is well inside either: it is a sixteenth of the
253/// scene's brightness, dark but plainly still a picture, and it is the range a
254/// camera's exposure-compensation dial covers.
255pub const EXPOSURE_MIN: f32 = 1.0 / 32.0;
256
257/// The brightest exposure [`ForwardRenderer::set_exposure`] will accept: **five
258/// stops above** [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`], for
259/// [`EXPOSURE_MIN`]'s reason.
260pub const EXPOSURE_MAX: f32 = 32.0;
261
262/// The default has to be reachable from both ends of the range, or a control
263/// that steps by a ratio starts somewhere it can only leave in one direction.
264const _: () = assert!(
265 EXPOSURE_MIN > 0.0
266 && EXPOSURE_MIN < crcbl_shaders::tonemap::DEFAULT_EXPOSURE
267 && EXPOSURE_MAX > crcbl_shaders::tonemap::DEFAULT_EXPOSURE
268);
269
270/// The format the frame's depth buffer is created with, taken from the
271/// description that creates it rather than written down a second time.
272///
273/// Read by [`ForwardRenderer::set_ground_grid`], whose pipeline is built for a
274/// depth attachment before there is a frame to ask. The extent is irrelevant to
275/// a format, which is why any is passed.
276pub(crate) const SCENE_DEPTH_FORMAT: Format = crate::targets::scene_depth((1, 1)).format;
277
278/// The format the frame's HDR scene target is created with, taken from the
279/// description that creates it rather than written down a second time.
280///
281/// Read by [`crate::debug_draw`], whose pipeline blends into whichever image the
282/// chain of HDR passes ended with — every one of them is a
283/// [`crate::targets::scene_color`]. The extent is irrelevant to a format,
284/// which is why any is passed.
285pub(crate) const SCENE_COLOR_FORMAT: Format = crate::targets::scene_color((1, 1)).format;
286
287/// The format §3.2's base-colour page is created with.
288///
289/// **`Rgba8UnormSrgb`, and that is the colour-space decision** — the argument
290/// for it is at the `upload_texture_mip_layers` call inside
291/// [`ForwardRenderer::with_scene`]. Named rather than spelled twice because
292/// [`ForwardRenderer::base_color_page_import`] has to declare the same format
293/// the image was created with, and a barrier naming a format the image is not in
294/// picks the wrong aspects.
295const BASE_COLOR_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
296
297/// The format topic 43 §2's **normal** page is
298/// created with.
299///
300/// **`Rgba8Unorm`, and the missing `Srgb` is the whole decision.**
301/// Topic 44's rung 2 argues it: a base-colour texel is a
302/// colour and glTF defines it as sRGB-encoded, so the format above is what makes
303/// the sampler decode it; a normal texel is a *number* — three components of a
304/// direction, stored as `n * 0.5 + 0.5` — and pushing it through the sRGB
305/// transfer curve is wrong by a gamma. What that looks like is not an error but
306/// a surface that leans further off vertical than the author drew, which is why
307/// the mistake survives review everywhere it is made.
308///
309/// `the_page_formats_split_colour_from_number` is the whole guard, and it is
310/// worth having because the four constants sit a few lines apart and the wrong
311/// one compiles.
312const NORMAL_PAGE_FORMAT: Format = Format::Rgba8Unorm;
313
314/// The format topic 43 §2's **metallic-roughness-
315/// occlusion** page is created with.
316///
317/// **`Rgba8Unorm`, and the missing `Srgb` is the same decision
318/// [`NORMAL_PAGE_FORMAT`] argues.** An occlusion, a roughness and a metalness
319/// are numbers rather than colours — glTF 2.0 §3.9.2 and §3.9.5 define them as
320/// linear factors — and a surface shaded through an sRGB decode of them is
321/// smoother and shinier than the author drew, which is a failure that survives
322/// review because it looks like a choice.
323///
324/// A separate constant from [`NORMAL_PAGE_FORMAT`] rather than a reuse of it,
325/// for [`LTC_SIZE_U32`]'s reason: the two stand for different facts, and a day
326/// one of them wanted a different format should be an edit here rather than a
327/// search for which callers of a shared name meant which page.
328const MRO_PAGE_FORMAT: Format = Format::Rgba8Unorm;
329
330/// The format topic 43 §2's **emissive** page is
331/// created with.
332///
333/// **`Rgba8UnormSrgb`, and it is the base-colour page's decision rather than
334/// the normal page's.** An emissive texel is a colour: glTF 2.0 §3.9.4 defines
335/// `emissiveTexture` as sRGB-encoded exactly as it defines `baseColorTexture`,
336/// and `GpuMaterial::emissive` beside it is a linear radiance, so the format is
337/// what puts the two in one space before they are multiplied.
338///
339/// A separate constant from [`BASE_COLOR_PAGE_FORMAT`] for the reason above it,
340/// and `the_page_formats_split_colour_from_number` is the guard that the four
341/// do not drift into one another.
342const EMISSIVE_PAGE_FORMAT: Format = Format::Rgba8UnormSrgb;
343
344/// What the renderer needs of a [`PageKind`] to create and fill its image.
345///
346/// Written here rather than in [`crate::scene`] because the two answers are the
347/// device's: the format is the one [`base_color_page_import`] and
348/// [`normal_page_import`] have to declare, and the filter is the one
349/// [`crate::mip`] builds the chain with. A kind added by
350/// topic 43 §2's rung 3 is a new arm in each.
351///
352/// [`base_color_page_import`]: ForwardRenderer::base_color_page_import
353/// [`normal_page_import`]: ForwardRenderer::normal_page_import
354impl PageKind {
355 /// The format this kind's image is created with.
356 ///
357 /// The sRGB in one and its absence in the other is the whole colour-space
358 /// decision — see [`BASE_COLOR_PAGE_FORMAT`] and [`NORMAL_PAGE_FORMAT`],
359 /// which is where each is argued.
360 const fn format(self) -> Format {
361 match self {
362 Self::BaseColor => BASE_COLOR_PAGE_FORMAT,
363 Self::Normal => NORMAL_PAGE_FORMAT,
364 Self::MetallicRoughnessOcclusion => MRO_PAGE_FORMAT,
365 Self::Emissive => EMISSIVE_PAGE_FORMAT,
366 }
367 }
368
369 /// Every mip level below `level0`, built on the host with this kind's own
370 /// filter.
371 ///
372 /// [`crate::mip::normal_chain`] averages the decoded vectors plainly and
373 /// renormalises, where [`crate::mip::chain`] decodes an sRGB curve and
374 /// weights by alpha. A normal map mipped through the colour filter leans
375 /// further off vertical at every level than the map it was built from, and
376 /// nothing in a frame reports it.
377 fn chain(self, level0: &[u8], extent: u32) -> Vec<Vec<u8>> {
378 match self {
379 Self::BaseColor | Self::Emissive => crate::mip::chain(level0, extent),
380 Self::Normal => crate::mip::normal_chain(level0, extent),
381 Self::MetallicRoughnessOcclusion => crate::mip::linear_chain(level0, extent),
382 }
383 }
384
385 /// The device label this kind's image is created under.
386 const fn upload_label(self) -> &'static str {
387 match self {
388 Self::BaseColor => "material base colour",
389 Self::Normal => "material normals",
390 Self::MetallicRoughnessOcclusion => "material metallic-roughness-occlusion",
391 Self::Emissive => "material emissive",
392 }
393 }
394}
395
396/// The one texel a page **nothing names** is created with.
397///
398/// [`crate::texture::upload_texture_mip_layers`] refuses a zero-layer image, and
399/// every bind group of the mesh layout has to fill both page bindings whether or
400/// not the description carried either page — so a [`PageKind`] with no layers
401/// gets a 1×1 single-layer image in its own format instead of an `extent²` one
402/// nobody samples. That is the whole of what row (d) bought back:
403/// `apps/alcove`, `apps/sundial` and `apps/quarry` name no page at all, and
404/// every scene in the tree that has no normal map used to carry a full neutral
405/// layer and a third again for its chain.
406///
407/// **Magenta, and it is never sampled for its value.** A material naming no page
408/// carries [`GpuMaterial::NO_PAGE`](mesh::GpuMaterial::NO_PAGE):
409/// `mesh.slang`'s `base_color_texel` discards the fetch with a select and
410/// returns the literal `1.0`, and `shading_normal_of` returns before it fetches
411/// at all. So nothing should ever read this — and the value is chosen so that if
412/// something does, the frame says so in a colour no lit surface in this engine
413/// produces. White would blend into every untextured surface and black would
414/// read as a shadow; both are failures a golden could pass.
415const PAGE_PLACEHOLDER_TEXEL: [u8; 4] = [0xFF, 0x00, 0xFF, 0xFF];
416
417/// The format the motion-vector target is created with: two channels of half
418/// float, topic 43 §9's third colour attachment.
419///
420/// **Named here rather than in [`crate::targets::motion`]**, on
421/// [`crate::graph`]'s other format-owning descriptions' terms: the description
422/// and
423/// [`MeshModules::COLOR_TARGETS`] have to agree, and the pass that builds the
424/// pipeline is the one that owns the answer.
425///
426/// # The convention the target holds, so a consumer never has to guess it
427///
428/// **Current minus previous, in texture coordinates, `+y` down.** A pass
429/// holding the previous frame reads its history at `uv - motion`, and a surface
430/// travelling right and down the screen has both components positive.
431/// `mesh.slang`'s `motion_vector` is where the mapping is written out and this
432/// is the same sentence on the host side, because the first consumer will read
433/// one of the two and not both.
434///
435/// # Two channels and half float
436///
437/// A motion vector is a screen-space offset and has no third component. Half
438/// float rather than a normalised integer because the value is signed and
439/// unbounded — an object crossing the frame in one frame is a motion past `1.0`
440/// — and because the interesting magnitudes are small: a surface moving a
441/// tenth of a pixel is the case a temporal filter is most sensitive to, and
442/// eight or even sixteen unsigned bits over a `-1..1` range would quantise it
443/// into rest. It is also the format `crcbl_hal::Format::Rg16Float`'s own doc
444/// names motion vectors as the use for.
445pub(crate) const MOTION_FORMAT: Format = Format::Rg16Float;
446
447/// Which picture the colour pass draws instead of the shaded one.
448///
449/// The engine's debug views, as one value rather than as independent booleans,
450/// because they are not independent: every one of them rides in a single lane of
451/// the frame's uniform block and the shaders test the thresholds outermost
452/// first, so a renderer with two of them set draws exactly one.
453/// [`ForwardRenderer::debug_view`] is where that order lives, and this is what it
454/// answers with — so a menu row, a debug panel and the picture cannot disagree
455/// about which view is on.
456///
457/// **The declaration order is not the precedence** — each view was appended as
458/// it arrived, and [`ForwardRenderer::debug_view`] is the one place the order is
459/// decided. The sentinels in
460/// [`FrameUniforms`](crcbl_shaders::mesh::FrameUniforms) ascend with it, though:
461/// see its `HEATMAP_VIEW_ON`, and the shaders test the outermost threshold
462/// first.
463#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
464pub enum DebugView {
465 /// The lit picture. What every frame draws unless a caller asked otherwise.
466 #[default]
467 Shaded,
468 /// Each cluster shaded by the projected screen-space error the LOD
469 /// selection judged it on — [`ForwardRenderer::set_heatmap`].
470 Heatmap,
471 /// Each cluster tinted by the DAG level it was decimated to —
472 /// [`ForwardRenderer::set_lod_view`].
473 LodTint,
474 /// World-space surface normals — [`ForwardRenderer::set_normals_view`].
475 Normals,
476 /// The ambient-occlusion channel alone, as grey —
477 /// [`ForwardRenderer::set_occlusion_view`].
478 AmbientOcclusion,
479 /// The motion vector each fragment wrote, stretched and centred on grey —
480 /// [`ForwardRenderer::set_motion_view`].
481 Motion,
482 /// The bent direction the occlusion channel carries beside its scalar, as
483 /// `n * 0.5 + 0.5` — [`ForwardRenderer::set_bent_normal_view`]. **Wins over
484 /// every other view.**
485 BentNormal,
486 /// The sun's cascades and the lit tiles beside them — the `D32Float` shadow
487 /// atlas itself, letterboxed over the finished frame with a border round
488 /// every occupied slot — [`ForwardRenderer::set_atlas_view`].
489 ///
490 /// **The one view that is a pass rather than a branch in `mesh.slang`**, and
491 /// therefore the one whose lane is the off sentinel: the colour pass draws
492 /// the shaded picture exactly as it always did and `crate::atlas_view`
493 /// replaces it afterwards. That module's header is where the placement is
494 /// argued.
495 ///
496 /// It resolves **below every view above and above [`Self::Cascades`]** — see
497 /// [`ForwardRenderer::debug_view`].
498 ShadowAtlas,
499 /// The shaded picture tinted by the cascade each sun-lit fragment's shadow
500 /// was sampled from, with the cross-fade band drawn as the blend of the two
501 /// — [`ForwardRenderer::set_cascade_view`].
502 ///
503 /// **Loses to every other view**, and it is the only one that does. The views
504 /// above draw something *instead of* the shaded picture; this one draws the
505 /// shaded picture and multiplies it, so there is nothing left for it to
506 /// modulate as soon as one of them is on. See
507 /// [`ForwardRenderer::debug_view`].
508 Cascades,
509}
510
511impl DebugView {
512 /// What a panel row or a summary line calls it.
513 #[must_use]
514 pub const fn label(self) -> &'static str {
515 match self {
516 Self::Shaded => "shaded",
517 Self::Heatmap => "heatmap",
518 Self::LodTint => "lod tint",
519 Self::Normals => "normals",
520 Self::AmbientOcclusion => "ambient occlusion",
521 Self::Motion => "motion",
522 Self::BentNormal => "bent normal",
523 Self::ShadowAtlas => "shadow atlas",
524 Self::Cascades => "cascades",
525 }
526 }
527}
528
529// Mesh-only resources follow the complete common fragment binding range.
530// Metal assigns dense native indices by resource-table order, so inserting a
531// mesh-only buffer before lights/probes would shift the layout away from the
532// independently compiled fragment stage. Sparse logical bindings cost no slots.
533const CLUSTERS_BINDING: u32 = 32;
534const CLUSTER_VERTICES_BINDING: u32 = 33;
535const CLUSTER_CORNERS_BINDING: u32 = 34;
536const CLUSTER_DRAW_ARGS_BINDING: u32 = 35;
537const CLUSTER_CULL_BINDING: u32 = 36;
538const CLUSTER_CULL_STATS_BINDING: u32 = 37;
539const CLUSTER_SELECT_BINDING: u32 = 38;
540const CLUSTER_SELECTION_BINDING: u32 = 39;
541const CLUSTER_GROUP_STATE_BINDING: u32 = 40;
542
543/// The shared fragment shader's shadow atlas slot. Historical logical gaps
544/// remain reserved so the raster shader bindings stay unchanged.
545const SHADOW_ATLAS_BINDING: u32 = 15;
546
547/// The bind-group slot the shadow atlas's **comparison** sampler is bound to.
548const SHADOW_SAMPLER_BINDING: u32 = 16;
549
550/// The bind-group slot the base-colour page is bound to.
551///
552/// Named because [`ForwardRenderer::replace_page`] rewrites it in every group
553/// of the mesh layout, as it does each page's binding — see
554/// `pages::page_binding`.
555const BASE_COLOR_PAGE_BINDING: u32 = 7;
556
557/// The bind-group slot the base-colour page's sampler is bound to.
558///
559/// Named because it is an entry [`ForwardRenderer::set_anisotropy`] rewrites
560/// in every group of the mesh layout: a sampler is a resource a group holds by
561/// handle, so a new sampler is a new group, and the rebuild finds the entry by
562/// this number.
563const PAGE_SAMPLER_BINDING: u32 = 8;
564
565/// The shared fragment shader's light list. Both shader modules declare it
566/// before mesh-only buffers so native buffer index 7 is common to both stages.
567const LIGHT_LIST_BINDING: u32 = 20;
568
569/// The bind-group slot the froxel grid is read through.
570const LIGHT_GRID_BINDING: u32 = 21;
571
572/// The fragment shader's screen-space occlusion texture. Mesh-only additions
573/// are buffers, so this resource does not shift their native argument table.
574const AMBIENT_OCCLUSION_BINDING: u32 = 22;
575
576/// The shared irradiance probe table, native buffer 9 in both shader modules.
577/// `mesh_cluster.slang` mirrors it before its own buffers to preserve the prefix.
578const PROBE_TABLE_BINDING: u32 = 23;
579
580/// The mesh path's packed `DrawGen` table, read for the screen-error heatmap.
581/// Its logical binding stays 24; after the shared fragment buffer prefix it is
582/// native buffer 10. The raster path does not declare this storage buffer.
583const LEVEL_GROUP_TABLE_BINDING: u32 = 24;
584
585/// The bind-group slot the split-sum `DFG` table is fetched through — how much
586/// of the light arriving at a GGX lobe that lobe hands back.
587///
588/// No mirror is needed in `mesh_cluster.slang`: that module adds only buffers
589/// after the shared prefix. The fragment shader's `specular_dfg` remains at
590/// native texture 3, following `ambient_occlusion` at texture 2.
591///
592/// **An image rather than a storage buffer, and that is forced.** The table is
593/// 4096 pairs and a buffer would carry it exactly; but the raster path's layout
594/// is at the WebGPU storage-buffer ceiling in its *vertex* stage, and Slang's
595/// Metal backend materialises every global into every entry point — so a row
596/// bound to the fragment stage alone would be a global the vertex stage names
597/// and nothing fills. See [`crcbl_hal::check_portable_storage_buffers`] and
598/// binding 7's `geometry` visibility.
599const SPECULAR_DFG_BINDING: u32 = 25;
600
601/// The bind-group slot §2's normal page is sampled through.
602///
603/// **Appended past [`SPECULAR_DFG_BINDING`], never inserted**, for
604/// [`PROBE_TABLE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
605/// next index in its Metal argument table by counting the same-table entries of
606/// this layout, and Slang numbers a stage's arguments by declaration order, so
607/// the two agree only while both ascend. No mirror is needed in
608/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
609///
610/// **No sampler of its own.** The page is read through
611/// [`PAGE_SAMPLER_BINDING`]'s sampler, the same trilinear anisotropic one the
612/// base-colour page uses, because it is sampled at the same UV over an image of
613/// the same extent. A second sampler would be a second layout entry, a second
614/// index in Metal's sampler argument table, and a second thing
615/// [`ForwardRenderer::set_anisotropy`] has to rebuild — for a filter that would
616/// be identical.
617const NORMAL_PAGE_BINDING: u32 = 26;
618
619/// The bind-group slot topic 44's rung 5 reads its linearly
620/// transformed cosine table through.
621///
622/// **Appended past [`NORMAL_PAGE_BINDING`], never inserted**, for that
623/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
624/// Metal argument table by counting the same-table entries of this layout, and
625/// Slang numbers a stage's arguments by declaration order, so the two agree only
626/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
627/// needs no mirror there and no index anything already owns moves.
628///
629/// **No sampler**, like the table two rows below it: four `Load`s and a bilinear
630/// blend written out in the shader, because a hardware filter's weights are
631/// fixed-function arithmetic four rasterisers compute independently and these
632/// goldens are compared across all four.
633const LTC_TABLE_BINDING: u32 = 27;
634
635/// The bind-group slot topic 45's contact-shadow channel is
636/// read through.
637///
638/// **Appended past [`LTC_TABLE_BINDING`], never inserted**, for that constant's
639/// reason exactly: `crcbl-mtl` gives a resource the next index in its Metal
640/// argument table by counting the same-table entries of this layout, and Slang
641/// numbers a stage's arguments by declaration order, so the two agree only while
642/// both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it needs
643/// no mirror there and no index anything already owns moves.
644///
645/// **No sampler**, like the occlusion channel: `mesh.slang`'s `contact_at` is a
646/// clamped `Load` at `SV_Position.xy`, and the channel is exactly the size of
647/// the frame on every pass that computed one.
648const CONTACT_SHADOW_BINDING: u32 = 28;
649
650/// The bind-group slot the irradiance probes' per-probe
651/// visibility maps are read through: one `Rg32Float` layer per probe.
652///
653/// **Appended past [`CONTACT_SHADOW_BINDING`], never inserted**, for that
654/// constant's reason exactly: `crcbl-mtl` gives a resource the next index in its
655/// Metal argument table by counting the same-table entries of this layout, and
656/// Slang numbers a stage's arguments by declaration order, so the two agree only
657/// while both ascend. `mesh_cluster.slang` adds only buffers after this texture, so it
658/// needs no mirror there and no index anything already owns moves —
659/// `msl/mesh.metal` puts it at `texture(7)`, the next free index of that table.
660///
661/// **A texture rather than a storage buffer, and that is forced**: the raster
662/// path's vertex stage is already at every storage buffer a WebGPU device
663/// guarantees, which is the same reason [`SPECULAR_DFG_BINDING`] is an image.
664///
665/// **No sampler**, like the occlusion channel and both cooked tables:
666/// `mesh.slang`'s `probe_moments` is four clamped `Load`s and a blend written
667/// out, because a hardware filter's weights are fixed-function arithmetic four
668/// rasterisers compute independently — and because `Rg32Float` is not a
669/// filterable format on WebGPU without an optional feature.
670const PROBE_VISIBILITY_BINDING: u32 = 29;
671
672/// The bind-group slot topic 43 §2's packed
673/// **metallic-roughness-occlusion** page is sampled through.
674///
675/// **Appended past [`PROBE_VISIBILITY_BINDING`], never inserted**, for
676/// [`NORMAL_PAGE_BINDING`]'s reason exactly: `crcbl-mtl` gives a resource the
677/// next index in its Metal argument table by counting the same-table entries of
678/// this layout, and Slang numbers a stage's arguments by declaration order, so
679/// the two agree only while both ascend. No mirror is needed in
680/// `mesh_cluster.slang`, which adds only buffers after the shared prefix.
681///
682/// **No sampler of its own**, for [`NORMAL_PAGE_BINDING`]'s reason: the page is
683/// read at the same UV over an image of the same shape as the base-colour one,
684/// so it goes through [`PAGE_SAMPLER_BINDING`]'s sampler and adds no entry to
685/// Metal's sampler argument table.
686const MRO_PAGE_BINDING: u32 = 30;
687
688/// The bind-group slot topic 43 §2's **emissive**
689/// page is sampled through.
690///
691/// **Appended past [`MRO_PAGE_BINDING`], never inserted**, for that constant's
692/// reason exactly, and it shares [`PAGE_SAMPLER_BINDING`]'s sampler on the same
693/// terms. `mesh_cluster.slang` adds only buffers after these textures, so it needs no
694/// mirror there and no index anything already owns moves.
695const EMISSIVE_PAGE_BINDING: u32 = 31;
696
697/// [`crcbl_shaders::dfg::DFG_SIZE`] as an image extent.
698///
699/// The table is square, and its size is a compile-time constant, so the
700/// conversion belongs here rather than as a fallible one at the upload.
701const DFG_SIZE_U32: u32 = dfg::DFG_SIZE as u32;
702
703/// [`crcbl_shaders::ltc::LTC_SIZE`] as an image extent.
704///
705/// The same number as [`DFG_SIZE_U32`], and a separate constant rather than a
706/// reuse of it: `crcbl_shaders::ltc`'s `the_grid_is_the_dfg_table_s_grid` is
707/// what says the two tables are the same square, and each upload naming its own
708/// module is what would make a day they were not into a compile error here
709/// rather than a stretched image.
710const LTC_SIZE_U32: u32 = ltc::LTC_SIZE as u32;
711
712/// The `Rgba8Unorm` texel that occludes nothing and steers nothing.
713///
714/// What [`ForwardRenderer::ambient_occlusion_placeholder`] holds, and therefore
715/// what `mesh.slang` reads on a frame drawing without
716/// [`RenderEffects::AMBIENT_OCCLUSION`].
717///
718/// **`r` is `0xFF`, which is `1.0`**: the shading multiplies its ambient by
719/// this and the term is untouched. Any other value would be a silent global
720/// ambient scale.
721///
722/// **`gba` are [`ssao::BENT_NORMAL_NONE`], which decodes to a zero-length
723/// direction** — the sentinel the occlusion chain writes wherever it has no
724/// bent direction to report, and which `mesh.slang`'s `bent_normal_at` answers
725/// with the fragment's own shading normal. So "no occlusion pass ran" and "no
726/// direction at this pixel" are one case with one answer, and a frame drawn
727/// with the effect off is the frame this renderer drew before the channel was
728/// widened. Encoding a direction here instead would tilt every ambient term in
729/// such a frame towards one world axis.
730const AMBIENT_OCCLUSION_NONE: [u8; 4] = [
731 0xFF,
732 ssao::BENT_NORMAL_NONE,
733 ssao::BENT_NORMAL_NONE,
734 ssao::BENT_NORMAL_NONE,
735];
736
737/// The `R8Unorm` texel the sun reaches unobstructed: `1.0`, which is `0xFF`.
738///
739/// What [`ForwardRenderer::contact_shadow_placeholder`] holds, and therefore
740/// what `mesh.slang` reads on a frame drawing without
741/// [`RenderEffects::CONTACT_SHADOWS`] — it multiplies `sun_visibility` by this
742/// and the cascades have the last word alone. Any other value would be a silent
743/// global scale on the sun.
744///
745/// The same byte as [`AMBIENT_OCCLUSION_NONE`]'s first and a constant of its
746/// own, for the reason [`LTC_SIZE_U32`] is not [`DFG_SIZE_U32`]: the two
747/// placeholders stand for different facts, and a day one of them wanted a
748/// different value should be an edit here rather than a search for which
749/// callers of a shared name meant which thing.
750const CONTACT_SHADOW_NONE: u8 = 0xFF;
751
752/// The one `Rg32Float` texel that occludes nothing: a mean distance of
753/// [`probe_visibility::FAR`](crcbl_shaders::probe_visibility::FAR) and its
754/// square.
755///
756/// What [`ForwardRenderer::probe_visibility_placeholder`] holds, and therefore
757/// what `mesh.slang` reads on a frame drawn before anything was captured or with
758/// `r_probe_visibility` off. No surface in any scene is further away than that,
759/// so `probe_weight` answers one for every probe and every fragment, and the
760/// grid is the unweighted trilinear blend it was before this rung — which is
761/// what makes the off position bit-identical rather than merely close.
762///
763/// Any *smaller* value would be a silent occluder: every probe in every scene
764/// would read as being behind a wall, and the whole grid would collapse onto
765/// `PROBE_OCCLUDED_WEIGHT`.
766fn probe_visibility_none() -> [u8; crcbl_shaders::probe_visibility::TEXEL_BYTES] {
767 let mut texel = [0u8; crcbl_shaders::probe_visibility::TEXEL_BYTES];
768 let far = crcbl_shaders::probe_visibility::FAR;
769 texel[..4].copy_from_slice(&far.to_le_bytes());
770 texel[4..].copy_from_slice(&(far * far).to_le_bytes());
771 texel
772}
773
774/// The reversed-Z far plane, in the two places that have to agree about it.
775///
776/// `ssao.slang` leaves early at exactly this depth because the unprojection there
777/// divides by a `clip.w` an infinite reversed-Z projection takes to zero. The
778/// shader cannot include the seam and `crcbl-shaders` does not depend on it, so
779/// the mirror is checked here — which is the only place both names are in scope.
780const _: () = assert!(crcbl_hal::depth::CLEAR == crcbl_shaders::ssao::DEPTH_FAR);
781
782/// How many buckets a resident mesh occupies, which is **not the same on every
783/// geometry path** — the one place in this renderer the two differ in shape
784/// rather than in the call they record.
785///
786/// A flat mesh is one bucket either way. A DAG is one bucket on
787/// [`EmitTail::Mesh`]: a bucket is a mesh's run of clusters, and the point of
788/// topic 25's per-cluster selection is that one dispatch covers
789/// several levels at once, so the run is every level's clusters end to end and
790/// the bucket's mesh id is level 0's.
791///
792/// On the two indirect tails a DAG is one bucket **per level**, because there
793/// the same plan takes a uniform cut and a level is drawn as an ordinary index
794/// range: a DAG's levels are separate mesh table entries, `draw_gen.slang`
795/// selects one per instance, and a bucket is what an indexed draw of one index
796/// range *is*. See [`ForwardRenderer::level_buckets`].
797const fn buckets_for(levels: usize, emit: EmitTail) -> usize {
798 if emit.is_mesh() { 1 } else { levels }
799}
800
801/// Every material mode this renderer routes a draw by, and the order the bucket
802/// table lays its per-mode runs of every mesh's levels down in.
803///
804/// [`GpuMaterial::mode`](mesh::GpuMaterial::mode)'s whole range, which is why
805/// the routing is total rather than checked: a row's mode is
806/// `flags & GpuMaterial::MODE_MASK`, that mask is the alpha-mask bit and the
807/// double-sided one, and the four combinations of them are these — so no
808/// material can carry a mode that is not in this list and no instance can
809/// scatter into a bucket that does not exist. Widening the mask means adding the
810/// mode here **and** giving it a depth pipeline in
811/// [`ForwardRenderer::depth_partitions`] in the same change — the two are the
812/// producer and the consumer of one list.
813///
814/// **A scene emits a twin per mode its own materials carry**, not one per
815/// entry here: two materials of two modes are two twins whichever two they are,
816/// and only a scene actually holding all four pays for four. The build below is
817/// where that filter is, and this module's
818/// `an_all_opaque_scene_keeps_one_bucket_per_mesh_level` is what holds it.
819const DEPTH_MODES: [u32; 4] = [
820 0,
821 mesh::GpuMaterial::ALPHA_MODE_MASK,
822 mesh::GpuMaterial::DOUBLE_SIDED,
823 mesh::GpuMaterial::ALPHA_MODE_MASK | mesh::GpuMaterial::DOUBLE_SIDED,
824];
825
826/// A pipeline and its [`CullMode::None`] twin: the two objects a pass binds to
827/// draw single-sided and double-sided buckets of one frame.
828///
829/// **A pipeline rather than a per-draw state, because no backend seam exposes
830/// dynamic cull mode** — and `crcbl_hal::CommandEncoder::set_stencil_reference`
831/// is the precedent for why one would not be added: a raster state a recorded
832/// stream carried per draw is a state every backend has to be able to change
833/// between two indirect calls, and the portable answer to "this draw rasterises
834/// differently" is a second pipeline. Which draws take which is
835/// [`ForwardRenderer::sided_partitions`].
836///
837/// Four passes need the pair — the colour pass, the two depth-only ones and the
838/// reflective shadow map — so it is a type rather than eight fields, and the
839/// twins are built together so a renderer can never hold one without the other.
840#[derive(Clone, Copy, Debug, PartialEq, Eq)]
841struct SidedPipelines {
842 /// [`CullMode::Back`]: every bucket whose material is single-sided, which is
843 /// every bucket of every scene that does not use `doubleSided`.
844 single: GraphicsPipelineHandle,
845 /// [`CullMode::None`]: the buckets whose material carries
846 /// [`GpuMaterial::DOUBLE_SIDED`](mesh::GpuMaterial::DOUBLE_SIDED).
847 ///
848 /// Built on every scene rather than only on one that has such a material,
849 /// for [`MeshModules::depth_masked_pipeline`]'s stated reason: the modules
850 /// are released inside `build` and a pipeline built later would need them
851 /// back, which is a second shader compilation.
852 double: GraphicsPipelineHandle,
853}
854
855/// The pixel budget topic 25's descent compares a group's projected
856/// error against, unless a caller sets another with
857/// [`ForwardRenderer::set_lod_error_budget`].
858///
859/// One pixel, because that is what the metric is *for*: a level's error is how
860/// far its simplification may have moved the surface, so a budget of a pixel is
861/// the point at which a level change stops being something a viewer can see.
862/// The plan's "correct thresholds make pops sub-pixel by definition" is this
863/// number.
864const LOD_ERROR_BUDGET: f32 = 1.0;
865
866/// Bytes one bucket's draw-constant block occupies, whichever of the two blocks
867/// it holds.
868///
869/// The larger of [`mesh::DRAW_CONSTANTS_SIZE`] and
870/// [`CLUSTER_DRAW_CONSTANTS_SIZE`](crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE),
871/// because which one a bucket holds is the geometry path's decision and the
872/// buffer, its dynamic stride and the range the bind group names are all fixed
873/// before that decision reaches them.
874///
875/// **The bound range is the half that bites.** A range sized for the smaller
876/// block leaves the larger one's tail outside it, and a uniform read past the
877/// bound range is not a fault — it is a zero. Sized at sixteen bytes, the mesh
878/// path's `group_stride` read back as zero and every instance descended against
879/// instance zero's LOD state.
880const DRAW_CONSTANTS_BLOCK: u64 =
881 if mesh::DRAW_CONSTANTS_SIZE > crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE {
882 mesh::DRAW_CONSTANTS_SIZE as u64
883 } else {
884 crcbl_shaders::meshlet::CLUSTER_DRAW_CONSTANTS_SIZE as u64
885 };
886
887/// How far below the budget an already-expanded group is held before it
888/// collapses again — topic 25's "switch-up and switch-down differ",
889/// as a fraction of [`LOD_ERROR_BUDGET`].
890///
891/// A ratio and not an offset because the band has to scale with the budget: a
892/// fixed number of pixels is most of a one-pixel budget and none of a fifty-pixel
893/// one. A fifth of the budget is a deadband a camera has to move decisively out
894/// of, and one a camera drifting along a boundary never leaves — which is the
895/// flicker the plan is about. `crcbl_shaders::cluster_select::LodBudgets` is the
896/// pair this produces, and a ratio of one is that type's `sharp`: no band, and
897/// the setting that shows the band is what stops the flicker.
898const LOD_HOLD_RATIO: f32 = 0.8;
899
900/// How much larger than the camera's the pixel budget a shadow cascade selects
901/// under is — topic 25's "**Shadow LOD bias**: shadow-pass culling
902/// selects +1/+2 coarser levels — casters are cheap where it never shows".
903///
904/// # A budget factor, because a level is not a parameter of the rule
905///
906/// The descent compares a group's projected error to a pixel budget; it never
907/// names a level. So "one or two levels coarser" is an *intent*, and the budget
908/// that produces it is the setting — and the two do not convert, because how far
909/// apart two levels' errors are is a property of the mesh. The committed dunes
910/// DAG is the demonstration: the step from one level's error to the next is
911/// several times larger in the middle of that hierarchy than at its base, and
912/// across its top levels there is no step at all — they report one error and are
913/// never separately selected by any budget. A bias expressed in levels would
914/// mean something different at each of those. `cook-clusters` prints the per
915/// level errors it built.
916///
917/// Four, then, is two doublings of the budget: enough that a caster is drawn
918/// coarser than the same object is in the colour pass, and small enough to stay
919/// inside what a shadow hides. What hides it is that a shadow edge is filtered —
920/// the atlas is read through a comparison sampler with linear filtering, so an
921/// edge arrives already spread over neighbouring texels — and that the atlas
922/// quantises every caster to [`shadow::TILE`] texels per cascade before anything
923/// samples it.
924///
925/// # Why one number, applied to the whole pass
926///
927/// **A cut is a cover only while expansion is monotone up the DAG**, and this
928/// scaling is what keeps it so. Multiplying both budgets by one positive
929/// constant leaves the rule in
930/// [`crcbl_shaders::cluster_select`]'s form with different constants in it, and
931/// that module's induction turns on the projected error being monotone up the
932/// DAG rather than on what the constants are — so the shadow pass's cut is a
933/// cover for exactly the reason the camera's is. A bias that varied by cluster,
934/// by group, by level or by cascade would not be: two groups on one branch would
935/// be judged against different budgets, and a child expanding under an
936/// unexpanded parent is a hole.
937///
938/// Being larger than one also makes the shadow pass's expanded set a **subset**
939/// of the colour pass's, since the two now select from one eye at one scale: a
940/// group over `k` times the budget is over the budget. So the shadow cut is
941/// never finer than the camera's anywhere, which is the property
942/// `crcbl-vk`'s `the_shadow_cascades_select_coarser_than_the_camera` reads back
943/// and asserts.
944pub const SHADOW_LOD_BIAS: f32 = 4.0;
945
946/// How many culls the shadow atlas needs: one per cascade and **one per shadowed
947/// light**, whatever kind of light it is.
948///
949/// Topic 18's fourth decision, as a number. A point light's six faces share the
950/// light's sphere — which is what a cull tests against — so they share one
951/// [`DrawGen`] and its visible set, and the six draws differ in a matrix and a
952/// viewport. Six generators per light would be six copies of
953/// [`TileBuffers::group_state`], which is where the cost of one is written down.
954const SHADOW_CULLS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS;
955
956/// How many shadow *views* there are: one per cascade, and one per face of every
957/// light slot.
958///
959/// A view is what has a matrix, so it is what has a frame-block copy, a bind
960/// group and a cut of its own — while a *tile* is where a view lands in the
961/// atlas and a *cull* is which visible set it draws. The three were one number
962/// until a light could own six tiles.
963///
964/// Every slot carries [`shadow::POINT_FACES`] views whether the light in it is a
965/// point or a spot, because a bind group names its buffers when it is created
966/// and the kind of light holding a slot changes per frame. A spot uses face 0's
967/// view and the other five are never recorded — they cost a uniform buffer and a
968/// descriptor each, which is nothing beside the [`DrawGen`] a second *cull*
969/// would cost.
970const SHADOW_VIEWS: usize = shadow::CASCADES + shadow::LIGHT_SLOTS * shadow::POINT_FACES;
971
972/// Cascade 0's view, which is the one the irradiance probes'
973/// reflective shadow map is drawn through.
974///
975/// **A cascade is its own view index**, which is what `add_shadow_pass`'s view
976/// list pushes; [`shadow_view`] numbers a *light slot's* faces and starts past
977/// [`shadow::CASCADES`], so it is not the function to reach for here.
978const CASCADE_ZERO_VIEW: usize = 0;
979
980const _: () = assert!(
981 CASCADE_ZERO_VIEW < shadow::CASCADES,
982 "cascade 0's view has to be one of the cascades' own, not a light slot's"
983);
984
985/// Which view is face `face` of light slot `slot`.
986const fn shadow_view(slot: usize, face: usize) -> usize {
987 shadow::CASCADES + slot * shadow::POINT_FACES + face
988}
989
990/// Which cull light slot `slot` draws from.
991const fn shadow_cull(slot: usize) -> usize {
992 shadow::CASCADES + slot
993}
994
995/// One punctual shadow face this frame draws into the punctual reflective
996/// shadow map, and everything both halves of the updater need of it.
997///
998/// The irradiance probes' punctual producer. It carries no
999/// matrix and no visible set: a face's transform is already in the uniform block
1000/// [`ForwardRenderer::shadow_groups`] binds, and its draws are the ones its
1001/// slot's cull generated for the atlas — which is what makes this rung cost no
1002/// second cull and no second matrix.
1003#[derive(Clone, Copy, Debug)]
1004struct PunctualFace {
1005 /// Which shadow view this face is — [`shadow_view`]'s answer, and the index
1006 /// of the bind group whose block holds that face's own `view_proj`.
1007 view: usize,
1008 /// Which of the frame's shadow culls generated its draws — [`shadow_cull`]'s
1009 /// answer for the slot this face belongs to.
1010 cull: usize,
1011 /// Which face of its light this is, and so — where the light's cull tagged
1012 /// its casters by face — which draw region it draws.
1013 face: usize,
1014 /// Where it lands in the punctual map — [`rsm::punctual_tile`], which is the
1015 /// rectangle the pass sets its viewport to *and* the one the gather reads
1016 /// this face's texels out of.
1017 tile: shadow::TileRect,
1018 /// The light this is a face of, as the gather weighs its texels.
1019 producer: PunctualProducer,
1020}
1021
1022/// The draw region face `face` of a light draws: its own region where the
1023/// light's cull tagged casters by face, and region 0 — every survivor — where it
1024/// did not. See [`crcbl_shaders::draw_gen::FACE_REGION_BASE`].
1025fn face_region(by_face: bool, face: usize) -> u32 {
1026 if by_face {
1027 crcbl_shaders::draw_gen::FACE_REGION_BASE
1028 + u32::try_from(face).unwrap_or_else(|_| unreachable!("a light has six faces"))
1029 } else {
1030 0
1031 }
1032}
1033
1034/// One light's row in the gather's producer table, for the face standing at
1035/// `tile`.
1036///
1037/// **Built out of the light's own row**, which is the one place a light becomes
1038/// numbers — so the falloff, the cone and the colour the bounce is weighed by
1039/// are the very ones `mesh.slang` weighs the same light's direct term by, rather
1040/// than a second reading of the same fields that could round or widen
1041/// differently. [`Light::row`](crate::light::Light::row) is handed [`None`]
1042/// because a producer occludes through nothing: the gather gates a texel with
1043/// the probe's own visibility map, not with the light's.
1044fn producer_row(light: &Light, tile: shadow::TileRect) -> PunctualProducer {
1045 let row = light.row(None);
1046 PunctualProducer {
1047 position: [row.position[0], row.position[1], row.position[2]],
1048 radius: row.position[3],
1049 color: [row.color[0], row.color[1], row.color[2]],
1050 cos_outer: row.direction[3],
1051 axis: [row.direction[0], row.direction[1], row.direction[2]],
1052 cos_inner: row.cos_inner,
1053 origin: [tile.x, tile.y],
1054 side: tile.side,
1055 kind: row.kind,
1056 }
1057}
1058
1059const _: () = assert!(
1060 SHADOW_CULLS == shadow::GROUPS,
1061 "a cull is a cadence group: `shadow::Cadence` schedules what this file \
1062 dispatches, and two different counts would schedule a group nothing draws"
1063);
1064
1065/// Vertices in the over-sized triangle `mesh.slang`'s `depthClearVertexMain`
1066/// generates from `SV_VertexID`. No geometry is bound.
1067const TILE_CLEAR_VERTICES: u32 = 3;
1068
1069const _: () = assert!(
1070 crcbl_shaders::mesh::SHADOW_ATLAS_CLEAR_DEPTH == crcbl_hal::depth::CLEAR,
1071 "the stage that resets one tile writes a depth the attachment's own clear \
1072 does not, so a held tile and a cleared one would answer differently where \
1073 nothing was drawn"
1074);
1075
1076/// Narrows the shadow pass's viewport and scissor to one tile of the atlas.
1077///
1078/// The rectangle the allocator handed out — the same one the fragment stage
1079/// samples through, out of [`shadow::Selection`]. The graph set a viewport over
1080/// the whole atlas before the pass body ran, and this is what narrows it: the
1081/// same clip-space matrix mapped into a different part of the image, and for a
1082/// point light six different matrices into six of them off one visible set.
1083///
1084/// A function rather than the two calls inline, because the tile clear and the
1085/// draws that follow it walk the same tiles and a viewport set one way for one
1086/// of them would clear a rectangle nothing draws into.
1087fn set_shadow_tile(encoder: &mut dyn crcbl_hal::CommandEncoder, tile: shadow::TileRect) {
1088 let rect = Rect2d {
1089 x: i32::try_from(tile.x).unwrap_or(i32::MAX),
1090 y: i32::try_from(tile.y).unwrap_or(i32::MAX),
1091 width: tile.side,
1092 height: tile.side,
1093 };
1094 encoder.set_viewport(&Viewport {
1095 x: rect.x as f32,
1096 y: rect.y as f32,
1097 width: rect.width as f32,
1098 height: rect.height as f32,
1099 ..Viewport::from_size(rect.width, rect.height)
1100 });
1101 encoder.set_scissor(&rect);
1102}
1103
1104/// What the last executed graph left the renderer-owned import `image` in, as an
1105/// [`ImportedImage::initial`].
1106///
1107/// **[`ResourceState::Undefined`] is the answer to an empty ledger, not a
1108/// fallback around one.** The ledger records what a graph *executed*, so nothing
1109/// recorded means nothing has run against this image on this pool — a freshly
1110/// created image before its first frame, and an image whose pool has been
1111/// through [`TransientPool::destroy`] — and `Undefined` is what an image no
1112/// barrier has moved is in. It is also the only declaration that lets the
1113/// incoming barrier hand the image a layout at all: every other state names an
1114/// old layout the image is not in.
1115///
1116/// The reason this is a lookup and not a field the renderer advances: a graph is
1117/// built, then compiled, and [`RenderGraph::compile`] can refuse it. A field
1118/// stepped forward while the passes were declared would have moved for a frame
1119/// that never reached the GPU, and the next frame's declaration — now wrong —
1120/// has no ledger entry to contradict it, so [`InitialClaim::Tracked`] would pass
1121/// it through. One source of truth is what removes that gap rather than
1122/// narrowing it.
1123fn imported_state(pool: &TransientPool, image: ImageHandle) -> ResourceState {
1124 pool.imported_image_use(image)
1125 .unwrap_or(ResourceState::Undefined)
1126}
1127
1128/// The passes [`ForwardRenderer::add_passes`] records itself: the shadow
1129/// atlas's, the two reflective shadow maps, the depth prepass, the forward pass,
1130/// the debug draw layer, the tonemap, the ground grid and the
1131/// culling-statistics copy — plus [`Ssao::MAX_PASSES`], [`Ssr::PASSES`],
1132/// [`ProbeGather::PASSES`], [`Bloom::MAX_PASSES`], [`Exposure::PASSES`],
1133/// [`POST_TONEMAP_PASSES`] and [`Upscale::PASSES`] beside them.
1134///
1135/// [`AtlasView::PASSES`] has no term of its own and is inside
1136/// [`POST_TONEMAP_PASSES`] instead, which is where that is argued: the atlas
1137/// viewer and the resolve are never both recorded.
1138///
1139/// The reflective shadow maps and [`ProbeGather::PASSES`] are counted on the
1140/// ground grid's terms: all three are off unless a scene's
1141/// [`ProbeUpdate`] asks for them, and a bound short
1142/// of the frame that does ask would silently stop timing its last pass. The
1143/// punctual map is a pass whether or not the frame has a punctual light to draw
1144/// into it — see `ForwardRenderer::add_shadow_pass`, where the clear is what the
1145/// gather reads on a frame that lights none.
1146///
1147/// Every other pass in the frame belongs to a [`DrawGen`] or to the
1148/// [`LightGrid`], which is why this is the only count written here rather than
1149/// derived — see [`ForwardRenderer::MAX_PASSES`]. The copy is counted even
1150/// though a device that refused the readback records one fewer: this is a
1151/// ceiling, and one that came up short would silently stop timing the last pass
1152/// of every frame. It is the **all-effects-on** count for the same reason: a
1153/// frame that switched one off records fewer, and a bound that tracked the
1154/// toggles would have to be re-sized whenever they moved.
1155///
1156/// The ground grid is counted on the same terms, even though it is off by
1157/// default and is not a [`RenderEffects`] bit: a caller that switches it on
1158/// records one more pass, and a bound short of that would silently stop timing
1159/// the last pass of every frame it drew. The render-scale upscale is the second
1160/// of those — see [`ForwardRenderer::set_render_scale`], which is `1.0` and
1161/// therefore absent until a caller moves it. The debug draw layer is the third,
1162/// and [`DebugDraw::MAX_PASSES`] is its own ceiling.
1163///
1164/// **The bloom, Hi-Z and occlusion terms are ceilings where the others are
1165/// counts**: a chain's length is a function of the target's extent — see
1166/// [`crate::bloom`] and [`crate::hiz`] — and the occlusion pair's is a function
1167/// of [`crate::ssao::r_ssao_blur_passes`], while this constant is read before
1168/// either an extent or a console is known. The frame that lands on
1169/// it is a large one with bloom switched on; every smaller frame records fewer,
1170/// exactly as a frame with a free shadow slot does.
1171const RENDER_PASSES: u32 = 8
1172 // The occlusion cull's late depth prepass and its farthest pyramid, on the
1173 // ground grid's terms: off unless a caller switches the cull on.
1174 + 1
1175 + OcclusionPyramid::PASSES
1176 + DebugDraw::MAX_PASSES
1177 + ProbeGather::PASSES
1178 + Ssao::MAX_PASSES
1179 + ContactShadows::PASSES
1180 + Hiz::PASSES
1181 + Ssr::PASSES
1182 + Volumetric::PASSES
1183 + Water::PASSES
1184 + Grass::PASSES
1185 + Exposure::PASSES
1186 + Bloom::MAX_PASSES
1187 + POST_TONEMAP_PASSES
1188 + Upscale::PASSES;
1189
1190/// What the frame's one resolve slot costs at its widest: the larger of the two
1191/// antialiasing tiers.
1192///
1193/// **The larger and not the sum**, because the two are never both recorded —
1194/// [`RenderEffects::CMAA2`] carries that in writing and
1195/// [`ForwardRenderer::add_passes`] is where the choice is made. So this is the
1196/// all-effects-on count as well as the ceiling, which is the property
1197/// [`RENDER_PASSES`] needs from every term it adds up.
1198///
1199/// [`ForwardRenderer::add_passes`]: ForwardRenderer::add_passes
1200const RESOLVE_PASSES: u32 = if Fxaa::PASSES > Cmaa2::PASSES {
1201 Fxaa::PASSES
1202} else {
1203 Cmaa2::PASSES
1204};
1205
1206/// What the frame's one **post-tonemap** slot costs at its widest: the resolve
1207/// above, or [`crate::atlas_view`]'s pass, which replaces the picture instead of
1208/// filtering it.
1209///
1210/// **The larger and not the sum**, on [`RESOLVE_PASSES`]' terms and for a
1211/// reason of the same shape: [`ForwardRenderer::resolved_effects`] takes *both*
1212/// antialiasing tiers off for every debug view, and the atlas viewer records
1213/// only on the frame [`ForwardRenderer::debug_view`] resolved to
1214/// [`DebugView::ShadowAtlas`] — which is a debug view. So a frame that draws the
1215/// atlas resolves nothing, a frame that resolves is not drawing the atlas, and
1216/// neither can be short of this. `the_pass_bound_is_the_widest_frame_the_renderer_records`
1217/// is what holds the arithmetic to a frame that was actually recorded.
1218const POST_TONEMAP_PASSES: u32 = if RESOLVE_PASSES > AtlasView::PASSES {
1219 RESOLVE_PASSES
1220} else {
1221 AtlasView::PASSES
1222};
1223
1224/// Draws a full-screen pass records: the over-sized triangle, drawn once.
1225///
1226/// The smallest fraction of the target extent a frame may be drawn at.
1227///
1228/// A quarter in each dimension, which is a sixteenth of the pixels — below that
1229/// the internal frame is small enough that a Catmull-Rom reconstruction of it
1230/// stops being a picture of the scene and starts being a picture of the filter,
1231/// and the Hi-Z pyramid and the bloom chain both run out of levels. Every
1232/// engine's resolution slider bottoms out somewhere; this is where this one
1233/// does, and [`ForwardRenderer::set_render_scale`] clamps to it rather than
1234/// refusing, so a settings slider cannot hand the renderer a frame it cannot
1235/// draw.
1236pub const MIN_RENDER_SCALE: f32 = 0.25;
1237
1238/// The anisotropy the base-colour page is sampled with where the device grants
1239/// [`Features::SAMPLER_ANISOTROPY`].
1240///
1241/// Eight, which is topic 43's filtering rung's
1242/// default and the figure current engines default their own slider to: past it
1243/// the footprint's long axis is already sampled finely enough that sixteen is
1244/// invisible at a grazing angle and costs the same again in fetches. A device
1245/// whose [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) is lower gets
1246/// that limit instead — [`ForwardRenderer::anisotropy_for`] is the clamp — and a
1247/// device without the feature gets one, which is the value that turns it off.
1248pub const DEFAULT_ANISOTROPY: f32 = 8.0;
1249
1250/// Named rather than written into [`ForwardRenderer::counters`]'s arithmetic,
1251/// because these are the only draws in this file whose instance and triangle
1252/// counts the CPU knows exactly — everything else here goes through an indirect
1253/// call.
1254const FULLSCREEN_DRAWS: u64 = 1;
1255
1256/// How many full-screen passes a frame drawing `effects` at `extent` records:
1257/// the tonemap, always, and each switched-on effect's passes beside it.
1258///
1259/// **A function of the frame rather than a constant**, since
1260/// topic 48's toggles: it was the tonemap alone, then
1261/// five, and either written down is a number that stops matching the frame. The
1262/// tonemap is the one that is not conditional — a frame has to reach the
1263/// swapchain.
1264///
1265/// **`extent` is here because the bloom chain's length depends on it** — see
1266/// [`crate::bloom`] — where the two pairs above are the same two passes at every
1267/// size. A frame too small for even one chain level records none of them, which
1268/// is the same arithmetic as the toggle being off. It is the **internal** render
1269/// extent for the same reason: that is the extent every one of these passes runs
1270/// at.
1271///
1272/// `upscaling` is not a [`RenderEffects`] bit and could not be one — it is a
1273/// resolution, not an effect — so it arrives as its own argument, on the ground
1274/// grid's terms. It is false on every frame at full render scale, which is the
1275/// frame this function counted before the knob existed.
1276///
1277/// `ssao_blurs` arrives the same way and for the same reason: it is a console
1278/// variable rather than an effect bit, and it is the caller's job to read it
1279/// **once** for the frame. Reading it here as well would be a second read that
1280/// a command landing between the two could disagree with, and the disagreement
1281/// would be a counter describing a frame that was not recorded.
1282fn fullscreen_passes(
1283 effects: RenderEffects,
1284 extent: (u32, u32),
1285 upscaling: bool,
1286 ssao_blurs: u32,
1287) -> u64 {
1288 let mut passes = 1;
1289 if upscaling {
1290 passes += Upscale::PASSES as u64;
1291 }
1292 if effects.contains(RenderEffects::AMBIENT_OCCLUSION) {
1293 passes += u64::from(Ssao::passes(ssao_blurs));
1294 }
1295 if effects.contains(RenderEffects::CONTACT_SHADOWS) {
1296 passes += u64::from(ContactShadows::PASSES);
1297 }
1298 if effects.contains(RenderEffects::REFLECTIONS) {
1299 // The march's pair, and the pyramid it climbs — which is as long as the
1300 // extent allows and is zero on a frame too small to halve once, so this
1301 // term is the only one here that is not a constant per effect.
1302 passes += Ssr::PASSES as u64 + u64::from(crate::hiz::levels_for(extent));
1303 }
1304 if effects.contains(RenderEffects::BLOOM) {
1305 passes += u64::from(Bloom::passes_for(extent));
1306 }
1307 // **One resolve slot, and the higher tier takes it.** Both bits set is a
1308 // frame with CMAA2's passes and no FXAA pass at all, which is what
1309 // [`RenderEffects::CMAA2`] means by the two never both running — so this is
1310 // an `else if` rather than two independent terms.
1311 //
1312 // **[`Cmaa2::FULLSCREEN_PASSES`] and not [`Cmaa2::PASSES`]**: what this
1313 // function counts is full-screen *draws*, and two of that tier's three
1314 // passes are compute dispatches. [`crate::exposure`]'s three are left out
1315 // of this arithmetic for the same reason.
1316 if effects.contains(RenderEffects::CMAA2) {
1317 passes += Cmaa2::FULLSCREEN_PASSES;
1318 } else if effects.contains(RenderEffects::ANTIALIASING) {
1319 passes += Fxaa::PASSES as u64;
1320 }
1321 if effects.contains(RenderEffects::VOLUMETRIC_FOG) {
1322 // **[`Volumetric::COMPOSITE_PASSES`], not [`Volumetric::PASSES`].** The
1323 // scatter and the column scan are compute dispatches; what this
1324 // function counts is full-screen *draws*, and only the composite is
1325 // one. An atmosphere runs the composite without the effect, and the
1326 // caller adds that one — it is not an effect bit.
1327 passes += u64::from(Volumetric::COMPOSITE_PASSES);
1328 }
1329 // [`RenderEffects::AUTO_EXPOSURE`] adds none, and that is the whole of its
1330 // entry here: all three of its passes are compute dispatches, and the
1331 // exposure they measure reaches the picture through the tonemap's own draw.
1332 passes
1333}
1334
1335/// The budget an **orthographic** camera selects under: one no group satisfies,
1336/// so every group expands and the base level is drawn whole.
1337///
1338/// The metric divides a projected error by the distance to the group's sphere,
1339/// and an orthographic projection has no such falloff — see
1340/// [`Projection::pixels_per_unit`], which is where the trade is written down.
1341/// Drawing the finest level is the conservative answer and the honest one; a
1342/// distance term invented for a projection that has none would be neither.
1343///
1344/// [`Projection::pixels_per_unit`]: crate::camera::Projection::pixels_per_unit
1345const LOD_BUDGET_NONE: f32 = f32::NEG_INFINITY;
1346
1347/// Where a skinned object is, and what it draws: [`InstanceDesc`] with a
1348/// [`SkinnedMesh`] where the description's mesh index would be.
1349///
1350/// The mesh is a reservation rather than an index because a skinned draw is not
1351/// only a mesh — it also names a *run of the vertex pool* the skinning dispatch
1352/// fills, and which of the reservation's two runs that is changes every frame.
1353/// [`ForwardRenderer::begin_skinned_frame`] is what keeps it current, so nothing
1354/// here carries a parity.
1355#[derive(Clone, Copy, Debug)]
1356pub struct SkinnedInstanceDesc<'a> {
1357 /// The region this object is drawn out of, from
1358 /// [`ForwardRenderer::reserve_skinned`].
1359 pub mesh: &'a SkinnedMesh,
1360 /// Which [`SceneDesc::materials`] row it shades through, exactly as
1361 /// [`InstanceDesc::material`].
1362 pub material: usize,
1363 /// Where it is: a model matrix, on [`InstanceDesc::transform`]'s terms.
1364 ///
1365 /// The joints are **not** in it — a palette carries each joint's global
1366 /// transform times its inverse bind matrix, and this is what puts the
1367 /// deformed mesh in the world. See
1368 /// [`SkinRange::palette`](crate::skinning::SkinRange::palette).
1369 pub transform: Mat4,
1370}
1371
1372/// The sky-view LUT a frame is drawn from, and everything taken out of it.
1373///
1374/// **The two projections are cached beside the LUT rather than taken per
1375/// frame**, which is what makes a frame under a sun that has not moved do no
1376/// host LUT work at all: both are functions of the LUT alone, and the LUT only
1377/// changes when [`ForwardRenderer::refresh_sky_view`] swaps a finished build
1378/// in. [`crate::sky_pass`] still encodes [`SkyView::rows`] and its aerial LUT's
1379/// rows per frame, because those are writes into the frame's own ring slots
1380/// rather than projections.
1381#[derive(Clone, Debug)]
1382struct PresentedSky {
1383 /// The normalised sun and viewpoint the LUT was marched for, which is what
1384 /// [`ForwardRenderer::refresh_sky_view`] compares this frame's atmosphere
1385 /// against.
1386 parameters: crcbl_shaders::atmosphere::Atmosphere,
1387 /// The marched LUT: what [`crate::sky_pass`] uploads and the background
1388 /// samples.
1389 view: SkyView,
1390 /// [`SkyView::gradient_fit`], which `ssr.slang` reflects with and the sky
1391 /// pass's block carries.
1392 gradient: crcbl_shaders::sky::SkyGradient,
1393 /// [`SkyView::irradiance`], which is the frame block's L1 ambient term.
1394 irradiance: crcbl_shaders::probe::GpuProbe,
1395}
1396
1397impl PresentedSky {
1398 /// Takes both projections from a LUT that has just been marched.
1399 fn new(parameters: crcbl_shaders::atmosphere::Atmosphere, view: SkyView) -> Self {
1400 Self {
1401 parameters,
1402 gradient: view.gradient_fit(),
1403 irradiance: view.irradiance(),
1404 view,
1405 }
1406 }
1407}
1408
1409/// What [`ForwardRenderer::begin_frame`] fitted for the whole frame, kept so a
1410/// secondary view begun after it writes its blocks against the same sun, light
1411/// rows and shadow matrices the primary camera's were written against.
1412///
1413/// Everything here is decided by the primary camera and drawn once: the rows
1414/// carry the shadow tiles the primary camera's selection handed out, and the
1415/// cascades are fitted to its frustum. A secondary view samples the maps those
1416/// passes drew — `docs/plan/29-fp-rendering.md`'s "shadow maps reused".
1417#[derive(Clone, Debug)]
1418struct FrameScene {
1419 light: DirectionalLight,
1420 rows: Vec<crcbl_shaders::light::GpuLight>,
1421 cascades: Cascades,
1422 shadow_view_proj: [[f32; 16]; shadow::CASCADES],
1423 light_view_proj: [[f32; 16]; shadow::LIGHT_TILES],
1424 atlas_rects: [[f32; 4]; shadow::TILES],
1425}
1426
1427/// The bucket and level tables a scene's generators are all built from, kept
1428/// so [`ForwardRenderer::create_view`] can build one more after `build` has
1429/// returned.
1430#[derive(Debug)]
1431struct DrawTables {
1432 bucket_meshes: Vec<u32>,
1433 bucket_clusters: Vec<u32>,
1434 bucket_cluster_bases: Vec<u32>,
1435 mesh_levels: Vec<level_select::MeshLevels>,
1436 level_groups: Vec<level_select::LevelGroup>,
1437 level_meshes: Vec<u32>,
1438 instance_capacity: u32,
1439 light_capacity: u32,
1440}
1441
1442/// The primary frame attachments an overlay may use before antialiasing and
1443/// render-scale reconstruction.
1444///
1445/// `display` is the display-space image the tonemap and post-tonemap overlays
1446/// have written. `depth` is the matching internal scene depth image, retained
1447/// as a read-only attachment for depth-tested overlays. Both have
1448/// `internal_extent` dimensions.
1449#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1450pub struct ForwardOverlayTargets {
1451 pub display: ImageId,
1452 pub depth: ImageId,
1453 pub internal_extent: (u32, u32),
1454}
1455
1456/// Everything the forward frame owns, created once.
1457#[derive(Debug)]
1458pub struct ForwardRenderer {
1459 // Geometry: the global pools, and the meshes resident in them. Each
1460 // range is resolved once, at build, and `MeshPool::mesh` only hands one out
1461 // for a mesh whose upload has completed — so there is no way to reach a
1462 // draw below with a mesh the GPU has not received.
1463 pool: MeshPool,
1464 /// The dynamic offset of each bucket's [`mesh::DrawConstants`] block, in
1465 /// [`SceneDesc::meshes`] order. Its length is the bucket count, which
1466 /// [`buckets_for`] says is a property of the path as well as of the scene.
1467 ///
1468 /// **The whole of what the CPU still says per draw.** Everything else a
1469 /// draw needs — how many instances, which indices, which vertices — is in
1470 /// the arguments the GPU wrote or in a table it resolves them through.
1471 bucket_constants: Vec<u32>,
1472 /// What one draw region adds to a bucket's offsets — the same for every
1473 /// generator this renderer built, because they share one bucket table.
1474 region_step: RegionStep,
1475 /// The material mode of each bucket, in the same order — the copy the
1476 /// **passes** read, where `DrawGen`'s copy is the one the GPU scatters
1477 /// against.
1478 ///
1479 /// What it is for: the depth prepass and the shadow atlas partition their
1480 /// call list on it and bind a pipeline per partition, so an opaque mesh in a
1481 /// scene with a cutout in it keeps the vertex-only stage. See
1482 /// [`ForwardRenderer::depth_partitions`].
1483 ///
1484 /// All zeroes for a scene whose materials are all opaque — every demo and
1485 /// every golden in this tree — which is exactly one bucket per mesh and one
1486 /// partition, byte for byte the stream they recorded before modes existed.
1487 bucket_modes: Vec<u32>,
1488
1489 // The instance array, and the objects' places in it. Nothing here is
1490 // rewritten per frame: the pool uploads what a caller changed and nothing
1491 // else, so a scene nobody moved costs no transfer at all.
1492 instances: InstancePool,
1493 /// The mesh table id of each description mesh's **level 0**, in
1494 /// [`SceneDesc::meshes`] order — what an [`InstanceDesc::mesh`] index
1495 /// resolves through.
1496 ///
1497 /// Level 0's and not the whole run, because that is the entry an instance
1498 /// carries: `cull.slang` reads a bounding box out of it and a DAG's coarser
1499 /// levels approximate the same surface inside the same box. The coarser
1500 /// entries are resident and no instance names one — a cluster reaches its
1501 /// own level's vertices through
1502 /// [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`], and the
1503 /// uniform cut reaches them through the bucket table.
1504 ///
1505 /// Kept rather than resolved per call because every write of an instance
1506 /// writes the whole record, and an instance that lost its mesh id would
1507 /// resolve to entry 0 — which is a mesh, and the wrong one.
1508 mesh_ids: Vec<u32>,
1509 /// Level 0's pool handle for each description mesh that can be skinned, in
1510 /// [`SceneDesc::meshes`] order, and [`None`] for the ones that cannot — see
1511 /// [`ResidentMesh::skinnable`].
1512 ///
1513 /// What [`ForwardRenderer::reserve_skinned`] resolves an
1514 /// [`InstanceDesc::mesh`] index through. Kept rather than looked up, because
1515 /// there is no way back from a table id to the handle that owns it: an id is
1516 /// a bare index and a [`MeshHandle`] is generational.
1517 skinnable_meshes: Vec<Option<MeshHandle>>,
1518 /// Every object [`ForwardRenderer::add_skinned_instance`] placed, with the
1519 /// two base vertices it alternates between.
1520 ///
1521 /// The list [`ForwardRenderer::begin_skinned_frame`] walks to point each one
1522 /// at the half of its region *this* frame's dispatch fills. Entries whose
1523 /// instance has gone stale are dropped as it walks, so
1524 /// [`ForwardRenderer::remove_instance`] needs to know nothing about
1525 /// skinning.
1526 skinned_instances: Vec<SkinnedInstance>,
1527
1528 /// §3.2's material table, and the rows in it.
1529 ///
1530 /// One buffer shared by every frame's bind group, not a ring — see
1531 /// [`crate::material_table`], which is where that decision lives.
1532 materials: MaterialTable,
1533 /// The table row of each description material, in [`SceneDesc::materials`]
1534 /// order — what an [`InstanceDesc::material`] index resolves through.
1535 ///
1536 /// Kept for the reason [`ForwardRenderer::mesh_ids`] is: a `set` writes the
1537 /// whole record, and an instance that lost its material id would name row 0
1538 /// by accident, which is a material and only *happens* to be the untinted
1539 /// one.
1540 material_ids: Vec<u32>,
1541 /// Topic 50's irradiance grid, row by row.
1542 ///
1543 /// One buffer shared by every frame's bind group, like the material table
1544 /// and for a stronger version of its reason: a probe is written when the
1545 /// scene is made resident and there is no call that rewrites one. See
1546 /// [`crate::probe`].
1547 probes: ProbeTable,
1548 /// Where those rows are, which rides in the frame block rather than in a
1549 /// buffer of its own — a fragment needs it before it knows which row to
1550 /// fetch.
1551 ///
1552 /// Kept rather than re-derived because [`SceneDesc`] is read once, at build.
1553 /// [`ProbeVolume::default`](crcbl_shaders::probe::ProbeVolume::default) is a
1554 /// grid of nothing, which is what a description with no probes leaves here
1555 /// and what makes the whole feature add zero.
1556 probe_volume: crcbl_shaders::probe::ProbeVolume,
1557 /// §3.2's texture side: one `D2Array` image whose layers the material rows
1558 /// index. One page, bound once, for every material — see the module docs on
1559 /// why this is [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) and not
1560 /// a bindless descriptor array.
1561 base_color_page: UploadedTexture,
1562 /// §2's second page: one `D2Array` image of tangent-space normals, whose
1563 /// layers [`GpuMaterial::normal_texture`](mesh::GpuMaterial::normal_texture)
1564 /// indexes.
1565 ///
1566 /// The base-colour page's own shape at [`NORMAL_PAGE_BINDING`], sampled
1567 /// through the same UV and the same sampler, and **created linear** — see
1568 /// [`NORMAL_PAGE_FORMAT`]. Its extent is its own: a description sizes each
1569 /// [`PageKind`] separately, so a 512² normal page beside a 2048²
1570 /// base-colour one is what the caller wrote and what this holds.
1571 normal_page: UploadedTexture,
1572 /// §2's third page: one `D2Array` image of glTF's packed occlusion,
1573 /// roughness and metallic, whose layers
1574 /// [`metallic_roughness_occlusion_texture`](mesh::GpuMaterial::metallic_roughness_occlusion_texture)
1575 /// indexes.
1576 ///
1577 /// The normal page's own shape at [`MRO_PAGE_BINDING`], sampled through the
1578 /// same UV and the same sampler, and **created linear** — see
1579 /// [`MRO_PAGE_FORMAT`].
1580 mro_page: UploadedTexture,
1581 /// §2's fourth page: one `D2Array` image of emitted radiance, whose layers
1582 /// [`emissive_texture`](mesh::GpuMaterial::emissive_texture) indexes.
1583 ///
1584 /// The base-colour page's own shape at [`EMISSIVE_PAGE_BINDING`], and
1585 /// **created sRGB** rather than linear, because an emissive texel is a
1586 /// colour — see [`EMISSIVE_PAGE_FORMAT`].
1587 emissive_page: UploadedTexture,
1588 /// Each [`PageKind`]'s image size in texels, as a width and a height,
1589 /// indexed by [`PageKind::index`].
1590 ///
1591 /// Square, because [`PageDesc`](crate::scene::PageDesc) carries one extent
1592 /// per kind rather than a rectangle. `(1, 1)` for a kind the description
1593 /// named no layer of, which is the placeholder's extent and not the
1594 /// description's — see [`PAGE_PLACEHOLDER_TEXEL`]. Kept rather than
1595 /// re-derived because [`add_passes`](Self::add_passes) declares both pages
1596 /// to the graph and an [`ImportedImage`] names an extent, and the
1597 /// description they came from is the caller's, read once at build.
1598 page_extents: [(u32, u32); PageKind::ALL.len()],
1599 /// The sampler the page is read through.
1600 base_color_sampler: SamplerHandle,
1601 /// The anisotropy [`ForwardRenderer::base_color_sampler`] was created
1602 /// with, after [`set_anisotropy`](ForwardRenderer::set_anisotropy)'s clamp.
1603 anisotropy: f32,
1604 /// How many layers each [`PageKind`]'s page holds, indexed by
1605 /// [`PageKind::index`] — zero for a kind the description named none of.
1606 ///
1607 /// What [`replace_page`](ForwardRenderer::replace_page) holds a
1608 /// replacement to, so every material row's layer number goes on naming the
1609 /// same texture.
1610 page_layers: [usize; PageKind::ALL.len()],
1611 /// `[frame]`: the page sampler and the four page views that slot's
1612 /// mesh-layout groups name.
1613 ///
1614 /// A slot moves onto [`ForwardRenderer::page_bindings`] at its own
1615 /// `begin_frame` and not before — see [`ForwardRenderer::adopt_pages`] —
1616 /// so this is what says which slots still name a sampler
1617 /// [`set_anisotropy`](ForwardRenderer::set_anisotropy) replaced or a page
1618 /// [`replace_page`](ForwardRenderer::replace_page) did.
1619 slot_pages: Vec<PageBindings>,
1620 /// Page samplers and pages replaced while some slot may still name them.
1621 /// Each is destroyed as the last slot naming it moves off, or at
1622 /// [`destroy`](ForwardRenderer::destroy).
1623 retired_pages: Vec<RetiredPage>,
1624
1625 /// Draw calls the last [`ForwardRenderer::add_passes`] recorded — see
1626 /// [`ForwardRenderer::counters`], which is the only thing that reads it.
1627 ///
1628 /// Kept rather than recomputed because the shadow pass's share is the number
1629 /// of **occupied** tiles, which [`ForwardRenderer::add_shadow_pass`] works
1630 /// out from topic 45's tile allocation and nothing outside
1631 /// it can restate without becoming the second copy that drifts.
1632 recorded_draws: u64,
1633 /// Which call the forward pass records — the device's [`GeometryPath`],
1634 /// resolved once.
1635 emit: EmitTail,
1636 /// The most buckets one call of the geometry passes draws, or `None` where
1637 /// they record a call per bucket — [`EmitTail::range_limit`], resolved at
1638 /// build with [`emit`](Self::emit) and for its reason.
1639 range_limit: Option<u32>,
1640 /// §3.5's clusters, and **only on [`EmitTail::Mesh`]**: the two indirect
1641 /// tails draw the same geometry out of the index pool and read none of
1642 /// this. `None` is therefore the ordinary state on most devices rather than
1643 /// a failure, and it is also what makes a fall-through impossible — see
1644 /// [`ForwardRenderer::geometry_path`].
1645 clusters: Option<ClusterPool>,
1646 /// Whether the mesh pipeline was built with §3.5's amplification stage in
1647 /// front of it — see [`ForwardRenderer::culls_clusters`], which is where
1648 /// what it means is written down.
1649 culls_clusters: bool,
1650 /// Where each description mesh's clusters are in
1651 /// [`ForwardRenderer::clusters`] — every level of it, as one run, in
1652 /// [`SceneDesc::meshes`] order. Empty off the mesh path, where there is no
1653 /// cluster pool at all. See [`ForwardRenderer::cluster_range`].
1654 mesh_clusters: Vec<ClusterRange>,
1655 /// The bucket each level of each description mesh draws through, finest
1656 /// first, in [`SceneDesc::meshes`] order — and empty on the mesh path. See
1657 /// [`ForwardRenderer::level_buckets`].
1658 ///
1659 /// **The run for the scene's first material mode**, which is `OPAQUE`
1660 /// wherever the scene has an opaque material at all: the table is every
1661 /// mesh's levels once per mode the scene holds, mode by mode, and this
1662 /// names a mesh's levels in the first of those runs. See
1663 /// [`ForwardRenderer::bucket_modes`].
1664 mesh_level_buckets: Vec<Vec<u32>>,
1665 /// The pixel budget topic 25's descent compares a group's
1666 /// projected error against. [`LOD_ERROR_BUDGET`] until
1667 /// [`ForwardRenderer::set_lod_error_budget`] says otherwise.
1668 lod_error_budget: f32,
1669 /// How far below that an expanded group is held before it collapses again.
1670 /// [`LOD_HOLD_RATIO`] until
1671 /// [`ForwardRenderer::set_lod_hold_ratio`] says otherwise.
1672 lod_hold_ratio: f32,
1673 /// The same three numbers the shadow cascades selected under, which is
1674 /// [`ForwardRenderer::lod_params`] with both budgets scaled by
1675 /// [`SHADOW_LOD_BIAS`] and the same pixels-per-unit.
1676 ///
1677 /// Kept beside the camera's for its reason: a reader comparing the two cuts
1678 /// takes both pairs from here rather than re-deriving the bias, which would
1679 /// be comparing two copies of one arithmetic instead of two selections.
1680 shadow_lod_params: [f32; 3],
1681
1682 /// The lights a caller set beside the sun, as
1683 /// [`ForwardRenderer::set_lights`] was handed them.
1684 ///
1685 /// Kept rather than converted on the way in, because a row is the *frame's*
1686 /// artefact: the sun arrives per frame at
1687 /// [`begin_frame`](ForwardRenderer::begin_frame) and is row 0, so the list a
1688 /// frame uploads cannot be assembled until then.
1689 extra_lights: Vec<Light>,
1690
1691 /// One [`mesh::DrawConstants`] block per draw, a device dynamic-offset
1692 /// alignment apart. Shared by every frame's bind group rather than ringed,
1693 /// because nothing rewrites it after `build`: a mesh's base vertex and an
1694 /// object's instance index are decided when the pools allocate them.
1695 draw_constants: BufferHandle,
1696 /// The camera's resources and history — see [`view`], which is where the
1697 /// line between a camera's state and the scene's is drawn.
1698 primary: View,
1699 /// Every secondary view [`ForwardRenderer::create_view`] built, indexed by
1700 /// [`ViewId::index`] less one — a free id is `None`.
1701 views: Vec<Option<View>>,
1702 /// The tables a view's generator is built from — see [`DrawTables`].
1703 draw_tables: DrawTables,
1704 /// Counts every [`begin_frame`](ForwardRenderer::begin_frame), so a view can
1705 /// say which frame it was last begun for — see [`View::begun`].
1706 frame_serial: u64,
1707 /// The frame the last `begin_frame` opened, for
1708 /// [`begin_view`](ForwardRenderer::begin_view). `None` before the first.
1709 frame_scene: Option<FrameScene>,
1710 /// Which frame-in-flight slot is current. Set from
1711 /// [`InstancePool::begin_frame`]'s return rather than counted here, so the
1712 /// uniform ring and the instance ring cannot drift apart.
1713 frame: usize,
1714
1715 mesh_layout: BindGroupLayoutHandle,
1716 mesh_pipeline_layout: PipelineLayoutHandle,
1717 mesh_pipeline: SidedPipelines,
1718 /// [`ForwardRenderer::mesh_pipeline`] again in
1719 /// [`PolygonMode::Line`], for
1720 /// [`set_wireframe`](ForwardRenderer::set_wireframe).
1721 ///
1722 /// [`None`] until a caller first switches the view on — the ground grid's
1723 /// arrangement exactly, and for its reason: a second pipeline compiled at
1724 /// build would be paid for by every sample, golden and headless run that
1725 /// never asks for a wireframe, which is all of them. Once built it is kept,
1726 /// because switching the view off is
1727 /// [`ForwardRenderer::wireframe_on`] and not a release.
1728 ///
1729 /// **A pair, like the pipeline it replaces**, because [`PolygonMode::Line`]
1730 /// does not disable culling: a single-sided wireframe drawn over a
1731 /// double-sided bucket would leave a surface out of the debug view that the
1732 /// shaded frame beside it draws, which is a view of the document that
1733 /// disagrees with the document.
1734 wireframe_pipeline: Option<SidedPipelines>,
1735 /// Whether [`add_passes`](ForwardRenderer::add_passes) drives the forward
1736 /// pass through [`ForwardRenderer::wireframe_pipeline`]. **`false` by
1737 /// default**: a wireframe is a tool's view of a document, and every sample
1738 /// and every golden image predates it.
1739 wireframe_on: bool,
1740 /// The occlusion and small-feature culls a caller asked for — see
1741 /// [`set_occlusion_culling`](ForwardRenderer::set_occlusion_culling).
1742 occlusion_culling: OcclusionCulling,
1743 /// Whether a point light's six faces cull separately — see
1744 /// [`set_point_face_culls`](ForwardRenderer::set_point_face_culls).
1745 point_face_culls: bool,
1746 /// What a test asked every shadow view's uploaded block to be rewritten
1747 /// with — see
1748 /// [`set_shadow_view_tamper`](ForwardRenderer::set_shadow_view_tamper).
1749 /// [`None`] outside a test.
1750 shadow_view_tamper: Option<fn(&mut mesh::FrameUniforms)>,
1751 /// Whether [`begin_frame`](ForwardRenderer::begin_frame) writes
1752 /// [`FrameUniforms::NORMALS_VIEW_ON`] into the frame block, which makes
1753 /// `mesh.slang`'s fragment stage draw world-space normals instead of shading
1754 /// — see [`set_normals_view`](ForwardRenderer::set_normals_view).
1755 ///
1756 /// **`false` by default**, on [`ForwardRenderer::wireframe_on`]'s terms
1757 /// exactly: it is a tool's view of a document, and every sample and every
1758 /// golden image predates it.
1759 ///
1760 /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
1761 normals_view: bool,
1762
1763 /// The exponential height fog the colour pass composites over its
1764 /// radiance — see [`set_fog`](ForwardRenderer::set_fog).
1765 ///
1766 /// **[`Fog::NONE`] by default**, on [`normals_view`](Self::normals_view)'s
1767 /// terms: a caller who never asks for fog draws the frame this renderer
1768 /// drew before the feature existed, and exactly that frame — the shader's
1769 /// composite is an identity at zero density rather than an interpolation
1770 /// that nearly is.
1771 fog: Fog,
1772
1773 /// The gradient sky whose irradiance the colour pass adds to the ambient
1774 /// term — see [`set_sky`](ForwardRenderer::set_sky).
1775 ///
1776 /// **[`Sky::NONE`] by default**, on [`fog`](Self::fog)'s terms: a black
1777 /// gradient projects to coefficients that are all zero, so the three dot
1778 /// products the fragment stage adds are zero and no frame drawn before a
1779 /// sky existed moves.
1780 sky: Sky,
1781 /// The atmosphere that **replaces** [`Self::sky`] when a caller sets one —
1782 /// see [`set_atmosphere`](ForwardRenderer::set_atmosphere).
1783 ///
1784 /// `None` by default, so a renderer nobody calls that on is the renderer it
1785 /// was.
1786 atmosphere: Option<Atmosphere>,
1787 /// The marched sky-view LUT this renderer is drawing, with the parameters
1788 /// it was marched for and the projections taken from it.
1789 ///
1790 /// **Cached against the parameters rather than rebuilt per frame**, because
1791 /// the march is tens of milliseconds of CPU and the sun in most frames has
1792 /// not moved. The stored parameters are the *normalised* ones the shader
1793 /// crate takes, so a caller handing over the same sun spelled two lengths
1794 /// does not force a rebuild.
1795 ///
1796 /// This is the LUT a frame is **drawn from**, which is not the one being
1797 /// marched: see [`Self::sky_view_build`].
1798 sky_view: Option<PresentedSky>,
1799 /// The march in flight, when the sun has moved away from
1800 /// [`Self::sky_view`]'s.
1801 ///
1802 /// [`ForwardRenderer::refresh_sky_view`] steps it
1803 /// [`SKY_VIEW_BUILD_ROWS`] rows per frame and swaps it into
1804 /// [`Self::sky_view`] when it finishes.
1805 ///
1806 /// **The host side is where the double buffer is**: the LUT being drawn and
1807 /// the LUT being marched are these two fields, and [`crate::sky_pass`]'s
1808 /// device ring is untouched. Putting the stripe on the device instead would
1809 /// mean writing part of a ring slot per frame, and that ring's slots are
1810 /// written whole precisely because each is a frame in flight — a partial
1811 /// write would have to track, per slot, which rows of *which* sun that slot
1812 /// already holds, which is bookkeeping the host copy does not need at all.
1813 sky_view_build: Option<SkyViewBuild>,
1814
1815 /// Whether the colour pass tints each cluster by its DAG level instead of
1816 /// shading — see [`set_lod_view`](ForwardRenderer::set_lod_view).
1817 ///
1818 /// **Wins over [`normals_view`](Self::normals_view) when both are set**,
1819 /// because one uniform lane carries both switches and the fragment stage
1820 /// tests the LOD threshold first. `crcbl_shaders`'
1821 /// `the_lod_view_threshold_lies_above_the_normals_view` is what keeps that
1822 /// order true.
1823 lod_view: bool,
1824
1825 /// Whether the colour pass shades each cluster by the projected error the
1826 /// LOD selection judged it on, instead of shading it or tinting it — see
1827 /// [`set_heatmap`](ForwardRenderer::set_heatmap).
1828 ///
1829 /// **Wins over both [`lod_view`](Self::lod_view) and
1830 /// [`normals_view`](Self::normals_view)**, on the same terms and for the same
1831 /// reason: one uniform lane carries all three switches and the shaders test
1832 /// the outermost threshold first. `crcbl_shaders`'
1833 /// `the_heatmap_view_threshold_lies_above_the_lod_view` is what keeps that
1834 /// order true, and
1835 /// `the_three_debug_views_resolve_in_one_order_however_they_are_set` is what
1836 /// holds this side to it.
1837 heatmap: bool,
1838
1839 /// Whether the colour pass draws the ambient-occlusion channel as grey
1840 /// instead of shading — see
1841 /// [`set_occlusion_view`](ForwardRenderer::set_occlusion_view).
1842 ///
1843 /// **Wins over every other view**, on [`heatmap`](Self::heatmap)'s terms and
1844 /// for its reason: one uniform lane, outermost threshold first.
1845 /// `crcbl_shaders`' `the_occlusion_view_threshold_lies_above_the_heatmap` is
1846 /// what keeps that order true, and
1847 /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1848 /// this side to it.
1849 occlusion_view: bool,
1850
1851 /// Whether the colour pass draws the motion vector instead of shading — see
1852 /// [`set_motion_view`](ForwardRenderer::set_motion_view).
1853 ///
1854 /// **Wins over every other view**, on [`occlusion_view`](Self::occlusion_view)'s
1855 /// terms and for its reason: one uniform lane, outermost threshold first.
1856 /// `crcbl_shaders`' `the_motion_view_threshold_lies_above_the_occlusion_view`
1857 /// is what keeps that order true, and
1858 /// `the_debug_views_resolve_in_one_order_however_they_are_set` is what holds
1859 /// this side to it.
1860 motion_view: bool,
1861 /// Whether the colour pass draws the occlusion channel's bent direction
1862 /// instead of shading — see
1863 /// [`set_bent_normal_view`](ForwardRenderer::set_bent_normal_view).
1864 ///
1865 /// **Wins over every other view**, on [`motion_view`](Self::motion_view)'s
1866 /// terms: it is the outermost sentinel in the lane, and
1867 /// `crcbl_shaders`' `the_bent_normal_view_threshold_lies_above_the_motion_view`
1868 /// is what holds the shader's branch order to it.
1869 bent_normal_view: bool,
1870
1871 /// Whether the colour pass tints the shaded picture by the cascade each
1872 /// sun-lit fragment's shadow was sampled from — see
1873 /// [`set_cascade_view`](ForwardRenderer::set_cascade_view).
1874 ///
1875 /// **Loses to every other view**, which is the opposite of every field
1876 /// above and for the reason [`DebugView::Cascades`] carries: every one of them
1877 /// replaces the shaded picture and this one multiplies it, so a frame drawing
1878 /// any of them has nothing for this tint to reach. `crcbl_shaders`'
1879 /// `the_cascade_view_threshold_lies_below_every_replacing_view` is what
1880 /// holds the shader to the same order, from the other end of the lane.
1881 cascade_view: bool,
1882
1883 /// Whether the frame draws the shadow atlas over the finished picture — see
1884 /// [`set_atlas_view`](ForwardRenderer::set_atlas_view).
1885 ///
1886 /// **Not a lane of the frame block**, unlike every field above: this view is
1887 /// a pass rather than a branch in `mesh.slang`, so what reads this is
1888 /// [`ForwardRenderer::add_passes`] deciding whether to record
1889 /// [`crate::atlas_view`]'s. It resolves below every replacing view and above
1890 /// [`cascade_view`](Self::cascade_view) — see
1891 /// [`ForwardRenderer::debug_view`].
1892 atlas_view: bool,
1893
1894 /// Where [`begin_frame`](ForwardRenderer::begin_frame) projects
1895 /// topic 25's selection from, when that is not the camera's own
1896 /// eye — see
1897 /// [`set_frozen_selection_eye`](ForwardRenderer::set_frozen_selection_eye).
1898 ///
1899 /// **[`None`] is not a position, it is "follow the camera"**, and it is what
1900 /// every frame the engine has drawn so far did: the eye handed to
1901 /// [`DrawGen::begin_frame`] is `camera.eye`, byte for byte, so a caller that
1902 /// never sets this writes the parameter block it wrote before this field
1903 /// existed.
1904 ///
1905 /// **Not a [`DebugView`]**, and deliberately: the three views are one
1906 /// picture chosen between, while this is a change to what the *selection*
1907 /// answers and leaves the picture's choice alone. A reviewer freezing the
1908 /// cut and then reading it off the LOD tint is the combination the feature
1909 /// exists for, so the two cannot be alternatives.
1910 frozen_selection_eye: Option<Vec3>,
1911
1912 /// Topic 18's shadow atlas: one `D32Float` image holding
1913 /// [`shadow::TILES`] square tiles in a fixed grid — the sun's cascades
1914 /// first, then one per shadowed light.
1915 ///
1916 /// Owned here rather than created by the graph per frame, because its
1917 /// extent is a **quality setting and not a window size** — nothing about it
1918 /// changes on a resize, so a transient would be re-created for no reason
1919 /// and could not be read back by a test that does not own the graph.
1920 shadow_atlas: ImageHandle,
1921 shadow_atlas_view: ImageViewHandle,
1922 /// A 1×1 depth image that exists so the depth-only pipeline's bind group can
1923 /// fill [`SHADOW_ATLAS_BINDING`] without naming the atlas it is writing.
1924 ///
1925 /// Both halves of that sentence are forced:
1926 ///
1927 /// * **The slot has to be filled.** Slang's Metal backend materialises every
1928 /// global into every entry point — `msl/mesh.metal`'s `vertexMain` takes
1929 /// `shadow_atlas [[texture(1)]]` whether it reads it or not — so a
1930 /// depth-only pipeline sharing this layout still declares the argument. A
1931 /// layout with the slot removed would break Metal alone, on a runner this
1932 /// team cannot debug on, which is the trap binding 6's comment already
1933 /// records.
1934 /// * **It cannot be the atlas.** WebGPU refuses a texture that is a render
1935 /// attachment and a bind-group resource in the same pass, and the shadow
1936 /// pass is exactly that pass.
1937 ///
1938 /// Nothing samples it: the shadow pipeline has no fragment stage. It is
1939 /// brought into the graph beside the atlas so its layout transition is the
1940 /// graph's like every other, rather than a hand-written barrier.
1941 shadow_placeholder: ImageHandle,
1942 shadow_placeholder_view: ImageViewHandle,
1943 /// The **comparison** sampler the atlas is read through — hardware PCF.
1944 shadow_sampler: SamplerHandle,
1945 /// The depth-only pipeline every tile is rendered with — and, driven with
1946 /// the camera's own draws, the depth prepass's: `mesh.slang`'s
1947 /// `depthVertexMain` where the geometry comes from a vertex stage, the same
1948 /// geometry stage as [`ForwardRenderer::mesh_pipeline`] where it comes from
1949 /// a mesh one, and no fragment stage in either case.
1950 shadow_pipeline: SidedPipelines,
1951 /// The same two passes' pipeline for the buckets whose material mode cuts
1952 /// an alpha mask: `vertexMain` and `depthMaskedFragmentMain` — see
1953 /// [`MeshModules::depth_masked_pipeline`].
1954 ///
1955 /// Built on every scene rather than only on one that has a masked material,
1956 /// for [`ForwardRenderer::rsm_pipeline`]'s reason: the modules are released
1957 /// inside `build` and a pipeline built later would need them back, which is
1958 /// a second shader compilation. Which buckets are drawn with it is
1959 /// [`ForwardRenderer::depth_partitions`], and it is a **partition of one
1960 /// frame's draws** rather than a choice for the whole frame.
1961 depth_masked_pipeline: SidedPipelines,
1962 /// The pipeline that resets one tile of the atlas before it is redrawn, on a
1963 /// frame that is keeping some of the others — see
1964 /// [`MeshModules::depth_clear_pipeline`], which is where the whole argument
1965 /// for it lives.
1966 shadow_clear_pipeline: GraphicsPipelineHandle,
1967 /// The irradiance probes' reflective shadow map — see
1968 /// [`MeshModules::rsm_pipeline`]. Built on every scene and bound only by a
1969 /// frame whose volume asked for [`ProbeUpdate::EveryFrame`].
1970 rsm_pipeline: SidedPipelines,
1971 /// The compute pass that reads that map into the probe rows, and [`None`]
1972 /// for every scene whose volume is [`ProbeUpdate::Authored`] — which is the
1973 /// whole of what the default costs such a scene: no pipeline, no buffers, no
1974 /// pass and no frame time.
1975 probe_gather: Option<ProbeGather>,
1976 /// Whether cascade 0's view block and cull parameters were written for the
1977 /// frame being recorded, so the reflective shadow map can be drawn from
1978 /// them.
1979 ///
1980 /// Not [`ForwardRenderer::shadow_group_redrawn`], which is a claim about the
1981 /// *atlas*: a frame drawing without
1982 /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) fits
1983 /// cascade 0 for the map and writes no tile, and overloading that flag would
1984 /// report a cascade as redrawn when nothing drew it.
1985 rsm_cull_ready: bool,
1986 /// What the scene said fills the probe rows.
1987 ///
1988 /// Read by [`ForwardRenderer::begin_frame`] — which keeps cascade 0 off the
1989 /// shadow atlas's static-cache hold when the updater is on, because the map
1990 /// is that cascade's own draws — and by the pass recording below.
1991 probe_update: ProbeUpdate,
1992 /// How far cascade 0 reached on the frame being recorded, which is the
1993 /// radius of the sphere it was fitted to — `crate::rsm::texel_area` is what
1994 /// reads it.
1995 ///
1996 /// Written by [`ForwardRenderer::begin_frame`] beside the cascade matrices
1997 /// themselves, rather than recomputed at pass-record time: a frame that
1998 /// scaled its gather by one cascade's footprint while drawing the map
1999 /// through another's would be a bounce that is uniformly wrong, and nothing
2000 /// in the frame could see it.
2001 cascade_reach: f32,
2002 /// The sun's colour premultiplied by its intensity, this frame.
2003 ///
2004 /// The reflective shadow map holds albedo rather than flux — `RsmOutput` in
2005 /// `mesh.slang` argues why — so this is what the gather multiplies by, and it
2006 /// is read off the same [`DirectionalLight`] the cascades were fitted to.
2007 /// The sun's *direction* is not carried beside it: the gather needs none, on
2008 /// `probe_gather.slang`'s own derivation.
2009 sun_color: Vec3,
2010 /// One cull and draw-argument pass **per cascade and per shadowed light**,
2011 /// which is topic 18's "one cull dispatch per cascade against the same
2012 /// instance/geometry pools" with a shadowed light counting as a cascade does.
2013 ///
2014 /// A whole [`DrawGen`] rather than just its cull half: the shadow pass emits
2015 /// the same indirect call the colour pass does, so it needs the same
2016 /// arguments, and there is no "cull only" constructor to reach for. The cost
2017 /// is that each duplicates the clear and draw-argument pipelines and
2018 /// [`DrawGen`]'s own per-instance state — see
2019 /// [`TileBuffers::group_state`], which is where that price is written down,
2020 /// and [`SHADOW_CULLS`], which is why a point light has one of these rather
2021 /// than six.
2022 ///
2023 /// **Indexed by cull**: `0..shadow::CASCADES` are the sun's and
2024 /// [`shadow_cull`] is where a light slot's is.
2025 shadow_draws: Vec<DrawGen>,
2026 /// `[frame][view]`: a copy of the frame block whose `view_proj` **is** that
2027 /// view's matrix, so the depth-only pipeline runs the unmodified vertex and
2028 /// mesh stages rather than a second transform path.
2029 shadow_uniforms: Vec<Vec<BufferHandle>>,
2030 /// Empty between frame preparations, with capacity retained for assembly.
2031 shadow_prepare_views: Vec<(usize, usize, mesh::FrameUniforms)>,
2032 /// Empty between frame preparations, with capacity retained for frusta.
2033 shadow_prepare_culls: Vec<(usize, Frustum)>,
2034 /// `[frame][view]`: the mesh layout again, reading that view's uniforms and
2035 /// the survivors of the cull its slot owns.
2036 shadow_groups: Vec<Vec<BindGroupHandle>>,
2037 /// `[frame][view]`: the cut that view's amplification stage chose, one word
2038 /// per resident cluster — and empty where there is no such stage.
2039 ///
2040 /// **A buffer per view rather than the camera's**, unlike every other
2041 /// resource these passes share: the colour pass is recorded last and writes
2042 /// [`ForwardRenderer::cluster_selection`] over whatever a view left in it,
2043 /// so a view writing there leaves nothing behind to read. Without one of
2044 /// these the shadow pass's descent is unobservable — which is the state
2045 /// [`SHADOW_LOD_BIAS`] arrived in, and it is what a bias nothing can measure
2046 /// would have stayed in.
2047 shadow_selection: Vec<Vec<BufferHandle>>,
2048 /// Which of [`ForwardRenderer::extra_lights`] holds each shadow slot, where
2049 /// in the atlas's light region its tiles are, and the memory that keeps that
2050 /// answer from flickering.
2051 ///
2052 /// Re-run every [`ForwardRenderer::begin_frame`] and read by
2053 /// [`ForwardRenderer::add_shadow_pass`], which records a cull for each
2054 /// occupied slot and a viewport per face it has, and nothing at all for the
2055 /// free ones — so an unheld tile keeps the reversed-Z clear, which reads as
2056 /// "nothing stored, fully lit" wherever anything did sample it.
2057 shadow_lights: shadow::Selection,
2058 /// `[group]`: everything that group's maps would be drawn from, as
2059 /// [`ForwardRenderer::shadow_group_record`] spells it.
2060 ///
2061 /// Kept only to tell one frame's answer from the last one's: it is compared
2062 /// and then replaced, and what travels from there is the number below.
2063 ///
2064 /// **Per group rather than per atlas**, since the cadence rung: a group is a
2065 /// cascade or a light slot's whole run of tiles, and holding one map while
2066 /// redrawing another is the whole of what that rung buys.
2067 shadow_group_inputs: Vec<Vec<u8>>,
2068 /// `[group]`: a number that moves whenever that group's entry of
2069 /// [`ForwardRenderer::shadow_group_inputs`] does, and never comes back to a
2070 /// value it has had.
2071 ///
2072 /// So "the image already holds this" is one integer comparison, which is
2073 /// what lets the pass body below carry the answer out of the graph.
2074 shadow_group_id: Vec<u64>,
2075 /// `[group]`: how many instance writes that group's cull could have seen,
2076 /// over the renderer's life — the per-group stand-in for
2077 /// [`InstancePool::revision`] in
2078 /// [`ForwardRenderer::shadow_group_record`], moved by
2079 /// [`ForwardRenderer::note_caster_writes`].
2080 shadow_group_writes: Vec<u64>,
2081 /// `[element]`: where each element of the instance array could draw into a
2082 /// shadow map, as of the last [`ForwardRenderer::note_caster_writes`] —
2083 /// which is what a write's *before* is read from. Grows to the highest
2084 /// element written; an element past its end has never been written and is
2085 /// [`shadow_inputs::CasterFootprint::Nowhere`].
2086 shadow_footprints: Vec<shadow_inputs::CasterFootprint>,
2087 /// The live elements whose mesh has a DAG, and so whose level the selection
2088 /// eye chooses — the ones that put the eye into a light group's record.
2089 shadow_dag_elements: std::collections::BTreeSet<u32>,
2090 /// Scratch for [`InstancePool::take_written`], kept so a frame that moved
2091 /// an instance does not allocate its list.
2092 shadow_written: Vec<u32>,
2093 /// This frame's written elements' footprints, before and after the write,
2094 /// from [`ForwardRenderer::note_caster_writes`] for
2095 /// [`shadow_inputs::shadow_groups_reached`]. Empty on a frame nothing was
2096 /// written in.
2097 shadow_moved: Vec<(
2098 shadow_inputs::CasterFootprint,
2099 shadow_inputs::CasterFootprint,
2100 )>,
2101 /// The number given to the shadow pass this renderer recorded last.
2102 ///
2103 /// Moves once per recorded pass, so the body below can say *which* pass ran
2104 /// with one integer.
2105 shadow_pass_id: u64,
2106 /// The [`ForwardRenderer::shadow_pass_id`] of the last shadow pass that
2107 /// **ran**, written by that pass's own body.
2108 ///
2109 /// By the body rather than by the call that recorded it, and that is the
2110 /// whole of why this is shared state rather than a plain field: a frame
2111 /// whose graph was refused — or built and dropped — recorded a pass that
2112 /// never executed, so the image still holds whatever the frame before it
2113 /// left there. `a_refused_frame_leaves_the_shadow_atlas_where_it_was` is
2114 /// that case, and it is the same boundary [`TransientPool`]'s ledger of
2115 /// imported images uses for the same reason.
2116 ///
2117 /// Zero until a pass has run, and the ids start above it, so the first frame
2118 /// of all draws.
2119 shadow_pass_ran: Arc<AtomicU64>,
2120 /// What the shadow pass recorded last would leave the image holding, if its
2121 /// body ran.
2122 ///
2123 /// Taken and applied by the next [`ForwardRenderer::begin_frame`], which is
2124 /// the only place that can tell whether it did — see
2125 /// [`ForwardRenderer::shadow_pass_ran`].
2126 shadow_pending: Option<ShadowCommit>,
2127 /// `[group]`: the id, the centre that group's maps were projected from and
2128 /// how far they reach, as the record the **image** holds describes them.
2129 ///
2130 /// The id is what says a map is out of date. The centre and reach are what
2131 /// say it is about somewhere else: a map whose own centre has moved further
2132 /// than its own reach covers ground it was never drawn for, and holding
2133 /// that is worse than a shadow that lags — see
2134 /// [`ForwardRenderer::shadow_cadence_reset`].
2135 shadow_group_held: Vec<(u64, Vec3, f32)>,
2136 /// `[group]`: whether this frame redraws that group's maps.
2137 ///
2138 /// Frozen by [`ForwardRenderer::begin_frame`] for
2139 /// [`ForwardRenderer::frame_effects`]' reason: this call decides it and
2140 /// `add_passes` acts on it, and a value that moved between them would skip
2141 /// a cull whose draws were recorded, or the other way about.
2142 shadow_group_redrawn: Vec<bool>,
2143 /// Where every atlas slot's map was laid out on the frame the **image** was
2144 /// drawn from, so a frame can tell whether the texels it is keeping still
2145 /// describe the layout it is about to sample through.
2146 ///
2147 /// A layout that has moved is what makes a frame clear the whole attachment
2148 /// and redraw every group: a tile left over from a different layout is
2149 /// texels nothing this frame can account for. Promoted beside
2150 /// [`ForwardRenderer::shadow_group_held`].
2151 ///
2152 /// [`None`] until a pass has drawn, which is **not** the layout a frame
2153 /// with shadows off produces: an image no pass has touched holds undefined
2154 /// memory rather than a clear, so the first frame of all has to write one
2155 /// whatever it is asked for.
2156 shadow_atlas_layout: Option<Vec<shadow::TileRect>>,
2157 /// Whether any map this frame samples is one an earlier frame drew, rather
2158 /// than one this frame did.
2159 ///
2160 /// The cadence's own readback — see
2161 /// [`ForwardRenderer::shadow_atlas_cached`], which is this for the whole
2162 /// atlas.
2163 shadow_atlas_cached: bool,
2164 /// Whether this frame ignored the cadence because some map's region moved
2165 /// out from under it — see [`ForwardRenderer::shadow_cadence_reset`].
2166 shadow_cadence_reset: bool,
2167 /// How many tiles this frame redraws — see
2168 /// [`ForwardRenderer::shadow_faces_redrawn`].
2169 shadow_faces_redrawn: u32,
2170 /// A shadow cadence the caller pinned, or [`None`] to take the console's.
2171 ///
2172 /// [`ForwardRenderer::set_effect_request`]'s shape at this knob and for its
2173 /// reason: `shadow::r_shadow_cadence` and `shadow::r_shadow_faces` are
2174 /// process-global, and an application that wants a tier's own pair — or a
2175 /// test that wants a frame nothing else in the process can move — needs one
2176 /// that is not.
2177 shadow_cadence_request: Option<shadow::Cadence>,
2178 /// Whether this frame's shadow pass clears the whole attachment, rather
2179 /// than loading it and resetting only the tiles it redraws.
2180 ///
2181 /// Frozen beside [`ForwardRenderer::shadow_group_redrawn`] and for its
2182 /// reason: the decision is `begin_frame`'s and the recording is
2183 /// `add_shadow_pass`'s, and a value that moved between them would load an
2184 /// attachment whose tiles nothing had reset.
2185 shadow_atlas_clears: bool,
2186 /// How many frames have been opened, which is what the cadence is keyed to.
2187 ///
2188 /// **Monotonic, unlike [`ForwardRenderer::frame`]**, which is the index of
2189 /// the frame in flight and wraps every [`FRAMES_IN_FLIGHT`]. A schedule
2190 /// keyed to that would repeat every few frames and bound nothing.
2191 shadow_frame: u64,
2192 /// Whether this frame dispatches skinning, and so rewrites part of the
2193 /// vertex pool the shadow pass draws from.
2194 ///
2195 /// The atlas's one **always redraw**: a skinned caster's vertices are
2196 /// produced by a compute pass into the pool, so there is nothing on the
2197 /// host to compare a frame's geometry against — the palette a caller hands
2198 /// over is not the vertices, and the vertices are never read back. Set by
2199 /// [`ForwardRenderer::begin_skinned_frame`], which is the only call that
2200 /// can make it true, and cleared by [`ForwardRenderer::begin_frame`], which
2201 /// dispatches none.
2202 frame_skins: bool,
2203
2204 /// Topic 03 §3.6's one permitted readback: the camera cull's statistics, on
2205 /// a delayed ring — see [`crate::cull_stats`], which is where the shape and
2206 /// the latency are argued.
2207 ///
2208 /// **The camera's cull only.** [`ForwardRenderer::shadow_draws`] each have a
2209 /// statistics buffer of their own and none of them is read: a cascade's
2210 /// survivor count is a different question about a different frustum, and
2211 /// added into this one it would produce a number larger than the pool holds.
2212 ///
2213 /// [`None`] on a device that would not give out the buffers, which is what
2214 /// makes the counters row degrade to `indirect` rather than fail.
2215 cull_stats: Option<CullStatsRing>,
2216
2217 tonemap_layout: BindGroupLayoutHandle,
2218 tonemap_pipeline_layout: PipelineLayoutHandle,
2219 tonemap_pipeline: GraphicsPipelineHandle,
2220 sampler: SamplerHandle,
2221 /// The multiplier the tonemap pass applies before its clamp — see
2222 /// [`set_exposure`](ForwardRenderer::set_exposure).
2223 ///
2224 /// Always within [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`], because the setter is
2225 /// the only thing that writes it and it clamps.
2226 exposure: f32,
2227 /// How far auto-exposure may move in one frame — see
2228 /// [`set_exposure_adaptation`](ForwardRenderer::set_exposure_adaptation).
2229 ///
2230 /// [`None`] until a caller says otherwise, and that is the whole distance in
2231 /// one frame: the picture the pass drew before adaptation existed.
2232 exposure_adaptation: Option<ExposureAdaptation>,
2233 /// Which operator the tonemap pass runs — see
2234 /// [`set_tonemap_curve`](ForwardRenderer::set_tonemap_curve).
2235 ///
2236 /// [`TonemapCurve::Aces`](crcbl_shaders::tonemap::TonemapCurve::Aces) until
2237 /// a caller says otherwise: this renderer shades in linear HDR, so the
2238 /// filmic roll-off is what a view that has said nothing wants. A
2239 /// display-referred view — a 2D sample, or a fixture whose assertions
2240 /// predict a code value — asks for
2241 /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp),
2242 /// which is the identity on `0..=1`.
2243 tonemap_curve: tonemap::TonemapCurve,
2244
2245 /// The format the tonemap pipeline was built for. A swapchain format change
2246 /// needs a new pipeline, which is why it is remembered rather than assumed.
2247 target_format: Format,
2248
2249 /// A 1×1 `R8Unorm` image holding [`AMBIENT_OCCLUSION_NONE`], so a group of
2250 /// the mesh layout can fill [`AMBIENT_OCCLUSION_BINDING`] without naming an
2251 /// occlusion image that does not exist yet.
2252 ///
2253 /// [`ForwardRenderer::shadow_placeholder`]'s argument, one binding along.
2254 /// The shadow pass and the depth prepass name it and never sample it — a
2255 /// depth-only pipeline has no fragment stage — and **the forward pass names
2256 /// it too on a frame drawing without [`RenderEffects::AMBIENT_OCCLUSION`]**,
2257 /// where it is the whole of that effect's off-switch. An AO-on frame binds
2258 /// the occlusion pair's blurred output instead.
2259 ///
2260 /// **It is white because that is the value that occludes nothing**, which is
2261 /// what makes it an honest stand-in for "no occlusion was computed" rather
2262 /// than decoration. That it *reads* as white is `mesh.slang`'s doing: the
2263 /// binding is fetched with a `Load`, and a `Load` past a 1×1 image's one
2264 /// texel is zero on every backend, so the shader clamps the coordinate to the
2265 /// image's extent. See [`add_passes`](ForwardRenderer::add_passes).
2266 ///
2267 /// It is uploaded rather than cleared, so it is in
2268 /// [`ResourceState::ShaderRead`] from the moment it exists and no pass has to
2269 /// declare it to give it a layout.
2270 ambient_occlusion_placeholder: UploadedTexture,
2271 /// A 1×1 `R8Unorm` image holding [`CONTACT_SHADOW_NONE`], so a group of the
2272 /// mesh layout can fill [`CONTACT_SHADOW_BINDING`] without naming a
2273 /// contact-shadow image that does not exist yet.
2274 ///
2275 /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, one
2276 /// binding along and with one difference worth stating: an unclamped `Load`
2277 /// past this one's single texel would cost the frame its **sun**, not its
2278 /// ambient. `mesh.slang`'s `contact_at` is what clamps it.
2279 contact_shadow_placeholder: UploadedTexture,
2280 /// A 1×1×1 `Rg32Float` image holding [`probe_visibility_none`], so a group
2281 /// of the mesh layout can fill [`PROBE_VISIBILITY_BINDING`] before anything
2282 /// has been captured — and so the console switch has something to name when
2283 /// the maps are turned off.
2284 ///
2285 /// [`ForwardRenderer::ambient_occlusion_placeholder`]'s argument, with the
2286 /// same clamp on the shader's side: `mesh.slang`'s `probe_moments` clamps
2287 /// against `GetDimensions`, so all four of its taps land on this image's one
2288 /// texel and every probe reads as unobstructed.
2289 probe_visibility_placeholder: UploadedTexture,
2290 /// The captured maps, one `Rg32Float` layer per probe — `None` until
2291 /// [`ForwardRenderer::capture_probe_visibility`] has run, which is every
2292 /// frame drawn by a caller that never calls it.
2293 probe_visibility: Option<UploadedTexture>,
2294 /// The scene's static triangles, kept for that capture and for nothing else.
2295 ///
2296 /// Empty for a description that reserved no probes, which is what makes the
2297 /// retention cost of this rung zero for every caller that does not use it —
2298 /// see [`crate::probe_visibility`].
2299 probe_occluders: crate::probe_visibility::Occluders,
2300 /// The split-sum `DFG` table as an `Rgba8Unorm` image — binding
2301 /// [`SPECULAR_DFG_BINDING`], read by multi-scatter energy compensation and
2302 /// by every area light's specular term.
2303 ///
2304 /// Uploaded once from `crcbl_shaders::dfg::pair_texels` and never written
2305 /// again: it is a property of the GGX lobe rather than of a scene, a view or
2306 /// a frame. Unlike [`ForwardRenderer::ambient_occlusion_placeholder`] beside
2307 /// it this is not a stand-in for anything — there is no path on which the
2308 /// table is absent, because there is no path on which the lobe is.
2309 specular_dfg: UploadedTexture,
2310 /// The linearly transformed cosine fit as an `Rgba16Float` image — binding
2311 /// [`LTC_TABLE_BINDING`], and the whole of an area light's specular shape.
2312 ///
2313 /// Uploaded once from `crcbl_shaders::ltc::texels`, on the table above it's
2314 /// terms exactly and for the same reason: it is a property of the lobe, and
2315 /// it is bound on every path because Slang's Metal backend materialises
2316 /// every global into every entry point.
2317 ltc_table: UploadedTexture,
2318 /// `[frame][view]`: the entries [`ForwardRenderer::shadow_groups`] was built
2319 /// from.
2320 ///
2321 /// Kept for one rebuild only: the pages' and their sampler's, which
2322 /// [`ForwardRenderer::adopt_pages`] performs on every group of the mesh
2323 /// layout a slot holds — [`View::prepass_group_entries`]' reason.
2324 shadow_group_entries: Vec<Vec<Vec<BindGroupEntry>>>,
2325
2326 /// The ground grid's pipeline and uniform ring — see [`crate::grid`].
2327 ///
2328 /// [`None`] until a caller first switches it on with
2329 /// [`set_ground_grid`](ForwardRenderer::set_ground_grid), which is what
2330 /// keeps a sample that never asks for a grid from building a pipeline and a
2331 /// ring of blocks for a pass it does not record. Once built it is kept —
2332 /// switching the grid off is [`ForwardRenderer::ground_grid_on`] and not a
2333 /// release, because releasing a uniform ring the frames in flight may still
2334 /// be reading is exactly what the ring exists to prevent.
2335 ground_grid: Option<GroundGrid>,
2336 /// Whether [`add_passes`](ForwardRenderer::add_passes) records the ground
2337 /// grid's pass. **`false` by default**: the grid is a tool's chrome, and
2338 /// every sample and every golden image predates it.
2339 ground_grid_on: bool,
2340
2341 /// The debug draw layer's immediate-mode buffer and its pass — see
2342 /// [`crate::debug_draw`].
2343 ///
2344 /// Always present and empty by default, because appending to it is what a
2345 /// system does and the buffer is a `Vec`; the pipeline and the rings inside
2346 /// it are what stay unbuilt until a frame has both a segment and
2347 /// [`crate::debug_draw::r_debug_draw`] switched on.
2348 debug_draw: DebugDraw,
2349
2350 /// The shadow atlas viewer — see [`crate::atlas_view`]. It draws on no frame
2351 /// but the one [`debug_view`](Self::debug_view) resolved to
2352 /// [`DebugView::ShadowAtlas`], which is none until a caller calls
2353 /// [`set_atlas_view`](Self::set_atlas_view).
2354 atlas_viewer: AtlasView,
2355 /// How large the internal render target is as a fraction of the extent a
2356 /// caller hands `begin_frame` — see [`set_render_scale`](Self::set_render_scale).
2357 render_scale: f32,
2358
2359 /// The three layers a caller supplies — see [`crate::effects`].
2360 effect_request: EffectRequest,
2361 /// The fourth layer: what this device can draw, which clamps last and
2362 /// absolutely.
2363 ///
2364 /// **Every effect, and that is a fact about the effects rather than an
2365 /// unfinished clamp.** Topic 18 says so of the occlusion pair in as many
2366 /// words — "there is no device fact to gate on … inventing a capability that
2367 /// is really a performance opinion is what topic 39 exists to prevent" — and
2368 /// the reflection pair's module says it of itself. The shadow atlas is a
2369 /// `D32Float` image and a depth-only pass, which is not something a device
2370 /// that got this far can be missing either: one too small for the atlas
2371 /// fails to *build* this renderer rather than degrading past it.
2372 ///
2373 /// So the clamp is real and its rule set is empty. The first rule arrives
2374 /// with the ray-traced variants of these same three effects, which
2375 /// [`LightingPath`](crcbl_hal::LightingPath) selects and which nothing
2376 /// builds yet.
2377 device_effects: RenderEffects,
2378 /// What the frame [`begin_frame`](ForwardRenderer::begin_frame) opened
2379 /// draws, resolved once there.
2380 ///
2381 /// **Frozen for the frame on purpose.** `begin_frame` skips a shadow cull's
2382 /// parameter write when shadows are off and
2383 /// [`add_passes`](ForwardRenderer::add_passes) skips its dispatch; a request
2384 /// changed between the two would dispatch a cull whose counters nothing
2385 /// zeroed, which is a plausible frame drawn off last frame's numbers.
2386 frame_effects: RenderEffects,
2387 /// How many blur passes the frame [`begin_frame`](ForwardRenderer::begin_frame)
2388 /// opened runs over the raw occlusion channel — [`crate::ssao::blur_passes`],
2389 /// read once there.
2390 ///
2391 /// **Frozen for the frame on [`ForwardRenderer::frame_effects`]'s terms.**
2392 /// [`add_passes`](ForwardRenderer::add_passes) both counts the frame's
2393 /// full-screen triangles and records its passes, and a console command
2394 /// landing between the two reads would leave `counters` describing a frame
2395 /// that was never submitted.
2396 frame_ssao_blurs: u32,
2397 /// Full-screen passes the last [`add_passes`](ForwardRenderer::add_passes)
2398 /// recorded, which is what [`counters`](ForwardRenderer::counters) reports
2399 /// as submitted beside the pool's instances.
2400 ///
2401 /// Stored rather than re-derived from [`ForwardRenderer::frame_effects`]:
2402 /// `counters` describes the frame that *was* recorded, and a request set
2403 /// after it would otherwise change the count of a frame already submitted.
2404 recorded_fullscreen: u64,
2405
2406 /// Whether the last [`add_passes`](ForwardRenderer::add_passes) recorded the
2407 /// debug draw layer's pass, as the one direct draw it costs.
2408 ///
2409 /// Separate from [`ForwardRenderer::recorded_fullscreen`] because it is not
2410 /// a full-screen triangle: it is one line-list draw of every segment this
2411 /// frame appended. Both are direct draws of one instance, which is what
2412 /// [`ForwardRenderer::direct_draws`] adds up.
2413 recorded_debug_draw: u64,
2414 /// How many tiles of the shadow atlas the last
2415 /// [`add_passes`](ForwardRenderer::add_passes) reset with a draw rather
2416 /// than with the attachment's own clear.
2417 ///
2418 /// Zero on every frame that clears the whole attachment, which is every
2419 /// frame until the cadence is switched on — see
2420 /// [`MeshModules::depth_clear_pipeline`]. One over-sized triangle of one
2421 /// instance each, so it joins the full-screen draws rather than the
2422 /// indirect ones.
2423 recorded_tile_clears: u64,
2424 /// `docs/plan/55-water.md`'s bodies of water, meshed, and the ring of
2425 /// buffers every view draws them from — see [`crate::water`]. Empty until
2426 /// [`set_water`](ForwardRenderer::set_water), and an empty set records no
2427 /// pass.
2428 water: WaterBodies,
2429 /// The surface draws the last [`add_passes`](ForwardRenderer::add_passes)
2430 /// recorded for the primary camera: one indexed draw per body, each of one
2431 /// instance, so they join the direct draws on the debug draw layer's terms.
2432 recorded_water_draws: u64,
2433 /// `docs/plan/57-grass.md`'s field, its device resources and the ring of
2434 /// retirements a replaced one leaves — see [`crate::grass`]. Empty until
2435 /// [`set_grass`](ForwardRenderer::set_grass), and an empty field records no
2436 /// pass.
2437 grass: GrassScene,
2438 /// The wind block every view writes into its own ring — see
2439 /// [`set_wind`](ForwardRenderer::set_wind). Calm until a caller sets one.
2440 wind: crcbl_shaders::wind::WindParams,
2441 /// The grass draws the last [`add_passes`](ForwardRenderer::add_passes)
2442 /// recorded for the primary camera: one per tile slot per look the field
2443 /// draws.
2444 ///
2445 /// **Not among the direct draws**, unlike the water surface's: every one of
2446 /// them is an indirect call whose instance count lives in a buffer a
2447 /// dispatch wrote, so the CPU knows how many *calls* it submitted and
2448 /// nothing about how many blades came out of them.
2449 recorded_grass_draws: u64,
2450}
2451
2452/// What a partly-built [`ForwardRenderer`] has to give back.
2453///
2454/// `new` creates a dozen objects with `?` between them, and the seam's
2455/// `destroy_*` is explicit — so a failure half way through used to leak
2456/// everything created before it. The recorder's leak assertions cover the happy
2457/// path; this covers the other one.
2458#[derive(Debug, Default)]
2459struct Rollback {
2460 buffers: Vec<BufferHandle>,
2461 bind_groups: Vec<BindGroupHandle>,
2462 bind_group_layouts: Vec<BindGroupLayoutHandle>,
2463 pipeline_layouts: Vec<PipelineLayoutHandle>,
2464 pipelines: Vec<GraphicsPipelineHandle>,
2465 samplers: Vec<SamplerHandle>,
2466 /// The shadow atlas and its placeholder, which are created here rather than
2467 /// uploaded — so unlike [`Rollback::textures`] they are a plain handle each,
2468 /// with their views beside them.
2469 images: Vec<ImageHandle>,
2470 image_views: Vec<ImageViewHandle>,
2471 /// Uploaded images, which own a view each and so cannot be rolled back as
2472 /// one list of handles.
2473 textures: Vec<UploadedTexture>,
2474 /// The geometry pool, which owns two buffers, a semaphore and anything
2475 /// still staged — so it cannot be rolled back as a list of handles.
2476 pool: Option<MeshPool>,
2477 /// The instance pool, which owns one buffer per frame in flight.
2478 instances: Option<InstancePool>,
2479 /// The material table, which owns one buffer.
2480 materials: Option<MaterialTable>,
2481 /// The irradiance probe table, which owns one buffer.
2482 probes: Option<ProbeTable>,
2483 /// The irradiance probes' updater, which owns one pipeline,
2484 /// one layout and a ring of blocks — and only exists for a scene whose
2485 /// volume asked to be updated.
2486 probe_gather: Option<ProbeGather>,
2487 /// The cull and draw-argument passes, which own two pipelines and a ring of
2488 /// buffers each — and which clean themselves up on their own failure path,
2489 /// so this only carries one that was built.
2490 draws: Option<DrawGen>,
2491 /// One more of the same per shadow-atlas tile — a `Vec` rather than an
2492 /// `Option`, because a failure part way through the tiles has to release the
2493 /// ones already built.
2494 shadow_draws: Vec<DrawGen>,
2495 /// The cluster buffers, which own three buffers and are built on the
2496 /// mesh-shader path alone.
2497 clusters: Option<ClusterPool>,
2498 /// Topic 18's light list and froxel grid, which own a pipeline and a ring of
2499 /// three buffers — and which clean themselves up on their own failure path,
2500 /// so this only carries one that was built.
2501 lights: Option<LightGrid>,
2502 /// Topic 46's occlusion pair, which owns two
2503 /// pipelines, two layouts and a ring of blocks.
2504 ssao: Option<Ssao>,
2505 /// Topic 45's contact-shadow march, which owns one
2506 /// pipeline, one layout and a ring of blocks.
2507 contact_shadows: Option<ContactShadows>,
2508 /// Topic 47's depth pyramid, which owns one
2509 /// pipeline, one layout and a ring of blocks per level.
2510 hiz: Option<Hiz>,
2511 /// Topic 03 §3.3's farthest-depth pyramid,
2512 /// which owns one pipeline, one layout and — once a frame culled — a chain
2513 /// of level images.
2514 occlusion_pyramid: Option<OcclusionPyramid>,
2515 /// Topic 47's reflection march, which owns one
2516 /// pipeline, one layout and a ring of blocks.
2517 ssr: Option<Ssr>,
2518 /// The froxel volume, which owns three
2519 /// pipelines, two layouts and two rings of buffers.
2520 volumetric: Option<Volumetric>,
2521 /// Topic 43 §6's auto-exposure, which owns three
2522 /// pipelines, one layout and three rings of buffers.
2523 exposure: Option<Exposure>,
2524 /// Topic 48's bloom chain, which owns three
2525 /// pipelines, two layouts, a sampler and a ring of blocks.
2526 bloom: Option<Bloom>,
2527 /// The cheap antialiasing tier, which owns one
2528 /// pipeline, one layout, a sampler and a ring of blocks.
2529 fxaa: Option<Fxaa>,
2530 /// The higher antialiasing tier, which owns
2531 /// four compute pipelines, one graphics pipeline, two layouts and a ring of
2532 /// blocks.
2533 cmaa2: Option<Cmaa2>,
2534 upscale: Option<Upscale>,
2535 /// The background pass, which owns one pipeline, one layout and a ring of
2536 /// blocks and groups.
2537 sky_pass: Option<SkyPass>,
2538 /// The water surface's two pipelines, their layouts and a ring of blocks.
2539 water: Option<Water>,
2540 /// The grass passes' pipelines, their layouts and their rings of
2541 /// blocks.
2542 grass: Option<Grass>,
2543 /// The shadow atlas viewer, which owns one pipeline, one layout and a ring
2544 /// of blocks and groups.
2545 atlas_viewer: Option<AtlasView>,
2546 /// The camera, once [`View::build`] has made it whole — released as one,
2547 /// by [`View::destroy`].
2548 primary: Option<View>,
2549}
2550
2551impl Rollback {
2552 /// Releases everything, in the same dependency order as
2553 /// [`ForwardRenderer::destroy`].
2554 fn run(self, device: &dyn Device) {
2555 if let Some(view) = self.primary {
2556 view.destroy(device);
2557 }
2558 for texture in self.textures {
2559 texture.destroy(device);
2560 }
2561 for handle in self.samplers {
2562 device.destroy_sampler(handle);
2563 }
2564 for handle in self.image_views {
2565 device.destroy_image_view(handle);
2566 }
2567 for handle in self.images {
2568 device.destroy_image(handle);
2569 }
2570 for handle in self.pipelines {
2571 device.destroy_graphics_pipeline(handle);
2572 }
2573 for handle in self.pipeline_layouts {
2574 device.destroy_pipeline_layout(handle);
2575 }
2576 for handle in self.bind_groups {
2577 device.destroy_bind_group(handle);
2578 }
2579 for handle in self.bind_group_layouts {
2580 device.destroy_bind_group_layout(handle);
2581 }
2582 for handle in self.buffers {
2583 device.destroy_buffer(handle);
2584 }
2585 if let Some(clusters) = self.clusters {
2586 clusters.destroy(device);
2587 }
2588 for draws in self.shadow_draws {
2589 draws.destroy(device);
2590 }
2591 if let Some(lights) = self.lights {
2592 lights.destroy(device);
2593 }
2594 if let Some(atlas_viewer) = self.atlas_viewer {
2595 atlas_viewer.destroy(device);
2596 }
2597 if let Some(grass) = self.grass {
2598 grass.destroy(device);
2599 }
2600 if let Some(water) = self.water {
2601 water.destroy(device);
2602 }
2603 if let Some(sky_pass) = self.sky_pass {
2604 sky_pass.destroy(device);
2605 }
2606 if let Some(upscale) = self.upscale {
2607 upscale.destroy(device);
2608 }
2609 if let Some(cmaa2) = self.cmaa2 {
2610 cmaa2.destroy(device);
2611 }
2612 if let Some(fxaa) = self.fxaa {
2613 fxaa.destroy(device);
2614 }
2615 if let Some(bloom) = self.bloom {
2616 bloom.destroy(device);
2617 }
2618 if let Some(exposure) = self.exposure {
2619 exposure.destroy(device);
2620 }
2621 if let Some(volumetric) = self.volumetric {
2622 volumetric.destroy(device);
2623 }
2624 if let Some(ssr) = self.ssr {
2625 ssr.destroy(device);
2626 }
2627 if let Some(occlusion_pyramid) = self.occlusion_pyramid {
2628 occlusion_pyramid.destroy(device);
2629 }
2630 if let Some(hiz) = self.hiz {
2631 hiz.destroy(device);
2632 }
2633 if let Some(contact_shadows) = self.contact_shadows {
2634 contact_shadows.destroy(device);
2635 }
2636 if let Some(ssao) = self.ssao {
2637 ssao.destroy(device);
2638 }
2639 if let Some(draws) = self.draws {
2640 draws.destroy(device);
2641 }
2642 // Before the table, because its bind groups name that table's rows.
2643 if let Some(gather) = self.probe_gather {
2644 gather.destroy(device);
2645 }
2646 if let Some(table) = self.probes {
2647 table.destroy(device);
2648 }
2649 if let Some(table) = self.materials {
2650 table.destroy(device);
2651 }
2652 if let Some(pool) = self.instances {
2653 pool.destroy(device);
2654 }
2655 if let Some(pool) = self.pool {
2656 pool.destroy(device);
2657 }
2658 }
2659}
2660
2661/// What every bind group of the mesh layout names identically.
2662///
2663/// Split from [`MeshGroup`] rather than folded into it because the split *is*
2664/// the claim: a resource here cannot differ between the colour pass's group and
2665/// a cascade's, and one there must be looked at.
2666struct SharedBindings<'a> {
2667 vertices: BufferHandle,
2668 draw_constants: BufferHandle,
2669 mesh_table: BufferHandle,
2670 materials: BufferHandle,
2671 /// Bindings [`BASE_COLOR_PAGE_BINDING`], [`NORMAL_PAGE_BINDING`],
2672 /// [`MRO_PAGE_BINDING`] and [`EMISSIVE_PAGE_BINDING`] — the four material
2673 /// pages, every one read through the sampler at [`PAGE_SAMPLER_BINDING`]
2674 /// beside them — as this frame slot names them, which is what
2675 /// [`ForwardRenderer::adopt_pages`] moves one slot at a time.
2676 pages: PageBindings,
2677 /// `Some` on [`GeometryPath::MeshShader`] and on no other path, which is
2678 /// what decides whether the mesh-only bindings exist at all.
2679 clusters: Option<&'a ClusterPool>,
2680 shadow_sampler: SamplerHandle,
2681 /// Bindings [`LIGHT_LIST_BINDING`] and [`LIGHT_GRID_BINDING`], this frame's
2682 /// slots of the light ring.
2683 ///
2684 /// Shared rather than per-group, unlike the instance array beside them, and
2685 /// that is the claim: **a cascade shades nothing**, so it reads the same
2686 /// list and the same grid the colour pass does — the depth-only pipeline
2687 /// simply never looks. Two buffers per pass would be two clustering
2688 /// dispatches for one camera.
2689 lights: BufferHandle,
2690 light_grid: BufferHandle,
2691 /// Binding [`PROBE_TABLE_BINDING`], **this frame's slot** of the irradiance
2692 /// grid's ring.
2693 ///
2694 /// Shared across the *groups of one frame* rather than across frames, which
2695 /// is the light list's arrangement exactly: a cascade shades nothing, so it
2696 /// reads the same rows the colour pass does and the depth-only pipeline
2697 /// simply never looks. What it is not is shared across the ring — see
2698 /// [`crate::probe`] for why the table is per-frame at all.
2699 probes: BufferHandle,
2700 /// Binding [`LEVEL_GROUP_TABLE_BINDING`], `DrawGen`'s packed table buffer.
2701 ///
2702 /// Shared rather than per-group for the probe grid's reason exactly: the
2703 /// regions are written when a mesh becomes resident and never per frame, so
2704 /// a cascade and the colour pass read the same words. What varies between
2705 /// them is the *budget* the mesh stage projects against, and that rides in
2706 /// each pass's own frame block.
2707 tables: BufferHandle,
2708 /// Binding [`SPECULAR_DFG_BINDING`], the split-sum `DFG` pair — see
2709 /// [`ForwardRenderer::specular_dfg`].
2710 ///
2711 /// Shared rather than per-group for the probe grid's reason and more
2712 /// strongly: it is cooked into the binary, uploaded once at build and
2713 /// identical for every view this engine will ever draw. A cascade names it
2714 /// and never looks.
2715 specular_dfg: ImageViewHandle,
2716 /// Binding [`LTC_TABLE_BINDING`], the area lights' fit — see
2717 /// [`ForwardRenderer::ltc_table`]. Shared for the table above it's reason.
2718 ltc_table: ImageViewHandle,
2719}
2720
2721/// The half of a mesh-layout bind group that differs between the colour pass and
2722/// each shadow cascade.
2723///
2724/// One description for both, so the two cannot drift: a cascade's group is the
2725/// colour pass's with six resources swapped, and swapping the wrong five of them
2726/// is a shadow map rendered from the camera — which looks like a shadow map.
2727struct MeshGroup {
2728 /// Binding 0. The colour pass's frame block, or a cascade's copy whose
2729 /// `view_proj` is that cascade's matrix.
2730 uniforms: BufferHandle,
2731 /// Binding 2. This frame's slot of the instance ring.
2732 instances: BufferHandle,
2733 /// Binding 5. Whose survivors this group draws.
2734 runs: BufferHandle,
2735 /// Binding 12, on the mesh path: the same survivors' indirect arguments,
2736 /// read as data.
2737 args: BufferHandle,
2738 /// Binding 13, where there is an amplification stage: the frustum it culls
2739 /// clusters against.
2740 cull_params: BufferHandle,
2741 /// Binding 14, likewise: what it counts survivors into.
2742 cull_stats: BufferHandle,
2743 /// Binding 18, likewise: the cut the descent chose, one word per resident
2744 /// cluster. `None` exactly where there is no amplification stage, which is
2745 /// where the layout has no CLUSTER_SELECTION_BINDING either.
2746 ///
2747 /// **A buffer per pass**, not one shared: the colour pass is recorded last,
2748 /// so a cascade writing the camera's would leave nothing of its own to read.
2749 /// See [`ForwardRenderer::shadow_selection`].
2750 cluster_selection: Option<BufferHandle>,
2751 /// Binding 19, likewise: topic 25's hysteresis state, which the
2752 /// draw-argument pass wrote this frame and this one only reads.
2753 ///
2754 /// **A buffer per pass** as well, because the colour pass and a cascade
2755 /// judge the same groups under different budgets — see
2756 /// [`TileBuffers::group_state`].
2757 group_state: Option<BufferHandle>,
2758 /// Binding [`SHADOW_ATLAS_BINDING`]. The atlas for the pass that reads it,
2759 /// and the placeholder for the pass that writes it — see
2760 /// [`ForwardRenderer::shadow_placeholder`], which is where that is argued.
2761 shadow_map: ImageViewHandle,
2762 /// Binding [`AMBIENT_OCCLUSION_BINDING`]. The blurred occlusion channel for
2763 /// a forward pass that computed one, and the white placeholder everywhere
2764 /// else — see [`ForwardRenderer::ambient_occlusion_placeholder`].
2765 ///
2766 /// **Every group built at `build` names the placeholder**, including the
2767 /// camera's: the occlusion image may be a graph transient whose view exists
2768 /// only at execute time, so the camera's group is rebuilt against whatever
2769 /// the frame bound inside the forward pass and cached — the shape
2770 /// [`View::tonemap_groups`] already has.
2771 ambient_occlusion: ImageViewHandle,
2772 /// Binding [`CONTACT_SHADOW_BINDING`]. The contact-shadow channel for a
2773 /// forward pass that marched one, and the white placeholder everywhere else
2774 /// — see [`ForwardRenderer::contact_shadow_placeholder`].
2775 ///
2776 /// [`MeshGroup::ambient_occlusion`]'s terms exactly, including that every
2777 /// group built at `build` names the placeholder.
2778 contact_shadow: ImageViewHandle,
2779 /// Binding [`PROBE_VISIBILITY_BINDING`]. The captured per-probe visibility
2780 /// maps for the camera's pass, and the one-texel placeholder everywhere
2781 /// else — see [`ForwardRenderer::probe_visibility_placeholder`].
2782 ///
2783 /// [`MeshGroup::ambient_occlusion`]'s terms, with one difference: the image
2784 /// is not a graph transient but an ordinary uploaded texture, so what makes
2785 /// this a per-frame swap is the console switch and whether a capture has
2786 /// happened yet — neither of which is known at `build`.
2787 probe_visibility: ImageViewHandle,
2788}
2789
2790impl MeshGroup {
2791 fn entries(&self, shared: &SharedBindings<'_>) -> Vec<BindGroupEntry> {
2792 let mut entries = vec![
2793 BindGroupEntry {
2794 binding: 0,
2795 array_index: 0,
2796 resource: BindingResource::whole_buffer(self.uniforms),
2797 },
2798 BindGroupEntry {
2799 binding: 1,
2800 array_index: 0,
2801 resource: BindingResource::whole_buffer(shared.vertices),
2802 },
2803 BindGroupEntry {
2804 binding: 2,
2805 array_index: 0,
2806 // **This frame's slot of the instance ring, not a shared
2807 // buffer.** Binding one buffer here for every group would undo
2808 // the ring and reintroduce the cross-submission
2809 // read-after-write hazard it exists to prevent.
2810 resource: BindingResource::whole_buffer(self.instances),
2811 },
2812 BindGroupEntry {
2813 binding: 3,
2814 array_index: 0,
2815 // **One block, not the whole buffer.** The binding is dynamic,
2816 // so the bind's offset is added on top of this one and both
2817 // Vulkan and WebGPU require `offset + dynamic + size` to stay
2818 // inside the buffer — bound whole, the very first non-zero
2819 // dynamic offset would be out of range.
2820 resource: BindingResource::Buffer {
2821 buffer: shared.draw_constants,
2822 offset: 0,
2823 size: DRAW_CONSTANTS_BLOCK,
2824 },
2825 },
2826 BindGroupEntry {
2827 binding: 4,
2828 array_index: 0,
2829 // The same table in every group, unlike the instance array
2830 // above it: the pool writes an entry when a mesh is uploaded or
2831 // freed, neither of which happens between frames here.
2832 resource: BindingResource::whole_buffer(shared.mesh_table),
2833 },
2834 BindGroupEntry {
2835 binding: 5,
2836 array_index: 0,
2837 // Whose cull this group draws from. This is the binding a
2838 // cascade's group differs in most consequentially: it is what
2839 // makes the shadow pass draw what the *light* can see rather
2840 // than what the camera can.
2841 resource: BindingResource::whole_buffer(self.runs),
2842 },
2843 BindGroupEntry {
2844 binding: 6,
2845 array_index: 0,
2846 resource: BindingResource::whole_buffer(shared.materials),
2847 },
2848 BindGroupEntry {
2849 binding: BASE_COLOR_PAGE_BINDING,
2850 array_index: 0,
2851 // **One entry, `array_index: 0`**, because the page is one
2852 // image and the layer is chosen in the shader. A bindless array
2853 // would be one entry per texture at ascending array indices,
2854 // which is the write path `BindGroupEntry`'s own docs describe
2855 // and the one this pass does not take.
2856 resource: BindingResource::ImageView(
2857 shared.pages.views[PageKind::BaseColor.index()],
2858 ),
2859 },
2860 BindGroupEntry {
2861 binding: PAGE_SAMPLER_BINDING,
2862 array_index: 0,
2863 resource: BindingResource::Sampler(shared.pages.sampler),
2864 },
2865 ];
2866 if let Some(clusters) = shared.clusters {
2867 entries.extend([
2868 BindGroupEntry {
2869 binding: CLUSTERS_BINDING,
2870 array_index: 0,
2871 // The same three buffers in every group, on the mesh table's
2872 // terms: clusters are written when the pool is built and
2873 // never again.
2874 resource: BindingResource::whole_buffer(clusters.clusters()),
2875 },
2876 BindGroupEntry {
2877 binding: CLUSTER_VERTICES_BINDING,
2878 array_index: 0,
2879 resource: BindingResource::whole_buffer(clusters.vertices()),
2880 },
2881 BindGroupEntry {
2882 binding: CLUSTER_CORNERS_BINDING,
2883 array_index: 0,
2884 resource: BindingResource::whole_buffer(clusters.corners()),
2885 },
2886 BindGroupEntry {
2887 binding: CLUSTER_DRAW_ARGS_BINDING,
2888 array_index: 0,
2889 // **Arguments read as data.** The mesh path records no
2890 // indirect draw at all; what it wants out of this buffer is
2891 // the one word only the GPU knows — how many instances
2892 // survived into each bucket.
2893 resource: BindingResource::whole_buffer(self.args),
2894 },
2895 ]);
2896 }
2897 // Both mesh entry points retain these native buffer arguments even
2898 // when no amplification stage reads them.
2899 if shared.clusters.is_some() {
2900 entries.extend([
2901 BindGroupEntry {
2902 binding: CLUSTER_CULL_BINDING,
2903 array_index: 0,
2904 resource: BindingResource::whole_buffer(self.cull_params),
2905 },
2906 BindGroupEntry {
2907 binding: CLUSTER_CULL_STATS_BINDING,
2908 array_index: 0,
2909 resource: BindingResource::whole_buffer(self.cull_stats),
2910 },
2911 ]);
2912 }
2913 entries.push(BindGroupEntry {
2914 binding: SHADOW_ATLAS_BINDING,
2915 array_index: 0,
2916 resource: BindingResource::ImageView(self.shadow_map),
2917 });
2918 entries.push(BindGroupEntry {
2919 binding: SHADOW_SAMPLER_BINDING,
2920 array_index: 0,
2921 resource: BindingResource::Sampler(shared.shadow_sampler),
2922 });
2923 // Mesh-only buffers are sorted after the common fragment prefix below.
2924 if let Some(clusters) = shared.clusters {
2925 entries.push(BindGroupEntry {
2926 binding: CLUSTER_SELECT_BINDING,
2927 array_index: 0,
2928 // Bound with the geometry rather than with the cull, because
2929 // `vertex_base` *is* geometry: it is which level of a DAG a
2930 // cluster's vertices live in, and both mesh entry points resolve
2931 // a vertex through it.
2932 resource: BindingResource::whole_buffer(clusters.selection()),
2933 });
2934 }
2935 if let Some(selection) = self.cluster_selection {
2936 entries.push(BindGroupEntry {
2937 binding: CLUSTER_SELECTION_BINDING,
2938 array_index: 0,
2939 resource: BindingResource::whole_buffer(selection),
2940 });
2941 }
2942 if let Some(state) = self.group_state {
2943 entries.push(BindGroupEntry {
2944 binding: CLUSTER_GROUP_STATE_BINDING,
2945 array_index: 0,
2946 resource: BindingResource::whole_buffer(state),
2947 });
2948 }
2949 // Topic 18's pair, on every path and in every group — see the layout,
2950 // which has no configuration that omits them either.
2951 entries.push(BindGroupEntry {
2952 binding: LIGHT_LIST_BINDING,
2953 array_index: 0,
2954 resource: BindingResource::whole_buffer(shared.lights),
2955 });
2956 entries.push(BindGroupEntry {
2957 binding: LIGHT_GRID_BINDING,
2958 array_index: 0,
2959 resource: BindingResource::whole_buffer(shared.light_grid),
2960 });
2961 // Shared fragment textures and probes retain their raster bindings.
2962 entries.push(BindGroupEntry {
2963 binding: AMBIENT_OCCLUSION_BINDING,
2964 array_index: 0,
2965 resource: BindingResource::ImageView(self.ambient_occlusion),
2966 });
2967 // And the irradiance grid past it — see [`PROBE_TABLE_BINDING`].
2968 entries.push(BindGroupEntry {
2969 binding: PROBE_TABLE_BINDING,
2970 array_index: 0,
2971 resource: BindingResource::whole_buffer(shared.probes),
2972 });
2973 // Group records are present on both mesh paths, matching the layout.
2974 if shared.clusters.is_some() {
2975 entries.push(BindGroupEntry {
2976 binding: LEVEL_GROUP_TABLE_BINDING,
2977 array_index: 0,
2978 resource: BindingResource::whole_buffer(shared.tables),
2979 });
2980 }
2981 // The DFG texture is read by the fragment stage of every path.
2982 entries.push(BindGroupEntry {
2983 binding: SPECULAR_DFG_BINDING,
2984 array_index: 0,
2985 resource: BindingResource::ImageView(shared.specular_dfg),
2986 });
2987 // And §2's normal page above that, on the same ascending terms — see
2988 // [`NORMAL_PAGE_BINDING`]. Unconditional and `array_index: 0` for
2989 // binding 7's reason: one image, and the layer is chosen in the shader.
2990 entries.push(BindGroupEntry {
2991 binding: NORMAL_PAGE_BINDING,
2992 array_index: 0,
2993 resource: BindingResource::ImageView(shared.pages.views[PageKind::Normal.index()]),
2994 });
2995 // And the area lights' table above that, on the same ascending terms —
2996 // see [`LTC_TABLE_BINDING`].
2997 entries.push(BindGroupEntry {
2998 binding: LTC_TABLE_BINDING,
2999 array_index: 0,
3000 resource: BindingResource::ImageView(shared.ltc_table),
3001 });
3002 // And the contact-shadow channel above that, last of the set and on the
3003 // same ascending terms — see [`CONTACT_SHADOW_BINDING`].
3004 entries.push(BindGroupEntry {
3005 binding: CONTACT_SHADOW_BINDING,
3006 array_index: 0,
3007 resource: BindingResource::ImageView(self.contact_shadow),
3008 });
3009 // And the probe visibility maps above that, on the same ascending terms
3010 // — see [`PROBE_VISIBILITY_BINDING`].
3011 entries.push(BindGroupEntry {
3012 binding: PROBE_VISIBILITY_BINDING,
3013 array_index: 0,
3014 resource: BindingResource::ImageView(self.probe_visibility),
3015 });
3016 // And §2's other two pages above that, last of the set and on the same
3017 // ascending terms — see [`MRO_PAGE_BINDING`] and
3018 // [`EMISSIVE_PAGE_BINDING`]. Unconditional and `array_index: 0` for the
3019 // normal page's reason: one image apiece, and the layer is chosen in
3020 // the shader.
3021 entries.push(BindGroupEntry {
3022 binding: MRO_PAGE_BINDING,
3023 array_index: 0,
3024 resource: BindingResource::ImageView(
3025 shared.pages.views[PageKind::MetallicRoughnessOcclusion.index()],
3026 ),
3027 });
3028 entries.push(BindGroupEntry {
3029 binding: EMISSIVE_PAGE_BINDING,
3030 array_index: 0,
3031 resource: BindingResource::ImageView(shared.pages.views[PageKind::Emissive.index()]),
3032 });
3033 entries.sort_by_key(|entry| entry.binding);
3034 entries
3035 }
3036}
3037
3038/// The two `ArrayPages` images every group of the mesh layout names, as the
3039/// graph knows them.
3040///
3041/// One value rather than two arguments because the two travel together
3042/// everywhere: every pass that declares one declares the other, and a pass
3043/// handed them the wrong way round would order a caller's copy into the wrong
3044/// image — which is a barrier bug, and therefore one that reproduces on one
3045/// backend and not the others.
3046#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3047struct MaterialPages {
3048 /// §3.2's base-colour page — [`ForwardRenderer::base_color_page_import`].
3049 base_color: ImageId,
3050 /// §2's normal page — [`ForwardRenderer::normal_page_import`].
3051 normal: ImageId,
3052 /// §2's metallic-roughness-occlusion page —
3053 /// [`ForwardRenderer::mro_page_import`].
3054 mro: ImageId,
3055 /// §2's emissive page — [`ForwardRenderer::emissive_page_import`].
3056 emissive: ImageId,
3057}
3058
3059/// Everything [`ForwardRenderer::add_shadow_pass`] declares and does not write,
3060/// as the graph knows it.
3061///
3062/// One value rather than an argument apiece for [`MaterialPages`]' reason, and
3063/// the list grew past what an argument list should be the moment the probe rows
3064/// joined it: each of these is in every cascade's bind group and read by no
3065/// cascade, so what the pass does with them is one thing — declare them, so the
3066/// graph can order whoever writes them against these draws.
3067#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3068struct ShadowReads {
3069 /// The occlusion placeholder every cascade's group stands the real channel
3070 /// in for — [`ForwardRenderer::ambient_occlusion_placeholder`].
3071 occlusion_placeholder: ImageId,
3072 /// §3.2's and §2's pages, which the cascades name and never sample.
3073 pages: MaterialPages,
3074 /// The skinned vertex region, where a frame has one — the cascades pull the
3075 /// same geometry the colour pass does.
3076 skinned: Option<BufferId>,
3077 /// This frame's slot of the probe ring — see [`crate::probe`].
3078 probes: BufferId,
3079}
3080
3081/// What the mesh pass's bind-group layout is called.
3082///
3083/// Named rather than written twice because a test asserts on it: the layout's
3084/// *binding numbers* are what `crcbl-mtl` turns into Metal argument-table
3085/// indices by counting, so `the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage`
3086/// has to find this one layout among the recorder's.
3087const MESH_LAYOUT_LABEL: &str = "mesh frame";
3088
3089/// Imports a buffer a pass both reads and writes, carried from one frame on
3090/// its slot to the next: it arrives in the state the previous frame that used
3091/// the slot left it in, and that is the state it is declared to leave in.
3092///
3093/// A record of the cut or a statistics sink, which a pass writes and the next
3094/// frame on the same slot writes again — a barrier naming `Undefined` as its
3095/// source would carry no source scope and order this frame's write against
3096/// nothing.
3097fn import_read_write(graph: &mut RenderGraph<'_>, label: &str, buffer: BufferHandle) -> BufferId {
3098 graph.import_buffer(
3099 label,
3100 ImportedBuffer {
3101 buffer,
3102 initial: ResourceState::ShaderReadWrite,
3103 final_state: ResourceState::ShaderReadWrite,
3104 },
3105 )
3106}
3107
3108/// Declares the buffers a geometry pass reads to find its draws.
3109///
3110/// The other half of [`BucketDraws`]: what the *graph* has to be told, where that
3111/// struct is what the encoder is told. Three passes declare exactly this set, and
3112/// the seam calls the barrier it produces the single most important one in a
3113/// GPU-driven frame — its absence produces "sometimes nothing draws".
3114///
3115/// A caller with a cluster-selection buffer of its own appends it; that is the
3116/// one declaration that differs between the colour pass, a cascade and the depth
3117/// prepass.
3118fn read_draw_sources<'g, 'a>(
3119 pass: PassBuilder<'g, 'a>,
3120 draws: &GeneratedDraws,
3121 emit: EmitTail,
3122) -> PassBuilder<'g, 'a> {
3123 // The buffers the draws come out of. Declaring them is what makes the graph
3124 // transition them out of the compute pass's `ShaderReadWrite`.
3125 let pass = pass.read_buffer(draws.runs_id);
3126 if emit.is_mesh() {
3127 // **The same arguments, read as data rather than executed**, which is
3128 // what the stages use to bound the run of surviving instances they index.
3129 // The per-bucket draw *counts* are not read at all, because nothing here
3130 // is a draw whose count could come from memory.
3131 //
3132 // The dispatch *extents* are a real indirect read — one structure per
3133 // bucket, written by the same pass. They are in a **different buffer**
3134 // from the arguments above and that separation is load-bearing: a
3135 // resource is in exactly one state per pass and these two are in
3136 // different ones. They share a buffer with the counts instead, which
3137 // this path does not read at all — see [`GeneratedDraws::counts`].
3138 let pass = pass
3139 .read_buffer(draws.args_id)
3140 .use_buffer(draws.counts_id, ResourceState::IndirectArgument);
3141 // The amplification stage counts its survivors into the culling
3142 // statistics, which the draw-argument pass read a moment ago — so this
3143 // is a write-after-read the graph has to order, and declaring it is
3144 // the whole of how it learns to.
3145 //
3146 // Topic 25's hysteresis state is read here and written by
3147 // the draw-argument pass a moment ago. Declaring it is what orders the
3148 // two — and what puts it back into `ShaderReadWrite` at the end of the
3149 // graph, which is where the next frame's draw-argument pass expects to
3150 // find it.
3151 //
3152 // **Declared on the whole mesh path, not only where there is an
3153 // amplification stage**, because that is where the bind group now
3154 // names both — see the layout, which is where the Metal argument-table
3155 // arithmetic that forced it is argued. A buffer bound writable and
3156 // never transitioned is a descriptor in the wrong resource state, which
3157 // is what the graph exists to prevent.
3158 pass.use_buffer(draws.visible_count_id, ResourceState::ShaderReadWrite)
3159 .read_buffer(draws.group_state_id)
3160 } else {
3161 pass.use_buffer(draws.args_id, ResourceState::IndirectArgument)
3162 .use_buffer(draws.counts_id, ResourceState::IndirectArgument)
3163 }
3164}
3165
3166/// What one [`MeshDesc`](crate::scene::MeshDesc) became once it was resident.
3167///
3168/// One of these per description mesh, in description order — so a mesh's index
3169/// here is its index there, which is what lets the bucket table, the level
3170/// tables and the cluster pool all be filled in by walking one list.
3171struct ResidentMesh {
3172 /// This mesh's table ids, finest first: one entry for a flat mesh, one per
3173 /// level for a DAG. Never empty.
3174 ///
3175 /// Every level is its own vertex range and so its own table entry. Level 0's
3176 /// id is the one the *instance* carries and the one the cull pass reads a
3177 /// bounding box out of; the coarser ones are named by the bucket table on a
3178 /// path that takes a uniform cut, and by nothing at all on the mesh path,
3179 /// where a cluster reaches its own level through
3180 /// [`vertex_bases`](Self::vertex_bases) instead.
3181 levels: Vec<u32>,
3182 /// Per level, how far that level's vertices start past level 0's — so a flat
3183 /// mesh's single entry is zero.
3184 ///
3185 /// What [`crcbl_shaders::cluster_select::ClusterSelect::vertex_base`] holds,
3186 /// and the whole of what makes a DAG drawable from one instance: the mesh
3187 /// stage adds this to the instance's own `base_vertex`, so a cut spanning
3188 /// three levels reads three different vertex ranges out of one pool.
3189 vertex_bases: Vec<u32>,
3190 /// Level 0's pool handle, for a mesh that can be **skinned** — and [`None`]
3191 /// for a [`Geometry::Dag`].
3192 ///
3193 /// A DAG is refused because its coarser levels are separate vertex runs no
3194 /// skinning dispatch writes: an instance drawn out of a skinned region
3195 /// resolves every level through [`vertex_bases`](Self::vertex_bases) added
3196 /// to the region's base, which for anything but level 0 is memory the
3197 /// dispatch never touched.
3198 skinnable: Option<MeshHandle>,
3199}
3200
3201impl ResidentMesh {
3202 /// The table id an instance of this mesh carries: **level 0's**, whatever
3203 /// the geometry path, because it is the entry `cull.slang` reads a bounding
3204 /// box out of and the coarser levels approximate the same surface inside the
3205 /// same box.
3206 fn id(&self) -> u32 {
3207 self.levels[0]
3208 }
3209}
3210
3211/// One skinned object the renderer re-points every frame: the instance, and the
3212/// base vertex it draws out of under each parity.
3213///
3214/// The bases are copied out of the [`SkinnedMesh`] rather than borrowed from it,
3215/// so placing an object does not tie the renderer's lifetime to the caller's
3216/// reservation — the renderer never needs the region again, only the two
3217/// numbers.
3218#[derive(Clone, Copy, Debug)]
3219struct SkinnedInstance {
3220 handle: InstanceHandle,
3221 /// Indexed by parity, in [`crate::skinning::SkinnedRegion::base`]'s
3222 /// indexing — so the half a frame of parity `p` draws out of is
3223 /// `bases[p & 1]` and the half the frame before it filled is
3224 /// `bases[(p ^ 1) & 1]`, which is
3225 /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base)'s
3226 /// answer for the same `p`.
3227 bases: [u32; 2],
3228 /// Whether a frame has already pointed this entry at a half of the region
3229 /// it now names.
3230 ///
3231 /// **What makes the previous base meaningful.** The half a frame did not
3232 /// write holds whatever its reservation came with until a dispatch fills
3233 /// it, so an object's first frame out of a region has no previous
3234 /// deformation to point at — naming that half would give it a motion vector
3235 /// against undefined vertices. Such an entry is put at rest instead, which
3236 /// is the rule [`InstancePool::insert`](crate::instance_pool::InstancePool::insert)
3237 /// applies to `previous_transform` for the same reason: a spawn did not
3238 /// travel from anywhere.
3239 pointed: bool,
3240}
3241
3242/// The two base vertices an object drawn out of `mesh` alternates between, in
3243/// [`SkinnedInstance::bases`]' indexing.
3244fn skinned_bases(mesh: &SkinnedMesh) -> [u32; 2] {
3245 [mesh.region().base(0), mesh.region().base(1)]
3246}
3247
3248/// One shadow cull's per-frame buffers, read out of its [`DrawGen`] before that
3249/// generator is handed to the rollback.
3250struct TileBuffers {
3251 runs: Vec<BufferHandle>,
3252 args: Vec<BufferHandle>,
3253 cull_params: Vec<BufferHandle>,
3254 cull_stats: Vec<BufferHandle>,
3255 /// This cull's own hysteresis state, and not the camera's.
3256 ///
3257 /// A shadow view selects from the camera's eye at the camera's scale, like
3258 /// the colour pass, but under budgets [`SHADOW_LOD_BIAS`] times as large — so
3259 /// it reaches a different answer for the same group, and an answer carried
3260 /// between frames needs somewhere of its own to be carried. Sharing the
3261 /// camera's buffer would be two rules writing one history and each undoing
3262 /// the other's band every frame.
3263 ///
3264 /// One per cull rather than one for the shadow pass, even though every one of
3265 /// them selects identically: each cull is its own [`DrawGen`], and one buffer
3266 /// between them would be several dispatches writing one element with nothing
3267 /// ordering them.
3268 ///
3269 /// **This is what a cull costs that is not a dispatch.** It is
3270 /// [`Capacities::instances`](crate::scene::Capacities::instances) × the
3271 /// resident group count words of device-local
3272 /// memory, held for the renderer's whole life whether anything is drawn
3273 /// through it or not, and it is the reason [`shadow::LIGHT_SLOTS`] is a
3274 /// budget rather than "however many lights the scene has" — and the reason a
3275 /// point light's six faces share one of these rather than owning six.
3276 group_state: BufferHandle,
3277}
3278
3279impl ForwardRenderer {
3280 /// Builds both pipelines and makes [`scene::demo`] resident.
3281 ///
3282 /// [`ForwardRenderer::with_scene`] with the engine's own description, and
3283 /// nothing else — so the frame this draws is the one the golden suite has
3284 /// always compared, and every existing caller is untouched.
3285 ///
3286 /// `target_format` must be the format the tonemap pass will render into —
3287 /// dynamic rendering checks pipeline and attachment formats against each
3288 /// other at pass-begin time, not at creation.
3289 ///
3290 /// # Errors
3291 ///
3292 /// [`HalError`], on [`ForwardRenderer::with_scene`]'s terms.
3293 pub fn new(
3294 device: &dyn Device,
3295 queue: QueueHandle,
3296 target_format: Format,
3297 ) -> Result<Self, HalError> {
3298 Self::with_scene(device, queue, target_format, &scene::demo())
3299 }
3300
3301 /// Builds both pipelines and makes `scene` resident.
3302 ///
3303 /// Everything in the description is created here and never grows: the
3304 /// geometry pools, the cluster pool, the material table, the page, the
3305 /// instance array and the bucket table are all sized and filled once. See
3306 /// [`crate::scene`] for why that split is where the seam is, and for the
3307 /// four places a description's *order* decides what the frame looks like.
3308 ///
3309 /// `target_format` must be the format the tonemap pass will render into —
3310 /// dynamic rendering checks pipeline and attachment formats against each
3311 /// other at pass-begin time, not at creation.
3312 ///
3313 /// # No description is too small
3314 ///
3315 /// One mesh and one material row is a scene, and so is
3316 /// [`scene::demo`]'s four and three. Nothing on this type names a
3317 /// description entry by position any more — the five `set_*` demo wrappers
3318 /// that did are gone, and [`ForwardRenderer::add_instance`] takes the mesh
3319 /// and the row a caller wrote its **own** description in.
3320 ///
3321 /// # Errors
3322 ///
3323 /// [`HalError::InvalidDescriptor`] if the description cannot be made
3324 /// resident as written: a page layer that is not its kind's extent's worth of
3325 /// RGBA8, a page kind holding layers at no extent, a material row naming a
3326 /// layer that kind's page has not got, a DAG carrying a vertex array for anything but each of its
3327 /// levels, a cluster array with a read outside itself in it (see
3328 /// [`MeshClusters::check`]), or more vertices, indices, mesh table entries or
3329 /// material rows than [`SceneDesc::capacities`] reserves — that last naming the pool, the
3330 /// capacity and what the description needs, because the answer to it is to
3331 /// raise the number. Every one of those is settled **before the first device
3332 /// object exists**, so a refusal leaks nothing.
3333 ///
3334 /// [`HalError`] otherwise, from any seam call — including the geometry a
3335 /// pool refuses for itself, such as vertex bytes that are not a whole number
3336 /// of vertices. A backend that cannot build a pipeline says so here rather
3337 /// than drawing nothing later, and a failure part-way through releases
3338 /// everything already created, so a caller that retries or exits leaves
3339 /// nothing behind.
3340 pub fn with_scene(
3341 device: &dyn Device,
3342 queue: QueueHandle,
3343 target_format: Format,
3344 scene: &SceneDesc<'_>,
3345 ) -> Result<Self, HalError> {
3346 Self::with_scene_serviced(device, queue, target_format, scene, &mut || {})
3347 }
3348
3349 /// [`ForwardRenderer::with_scene`], calling `service` between the steps of
3350 /// the build so the thread running it can keep its window alive.
3351 ///
3352 /// # What it is for: a build on the thread that owns the window
3353 ///
3354 /// The build needs the device, so it runs on whichever thread holds it —
3355 /// for a game that is the loop thread, which also owns the window, and a
3356 /// desktop marks a window hung when its thread takes no message for a few
3357 /// seconds (see `crcbl_shell::Shell::keep_alive`). A game passes
3358 /// `&mut || shell.keep_alive()` here and the window keeps answering for the
3359 /// whole build.
3360 ///
3361 /// # Where it is called
3362 ///
3363 /// Where the time is, which was measured rather than guessed. With a cold
3364 /// driver shader cache — a player's first launch, or the first after a
3365 /// driver update — **pipeline creation is most of the build**. Measured in
3366 /// 2026-09 on an RX 7900 XTX, release, building one glTF scene: 2.2 to 2.4 s
3367 /// on Vulkan and 1.9 to 2.2 s on D3D12 cold against 0.25 s warm, while the
3368 /// mesh and page uploads took about 0.1 s either way. So `service` runs
3369 /// after every mesh upload (each level of a DAG), after every page layer's
3370 /// mip chain and each page's upload, after each of the camera's
3371 /// post-processing subsystems, before every mesh-pass and grass pipeline,
3372 /// and between the build's other phases.
3373 ///
3374 /// **The longest gap left is one pipeline**, and a pipeline cannot be
3375 /// split: on that scene, cold, it was the forward pass's colour pipeline
3376 /// at 0.31 s on Vulkan and 0.36 s on D3D12, where the build without calls
3377 /// had been one gap of 2 s. Warm, the longest was about 0.04 s. A machine
3378 /// eight times slower under contention still calls back inside the five
3379 /// seconds Windows allows.
3380 ///
3381 /// `service` sees nothing of the build and cannot touch the renderer or the
3382 /// scene. Whatever reaches the window meanwhile — input, a resize, a close
3383 /// request — is the caller's to keep for later, as
3384 /// `crcbl_shell::Shell::keep_alive` does.
3385 ///
3386 /// # Errors
3387 ///
3388 /// [`ForwardRenderer::with_scene`]'s, on its terms: a failure part-way
3389 /// through releases everything already created.
3390 pub fn with_scene_serviced(
3391 device: &dyn Device,
3392 queue: QueueHandle,
3393 target_format: Format,
3394 scene: &SceneDesc<'_>,
3395 service: &mut dyn FnMut(),
3396 ) -> Result<Self, HalError> {
3397 Self::build_on_path(
3398 device,
3399 queue,
3400 target_format,
3401 scene,
3402 device.preferred_geometry_path(),
3403 service,
3404 )
3405 }
3406
3407 /// Builds exactly the requested geometry tail, independently of the device's
3408 /// performance preference. Capabilities remain available to other callers.
3409 ///
3410 /// # Errors
3411 ///
3412 /// Returns [`HalError::UnsupportedFeatures`] before creating device objects
3413 /// when the requested tail lacks its required feature. Other failures follow
3414 /// [`Self::with_scene`]'s rollback contract.
3415 pub fn with_scene_on_path(
3416 device: &dyn Device,
3417 queue: QueueHandle,
3418 target_format: Format,
3419 scene: &SceneDesc<'_>,
3420 geometry_path: GeometryPath,
3421 ) -> Result<Self, HalError> {
3422 Self::build_on_path(
3423 device,
3424 queue,
3425 target_format,
3426 scene,
3427 geometry_path,
3428 &mut || {},
3429 )
3430 }
3431
3432 /// The body of [`Self::with_scene_on_path`] and
3433 /// [`Self::with_scene_serviced`], calling `service` where the latter
3434 /// documents.
3435 fn build_on_path(
3436 device: &dyn Device,
3437 queue: QueueHandle,
3438 target_format: Format,
3439 scene: &SceneDesc<'_>,
3440 geometry_path: GeometryPath,
3441 service: &mut dyn FnMut(),
3442 ) -> Result<Self, HalError> {
3443 let required = match geometry_path {
3444 GeometryPath::MeshShader => crcbl_hal::Features::MESH_SHADER,
3445 GeometryPath::IndirectCount => crcbl_hal::Features::DRAW_INDIRECT_COUNT,
3446 GeometryPath::IndirectPerBatch => crcbl_hal::Features::empty(),
3447 };
3448 let missing = required.difference(device.caps().features);
3449 if !missing.is_empty() {
3450 return Err(HalError::UnsupportedFeatures { missing });
3451 }
3452 let mut rollback = Rollback::default();
3453 match Self::build(
3454 device,
3455 queue,
3456 target_format,
3457 scene,
3458 geometry_path,
3459 &mut rollback,
3460 service,
3461 ) {
3462 Ok(renderer) => Ok(renderer),
3463 Err(error) => {
3464 rollback.run(device);
3465 Err(error)
3466 }
3467 }
3468 }
3469
3470 /// Everything `build` needs to be true of a description, checked **before
3471 /// the first device object exists**.
3472 ///
3473 /// That placement is the whole design of this function. `build` hands the
3474 /// geometry pool and the material table to the rollback and creates a dozen
3475 /// objects with `?` between them; a check that ran part way down that list
3476 /// would be a new early exit on the wrong side of a handover, and a rejected
3477 /// description would leak two device-local buffers. Run from the top of
3478 /// `build`, a refusal costs nothing to unwind because nothing was made.
3479 ///
3480 /// # Errors
3481 ///
3482 /// [`HalError::InvalidDescriptor`] naming the entry that is wrong and what
3483 /// is wrong with it.
3484 fn check_scene(scene: &SceneDesc<'_>) -> Result<(), HalError> {
3485 let refuse = |what: String| Err(HalError::InvalidDescriptor(what));
3486 // A renderer draws meshes, and every table below is sized from them:
3487 // with none, the mesh table's sizing has no level to take a maximum
3488 // of. A scene that draws only the sky is one with meshes and no
3489 // instances.
3490 if scene.meshes.is_empty() {
3491 return refuse(
3492 "a scene description needs at least one mesh; one with meshes and no \
3493 instances draws only the sky"
3494 .to_owned(),
3495 );
3496 }
3497 // Every layer's length against its own kind's extent, and layers at no
3498 // extent at all. Checked by the type that owns the page rather than
3499 // here, because that is where a page can be built wrong and where the
3500 // check can be made to fail; see `PageDesc::check`.
3501 scene.page.check()?;
3502 // The probe grid's counts against the rows it carries, which is what
3503 // bounds the shader's fetch. Checked by the type that owns the grid, on
3504 // `PageDesc::check`'s terms exactly — see `ProbeGrid::check`.
3505 scene.probes.check()?;
3506 // A row naming a layer the page does not have is an out-of-range sample,
3507 // which nothing below the seam reports.
3508 //
3509 // **A column carrying `NO_PAGE` is exempt**, and it is the only exempt
3510 // value: it is a sentinel rather than an index — `0xFFFF`, one past
3511 // `mesh::MAX_PAGE_LAYER`, so no page can grow to hold it — and the
3512 // fragment stage never reads a page for it. Exempting it here is what
3513 // lets a material name no texture without the page having to carry a
3514 // layer for it to point at — or, since row (d), having to exist at all.
3515 //
3516 // **Per kind**, because the kinds are separate images with separate
3517 // layer lists and separate extents: a row pointed at a base-colour layer
3518 // number would pass a check that only counted one of them and then
3519 // sample past the end of the other image.
3520 for (row, material) in scene.materials.iter().enumerate() {
3521 for kind in PageKind::ALL {
3522 let names = match kind {
3523 PageKind::BaseColor => material.base_color_texture,
3524 PageKind::Normal => material.normal_texture,
3525 PageKind::MetallicRoughnessOcclusion => {
3526 material.metallic_roughness_occlusion_texture
3527 }
3528 PageKind::Emissive => material.emissive_texture,
3529 };
3530 if names == mesh::GpuMaterial::NO_PAGE {
3531 continue;
3532 }
3533 let have = scene.page.layers(kind).len();
3534 if names as usize >= have {
3535 return refuse(format!(
3536 "material row {row} samples {} page layer {names}, and that page \
3537 has {have}",
3538 kind.label()
3539 ));
3540 }
3541 }
3542 }
3543
3544 for (index, desc) in scene.meshes.iter().enumerate() {
3545 let Geometry::Dag { levels, dag, .. } = &desc.geometry else {
3546 continue;
3547 };
3548 // Zipped together at upload and again at
3549 // `ClusterDag::selection_records`, so a short list would silently
3550 // leave a level's clusters reading the level below's vertices.
3551 if levels.len() != dag.levels.len() {
3552 return refuse(format!(
3553 "mesh {index} ({}) carries {} vertex array(s) for a DAG of {} level(s)",
3554 desc.label,
3555 levels.len(),
3556 dag.levels.len()
3557 ));
3558 }
3559 for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
3560 let want = level.positions.len() * mesh::VERTEX_STRIDE;
3561 if bytes.len() != want {
3562 return refuse(format!(
3563 "mesh {index} ({}) level {depth} carries {} vertex byte(s) for {} \
3564 position(s), which is {want}",
3565 desc.label,
3566 bytes.len(),
3567 level.positions.len()
3568 ));
3569 }
3570 }
3571 }
3572
3573 // **Every read the mesh stage makes from a cluster array lands inside
3574 // it.** Checked by the type that owns the arrays, on `PageDesc::check`'s
3575 // terms exactly — see `MeshClusters::check`, which is where the reason
3576 // it cannot be checked below the seam is argued. Both variants carry
3577 // the same type beside a vertex count, so both are checked the same way.
3578 for (index, desc) in scene.meshes.iter().enumerate() {
3579 let levels: Vec<(usize, &MeshClusters)> = match &desc.geometry {
3580 Geometry::Flat {
3581 vertices, clusters, ..
3582 } => vec![(vertices.len() / mesh::VERTEX_STRIDE, clusters)],
3583 Geometry::Dag { dag, .. } => dag
3584 .levels
3585 .iter()
3586 .map(|level| (level.positions.len(), &level.clusters))
3587 .collect(),
3588 };
3589 for (depth, (vertices, clusters)) in levels.into_iter().enumerate() {
3590 if let Err(fault) = clusters.check(vertices) {
3591 return refuse(format!(
3592 "mesh {index} ({}) level {depth} {fault}",
3593 desc.label
3594 ));
3595 }
3596 }
3597 }
3598
3599 // **Capacity, summed over the whole description**, which is the one
3600 // refusal no pool can make for itself. `MeshPool` and `MaterialTable`
3601 // do refuse their own overflow, but they refuse it part way through
3602 // filling something that already exists, and the pair of numbers
3603 // [`MeshPoolError::PoolExhausted`](crate::mesh_pool::MeshPoolError::PoolExhausted)
3604 // carries to tell fragmentation from a full pool says nothing *here*:
3605 // the pool was created empty a few lines below, nothing has been freed
3606 // in it, so its free list is one block and the largest block and the
3607 // total are the same number. At build the answer is always "raise this
3608 // capacity", so it is said by name and before anything is created.
3609 let mut vertices: u64 = 0;
3610 let mut indices: u64 = 0;
3611 for desc in &scene.meshes {
3612 match &desc.geometry {
3613 Geometry::Flat {
3614 vertices: bytes,
3615 indices: list,
3616 ..
3617 } => {
3618 // Bytes that are not a whole number of vertices are the
3619 // pool's to refuse, and it refuses before it allocates.
3620 vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3621 indices += list.len() as u64;
3622 }
3623 Geometry::Dag { levels, dag, .. } => {
3624 for bytes in levels {
3625 vertices += (bytes.len() / mesh::VERTEX_STRIDE) as u64;
3626 }
3627 for level in &dag.levels {
3628 // The call the upload itself makes, so the two cannot
3629 // disagree about what a level costs.
3630 indices += level.indices().len() as u64;
3631 }
3632 }
3633 }
3634 }
3635 let entries: u64 = scene
3636 .meshes
3637 .iter()
3638 .map(|desc| desc.geometry.levels() as u64)
3639 .sum();
3640 for (pool, needed, capacity) in [
3641 ("vertex pool", vertices, scene.capacities.vertices),
3642 ("index pool", indices, scene.capacities.indices),
3643 ("mesh table", entries, scene.capacities.meshes),
3644 (
3645 "material table",
3646 scene.materials.len() as u64,
3647 scene.capacities.materials,
3648 ),
3649 (
3650 "probe table",
3651 scene.probes.probes.len() as u64,
3652 scene.capacities.probes,
3653 ),
3654 ] {
3655 if needed > u64::from(capacity) {
3656 return refuse(format!(
3657 "the {pool} holds {capacity} and the description needs {needed}"
3658 ));
3659 }
3660 }
3661 Ok(())
3662 }
3663
3664 /// The body of [`ForwardRenderer::with_scene`], recording what it has
3665 /// created into `rollback` as it goes and calling `service` where
3666 /// [`ForwardRenderer::with_scene_serviced`] documents.
3667 fn build(
3668 device: &dyn Device,
3669 queue: QueueHandle,
3670 target_format: Format,
3671 scene: &SceneDesc<'_>,
3672 geometry_path: GeometryPath,
3673 rollback: &mut Rollback,
3674 service: &mut dyn FnMut(),
3675 ) -> Result<Self, HalError> {
3676 // Before anything exists, so a refused description leaks nothing — see
3677 // `check_scene`, which is where that placement is argued.
3678 Self::check_scene(scene)?;
3679
3680 // Resolved before anything is created, because it decides the *shape*
3681 // of what is created — the bind group layout, which pipeline kind the
3682 // pass builds, and what a bucket's constant block says. A device on the
3683 // mesh path never builds the raster pipeline and a device on either
3684 // indirect tail never builds the mesh one, which is what makes "the
3685 // frame came out of the mesh stage" a fact about the object graph
3686 // rather than a claim about a branch.
3687 let emit = EmitTail::from_path(geometry_path);
3688 // And whether that tail draws a range of buckets per call, which only
3689 // changes what the passes record — the constant blocks carry the words
3690 // both shapes read — so it decides nothing about what is created.
3691 let range_limit = emit.range_limit(&device.caps());
3692 // **A second capability, asked separately.** `Features::TASK_SHADER` is
3693 // not implied by `MESH_SHADER`, so §3.5's per-cluster cull is an
3694 // amplification stage this renderer builds where the device has one and
3695 // leaves out where it does not — and a device without it keeps drawing
3696 // through `mesh_cluster.slang`'s un-amplified `meshMain`, which culls
3697 // nothing and emits every cluster. Same picture, more work.
3698 let culls_clusters = emit.is_mesh()
3699 && device
3700 .caps()
3701 .features
3702 .contains(crcbl_hal::Features::TASK_SHADER);
3703
3704 let (pool, residents) = Self::build_geometry(device, queue, scene, service)?;
3705 // What an `InstanceDesc::mesh` index resolves through: one id per
3706 // description mesh, in description order, and each of them that mesh's
3707 // **level 0** whatever the path — because it is the entry the cull pass
3708 // reads a bounding box out of, and a DAG's coarser levels approximate
3709 // the same surface inside the same box.
3710 let mesh_ids: Vec<u32> = residents.iter().map(ResidentMesh::id).collect();
3711 // The scene's own triangles, kept for the probe-visibility capture and
3712 // for nothing else — and kept at all only when the description reserves
3713 // a probe, so a scene without one pays no memory for this rung. Taken
3714 // here because `scene` is the caller's and is read once.
3715 let probe_occluders = crate::probe_visibility::Occluders::from_scene(scene, &mesh_ids);
3716 // The same list one level down: what a caller reserving a skinned region
3717 // names its mesh with. Read here beside the ids rather than from
3718 // `residents` later, because the descriptions this came from are the
3719 // caller's and are read once.
3720 let skinnable_meshes: Vec<Option<MeshHandle>> =
3721 residents.iter().map(|mesh| mesh.skinnable).collect();
3722 // The handles are `Copy`, so they can be read out before the pool
3723 // becomes the rollback's — which it must be before the first `?` below,
3724 // or a failed pipeline would leak two device-local buffers. The index
3725 // pool is not named here at all: it is bound at draw time rather than
3726 // descriptor-written, so only the vertex pool and the mesh table reach a
3727 // bind group.
3728 let vertices = pool.vertex_buffer();
3729 let mesh_table = pool.table_buffer();
3730 rollback.pool = Some(pool);
3731
3732 // §3.2's texture side, before the table that indexes it: a material row
3733 // is written with a layer number, so the layer has to exist to be named.
3734 //
3735 // **One loop over [`PageKind::ALL`]**, because the kinds differ only in
3736 // three answers the kind itself owns — its format, its mip filter and
3737 // its device label — and everything else about creating a page is the
3738 // same code. Two hand-written copies were what let the normal page be
3739 // created through the colour page's filter for as long as nobody
3740 // compared the two, and rung 3 adds two more kinds to get wrong.
3741 //
3742 // **`Rgba8UnormSrgb` on the base-colour page, `Rgba8Unorm` on the
3743 // normal page, and that is the colour-space decision.** A base-colour
3744 // description's texels are sRGB-encoded, which is what glTF defines a
3745 // base-colour texture to be, so the format is what makes the sampler
3746 // decode them — and `mesh.slang` then multiplies a linear texel by a
3747 // linear `base_color` and lights in linear, exactly as it did before
3748 // there was a texture. A normal texel is a *number* and nothing decodes
3749 // it. See `PageKind::format`, and topic 44's rung 2.
3750 //
3751 // Every layer's length against its kind's extent was settled by
3752 // `check_scene` above, before this device object existed.
3753 //
3754 // **Every layer goes up with its mip chain**, built here on the host by
3755 // [`crate::mip`] — topic 43's filtering rung.
3756 // The chain is what a trilinear sampler needs to stop shimmering on a
3757 // minified surface, and it is built at upload rather than by a compute
3758 // pass because the page's format is what decodes it and a host chain is
3759 // the same bytes on every backend.
3760 //
3761 // **A kind with no layers takes one texel.** `upload_texture_mip_layers`
3762 // refuses a zero-layer image and every bind group has to fill both page
3763 // bindings, so a page nothing names is created 1×1 in its own format
3764 // holding [`PAGE_PLACEHOLDER_TEXEL`] — which the shader never reads,
3765 // and which is magenta so that a frame says so if it ever does.
3766 //
3767 // The upload itself is [`upload_page`], shared with
3768 // [`ForwardRenderer::replace_page`] so a page reloaded under a running
3769 // renderer is built exactly as this one was. A layer's chain is host
3770 // work proportional to its texels, so a page of many large layers is
3771 // serviced one layer at a time.
3772 let mut pages: [Option<UploadedTexture>; PageKind::ALL.len()] = [None; PageKind::ALL.len()];
3773 let mut page_extents = [(1, 1); PageKind::ALL.len()];
3774 let mut page_layers = [0; PageKind::ALL.len()];
3775 for kind in PageKind::ALL {
3776 let layers = scene.page.layers(kind);
3777 let (page, extent) = upload_page(
3778 device,
3779 queue,
3780 kind,
3781 scene.page.extent(kind),
3782 layers,
3783 service,
3784 )?;
3785 rollback.textures.push(page);
3786 page_extents[kind.index()] = (extent, extent);
3787 page_layers[kind.index()] = layers.len();
3788 pages[kind.index()] = Some(page);
3789 service();
3790 }
3791 let [
3792 Some(base_color_page),
3793 Some(normal_page),
3794 Some(mro_page),
3795 Some(emissive_page),
3796 ] = pages
3797 else {
3798 unreachable!("the loop above fills a slot for every PageKind::ALL entry");
3799 };
3800
3801 // The page's sampler at the device's default — see `create_page_sampler`
3802 // for what it filters, and `set_anisotropy` for how a caller moves it.
3803 let anisotropy = Self::anisotropy_for(&device.caps());
3804 let base_color_sampler = Self::create_page_sampler(device, anisotropy)?;
3805 rollback.samplers.push(base_color_sampler);
3806 // What every slot's groups are built naming, and what each moves off
3807 // only at its own frame — see `ForwardRenderer::adopt_pages`.
3808 let page_bindings = PageBindings {
3809 sampler: base_color_sampler,
3810 views: [
3811 base_color_page.view,
3812 normal_page.view,
3813 mro_page.view,
3814 emissive_page.view,
3815 ],
3816 };
3817
3818 // The material table, before the instances: an instance is written with
3819 // the material id it carries, so the row has to exist to be named.
3820 let (materials, material_ids) = Self::build_materials(device, scene)?;
3821 let material_buffer = materials.buffer();
3822 rollback.materials = Some(materials);
3823
3824 // Topic 50's irradiance grid: the table is created here once, and
3825 // `crate::probe_gather`'s compute pass rewrites its rows every frame —
3826 // see [`crate::probe`]. **Created even for a description with no probes**, because
3827 // every group of this layout has to fill [`PROBE_TABLE_BINDING`] and the
3828 // honest filler for "no probes were authored" is the zeroed row the
3829 // shader's clamp lands on.
3830 let probe_table = ProbeTable::new(
3831 device,
3832 queue,
3833 &ProbeTableDesc {
3834 label: Some("forward"),
3835 capacity: scene.capacities.probes,
3836 frames: FRAMES_IN_FLIGHT,
3837 },
3838 )?;
3839 // Into the rollback before it is filled, so a copy that fails releases
3840 // the buffers rather than leaking them.
3841 rollback.probes = Some(probe_table);
3842 let probe_table = rollback.probes.as_ref().expect("just stored");
3843 probe_table.fill(device, queue, &scene.probes.probes)?;
3844 // Read out here, like the instance ring's below and for the same
3845 // reason: the handles are `Copy`, and the loop that builds the bind
3846 // groups mutates the rollback the table now lives in.
3847 let probe_buffers: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
3848 .map(|frame| probe_table.buffer(frame))
3849 .collect();
3850 // The irradiance probes' updater, built **only** for a
3851 // description that asked for it. A volume left at
3852 // [`ProbeUpdate::Authored`] gets no pipeline, no buffers and no pass, so
3853 // the default really is the frame every scene drew before this landed.
3854 let probe_gather = match scene.probes.update {
3855 ProbeUpdate::Authored => None,
3856 ProbeUpdate::EveryFrame => Some(ProbeGather::new(
3857 device,
3858 &ProbeGatherDesc {
3859 label: Some("forward probes"),
3860 volume: scene.probes.volume,
3861 probes: &probe_buffers,
3862 },
3863 )?),
3864 };
3865 rollback.probe_gather = probe_gather;
3866 let probe_gather = rollback.probe_gather.take();
3867 service();
3868
3869 // **Empty.** Every object in the scene arrives through
3870 // [`ForwardRenderer::add_instance`], including the demo scene's cube: a
3871 // renderer that inserted one of its description's meshes here would put
3872 // an object in a caller's frame that the caller never asked for.
3873 let instances = InstancePool::new(
3874 device,
3875 &InstancePoolDesc {
3876 label: Some("forward instances"),
3877 capacity: scene.capacities.instances,
3878 frames_in_flight: FRAMES_IN_FLIGHT,
3879 },
3880 )?;
3881 // Same handle-then-hand-over dance as the geometry pool above: the
3882 // buffers are `Copy` and are read out before the pool becomes the
3883 // rollback's, which it must be before the first `?` below — after which
3884 // nothing needs the pool again until `begin_frame`.
3885 let instance_buffers: Vec<BufferHandle> = instances.buffers().to_vec();
3886 rollback.instances = Some(instances);
3887
3888 // The two compute passes, and the buffers the draws come out of. Built
3889 // here rather than beside the pipelines below because the mesh bind
3890 // group names one of its buffers, so it has to exist first.
3891 //
3892 // The bucket table, and the one place its order is decided.
3893 //
3894 // **Built by walking the description**, which is what makes a duplicate
3895 // structurally impossible rather than refused: every bucket's mesh id is
3896 // the id of the description mesh it came from, and two description
3897 // meshes are two uploads with two table entries however alike their
3898 // geometry is. That matters because `draw_gen.slang`'s scatter takes the
3899 // *first* bucket whose mesh id matches, so a second bucket naming one
3900 // mesh would never draw anything at all.
3901 //
3902 // One bucket per mesh, except for two things. A DAG is one bucket where
3903 // an amplification stage picks its cut per cluster and one per level
3904 // where the cull pass picks a uniform one — see [`buckets_for`]. And the
3905 // whole run is repeated once per **material mode** the scene holds, so
3906 // an instance's mode picks a bucket exactly as its mesh does; see
3907 // [`ForwardRenderer::bucket_modes`].
3908 //
3909 // **Mode-major: every mesh's run for one mode, then the next mode's.**
3910 // A mode picks the pipeline a pass binds, so this makes each pipeline's
3911 // partition — [`ForwardRenderer::depth_partitions`] and
3912 // [`ForwardRenderer::sided_partitions`] — one contiguous run of
3913 // buckets, which a device with a draw index records as one ranged call
3914 // rather than a call per bucket — and which the mesh tail behind a
3915 // task stage must have, because it draws each partition as one flat
3916 // call of its run. `DEPTH_MODES` order makes a sided partition one run
3917 // too: opaque sits beside masked, and double-sided beside both.
3918 //
3919 // **Once per mode the scene holds, not once per mode that exists.** A
3920 // scene whose materials are all opaque gets exactly the table it always
3921 // had — same length, same order, same bytes — so the twin costs nothing
3922 // where nothing is masked, which is every demo and every golden here. A
3923 // bucket is not free: every pass records one indirect call per bucket
3924 // per view, and every generator holds its run start.
3925 let scene_modes: Vec<u32> = {
3926 let held: Vec<u32> = DEPTH_MODES
3927 .into_iter()
3928 .filter(|mode| {
3929 scene
3930 .materials
3931 .iter()
3932 .any(|material| material.mode() == *mode)
3933 })
3934 .collect();
3935 // A description with no materials at all still needs a bucket per
3936 // mesh, or nothing it holds can be drawn.
3937 if held.is_empty() {
3938 vec![DEPTH_MODES[0]]
3939 } else {
3940 held
3941 }
3942 };
3943 // One mode's run: every description mesh's levels, in description
3944 // order. `bucket_bases` is where each mesh starts within it, so the
3945 // tables below can be filled in mesh by mesh rather than by re-deriving
3946 // the arithmetic; mode slot `s` of the mesh is `s` runs further on.
3947 let mut mode_run: Vec<u32> = Vec::new();
3948 let mut bucket_bases: Vec<usize> = Vec::with_capacity(residents.len());
3949 for resident in &residents {
3950 bucket_bases.push(mode_run.len());
3951 mode_run
3952 .extend_from_slice(&resident.levels[..buckets_for(resident.levels.len(), emit)]);
3953 }
3954 let mut bucket_meshes: Vec<u32> = Vec::with_capacity(mode_run.len() * scene_modes.len());
3955 // The mode each of those buckets draws, in step with it.
3956 let mut bucket_modes: Vec<u32> = Vec::with_capacity(bucket_meshes.capacity());
3957 for mode in &scene_modes {
3958 bucket_meshes.extend_from_slice(&mode_run);
3959 bucket_modes.extend(std::iter::repeat_n(*mode, mode_run.len()));
3960 }
3961 let bucket_count = u32::try_from(bucket_meshes.len())
3962 .unwrap_or_else(|_| unreachable!("a table of a few buckets"));
3963
3964 // Topic 25's selection tables, and the one thing that
3965 // decides whether `draw_gen.slang` takes a uniform cut at all.
3966 //
3967 // Every mesh id gets an entry, because the shader indexes this with
3968 // `GpuInstance::mesh` and an instance can name any of them; the default
3969 // is `MeshLevels::FLAT` pointing at a level run that is the mesh itself,
3970 // so a mesh with no hierarchy resolves back to itself with no branch.
3971 // **A DAG keeps that default on the mesh path**, which is how a device
3972 // already descending it per cluster avoids a second, coarser cut on top
3973 // of it — the suppression is data rather than a branch in the shader.
3974 //
3975 // **Sized by the mesh table's capacity, not by the meshes resident in
3976 // it**, because that is the invariant `draw_gen.slang`'s
3977 // `mesh_levels_of` states and indexes on: "every entry an instance can
3978 // name is filled". The read is unbounded and an instance's mesh id is a
3979 // bare table index, so a table sized to the description alone is an
3980 // out-of-range read of whatever the packer laid down next for any id the
3981 // description did not fill. What it finds there decides the frame: zeros
3982 // resolve to mesh 0 and draw another mesh's geometry, and a live
3983 // `group_count` sends `select_level`'s loop over a count no allocation
3984 // backs, which on radv is a hard GPU recovery rather than a wrong
3985 // picture. That is not a hypothetical: it is what a skinned instance
3986 // naming an alias entry did until 2026-08, before it learned to name its
3987 // source mesh instead.
3988 let table_len = usize::try_from(scene.capacities.meshes)
3989 .unwrap_or(usize::MAX)
3990 .max(
3991 usize::try_from(
3992 residents
3993 .iter()
3994 .flat_map(|resident| resident.levels.iter().copied())
3995 .max()
3996 .unwrap_or_else(|| {
3997 unreachable!("check_scene refused an empty description")
3998 })
3999 + 1,
4000 )
4001 .unwrap_or_else(|_| unreachable!("a table of a few meshes")),
4002 );
4003 let mut level_meshes: Vec<u32> = (0..table_len)
4004 .map(|id| u32::try_from(id).unwrap_or_else(|_| unreachable!("bounded by table_len")))
4005 .collect();
4006 let mut mesh_levels: Vec<level_select::MeshLevels> = level_meshes
4007 .iter()
4008 .map(|&id| level_select::MeshLevels {
4009 first_level: id,
4010 ..level_select::MeshLevels::FLAT
4011 })
4012 .collect();
4013 // Every DAG's groups end to end, in description order, and where each
4014 // one's run starts. `ClusterSelect` records name a group by its index in
4015 // *this* array — see `ClusterDag::selection_records`' `first_group` — so
4016 // several DAGs concatenate without `crcbl-shaders` knowing they did.
4017 let mut level_groups: Vec<level_select::LevelGroup> = Vec::new();
4018 let mut first_groups: Vec<u32> = Vec::with_capacity(residents.len());
4019 for (index, desc) in scene.meshes.iter().enumerate() {
4020 first_groups.push(
4021 u32::try_from(level_groups.len())
4022 .unwrap_or_else(|_| unreachable!("a few dozen groups per DAG")),
4023 );
4024 let Geometry::Dag { dag, .. } = &desc.geometry else {
4025 continue;
4026 };
4027 let groups = dag.level_groups();
4028 let id = residents[index].id();
4029 mesh_levels[id as usize] = level_select::MeshLevels {
4030 first_group: first_groups[index],
4031 group_count: u32::try_from(groups.len())
4032 .unwrap_or_else(|_| unreachable!("a DAG of a few dozen groups")),
4033 // **The mesh path suppresses the uniform cut with a top level of
4034 // zero, not with a group count of zero**, and the difference is
4035 // the hysteresis state: `draw_gen.slang` judges every group it is
4036 // given whatever level it answers, and the amplification stage
4037 // reads those answers. A record naming no groups would leave the
4038 // state untouched and every cluster of the patch collapsed. A
4039 // top level of zero makes the level loop's minimum unreachable,
4040 // so the instance routes to the mesh it already names — which is
4041 // level 0.
4042 first_level: if emit.is_mesh() {
4043 id
4044 } else {
4045 u32::try_from(level_meshes.len())
4046 .unwrap_or_else(|_| unreachable!("a table of a few meshes"))
4047 },
4048 top_level: if emit.is_mesh() {
4049 0
4050 } else {
4051 u32::try_from(residents[index].levels.len() - 1)
4052 .unwrap_or_else(|_| unreachable!("a DAG of a few levels"))
4053 },
4054 };
4055 level_groups.extend(groups);
4056 if !emit.is_mesh() {
4057 level_meshes.extend_from_slice(&residents[index].levels);
4058 }
4059 }
4060
4061 // §3.5's clusters, on the path that reads them and on no other. The
4062 // records are `crcbl-shaders`' — cooked, because the builder is
4063 // `crcbl-scene`'s and the renderer must not depend on that crate — and
4064 // they arrive in bucket-mesh order so a bucket's range is its own
4065 // index. See `crate::cluster_pool`.
4066 //
4067 // Before the draw generation below rather than after it, because the
4068 // per-bucket cluster counts are the x extent of each bucket's mesh
4069 // dispatch and that pass writes the argument structure carrying them.
4070 let mut bucket_clusters = vec![0u32; bucket_meshes.len()];
4071 let mut bucket_cluster_bases = vec![0u32; bucket_meshes.len()];
4072 let mut mesh_clusters: Vec<ClusterRange> = Vec::new();
4073 if emit.is_mesh() {
4074 // A flat mesh is one pool entry and its clusters carry
4075 // `ClusterSelect::ALWAYS`, so the descent draws them from every
4076 // camera; a DAG is **one entry per level**, laid end to end.
4077 let mut cooked: Vec<PooledMesh> = Vec::with_capacity(residents.len());
4078 // Where each description mesh's entries start, on `bucket_bases`'
4079 // terms — the two differ exactly where a DAG's levels are one bucket
4080 // and several entries.
4081 let mut entry_bases: Vec<usize> = Vec::with_capacity(residents.len());
4082 for (index, desc) in scene.meshes.iter().enumerate() {
4083 entry_bases.push(cooked.len());
4084 match &desc.geometry {
4085 Geometry::Flat { clusters, .. } => {
4086 cooked.push(PooledMesh::without_lod(clusters.clone()));
4087 }
4088 Geometry::Dag { dag, .. } => {
4089 let selection = dag
4090 .selection_records(&residents[index].vertex_bases, first_groups[index]);
4091 for (level, records) in dag.levels.iter().zip(selection) {
4092 cooked.push(PooledMesh {
4093 clusters: level.clusters.clone(),
4094 selection: records,
4095 });
4096 }
4097 }
4098 }
4099 }
4100
4101 let clusters = ClusterPool::new(device, "forward", &cooked)?;
4102 let range = |entry: usize| {
4103 clusters
4104 .range(entry)
4105 .unwrap_or_else(|| unreachable!("one range per entry, in order"))
4106 };
4107 // **A DAG's levels are one run, not one per bucket.** `concatenate`
4108 // lays the entries down in the order it was given them, so the
4109 // levels are contiguous: the bucket starts where level 0 does and
4110 // reaches to the end of the last level. That is what lets one
4111 // dispatch cover a cut spanning several of them — and it is why a
4112 // flat mesh, whose one entry is the whole sum, needs no second case.
4113 mesh_clusters.reserve(residents.len());
4114 for (index, resident) in residents.iter().enumerate() {
4115 let entry = entry_bases[index];
4116 let base = range(entry).base;
4117 let count: u32 = (entry..entry + resident.levels.len())
4118 .map(|entry| range(entry).count)
4119 .sum();
4120 // **Every one of this mesh's buckets, not only the first.** A
4121 // mode twin draws the same geometry, so it dispatches over the
4122 // same clusters; a twin left at zero launches no workgroup and
4123 // its instances vanish from the frame. One bucket per mode here,
4124 // because the mesh path takes `buckets_for` of one, each a whole
4125 // mode's run past the one before.
4126 for slot in 0..scene_modes.len() {
4127 let bucket = slot * mode_run.len() + bucket_bases[index];
4128 bucket_cluster_bases[bucket] = base;
4129 bucket_clusters[bucket] = count;
4130 }
4131 mesh_clusters.push(ClusterRange { base, count });
4132 }
4133
4134 rollback.clusters = Some(clusters);
4135 service();
4136 }
4137
4138 // One ring per shadow view, indexed `[view][frame]`: topic 25's
4139 // observable, one word per resident cluster holding the cut the descent
4140 // chose — see `ForwardRenderer::shadow_selection` for why a view cannot
4141 // share the camera's, which [`View::build`] allocates beside its cull.
4142 //
4143 // Allocated on the whole mesh path rather than only where there is an
4144 // amplification stage to write them, because the layout declares
4145 // CLUSTER_SELECTION_BINDING there — see the layout, which is where that is argued.
4146 let mut tile_selection: Vec<Vec<BufferHandle>> = Vec::new();
4147 if emit.is_mesh() {
4148 let count = rollback
4149 .clusters
4150 .as_ref()
4151 .unwrap_or_else(|| unreachable!("the mesh path implies a cluster pool"))
4152 .count();
4153 let mut ring = |label: &str| -> Result<Vec<BufferHandle>, HalError> {
4154 let mut buffers = Vec::with_capacity(instance_buffers.len());
4155 for frame in 0..instance_buffers.len() {
4156 let buffer = device.create_buffer(&BufferDesc {
4157 label: Some(&format!("{label} {frame}")),
4158 size: u64::from(count) * 4,
4159 usage: BufferUsage::STORAGE.union(BufferUsage::TRANSFER_SRC),
4160 memory: MemoryLocation::DeviceLocal,
4161 })?;
4162 rollback.buffers.push(buffer);
4163 buffers.push(buffer);
4164 }
4165 Ok(buffers)
4166 };
4167 for view in 0..SHADOW_VIEWS {
4168 tile_selection.push(ring(&format!("shadow selection {view}"))?);
4169 }
4170 }
4171
4172 // --- the mesh pass ---
4173 //
4174 // No `BindingFlags` anywhere: this layout is legal on **both** tiers,
4175 // because a lit mesh is not a Tier A feature. The bindless shape — a
4176 // trailing `VARIABLE_COUNT | PARTIALLY_BOUND | UPDATE_AFTER_BIND`
4177 // texture array — is topic 03's, at P3.
4178 // **Which stage pulls the geometry**, and the only thing the two shapes
4179 // of this layout disagree about for bindings 0 to 8. `ShaderStages::MESH`
4180 // is outside `GRAPHICS` and `ALL`, so it is named rather than implied,
4181 // and every backend refuses a layout carrying it on a device without
4182 // `Features::MESH_SHADER` — which is exactly the device that never
4183 // reaches this arm.
4184 //
4185 // **`TASK` joins it when there is an amplification stage**, and the
4186 // union is deliberately over every binding rather than the eight
4187 // `taskMain` actually reads. Slang's Metal backend materialises every
4188 // global in every entry point of a module — the argument bindings 6 to
4189 // 8 already carry — so a layout that named only the task stage's own
4190 // reads would be a layout `msl/mesh_cluster.metal` disagrees with, on a
4191 // runner this team cannot debug on.
4192 let geometry = match (emit.is_mesh(), culls_clusters) {
4193 (true, true) => ShaderStages::MESH.union(ShaderStages::TASK),
4194 (true, false) => ShaderStages::MESH,
4195 (false, _) => ShaderStages::VERTEX,
4196 };
4197 let mut mesh_entries = vec![
4198 BindGroupLayoutEntry {
4199 binding: 0,
4200 visibility: geometry.union(ShaderStages::FRAGMENT),
4201 kind: BindingKind::UniformBuffer { dynamic: false },
4202 count: 1,
4203 flags: BindingFlags::empty(),
4204 },
4205 BindGroupLayoutEntry {
4206 binding: 1,
4207 // **Both stages, and here it is the FRAGMENT half that needs
4208 // saying** — binding 6 and 7 are the mirror image, where the
4209 // fragment stage plainly reads the row and the vertex half is
4210 // the one Slang forces. Slang's Metal backend materialises
4211 // every module global into every entry point, so
4212 // `msl/mesh.metal`'s `fragmentMain` takes this buffer whether
4213 // its body dereferences it or not — and Metal's debug layer
4214 // answers a declared-but-unbound fragment argument with
4215 // `missing Buffer binding at index N`, once per draw. Vulkan,
4216 // D3D12 and WebGPU all accept a visibility wider than the
4217 // shader's reads, so naming FRAGMENT costs them nothing but the
4218 // entry itself.
4219 //
4220 // **It does not cost a redundant bind on Metal either**, and
4221 // that is what makes it safe rather than a trade: `crcbl-mtl`
4222 // consults `MTLPipelineOption::BindingInfo` reflection and
4223 // issues the fragment-stage bind only where `MTLBinding::isUsed`
4224 // says the compiled function kept the argument. This entry is
4225 // the permission; the reflection is the decision.
4226 visibility: geometry.union(ShaderStages::FRAGMENT),
4227 kind: BindingKind::StorageBuffer {
4228 // The shader says `StructuredBuffer`, not
4229 // `RWStructuredBuffer`, so this is the truth rather than a
4230 // hint — and it is what lets the graph merge read-after-read.
4231 read_only: true,
4232 dynamic: false,
4233 stride: size_of::<u32>() as u32,
4234 },
4235 count: 1,
4236 flags: BindingFlags::empty(),
4237 },
4238 BindGroupLayoutEntry {
4239 binding: 2,
4240 // Both stages, for binding 1's reason exactly.
4241 visibility: geometry.union(ShaderStages::FRAGMENT),
4242 kind: BindingKind::StorageBuffer {
4243 // `StructuredBuffer` again: the vertex stage reads its
4244 // instance and writes nothing. The *host* writes this one
4245 // every frame, which is a mapped write rather than a shader
4246 // one and does not make it read-write here.
4247 read_only: true,
4248 dynamic: false,
4249 stride: crcbl_shaders::mesh::INSTANCE_STRIDE as u32,
4250 },
4251 count: 1,
4252 flags: BindingFlags::empty(),
4253 },
4254 BindGroupLayoutEntry {
4255 binding: 3,
4256 // Both stages, for binding 1's reason exactly.
4257 visibility: geometry.union(ShaderStages::FRAGMENT),
4258 // `dynamic: true`, and it is the whole mechanism: it is what
4259 // lets a draw say where its run of instances starts without
4260 // `draw_indexed`'s own base instance, which the module docs and
4261 // `mesh.slang`'s header explain the targets disagree about.
4262 // Same shape, for the same reason, as `crate::sprite_pass`'s.
4263 kind: BindingKind::UniformBuffer { dynamic: true },
4264 count: 1,
4265 flags: BindingFlags::empty(),
4266 },
4267 BindGroupLayoutEntry {
4268 binding: 4,
4269 // Both stages, for binding 1's reason exactly.
4270 visibility: geometry.union(ShaderStages::FRAGMENT),
4271 kind: BindingKind::StorageBuffer {
4272 // The mesh table. `StructuredBuffer` again — the vertex
4273 // stage looks its mesh up and writes nothing — and one
4274 // buffer shared by every frame's group, because unlike the
4275 // instance array nothing rewrites it between frames.
4276 read_only: true,
4277 dynamic: false,
4278 stride: crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u32,
4279 },
4280 count: 1,
4281 flags: BindingFlags::empty(),
4282 },
4283 BindGroupLayoutEntry {
4284 binding: 5,
4285 // Both stages, for binding 1's reason exactly.
4286 visibility: geometry.union(ShaderStages::FRAGMENT),
4287 kind: BindingKind::StorageBuffer {
4288 // The per-bucket runs of surviving instances. Read-only
4289 // here and written by the draw-argument pass, which is a
4290 // different bind group and a different pass — the graph is
4291 // what orders the two.
4292 read_only: true,
4293 dynamic: false,
4294 stride: size_of::<u32>() as u32,
4295 },
4296 count: 1,
4297 flags: BindingFlags::empty(),
4298 },
4299 BindGroupLayoutEntry {
4300 binding: 6,
4301 // **Both stages, and the union is not belt-and-braces.** The
4302 // fragment stage is where `mesh.slang` now reads the table, so
4303 // it plainly needs it — a pipeline layout that leaves it out is
4304 // refused outright by wgpu and reported as
4305 // `VUID-VkGraphicsPipelineCreateInfo-layout-07988` by Vulkan.
4306 // The vertex half has to stay because Slang's Metal backend
4307 // materialises every global in every entry point: `vertexMain`
4308 // in `msl/mesh.metal` still takes `materials [[buffer(6)]]`
4309 // whether it reads it or not, so dropping VERTEX would break
4310 // Metal alone, on a runner this team cannot debug on.
4311 visibility: geometry.union(ShaderStages::FRAGMENT),
4312 kind: BindingKind::StorageBuffer {
4313 // The material table. One buffer in every frame's group,
4314 // like the mesh table above and unlike the instance ring:
4315 // a material is written when it is created, not per frame.
4316 read_only: true,
4317 dynamic: false,
4318 stride: crcbl_shaders::mesh::MATERIAL_STRIDE as u32,
4319 },
4320 count: 1,
4321 flags: BindingFlags::empty(),
4322 },
4323 BindGroupLayoutEntry {
4324 binding: BASE_COLOR_PAGE_BINDING,
4325 // Both stages, for binding 6's reason exactly: the fragment
4326 // stage samples it, and Slang's Metal backend materialises
4327 // every global in every entry point — `vertexMain` in
4328 // `msl/mesh.metal` takes the texture whether it reads it or
4329 // not, so a layout without VERTEX would break Metal alone.
4330 visibility: geometry.union(ShaderStages::FRAGMENT),
4331 // **`D2Array`, and the layout is where wgpu wants to hear it.**
4332 // The other three backends read the dimension off the bound
4333 // view and never consult this; WebGPU compares the two at
4334 // pipeline creation and refuses the pair, which is what a
4335 // layout claiming `D2` over an array view got — "expects
4336 // dimension = D2, but given a view with dimension = D2Array".
4337 kind: BindingKind::SampledImage {
4338 view_type: ImageViewType::D2Array,
4339 sample_type: SampleType::Float,
4340 },
4341 // **`count: 1`, and this is the binding-model decision.** One
4342 // `D2Array` image whose *layers* the material rows index is
4343 // `BindingModel::ArrayPages`; an array of `count` descriptors
4344 // indexed per fragment would be `Bindless` and would need
4345 // `Features::DESCRIPTOR_INDEXING`, which `crcbl-mtl` withdraws.
4346 // So this layout is legal on every device, exactly as the six
4347 // buffers above are, and no `BindingFlags` appear anywhere in
4348 // this file yet.
4349 count: 1,
4350 flags: BindingFlags::empty(),
4351 },
4352 BindGroupLayoutEntry {
4353 binding: PAGE_SAMPLER_BINDING,
4354 visibility: geometry.union(ShaderStages::FRAGMENT),
4355 kind: BindingKind::Sampler { comparison: false },
4356 count: 1,
4357 flags: BindingFlags::empty(),
4358 },
4359 ];
4360 if emit.is_mesh() {
4361 // §3.5's four extra reads, and only on the path that has them.
4362 // Adding them unconditionally would make every device declare four
4363 // buffers `mesh.slang` does not name — and WebGPU, which checks a
4364 // bind group against its layout entry for entry, would then need
4365 // four buffers created for a path that never reads them.
4366 //
4367 // `read_only: true` on all four, which is the truth rather than a
4368 // hint: the mesh stage indexes them and writes nothing, and it is
4369 // what lets the graph merge read-after-read.
4370 //
4371 // Four different element types, so four strides, in binding order:
4372 // the clusters (`Meshlet`), the cluster vertex and corner pools
4373 // (`uint` each), and the per-cluster draw arguments
4374 // (`DrawIndexedArgs`, the indirect layout every API agrees on).
4375 let cluster_strides = [
4376 crcbl_shaders::meshlet::MESHLET_STRIDE as u32,
4377 size_of::<u32>() as u32,
4378 size_of::<u32>() as u32,
4379 crcbl_hal::indirect::DRAW_INDEXED_ARGS_BYTES as u32,
4380 ];
4381 mesh_entries.extend(
4382 (CLUSTERS_BINDING..=CLUSTER_DRAW_ARGS_BINDING)
4383 .zip(cluster_strides)
4384 .map(|(binding, stride)| {
4385 BindGroupLayoutEntry {
4386 binding,
4387 // **Not the fragment stage.** These four are the geometry
4388 // stage's alone, and `mesh_cluster.slang` has no fragment entry
4389 // point of its own to materialise them into — its fragment
4390 // stage is `mesh.slang`'s, which does not declare mesh-only
4391 // buffers.
4392 visibility: geometry,
4393 kind: BindingKind::StorageBuffer {
4394 read_only: true,
4395 dynamic: false,
4396 stride,
4397 },
4398 count: 1,
4399 flags: BindingFlags::empty(),
4400 }
4401 }),
4402 );
4403 }
4404 // Both mesh entry points retain these declarations. Omitting unused
4405 // task buffers would shift later native buffer indices on the plain
4406 // mesh path, so the layout includes them on both paths.
4407 if emit.is_mesh() {
4408 mesh_entries.push(BindGroupLayoutEntry {
4409 binding: CLUSTER_CULL_BINDING,
4410 visibility: geometry,
4411 // **The same block the instance cull reads**, not a copy: one
4412 // camera, one frustum, and no way for the two rejections to
4413 // disagree about which. `dynamic: false` because there is one
4414 // block per frame rather than one per bucket.
4415 kind: BindingKind::UniformBuffer { dynamic: false },
4416 count: 1,
4417 flags: BindingFlags::empty(),
4418 });
4419 mesh_entries.push(BindGroupLayoutEntry {
4420 binding: CLUSTER_CULL_STATS_BINDING,
4421 visibility: geometry,
4422 kind: BindingKind::StorageBuffer {
4423 // **The one writable binding this pass has.** The stage adds
4424 // to a counter, so `read_only: false` is the truth rather
4425 // than a hint, and it is what makes the graph order this
4426 // write after the draw-argument pass's read of the same
4427 // buffer.
4428 read_only: false,
4429 dynamic: false,
4430 stride: size_of::<u32>() as u32,
4431 },
4432 count: 1,
4433 flags: BindingFlags::empty(),
4434 });
4435 }
4436 // Topic 18's cascades, read by the fragment stage and declared last —
4437 // above `mesh_cluster.slang`'s range rather than inside it, for the
4438 // reason `SHADOW_ATLAS_BINDING` gives.
4439 //
4440 // Both carry `geometry` in their visibility beside `FRAGMENT`, for
4441 // binding 7's reason exactly: Slang's Metal backend materialises every
4442 // global into every entry point, and `msl/mesh.metal`'s `vertexMain`
4443 // takes `shadow_atlas [[texture(1)]]` and `shadow_sampler
4444 // [[sampler(1)]]` whether it reads them or not.
4445 mesh_entries.push(BindGroupLayoutEntry {
4446 binding: SHADOW_ATLAS_BINDING,
4447 visibility: geometry.union(ShaderStages::FRAGMENT),
4448 kind: BindingKind::SampledImage {
4449 view_type: ImageViewType::D2,
4450 // **`Depth`, and this is the field the seam grew for this
4451 // pass.** WebGPU will only bind a `D32Float` view through a
4452 // depth sample type, and its shader side agrees — the WGSL
4453 // artifact declares `texture_depth_2d`. The other three
4454 // backends take the interpretation off the view's format and
4455 // never read this.
4456 sample_type: SampleType::Depth,
4457 },
4458 count: 1,
4459 flags: BindingFlags::empty(),
4460 });
4461 mesh_entries.push(BindGroupLayoutEntry {
4462 binding: SHADOW_SAMPLER_BINDING,
4463 visibility: geometry.union(ShaderStages::FRAGMENT),
4464 // The sampler-side twin of the line above: `sampler_comparison` in
4465 // the WGSL, `SamplerComparisonState` in the HLSL, and a
4466 // `compareEnable` on the Vulkan sampler object. The layout has to
4467 // say so on WebGPU and cannot on the other three.
4468 kind: BindingKind::Sampler { comparison: true },
4469 count: 1,
4470 flags: BindingFlags::empty(),
4471 });
4472 // DAG geometry and selection state, in the mesh-only binding range.
4473 if emit.is_mesh() {
4474 mesh_entries.push(BindGroupLayoutEntry {
4475 binding: CLUSTER_SELECT_BINDING,
4476 visibility: geometry,
4477 // Read-only and read by **both** mesh entry points, unlike the
4478 // pair below: a cluster's `vertex_base` is which level of a DAG
4479 // its geometry lives in, which an un-amplified stage needs just
4480 // as much as an amplified one.
4481 kind: BindingKind::StorageBuffer {
4482 read_only: true,
4483 dynamic: false,
4484 stride: crcbl_shaders::cluster_select::CLUSTER_SELECT_STRIDE as u32,
4485 },
4486 count: 1,
4487 flags: BindingFlags::empty(),
4488 });
4489 }
4490 // Both on the whole mesh path, for the two above's reason exactly: the
4491 // amplification stage is the only writer and the only reader, and the
4492 // Metal argument table counts entries rather than reading binding
4493 // numbers.
4494 if emit.is_mesh() {
4495 mesh_entries.push(BindGroupLayoutEntry {
4496 binding: CLUSTER_SELECTION_BINDING,
4497 visibility: geometry,
4498 kind: BindingKind::StorageBuffer {
4499 // The second writable binding: the amplification stage
4500 // records the cut it chose, one word per resident cluster.
4501 read_only: false,
4502 dynamic: false,
4503 stride: size_of::<u32>() as u32,
4504 },
4505 count: 1,
4506 flags: BindingFlags::empty(),
4507 });
4508 mesh_entries.push(BindGroupLayoutEntry {
4509 binding: CLUSTER_GROUP_STATE_BINDING,
4510 visibility: geometry,
4511 kind: BindingKind::StorageBuffer {
4512 // Topic 25's hysteresis state, and read-only
4513 // here: the draw-argument pass is its only writer, which is
4514 // what lets a stage with one workgroup per cluster use a
4515 // decision that has to survive a frame.
4516 read_only: true,
4517 dynamic: false,
4518 stride: size_of::<u32>() as u32,
4519 },
4520 count: 1,
4521 flags: BindingFlags::empty(),
4522 });
4523 }
4524
4525 // The shared fragment light list and froxel grid are bound on every
4526 // path and in every group, unlike the four
4527 // conditional ranges above: `mesh.slang`'s fragment stage reads them
4528 // whatever geometry produced the primitive, so there is no configuration
4529 // in which the layout can omit them.
4530 //
4531 // `geometry` joins `FRAGMENT` in the visibility for binding 7's reason
4532 // exactly: Slang's Metal backend materialises every global into every
4533 // entry point, so the vertex and mesh stages take these buffers whether
4534 // they read them or not.
4535 mesh_entries.push(BindGroupLayoutEntry {
4536 binding: LIGHT_LIST_BINDING,
4537 visibility: geometry.union(ShaderStages::FRAGMENT),
4538 kind: BindingKind::StorageBuffer {
4539 read_only: true,
4540 dynamic: false,
4541 stride: crcbl_shaders::light::LIGHT_STRIDE as u32,
4542 },
4543 count: 1,
4544 flags: BindingFlags::empty(),
4545 });
4546 mesh_entries.push(BindGroupLayoutEntry {
4547 binding: LIGHT_GRID_BINDING,
4548 visibility: geometry.union(ShaderStages::FRAGMENT),
4549 kind: BindingKind::StorageBuffer {
4550 // **Read-only here**, and written by the clustering pass through
4551 // a layout of its own. The graph is what orders the two.
4552 read_only: true,
4553 dynamic: false,
4554 stride: size_of::<u32>() as u32,
4555 },
4556 count: 1,
4557 flags: BindingFlags::empty(),
4558 });
4559 // Topic 46's occlusion channel, last of the set
4560 // — see [`AMBIENT_OCCLUSION_BINDING`] on why last is structural rather
4561 // than tidy.
4562 //
4563 // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4564 // `msl/mesh.metal` is the proof rather than the theory: its `vertexMain`
4565 // takes `ambient_occlusion [[texture(2)]]` whether it reads it or not.
4566 mesh_entries.push(BindGroupLayoutEntry {
4567 binding: AMBIENT_OCCLUSION_BINDING,
4568 visibility: geometry.union(ShaderStages::FRAGMENT),
4569 kind: BindingKind::SampledImage {
4570 view_type: ImageViewType::D2,
4571 // **`Float`, unlike the shadow atlas above.** This one is an
4572 // ordinary `R8Unorm` colour image and the WGSL artifact declares
4573 // `texture_2d<f32>` for it; `Depth` here would be a layout
4574 // claiming a depth format the view does not have.
4575 sample_type: SampleType::Float,
4576 },
4577 count: 1,
4578 flags: BindingFlags::empty(),
4579 });
4580 // The irradiance grid, past the occlusion channel — see
4581 // [`PROBE_TABLE_BINDING`] on why the list only ever grows at its top.
4582 //
4583 // `geometry` beside `FRAGMENT` for binding 7's reason exactly, and
4584 // `msl/mesh.metal` is again the proof rather than the theory: its
4585 // `vertexMain` takes `probes [[buffer(9)]]` whether it reads it or not.
4586 mesh_entries.push(BindGroupLayoutEntry {
4587 binding: PROBE_TABLE_BINDING,
4588 visibility: geometry.union(ShaderStages::FRAGMENT),
4589 kind: BindingKind::StorageBuffer {
4590 // **Read-only, and it stays read-only when the updater lands.**
4591 // The rows are device-local now — see [`crate::probe`], which is
4592 // where that is argued — so the seam no longer forces this;
4593 // what forces it is that the shading path does not write a
4594 // probe and this layout has no headroom to pretend otherwise.
4595 // The raster path is at the WebGPU per-stage storage-buffer
4596 // ceiling already, which the check at the end of the layout
4597 // holds it to, so `read_only: false` here would buy a write
4598 // nothing performs at the price of a binding budget there is
4599 // none of. The irradiance probes' gather is a
4600 // compute pass with a layout of its own, and that is where the
4601 // writable binding of these rows belongs.
4602 read_only: true,
4603 dynamic: false,
4604 stride: crcbl_shaders::probe::PROBE_STRIDE as u32,
4605 },
4606 count: 1,
4607 flags: BindingFlags::empty(),
4608 });
4609 if emit.is_mesh() {
4610 // DAG group records follow the common buffer prefix; the
4611 // remaining mesh-only buffers are sorted after them below.
4612 //
4613 // **Conditional like the mesh-only bindings**, and not for tidiness:
4614 // the raster path's layout is at the WebGPU storage-buffer ceiling
4615 // already, so a row bound unconditionally would be a renderer that
4616 // cannot be built in a browser. The mesh path's own reads sit outside
4617 // that count because `ShaderStages::MESH` is not one of the three
4618 // stages it sums.
4619 mesh_entries.push(BindGroupLayoutEntry {
4620 binding: LEVEL_GROUP_TABLE_BINDING,
4621 // Only the geometry stage reads this table: the
4622 // heatmap's colour is chosen where the cluster is known, and
4623 // `mesh.slang`'s fragment stage — which is this pipeline's —
4624 // does not declare this buffer.
4625 visibility: geometry,
4626 kind: BindingKind::StorageBuffer {
4627 // Read-only and read by **both** mesh entry points, like
4628 // CLUSTER_SELECT_BINDING: an un-amplified stage draws through the same
4629 // `emit_cluster`, so a row present for one and absent for the
4630 // other is a descriptor read out of an empty slot.
4631 read_only: true,
4632 dynamic: false,
4633 stride: size_of::<u32>() as u32,
4634 },
4635 count: 1,
4636 flags: BindingFlags::empty(),
4637 });
4638 }
4639
4640 // The `DFG` table, above everything — see [`SPECULAR_DFG_BINDING`].
4641 //
4642 // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4643 // Metal backend materialises every global into every entry point, so
4644 // `msl/mesh.metal`'s `vertexMain` takes `specular_dfg [[texture(3)]]`
4645 // whether it reads it or not.
4646 mesh_entries.push(BindGroupLayoutEntry {
4647 binding: SPECULAR_DFG_BINDING,
4648 visibility: geometry.union(ShaderStages::FRAGMENT),
4649 kind: BindingKind::SampledImage {
4650 view_type: ImageViewType::D2,
4651 // `Float`, as the occlusion channel above: an `Rgba8Unorm`
4652 // colour image, declared `texture_2d<f32>` by the WGSL artifact.
4653 sample_type: SampleType::Float,
4654 },
4655 count: 1,
4656 flags: BindingFlags::empty(),
4657 });
4658
4659 // §2's normal page, above everything — see [`NORMAL_PAGE_BINDING`].
4660 //
4661 // `geometry` beside `FRAGMENT` for binding 7's reason exactly: Slang's
4662 // Metal backend materialises every global into every entry point, so
4663 // `msl/mesh.metal`'s `vertexMain` takes the page whether it samples it
4664 // or not. **A sampled image and not a storage buffer**, which costs this
4665 // layout nothing at the WebGPU ceiling checked below — that limit counts
4666 // storage buffers, and this row is a texture.
4667 mesh_entries.push(BindGroupLayoutEntry {
4668 binding: NORMAL_PAGE_BINDING,
4669 visibility: geometry.union(ShaderStages::FRAGMENT),
4670 kind: BindingKind::SampledImage {
4671 view_type: ImageViewType::D2Array,
4672 // `Float`: an `Rgba8Unorm` image, declared
4673 // `texture_2d_array<f32>` by the WGSL artifact — the same
4674 // sample type the sRGB base-colour page reports, since both
4675 // decode to floats.
4676 sample_type: SampleType::Float,
4677 },
4678 count: 1,
4679 flags: BindingFlags::empty(),
4680 });
4681 // The area lights' table, above the page — see [`LTC_TABLE_BINDING`].
4682 //
4683 // `geometry` beside `FRAGMENT` for the two rows above it's reason.
4684 // `Float` because `Rgba16Float` is a filterable sampled format on every
4685 // target this engine opens, and the WGSL artifact declares it
4686 // `texture_2d<f32>` — the shader only ever `Load`s it, but the layout
4687 // has to say what the module declared.
4688 mesh_entries.push(BindGroupLayoutEntry {
4689 binding: LTC_TABLE_BINDING,
4690 visibility: geometry.union(ShaderStages::FRAGMENT),
4691 kind: BindingKind::SampledImage {
4692 view_type: ImageViewType::D2,
4693 sample_type: SampleType::Float,
4694 },
4695 count: 1,
4696 flags: BindingFlags::empty(),
4697 });
4698 // Topic 45's contact-shadow channel, last of the set —
4699 // see [`CONTACT_SHADOW_BINDING`] on why last is structural rather than
4700 // tidy.
4701 //
4702 // `geometry` beside `FRAGMENT` and `Float` for the occlusion channel's
4703 // reasons exactly: it is the same `R8Unorm` shape, and Slang's Metal
4704 // backend materialises every global into every entry point whether that
4705 // stage reads it or not.
4706 mesh_entries.push(BindGroupLayoutEntry {
4707 binding: CONTACT_SHADOW_BINDING,
4708 visibility: geometry.union(ShaderStages::FRAGMENT),
4709 kind: BindingKind::SampledImage {
4710 view_type: ImageViewType::D2,
4711 sample_type: SampleType::Float,
4712 },
4713 count: 1,
4714 flags: BindingFlags::empty(),
4715 });
4716 // The irradiance probes' per-probe visibility maps, last
4717 // of the set — see [`PROBE_VISIBILITY_BINDING`] on why last is
4718 // structural.
4719 //
4720 // `D2Array` has to be *declared*, not merely bound: WebGPU compares the
4721 // dimension a layout entry claims against the view handed to it at
4722 // pipeline creation, which is the normal page's own note.
4723 // `UnfilterableFloat` for the same reason and measured the same way: the
4724 // image is `Rg32Float`, which is unfilterable without WebGPU's
4725 // `float32-filterable`, and this slot declared `Float` made Chromium
4726 // refuse the whole mesh bind group — "None of the supported sample types
4727 // (UnfilterableFloat) ... match the expected sample types (Float)" —
4728 // which took every 3D demo's frame to black. Reading it only with `Load`
4729 // does not lift that: the check is on the layout against the view's
4730 // format, not on how the shader gets at it.
4731 mesh_entries.push(BindGroupLayoutEntry {
4732 binding: PROBE_VISIBILITY_BINDING,
4733 visibility: geometry.union(ShaderStages::FRAGMENT),
4734 kind: BindingKind::SampledImage {
4735 view_type: ImageViewType::D2Array,
4736 sample_type: SampleType::UnfilterableFloat,
4737 },
4738 count: 1,
4739 flags: BindingFlags::empty(),
4740 });
4741 // §2's other two pages, last of the set — see [`MRO_PAGE_BINDING`] and
4742 // [`EMISSIVE_PAGE_BINDING`] on why last is structural rather than tidy.
4743 //
4744 // `geometry` beside `FRAGMENT`, `D2Array` and `Float` are the normal
4745 // page's three answers exactly, and for its reasons: Slang's Metal
4746 // backend materialises every global into every entry point, WebGPU
4747 // compares the declared dimension against the bound view, and both
4748 // images are `Rgba8Unorm`-family formats that decode to filterable
4749 // floats.
4750 for binding in [MRO_PAGE_BINDING, EMISSIVE_PAGE_BINDING] {
4751 mesh_entries.push(BindGroupLayoutEntry {
4752 binding,
4753 visibility: geometry.union(ShaderStages::FRAGMENT),
4754 kind: BindingKind::SampledImage {
4755 view_type: ImageViewType::D2Array,
4756 sample_type: SampleType::Float,
4757 },
4758 count: 1,
4759 flags: BindingFlags::empty(),
4760 });
4761 }
4762 mesh_entries.sort_by_key(|entry| entry.binding);
4763 let mesh_desc = BindGroupLayoutDesc {
4764 label: Some(MESH_LAYOUT_LABEL),
4765 entries: &mesh_entries,
4766 };
4767 // **This layout is at the guaranteed limit with no headroom on the
4768 // raster path, in both raster stages**: the vertex stage takes every
4769 // storage buffer a WebGPU device promises, and since bindings 1 to 5
4770 // gained FRAGMENT visibility for Metal's debug layer the fragment stage
4771 // takes the same number. A ninth in either is a renderer that cannot be
4772 // built in a browser or on SwiftShader, so it fails here rather than at
4773 // somebody else's `createPipelineLayout` — see
4774 // [`crcbl_hal::check_portable_storage_buffers`], which also says why the
4775 // mesh path's extra reads are outside the count.
4776 // `Some("mesh")`, which is the *pipeline* layout's label, not
4777 // `mesh_desc.label` — the error text reads "pipeline layout {label}
4778 // binds …", so naming the bind group layout there sends the reader to
4779 // the wrong object.
4780 check_portable_storage_buffers(Some("mesh"), &[&mesh_desc])?;
4781 let mesh_layout = device.create_bind_group_layout(&mesh_desc)?;
4782 rollback.bind_group_layouts.push(mesh_layout);
4783
4784 // A dynamic offset must be a multiple of the device's alignment, and one
4785 // block has to fit inside one stride. Read from the device rather than
4786 // assumed, exactly as `crate::sprite_pass` does: 256 on WebGPU, 64 on a
4787 // typical desktop Vulkan driver.
4788 //
4789 // One stride for both blocks, sized for the larger — see
4790 // [`DRAW_CONSTANTS_BLOCK`]. Which of the two a bucket's block holds is
4791 // decided below.
4792 let alignment = device.caps().limits.min_uniform_buffer_offset_alignment;
4793 let draw_stride =
4794 u32::try_from(DRAW_CONSTANTS_BLOCK.next_multiple_of(alignment)).map_err(|_| {
4795 HalError::InvalidDescriptor(format!(
4796 "min_uniform_buffer_offset_alignment is {alignment}, which no dynamic \
4797 offset can express"
4798 ))
4799 })?;
4800 let draw_constants = device.create_buffer(&BufferDesc {
4801 label: Some("mesh draw constants"),
4802 // A block per bucket per draw region: a region's draws name their
4803 // own run starts, and the mesh path's block names the region's
4804 // argument structure. See `crcbl_shaders::draw_gen::DRAW_REGIONS`.
4805 size: u64::from(draw_stride)
4806 * u64::from(bucket_count)
4807 * u64::from(crcbl_shaders::draw_gen::DRAW_REGIONS),
4808 usage: BufferUsage::UNIFORM,
4809 memory: MemoryLocation::HostUpload,
4810 })?;
4811 rollback.buffers.push(draw_constants);
4812 // --- the shadow map's own resources ---
4813 //
4814 // Before the bind groups, because every one of them names the atlas or
4815 // the placeholder standing in for it.
4816 let (atlas_width, atlas_height) = shadow::atlas_extent();
4817 let shadow_atlas = device.create_image(&ImageDesc {
4818 label: Some("shadow atlas"),
4819 image_type: ImageType::D2,
4820 format: Format::D32Float,
4821 extent: crcbl_hal::Extent3d::d2(atlas_width, atlas_height),
4822 mip_levels: 1,
4823 samples: 1,
4824 // `TRANSFER_SRC` so a test can copy the cascades back and check
4825 // that something was written into them. A shadow map that stayed at
4826 // its clear value produces a frame that looks entirely plausible —
4827 // everything is lit — so the readback is the only thing that can
4828 // tell a working pass from one that drew nothing.
4829 usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT
4830 .union(ImageUsage::SAMPLED)
4831 .union(ImageUsage::TRANSFER_SRC),
4832 })?;
4833 rollback.images.push(shadow_atlas);
4834 let shadow_atlas_view = device.create_image_view(&ImageViewDesc {
4835 label: Some("shadow atlas"),
4836 image: shadow_atlas,
4837 view_type: ImageViewType::D2,
4838 format: Format::D32Float,
4839 range: ImageSubresourceRange::all(Format::D32Float),
4840 })?;
4841 rollback.image_views.push(shadow_atlas_view);
4842
4843 let shadow_placeholder = device.create_image(&ImageDesc {
4844 label: Some("shadow placeholder"),
4845 image_type: ImageType::D2,
4846 format: Format::D32Float,
4847 extent: crcbl_hal::Extent3d::d2(1, 1),
4848 mip_levels: 1,
4849 samples: 1,
4850 usage: ImageUsage::DEPTH_STENCIL_ATTACHMENT.union(ImageUsage::SAMPLED),
4851 })?;
4852 rollback.images.push(shadow_placeholder);
4853 let shadow_placeholder_view = device.create_image_view(&ImageViewDesc {
4854 label: Some("shadow placeholder"),
4855 image: shadow_placeholder,
4856 view_type: ImageViewType::D2,
4857 format: Format::D32Float,
4858 range: ImageSubresourceRange::all(Format::D32Float),
4859 })?;
4860 rollback.image_views.push(shadow_placeholder_view);
4861
4862 // The occlusion placeholder, beside the shadow one and for the same
4863 // reason: every group of this layout has to fill
4864 // [`AMBIENT_OCCLUSION_BINDING`], and most of them are built before the
4865 // graph has an occlusion image to name.
4866 //
4867 // **Uploaded rather than cleared**, unlike the depth placeholder above,
4868 // and the four bytes are the whole point — see
4869 // [`AMBIENT_OCCLUSION_NONE`], which is where each of them is argued.
4870 // Left undefined this would be a random ambient scale *and* a random
4871 // direction to steer it along, on any frame that fell back to it.
4872 let ambient_occlusion_placeholder = upload_texture(
4873 device,
4874 queue,
4875 "ssao placeholder",
4876 Format::Rgba8Unorm,
4877 1,
4878 1,
4879 &AMBIENT_OCCLUSION_NONE,
4880 )?;
4881 rollback.textures.push(ambient_occlusion_placeholder);
4882
4883 // The contact-shadow placeholder, beside the occlusion one and on its
4884 // terms exactly: every group of this layout has to fill
4885 // [`CONTACT_SHADOW_BINDING`], and most of them are built before the graph
4886 // has a contact-shadow image to name. `0xFF` is `1.0` through `R8Unorm`,
4887 // so a fragment that reads this one is a fragment the sun reaches
4888 // unobstructed.
4889 let contact_shadow_placeholder = upload_texture(
4890 device,
4891 queue,
4892 "contact shadow placeholder",
4893 Format::R8Unorm,
4894 1,
4895 1,
4896 &[CONTACT_SHADOW_NONE],
4897 )?;
4898 rollback.textures.push(contact_shadow_placeholder);
4899
4900 // The probe-visibility placeholder, on the two above it's terms: every
4901 // group of this layout has to fill [`PROBE_VISIBILITY_BINDING`], and
4902 // nothing has been captured when they are built. One texel of
4903 // [`probe_visibility_none`], which no surface is further away than, so a
4904 // probe read through it keeps all of its weight.
4905 let probe_visibility_placeholder = upload_texture_layers(
4906 device,
4907 queue,
4908 "probe visibility placeholder",
4909 Format::Rg32Float,
4910 1,
4911 1,
4912 &[&probe_visibility_none()],
4913 )?;
4914 rollback.textures.push(probe_visibility_placeholder);
4915
4916 // The split-sum `DFG` table, uploaded once and read by every frame this
4917 // renderer will draw — `crcbl_shaders::dfg` is where it is integrated,
4918 // committed and encoded, and `SPECULAR_ALBEDO_BINDING` is where it lands.
4919 //
4920 // **Cooked bytes rather than a computed image**: the integrator
4921 // importance-samples a lobe, which is `sin`, `cos` and a `powf`, and this
4922 // engine's goldens are compared across four backends with no tolerance.
4923 // Baking here would be four slightly different tables.
4924 let specular_dfg = upload_texture(
4925 device,
4926 queue,
4927 "dfg table",
4928 // Two bytes of fixed point per channel, high byte first — see
4929 // `crcbl_shaders::dfg::PAIR_TEXEL_BYTES`, which argues why this is
4930 // not the `Rg16Float` the format's own doc anticipated.
4931 Format::Rgba8Unorm,
4932 DFG_SIZE_U32,
4933 DFG_SIZE_U32,
4934 &dfg::pair_texels(),
4935 )?;
4936 rollback.textures.push(specular_dfg);
4937
4938 // The area lights' fit, beside it and on its terms — cooked bytes for
4939 // the same reason, and `Rgba16Float` rather than fixed point because
4940 // these are matrix entries rather than shares of arriving light.
4941 // `crcbl_shaders::ltc::LTC_TEXEL_BYTES` argues the format.
4942 let ltc_table = upload_texture(
4943 device,
4944 queue,
4945 "ltc table",
4946 Format::Rgba16Float,
4947 LTC_SIZE_U32,
4948 LTC_SIZE_U32,
4949 <c::texels(),
4950 )?;
4951 rollback.textures.push(ltc_table);
4952 service();
4953
4954 // **A comparison sampler, and that is the PCF.** Each
4955 // `SampleCmpLevelZero` returns the filtered fraction of four texels that
4956 // passed the test, so the shader's 3×3 kernel is nine hardware-bilinear
4957 // comparisons rather than nine raw fetches it averages itself.
4958 //
4959 // `Greater` for the engine's reversed-Z, exactly as the depth *test*
4960 // is: the receiver survives when it is nearer the light than whatever
4961 // the map stored. `SamplerDesc::compare` carries the same warning.
4962 //
4963 // Clamped on every axis so a receiver just outside a cascade's box
4964 // reads the edge rather than wrapping into the opposite corner — the
4965 // shader's own bounds check is what actually handles that case, and this
4966 // is the second line of defence one texel wide.
4967 let shadow_sampler = device.create_sampler(&SamplerDesc {
4968 label: Some("shadow comparison"),
4969 mag_filter: FilterMode::Linear,
4970 min_filter: FilterMode::Linear,
4971 mip_filter: FilterMode::Nearest,
4972 address_mode: [SamplerAddressMode::ClampToEdge; 3],
4973 compare: Some(crcbl_hal::CompareOp::Greater),
4974 ..SamplerDesc::default()
4975 })?;
4976 rollback.samplers.push(shadow_sampler);
4977
4978 // --- the camera ---
4979 //
4980 // Everything the camera's picture needs of its own, built against the
4981 // scene resources above — see [`view`], which is where the line between
4982 // the two is drawn. Into the rollback whole as soon as it exists, so a
4983 // failure further down releases it with everything else.
4984 let slot_pages = vec![page_bindings; instance_buffers.len()];
4985 rollback.primary = Some(View::build(
4986 device,
4987 queue,
4988 &ViewInputs {
4989 id: ViewId::PRIMARY,
4990 effects: RenderEffects::all(),
4991 background: ViewBackground::Scene,
4992 lighting: ViewLighting::Scene,
4993 target_format,
4994 emit,
4995 instances: &instance_buffers,
4996 mesh_table,
4997 bucket_meshes: &bucket_meshes,
4998 bucket_modes: &bucket_modes,
4999 bucket_clusters: &bucket_clusters,
5000 bucket_cluster_bases: &bucket_cluster_bases,
5001 mesh_levels: &mesh_levels,
5002 level_groups: &level_groups,
5003 level_meshes: &level_meshes,
5004 instance_capacity: scene.capacities.instances,
5005 light_capacity: scene.capacities.lights,
5006 clusters: rollback.clusters.as_ref(),
5007 task_lanes: view::task_lanes(culls_clusters),
5008 mesh_layout,
5009 vertices,
5010 draw_constants,
5011 materials: material_buffer,
5012 pages: &slot_pages,
5013 probes: &probe_buffers,
5014 specular_dfg: specular_dfg.view,
5015 ltc_table: ltc_table.view,
5016 shadow_map: shadow_atlas_view,
5017 shadow_sampler,
5018 ambient_occlusion: ambient_occlusion_placeholder.view,
5019 contact_shadow: contact_shadow_placeholder.view,
5020 probe_visibility: probe_visibility_placeholder.view,
5021 },
5022 service,
5023 )?);
5024 let primary = rollback.primary.as_ref().expect("just stored");
5025
5026 // Written here and never again: **which word holds** a bucket's run
5027 // start is fixed by the bucket table and the capacity, and both are
5028 // fixed at build. What varies per frame is where the run starts and how
5029 // much of it is filled, and the GPU writes both — the start into that
5030 // word, the count into the bucket's indirect arguments. See
5031 // `mesh.slang`'s header for why the block names a word rather than
5032 // carrying the start.
5033 //
5034 // Taken from the camera's generator and bound for every generator's
5035 // draws: the shadow culls and every secondary view are built from the
5036 // same table and the same capacity, so `bucket_start_word` answers the
5037 // same for all of them.
5038 let draws = &primary.draws;
5039 let mut bucket_constants = vec![0u32; bucket_meshes.len()];
5040 // **Every draw region's copy**, region 0's at the offsets
5041 // `bucket_constants` records and each further region a bucket count of
5042 // strides behind the one before: a region's draw reads its own run
5043 // start and — on the mesh path — its own argument structure, and the
5044 // two are the only words a region changes. See
5045 // `crcbl_shaders::draw_gen::DRAW_REGIONS`.
5046 for (region, (bucket, index)) in
5047 (0..crcbl_shaders::draw_gen::DRAW_REGIONS).flat_map(|region| {
5048 (0..bucket_count).map(move |bucket| (region, (bucket, bucket as usize)))
5049 })
5050 {
5051 let offset = (region * bucket_count + bucket) * draw_stride;
5052 if region == 0 {
5053 bucket_constants[index] = offset;
5054 }
5055 let start_at = draws.region_start_word(region, bucket);
5056 // The mesh path's block says three more things — where this
5057 // bucket's mesh's clusters are, how many it has, and which element
5058 // of the indirect arguments holds its instance count — because a
5059 // dispatch carries none of them and a `draw_indexed_indirect` does
5060 // not need them. All three are fixed when the bucket table is,
5061 // exactly like `start_at`.
5062 let block = if emit.is_mesh() {
5063 crcbl_shaders::meshlet::ClusterDrawConstants {
5064 start_at,
5065 cluster_base: bucket_cluster_bases[index],
5066 cluster_count: bucket_clusters[index],
5067 // The region's argument structure, which is where this
5068 // region's instance count is.
5069 bucket: region * bucket_count + bucket,
5070 // The same number the draw-argument pass indexes the state
5071 // with, taken from the object that owns the buffer rather
5072 // than recomputed from the group table — the two indexing it
5073 // differently is a cluster reading another instance's
5074 // decision.
5075 group_stride: draws.group_stride(),
5076 // Where the group records are in the table buffer, from the
5077 // object that packed it — the screen-error heatmap's one
5078 // input that is not already in the frame block. Taken from
5079 // `DrawGen` rather than recomputed here for `group_stride`'s
5080 // reason: two spellings of one offset is an overlay reading
5081 // another region's words as a group.
5082 level_groups_at: draws.table_offsets().level_groups_at,
5083 // The same two numbers again as words of that buffer,
5084 // which is where a draw that is not the first of a ranged
5085 // call reads them — `mesh_cluster.slang`'s "One call for
5086 // a range of buckets". This bucket's, not the region's
5087 // argument structure's: the tables hold one word a bucket.
5088 cluster_base_at: draws.table_offsets().bucket_cluster_bases_at + bucket,
5089 cluster_count_at: draws.table_offsets().bucket_clusters_at + bucket,
5090 // Where this bucket's task chunks start in this region,
5091 // and where the region's end: what a flat call binding
5092 // this block searches between — `mesh_cluster.slang`'s
5093 // `taskMain`.
5094 chunk_starts_at: draws.chunk_start_word(region, bucket),
5095 chunk_starts_end: draws.chunk_start_word(region, bucket_count),
5096 }
5097 .to_bytes()
5098 .to_vec()
5099 } else {
5100 // **The bucket's mesh, which is not always the drawn instance's.**
5101 // A uniform cut selects one of a DAG's levels and each level is
5102 // a mesh table entry of its own, so this is what says which
5103 // geometry the draw's index range belongs to; the instance goes
5104 // on naming level 0. See `mesh::DrawConstants::mesh`.
5105 mesh::DrawConstants {
5106 start_at,
5107 mesh: bucket_meshes[index],
5108 mesh_at: draws.bucket_mesh_word(bucket),
5109 }
5110 .to_bytes()
5111 .to_vec()
5112 };
5113 device.write_buffer(draw_constants, u64::from(offset), &block)?;
5114 }
5115
5116 let region_step = RegionStep {
5117 constants: bucket_count * draw_stride,
5118 args: draws.args_region_offset(1),
5119 counts: draws.counts_region_offset(1),
5120 };
5121
5122 // §3.3's cull, once per cascade and once per shadowed light. Each gets
5123 // its own `DrawGen` and therefore its own frustum, survivor list and
5124 // indirect arguments — which is what "one cull dispatch per cascade
5125 // against the same instance/geometry pools" means, and why the instance
5126 // ring and the mesh table below are the same handles the camera's cull
5127 // was given.
5128 //
5129 // **One per light rather than one per tile**, which is topic 18's fourth
5130 // decision and what `SHADOW_CULLS` is: a point light's six faces cull
5131 // against the light's sphere once and draw that one visible set through
5132 // six matrices.
5133 //
5134 // **Built for every slot, including the ones no light may ever hold.** A
5135 // generator's buffers are sized by the instance capacity rather than by
5136 // the scene, so building one on demand would mean allocating device
5137 // memory inside `begin_frame` — and a frame that cannot allocate is a
5138 // frame that cannot draw. The unused ones cost memory and no dispatch:
5139 // `add_shadow_pass` records passes for the occupied slots alone.
5140 for cull in 0..SHADOW_CULLS {
5141 // Into the rollback as each is built, on the same terms as the
5142 // camera's: a failure two culls in has to release the first one,
5143 // and the rollback is the only thing that knows about it.
5144 let label = if cull < shadow::CASCADES {
5145 format!("shadow cascade {cull}")
5146 } else {
5147 format!("shadow light {}", cull - shadow::CASCADES)
5148 };
5149 let draws = DrawGen::new(
5150 device,
5151 queue,
5152 &DrawGenDesc {
5153 label: Some(&label),
5154 instances: &instance_buffers,
5155 mesh_table,
5156 bucket_meshes: &bucket_meshes,
5157 bucket_modes: &bucket_modes,
5158 bucket_clusters: &bucket_clusters,
5159 bucket_cluster_bases: &bucket_cluster_bases,
5160 mesh_levels: &mesh_levels,
5161 level_groups: &level_groups,
5162 level_meshes: &level_meshes,
5163 instance_capacity: scene.capacities.instances,
5164 // No view's: a shadow map is drawn from everything resident
5165 // that casts, so an instance a camera hides still casts its
5166 // shadow and one `set_instance_casts_shadow` turned off does
5167 // not — on every geometry path, since this is the cull they
5168 // all draw from. The reflective shadow maps draw these same
5169 // survivors, so such an instance bounces no light either.
5170 hidden_view: mesh::GpuInstance::CASTS_NO_SHADOW,
5171 // A light slot may hold a point light, whose six faces cull
5172 // separately into six regions of the one generator; a
5173 // cascade never does.
5174 mode: if cull < shadow::CASCADES {
5175 crcbl_shaders::draw_gen::DrawMode::Plain
5176 } else {
5177 crcbl_shaders::draw_gen::DrawMode::Faces
5178 },
5179 task_lanes: view::task_lanes(culls_clusters),
5180 },
5181 )?;
5182 rollback.shadow_draws.push(draws);
5183 service();
5184 }
5185 // The handles are `Copy` and are read out here for the same reason the
5186 // camera's are above: the pool they came from is the rollback's now.
5187 let tile_buffers: Vec<TileBuffers> = rollback
5188 .shadow_draws
5189 .iter()
5190 .map(|draws| TileBuffers {
5191 runs: (0..instance_buffers.len())
5192 .map(|frame| draws.runs(frame))
5193 .collect(),
5194 args: (0..instance_buffers.len())
5195 .map(|frame| draws.args(frame))
5196 .collect(),
5197 cull_params: (0..instance_buffers.len())
5198 .map(|frame| draws.cull_params(frame))
5199 .collect(),
5200 cull_stats: (0..instance_buffers.len())
5201 .map(|frame| draws.visible_count(frame))
5202 .collect(),
5203 group_state: draws.group_state(),
5204 })
5205 .collect();
5206
5207 let mut shadow_uniforms = Vec::with_capacity(FRAMES_IN_FLIGHT);
5208 let mut shadow_groups = Vec::with_capacity(FRAMES_IN_FLIGHT);
5209 let mut shadow_selection = Vec::with_capacity(FRAMES_IN_FLIGHT);
5210 let mut shadow_group_entries = Vec::with_capacity(FRAMES_IN_FLIGHT);
5211 for (frame, &slot_instances) in instance_buffers.iter().enumerate() {
5212 // Everything a group of this layout names that is the same in all of
5213 // this frame's — the camera's list and table buffers included, which
5214 // a shadow view binds because the layout declares them and reads
5215 // nothing of. The per-group half is what `MeshGroup` below varies,
5216 // and the two exist so the colour pass's group and the shadow pass's
5217 // are one description rather than two that agree today.
5218 let shared = SharedBindings {
5219 vertices,
5220 draw_constants,
5221 mesh_table,
5222 materials: material_buffer,
5223 pages: page_bindings,
5224 clusters: rollback.clusters.as_ref(),
5225 shadow_sampler,
5226 lights: primary.lights.lights(frame),
5227 light_grid: primary.lights.grid(frame),
5228 probes: probe_buffers[frame],
5229 tables: primary.draws.tables(),
5230 specular_dfg: specular_dfg.view,
5231 ltc_table: ltc_table.view,
5232 };
5233
5234 // The same layout again, once per shadow view, differing in exactly
5235 // the things a view is: which matrix, and which cull's survivors.
5236 //
5237 // **The view's own uniforms and the cull's shared buffers**, which
5238 // is the whole of what a point light's six faces are: one visible
5239 // set, six matrices. `shadow_cull` is the map from a view to the
5240 // generator behind it, and it is a compile-time one because a bind
5241 // group names its buffers when it is created — where a face's *tile*
5242 // is decided per frame and reaches the device as a viewport.
5243 let mut frame_shadow_uniforms = Vec::with_capacity(SHADOW_VIEWS);
5244 let mut frame_shadow_groups = Vec::with_capacity(SHADOW_VIEWS);
5245 let mut frame_shadow_selection = Vec::with_capacity(SHADOW_VIEWS);
5246 let mut frame_shadow_entries = Vec::with_capacity(SHADOW_VIEWS);
5247 for view in 0..SHADOW_VIEWS {
5248 let buffers = &tile_buffers[if view < shadow::CASCADES {
5249 view
5250 } else {
5251 shadow_cull((view - shadow::CASCADES) / shadow::POINT_FACES)
5252 }];
5253 let tile_uniforms = device.create_buffer(&BufferDesc {
5254 label: Some("shadow view uniforms"),
5255 size: mesh::FRAME_UNIFORMS_SIZE as u64,
5256 usage: BufferUsage::UNIFORM,
5257 memory: MemoryLocation::HostUpload,
5258 })?;
5259 rollback.buffers.push(tile_uniforms);
5260 let entries = MeshGroup {
5261 uniforms: tile_uniforms,
5262 instances: slot_instances,
5263 runs: buffers.runs[frame],
5264 args: buffers.args[frame],
5265 // The amplification stage culls clusters against whatever
5266 // frustum is in this block, and against
5267 // `frame.camera_position` — which in a view's copy is the
5268 // *light*. So the per-cluster cull rejects what faces away
5269 // from the light, which is the right question for a shadow
5270 // map and the wrong one to have asked with the camera's
5271 // frustum.
5272 cull_params: buffers.cull_params[frame],
5273 cull_stats: buffers.cull_stats[frame],
5274 // **This view's own**, and not the colour pass's: that pass
5275 // is recorded last and would write over it. See
5276 // `ForwardRenderer::shadow_selection`.
5277 cluster_selection: tile_selection.get(view).map(|ring| ring[frame]),
5278 // Its cull's — see `TileBuffers::group_state`, which is
5279 // where that budget is argued.
5280 group_state: emit.is_mesh().then_some(buffers.group_state),
5281 shadow_map: shadow_placeholder_view,
5282 // A cascade shades nothing — the pipeline has no fragment
5283 // stage — so this slot exists only because Metal
5284 // materialises every global into every entry point.
5285 ambient_occlusion: ambient_occlusion_placeholder.view,
5286 contact_shadow: contact_shadow_placeholder.view,
5287 probe_visibility: probe_visibility_placeholder.view,
5288 }
5289 .entries(&shared);
5290 let group = device.create_bind_group(&BindGroupDesc {
5291 label: Some("shadow view"),
5292 layout: mesh_layout,
5293 entries: &entries,
5294 variable_count: None,
5295 })?;
5296 rollback.bind_groups.push(group);
5297 frame_shadow_uniforms.push(tile_uniforms);
5298 frame_shadow_groups.push(group);
5299 frame_shadow_entries.push(entries);
5300 frame_shadow_selection.extend(tile_selection.get(view).map(|ring| ring[frame]));
5301 }
5302 shadow_uniforms.push(frame_shadow_uniforms);
5303 shadow_groups.push(frame_shadow_groups);
5304 shadow_group_entries.push(frame_shadow_entries);
5305 shadow_selection.push(frame_shadow_selection);
5306 service();
5307 }
5308
5309 let mesh_set_layouts = [mesh_layout];
5310 let mesh_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5311 label: Some("mesh"),
5312 bind_group_layouts: &mesh_set_layouts,
5313 // The camera goes in the uniform buffer above rather than here:
5314 // `Features::PUSH_CONSTANTS` is absent on Tier B and the seam is
5315 // explicit that the substitute is a data-layout decision. So this
5316 // file needs no tier branch at all — it has been on Tier B's shape
5317 // since P1, and `crate::ui_pass` is where the split actually bites.
5318 push_constants: None,
5319 })?;
5320 rollback.pipeline_layouts.push(mesh_pipeline_layout);
5321
5322 // The colour pass's pipeline and its depth-only twin, out of one set of
5323 // modules — see [`MeshModules`], which is where the two shapes and the
5324 // reasons for them live. Both are created before either is unwrapped and
5325 // the modules are released between, so a failing creation leaks nothing.
5326 //
5327 // **Each shape is built twice, once per material side** — see
5328 // [`SidedPipelines`], which is where the cull modes and the reason for a
5329 // pipeline rather than a per-draw state live. The shadow tile clear is
5330 // the one exception: its triangle comes out of `SV_VertexID` and it
5331 // already culls nothing.
5332 //
5333 // **`service` before every one of them**: on a cold driver cache each is
5334 // a shader compilation, and this batch is the build's longest run of
5335 // them — see [`ForwardRenderer::with_scene_serviced`].
5336 let modules = MeshModules::new(device, emit, culls_clusters)?;
5337 let mesh_results = MeshModules::sided(|cull| {
5338 service();
5339 modules.color_pipeline(
5340 device,
5341 mesh_pipeline_layout,
5342 PolygonMode::Fill,
5343 cull,
5344 "forward",
5345 )
5346 });
5347 let shadow_results = MeshModules::sided(|cull| {
5348 service();
5349 modules.depth_pipeline(device, mesh_pipeline_layout, cull)
5350 });
5351 // And its cutout twin, which a frame whose material table masks alpha is
5352 // recorded with instead — see [`MeshModules::depth_masked_pipeline`].
5353 let depth_masked_results = MeshModules::sided(|cull| {
5354 service();
5355 modules.depth_masked_pipeline(device, mesh_pipeline_layout, cull)
5356 });
5357 // And the one that resets a tile, which the cadence rung needs and the
5358 // attachment's load operation cannot express — see
5359 // [`MeshModules::depth_clear_pipeline`].
5360 service();
5361 let shadow_clear_result = modules.depth_clear_pipeline(device, mesh_pipeline_layout);
5362 // And the irradiance probes' reflective shadow map, built
5363 // from the same modules and the same layout — see
5364 // [`MeshModules::rsm_pipeline`]. Built on every scene rather than only
5365 // on one whose probes ask to be updated: the modules are released a line
5366 // below and a pipeline built later would need them back, which is a
5367 // second shader compilation for a field a `ProbeGrid` decides.
5368 let rsm_results = MeshModules::sided(|cull| {
5369 service();
5370 modules.rsm_pipeline(device, mesh_pipeline_layout, cull)
5371 });
5372 modules.destroy(device);
5373 // Register every successful creation before propagating any error.
5374 // Results later in this batch may own pipelines even when the first
5375 // result failed; dropping an unvisited Result does not release a HAL
5376 // handle. The outer rollback owns all of them until build succeeds.
5377 for pipeline in mesh_results
5378 .iter()
5379 .chain(&shadow_results)
5380 .chain(&depth_masked_results)
5381 .chain(std::iter::once(&shadow_clear_result))
5382 .chain(&rsm_results)
5383 .flatten()
5384 {
5385 rollback.pipelines.push(*pipeline);
5386 }
5387 let into_sided = |results: [Result<GraphicsPipelineHandle, HalError>; 2]|
5388 -> Result<SidedPipelines, HalError> {
5389 let [single, double] = results;
5390 Ok(SidedPipelines { single: single?, double: double? })
5391 };
5392 let mesh_pipeline = into_sided(mesh_results)?;
5393 let shadow_pipeline = into_sided(shadow_results)?;
5394 let depth_masked_pipeline = into_sided(depth_masked_results)?;
5395 let shadow_clear_pipeline = shadow_clear_result?;
5396 let rsm_pipeline = into_sided(rsm_results)?;
5397
5398 // --- the tonemap pass ---
5399 let tonemap_entries = [
5400 BindGroupLayoutEntry {
5401 binding: 0,
5402 visibility: ShaderStages::FRAGMENT,
5403 kind: BindingKind::SampledImage {
5404 view_type: ImageViewType::D2,
5405 sample_type: SampleType::Float,
5406 },
5407 count: 1,
5408 flags: BindingFlags::empty(),
5409 },
5410 BindGroupLayoutEntry {
5411 binding: 1,
5412 visibility: ShaderStages::FRAGMENT,
5413 kind: BindingKind::Sampler { comparison: false },
5414 count: 1,
5415 flags: BindingFlags::empty(),
5416 },
5417 // The exposure — see [`set_exposure`](Self::set_exposure). A uniform
5418 // buffer rather than a push constant, which is [`crate::ui_pass`]'s
5419 // decision restated: WebGPU has no push constants at all, so a range
5420 // here would split this pass into a tier A and a tier B form —
5421 // two layouts, two buffers and, because one Slang entry point reads
5422 // either a `[[vk::push_constant]]` block or a `[[vk::binding]]`ed
5423 // one and never both, a second copy of `tonemap.slang`. Four bytes
5424 // once a frame do not buy that.
5425 //
5426 // `FRAGMENT` alone, and the artifact agrees: `spirv/tonemap.spv`
5427 // lists `%params` in the fragment `OpEntryPoint`'s interface and not
5428 // in the vertex one, because the vertex stage generates three
5429 // corners out of `SV_VertexID` and reads nothing.
5430 BindGroupLayoutEntry {
5431 binding: 2,
5432 visibility: ShaderStages::FRAGMENT,
5433 kind: BindingKind::UniformBuffer { dynamic: false },
5434 count: 1,
5435 flags: BindingFlags::empty(),
5436 },
5437 // The measured exposure — see [`crate::exposure`]. **Bound on every
5438 // frame, whether or not anything measured**, because a binding that
5439 // comes and goes is a second pipeline layout and a second group
5440 // cache keyed on which one is live, to save four bytes. The block
5441 // above carries the switch that decides whether the shader reads it.
5442 BindGroupLayoutEntry {
5443 binding: 3,
5444 visibility: ShaderStages::FRAGMENT,
5445 kind: BindingKind::StorageBuffer {
5446 // Written by `exposure.slang`'s reduce and read here —
5447 // `StructuredBuffer` in this shader, which is the truth
5448 // rather than a hint.
5449 read_only: true,
5450 dynamic: false,
5451 stride: size_of::<u32>() as u32,
5452 },
5453 count: 1,
5454 flags: BindingFlags::empty(),
5455 },
5456 ];
5457 let tonemap_desc = BindGroupLayoutDesc {
5458 label: Some("tonemap scene"),
5459 entries: &tonemap_entries,
5460 };
5461 check_portable_storage_buffers(Some("tonemap"), &[&tonemap_desc])?;
5462 let tonemap_layout = device.create_bind_group_layout(&tonemap_desc)?;
5463 rollback.bind_group_layouts.push(tonemap_layout);
5464 let tonemap_set_layouts = [tonemap_layout];
5465 let tonemap_pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
5466 label: Some("tonemap"),
5467 bind_group_layouts: &tonemap_set_layouts,
5468 push_constants: None,
5469 })?;
5470 rollback.pipeline_layouts.push(tonemap_pipeline_layout);
5471 let tonemap_vertex = entry(&TONEMAP, Stage::Vertex)?;
5472 let tonemap_fragment = entry(&TONEMAP, Stage::Fragment)?;
5473 let tonemap_module = device.create_shader_module(&ShaderModuleDesc {
5474 label: Some("tonemap.slang"),
5475 spirv: TONEMAP.spirv(),
5476 wgsl: TONEMAP.wgsl(),
5477 msl: TONEMAP.msl(),
5478 // A container per entry point, for the reason the mesh module above
5479 // gives.
5480 dxil: &TONEMAP.dxil_containers(),
5481 })?;
5482 let tonemap_targets = [ColorTargetState::opaque(target_format)];
5483 let tonemap_pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5484 label: Some("tonemap"),
5485 layout: tonemap_pipeline_layout,
5486 vertex: ShaderEntry {
5487 module: tonemap_module,
5488 entry_point: tonemap_vertex,
5489 },
5490 fragment: Some(ShaderEntry {
5491 module: tonemap_module,
5492 entry_point: tonemap_fragment,
5493 }),
5494 // The full-screen triangle is deliberately oversized, so two of its
5495 // vertices are outside the viewport and its winding is not worth
5496 // reasoning about. `CullMode::None` is the honest setting.
5497 primitive: PrimitiveState::default(),
5498 depth_stencil: None,
5499 multisample: MultisampleState::default(),
5500 color_targets: &tonemap_targets,
5501 });
5502 device.destroy_shader_module(tonemap_module);
5503 let tonemap_pipeline = tonemap_pipeline?;
5504 rollback.pipelines.push(tonemap_pipeline);
5505 service();
5506
5507 // Nearest, not linear: see `tonemap.slang` on why a 1:1 blit must not
5508 // leave a golden image depending on two rasterisers agreeing about
5509 // texel-centre arithmetic.
5510 let sampler = device.create_sampler(&SamplerDesc {
5511 label: Some("tonemap scene"),
5512 mag_filter: FilterMode::Nearest,
5513 min_filter: FilterMode::Nearest,
5514 mip_filter: FilterMode::Nearest,
5515 address_mode: [SamplerAddressMode::ClampToEdge; 3],
5516 ..SamplerDesc::default()
5517 })?;
5518 rollback.samplers.push(sampler);
5519
5520 // --- the shadow atlas viewer ---
5521 //
5522 // Built last, so `Rollback::run` releases it first. It writes the
5523 // caller's target rather than a transient — it replaces the picture the
5524 // tonemap put there, which is [`crate::atlas_view`]'s argument — and it
5525 // records on no frame but the one that resolved
5526 // [`DebugView::ShadowAtlas`].
5527 rollback.atlas_viewer = Some(AtlasView::new(
5528 device,
5529 instance_buffers.len(),
5530 target_format,
5531 Self::build_fullscreen,
5532 )?);
5533 service();
5534
5535 Ok(Self {
5536 pool: rollback
5537 .pool
5538 .take()
5539 .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5540 bucket_constants,
5541 region_step,
5542 bucket_modes,
5543 instances: rollback
5544 .instances
5545 .take()
5546 .unwrap_or_else(|| unreachable!("the pool was placed in the rollback above")),
5547 mesh_ids,
5548 skinnable_meshes,
5549 skinned_instances: Vec::new(),
5550 materials: rollback
5551 .materials
5552 .take()
5553 .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5554 material_ids,
5555 probes: rollback
5556 .probes
5557 .take()
5558 .unwrap_or_else(|| unreachable!("the table was placed in the rollback above")),
5559 probe_volume: scene.probes.volume,
5560 base_color_page,
5561 normal_page,
5562 mro_page,
5563 emissive_page,
5564 page_extents,
5565 page_layers,
5566 base_color_sampler,
5567 anisotropy,
5568 // Every slot's groups were just built naming these.
5569 slot_pages: vec![page_bindings; FRAMES_IN_FLIGHT],
5570 retired_pages: Vec::new(),
5571 // No frame has been recorded yet, and the counters say so rather
5572 // than reporting the count a frame *would* have.
5573 recorded_draws: 0,
5574 emit,
5575 range_limit,
5576 clusters: rollback.clusters.take(),
5577 culls_clusters,
5578 draw_constants,
5579 mesh_clusters,
5580 // One entry per description mesh, each holding one bucket per level,
5581 // where the cull pass takes a uniform cut — and nothing at all where
5582 // the amplification stage takes a per-cluster one. Read off the
5583 // bucket table that was actually built rather than re-derived from
5584 // the path.
5585 mesh_level_buckets: if emit.is_mesh() {
5586 Vec::new()
5587 } else {
5588 residents
5589 .iter()
5590 .enumerate()
5591 .map(|(index, resident)| {
5592 let base = bucket_bases[index];
5593 (base..base + resident.levels.len())
5594 .map(|bucket| {
5595 u32::try_from(bucket)
5596 .unwrap_or_else(|_| unreachable!("a table of a few buckets"))
5597 })
5598 .collect()
5599 })
5600 .collect()
5601 },
5602 lod_error_budget: LOD_ERROR_BUDGET,
5603 lod_hold_ratio: LOD_HOLD_RATIO,
5604 // Overwritten by the first `begin_frame`, which is the only thing
5605 // that can know the viewport.
5606 shadow_lod_params: [0.0, 0.0, 0.0],
5607 extra_lights: Vec::new(),
5608 primary: rollback
5609 .primary
5610 .take()
5611 .unwrap_or_else(|| unreachable!("the camera was placed in the rollback above")),
5612 views: Vec::new(),
5613 draw_tables: DrawTables {
5614 bucket_meshes,
5615 bucket_clusters,
5616 bucket_cluster_bases,
5617 mesh_levels,
5618 level_groups,
5619 level_meshes,
5620 instance_capacity: scene.capacities.instances,
5621 light_capacity: scene.capacities.lights,
5622 },
5623 frame_serial: 0,
5624 frame_scene: None,
5625 frame: 0,
5626 mesh_layout,
5627 mesh_pipeline_layout,
5628 mesh_pipeline,
5629 // Off, and unbuilt, on the ground grid's terms below: the wireframe
5630 // view is opt-in, so a caller that never asks for one draws the
5631 // frame it drew before `set_wireframe` existed.
5632 wireframe_pipeline: None,
5633 wireframe_on: false,
5634 occlusion_culling: OcclusionCulling::OFF,
5635 point_face_culls: true,
5636 shadow_view_tamper: None,
5637 // Off, on the line above's terms: the normals view is opt-in, so a
5638 // caller that never asks for one draws the frame it drew before
5639 // `set_normals_view` existed. It builds nothing, so there is no
5640 // second field here.
5641 normals_view: false,
5642 // Off on the same terms, and "off" here is a density of zero: the
5643 // shader's composite is exactly the identity there, so a caller who
5644 // never calls `set_fog` gets the frame byte for byte.
5645 fog: Fog::NONE,
5646 sky: Sky::NONE,
5647 atmosphere: None,
5648 sky_view: None,
5649 sky_view_build: None,
5650 lod_view: false,
5651 heatmap: false,
5652 occlusion_view: false,
5653 motion_view: false,
5654 bent_normal_view: false,
5655 cascade_view: false,
5656 atlas_view: false,
5657 // Following the camera, on the line above's terms: the selection eye
5658 // is the camera's until a caller pins it, so a renderer nobody calls
5659 // `set_frozen_selection_eye` on hands `begin_frame` exactly what it
5660 // handed before this field existed.
5661 frozen_selection_eye: None,
5662 shadow_atlas,
5663 shadow_atlas_view,
5664 shadow_placeholder,
5665 shadow_placeholder_view,
5666 shadow_sampler,
5667 shadow_pipeline,
5668 depth_masked_pipeline,
5669 shadow_clear_pipeline,
5670 rsm_pipeline,
5671 probe_gather,
5672 probe_update: scene.probes.update,
5673 // Overwritten by the first `begin_frame`, which is the only reader's
5674 // only source. Zero is the honest placeholder: no cascade has been
5675 // fitted yet, and a gather recorded against it would scale by zero
5676 // rather than by a number nobody chose.
5677 cascade_reach: 0.0,
5678 // Nothing has been fitted before the first `begin_frame`.
5679 rsm_cull_ready: false,
5680 sun_color: Vec3::ZERO,
5681 shadow_draws: std::mem::take(&mut rollback.shadow_draws),
5682 shadow_uniforms,
5683 shadow_prepare_views: Vec::new(),
5684 shadow_prepare_culls: Vec::new(),
5685 shadow_groups,
5686 shadow_selection,
5687 shadow_lights: shadow::Selection::default(),
5688 // Nothing has drawn the atlas, so the first frame draws every group
5689 // whatever it is asked for — which is also what gives the image a
5690 // defined content before anything samples it. A record is never
5691 // empty, so the first frame's is a change and takes every id past
5692 // the zero below it.
5693 shadow_group_inputs: vec![Vec::new(); SHADOW_CULLS],
5694 shadow_group_id: vec![0; SHADOW_CULLS],
5695 shadow_group_writes: vec![0; SHADOW_CULLS],
5696 shadow_footprints: Vec::new(),
5697 shadow_dag_elements: std::collections::BTreeSet::new(),
5698 shadow_written: Vec::new(),
5699 shadow_moved: Vec::new(),
5700 shadow_pass_id: 0,
5701 shadow_pass_ran: Arc::new(AtomicU64::new(0)),
5702 shadow_pending: None,
5703 // A reach of zero, so every centre on the first frame is further
5704 // from what the image holds than the nothing it holds reaches —
5705 // which is the reset that frame should be.
5706 shadow_group_held: vec![(0, Vec3::ZERO, 0.0); SHADOW_CULLS],
5707 shadow_group_redrawn: vec![false; SHADOW_CULLS],
5708 shadow_atlas_layout: None,
5709 shadow_atlas_cached: false,
5710 shadow_cadence_reset: false,
5711 shadow_faces_redrawn: 0,
5712 shadow_cadence_request: None,
5713 shadow_atlas_clears: true,
5714 shadow_frame: 0,
5715 frame_skins: false,
5716 // [`FRAMES_IN_FLIGHT`], the number every other ring here is sized
5717 // by, so a slot has been through the whole loop before it is read.
5718 // `culls_clusters` rather than the device's feature bits: what
5719 // decides whether the cluster word is a count is whether *this
5720 // renderer* built an amplification stage.
5721 cull_stats: CullStatsRing::new(device, FRAMES_IN_FLIGHT, culls_clusters),
5722 tonemap_layout,
5723 tonemap_pipeline_layout,
5724 tonemap_pipeline,
5725 sampler,
5726 // The value `tonemap.slang`'s `EXPOSURE` constant held, so a
5727 // renderer nobody has called `set_exposure` on writes the frame it
5728 // wrote before the block existed.
5729 exposure: tonemap::DEFAULT_EXPOSURE,
5730 exposure_adaptation: None,
5731 // And the filmic roll-off over it: this renderer shades in linear
5732 // HDR, so a view that has asked for nothing gets the operator that
5733 // range was shaded for.
5734 tonemap_curve: tonemap::TonemapCurve::Aces,
5735 target_format,
5736 ambient_occlusion_placeholder,
5737 contact_shadow_placeholder,
5738 probe_visibility_placeholder,
5739 // Nothing has been captured, so every frame drawn before
5740 // `capture_probe_visibility` reads the placeholder and weighs every
5741 // probe at one — which is the frame this renderer drew before the
5742 // maps existed.
5743 probe_visibility: None,
5744 probe_occluders,
5745 specular_dfg,
5746 ltc_table,
5747 shadow_group_entries,
5748 // Off, and unbuilt: the grid is opt-in, so a caller that never asks
5749 // for one draws the frame it drew before this module existed.
5750 ground_grid: None,
5751 ground_grid_on: false,
5752 // Empty, and unbuilt: nothing has appended a segment, so this
5753 // renderer records the frame it recorded before the layer existed.
5754 debug_draw: DebugDraw::default(),
5755 atlas_viewer: rollback
5756 .atlas_viewer
5757 .take()
5758 .unwrap_or_else(|| unreachable!("the viewer was placed in the rollback above")),
5759 // Full resolution, which is the frame every caller of this type drew
5760 // before there was a knob — see [`Self::set_render_scale`].
5761 render_scale: 1.0,
5762 // The default stack the view wants, no quality clamp and no
5763 // override, which resolves to every effect this device permits but
5764 // the lens one — the frame every caller of this type drew before
5765 // there were toggles. See [`RenderEffects::DEFAULT_STACK`].
5766 effect_request: EffectRequest::default(),
5767 device_effects: RenderEffects::all(),
5768 frame_effects: RenderEffects::DEFAULT_STACK,
5769 // What the switch says today, so a renderer built and never opened
5770 // still describes the frame it would draw. `begin_frame` reads it
5771 // again for the frame it opens.
5772 frame_ssao_blurs: crate::ssao::blur_passes(),
5773 // No frame has been recorded yet, on `recorded_draws`' terms.
5774 recorded_fullscreen: 0,
5775 // No frame has been recorded yet, on `recorded_fullscreen`'s terms.
5776 recorded_debug_draw: 0,
5777 recorded_tile_clears: 0,
5778 // No bodies, so no pass: the frame every caller of this type drew
5779 // before water existed. Nothing is allocated until a body is set.
5780 water: WaterBodies::new(FRAMES_IN_FLIGHT),
5781 recorded_water_draws: 0,
5782 // No field, so no pass: the frame every caller of this type drew
5783 // before grass existed. The two calm wind layers are one texel
5784 // each and are what makes a field with no weather set still.
5785 grass: GrassScene::new(device, queue, FRAMES_IN_FLIGHT)?,
5786 wind: crcbl_shaders::wind::WindParams::default(),
5787 recorded_grass_draws: 0,
5788 })
5789 }
5790
5791 /// Builds a full-screen-triangle pipeline out of `shader`'s vertex and
5792 /// fragment entry points.
5793 ///
5794 /// One helper because every post pass in this crate wants the same
5795 /// pipeline — the tonemap's, `ssao`'s, `ssao-blur`'s, `ssr`'s and the rest —
5796 /// differing in the module, the layout and the target format alone. The
5797 /// tonemap's stays written out where it is: it is the one that carries the
5798 /// *why* of the shape, and this is the shape repeated.
5799 ///
5800 /// The module is destroyed before the pipeline result is unwrapped, so a
5801 /// failing creation leaks nothing.
5802 ///
5803 /// # Errors
5804 ///
5805 /// [`HalError`] from the manifest lookup, the module or the pipeline.
5806 fn build_fullscreen(
5807 device: &dyn Device,
5808 label: &str,
5809 shader: &crcbl_shaders::Shader,
5810 layout: PipelineLayoutHandle,
5811 color_targets: &[ColorTargetState],
5812 ) -> Result<GraphicsPipelineHandle, HalError> {
5813 Self::build_fullscreen_with(device, label, shader, layout, color_targets, None)
5814 }
5815
5816 /// [`Self::build_fullscreen`] for a pass that **depth-tests** what it draws
5817 /// against an attachment it does not write.
5818 ///
5819 /// The state is [`DepthStencilState::equal_depth_read_only`], whose
5820 /// [`CompareOp::GreaterOrEqual`] is the reversed-Z pair for "the fragment's
5821 /// depth must equal what is already there". One caller, [`crate::sky_pass`],
5822 /// which emits its triangle at the far plane so that the test selects
5823 /// exactly the pixels no geometry covered — see that module.
5824 ///
5825 /// # Errors
5826 ///
5827 /// [`HalError`] from the manifest lookup, the module or the pipeline.
5828 fn build_tested_fullscreen(
5829 device: &dyn Device,
5830 label: &str,
5831 shader: &crcbl_shaders::Shader,
5832 layout: PipelineLayoutHandle,
5833 color_targets: &[ColorTargetState],
5834 depth_format: Format,
5835 ) -> Result<GraphicsPipelineHandle, HalError> {
5836 Self::build_fullscreen_with(
5837 device,
5838 label,
5839 shader,
5840 layout,
5841 color_targets,
5842 Some(DepthStencilState::equal_depth_read_only(depth_format)),
5843 )
5844 }
5845
5846 /// The body of the two above, which differ in their depth state and in
5847 /// nothing else.
5848 ///
5849 /// # Errors
5850 ///
5851 /// [`HalError`] from the manifest lookup, the module or the pipeline.
5852 fn build_fullscreen_with(
5853 device: &dyn Device,
5854 label: &str,
5855 shader: &crcbl_shaders::Shader,
5856 layout: PipelineLayoutHandle,
5857 color_targets: &[ColorTargetState],
5858 depth_stencil: Option<DepthStencilState>,
5859 ) -> Result<GraphicsPipelineHandle, HalError> {
5860 let vertex = entry(shader, Stage::Vertex)?;
5861 let fragment = entry(shader, Stage::Fragment)?;
5862 let module = device.create_shader_module(&ShaderModuleDesc {
5863 label: Some(shader.source()),
5864 spirv: shader.spirv(),
5865 wgsl: shader.wgsl(),
5866 msl: shader.msl(),
5867 // A container per entry point, for the reason the mesh module gives.
5868 dxil: &shader.dxil_containers(),
5869 })?;
5870 let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5871 label: Some(label),
5872 layout,
5873 vertex: ShaderEntry {
5874 module,
5875 entry_point: vertex,
5876 },
5877 fragment: Some(ShaderEntry {
5878 module,
5879 entry_point: fragment,
5880 }),
5881 // The triangle is deliberately oversized, so two of its vertices are
5882 // outside the viewport and its winding is not worth reasoning about.
5883 primitive: PrimitiveState::default(),
5884 depth_stencil,
5885 multisample: MultisampleState::default(),
5886 color_targets,
5887 });
5888 device.destroy_shader_module(module);
5889 pipeline
5890 }
5891
5892 /// Builds a full-screen-triangle pipeline that writes a **depth**
5893 /// attachment and no colour one.
5894 ///
5895 /// [`Self::build_fullscreen`]'s shape with the two halves of that swapped:
5896 /// no colour target at all, and a depth state whose comparison always
5897 /// passes so every texel of the destination takes the value the fragment
5898 /// computed. The reversed-Z [`CompareOp::Greater`] every geometry pipeline
5899 /// in this file uses would be wrong here — this pass is not depth-testing
5900 /// anything, it is writing a reduction, and a test against the target's
5901 /// undefined contents would drop texels at random.
5902 ///
5903 /// Two callers, [`crate::hiz`] and [`crate::occlusion_cull`], and it stays
5904 /// a method rather than moving there because the module and the
5905 /// destroy-before-unwrap above are this file's, and both take it in exactly
5906 /// as `crate::ssao` takes the sibling.
5907 ///
5908 /// **The entry points are named**, unlike the sibling's: `hiz.slang` has a
5909 /// fragment stage per pyramid, and a stage looked up by kind would be
5910 /// ambiguous.
5911 ///
5912 /// # Errors
5913 ///
5914 /// [`HalError`] from the module or the pipeline.
5915 fn build_depth_fullscreen(
5916 device: &dyn Device,
5917 label: &str,
5918 shader: &crcbl_shaders::Shader,
5919 vertex: &str,
5920 fragment: &str,
5921 layout: PipelineLayoutHandle,
5922 format: Format,
5923 ) -> Result<GraphicsPipelineHandle, HalError> {
5924 let module = device.create_shader_module(&ShaderModuleDesc {
5925 label: Some(shader.source()),
5926 spirv: shader.spirv(),
5927 wgsl: shader.wgsl(),
5928 msl: shader.msl(),
5929 dxil: &shader.dxil_containers(),
5930 })?;
5931 let pipeline = device.create_graphics_pipeline(&GraphicsPipelineDesc {
5932 label: Some(label),
5933 layout,
5934 vertex: ShaderEntry {
5935 module,
5936 entry_point: vertex,
5937 },
5938 fragment: Some(ShaderEntry {
5939 module,
5940 entry_point: fragment,
5941 }),
5942 primitive: PrimitiveState::default(),
5943 depth_stencil: Some(DepthStencilState {
5944 format,
5945 depth_write: true,
5946 depth_compare: CompareOp::Always,
5947 stencil: None,
5948 bias: DepthBias::default(),
5949 }),
5950 multisample: MultisampleState::default(),
5951 color_targets: &[],
5952 });
5953 device.destroy_shader_module(module);
5954 pipeline
5955 }
5956
5957 /// Creates the geometry pool and makes every mesh of `scene` resident in it.
5958 ///
5959 /// Separate from [`ForwardRenderer::build`] because it is **self-cleaning**:
5960 /// the pool is not the rollback's until this has returned, so a failure
5961 /// between creating it and flushing the last upload releases it here.
5962 fn build_geometry(
5963 device: &dyn Device,
5964 queue: QueueHandle,
5965 scene: &SceneDesc<'_>,
5966 service: &mut dyn FnMut(),
5967 ) -> Result<(MeshPool, Vec<ResidentMesh>), HalError> {
5968 let mut pool = MeshPool::new(
5969 device,
5970 &MeshPoolDesc {
5971 label: Some("forward geometry"),
5972 vertex_capacity: scene.capacities.vertices,
5973 index_capacity: scene.capacities.indices,
5974 mesh_capacity: scene.capacities.meshes,
5975 },
5976 )?;
5977 match Self::residents(device, queue, &mut pool, scene, service) {
5978 Ok(residents) => Ok((pool, residents)),
5979 Err(error) => {
5980 pool.destroy(device);
5981 Err(error)
5982 }
5983 }
5984 }
5985
5986 /// Creates the material table and fills it with `scene`'s rows, returning it
5987 /// and the id of each.
5988 ///
5989 /// Self-cleaning for the same reason [`ForwardRenderer::build_geometry`] is:
5990 /// the table is not the rollback's until this has returned.
5991 fn build_materials(
5992 device: &dyn Device,
5993 scene: &SceneDesc<'_>,
5994 ) -> Result<(MaterialTable, Vec<u32>), HalError> {
5995 let mut materials = MaterialTable::new(
5996 device,
5997 &MaterialTableDesc {
5998 label: Some("forward"),
5999 capacity: scene.capacities.materials,
6000 },
6001 )?;
6002 match Self::material_rows(device, &mut materials, &scene.materials) {
6003 Ok(ids) => Ok((materials, ids)),
6004 Err(error) => {
6005 materials.destroy(device);
6006 Err(error)
6007 }
6008 }
6009 }
6010
6011 /// Inserts `rows` **in order** and returns the id of each.
6012 ///
6013 /// Split out of [`ForwardRenderer::build_materials`] only so the table can
6014 /// be released on a failure without the borrow that filling it takes, which
6015 /// is the same shape [`ForwardRenderer::residents`] has.
6016 ///
6017 /// **In order, because row 0 is not this function's to choose**: it is what
6018 /// [`mesh::GpuInstance::default`] names, so it is what an instance written
6019 /// without a material id shades with. Inserting a description's rows in any
6020 /// other order would move that row under every caller — see
6021 /// [`SceneDesc::materials`], which is where it is a caller's decision.
6022 fn material_rows(
6023 device: &dyn Device,
6024 materials: &mut MaterialTable,
6025 rows: &[mesh::GpuMaterial],
6026 ) -> Result<Vec<u32>, HalError> {
6027 let mut ids = Vec::with_capacity(rows.len());
6028 for row in rows {
6029 let handle = materials.insert(device, row)?;
6030 // The id is asked for rather than assumed, because the number an
6031 // instance carries is this one and nothing else knows it.
6032 ids.push(materials.index(handle).ok_or_else(|| {
6033 HalError::Backend(
6034 "a material inserted into an empty table did not resolve".to_string(),
6035 )
6036 })?);
6037 }
6038 Ok(ids)
6039 }
6040
6041 /// Uploads every mesh of `scene` and returns their mesh ids — **only** once
6042 /// the transfers have completed.
6043 ///
6044 /// The calls are §3.1's upload path in order: the copies are recorded and
6045 /// submitted against timeline values, [`MeshPool::flush`] is what makes those
6046 /// values pass, and [`MeshPool::mesh`] is what refuses to hand out a range
6047 /// before they have.
6048 ///
6049 /// **In description order**, which is what makes a mesh's table id a
6050 /// property of the description rather than of this loop — the second mesh
6051 /// uploaded is the pool's first resident at a non-zero base vertex, which is
6052 /// what the module docs call the one thing that can tell a working base
6053 /// vertex from a cancelled one.
6054 ///
6055 /// A DAG is **one upload per level**. Every level was decimated separately,
6056 /// so a coarser level's vertices are wherever the collapses put them and
6057 /// belong to no vertex of the level below — a DAG is several vertex ranges,
6058 /// and the pool suballocates in vertices, so several ranges means several
6059 /// uploads. Level 0 goes first, so every other level starts past it and the
6060 /// offsets a cluster carries are non-negative; that is checked rather than
6061 /// assumed, because the pool's free list makes no promise about where a mesh
6062 /// lands.
6063 fn residents(
6064 device: &dyn Device,
6065 queue: QueueHandle,
6066 pool: &mut MeshPool,
6067 scene: &SceneDesc<'_>,
6068 service: &mut dyn FnMut(),
6069 ) -> Result<Vec<ResidentMesh>, HalError> {
6070 let mut uploaded: Vec<Vec<crate::mesh_pool::MeshHandle>> =
6071 Vec::with_capacity(scene.meshes.len());
6072 for desc in &scene.meshes {
6073 match &desc.geometry {
6074 Geometry::Flat {
6075 vertices,
6076 indices,
6077 uv_range,
6078 flags,
6079 ..
6080 } => {
6081 uploaded.push(vec![pool.upload(
6082 device,
6083 queue,
6084 &MeshUpload {
6085 label: &desc.label,
6086 vertices,
6087 indices,
6088 uv_range: *uv_range,
6089 flags: *flags,
6090 },
6091 )?]);
6092 service();
6093 }
6094 Geometry::Dag {
6095 levels,
6096 dag,
6097 uv_range,
6098 flags,
6099 } => {
6100 let mut handles = Vec::with_capacity(levels.len());
6101 for (depth, (vertices, level)) in levels.iter().zip(&dag.levels).enumerate() {
6102 handles.push(pool.upload(
6103 device,
6104 queue,
6105 &MeshUpload {
6106 label: &format!("{} level {depth}", desc.label),
6107 vertices,
6108 indices: &level.indices(),
6109 // Level 0's range for every level, which is the
6110 // one the mesh path reads whichever level it
6111 // draws — see `Geometry::Dag::uv_range`.
6112 uv_range: *uv_range,
6113 // And the description's flags for every level,
6114 // for the same reason: the levels are one
6115 // surface, so a tangent frame either describes
6116 // all of them or none.
6117 flags: *flags,
6118 },
6119 )?);
6120 service();
6121 }
6122 uploaded.push(handles);
6123 }
6124 }
6125 }
6126
6127 pool.flush(device)?;
6128 service();
6129 // The table index is the only number that leaves here — where the
6130 // geometry actually is reaches the GPU through the mesh table, and the
6131 // draw arguments are built from that table by a shader. `MeshPool::mesh`
6132 // is still asked, because it is the call that refuses a mesh whose
6133 // upload has not completed, and an id for a mesh that is not there yet
6134 // would be a draw of nothing.
6135 let resolve = |handle| match (pool.mesh(handle), pool.table_index(handle)) {
6136 (Some(_), Some(id)) => Ok(id),
6137 _ => Err(MeshPoolError::NotResident { handle }),
6138 };
6139 let base_vertex = |handle| match pool.mesh(handle) {
6140 Some(range) => Ok(range.base_vertex),
6141 None => Err(MeshPoolError::NotResident { handle }),
6142 };
6143
6144 let mut residents = Vec::with_capacity(uploaded.len());
6145 for (desc, handles) in scene.meshes.iter().zip(&uploaded) {
6146 // **Relative to level 0's base**, because that is the base the
6147 // instance resolves through its mesh id and the one the stage adds
6148 // this on top of. A level that landed *below* level 0 would make the
6149 // sum wrap, so it is refused here rather than drawn as another
6150 // mesh's vertices. A flat mesh is one level and reads zero.
6151 let level_zero = base_vertex(handles[0])?;
6152 let mut vertex_bases = Vec::with_capacity(handles.len());
6153 for (depth, &handle) in handles.iter().enumerate() {
6154 let base = base_vertex(handle)?;
6155 vertex_bases.push(base.checked_sub(level_zero).ok_or_else(|| {
6156 HalError::InvalidDescriptor(format!(
6157 "{} level {depth} landed at vertex {base}, below level 0's \
6158 {level_zero}, so its clusters cannot name their own geometry",
6159 desc.label
6160 ))
6161 })?);
6162 }
6163 residents.push(ResidentMesh {
6164 levels: handles
6165 .iter()
6166 .map(|&handle| resolve(handle))
6167 .collect::<Result<_, _>>()?,
6168 vertex_bases,
6169 // Matched on the description rather than counted off `handles`,
6170 // so a DAG decimated to a single level is still refused: what
6171 // makes a mesh skinnable is that every draw of it reads one
6172 // vertex run, and that is a property of the geometry rather than
6173 // of how many levels it happened to arrive with.
6174 skinnable: matches!(desc.geometry, Geometry::Flat { .. }).then(|| handles[0]),
6175 });
6176 }
6177 Ok(residents)
6178 }
6179
6180 /// Rotates to the next frame's uniform buffer and instance buffer, writes
6181 /// this frame's camera and light into the first, and uploads whatever
6182 /// changed into the second.
6183 ///
6184 /// Must be called once per frame, before [`ForwardRenderer::add_passes`].
6185 /// Separate from `add_passes` because the write happens on the CPU and the
6186 /// passes are recorded on the GPU timeline: fusing them would hide the ring
6187 /// rotation inside a function whose name says nothing about it.
6188 ///
6189 /// **It moves nothing.** Every object's transform is the caller's, written
6190 /// through [`ForwardRenderer::set_instance`] whenever it changes, so the
6191 /// transfer this records is [`InstancePool::begin_frame`]'s delta and a
6192 /// frame in which nothing moved uploads no instance bytes at all. The
6193 /// sandbox's spinning cube is one 80-byte write a frame because the sandbox
6194 /// spins it; a still scene is free.
6195 ///
6196 /// It also writes this frame's **cull parameters** — the camera's frustum,
6197 /// extracted from the very same view-projection the uniform block carries,
6198 /// so the pass that decides what is on screen and the pass that draws it
6199 /// cannot be looking at two different cameras — and zeroes the counters the
6200 /// two compute passes only ever add to. See [`crate::draw_gen`] on why those
6201 /// zeroes come from the host.
6202 ///
6203 /// # Errors
6204 ///
6205 /// [`HalError`] if the uniform buffer, the instance buffer or any of the
6206 /// draw-generation buffers could not be written.
6207 pub fn begin_frame(
6208 &mut self,
6209 device: &dyn Device,
6210 camera: &Camera,
6211 light: &DirectionalLight,
6212 extent: (u32, u32),
6213 ) -> Result<(), HalError> {
6214 // The instance pool owns the ring, so its slot is the frame index the
6215 // uniform buffer and the bind group below are picked with.
6216 self.frame = self.instances.rotate();
6217 self.frame_skins = false;
6218 self.instances.flush(device)?;
6219 self.begin_frame_body(device, camera, light, extent)
6220 }
6221
6222 /// [`begin_frame`](Self::begin_frame) for a frame that **skins**: the same
6223 /// call with the skinning plan folded into it.
6224 ///
6225 /// It does four things in the one order that is correct, which is why it is
6226 /// a call and not a note in someone's docs:
6227 ///
6228 /// 1. rotates the instance ring, so the frame slot exists;
6229 /// 2. hands that slot and `ranges` to `skinning`, which validates them,
6230 /// uploads the palettes and **moves the ping-pong** — the only place the
6231 /// parity ever moves;
6232 /// 3. points every object placed by
6233 /// [`add_skinned_instance`](Self::add_skinned_instance) at the half of its
6234 /// region the parity now names;
6235 /// 4. uploads the instance delta, so those bases are the ones this frame
6236 /// draws.
6237 ///
6238 /// Do those three and four in the other order and the objects carry the
6239 /// previous frame's half — a character posed one frame late, every frame,
6240 /// with nothing to report it. A caller never sees a parity or a table id, and
6241 /// so cannot get that wrong.
6242 ///
6243 /// Build `ranges` with [`SkinnedMesh::skin_range`], one per reserved region
6244 /// this frame animates. A frame with **no** skinned object still calls this
6245 /// with an empty slice — see [`Skinning::begin_frame`], whose slot would
6246 /// otherwise re-dispatch whichever frame last used it.
6247 ///
6248 /// [`add_skinned_passes`](Self::add_skinned_passes) is the other half, and
6249 /// the one that orders the dispatch before the draws.
6250 ///
6251 /// # Errors
6252 ///
6253 /// Whatever [`Skinning::begin_frame`] refuses — a joint index past its
6254 /// palette, a binding count that is not the region's vertex count, more than
6255 /// the pass was built for — and [`SkinningError::Hal`] for anything the seam
6256 /// refused, this renderer's own uniform and instance writes included.
6257 ///
6258 /// # Panics
6259 ///
6260 /// If `skinning` was not built with at least [`FRAMES_IN_FLIGHT`] frames:
6261 /// its rings are indexed by this renderer's frame slot, and
6262 /// [`Skinning::begin_frame`] refuses a slot it has no buffers for.
6263 pub fn begin_skinned_frame(
6264 &mut self,
6265 device: &dyn Device,
6266 skinning: &mut Skinning,
6267 ranges: &[SkinRange<'_>],
6268 camera: &Camera,
6269 light: &DirectionalLight,
6270 extent: (u32, u32),
6271 ) -> Result<(), SkinningError> {
6272 self.frame = self.instances.rotate();
6273 // An empty plan dispatches nothing — see [`Skinning::begin_frame`] — so
6274 // it leaves the vertex pool where it was, and the shadow atlas with it.
6275 self.frame_skins = !ranges.is_empty();
6276 skinning.begin_frame(device, self.frame, ranges)?;
6277 self.point_skinned_instances(skinning.parity());
6278 self.instances.flush(device)?;
6279 self.begin_frame_body(device, camera, light, extent)?;
6280 Ok(())
6281 }
6282
6283 /// Whether this frame records the irradiance probes' two
6284 /// updater passes.
6285 ///
6286 /// The scene's own answer and the console's together: the volume decides
6287 /// whether the feature applies at all — see [`ProbeUpdate`], which is where
6288 /// the reason it is not an effect bit lives — and `r_probe_bounce` is the
6289 /// on/off pair a pricing run reads the two passes' cost off with everything
6290 /// else held still.
6291 ///
6292 /// **It is not the whole condition.** The map is cascade 0's own draws, so
6293 /// the pass is recorded only where that cascade is being drawn too — see
6294 /// `add_shadow_pass`, which is where the rest of it is.
6295 fn probe_update_runs(&self) -> bool {
6296 self.probe_update == ProbeUpdate::EveryFrame && rsm::enabled()
6297 }
6298
6299 /// The six side-plane sets a point light's face culls test, or `None` for
6300 /// a light that is not a point — or with the face culls switched off, which
6301 /// is one cull against the light's box drawn into all six faces.
6302 ///
6303 /// `faces` are the light's face matrices in face order, the ones its tiles
6304 /// render through.
6305 fn point_face_planes(&self, light: &Light, faces: &[Mat4]) -> Option<crate::cull::FacePlanes> {
6306 if !self.point_face_culls || !matches!(light, Light::Point(_)) {
6307 return None;
6308 }
6309 let matrices: [Mat4; shadow::POINT_FACES] = faces.try_into().ok()?;
6310 Some(crate::cull::face_planes(&matrices))
6311 }
6312
6313 /// Every punctual shadow face this frame draws into the punctual reflective
6314 /// shadow map, in the order the pass draws them and the producer table lists
6315 /// them.
6316 ///
6317 /// **One list for both halves of the updater**, and that is the point:
6318 /// `add_shadow_pass` sets a viewport from a face's
6319 /// [`tile`](PunctualFace::tile) and the gather reads that same rectangle out
6320 /// of the matching producer row, so a face the pass drew and a row the
6321 /// gather walked have to be the same face. Building the two from separate
6322 /// filters is two things that can drift, and the drift would be a light
6323 /// bouncing another light's map.
6324 ///
6325 /// **The occupied slots this frame redraws**, which is the same set
6326 /// `add_shadow_pass` gives the atlas: a face's transform is a shadow view's
6327 /// block and its draws are a shadow cull's, and
6328 /// [`Self::begin_frame_body`](Self::begin_frame) writes neither for a slot
6329 /// it is holding.
6330 ///
6331 /// # Every occupied tile, and no budget of its own
6332 ///
6333 /// The producers are exactly the atlas's occupied faces — up to
6334 /// [`shadow::LIGHT_SLOTS`] lights and [`shadow::LIGHT_TILES`] tiles between
6335 /// them — rather than the highest-ranked light or some smaller count.
6336 ///
6337 /// **Because the budget already exists and is spent.**
6338 /// [`shadow::Selection`] has ranked these lights by projected screen
6339 /// influence and handed out every tile there is; a second budget on top
6340 /// would rank the same lights again, differently, and produce a light that
6341 /// casts a shadow and lends no bounce. That is a difference no picture shows
6342 /// — the same argument [`Self::shadow_lights`] makes about a map's size —
6343 /// and it is the kind of quiet inconsistency the two halves of one light are
6344 /// worst placed to have.
6345 ///
6346 /// It is affordable at the extent that was chosen for it:
6347 /// `apps/lantern` lights seven faces, and
6348 /// [`PUNCTUAL_RSM_SIDE`](crcbl_shaders::probe_gather::PUNCTUAL_RSM_SIDE)
6349 /// carries the sweep that priced them.
6350 ///
6351 /// **Empty where shadows are off**, for that same reason — a punctual face
6352 /// *is* a shadow view. The sun's half is not, which is what
6353 /// `updater_drives_cascade_zero` exists for: switching shadows off keeps the
6354 /// sun's bounce and loses every punctual one, rather than switching the
6355 /// whole updater off with them.
6356 fn punctual_faces(&self) -> Vec<PunctualFace> {
6357 if !self.probe_update_runs() {
6358 return Vec::new();
6359 }
6360 // A frame with the shadows switched off draws no atlas, so no group of
6361 // it is *redrawn* — and `begin_frame_body`'s `updater_drives_cascade_zero`
6362 // branch has still written every one of these views and dispatched every
6363 // one of these culls, for this pass to draw through.
6364 let updater_drives = !self.frame_effects.contains(RenderEffects::SHADOWS);
6365 let mut faces = Vec::new();
6366 for (slot, held) in self.shadow_lights.slots().iter().enumerate() {
6367 let Some(held) = *held else {
6368 continue;
6369 };
6370 if !updater_drives && !self.shadow_group_redrawn[shadow_cull(slot)] {
6371 continue;
6372 }
6373 let Some(light) = self.extra_lights.get(held.light) else {
6374 continue;
6375 };
6376 // A spot draws face 0 alone and a point light all six, each through
6377 // its own matrix into its own tile — `shadow::tile_span` is the same
6378 // function `Selection` allocated the run with, so a face here and a
6379 // tile there cannot disagree about how many there are.
6380 for face in 0..shadow::tile_span(light) {
6381 let tile = rsm::punctual_tile(held.base + face);
6382 faces.push(PunctualFace {
6383 view: shadow_view(slot, face),
6384 cull: shadow_cull(slot),
6385 face,
6386 tile,
6387 producer: producer_row(light, tile),
6388 });
6389 }
6390 }
6391 faces
6392 }
6393
6394 /// Puts an object in the scene and returns the handle that names it.
6395 ///
6396 /// An instance in the pool **is** an object in the scene: the frame records
6397 /// a fixed number of draws and the cull pass decides which instances they
6398 /// walk, so adding one costs a slot in an array and not a command. It is
6399 /// drawn from the next [`ForwardRenderer::begin_frame`], which is what
6400 /// uploads it.
6401 ///
6402 /// # The index it lands at is not decoration
6403 ///
6404 /// `draw_gen.slang` keys topic 25's hysteresis state by the
6405 /// instance's **array index**, at `instance_index * group_stride`, and
6406 /// `mesh_cluster.slang`'s amplification stage reads the same address. So the
6407 /// record of which of a DAG's groups an object had expanded belongs to the
6408 /// *slot*, not to the object — and a slot that [`remove_instance`] freed is
6409 /// handed to the next `add_instance`, which inherits it. What that costs is
6410 /// one frame selected against a history that is not this object's, and the
6411 /// next frame's own judgement replaces it; it is never a wrong picture,
6412 /// because every group is judged afresh whatever the state said.
6413 ///
6414 /// That inheritance is inert while the scene holds **one** instance of a DAG
6415 /// mesh, which is every frame the engine has drawn so far — one instance's
6416 /// run has no previous occupant, and a flat mesh's
6417 /// [`MeshLevels`](level_select::MeshLevels) record names no groups at all, so
6418 /// nothing indexes the state for it. It stops being inert the moment an
6419 /// application places a second.
6420 ///
6421 /// [`remove_instance`]: ForwardRenderer::remove_instance
6422 ///
6423 /// # A DAG mesh needs a device that can choose a level
6424 ///
6425 /// One device shape cannot draw a [`Geometry::Dag`] mesh: a mesh stage with
6426 /// **no** amplification stage in front of it emits every cluster of the
6427 /// bucket, which for a DAG is every level at once — several overlapping
6428 /// copies of one surface. This does not refuse it, because it has no
6429 /// vocabulary for that refusal; a caller placing a DAG asks
6430 /// [`ForwardRenderer::selects_levels`] first, and places it only where that
6431 /// says yes. A flat mesh is unaffected on every path.
6432 ///
6433 /// # Errors
6434 ///
6435 /// [`InstancePoolError::PoolFull`] when the instance pool is full. It never
6436 /// grows — [`Capacities::instances`](crate::scene::Capacities::instances) is
6437 /// what a caller sizes it with.
6438 ///
6439 /// # Panics
6440 ///
6441 /// If [`InstanceDesc::mesh`] or [`InstanceDesc::material`] is past the end of
6442 /// the description this renderer was built from. Both are indices a caller
6443 /// wrote against a description it holds, so an out-of-range one is a mistake
6444 /// in the calling code rather than a condition the frame can be in — and the
6445 /// alternative is an object silently drawn as some other mesh, in some other
6446 /// colour.
6447 pub fn add_instance(
6448 &mut self,
6449 desc: &InstanceDesc,
6450 ) -> Result<InstanceHandle, InstancePoolError> {
6451 let instance = self.gpu_instance(desc);
6452 self.instances.insert(&instance)
6453 }
6454
6455 /// Rewrites the object `handle` names — its mesh, its material and its
6456 /// transform, all three.
6457 ///
6458 /// A stale handle — one [`ForwardRenderer::remove_instance`] retired — writes
6459 /// nothing, rather than overwriting whatever took its slot.
6460 ///
6461 /// Takes effect at the next [`ForwardRenderer::begin_frame`], which uploads
6462 /// the element and nothing else: an object that did not move costs no
6463 /// transfer at all.
6464 ///
6465 /// # Panics
6466 ///
6467 /// On [`ForwardRenderer::add_instance`]'s terms, for the same reason.
6468 pub fn set_instance(&mut self, handle: InstanceHandle, desc: &InstanceDesc) {
6469 let mut instance = self.gpu_instance(desc);
6470 instance.flags |= self.kept_flags(handle);
6471 self.instances.set(handle, &instance);
6472 }
6473
6474 /// The bits of `handle`'s record a rewrite of it keeps: its hidden views
6475 /// and whether it casts — see [`ForwardRenderer::set_instance_views`] and
6476 /// [`ForwardRenderer::set_instance_casts_shadow`]. Zero for a stale
6477 /// handle, whose rewrite writes nothing anyway.
6478 fn kept_flags(&self, handle: InstanceHandle) -> u32 {
6479 self.instances.get(handle).map_or(0, |record| {
6480 record.flags
6481 & (mesh::GpuInstance::HIDDEN_VIEWS_MASK | mesh::GpuInstance::CASTS_NO_SHADOW)
6482 })
6483 }
6484
6485 /// Sets whether `handle` casts a shadow. Every instance starts casting.
6486 ///
6487 /// **Every shadow map and nothing else**: an instance that casts none is
6488 /// rejected by the cull of the sun's cascades and of every shadowed light,
6489 /// on every geometry path, so it lands in no tile of the atlas — and in no
6490 /// reflective shadow map, which draws those same culls' survivors, so it
6491 /// bounces no light into the probes either. Every camera still draws it,
6492 /// and it still receives the shadows the rest of the scene casts.
6493 ///
6494 /// What a model drawn for an icon wants, placed where the scene's sun can
6495 /// see it: see [`ViewBackground::Transparent`] and
6496 /// [`set_instance_views`](Self::set_instance_views).
6497 ///
6498 /// A change redraws every shadow map whose cull the instance could be kept
6499 /// by, because it is a write [`InstancePool::take_written`] names. Not a
6500 /// move, on
6501 /// [`set_instance_views`](Self::set_instance_views)' terms, and a stale
6502 /// handle is ignored.
6503 pub fn set_instance_casts_shadow(&mut self, handle: InstanceHandle, casts: bool) {
6504 if let Some(record) = self.instances.get(handle) {
6505 let flags = if casts {
6506 record.flags & !mesh::GpuInstance::CASTS_NO_SHADOW
6507 } else {
6508 record.flags | mesh::GpuInstance::CASTS_NO_SHADOW
6509 };
6510 self.instances.set_flags(handle, flags);
6511 }
6512 }
6513
6514 /// Whether `handle` casts a shadow, or `None` for a stale handle.
6515 #[must_use]
6516 pub fn instance_casts_shadow(&self, handle: InstanceHandle) -> Option<bool> {
6517 self.instances
6518 .get(handle)
6519 .map(|record| record.flags & mesh::GpuInstance::CASTS_NO_SHADOW == 0)
6520 }
6521
6522 /// Takes the object `handle` names back out of the scene, freeing its slot.
6523 ///
6524 /// **A removal is a cleared live bit, not a skipped draw**, because the frame
6525 /// no longer records a draw per object: `cull.slang` asks whether an instance
6526 /// is live before it reads anything else, so removing an object and culling
6527 /// it off screen take the same path out of the frame. An instance left in the
6528 /// pool would be drawn wherever its transform put it.
6529 ///
6530 /// A stale handle removes nothing. Takes effect at the next
6531 /// [`ForwardRenderer::begin_frame`], on
6532 /// [`ForwardRenderer::set_instance`]'s terms.
6533 pub fn remove_instance(&mut self, handle: InstanceHandle) {
6534 self.instances.remove(handle);
6535 }
6536
6537 /// Captures a visibility map for every probe, from the static geometry
6538 /// standing in the scene right now.
6539 ///
6540 /// The probe visibility rung: each probe records how far
6541 /// away the nearest surface is in every direction, and `mesh.slang`'s
6542 /// `probe_irradiance` then weighs each of a fragment's eight probes by
6543 /// whether it can *see* that fragment — so a probe on the far side of a wall
6544 /// contributes nothing and a room stops lighting the room next door.
6545 /// This crate's own `probe_capture` module is the pass, `probe_visibility`
6546 /// is the geometry it draws, and [`crcbl_shaders::probe_visibility`] is the
6547 /// format.
6548 ///
6549 /// # Call it once, after the scene's walls are placed
6550 ///
6551 /// **A description carries no instances** — [`SceneDesc`] is meshes,
6552 /// materials, a page and the probe rows, and the objects arrive afterwards
6553 /// through [`ForwardRenderer::add_instance`] — so there is nothing for a
6554 /// capture inside [`ForwardRenderer::with_scene`] to be about. This is the
6555 /// call that has the room in it, and an application makes it once its static
6556 /// geometry is placed.
6557 ///
6558 /// A caller that never makes it draws exactly the frame this renderer drew
6559 /// before the maps existed: every group names the one-texel placeholder,
6560 /// which no surface is further away than, and every probe keeps all of its
6561 /// weight.
6562 ///
6563 /// **It is a capture of geometry and not a bake of light.** Nothing about
6564 /// the lights is recorded, every one of them still moves, and the rows the
6565 /// probes carry are untouched.
6566 ///
6567 /// # What it sees, and what it does not
6568 ///
6569 /// Every instance live in the pool when it is called, at the transform it
6570 /// then has, rasterised from its mesh's level-0 triangles into six 90°
6571 /// faces per probe. Objects that move
6572 /// afterwards keep the occlusion they had here, which is the accepted limit
6573 /// this technique has everywhere it is used — a probe volume is about the
6574 /// walls. Recapturing after a wall moves is this call again.
6575 ///
6576 /// **The device must be idle.** The previous capture's image is released
6577 /// here, and a frame in flight may still be reading it.
6578 ///
6579 /// # Errors
6580 ///
6581 /// [`HalError`] from the capture. The previous maps are kept on the failing
6582 /// path, so a renderer that has captured once and then failed goes on
6583 /// drawing with what it had.
6584 pub fn capture_probe_visibility(
6585 &mut self,
6586 device: &dyn Device,
6587 queue: QueueHandle,
6588 ) -> Result<(), HalError> {
6589 let placed: Vec<crate::probe_visibility::Occluder> = self
6590 .instances
6591 .live()
6592 .into_iter()
6593 .map(|record| crate::probe_visibility::Occluder {
6594 mesh: record.mesh,
6595 transform: Mat4::from_cols_array(&record.transform),
6596 })
6597 .collect();
6598 let Some(uploaded) = crate::probe_capture::capture(
6599 device,
6600 queue,
6601 &self.probe_volume,
6602 &self.probe_occluders,
6603 &placed,
6604 )?
6605 else {
6606 // No probes, or nothing placed for a map to be about. Leaving the
6607 // placeholder bound is the honest answer, and it is what a scene
6608 // with no probes has always read.
6609 return Ok(());
6610 };
6611 // The cached groups name the view this replaces, so they go before it
6612 // does — a bind group outliving the image it names is a validation
6613 // error on every backend that checks, and a use-after-free on the ones
6614 // that do not.
6615 for slot in &mut self.primary.screen_channel_groups {
6616 if let Some((_, stale)) = slot.take() {
6617 device.destroy_bind_group(stale);
6618 }
6619 }
6620 if let Some(previous) = self.probe_visibility.replace(uploaded) {
6621 previous.destroy(device);
6622 }
6623 Ok(())
6624 }
6625
6626 /// Re-centres the irradiance clipmap on `point` by whole probe steps, and
6627 /// captures the probes the step exposed.
6628 ///
6629 /// The irradiance probes' scrolling: each level moves a whole
6630 /// number of its own probe spacings towards `point`, so the probes that stay
6631 /// inside it stand exactly where they stood and go on being addressed at the
6632 /// rows they already had — and only the slabs the step brought in are
6633 /// captured. Answers how many rows that was, which is **zero for the
6634 /// ordinary frame**: the point has to travel half a probe spacing before the
6635 /// nearest whole step changes at all.
6636 ///
6637 /// [`ProbeVolume::follow`](crcbl_shaders::probe::ProbeVolume::follow) is the
6638 /// rule and `exposed` beside it is the invalidation; this is the two of them
6639 /// plus the device work they imply — the visibility maps of the exposed
6640 /// rows, and the position table the reflective-shadow-map gather reads.
6641 ///
6642 /// # A volume authored to cover its whole world does not move
6643 ///
6644 /// The steps are the ones that centre a level on `point`, and a caller whose
6645 /// volume is already the world it is in wants none of them — so a caller
6646 /// passes the point it wants the *centre* at rather than the camera outright
6647 /// when the two differ. `apps/lantern` and `apps/shard` are that case and
6648 /// their own modules say so.
6649 ///
6650 /// # A step stalls, and a frame that does not step costs a comparison
6651 ///
6652 /// The recapture is [`ForwardRenderer::capture_probe_visibility`]'s pass
6653 /// over fewer rows, and it waits on [`Device::wait_idle`] exactly as that
6654 /// one does — so a step drains the device before it rewrites anything and
6655 /// leaves it drained. That is a stall, and it is why the probe records price a step
6656 /// separately from a frame. A call that steps nothing returns before the
6657 /// wait, so the ordinary frame pays a rounding per level and per axis and
6658 /// nothing else.
6659 ///
6660 /// It may therefore be called from a frame loop, but **not after**
6661 /// [`ForwardRenderer::begin_frame`] has been called for the frame being
6662 /// recorded: the header it moves is the one that frame's uniform block has
6663 /// already been written from.
6664 ///
6665 /// A renderer that has never captured re-centres the header and captures
6666 /// nothing: there is no image to write slabs into, every group still names
6667 /// the placeholder, and the first
6668 /// [`ForwardRenderer::capture_probe_visibility`] covers the scrolled volume
6669 /// whole.
6670 ///
6671 /// # It moves the geometry and not the light
6672 ///
6673 /// What a step re-captures is the *visibility* of the probes it exposed,
6674 /// which is what the maps are about. The **rows** are not touched, so under
6675 /// [`ProbeUpdate::Authored`] a probe
6676 /// that a step brought in keeps the irradiance the probe that left had —
6677 /// authored for somewhere else. A volume that scrolls therefore wants
6678 /// [`ProbeUpdate::EveryFrame`], whose
6679 /// gather refills every row from the scene each frame and has no such gap;
6680 /// `docs/backlog.md` carries what an authored one would need instead.
6681 ///
6682 /// # Errors
6683 ///
6684 /// [`HalError`] from the recapture or from the position rewrite. The volume
6685 /// keeps the steps it had on either failing path, so a renderer that could
6686 /// not capture a slab does not go on drawing with rows about somewhere else.
6687 pub fn follow_probe_volume(
6688 &mut self,
6689 device: &dyn Device,
6690 queue: QueueHandle,
6691 point: [f32; 3],
6692 ) -> Result<u32, HalError> {
6693 let mut moved = self.probe_volume;
6694 let rows = moved.follow(point);
6695 if rows.is_empty() && moved.steps == self.probe_volume.steps {
6696 return Ok(0);
6697 }
6698 // **Before anything is written**, so a caller may make this call from
6699 // its frame loop: the layers the recapture rewrites and the position
6700 // table beside them are read by whatever frames are still in flight, and
6701 // neither is a ring. A frame that does not step never reaches this line,
6702 // which is what keeps the ordinary frame free of it.
6703 device.wait_idle()?;
6704 if let Some(captured) = &self.probe_visibility {
6705 let placed: Vec<crate::probe_visibility::Occluder> = self
6706 .instances
6707 .live()
6708 .into_iter()
6709 .map(|record| crate::probe_visibility::Occluder {
6710 mesh: record.mesh,
6711 transform: Mat4::from_cols_array(&record.transform),
6712 })
6713 .collect();
6714 crate::probe_capture::recapture(
6715 device,
6716 queue,
6717 &moved,
6718 &self.probe_occluders,
6719 &placed,
6720 &rows,
6721 captured.image,
6722 )?;
6723 }
6724 // After the capture, so a volume whose slabs could not be drawn keeps
6725 // the header its maps are about.
6726 if let Some(gather) = &self.probe_gather {
6727 gather.rewrite_positions(device, &moved)?;
6728 }
6729 self.probe_volume = moved;
6730 Ok(u32::try_from(rows.len()).unwrap_or(u32::MAX))
6731 }
6732
6733 /// Where the irradiance clipmap stands right now — the header the frame
6734 /// block carries, [`ForwardRenderer::follow_probe_volume`]'s scroll
6735 /// included.
6736 #[must_use]
6737 pub const fn probe_volume(&self) -> crcbl_shaders::probe::ProbeVolume {
6738 self.probe_volume
6739 }
6740
6741 /// `draws` split by the **whole** material mode, each partition under the
6742 /// depth-only pipeline that honours it — what the depth prepass and every
6743 /// shadow view record instead of one call list under one pipeline.
6744 ///
6745 /// Four pipelines for [`DEPTH_MODES`]' four values, which is what makes the
6746 /// split total: the opaque buckets are drawn with
6747 /// [`shadow_pipeline`](Self::shadow_pipeline) — `depthVertexMain` and no
6748 /// fragment stage — the masked ones with
6749 /// [`depth_masked_pipeline`](Self::depth_masked_pipeline), which can
6750 /// `discard`, and each of those has a [`CullMode::None`] twin for the
6751 /// buckets whose material is double-sided. A scene with one cutout in it
6752 /// pays a fragment stage for that mesh's draws and for no others; before
6753 /// this it paid for the whole frame, which on lavapipe roughly doubled the
6754 /// prepass and added two thirds to the shadow pass.
6755 ///
6756 /// **Both depth passes and not just the atlas.** A double-sided plate whose
6757 /// back face the prepass culled writes no depth there, so the colour pass's
6758 /// `GreaterOrEqual` test against it rejects the fragment and the surface is
6759 /// missing from the frame; and a cascade that culled it casts no shadow.
6760 fn depth_partitions(&self, draws: &BucketDraws) -> Vec<BucketDraws> {
6761 self.partitions(
6762 draws,
6763 mesh::GpuMaterial::MODE_MASK,
6764 &[
6765 (DEPTH_MODES[0], self.shadow_pipeline.single),
6766 (DEPTH_MODES[1], self.depth_masked_pipeline.single),
6767 (DEPTH_MODES[2], self.shadow_pipeline.double),
6768 (DEPTH_MODES[3], self.depth_masked_pipeline.double),
6769 ],
6770 )
6771 }
6772
6773 /// `draws` split by the material's **side** alone, each partition under the
6774 /// matching half of `pipelines` — what the colour pass and the two
6775 /// reflective shadow maps record.
6776 ///
6777 /// Two partitions where [`depth_partitions`](Self::depth_partitions) has
6778 /// four, and the difference is the whole of what these passes do not care
6779 /// about: their pipelines carry a fragment stage either way and cut the
6780 /// alpha mask inside it, so a masked bucket and an opaque one are the same
6781 /// draw here. What they cannot express inside the stage is the cull mode.
6782 fn sided_partitions(&self, draws: &BucketDraws, pipelines: SidedPipelines) -> Vec<BucketDraws> {
6783 self.partitions(
6784 draws,
6785 mesh::GpuMaterial::DOUBLE_SIDED,
6786 &[
6787 (0, pipelines.single),
6788 (mesh::GpuMaterial::DOUBLE_SIDED, pipelines.double),
6789 ],
6790 )
6791 }
6792
6793 /// Resolves a description's mesh and material indices into the table ids the
6794 /// GPU reads.
6795 ///
6796 /// The whole record every time, because [`InstancePool::set`] writes the
6797 /// whole record: an instance that lost either id would name entry 0 of that
6798 /// table, which is a mesh and a material rather than an absence.
6799 fn gpu_instance(&self, desc: &InstanceDesc) -> mesh::GpuInstance {
6800 mesh::GpuInstance {
6801 transform: desc.transform.to_cols_array(),
6802 mesh: self.mesh_ids[desc.mesh],
6803 material: self.material_ids[desc.material],
6804 flags: self.material_mode_bits(desc.material),
6805 ..mesh::GpuInstance::default()
6806 }
6807 }
6808
6809 /// The material mode of description material `material`, in the bits an
6810 /// instance record carries it in.
6811 ///
6812 /// **Read out of the table rather than out of the description**, because the
6813 /// table is what a `set` would move and the row is what the shader shades
6814 /// through. It is the other half of the record's routing key: `draw_gen`
6815 /// buckets an instance by [`mesh`](mesh::GpuInstance::mesh) and by this,
6816 /// which is how a masked material costs a fragment stage in the depth passes
6817 /// for its own mesh alone.
6818 ///
6819 /// The mode is captured **here**, when the record is written — see
6820 /// [`GpuInstance::MATERIAL_MODE_SHIFT`](mesh::GpuInstance::MATERIAL_MODE_SHIFT)
6821 /// for what that means for a material rewritten afterwards.
6822 fn material_mode_bits(&self, material: usize) -> u32 {
6823 self.materials.mode(self.material_ids[material]) << mesh::GpuInstance::MATERIAL_MODE_SHIFT
6824 }
6825
6826 // --- skinning: reserving the region, placing the object, ordering the
6827 // dispatch ---
6828
6829 /// The vertex pool every mesh here is resident in — what
6830 /// [`SkinningDesc::vertices`](crate::skinning::SkinningDesc::vertices)
6831 /// takes.
6832 ///
6833 /// The skinning pass reads a bind pose out of this buffer and writes the
6834 /// deformed vertices back into another run of it, which is what makes a
6835 /// skinned draw an ordinary draw. It must be *this* pool's buffer: a
6836 /// [`Skinning`] built against any other writes vertices no draw here can
6837 /// reach.
6838 #[must_use]
6839 pub const fn vertex_buffer(&self) -> BufferHandle {
6840 self.pool.vertex_buffer()
6841 }
6842
6843 /// Where that pool's **attribute** region begins, in words — what
6844 /// [`SkinningDesc::attribute_base`](crate::skinning::SkinningDesc::attribute_base)
6845 /// takes.
6846 ///
6847 /// The buffer holds two streams, so a pass that writes it needs the
6848 /// boundary as well as the handle; a [`Skinning`] built with the wrong one
6849 /// writes a mesh's attributes over another mesh's positions. See
6850 /// [`MeshPool::attribute_base`](crate::MeshPool::attribute_base).
6851 #[must_use]
6852 pub const fn attribute_base(&self) -> u32 {
6853 self.pool.attribute_base()
6854 }
6855
6856 /// Reserves a skinned region for description mesh `mesh`.
6857 ///
6858 /// The whole of what a caller needs to skin something, in one value: hand
6859 /// [`SkinnedMesh::skin_range`] a palette and a set of bindings to get the
6860 /// frame's [`SkinRange`], hand the result to
6861 /// [`begin_skinned_frame`](Self::begin_skinned_frame), and place it with
6862 /// [`add_skinned_instance`](Self::add_skinned_instance). The bases and the
6863 /// parity never have to be spelled by the caller at all — see
6864 /// [`crate::skinning::SkinnedMesh`], where the ping-pong lives.
6865 ///
6866 /// **The mesh keeps its own entry and the region takes none**, so the same
6867 /// description mesh can be drawn skinned through this and in its bind pose
6868 /// through [`add_instance`](Self::add_instance) in the same frame, both
6869 /// resolving through the one table entry it already had.
6870 ///
6871 /// Give it back with [`release_skinned`](Self::release_skinned).
6872 ///
6873 /// # Errors
6874 ///
6875 /// Whatever [`SkinnedMesh::reserve`] refuses: a vertex pool with no room for
6876 /// both halves. **Two vertex runs per skinned primitive** is what a scene's
6877 /// [`Capacities`](crate::scene::Capacities) has to have been sized for.
6878 ///
6879 /// # Panics
6880 ///
6881 /// If `mesh` is past the end of the description this renderer was built
6882 /// from, on [`add_instance`](Self::add_instance)'s terms — and if it names a
6883 /// [`Geometry::Dag`], which cannot be drawn out of a skinned region at all.
6884 /// A DAG is refused rather than skinned wrongly: its coarser levels are
6885 /// separate vertex runs no dispatch writes, so a cut that descended past
6886 /// level 0 would draw whatever the pool happened to be holding there.
6887 pub fn reserve_skinned(&mut self, mesh: usize) -> Result<SkinnedMesh, MeshPoolError> {
6888 let source = self.skinnable_meshes[mesh].unwrap_or_else(|| {
6889 panic!(
6890 "description mesh {mesh} is a Geometry::Dag, whose coarser levels are vertex \
6891 runs no skinning dispatch writes; only a flat mesh can be skinned"
6892 )
6893 });
6894 SkinnedMesh::reserve(&mut self.pool, source)
6895 }
6896
6897 /// Gives `skinned`'s region back to the vertex pool.
6898 ///
6899 /// The device must not still be drawing it: this records no barrier, on
6900 /// [`SkinnedMesh::release`]'s terms. Objects placed through it are **not**
6901 /// removed — [`remove_instance`](Self::remove_instance) is what does that,
6902 /// and an instance left behind goes on drawing its source mesh's geometry
6903 /// out of vertices the pool has handed back. Remove the objects first.
6904 pub fn release_skinned(&mut self, skinned: SkinnedMesh) {
6905 skinned.release(&mut self.pool);
6906 }
6907
6908 /// Places a skinned object in the scene.
6909 ///
6910 /// [`add_instance`](Self::add_instance) with a reserved region in place of a
6911 /// description mesh. The renderer keeps the object in a list of its own and
6912 /// **re-points it every [`begin_skinned_frame`](Self::begin_skinned_frame)**
6913 /// at the half of the region that frame's dispatch fills, so the parity is
6914 /// never something a caller writes.
6915 ///
6916 /// A skinned object driven by plain [`begin_frame`](Self::begin_frame) is
6917 /// therefore left pointing wherever it last was, which after the first frame
6918 /// is the pose of the frame before — the reason the two entry points are
6919 /// separate calls rather than a flag.
6920 ///
6921 /// # Errors
6922 ///
6923 /// [`InstancePoolError::PoolFull`], on
6924 /// [`add_instance`](Self::add_instance)'s terms.
6925 ///
6926 /// # Panics
6927 ///
6928 /// If [`SkinnedInstanceDesc::material`] is past the end of the description
6929 /// this renderer was built from, on
6930 /// [`add_instance`](Self::add_instance)'s terms.
6931 pub fn add_skinned_instance(
6932 &mut self,
6933 desc: &SkinnedInstanceDesc<'_>,
6934 ) -> Result<InstanceHandle, InstancePoolError> {
6935 // Parity zero, and it never reaches the GPU as such: the instance pool
6936 // uploads by delta at `begin_skinned_frame`, which re-points every entry
6937 // of the list below before it flushes. What this writes is the rest of
6938 // the record.
6939 let instance = self.skinned_gpu_instance(desc, 0);
6940 let handle = self.instances.insert(&instance)?;
6941 self.skinned_instances.push(SkinnedInstance {
6942 handle,
6943 bases: skinned_bases(desc.mesh),
6944 pointed: false,
6945 });
6946 Ok(handle)
6947 }
6948
6949 /// Rewrites the skinned object `handle` names — its region, its material and
6950 /// its transform.
6951 ///
6952 /// [`set_instance`](Self::set_instance) for an object placed by
6953 /// [`add_skinned_instance`](Self::add_skinned_instance), and the call a
6954 /// character's transform changes through. A stale handle writes nothing.
6955 ///
6956 /// Passing a handle this renderer has never seen skinned adopts it: the
6957 /// object joins the re-pointed list from here on. That is what lets a caller
6958 /// swap a bind-pose instance over to a region without removing and replacing
6959 /// it.
6960 ///
6961 /// # Panics
6962 ///
6963 /// On [`add_skinned_instance`](Self::add_skinned_instance)'s terms.
6964 pub fn set_skinned_instance(&mut self, handle: InstanceHandle, desc: &SkinnedInstanceDesc<'_>) {
6965 let mut instance = self.skinned_gpu_instance(desc, 0);
6966 instance.flags |= self.kept_flags(handle);
6967 if !self.instances.set(handle, &instance) {
6968 return;
6969 }
6970 let bases = skinned_bases(desc.mesh);
6971 match self
6972 .skinned_instances
6973 .iter_mut()
6974 .find(|entry| entry.handle == handle)
6975 {
6976 // **A different region is a fresh entry.** The half this object has
6977 // never been drawn out of holds whatever its reservation came with,
6978 // so the next pointing owes it rest rather than a previous
6979 // deformation — see [`SkinnedInstance::pointed`]. The pair of bases
6980 // is what "different" means here: two calls naming one region give
6981 // the same two runs, so rewriting an object's material or transform
6982 // is not a change of region.
6983 Some(entry) => {
6984 entry.pointed &= entry.bases == bases;
6985 entry.bases = bases;
6986 }
6987 None => self.skinned_instances.push(SkinnedInstance {
6988 handle,
6989 bases,
6990 pointed: false,
6991 }),
6992 }
6993 }
6994
6995 /// A skinned object's record, at one parity — [`gpu_instance`](Self::gpu_instance)
6996 /// with the region's base vertex carried in the record and the bit that says
6997 /// to read it.
6998 ///
6999 /// The mesh id is the **source** mesh's, not a second entry's, so the bucket
7000 /// this instance is scattered into, the levels it selects through and the
7001 /// box it is culled against are the ones the undeformed mesh already had.
7002 fn skinned_gpu_instance(
7003 &self,
7004 desc: &SkinnedInstanceDesc<'_>,
7005 parity: u32,
7006 ) -> mesh::GpuInstance {
7007 let base_vertex = desc.mesh.region().base(parity);
7008 mesh::GpuInstance {
7009 transform: desc.transform.to_cols_array(),
7010 mesh: desc.mesh.mesh_id(),
7011 material: self.material_ids[desc.material],
7012 // The override bit **and** the material mode: a skinned instance is
7013 // routed by the same key as a rigid one, so a skinned cutout lands
7014 // in its mesh's masked bucket rather than in the opaque twin.
7015 flags: mesh::GpuInstance::BASE_VERTEX_OVERRIDE | self.material_mode_bits(desc.material),
7016 base_vertex,
7017 // At rest, which is what a record this call writes has to be: the
7018 // object has not been drawn out of this region yet, so the other
7019 // half holds whatever its reservation came with. A frame that runs
7020 // [`point_skinned_instances`](Self::point_skinned_instances) is
7021 // what starts pointing this at the half before.
7022 previous_base_vertex: base_vertex,
7023 ..mesh::GpuInstance::default()
7024 }
7025 }
7026
7027 /// Points every skinned object at the half of its region a frame of this
7028 /// parity fills **and at the half the frame before it filled**, and forgets
7029 /// the ones whose instance has gone.
7030 ///
7031 /// Called between the instance ring's rotation and its upload, which is the
7032 /// whole reason those two are separate calls — see
7033 /// [`InstancePool::rotate`](crate::instance_pool::InstancePool::rotate).
7034 ///
7035 /// The second base is what a skinned fragment's motion vector is subtracted
7036 /// against — see
7037 /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
7038 /// **A region this frame's `ranges` left out was not skinned this frame**,
7039 /// so the half this points at as the current one already holds an earlier
7040 /// frame's pose. That is pre-existing — it is what a caller driving a
7041 /// skinned object through plain [`begin_frame`](Self::begin_frame) gets, and
7042 /// it predates this second base — and the previous half is then no worse off
7043 /// than the current one.
7044 fn point_skinned_instances(&mut self, parity: u32) {
7045 let Self {
7046 instances,
7047 skinned_instances,
7048 ..
7049 } = self;
7050 skinned_instances.retain_mut(|entry| {
7051 // `SkinnedRegion::base`'s indexing and `SkinnedRegion::previous_base`'s,
7052 // applied to the entry's own copy of the pair — see
7053 // [`SkinnedInstance::bases`].
7054 let base_vertex = entry.bases[(parity & 1) as usize];
7055 let previous_base_vertex = if entry.pointed {
7056 entry.bases[((parity ^ 1) & 1) as usize]
7057 } else {
7058 // Nothing has been written into the other half for this object,
7059 // so it is put at rest — see [`SkinnedInstance::pointed`].
7060 base_vertex
7061 };
7062 entry.pointed = true;
7063 // The two bases and nothing else: the transform, the material and
7064 // the mesh the caller last set survive, and so does the transform
7065 // the record moved *from* — which
7066 // [`InstancePool::set`](crate::instance_pool::InstancePool::set)
7067 // would overwrite with this frame's, leaving a skinned object's own
7068 // travel out of the motion target. See
7069 // [`InstancePool::set_bases`](crate::instance_pool::InstancePool::set_bases).
7070 // Its answer is also what says the instance is still there, so an
7071 // object a caller removed drops out of the list here.
7072 instances.set_bases(entry.handle, base_vertex, previous_base_vertex)
7073 });
7074 }
7075
7076 /// The lights in the frame **beside the sun**, which
7077 /// [`begin_frame`](Self::begin_frame) still takes on its own.
7078 ///
7079 /// Topic 44's light list, minus its first row: the
7080 /// sun is row 0 of every frame's list and the ones set here follow it, in
7081 /// the order given. That order is the one a froxel keeps a prefix of when it
7082 /// runs out of budget — see [`ForwardRenderer::light_capacity`] and the
7083 /// overflow counter beside it — so it is a caller's lever and not an
7084 /// accident.
7085 ///
7086 /// The sun keeps a parameter of its own because it is the light that owns
7087 /// the ambient term and the shadow cascades, neither of which a [`Light`]
7088 /// has. What it stopped being is a special case in the *shader*, which is
7089 /// what the list bought.
7090 ///
7091 /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7092 /// what uploads the rows.
7093 ///
7094 /// # Panics
7095 ///
7096 /// If there are more lights than [`ForwardRenderer::light_capacity`] leaves
7097 /// room for once the sun has its row. Refused rather than truncated: a light
7098 /// missing from the list is missing from every froxel, and **no counter in
7099 /// the frame would report it** — the overflow counter counts what a froxel's
7100 /// budget refused, which is a different number.
7101 pub fn set_lights(&mut self, lights: &[Light]) {
7102 assert!(
7103 lights.len() < self.primary.lights.capacity() as usize,
7104 "{} lights beside the sun, in a list of {}",
7105 lights.len(),
7106 self.primary.lights.capacity()
7107 );
7108 self.extra_lights.clear();
7109 self.extra_lights.extend_from_slice(lights);
7110 }
7111
7112 /// Rows the light list holds, the sun's included.
7113 #[must_use]
7114 pub const fn light_capacity(&self) -> u32 {
7115 self.primary.lights.capacity()
7116 }
7117
7118 /// This frame's froxel grid, as [`begin_frame`](Self::begin_frame) sized it
7119 /// from the viewport and the camera.
7120 ///
7121 /// Exposed for the reason [`lod_params`](Self::lod_params) is: a test that
7122 /// wants to know which froxel a point was shaded out of has to use the grid
7123 /// the frame really used, and re-deriving it would be a second copy of the
7124 /// arithmetic rather than a reading of the first.
7125 #[must_use]
7126 pub const fn grid(&self) -> Grid {
7127 self.primary.grid
7128 }
7129
7130 /// `frame`'s froxel grid buffer, for a test copying out what the clustering
7131 /// pass decided.
7132 ///
7133 /// # Panics
7134 ///
7135 /// If `frame` is not a slot this was built with.
7136 #[must_use]
7137 pub fn light_grid_buffer(&self, frame: usize) -> BufferHandle {
7138 self.primary.lights.grid(frame)
7139 }
7140
7141 /// The pixel budget the descent compares a group's projected error against.
7142 ///
7143 /// One pixel until this is called — see the constant this crate keeps it
7144 /// in. Larger is coarser: a group
7145 /// projecting *over* the budget is expanded and its children are drawn, so
7146 /// raising it stops the descent higher up the DAG.
7147 ///
7148 /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7149 /// what writes it into the frame block.
7150 pub const fn set_lod_error_budget(&mut self, budget: f32) {
7151 self.lod_error_budget = budget;
7152 }
7153
7154 /// The budget this renderer selects under unless
7155 /// [`set_lod_error_budget`](Self::set_lod_error_budget) says otherwise, and
7156 /// the ratio the hold budget sits at below whichever one is in force.
7157 ///
7158 /// Public because a test that drives a camera across a level boundary has to
7159 /// know where the boundary is, and where it is depends on both numbers —
7160 /// re-deriving either in the test would be a second copy to drift.
7161 pub const LOD_ERROR_BUDGET: f32 = LOD_ERROR_BUDGET;
7162 /// See [`LOD_ERROR_BUDGET`](Self::LOD_ERROR_BUDGET).
7163 pub const LOD_HOLD_RATIO: f32 = LOD_HOLD_RATIO;
7164
7165 /// How far below the budget an already-expanded group is held before it
7166 /// collapses again — topic 25's hysteresis, as a fraction of
7167 /// the budget.
7168 ///
7169 /// [`LOD_HOLD_RATIO`](Self::LOD_HOLD_RATIO) until this is called. **A ratio
7170 /// of one removes the band**, which makes the two budgets equal and the
7171 /// previous frame's answer stop mattering — the setting a test uses to show
7172 /// that the band is what stops a drifting camera flickering, on the same
7173 /// code path and one number apart.
7174 ///
7175 /// Takes effect at the next [`begin_frame`](Self::begin_frame), which is
7176 /// what writes it into the two params blocks.
7177 pub const fn set_lod_hold_ratio(&mut self, ratio: f32) {
7178 self.lod_hold_ratio = ratio;
7179 }
7180
7181 /// What the last [`begin_frame`](Self::begin_frame) handed the descent:
7182 /// pixels per unit at one unit from the eye, and the pixel budget.
7183 ///
7184 /// Pixels per unit at one unit from the eye, the budget an unexpanded group
7185 /// starts expanding over, and the budget an expanded one is held down to.
7186 ///
7187 /// What `ClusterDag::expand` takes, so a caller reading
7188 /// [`cluster_selection`](Self::cluster_selection) back can run the same
7189 /// frames host-side rather than re-deriving the numbers from the camera and
7190 /// hoping they agree. `[0.0, 0.0, 0.0]` before the first frame.
7191 #[must_use]
7192 pub const fn lod_params(&self) -> [f32; 3] {
7193 self.primary.lod_params
7194 }
7195
7196 /// The same three numbers the **shadow cascades** selected under, which is
7197 /// [`lod_params`](Self::lod_params) with both budgets multiplied by
7198 /// [`SHADOW_LOD_BIAS`] — topic 25's shadow LOD bias, as the
7199 /// parameters it actually reaches the GPU as.
7200 ///
7201 /// The pixels-per-unit is the camera's, unchanged, because the cascades
7202 /// select from the camera's eye at the camera's scale; see
7203 /// [`begin_frame`](Self::begin_frame). `[0.0, 0.0, 0.0]` before the first
7204 /// frame.
7205 #[must_use]
7206 pub const fn shadow_lod_params(&self) -> [f32; 3] {
7207 self.shadow_lod_params
7208 }
7209
7210 /// Where description mesh `mesh`'s clusters are in the cluster pool — every
7211 /// level of it, as one run — or `None` off the mesh path, where there is no
7212 /// cluster pool at all.
7213 ///
7214 /// The base a reader adds a `(level, cluster)` to in order to index
7215 /// [`cluster_selection`](Self::cluster_selection): the levels are laid down
7216 /// finest first and contiguously, so level `d` cluster `c` is at
7217 /// `base + (clusters of levels below d) + c`. A flat mesh is one level, so
7218 /// its run is its clusters and `c` indexes it directly.
7219 ///
7220 /// # Panics
7221 ///
7222 /// If `mesh` is past the end of the description this renderer was built
7223 /// from, on [`add_instance`](Self::add_instance)'s terms.
7224 #[must_use]
7225 pub fn cluster_range(&self, mesh: usize) -> Option<ClusterRange> {
7226 (!self.mesh_clusters.is_empty()).then(|| self.mesh_clusters[mesh])
7227 }
7228
7229 /// The buffer `frame`'s amplification stage recorded its chosen cut into:
7230 /// one `u32` per resident cluster, `1` where the cluster was drawn.
7231 ///
7232 /// `None` where there is no amplification stage, which is every device that
7233 /// reports no [`Features::TASK_SHADER`] and every non-mesh geometry path.
7234 ///
7235 /// **This is topic 25's observable and nothing in the frame
7236 /// reads it.** A frame whose every cluster came from one level is a
7237 /// plausible picture and matches any golden blessed from it, so a golden
7238 /// cannot show per-cluster selection happening at all; this can. It is
7239 /// `TRANSFER_SRC`, and copying it out is the caller's to record.
7240 ///
7241 /// [`Features::TASK_SHADER`]: crcbl_hal::Features::TASK_SHADER
7242 #[must_use]
7243 pub fn cluster_selection(&self, frame: usize) -> Option<BufferHandle> {
7244 self.primary.cluster_selection.get(frame).copied()
7245 }
7246
7247 /// The same, for `cascade`'s shadow pass: the cut that cascade's
7248 /// amplification stage chose this frame.
7249 ///
7250 /// **The shadow LOD bias' observable.** A budget the cascades merely *were
7251 /// passed* is a parameter; the cut they reached under it is the behaviour,
7252 /// and this is the only thing that carries it out of a frame — the colour
7253 /// pass overwrites [`cluster_selection`](Self::cluster_selection) after the
7254 /// cascades have run. Indexed and read exactly as that buffer is, through
7255 /// [`cluster_range`](Self::cluster_range).
7256 ///
7257 /// `None` where there is no amplification stage, and where `cascade` is not
7258 /// one of [`shadow::CASCADES`].
7259 #[must_use]
7260 pub fn shadow_selection(&self, frame: usize, cascade: usize) -> Option<BufferHandle> {
7261 self.shadow_selection
7262 .get(frame)
7263 .and_then(|cascades| cascades.get(cascade))
7264 .copied()
7265 }
7266
7267 /// The buckets description mesh `mesh`'s levels draw through, finest first —
7268 /// element `d` is level `d`'s bucket, and it is empty on the mesh path.
7269 ///
7270 /// **This is the uniform cut's observable**, and it is the indirect
7271 /// arguments rather than a buffer of its own: `draw_gen.slang` scatters an
7272 /// instance into the bucket for the level it selected, so exactly one of
7273 /// these buckets comes out of a frame with a non-zero instance count and
7274 /// which one it is *is* the chosen level. A reader takes
7275 /// [`DrawGen::args_offset`](crate::draw_gen::DrawGen::args_offset) of each
7276 /// and looks at
7277 /// [`DrawIndexedArgs::instance_count`](crcbl_shaders::draw_gen::DrawIndexedArgs::instance_count).
7278 ///
7279 /// Empty on [`GeometryPath::MeshShader`], where a mesh is one bucket and the
7280 /// level is chosen per cluster instead — see
7281 /// [`cluster_selection`](Self::cluster_selection), which is that path's
7282 /// observable.
7283 ///
7284 /// **These are the buckets of the scene's first material mode** — `OPAQUE`
7285 /// in any scene that has an opaque material, since the table is every
7286 /// mesh's levels once per mode the scene holds, mode by mode in
7287 /// `DEPTH_MODES` order. An instance of another mode selects the same level
7288 /// and lands in that level's bucket in its own mode's run, which this does
7289 /// not name; every scene in this tree that reads this accessor is all
7290 /// opaque, so "exactly one of these has a non-zero instance count" holds for
7291 /// them as it always did.
7292 ///
7293 /// # Panics
7294 ///
7295 /// If `mesh` is past the end of the description this renderer was built
7296 /// from, on [`add_instance`](Self::add_instance)'s terms.
7297 #[must_use]
7298 pub fn level_buckets(&self, mesh: usize) -> &[u32] {
7299 if self.mesh_level_buckets.is_empty() {
7300 return &[];
7301 }
7302 &self.mesh_level_buckets[mesh]
7303 }
7304
7305 /// `frame`'s indirect draw arguments, [`crcbl_shaders::draw_gen::DRAW_ARGS_SIZE`]
7306 /// bytes per bucket — what a reader of
7307 /// [`level_buckets`](Self::level_buckets) copies out.
7308 ///
7309 /// # Panics
7310 ///
7311 /// If `frame` is not a slot this renderer was built with.
7312 #[must_use]
7313 pub fn draw_args(&self, frame: usize) -> BufferHandle {
7314 self.primary.draws.args(frame)
7315 }
7316
7317 /// `frame`'s survivor list for the primary camera and the culling
7318 /// statistics beside it — `cull.slang`'s entries, tags and all, in the first
7319 /// [`DrawGen::visible_capacity`](crate::DrawGen::visible_capacity) words of
7320 /// the first buffer, and their count in word
7321 /// [`INSTANCE_SURVIVOR_WORD`](crcbl_shaders::cull::INSTANCE_SURVIVOR_WORD)
7322 /// of the second — for a test holding the GPU's occlusion verdicts against
7323 /// [`crate::cull`]'s oracle. The first buffer holds the routes and runs
7324 /// behind the list; see [`crate::draw_gen`].
7325 ///
7326 /// # Panics
7327 ///
7328 /// If `frame` is not a slot this renderer was built with.
7329 #[must_use]
7330 pub fn camera_cull_buffers(&self, frame: usize) -> (BufferHandle, BufferHandle) {
7331 (
7332 self.primary.draws.visible(frame),
7333 self.primary.draws.visible_count(frame),
7334 )
7335 }
7336
7337 /// What the primary camera's cull reads, as the oracle in [`crate::cull`]
7338 /// takes it: every instance slot the pool has handed out, and the whole mesh
7339 /// table — both decoded from the host's own copies of what was uploaded.
7340 #[must_use]
7341 pub fn cull_records(&self) -> (Vec<mesh::GpuInstance>, Vec<mesh::GpuMesh>) {
7342 (self.instances.records(), self.pool.table_entries())
7343 }
7344
7345 /// The generator behind shadow cull `cull` — a cascade's below
7346 /// [`shadow::CASCADES`], a light slot's after —
7347 /// for a test reading back what a point light's face culls kept.
7348 ///
7349 /// # Panics
7350 ///
7351 /// If `cull` is not one of the renderer's shadow culls.
7352 #[must_use]
7353 pub fn shadow_generator(&self, cull: usize) -> &DrawGen {
7354 &self.shadow_draws[cull]
7355 }
7356
7357 /// The primary camera's farthest-depth pyramid — every level's image, view
7358 /// and extent, level 1 first — or empty before a frame culled by occlusion.
7359 ///
7360 /// For a test reading a level back: the images carry `TRANSFER_SRC` for
7361 /// exactly that, and they hold the last frame's early depth once that frame
7362 /// has finished.
7363 #[must_use]
7364 pub fn occlusion_pyramid(&self) -> Vec<(crcbl_hal::ImageHandle, ImageViewHandle, (u32, u32))> {
7365 self.primary.occlusion_pyramid.level_images()
7366 }
7367
7368 /// The most passes [`add_passes`](Self::add_passes) adds to one frame.
7369 ///
7370 /// [`DrawGen::MAX_PASSES`] per cull — the camera's, and one per shadow cull
7371 /// beside it — plus [`LightGrid::MAX_PASSES`] for the froxel grid and the
7372 /// passes that draw. **A ceiling, not a count**: a frame whose shadow slots
7373 /// are not all filled runs fewer culls, which is what makes a free tile
7374 /// free.
7375 ///
7376 /// Derived rather than written down, because a number written down is one
7377 /// that stops matching the frame the day a pass is added — which is exactly
7378 /// how the samples' hand-picked `8` came to time the first eight passes of a
7379 /// fourteen-pass frame. A caller sizing
7380 /// [`PassTimers`](crate::timing::PassTimers) wants
7381 /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES), which adds this to
7382 /// what the overlay renderers record.
7383 pub const MAX_PASSES: u32 = DrawGen::MAX_PASSES * (1 + SHADOW_CULLS as u32)
7384 + DrawGen::LATE_PASSES
7385 + LightGrid::MAX_PASSES
7386 + RENDER_PASSES;
7387
7388 /// Adds the forward and tonemap passes to `graph`, rendering into `target`,
7389 /// and returns the HDR scene target they went through.
7390 ///
7391 /// `target` is normally the imported swapchain image. Everything else — the
7392 /// HDR scene colour, the depth buffer, and every barrier between them — is
7393 /// the graph's.
7394 ///
7395 /// The returned [`ImageId`] is the `Rgba16Float` frame the tonemap read:
7396 /// the scene colour **with the screen-space reflections already added**, not
7397 /// the target the forward pass wrote. A caller that wants to add a pass of
7398 /// its own after the tonemap — a debug overlay, or a readback proving the
7399 /// HDR range is real — declares a read of it and the graph works out the
7400 /// transition, exactly as it does for the tonemap.
7401 ///
7402 /// The two are the same description and different images, which is the
7403 /// design's off-switch as data rather than as a branch: a frame with
7404 /// [`RenderEffects::REFLECTIONS`] off adds neither pass, returns the forward
7405 /// pass's own id, and is bit-identical.
7406 ///
7407 /// # Which passes this adds is [`effects`](Self::effects)
7408 ///
7409 /// Resolved by the [`begin_frame`](Self::begin_frame) that opened this frame
7410 /// and read here — see [`crate::effects`] for the four layers and for what
7411 /// each toggle removes. Every effect is on by default, which is the frame
7412 /// every caller drew before the toggles existed.
7413 ///
7414 /// A switched-off effect is **fewer passes and one different bound
7415 /// descriptor**, never a shader permutation: the shadow atlas keeps its
7416 /// reversed-Z clear and reads as fully lit, the occlusion binding falls back
7417 /// to the renderer's white 1×1, and the reflection pair simply is not there.
7418 ///
7419 /// # The ground grid comes last, and after the tonemap
7420 ///
7421 /// [`set_ground_grid`](Self::set_ground_grid) is what puts it in the frame,
7422 /// and it is off by default. When it is on, its pass is added **after** the
7423 /// tonemap and writes `target` rather than the HDR scene colour, depth-tested
7424 /// against the scene depth: the grid is reference chrome, and a grid drawn
7425 /// before the tonemap would be exposed and tonemapped like geometry, so its
7426 /// colour would move with how bright the scene is. See [`crate::grid`].
7427 ///
7428 /// # `pool` is where the shadow atlas's incoming state comes from
7429 ///
7430 /// It must be the same pool the caller is about to
7431 /// [`compile`](RenderGraph::compile) and
7432 /// [`execute`](crate::CompiledGraph::execute) against, because the atlas and
7433 /// its placeholder are imports this renderer owns across frames and the
7434 /// pool's ledger is the record of what the last executed graph left them in
7435 /// — [`TransientPool::imported_image_use`], with [`None`] read as
7436 /// [`ResourceState::Undefined`]. Reading it here rather than carrying a
7437 /// field of our own is what keeps the declaration and the audit
7438 /// ([`InitialClaim::Tracked`]) one answer instead of two that drift: a frame
7439 /// whose `compile` fails is a frame that never ran, and a field advanced at
7440 /// build time would already have moved on without it.
7441 pub fn add_passes<'a>(
7442 &'a mut self,
7443 graph: &mut RenderGraph<'a>,
7444 pool: &TransientPool,
7445 target: ImageId,
7446 extent: (u32, u32),
7447 ) -> ImageId {
7448 self.add_frame_passes(
7449 graph,
7450 pool,
7451 FrameTargets::primary(target, extent, None),
7452 |_, _| {},
7453 )
7454 }
7455
7456 /// [`add_passes`](Self::add_passes) for a frame that **skins**: the same
7457 /// frame with `skinning`'s dispatch in front of every pass that draws.
7458 ///
7459 /// # This takes the pass rather than its [`BufferId`], and that is the point
7460 ///
7461 /// [`Skinning::add_pass`] hands back the id of the vertex pool so that a
7462 /// mesh pass can declare a read of it and be ordered after the dispatch. The
7463 /// obvious seam is therefore an id parameter here — and it is the wrong one,
7464 /// because every way of getting it wrong is silent. A caller can pass the id
7465 /// of a *different* import, add the skinning pass after this one, or not add
7466 /// it at all, and in each case the graph orders nothing, the draws read the
7467 /// region before the compute write has been made visible, and what comes out
7468 /// is a mesh that flickers between two poses on hardware and looks perfect
7469 /// under a validation layer.
7470 ///
7471 /// So this takes the [`Skinning`] and **adds the pass itself**, first, with
7472 /// this renderer's own frame slot, and declares the read on the three passes
7473 /// that pull vertices out of the pool — the shadow atlas, the depth prepass
7474 /// and the forward pass. There is no order for a caller to get right,
7475 /// because there is only one call.
7476 ///
7477 /// A frame whose [`begin_skinned_frame`](Self::begin_skinned_frame) was
7478 /// handed no ranges adds no dispatch and no declarations, and is the frame
7479 /// [`add_passes`](Self::add_passes) would have built.
7480 ///
7481 /// # It records one pass more than [`MAX_PASSES`](Self::MAX_PASSES)
7482 ///
7483 /// That constant is the bound on [`add_passes`](Self::add_passes) and stays
7484 /// so; the skinning dispatch is [`Skinning::MAX_PASSES`], and
7485 /// [`MAX_TIMED_PASSES`](crate::timing::MAX_TIMED_PASSES) — what a caller
7486 /// sizes [`PassTimers`](crate::PassTimers) with — already sums the two.
7487 pub fn add_skinned_passes<'a>(
7488 &'a mut self,
7489 graph: &mut RenderGraph<'a>,
7490 pool: &TransientPool,
7491 target: ImageId,
7492 extent: (u32, u32),
7493 skinning: &Skinning,
7494 ) -> ImageId {
7495 self.add_frame_passes(
7496 graph,
7497 pool,
7498 FrameTargets::primary(target, extent, Some(skinning)),
7499 |_, _| {},
7500 )
7501 }
7502
7503 /// [`add_skinned_passes`](Self::add_skinned_passes) with one game-owned
7504 /// overlay inserted after the display-space frame is complete and before
7505 /// antialiasing or render-scale reconstruction.
7506 ///
7507 /// The callback receives the display target and its matching scene depth
7508 /// attachment at the internal render extent. It may add graph passes that
7509 /// sample `display` and attach `depth` read-only; it must leave both images
7510 /// in states its declarations name. The forward renderer continues with its
7511 /// existing resolve and upscale passes after the callback returns.
7512 pub fn add_skinned_passes_with_overlay<'a, F>(
7513 &'a mut self,
7514 graph: &mut RenderGraph<'a>,
7515 pool: &TransientPool,
7516 target: ImageId,
7517 extent: (u32, u32),
7518 skinning: &Skinning,
7519 overlay: F,
7520 ) -> ImageId
7521 where
7522 F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7523 {
7524 self.add_frame_passes(
7525 graph,
7526 pool,
7527 FrameTargets::primary(target, extent, Some(skinning)),
7528 overlay,
7529 )
7530 }
7531
7532 /// [`add_skinned_passes_with_overlay`](Self::add_skinned_passes_with_overlay)
7533 /// for a frame that also draws secondary views — see
7534 /// [`create_view`](Self::create_view).
7535 ///
7536 /// **The scene's passes are recorded once**: one skinning dispatch (where
7537 /// `skinning` is `Some`), one shadow atlas, one probe gather. Then each view
7538 /// in `views` records its own cull, clustering and frame into its own
7539 /// target, and the primary camera's frame into `target` comes last — so
7540 /// `overlay` may read a view's target, which is already drawn by then.
7541 ///
7542 /// Every view named must have been begun this frame by
7543 /// [`begin_view`](Self::begin_view).
7544 ///
7545 /// # Panics
7546 ///
7547 /// If a [`ViewTarget`] in [`FrameTargets::views`] names [`ViewId::PRIMARY`],
7548 /// a view this renderer did not build, a view not begun this frame, or a
7549 /// view twice.
7550 pub fn add_passes_with_views<'a, F>(
7551 &'a mut self,
7552 graph: &mut RenderGraph<'a>,
7553 pool: &TransientPool,
7554 frame: FrameTargets<'_>,
7555 overlay: F,
7556 ) -> ImageId
7557 where
7558 F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7559 {
7560 self.add_frame_passes(graph, pool, frame, overlay)
7561 }
7562
7563 /// The body of every `add_*passes` entry point, which differ in their
7564 /// arguments and in nothing else.
7565 fn add_frame_passes<'a, F>(
7566 &'a mut self,
7567 graph: &mut RenderGraph<'a>,
7568 pool: &TransientPool,
7569 frame: FrameTargets<'_>,
7570 overlay: F,
7571 ) -> ImageId
7572 where
7573 F: FnOnce(&mut RenderGraph<'a>, ForwardOverlayTargets),
7574 {
7575 let FrameTargets {
7576 target,
7577 extent,
7578 skinning,
7579 views,
7580 } = frame;
7581 // **From here down `extent` is the extent the frame is *drawn* at**,
7582 // which is the caller's at a render scale of `1.0` and smaller below it.
7583 // Every use of it in this function sizes a transient, and every one of
7584 // those transients belongs to the internal frame; `target` is the only
7585 // thing here at the caller's extent, and it is an id whose image already
7586 // knows how big it is. `begin_frame_body` shadows it the same way and
7587 // for the same reason, so the two halves of a frame cannot disagree.
7588 //
7589 // `upscaling` is derived from the two extents rather than from the scale
7590 // itself, which is what makes it exact: a target small enough that the
7591 // scaled extent rounds back onto it adds no pass, because there would be
7592 // nothing for the pass to do.
7593 let target_extent = extent;
7594 let extent = self.internal_extent(target_extent);
7595 let upscaling = extent != target_extent;
7596 let frame = self.frame;
7597 let instance_count = self.instances.slot_count();
7598 let emit = self.emit;
7599
7600 // Every secondary view the caller asked for, checked before anything of
7601 // theirs is recorded: a view that does not exist, or one nothing began
7602 // this frame, would draw out of blocks written for some other frame.
7603 let secondary: Vec<(ViewTarget, (u32, u32))> = views
7604 .iter()
7605 .map(|view| {
7606 assert!(
7607 view.view != ViewId::PRIMARY,
7608 "the primary camera draws into the target `add_passes_with_views` takes, \
7609 not into a `ViewTarget`"
7610 );
7611 let built = self
7612 .views
7613 .get(view.view.index() - 1)
7614 .and_then(Option::as_ref)
7615 .unwrap_or_else(|| panic!("{:?} is not a view this renderer built", view.view));
7616 assert_eq!(
7617 built.begun, self.frame_serial,
7618 "{:?} was not begun this frame; call `begin_view` after `begin_frame`",
7619 view.view
7620 );
7621 assert!(
7622 views.iter().filter(|other| other.view == view.view).count() == 1,
7623 "{:?} was named twice in one frame",
7624 view.view
7625 );
7626 (*view, self.view_extent(built.background, view.extent))
7627 })
7628 .collect();
7629
7630 // **The skinning dispatch, before anything else is added.** It imports
7631 // the vertex pool and hands back that node's id; every pass below that
7632 // pulls vertices declares a read of it, and the graph is what turns the
7633 // two declarations into the barrier between the compute write and the
7634 // draws. `None` is a frame with nothing to skin, which adds no pass and
7635 // declares nothing — see `Skinning::add_pass`.
7636 let skinned = skinning.and_then(|skinning| skinning.add_pass(graph, frame));
7637
7638 // The camera's cull dispatch and the draw-argument dispatch, and the
7639 // light clustering after them — before anything draws, and before the
7640 // shadow atlas, which is where they always ran. See [`View::add_cull`].
7641 let cull = self.primary.add_cull(graph, pool, frame, instance_count);
7642
7643 // Topic 25's record of each cascade's cut. Each is written by
7644 // exactly one mesh pass, so what the graph orders here is this frame's
7645 // write against the next frame's use of the same slot. Each arrives in
7646 // the state the previous frame left it in, which is the one declared as
7647 // final.
7648 let tile_selection: Vec<BufferId> = self
7649 .shadow_selection
7650 .get(self.frame)
7651 .into_iter()
7652 .flatten()
7653 .enumerate()
7654 .map(|(tile, &buffer)| {
7655 import_read_write(graph, &format!("shadow-selection-{tile}"), buffer)
7656 })
7657 .collect();
7658
7659 // **This frame's slot of the probe ring**, which is the buffer every
7660 // one of this frame's bind groups names — see [`crate::probe`] for why
7661 // there is more than one. Imported in `ShaderRead` and handed back in
7662 // it: the build's staging copy left it there and no pass in the frame
7663 // writes it yet.
7664 let probe_buffer = self.probes.buffer(frame);
7665 let probe_table = graph.import_buffer(
7666 "probes",
7667 ImportedBuffer {
7668 buffer: probe_buffer,
7669 initial: ResourceState::ShaderRead,
7670 final_state: ResourceState::ShaderRead,
7671 },
7672 );
7673
7674 // The occlusion placeholder, imported once and read by every pass whose
7675 // bind group names it: the shadow pass's views, the depth prepass's copy
7676 // of the camera's group, and — on a frame drawing without
7677 // `RenderEffects::AMBIENT_OCCLUSION` — the forward pass itself. It was
7678 // uploaded at build, so it is already in `ShaderRead` and the graph has
7679 // nothing to transition; declaring it is what keeps that true if a later
7680 // pass wants it in some other state.
7681 let occlusion_placeholder = graph.import_image(
7682 "ssao-placeholder",
7683 ImportedImage {
7684 image: self.ambient_occlusion_placeholder.image,
7685 view: self.ambient_occlusion_placeholder.view,
7686 format: Format::R8Unorm,
7687 extent: (1, 1),
7688 initial: ResourceState::ShaderRead,
7689 claim: InitialClaim::Tracked,
7690 final_state: ResourceState::ShaderRead,
7691 },
7692 );
7693
7694 // The contact-shadow placeholder, imported beside the occlusion one and
7695 // on its terms exactly: every group of the mesh layout names this
7696 // binding, and on a frame drawing without `RenderEffects::CONTACT_SHADOWS`
7697 // it is what the forward pass binds.
7698 let contact_placeholder = graph.import_image(
7699 "contact-shadows-placeholder",
7700 ImportedImage {
7701 image: self.contact_shadow_placeholder.image,
7702 view: self.contact_shadow_placeholder.view,
7703 format: Format::R8Unorm,
7704 extent: (1, 1),
7705 initial: ResourceState::ShaderRead,
7706 claim: InitialClaim::Tracked,
7707 final_state: ResourceState::ShaderRead,
7708 },
7709 );
7710
7711 // §3.2's base-colour page, in every bind group of `mesh_layout` and so
7712 // read by all three of the passes that draw geometry. Like the
7713 // placeholder above it is already in `ShaderRead` and the graph has
7714 // nothing to transition on a frame nothing writes it — **the
7715 // declaration is for the frames something does**. A caller that copies a
7716 // render-to-texture view into one of its layers imports the same handle,
7717 // gets this same id back (`RenderGraph::import_image`), and the graph
7718 // then has an edge to order its write against these reads. Without the
7719 // declaration there is no such edge: the page is bound out of a
7720 // descriptor the graph never hears about, and a copy scheduled anywhere
7721 // but the tail of the frame leaves it in `TransferDst` for the passes
7722 // that sample it.
7723 let base_color_page =
7724 graph.import_image(Self::BASE_COLOR_PAGE_LABEL, self.base_color_page_import());
7725 // §2's normal page beside it, declared for exactly the reason above: it
7726 // is in every group of `mesh_layout` too, so a caller copying into one
7727 // of its layers needs the same edge against these draws.
7728 let normal_page = graph.import_image(Self::NORMAL_PAGE_LABEL, self.normal_page_import());
7729 // §2's other two pages beside them, declared for exactly the same
7730 // reason: both are in every group of `mesh_layout`, so a caller copying
7731 // into one of their layers needs the same edge against these draws.
7732 let mro_page = graph.import_image(Self::MRO_PAGE_LABEL, self.mro_page_import());
7733 let emissive_page =
7734 graph.import_image(Self::EMISSIVE_PAGE_LABEL, self.emissive_page_import());
7735
7736 // What this frame draws, resolved by the `begin_frame` that opened it —
7737 // see [`crate::effects`]. Read once here so every conditional below is
7738 // about one value rather than about four reads of a field.
7739 let effects = self.frame_effects;
7740 // Read here for `effects`' reason and for one more: the passes below
7741 // borrow `self` field by field, and a `&self` method called between
7742 // them would borrow the whole of it.
7743 let draws_sky = self.draws_sky();
7744 // What the frame's water draws, or `None` for a frame with none — read
7745 // here for `draws_sky`'s reason, and the same value every view records
7746 // from.
7747 let water = self.water.frame(self.frame);
7748 // The same, for the grass field: read here for `draws_sky`'s reason,
7749 // and the same value every view records from.
7750 let grass = self.grass.frame();
7751 // Whether this frame ends by drawing the shadow atlas over itself — the
7752 // resolved view rather than the switch, so a caller who left the atlas
7753 // up and then asked for normals gets normals. Read here for
7754 // `draws_sky`'s reason exactly: `debug_view` takes `&self`.
7755 let draws_atlas_view = self.debug_view() == DebugView::ShadowAtlas;
7756
7757 let pages = MaterialPages {
7758 base_color: base_color_page,
7759 normal: normal_page,
7760 mro: mro_page,
7761 emissive: emissive_page,
7762 };
7763 let (shadow_atlas, shadow_draws, shadow_tile_clears, rsm_images) = self.add_shadow_pass(
7764 graph,
7765 pool,
7766 &tile_selection,
7767 ShadowReads {
7768 occlusion_placeholder,
7769 pages,
7770 skinned,
7771 probes: probe_table,
7772 },
7773 );
7774
7775 // The wireframe twin where a caller switched the view on, and `None`
7776 // everywhere else — see `set_wireframe`. Written on `ground_grid`'s
7777 // terms, and the `filter` is what keeps "switched on" from outrunning
7778 // "built": the field is only `Some` after a build that succeeded.
7779 //
7780 // The depth prepass below takes the depth-only pipeline and is untouched
7781 // by this, which is the half that makes a wireframe frame legible: the
7782 // occlusion pair still reads solid depth. **It is also what makes this
7783 // one variable rather than two**: the colour pass's depth attachment
7784 // branches on it as well, because a wireframe is not the geometry the
7785 // prepass drew — see `MeshModules::color_depth_stencil`.
7786 let wireframe = self.wireframe_pipeline.filter(|_| self.wireframe_on);
7787 let bucket_draws = BucketDraws {
7788 // Replaced per partition below, in both passes that draw this list —
7789 // see [`ForwardRenderer::sided_partitions`] and
7790 // [`ForwardRenderer::depth_partitions`]. The field is what the
7791 // partitions inherit everything else from.
7792 pipeline: self.mesh_pipeline.single,
7793 layout: self.mesh_pipeline_layout,
7794 indices: self.pool.index_buffer(),
7795 emit,
7796 calls: self
7797 .bucket_constants
7798 .iter()
7799 .enumerate()
7800 .map(|(bucket, constant_offset)| {
7801 let bucket = u32::try_from(bucket)
7802 .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
7803 (
7804 *constant_offset,
7805 self.primary.draws.args_offset(bucket),
7806 self.primary.draws.count_offset(bucket),
7807 self.primary.draws.mesh_args_offset(bucket),
7808 )
7809 })
7810 .collect(),
7811 region_step: self.region_step,
7812 // Packed per partition, where the partition's buckets are known.
7813 ranges: None,
7814 flat: None,
7815 };
7816
7817 // Every draw this frame records: the shadow pass's, one per bucket — or
7818 // per range of buckets, or per partition behind a task stage — in
7819 // **each** of the depth prepass and the forward pass, and one full-screen
7820 // triangle per full-screen pass. Assigned before the passes below borrow
7821 // the fields they need, so it is the count for the frame being built
7822 // rather than the one before it — and off this frame's resolved effects
7823 // rather than off a constant, so a switched-off effect's triangle is not
7824 // counted as submitted.
7825 //
7826 // The ground grid is added on top rather than folded into
7827 // `fullscreen_passes`: it is not a [`RenderEffects`] bit and is not
7828 // resolved by the toggle order — it is a caller's opt-in, off by
7829 // default — so what decides it is the field and not this frame's
7830 // effects.
7831 self.recorded_fullscreen = fullscreen_passes(effects, extent, upscaling, self.frame_ssao_blurs)
7832 + u64::from(self.ground_grid().is_some() && !draws_atlas_view)
7833 + if draws_sky { SkyPass::PASSES } else { 0 }
7834 // The composite on an atmosphere frame whose fog effect is off,
7835 // on the sky's terms: it is there for the air in front of the
7836 // scene, which the atmosphere decides and no effect bit does.
7837 // With the effect on, `fullscreen_passes` already counted it.
7838 + if self.primary.frame_aerial
7839 && !effects.contains(RenderEffects::VOLUMETRIC_FOG)
7840 {
7841 u64::from(Volumetric::COMPOSITE_PASSES)
7842 } else {
7843 0
7844 }
7845 // The water copy's triangle, on the sky's terms: content rather
7846 // than an effect bit, so the bodies decide it.
7847 + if water.is_some() { Water::FULLSCREEN_PASSES } else { 0 }
7848 // The atlas viewer, on the ground grid's terms: not an effect
7849 // bit and not resolved by the toggle order, so what decides it
7850 // is the debug view and not this frame's effects. It *replaces*
7851 // the tonemap `fullscreen_passes` counted and the grid above —
7852 // see `View::add_passes` — so its passes stand in for the one.
7853 + if draws_atlas_view {
7854 u64::from(AtlasView::PASSES) - 1
7855 } else {
7856 0
7857 };
7858 // The debug draw layer's own call, on the ground grid's terms: not an
7859 // effect bit, and decided by whether this frame's slot has a segment in
7860 // it. One direct draw of one instance covering every segment appended,
7861 // which is why it joins the full-screen triangles rather than the
7862 // indirect draws — `counters` counts both as submitted *and* drawn,
7863 // because the CPU knows what they cover.
7864 self.recorded_debug_draw = u64::from(self.debug_draw.records_pass(self.frame));
7865 // The shadow pass's tile resets, on the same terms: one over-sized
7866 // triangle of one instance per tile it redrew, and none at all on a
7867 // frame that cleared the whole attachment — see
7868 // [`MeshModules::depth_clear_pipeline`].
7869 self.recorded_tile_clears = shadow_tile_clears;
7870 // One indexed draw per body the frame's water holds.
7871 self.recorded_water_draws = water
7872 .as_ref()
7873 .map_or(0, |water: &WaterFrame| water.draws.len() as u64);
7874 // One indirect draw per tile slot the frame's field holds, per look it
7875 // draws.
7876 self.recorded_grass_draws = grass.as_ref().map_or(0, |grass: &GrassFrame| {
7877 u64::from(grass.slots) * u64::from(grass.draws_per_slot())
7878 });
7879 // The late depth prepass is a third list of calls, on a frame whose
7880 // camera culls in two phases.
7881 let camera_passes: u64 = if self.primary.draws.frame_mode(frame)
7882 == crcbl_shaders::draw_gen::DrawMode::Occlusion
7883 {
7884 3
7885 } else {
7886 2
7887 };
7888 let prepass_partitions = self.depth_partitions(&bucket_draws);
7889 // And the colour pass's own split, which is by **side** alone: its
7890 // pipeline has a fragment stage either way, so an alpha mask is nothing
7891 // it has to route around and a cull mode is. The wireframe twin pair
7892 // substitutes for the shaded one here exactly as the single pipeline
7893 // used to.
7894 let color_partitions =
7895 self.sided_partitions(&bucket_draws, wireframe.unwrap_or(self.mesh_pipeline));
7896 // Off the partitions the passes below record, because where a call
7897 // draws a range of buckets the two splits pack into different numbers
7898 // of ranges — see [`BucketDraws::call_count`].
7899 let calls = |partitions: &[BucketDraws]| -> u64 {
7900 partitions.iter().map(BucketDraws::call_count).sum()
7901 };
7902 self.recorded_draws = shadow_draws
7903 + (camera_passes - 1) * calls(&prepass_partitions)
7904 + calls(&color_partitions)
7905 + self.recorded_grass_draws
7906 + self.direct_draws();
7907
7908 // --- the probe gather ---
7909 //
7910 // The irradiance probes' updater, second half: the map
7911 // the pass above drew, read into every row of the table. **Here rather
7912 // than beside that pass** because the write is `&mut` — the group naming
7913 // the map's transient views is cached across frames, and a group naming a
7914 // transient cannot be built where the others are; see
7915 // [`crate::ssao::cached_group`].
7916 //
7917 // It is before the depth prepass and the forward pass, which is the
7918 // ordering that matters: both declare a read of these rows, so the graph
7919 // barriers this write against them.
7920 //
7921 // Which map layer a row is weighed against is the row's own index, so
7922 // the view is resolved exactly as the drawing passes resolve it — the
7923 // placeholder until `capture_probe_visibility` has run, and off entirely
7924 // where `r_probe_visibility` is off. A gather against the placeholder
7925 // occludes nothing, which is the honest answer for a scene that never
7926 // captured.
7927 let probe_visibility_view = match &self.probe_visibility {
7928 Some(captured) if crate::probe_visibility::enabled() => captured.view,
7929 _ => self.probe_visibility_placeholder.view,
7930 };
7931 let frame = self.frame;
7932 if let Some((gather, images)) = self.probe_gather.as_mut().zip(rsm_images) {
7933 gather.add_pass(graph, frame, images, probe_visibility_view, probe_table);
7934 }
7935
7936 let passes = FramePasses {
7937 slot: frame,
7938 emit,
7939 target_format: self.target_format,
7940 ssao_blurs: self.frame_ssao_blurs,
7941 draws_sky,
7942 water,
7943 grass,
7944 skinned,
7945 probe_buffer,
7946 probe_table,
7947 occlusion_placeholder,
7948 contact_placeholder,
7949 pages,
7950 shadow_atlas,
7951 probe_visibility: probe_visibility_view,
7952 mesh_layout: self.mesh_layout,
7953 wireframe,
7954 prepass_partitions,
7955 color_partitions,
7956 tonemap: TonemapPipeline {
7957 sampler: self.sampler,
7958 layout: self.tonemap_layout,
7959 pipeline_layout: self.tonemap_pipeline_layout,
7960 pipeline: self.tonemap_pipeline,
7961 },
7962 };
7963 // From here the frame is borrowed field by field, because every view's
7964 // passes hold its own caches for the life of the graph.
7965 let Self {
7966 primary,
7967 views: built,
7968 debug_draw,
7969 ground_grid,
7970 ground_grid_on,
7971 atlas_viewer,
7972 cull_stats,
7973 ..
7974 } = self;
7975
7976 // **Every secondary view before the primary camera's frame**, so a pass
7977 // the primary records — an overlay compositing a scope's picture onto
7978 // the lens it is seen through — reads a view that is already drawn. Each
7979 // records its whole frame straight through: its own cull, its own
7980 // clustering, and every pass the primary records after them, against the
7981 // atlas and the probe rows the scene passes above left behind.
7982 for (index, slot) in built.iter_mut().enumerate() {
7983 let Some((view_target, view_extent)) = secondary
7984 .iter()
7985 .find(|(view, _)| view.view.index() == index + 1)
7986 else {
7987 continue;
7988 };
7989 let view = slot
7990 .as_mut()
7991 .unwrap_or_else(|| unreachable!("checked against the built views above"));
7992 let view_cull = view.add_cull(graph, pool, frame, instance_count);
7993 view.add_passes(
7994 graph,
7995 &passes,
7996 view_cull,
7997 ViewOutput {
7998 target: view_target.target,
7999 target_extent: view_target.extent,
8000 extent: *view_extent,
8001 },
8002 Overlays::default(),
8003 |_, _| {},
8004 );
8005 }
8006
8007 // The statistics buffer's id, read before the cull moves into the pass
8008 // recording below: the copy that reads it is the frame's last pass.
8009 let stats_id = cull.generated.visible_count_id;
8010 let tonemapped = primary.add_passes(
8011 graph,
8012 &passes,
8013 cull,
8014 ViewOutput {
8015 target,
8016 target_extent,
8017 extent,
8018 },
8019 Overlays {
8020 debug_draw: Some(debug_draw),
8021 ground_grid: ground_grid.as_ref().filter(|_| *ground_grid_on),
8022 atlas_viewer: draws_atlas_view.then_some(atlas_viewer),
8023 },
8024 overlay,
8025 );
8026
8027 // **Last, and that is the point.** Three passes add to the statistics
8028 // buffer — the cull dispatch, the light grid's overflow counter and the
8029 // amplification stage inside the forward pass — so a copy scheduled any
8030 // earlier would take a total the frame had not finished writing. The
8031 // graph puts it in `TransferSrc` for this and back into the state the
8032 // next frame on this slot imports it in; there is not a barrier written
8033 // here.
8034 if let Some(stats) = cull_stats.as_mut() {
8035 stats.add_copy_pass(graph, stats_id);
8036 }
8037
8038 tonemapped
8039 }
8040
8041 /// Adds the cull dispatches and the depth-only pass that fill the shadow
8042 /// atlas, and returns the atlas as the graph knows it.
8043 ///
8044 /// Every tile is one viewport of one render pass. A pass per tile would be
8045 /// one clear of the same image and one more barrier per tile, and the graph
8046 /// would have to be told each of them only touches part of it — where one
8047 /// pass with a viewport per tile is what a shadow *atlas* is for in the first
8048 /// place.
8049 ///
8050 /// **Only the occupied tiles get a cull and a viewport.** The cascades
8051 /// always are; a light tile is occupied when
8052 /// [`shadow::Selection`] gave it to a light. A free one keeps the
8053 /// reversed-Z clear the pass wrote, which is `0.0` — "nothing stored, as far
8054 /// away as depth goes" — so anything that did sample it would come back
8055 /// fully lit rather than fully shadowed.
8056 ///
8057 /// # With [`RenderEffects::SHADOWS`] off, every tile is a free one
8058 ///
8059 /// That is the whole switch, and it is the same mechanism a free tile
8060 /// already had rather than a second one: no cull is dispatched and no
8061 /// viewport is drawn, the pass records its clear and nothing else, and every
8062 /// comparison against the atlas comes back fully lit. The pass itself stays
8063 /// on the frame that switches it off — it is what *writes* that clear, and a
8064 /// frame that skipped it would leave the atlas holding the last frame that
8065 /// did draw into it, or undefined memory on the first frame of all.
8066 ///
8067 /// # A cached atlas records nothing at all
8068 ///
8069 /// Topic 45's static-caching rung. When
8070 /// [`ForwardRenderer::shadow_atlas_cached`] says the image already holds
8071 /// what this frame would draw, this adds **no cull and no pass**: the atlas
8072 /// is imported so the passes that sample it have an edge to the resource,
8073 /// and it keeps the contents an earlier frame left in it. That is why the
8074 /// image is a persistent one with a tracked ledger entry rather than a
8075 /// transient — nothing else in the frame can alias it, so what it holds is
8076 /// what the last pass to write it wrote.
8077 ///
8078 /// # Per group, and what pays for the tiles it keeps
8079 ///
8080 /// Topic 45's cadence rung. A **group** — a cascade, or a
8081 /// light slot's whole run of tiles — is redrawn or held on its own, and
8082 /// [`ForwardRenderer::shadow_group_redrawn`] is what says which. A frame
8083 /// that holds nothing clears the whole attachment, which is the recording
8084 /// that shipped before the rung; a frame that holds something **loads** the
8085 /// attachment instead and resets each tile it redraws with
8086 /// [`MeshModules::depth_clear_pipeline`], which is the portable statement of
8087 /// a clear bounded to one tile.
8088 ///
8089 /// The attachment's own [`LoadOp::Clear`] cannot serve there: it covers
8090 /// every tile including the ones being kept, and the region-bounded
8091 /// alternatives are not portable — Metal's load action and WebGPU's
8092 /// `loadOp` have no render area to bound them, so a clear that covered part
8093 /// of the image on Vulkan and all of it on Metal would be a held tile that
8094 /// survives on one backend and is erased on another.
8095 fn add_shadow_pass(
8096 &self,
8097 graph: &mut RenderGraph<'_>,
8098 pool: &TransientPool,
8099 selection: &[BufferId],
8100 reads: ShadowReads,
8101 ) -> (ImageId, u64, u64, Option<RsmImages>) {
8102 let shadows = self.frame_effects.contains(RenderEffects::SHADOWS);
8103 let (atlas_width, atlas_height) = shadow::atlas_extent();
8104 let atlas = graph.import_image(
8105 "shadow-atlas",
8106 ImportedImage {
8107 image: self.shadow_atlas,
8108 view: self.shadow_atlas_view,
8109 format: Format::D32Float,
8110 extent: (atlas_width, atlas_height),
8111 // What the previous executed frame left it in — `Undefined` on
8112 // the first, which is what makes the graph give it a layout at
8113 // all.
8114 initial: imported_state(pool, self.shadow_atlas),
8115 // The renderer keeps this image across frames, so the pool's
8116 // ledger is the record of what happened to it and the line above
8117 // is that record read back rather than a second copy of it.
8118 claim: InitialClaim::Tracked,
8119 final_state: ResourceState::ShaderRead,
8120 },
8121 );
8122 // The cached frame's whole answer: the image above and nothing that
8123 // touches it. It is already in `ShaderRead` — the frame that drew it
8124 // handed it back that way — so the graph has no transition to make, and
8125 // the passes that sample it read the maps an earlier frame left there.
8126 if self.shadow_atlas_cached {
8127 // **And no reflective shadow map either**, which cannot happen while
8128 // the updater is on: `begin_frame` keeps cascade 0 off the hold in
8129 // exactly that case, so a frame reaching here has nothing to draw
8130 // the map from. See `probe_update_runs`.
8131 return (atlas, 0, 0, None);
8132 }
8133 let placeholder = graph.import_image(
8134 "shadow-placeholder",
8135 ImportedImage {
8136 image: self.shadow_placeholder,
8137 view: self.shadow_placeholder_view,
8138 format: Format::D32Float,
8139 extent: (1, 1),
8140 // **Its own ledger entry, not the atlas's.** The two move
8141 // together today — both are imported by this function on every
8142 // frame and both are handed back in `ShaderRead` — so one lookup
8143 // would answer both, and that is exactly the coincidence a
8144 // second declared state here stops depending on.
8145 initial: imported_state(pool, self.shadow_placeholder),
8146 claim: InitialClaim::Tracked,
8147 final_state: ResourceState::ShaderRead,
8148 },
8149 );
8150
8151 // Which light slots have a light this frame, resolved once: a slot's
8152 // cull is dispatched and its faces are drawn together or not at all, and
8153 // `begin_frame` filled that generator's parameters under exactly this
8154 // condition.
8155 //
8156 // **And only the ones this frame redraws**, since the cadence rung: a
8157 // held slot keeps the texels it has, so recording its cull and its
8158 // draws would be the same picture at the full price.
8159 let occupied: Vec<(usize, shadow::Assignment, &Light)> = self
8160 .shadow_lights
8161 .slots()
8162 .iter()
8163 .enumerate()
8164 .filter(|_| shadows)
8165 .filter(|(slot, _)| self.shadow_group_redrawn[shadow_cull(*slot)])
8166 .filter_map(|(slot, held)| {
8167 let held = (*held)?;
8168 Some((slot, held, self.extra_lights.get(held.light)?))
8169 })
8170 .collect();
8171
8172 // One cull dispatch per cascade and per occupied slot, before the pass
8173 // that draws from them — **not one per tile**, which is topic 18's
8174 // fourth decision: a point light's six faces draw one visible set.
8175 let cascades: Vec<usize> = if shadows {
8176 (0..shadow::CASCADES)
8177 .filter(|cascade| self.shadow_group_redrawn[*cascade])
8178 .collect()
8179 } else {
8180 Vec::new()
8181 };
8182 // **Cascade 0's cull, on a frame that is not drawing it into the
8183 // atlas.** `begin_frame` fits it whenever the updater is on, shadows or
8184 // no shadows — see `rsm_cull_ready` — so this is the case where the map
8185 // is drawn and the atlas keeps its clear. Chained **last**, because the
8186 // occupied slots' entries are indexed by `cascades.len() + index` a few
8187 // lines below and an insertion before them would hand a light's draws to
8188 // the wrong viewport.
8189 let rsm_only_cull = self.rsm_cull_ready && !cascades.contains(&0);
8190 // The punctual producer's faces, which are also the light slots'
8191 // atlas views — see `punctual_faces`, the one list both halves of the
8192 // updater walk.
8193 let punctual = self.punctual_faces();
8194 // And their culls on a frame that is not drawing the atlas, which
8195 // `occupied` is empty on for the same reason `cascades` is. Deduplicated
8196 // because a point light's six faces draw one visible set, and chained
8197 // **after** the entries `views` indexes positionally below.
8198 let punctual_only_culls: Vec<usize> = if shadows {
8199 Vec::new()
8200 } else {
8201 punctual
8202 .iter()
8203 .map(|face| face.cull)
8204 .collect::<std::collections::BTreeSet<_>>()
8205 .into_iter()
8206 .collect()
8207 };
8208 let generated: Vec<(usize, GeneratedDraws)> = cascades
8209 .iter()
8210 .copied()
8211 .chain(occupied.iter().map(|(slot, _, _)| shadow_cull(*slot)))
8212 .chain(rsm_only_cull.then_some(0))
8213 .chain(punctual_only_culls)
8214 .map(|cull| {
8215 (
8216 cull,
8217 self.shadow_draws[cull].add_passes(
8218 graph,
8219 self.frame,
8220 self.instances.slot_count(),
8221 ),
8222 )
8223 })
8224 .collect();
8225
8226 // What the pass body records, in order: which view's bind group, which
8227 // rectangle of the atlas its viewport covers, and which of the culls
8228 // above it draws from. Paired rather than positional, because the free
8229 // slots are missing from every one of these lists and a bare index into
8230 // one would hand a light's draws to the wrong viewport the moment one
8231 // slot is free and a later one is not.
8232 //
8233 // **The rectangle rather than the slot**, resolved here: the body runs
8234 // in a closure that outlives this borrow, and asking the selection for
8235 // it there would be a second reading of an allocation that has to be the
8236 // one the frame block was written from.
8237 //
8238 // **And which draw region of that cull**: region 0, every survivor, for
8239 // a cascade and a spot; and for a point light whose cull tagged its
8240 // casters by face, the region of the face being drawn — see
8241 // `set_point_face_culls`.
8242 let mut views: Vec<(usize, shadow::TileRect, usize, u32)> = cascades
8243 .iter()
8244 .enumerate()
8245 .map(|(position, cascade)| {
8246 (
8247 *cascade,
8248 self.shadow_lights.atlas_rect(*cascade),
8249 position,
8250 0,
8251 )
8252 })
8253 .collect();
8254 for (index, (slot, held, light)) in occupied.iter().enumerate() {
8255 // A spot draws face 0 alone; a point light draws all six, each
8256 // through its own matrix into its own tile. `shadow::tile_span` is
8257 // the same function `Selection` allocated the run with, so a face
8258 // here and a tile there cannot disagree about how many there are.
8259 let by_face = self.shadow_draws[shadow_cull(*slot)].frame_mode(self.frame)
8260 == crcbl_shaders::draw_gen::DrawMode::Faces;
8261 for face in 0..shadow::tile_span(light) {
8262 views.push((
8263 shadow_view(*slot, face),
8264 self.shadow_lights
8265 .atlas_rect(shadow::light_tile(held.base + face)),
8266 cascades.len() + index,
8267 face_region(by_face, face),
8268 ));
8269 }
8270 }
8271
8272 let mut pass = graph
8273 .add_render_pass("shadow")
8274 // **Stored, unlike the scene's depth.** This is the one depth buffer
8275 // in the engine that something downstream reads, which is what
8276 // `PassBuilder::clear_depth`'s docs said would need a `StoreOp` the
8277 // day a prepass existed.
8278 .depth(
8279 atlas,
8280 // **Loaded on a frame that is keeping a tile**, which is the
8281 // cadence rung's whole seam: a clear here covers the image, so
8282 // the tiles this frame *does* redraw are reset one at a time by
8283 // the pipeline below instead. A frame keeping nothing clears,
8284 // which is what shipped.
8285 if self.shadow_atlas_clears {
8286 LoadOp::Clear
8287 } else {
8288 LoadOp::Load
8289 },
8290 StoreOp::Store,
8291 crcbl_hal::ClearValue {
8292 depth: crcbl_hal::depth::CLEAR,
8293 ..crcbl_hal::ClearValue::default()
8294 },
8295 )
8296 // Declared so the graph gives it a shader-read layout: it is in
8297 // every cascade's bind group, standing in for the atlas this pass is
8298 // writing. See `ForwardRenderer::shadow_placeholder`.
8299 .read_image(placeholder)
8300 // Likewise, and it is in every one of those groups too — see
8301 // `ForwardRenderer::ambient_occlusion_placeholder`. Nothing samples
8302 // it here either: the depth-only pipeline has no fragment stage.
8303 .read_image(reads.occlusion_placeholder)
8304 // And §3.2's page, which `mesh_layout` names in every group — a
8305 // cascade's included. See `ForwardRenderer::base_color_page_import`
8306 // for what the declaration buys a caller that writes the page.
8307 .read_image(reads.pages.base_color)
8308 // And §2's other three pages beside it, in those same groups and
8309 // sampled by no cascade — see
8310 // `ForwardRenderer::normal_page_import`.
8311 .read_image(reads.pages.normal)
8312 .read_image(reads.pages.mro)
8313 .read_image(reads.pages.emissive)
8314 // And the probe rows, which are in those groups too and which no
8315 // cascade reads — declared on the placeholder's and the pages'
8316 // terms, plus one of their own: the rows are device-local and a copy
8317 // destination so the irradiance probes' gather can
8318 // write them, and a pass that binds a buffer it has not declared is
8319 // one the graph cannot order that write against.
8320 .read_buffer(reads.probes);
8321 // Each tile's mesh pass records the cut it descended to, into a buffer
8322 // of its own — see `ForwardRenderer::shadow_selection`. Empty where
8323 // there is no amplification stage to descend anything.
8324 //
8325 // Declared for every tile rather than for the occupied ones: the state
8326 // is what the buffer is *in*, which does not depend on whether this
8327 // frame happened to write it, and a free tile's buffer still has to
8328 // arrive in the state the next frame's import claims.
8329 for &buffer in selection {
8330 pass = pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8331 }
8332 // The skinned vertices this pass may pull, and the reason it is declared
8333 // here as well as on the colour passes: a cascade draws the same
8334 // geometry out of the same pool, so a shadow that fell before the
8335 // dispatch was visible would be cast by the previous pose — a shadow
8336 // that does not match its caster, on a frame whose picture is otherwise
8337 // right.
8338 if let Some(vertices) = reads.skinned {
8339 pass = pass.read_buffer(vertices);
8340 }
8341 for (_, draws) in &generated {
8342 pass = read_draw_sources(pass, draws, self.emit);
8343 }
8344
8345 let groups = self.shadow_groups[self.frame].clone();
8346 // **What the reflective shadow map is drawn from**, read out here rather
8347 // than reconstructed by the caller: cascade 0's bind group — whose
8348 // uniform block already holds that cascade's `view_proj`, which is what
8349 // "reusing cascade 0's matrix" means — and the `GeneratedDraws` its cull
8350 // produced a moment ago. Both are `Copy`, so recording a second pass
8351 // from them costs no second cull and no second matrix.
8352 //
8353 // [`None`] on a frame that is not drawing cascade 0 at all: shadows off,
8354 // or a `r_shadow_cadence` past one that held the group anyway. The rows
8355 // then keep what the last gather wrote — see [`ProbeUpdate::EveryFrame`],
8356 // which says so.
8357 let cascade_zero: Option<(BindGroupHandle, GeneratedDraws)> = self
8358 .rsm_cull_ready
8359 .then(|| {
8360 generated
8361 .iter()
8362 .find(|(cull, _)| *cull == 0)
8363 .map(|(_, draws)| (groups[CASCADE_ZERO_VIEW], *draws))
8364 })
8365 .flatten();
8366 // **What the punctual reflective shadow map is drawn from**, resolved
8367 // here for `cascade_zero`'s reason and on its terms: each face's own
8368 // bind group — whose uniform block already holds that face's
8369 // `view_proj` — and the `GeneratedDraws` its slot's cull produced a
8370 // moment ago. Both are `Copy`, so the second pass costs no second cull
8371 // and no second matrix.
8372 //
8373 // Found by cull id rather than by position, so this list and the atlas's
8374 // cannot be knocked out of step by a slot the other one skipped.
8375 //
8376 // And the face's draw region, on the atlas's terms: a point light whose
8377 // cull tagged its casters draws each face from that face's region.
8378 let punctual_views: Vec<(BindGroupHandle, shadow::TileRect, GeneratedDraws, u32)> =
8379 punctual
8380 .iter()
8381 .filter_map(|face| {
8382 let (_, draws) = generated.iter().find(|(cull, _)| *cull == face.cull)?;
8383 let by_face = self.shadow_draws[face.cull].frame_mode(self.frame)
8384 == crcbl_shaders::draw_gen::DrawMode::Faces;
8385 Some((
8386 groups[face.view],
8387 face.tile,
8388 *draws,
8389 face_region(by_face, face.face),
8390 ))
8391 })
8392 .collect();
8393 // The culls those faces draw from, **once each**: a point light's six
8394 // faces draw one visible set, so declaring a face's sources would
8395 // declare the same buffers six times in one pass.
8396 let punctual_sources: Vec<GeneratedDraws> = punctual
8397 .iter()
8398 .map(|face| face.cull)
8399 .collect::<std::collections::BTreeSet<_>>()
8400 .into_iter()
8401 .filter_map(|cull| {
8402 let (_, draws) = generated.iter().find(|(candidate, _)| *candidate == cull)?;
8403 Some(*draws)
8404 })
8405 .collect();
8406 let bucket_draws = BucketDraws {
8407 // Replaced per partition below; the field is what the tile clears
8408 // and the reflective shadow map inherit, and neither binds it.
8409 pipeline: self.shadow_pipeline.single,
8410 layout: self.mesh_pipeline_layout,
8411 indices: self.pool.index_buffer(),
8412 emit: self.emit,
8413 calls: self
8414 .bucket_constants
8415 .iter()
8416 .enumerate()
8417 .map(|(bucket, constant_offset)| {
8418 let bucket = u32::try_from(bucket)
8419 .unwrap_or_else(|_| unreachable!("a fixed table of a few buckets"));
8420 (
8421 *constant_offset,
8422 self.primary.draws.args_offset(bucket),
8423 self.primary.draws.count_offset(bucket),
8424 self.primary.draws.mesh_args_offset(bucket),
8425 )
8426 })
8427 .collect(),
8428 region_step: self.region_step,
8429 // Packed per partition, where the partition's buckets are known.
8430 ranges: None,
8431 flat: None,
8432 };
8433 // Kept back for the reflective shadow map below, which is the same
8434 // per-bucket call list under a different pipeline — the depth prepass
8435 // plays exactly this trick with the camera's. Cloned before the pass
8436 // body takes the original.
8437 let bucket_calls = bucket_draws.clone();
8438 // The atlas's own split by material mode: an opaque bucket's tile is
8439 // drawn with no fragment stage in a scene that has a cutout in it. Every
8440 // view draws every partition — one call per bucket, per range of
8441 // buckets, or behind a task stage one flat call, per view, under a
8442 // pipeline per mode.
8443 let tile_partitions = self.depth_partitions(&bucket_draws);
8444
8445 // Counted off the two loops the body below runs, before it takes them:
8446 // every partition's calls per occupied view. `ForwardRenderer::counters`
8447 // is what reports it, and reading it back off the same `Vec`s is what
8448 // makes it move when the tile allocation does.
8449 let recorded = views.len() as u64
8450 * tile_partitions
8451 .iter()
8452 .map(BucketDraws::call_count)
8453 .sum::<u64>();
8454 // And the tile resets beside them, which are direct draws of one
8455 // instance rather than indirect ones: a frame that cleared the whole
8456 // attachment records none, and a frame that loaded it records one per
8457 // tile it redraws.
8458 let clears = if self.shadow_atlas_clears {
8459 0
8460 } else {
8461 views.len() as u64
8462 };
8463
8464 // What the image will hold once this body has run, carried into it so
8465 // that *recording* the pass is not what claims the atlas was drawn — see
8466 // [`ForwardRenderer::shadow_atlas_drawn`].
8467 let ran = Arc::clone(&self.shadow_pass_ran);
8468 let pass_id = self.shadow_pass_id;
8469 // The tiles this pass redraws have to be reset before anything is drawn
8470 // into them, and on a frame that loaded the attachment there is nothing
8471 // else that will — see [`MeshModules::depth_clear_pipeline`]. A frame
8472 // that cleared has already had every tile reset by the attachment, so
8473 // this is `None` and the recording is the one that shipped.
8474 let clear = (!self.shadow_atlas_clears).then_some(self.shadow_clear_pipeline);
8475 // **The reset draw has to bind a group, and only a browser says so.**
8476 // `MeshModules::depth_clear_pipeline` builds this pipeline from
8477 // `mesh_pipeline_layout`, so its layout declares group 0 whether or not
8478 // the one triangle's vertex shader reads a byte of it — and WebGPU
8479 // refuses a draw with any group the *layout* declares left unset, where
8480 // Vulkan and the others only care about what the shader dereferences. An
8481 // unbound reset therefore fails no native run and rejects the whole
8482 // browser frame: `No bind group set at group index 0` arrives when the
8483 // encoder is finished, so every pass recorded after it is thrown away
8484 // with it and the canvas stays at the clear colour.
8485 //
8486 // Any bucket's offset does: the block is what the mesh draws index and
8487 // this draw reads none of it, so what matters is that the offset is one
8488 // the layout accepts rather than which bucket it names.
8489 let clear_layout = bucket_draws.layout;
8490 let clear_offset = bucket_draws
8491 .calls
8492 .first()
8493 .map_or(0, |(constant_offset, ..)| *constant_offset);
8494 pass.execute(move |ctx| {
8495 ran.store(pass_id, Ordering::Relaxed);
8496 let encoder = ctx.encoder();
8497 if let Some(clear) = clear {
8498 encoder.bind_graphics_pipeline(clear);
8499 for (view, tile, _, _) in &views {
8500 set_shadow_tile(encoder, *tile);
8501 encoder.bind_group(0, groups[*view], &[clear_offset], clear_layout);
8502 encoder.draw(0..TILE_CLEAR_VERTICES, 0..1);
8503 }
8504 }
8505 for partition in &tile_partitions {
8506 partition.open(encoder);
8507 for (view, tile, cull, region) in &views {
8508 set_shadow_tile(encoder, *tile);
8509 partition.record_region(encoder, groups[*view], &generated[*cull].1, *region);
8510 }
8511 }
8512 });
8513
8514 // --- the reflective shadow map ---
8515 //
8516 // The irradiance probes' updater, first half, recorded
8517 // here because this is where cascade 0's bind group and its
8518 // already-generated draws are. **A pass of its own at its own extent**,
8519 // and [`crate::rsm`]'s header argues why it cannot ride the atlas above:
8520 // one colour attachment there spans the whole 3072² image for data only
8521 // one 768² tile is read from, and it would give all fourteen light tiles
8522 // a fragment stage.
8523 //
8524 // No viewport is set: the graph opens a pass with a full-target viewport
8525 // and scissor already, and every attachment here is the map's own square.
8526 let Some((cascade_group, cascade_draws)) = cascade_zero else {
8527 return (atlas, recorded, clears, None);
8528 };
8529 let extent = rsm::extent();
8530 let sun = RsmTargets {
8531 albedo: graph.create_image("rsm-albedo", rsm::albedo_target(extent)),
8532 normal: graph.create_image("rsm-normal", rsm::normal_target(extent)),
8533 world: graph.create_image("rsm-world", rsm::world_target(extent)),
8534 };
8535 // Its own depth, cleared and discarded: it resolves which surface a
8536 // texel of the map holds and nothing reads it afterwards.
8537 let rsm_depth = graph.create_image("rsm-depth", rsm::depth_target(extent));
8538 let mut rsm = graph
8539 .add_render_pass("rsm")
8540 // **Cleared, and the world target's clear is load-bearing**: `w` is
8541 // the coverage flag `RsmOutput::world` writes, so a texel the pass
8542 // draws nothing into reads back zero there and the gather skips it.
8543 // Without the clear the world origin would stand in for every part
8544 // of the cascade the geometry does not cover.
8545 .clear_color(sun.albedo, [0.0; 4])
8546 .clear_color(sun.normal, [0.0; 4])
8547 .clear_color(sun.world, [0.0; 4])
8548 .clear_depth(rsm_depth)
8549 // The same declarations the cascade above makes, for the same
8550 // reason: every group of the mesh layout names these, and this pass
8551 // binds one of those groups. Unlike the cascade, this one has a
8552 // fragment stage — so the pages really are sampled here.
8553 .read_image(placeholder)
8554 .read_image(reads.occlusion_placeholder)
8555 .read_image(reads.pages.base_color)
8556 .read_image(reads.pages.normal)
8557 .read_image(reads.pages.mro)
8558 .read_image(reads.pages.emissive)
8559 .read_buffer(reads.probes);
8560 if let Some(vertices) = reads.skinned {
8561 rsm = rsm.read_buffer(vertices);
8562 }
8563 // Cascade 0's cluster-selection buffer, which the mesh path's stages
8564 // write — declared on the atlas pass's terms, and only for the one view
8565 // this pass draws.
8566 if let Some(&buffer) = selection.get(CASCADE_ZERO_VIEW) {
8567 rsm = rsm.use_buffer(buffer, ResourceState::ShaderReadWrite);
8568 }
8569 rsm = read_draw_sources(rsm, &cascade_draws, self.emit);
8570 // Split by side, on the colour pass's terms: this stage cuts the alpha
8571 // mask itself, so the only thing it cannot say inside the fragment stage
8572 // is which faces the rasteriser keeps.
8573 let rsm_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8574 let rsm_recorded: u64 = rsm_partitions.iter().map(BucketDraws::call_count).sum();
8575 rsm.execute(move |ctx| {
8576 let encoder = ctx.encoder();
8577 for partition in &rsm_partitions {
8578 partition.open(encoder);
8579 partition.record(encoder, cascade_group, &cascade_draws);
8580 }
8581 });
8582
8583 // --- the punctual reflective shadow map ---
8584 //
8585 // The irradiance probes' punctual producer: the same
8586 // pipeline and the same per-bucket call list as the pass above, under
8587 // one viewport per shadowed light face instead of one whole map. A spot
8588 // is a tile and a point light is six, which is `shadow::tile_span` — so
8589 // this is the atlas pass's own view loop drawn into a second, much
8590 // smaller set of targets.
8591 //
8592 // **Recorded whether or not the frame lights a punctual face**, unlike
8593 // the map above. The clear is a legitimate answer — a frame with no
8594 // shadowed punctual light has no punctual bounce, and the coverage flag
8595 // in `w` says so at every texel — and a pass that came and went with the
8596 // lights would be a pass list that changes shape with the scene, which
8597 // is what `RENDER_PASSES` and every timing reader are written against.
8598 let punctual_extent = rsm::punctual_extent();
8599 let punctual_targets = RsmTargets {
8600 albedo: graph.create_image("rsm-punctual-albedo", rsm::albedo_target(punctual_extent)),
8601 normal: graph.create_image("rsm-punctual-normal", rsm::normal_target(punctual_extent)),
8602 world: graph.create_image("rsm-punctual-world", rsm::world_target(punctual_extent)),
8603 };
8604 let punctual_depth =
8605 graph.create_image("rsm-punctual-depth", rsm::depth_target(punctual_extent));
8606 let mut punctual_pass = graph
8607 .add_render_pass("rsm-punctual")
8608 // Cleared on the map above's terms, and the world target's clear is
8609 // load-bearing for its reason as well as for one of this map's own:
8610 // the tiles the cascades would hold are drawn into by nothing at
8611 // all, and a coverage flag of zero is what keeps the gather out of
8612 // them.
8613 .clear_color(punctual_targets.albedo, [0.0; 4])
8614 .clear_color(punctual_targets.normal, [0.0; 4])
8615 .clear_color(punctual_targets.world, [0.0; 4])
8616 .clear_depth(punctual_depth)
8617 .read_image(placeholder)
8618 .read_image(reads.occlusion_placeholder)
8619 .read_image(reads.pages.base_color)
8620 .read_image(reads.pages.normal)
8621 .read_image(reads.pages.mro)
8622 .read_image(reads.pages.emissive)
8623 .read_buffer(reads.probes);
8624 if let Some(vertices) = reads.skinned {
8625 punctual_pass = punctual_pass.read_buffer(vertices);
8626 }
8627 // Each face's own cluster-selection buffer, which the mesh path's stages
8628 // write — declared on the atlas pass's terms, and only for the views
8629 // this pass draws.
8630 for face in &punctual {
8631 if let Some(&buffer) = selection.get(face.view) {
8632 punctual_pass = punctual_pass.use_buffer(buffer, ResourceState::ShaderReadWrite);
8633 }
8634 }
8635 for draws in &punctual_sources {
8636 punctual_pass = read_draw_sources(punctual_pass, draws, self.emit);
8637 }
8638 let punctual_partitions = self.sided_partitions(&bucket_calls, self.rsm_pipeline);
8639 let punctual_recorded = punctual_views.len() as u64
8640 * punctual_partitions
8641 .iter()
8642 .map(BucketDraws::call_count)
8643 .sum::<u64>();
8644 punctual_pass.execute(move |ctx| {
8645 let encoder = ctx.encoder();
8646 // The partition is **outside** the view loop, on the shadow atlas's
8647 // terms: one pipeline bind covers every face of that side.
8648 for partition in &punctual_partitions {
8649 partition.open(encoder);
8650 for (group, tile, draws, region) in &punctual_views {
8651 set_shadow_tile(encoder, *tile);
8652 partition.record_region(encoder, *group, draws, *region);
8653 }
8654 }
8655 });
8656
8657 let images = RsmImages {
8658 sun,
8659 punctual: punctual_targets,
8660 };
8661 (
8662 atlas,
8663 recorded + rsm_recorded + punctual_recorded,
8664 clears,
8665 Some(images),
8666 )
8667 }
8668
8669 /// Which lights hold the atlas's light tiles this frame, and where each
8670 /// map was laid out.
8671 ///
8672 /// **The observable topic 45's priority rung otherwise has
8673 /// none for.** A map's *size* leaves no trace in the picture that a golden
8674 /// can hold anyone to: a light demoted to a quarter of a cell draws a
8675 /// slightly softer shadow, which is a perfectly plausible frame and one a
8676 /// re-bless accepts. [`Selection::atlas_rect`](crate::shadow::Selection)
8677 /// off this is what says which level the allocator actually handed out, and
8678 /// `crates/crcbl/tests/mesh_e2e/shadow_tiles.rs` is what reads it.
8679 ///
8680 /// Named for the selection's own subject rather than for its type, because
8681 /// [`Self::shadow_selection`] above is a *buffer* — the cut a cascade
8682 /// descended to — and two accessors of one name is a caller reaching for
8683 /// the wrong one.
8684 ///
8685 /// It is this frame's answer, written by [`Self::begin_frame`]: before the
8686 /// first frame every slot is free.
8687 /// Whether this frame took the shadow atlas as an earlier frame left it,
8688 /// rather than drawing it again.
8689 ///
8690 /// Topic 45's static-caching rung, read back. True means
8691 /// this frame recorded **no** shadow cull and no shadow pass, and every map
8692 /// sampled through [`Self::shadow_lights`]'s rectangles is the one the last
8693 /// frame that did draw put there — so a caller comparing two frames' pass
8694 /// lists, draw counts or GPU timings has to know which of them redrew.
8695 ///
8696 /// Decided by [`Self::begin_frame`] out of everything each group of the
8697 /// atlas is a function of — see `ForwardRenderer::shadow_group_record` —
8698 /// and it answers `false` before the first frame, because no frame has been
8699 /// opened and so none of them has held anything.
8700 ///
8701 /// **Whole-atlas, and since the cadence rung a frame can be neither.** A
8702 /// frame that redraws one map and holds another answers `false` here and
8703 /// `false` from [`Self::shadow_slot_redrawn`] for the maps it held; the two
8704 /// together are what say which.
8705 #[must_use]
8706 pub const fn shadow_atlas_cached(&self) -> bool {
8707 self.shadow_atlas_cached
8708 }
8709
8710 /// Whether this frame redrew cascade `cascade`'s map, rather than keeping
8711 /// the one an earlier frame put there.
8712 ///
8713 /// Topic 45's cadence rung, read back. **The observable
8714 /// that rung otherwise has none for**: a held map draws a shadow lagging its
8715 /// caster by a frame or two, which is a perfectly plausible picture and one
8716 /// a golden accepts — so nothing but this distinguishes a cadence that is
8717 /// working from one that is not running at all.
8718 ///
8719 /// `false` for a `cascade` past [`shadow::CASCADES`] and before the first
8720 /// frame, which is the same answer for the same reason: no map was drawn
8721 /// there.
8722 #[must_use]
8723 pub fn shadow_cascade_redrawn(&self, cascade: usize) -> bool {
8724 cascade < shadow::CASCADES && self.shadow_group_redrawn[cascade]
8725 }
8726
8727 /// Whether this frame redrew the maps of light slot `slot` —
8728 /// [`shadow::Selection::slots`]' index — rather than keeping the ones an
8729 /// earlier frame put there.
8730 ///
8731 /// [`Self::shadow_cascade_redrawn`]'s answer for the light region, and a
8732 /// point light's [`shadow::POINT_FACES`] faces answer together: they cull
8733 /// once and draw one visible set, so they are redrawn or held as one.
8734 #[must_use]
8735 pub fn shadow_slot_redrawn(&self, slot: usize) -> bool {
8736 slot < shadow::LIGHT_SLOTS && self.shadow_group_redrawn[shadow_cull(slot)]
8737 }
8738
8739 /// How many tiles of the atlas this frame redrew.
8740 ///
8741 /// What [`shadow::r_shadow_faces`] is spent in, read back — so a test can
8742 /// say the budget bound rather than that it was configured. A cascade costs
8743 /// one and a point light's cube costs [`shadow::POINT_FACES`].
8744 #[must_use]
8745 pub const fn shadow_faces_redrawn(&self) -> u32 {
8746 self.shadow_faces_redrawn
8747 }
8748
8749 /// Pins the shadow cadence for this renderer, or hands it back to the
8750 /// console.
8751 ///
8752 /// [`Self::set_effect_request`]'s shape at this knob:
8753 /// [`shadow::r_shadow_cadence`] and [`shadow::r_shadow_faces`] are
8754 /// process-global, so they are the *default* rather than the only answer —
8755 /// an application drawing two views at two qualities, or a test that needs a
8756 /// frame nothing else in the process can move, pins its own.
8757 ///
8758 /// [`None`] hands it back, which is what a renderer starts at.
8759 ///
8760 /// Read once per [`Self::begin_frame`], on `ForwardRenderer::frame_effects`'
8761 /// terms: this call decides it and `add_passes` acts on it.
8762 pub const fn set_shadow_cadence(&mut self, cadence: Option<shadow::Cadence>) {
8763 self.shadow_cadence_request = cadence;
8764 }
8765
8766 /// Whether this frame ignored the cadence for at least one map because the
8767 /// region that map covers had moved out from under it.
8768 ///
8769 /// Topic 45's "a moving light or camera cut resets it",
8770 /// made precise: a map is *reset* rather than merely out of date when the
8771 /// centre it is projected from has moved further than the map's own reach —
8772 /// a light further than its own radius, or a cascade's eye further than the
8773 /// sphere that cascade was fitted to. Holding such a map is not a shadow
8774 /// that lags; it is a shadow of somewhere else.
8775 ///
8776 /// A frame whose atlas was **relaid** — a light gained, lost or resized a
8777 /// tile, or shadows were switched on or off — answers `true` as well, and
8778 /// that frame redraws every map it has: the only clear this seam can make
8779 /// covers the whole image, so there is nothing left to hold.
8780 #[must_use]
8781 pub const fn shadow_cadence_reset(&self) -> bool {
8782 self.shadow_cadence_reset
8783 }
8784
8785 #[must_use]
8786 pub const fn shadow_lights(&self) -> &shadow::Selection {
8787 &self.shadow_lights
8788 }
8789
8790 /// The shadow atlas, for a caller that wants to read it back.
8791 ///
8792 /// **The observable this whole slice can otherwise hide behind.** A shadow
8793 /// pass that renders nothing leaves every texel at
8794 /// [`depth::CLEAR`](crcbl_hal::depth::CLEAR) and produces a frame in which
8795 /// everything is lit — which is a perfectly plausible picture and matches
8796 /// any golden blessed from it. Copying this image back and finding a texel
8797 /// that is not the clear value is what distinguishes the two.
8798 ///
8799 /// It is created with
8800 /// [`ImageUsage::TRANSFER_SRC`](crcbl_hal::ImageUsage::TRANSFER_SRC) for
8801 /// exactly that, and its extent is [`shadow::atlas_extent`].
8802 #[must_use]
8803 pub const fn shadow_atlas(&self) -> crcbl_hal::ImageHandle {
8804 self.shadow_atlas
8805 }
8806
8807 /// The view [`shadow_atlas`](Self::shadow_atlas) is bound and imported
8808 /// through, for a reader importing the atlas into a graph of its own.
8809 #[must_use]
8810 pub const fn shadow_atlas_view(&self) -> ImageViewHandle {
8811 self.shadow_atlas_view
8812 }
8813
8814 /// The base-colour page every material row samples through
8815 /// [`GpuMaterial::base_color_texture`](crcbl_shaders::mesh::GpuMaterial::base_color_texture),
8816 /// as the image and the view [`crate::texture`] uploaded.
8817 ///
8818 /// **What a render-to-texture view copies into.** A second camera drawing
8819 /// into an image is only half of a monitor: the surface that *shows* it
8820 /// samples a page layer, and nothing above this crate can name the image
8821 /// that layer lives in.
8822 ///
8823 /// A caller that wants to *write* it wants
8824 /// [`base_color_page_import`](Self::base_color_page_import) instead: the
8825 /// graph can only order a copy against the draws that sample the page while
8826 /// both are declared, and the two declarations have to agree field for
8827 /// field. This one is the raw handles, for a caller that binds or reads them
8828 /// outside a graph.
8829 ///
8830 /// It is created with
8831 /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST),
8832 /// because the upload that filled it is a copy, so a per-frame copy into it
8833 /// needs no new usage flag. Its extent is
8834 /// [`PageDesc::extent`](crate::scene::PageDesc::extent) of
8835 /// [`PageKind::BaseColor`] squared and it has one layer per
8836 /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of that kind;
8837 /// the description is the caller's, so the caller already knows both. A
8838 /// description naming no base-colour layer gets a 1×1 placeholder instead —
8839 /// see this module's `PAGE_PLACEHOLDER_TEXEL`.
8840 #[must_use]
8841 pub const fn base_color_page(&self) -> UploadedTexture {
8842 self.base_color_page
8843 }
8844
8845 /// What [`add_passes`](Self::add_passes) names the base-colour page in the
8846 /// graph.
8847 ///
8848 /// [`RenderGraph::import_image`] keeps the label of whichever import ran
8849 /// first, so a caller importing the page too passes this rather than a
8850 /// string of its own — otherwise every barrier record and
8851 /// [`dump`](crate::CompiledGraph::dump) line would name the page differently
8852 /// depending on which subsystem got there first.
8853 pub const BASE_COLOR_PAGE_LABEL: &'static str = "base-colour-page";
8854
8855 /// The base-colour page **as this renderer declares it to a graph**.
8856 ///
8857 /// [`add_passes`](Self::add_passes) imports exactly this value under
8858 /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL) and declares a read
8859 /// of it on every pass whose bind group names the page, so a caller that
8860 /// writes the page — a render-to-texture view copied into one layer — gets
8861 /// the graph to order its write against those draws.
8862 ///
8863 /// **A caller that writes it imports this value rather than one of its
8864 /// own.** [`RenderGraph::import_image`] hands the second importer the id the
8865 /// first got, which is what puts the write and the reads on one state
8866 /// tracker, and it does that only while the two declarations agree in every
8867 /// field — a disagreement is [`GraphError::ImportDeclarationConflict`] at
8868 /// [`compile`](RenderGraph::compile). Reading the declaration off the
8869 /// renderer that owns the page is what makes them one answer instead of two
8870 /// constants that have to be kept equal by hand.
8871 ///
8872 /// [`InitialClaim::Tracked`] with [`ResourceState::ShaderRead`] both ways:
8873 /// [`crate::texture`] leaves an uploaded page in that state, and the
8874 /// trailing barrier the `final_state` asks for puts it back there at the end
8875 /// of every frame — so the pool's ledger and this declaration are the same
8876 /// answer, which is what `Tracked` has the graph check.
8877 ///
8878 /// [`GraphError::ImportDeclarationConflict`]: crate::graph::GraphError::ImportDeclarationConflict
8879 #[must_use]
8880 pub const fn base_color_page_import(&self) -> ImportedImage {
8881 ImportedImage {
8882 image: self.base_color_page.image,
8883 view: self.base_color_page.view,
8884 format: BASE_COLOR_PAGE_FORMAT,
8885 extent: self.page_extents[PageKind::BaseColor.index()],
8886 initial: ResourceState::ShaderRead,
8887 claim: InitialClaim::Tracked,
8888 final_state: ResourceState::ShaderRead,
8889 }
8890 }
8891
8892 /// Topic 43 §2's **normal** page, the raw handles.
8893 ///
8894 /// [`base_color_page`](Self::base_color_page)'s counterpart, on every one of
8895 /// its terms: one `D2Array` image, one layer per
8896 /// [`PageDesc::layers`](crate::scene::PageDesc::layers) entry of
8897 /// [`PageKind::Normal`], at **that kind's own extent**, and created with
8898 /// [`ImageUsage::TRANSFER_DST`](crcbl_hal::ImageUsage::TRANSFER_DST) so a
8899 /// per-frame copy into a layer needs no new usage flag. What it is *not* is
8900 /// the same format: it is `Rgba8Unorm`, where the base-colour page is
8901 /// `Rgba8UnormSrgb`, and topic 44's rung 2 is where that
8902 /// is argued.
8903 #[must_use]
8904 pub const fn normal_page(&self) -> UploadedTexture {
8905 self.normal_page
8906 }
8907
8908 /// What [`add_passes`](Self::add_passes) names the normal page in the graph,
8909 /// on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8910 pub const NORMAL_PAGE_LABEL: &'static str = "normal-page";
8911
8912 /// The normal page **as this renderer declares it to a graph**, on
8913 /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly
8914 /// — including that a caller writing a layer imports *this* value rather
8915 /// than one of its own, so the write and the draws land on one state
8916 /// tracker.
8917 #[must_use]
8918 pub const fn normal_page_import(&self) -> ImportedImage {
8919 ImportedImage {
8920 image: self.normal_page.image,
8921 view: self.normal_page.view,
8922 format: NORMAL_PAGE_FORMAT,
8923 extent: self.page_extents[PageKind::Normal.index()],
8924 initial: ResourceState::ShaderRead,
8925 claim: InitialClaim::Tracked,
8926 final_state: ResourceState::ShaderRead,
8927 }
8928 }
8929
8930 /// Topic 43 §2's packed
8931 /// **metallic-roughness-occlusion** page, the raw handles.
8932 ///
8933 /// [`normal_page`](Self::normal_page)'s counterpart, on every one of its
8934 /// terms and at the same `Rgba8Unorm` format: a layer of it is glTF's
8935 /// occlusion, roughness and metallic in `r`, `g` and `b`, which are numbers
8936 /// rather than a colour — see this module's `MRO_PAGE_FORMAT`.
8937 #[must_use]
8938 pub const fn mro_page(&self) -> UploadedTexture {
8939 self.mro_page
8940 }
8941
8942 /// What [`add_passes`](Self::add_passes) names the
8943 /// metallic-roughness-occlusion page in the graph, on
8944 /// [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8945 pub const MRO_PAGE_LABEL: &'static str = "metallic-roughness-occlusion-page";
8946
8947 /// The metallic-roughness-occlusion page **as this renderer declares it to a
8948 /// graph**, on [`base_color_page_import`](Self::base_color_page_import)'s
8949 /// terms exactly.
8950 #[must_use]
8951 pub const fn mro_page_import(&self) -> ImportedImage {
8952 ImportedImage {
8953 image: self.mro_page.image,
8954 view: self.mro_page.view,
8955 format: MRO_PAGE_FORMAT,
8956 extent: self.page_extents[PageKind::MetallicRoughnessOcclusion.index()],
8957 initial: ResourceState::ShaderRead,
8958 claim: InitialClaim::Tracked,
8959 final_state: ResourceState::ShaderRead,
8960 }
8961 }
8962
8963 /// Topic 43 §2's **emissive** page, the raw
8964 /// handles.
8965 ///
8966 /// [`base_color_page`](Self::base_color_page)'s counterpart down to the
8967 /// format: an emissive texel is a colour, so this image is
8968 /// `Rgba8UnormSrgb` and the sampler decodes it — see this module's
8969 /// `EMISSIVE_PAGE_FORMAT`.
8970 #[must_use]
8971 pub const fn emissive_page(&self) -> UploadedTexture {
8972 self.emissive_page
8973 }
8974
8975 /// What [`add_passes`](Self::add_passes) names the emissive page in the
8976 /// graph, on [`BASE_COLOR_PAGE_LABEL`](Self::BASE_COLOR_PAGE_LABEL)'s terms.
8977 pub const EMISSIVE_PAGE_LABEL: &'static str = "emissive-page";
8978
8979 /// The emissive page **as this renderer declares it to a graph**, on
8980 /// [`base_color_page_import`](Self::base_color_page_import)'s terms exactly.
8981 #[must_use]
8982 pub const fn emissive_page_import(&self) -> ImportedImage {
8983 ImportedImage {
8984 image: self.emissive_page.image,
8985 view: self.emissive_page.view,
8986 format: EMISSIVE_PAGE_FORMAT,
8987 extent: self.page_extents[PageKind::Emissive.index()],
8988 initial: ResourceState::ShaderRead,
8989 claim: InitialClaim::Tracked,
8990 final_state: ResourceState::ShaderRead,
8991 }
8992 }
8993
8994 /// The model matrix for a cube spinning at `seconds` into the run.
8995 ///
8996 /// Two axes at incommensurable rates, so the animation never repeats and
8997 /// every face comes into view — which is what makes "the cube is spinning"
8998 /// observable rather than a claim about a matrix.
8999 #[must_use]
9000 pub fn spin(seconds: f32) -> Mat4 {
9001 Mat4::from_quat(
9002 Quat::from_axis_angle(Vec3::Y, seconds * 0.9)
9003 * Quat::from_axis_angle(Vec3::X, seconds * 0.55),
9004 )
9005 }
9006
9007 /// The format the tonemap pass renders into.
9008 #[must_use]
9009 pub const fn target_format(&self) -> Format {
9010 self.target_format
9011 }
9012
9013 /// Switches the infinite ground grid on with `style`, or off with [`None`].
9014 ///
9015 /// **Off by default.** Every sample and every golden image predates the
9016 /// grid, so a renderer nobody has called this on records exactly the passes
9017 /// it always did — see [`crate::grid`] for what the pass is and
9018 /// [`add_passes`](Self::add_passes) for where in the frame it lands.
9019 ///
9020 /// The first `Some` builds the pipeline and the uniform ring; later calls
9021 /// only replace the style, and a `None` leaves both built. Releasing them
9022 /// here would mean releasing blocks the frames in flight may still be
9023 /// reading, so they are released by [`destroy`](Self::destroy) alone — the
9024 /// one call that already requires an idle device.
9025 ///
9026 /// # Errors
9027 ///
9028 /// [`HalError`] if the grid's pipeline or its blocks could not be created.
9029 /// Nothing is left switched on when that happens: the grid stays as it was.
9030 pub fn set_ground_grid(
9031 &mut self,
9032 device: &dyn Device,
9033 style: Option<GridStyle>,
9034 ) -> Result<(), HalError> {
9035 let Some(style) = style else {
9036 self.ground_grid_on = false;
9037 return Ok(());
9038 };
9039 let grid = match self.ground_grid.as_mut() {
9040 Some(grid) => grid,
9041 None => {
9042 // Built for the tonemap's target and the scene depth, because
9043 // those are the two attachments the pass is given — see
9044 // `add_passes`. Both are pipeline state, so a renderer whose
9045 // target format changed would need a new `Grid`; nothing in this
9046 // crate changes it after `build`, and `target_format` is kept
9047 // for exactly that reason.
9048 let grid = GroundGrid::new(
9049 device,
9050 self.primary.uniforms.len(),
9051 self.target_format,
9052 SCENE_DEPTH_FORMAT,
9053 )?;
9054 self.ground_grid.insert(grid)
9055 }
9056 };
9057 grid.set_style(style);
9058 self.ground_grid_on = true;
9059 Ok(())
9060 }
9061
9062 /// The debug draw layer's immediate-mode buffer, to append to.
9063 ///
9064 /// The UI's debug item 5 (`docs/notes/tooling.md`): any system appends lines, boxes,
9065 /// spheres and frusta during the frame, and
9066 /// [`begin_frame`](Self::begin_frame) uploads and clears what is there — so
9067 /// a segment lives exactly the frame it was appended in and nothing has to
9068 /// be un-appended. See [`crate::debug_draw`] for where the pass lands and
9069 /// for the console switch that has to be on before anything is drawn.
9070 ///
9071 /// **Appending is free while the layer is off**, but building the geometry
9072 /// is the caller's: a system whose overlay costs something to compute asks
9073 /// [`DebugDraw::enabled`] first.
9074 pub fn debug_draw(&mut self) -> &mut DebugDraw {
9075 &mut self.debug_draw
9076 }
9077
9078 /// How the ground grid is drawn, or [`None`] where it is switched off.
9079 ///
9080 /// The read-back half of [`set_ground_grid`](Self::set_ground_grid), and the
9081 /// observable a test asking "is the grid on" wants: a renderer that built
9082 /// the grid and then switched it off answers [`None`], because what it draws
9083 /// is what the question is about.
9084 #[must_use]
9085 pub fn ground_grid(&self) -> Option<&GridStyle> {
9086 self.ground_grid
9087 .as_ref()
9088 .filter(|_| self.ground_grid_on)
9089 .map(GroundGrid::style)
9090 }
9091
9092 /// Whether this frame adds [`crate::sky_pass`]'s background pass.
9093 ///
9094 /// [`Sky::NONE`] with no atmosphere is the value a renderer nobody called
9095 /// [`set_sky`](Self::set_sky) or
9096 /// [`set_atmosphere`](Self::set_atmosphere) on holds, and it is checked
9097 /// here rather than left to the shader for the reason [`crate::sky_pass`]
9098 /// gives: a black gradient drawn over [`SCENE_CLEAR`] would *change* those
9099 /// frames, where adding no pass leaves them exactly as they were.
9100 fn draws_sky(&self) -> bool {
9101 self.sky != Sky::NONE || self.atmosphere.is_some()
9102 }
9103
9104 /// Brings [`Self::sky_view`] up to the sun this frame has, a stripe of rows
9105 /// per frame.
9106 ///
9107 /// Called once per [`Self::begin_frame`]. The comparison is on the
9108 /// normalised parameters rather than on the [`Atmosphere`] a caller handed
9109 /// over, so re-setting the same sun spelled a different length is not a
9110 /// rebuild — and a caller that sets the same value every frame, which is
9111 /// the ordinary shape of a scene's update, pays the comparison and nothing
9112 /// else.
9113 ///
9114 /// # The first LUT is marched whole; every later one is marched in stripes
9115 ///
9116 /// A renderer that has no LUT has no sky to draw, so the first march after
9117 /// [`set_atmosphere`](Self::set_atmosphere) runs to completion inside this
9118 /// call and a caller that draws a single frame gets that frame's sky. After
9119 /// that there is always a finished LUT to show, so a sun that moved starts
9120 /// a [`SkyViewBuild`] and this steps it [`SKY_VIEW_BUILD_ROWS`] rows per
9121 /// frame — the frames in between keep drawing the LUT the last completed
9122 /// march produced, and no frame pays the whole march.
9123 ///
9124 /// # A sun that moves again restarts the march rather than finishing it
9125 ///
9126 /// The build in flight is kept only while its own sun is still the one the
9127 /// caller wants; a sun that moved during it is a new build from row zero,
9128 /// because finishing the old one would swap in a LUT for a sun that is
9129 /// already wrong and then immediately start marching again. **A sun that
9130 /// moves every frame therefore never completes a build and goes on showing
9131 /// the last one it finished** — a sky frozen at the sun it last caught up
9132 /// with, rather than a sky that stutters at whatever the march last passed.
9133 /// That is the trade this makes: the frame cost is bounded and the sky
9134 /// lags, where the whole-march rebuild it replaced had the sky exact and
9135 /// the frame cost unbounded. A caller that wants the sky exact stops the
9136 /// sun on a value and leaves it there: the march then completes, and the
9137 /// frames it takes are `SKY_VIEW_HEIGHT` over [`SKY_VIEW_BUILD_ROWS`].
9138 ///
9139 /// **The aerial-perspective LUT is marched in the same steps** — see
9140 /// [`SkyViewBuild`] — so the air in front of the scene arrives on the same
9141 /// frame as the sky and lags the sun by the same frames, never a sun apart
9142 /// from it. A change of [`Atmosphere::km_per_unit`] alone is a new march
9143 /// on the same terms, since it is part of the parameters compared.
9144 fn refresh_sky_view(&mut self) {
9145 let Some(atmosphere) = self.atmosphere else {
9146 self.sky_view = None;
9147 self.sky_view_build = None;
9148 return;
9149 };
9150 let parameters = atmosphere.parameters();
9151 if self
9152 .sky_view
9153 .as_ref()
9154 .is_some_and(|presented| presented.parameters == parameters)
9155 {
9156 self.sky_view_build = None;
9157 return;
9158 }
9159 if self.sky_view.is_none() {
9160 self.sky_view_build = None;
9161 self.sky_view = Some(PresentedSky::new(parameters, SkyView::build(¶meters)));
9162 return;
9163 }
9164 let mut build = match self.sky_view_build.take() {
9165 Some(build) if build.atmosphere() == parameters => build,
9166 _ => SkyViewBuild::start(¶meters),
9167 };
9168 if build.step(SKY_VIEW_BUILD_ROWS) {
9169 self.sky_view = Some(PresentedSky::new(parameters, build.finish()));
9170 } else {
9171 self.sky_view_build = Some(build);
9172 }
9173 }
9174
9175 /// Sets the multiplier the tonemap pass applies before its clamp, clamped
9176 /// into [`EXPOSURE_MIN`]`..=`[`EXPOSURE_MAX`].
9177 ///
9178 /// **The default is [`crcbl_shaders::tonemap::DEFAULT_EXPOSURE`]**, which is
9179 /// the value `tonemap.slang` held as a compile-time constant until this
9180 /// became a runtime one — so a renderer nobody calls this on draws the frame
9181 /// it always drew, and every golden image is untouched.
9182 ///
9183 /// It takes effect on the next
9184 /// [`begin_frame`](Self::begin_frame), which is what writes the block: a
9185 /// frame already recorded reads the value it was recorded with.
9186 ///
9187 /// **The clamp is here rather than at the call site** so that no caller can
9188 /// reach a picture it cannot get back from, and so that a control which
9189 /// steps by reading this back and setting a multiple of it — which is what
9190 /// [`exposure`](Self::exposure) is for — cannot wind up past the end and
9191 /// then need as many presses to come back.
9192 pub const fn set_exposure(&mut self, exposure: f32) {
9193 // `max` then `min` rather than `f32::clamp`: `clamp` propagates a NaN,
9194 // and a NaN reaching the block is a frame of NaN pixels with no key to
9195 // press to get out of it. `f32::max` returns the bound instead, so a NaN
9196 // lands on `EXPOSURE_MIN` — dark, and one press from being bright again.
9197 self.exposure = exposure.max(EXPOSURE_MIN).min(EXPOSURE_MAX);
9198 }
9199
9200 /// How far auto-exposure may travel toward its measurement in one frame.
9201 ///
9202 /// **[`None`] is the whole distance**, which is what a renderer nobody
9203 /// calls this on does and what the pass did before adaptation existed — so
9204 /// no golden moved when this arrived. A view that wants the roll asks, and
9205 /// asks *every frame*, because [`ExposureAdaptation`] carries that frame's
9206 /// own delta: this crate has no clock, and the frame time lives where the
9207 /// frame loop is.
9208 ///
9209 /// It takes effect on the next [`begin_frame`](Self::begin_frame), which is
9210 /// what writes the block, and it does nothing at all on a frame that did not
9211 /// ask for [`RenderEffects::AUTO_EXPOSURE`] — the passes that read it are
9212 /// the ones that bit adds.
9213 pub const fn set_exposure_adaptation(&mut self, adaptation: Option<ExposureAdaptation>) {
9214 self.exposure_adaptation = adaptation;
9215 }
9216
9217 /// What [`set_exposure_adaptation`](Self::set_exposure_adaptation) was last
9218 /// handed.
9219 #[must_use]
9220 pub const fn exposure_adaptation(&self) -> Option<ExposureAdaptation> {
9221 self.exposure_adaptation
9222 }
9223
9224 /// Which operator the tonemap pass runs on the exposed scene colour.
9225 ///
9226 /// **The ACES fit by default**, because this renderer shades in linear HDR
9227 /// and the roll-off is what that range is for. What a caller asks *for* here
9228 /// is therefore usually the other one: `tonemap.slang`'s clamp is the
9229 /// identity on `0..=1`, so display-referred content reaches the swapchain
9230 /// exactly, and a fixture that predicts a code value from a host model of
9231 /// the shading needs the frame to stay scene-referred. Every 2D sample in
9232 /// this tree draws through `crate::sprite_pass` and `crate::ui_pass`
9233 /// instead, so none of them reaches this pass at all.
9234 ///
9235 /// It takes effect on the next [`begin_frame`](Self::begin_frame), for
9236 /// [`set_exposure`](Self::set_exposure)'s reason: the block is written
9237 /// there, and a frame already recorded reads the value it was recorded
9238 /// with.
9239 ///
9240 /// **There is nothing to refuse and no `supports_` probe beside it.** The
9241 /// selector is a lane of a uniform block read by a branch every device
9242 /// already runs, so unlike the wireframe there is no second pipeline for a
9243 /// device to decline to build.
9244 pub const fn set_tonemap_curve(&mut self, curve: tonemap::TonemapCurve) {
9245 self.tonemap_curve = curve;
9246 }
9247
9248 /// The operator in force, on [`exposure`](Self::exposure)'s terms: the
9249 /// value the next frame will be drawn with.
9250 #[must_use]
9251 pub const fn tonemap_curve(&self) -> tonemap::TonemapCurve {
9252 self.tonemap_curve
9253 }
9254
9255 /// How large the internal render target is as a fraction of the extent
9256 /// [`begin_frame`](Self::begin_frame) is handed, clamped to
9257 /// `MIN_RENDER_SCALE..=1.0`.
9258 ///
9259 /// **This is the largest performance knob this renderer has.** Every pass
9260 /// before the upscale costs what its extent costs, so a scale of `0.7` is
9261 /// roughly half the shading work of `1.0`; the UI is composited onto the
9262 /// target afterwards at native resolution, so text stays sharp while the 3D
9263 /// frame gets cheap. `docs/notes/rendering.md` (_What the deleted
9264 /// 48-post-processing plan left behind_) is where that trade is written down.
9265 ///
9266 /// **`1.0` is not a special case with a fast path, it is the absence of the
9267 /// feature.** At full scale the internal extent *is* the caller's, the post
9268 /// chain writes the target directly, and no upscale pass is recorded — which
9269 /// is what makes a renderer nobody has called this on draw the frame it drew
9270 /// before the knob existed, bit for bit.
9271 ///
9272 /// **Above `1.0` is clamped away rather than supported.** Supersampling
9273 /// wants a box or Lanczos reduction and `upscale.slang` is a Catmull-Rom
9274 /// *reconstruction*; running it as a minification filter would alias, which
9275 /// is the opposite of what a caller asking for it wants. A non-finite scale
9276 /// is clamped to `1.0` for the same reason a `NaN` extent would be refused:
9277 /// the failure it produces is a zero-sized target somewhere downstream.
9278 ///
9279 /// Takes effect on the next [`begin_frame`](Self::begin_frame), on
9280 /// [`set_exposure`](Self::set_exposure)'s terms exactly — a frame already
9281 /// recorded is drawn at the scale it was recorded with.
9282 pub fn set_render_scale(&mut self, scale: f32) {
9283 self.render_scale = if scale.is_finite() {
9284 scale.clamp(MIN_RENDER_SCALE, 1.0)
9285 } else {
9286 1.0
9287 };
9288 }
9289
9290 /// The render scale in force, after the clamp
9291 /// [`set_render_scale`](Self::set_render_scale) applied.
9292 ///
9293 /// The read-back half, on [`exposure`](Self::exposure)'s terms.
9294 #[must_use]
9295 pub const fn render_scale(&self) -> f32 {
9296 self.render_scale
9297 }
9298
9299 /// The anisotropy the base-colour page is sampled with, in force from the
9300 /// next [`begin_frame`](Self::begin_frame).
9301 ///
9302 /// Topic 43's filtering rung, the player's half:
9303 /// [`anisotropy_for`](Self::anisotropy_for) is what a renderer nobody has
9304 /// called this on samples with, and this is what a settings row moves it
9305 /// to. Clamped to `1.0..=max_sampler_anisotropy` where the device was
9306 /// granted [`Features::SAMPLER_ANISOTROPY`] and to exactly `1.0` where it
9307 /// was not — the row can turn the filter off or push it to the device's
9308 /// ceiling, and nothing it asks reaches a `create_sampler` that would
9309 /// refuse it. A value that is not a number is the default, on
9310 /// [`set_render_scale`](Self::set_render_scale)'s terms.
9311 ///
9312 /// **A sampler is a resource a bind group holds by handle**, so a new
9313 /// anisotropy is a new sampler, and every group of the mesh layout has to
9314 /// be rebuilt to name it. That happens per frame slot, at the slot's own
9315 /// `begin_frame`, which is the moment the ring guarantees the slot's
9316 /// previous submission has retired — the guarantee every host write in
9317 /// that call already leans on — so a frame in flight goes on naming the
9318 /// sampler it was recorded with, and the replaced sampler is destroyed once
9319 /// no slot names it. This call creates the sampler and nothing else, and
9320 /// asking for the anisotropy already in force creates nothing.
9321 ///
9322 /// # Errors
9323 ///
9324 /// `create_sampler`'s, and the renderer is unchanged — the sampler in force
9325 /// stays in force.
9326 pub fn set_anisotropy(&mut self, device: &dyn Device, anisotropy: f32) -> Result<(), HalError> {
9327 let caps = device.caps();
9328 let ceiling = if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9329 caps.limits.max_sampler_anisotropy
9330 } else {
9331 1.0
9332 };
9333 let wanted = if anisotropy.is_finite() {
9334 anisotropy.clamp(1.0, ceiling)
9335 } else {
9336 Self::anisotropy_for(&caps)
9337 };
9338 // Bit-equal rather than within an epsilon: both sides came out of the
9339 // same clamp, and a row that lands on the value in force must not
9340 // rebuild every group for it.
9341 if wanted.to_bits() == self.anisotropy.to_bits() {
9342 return Ok(());
9343 }
9344 let sampler = Self::create_page_sampler(device, wanted)?;
9345 self.retired_pages
9346 .push(RetiredPage::Sampler(std::mem::replace(
9347 &mut self.base_color_sampler,
9348 sampler,
9349 )));
9350 self.anisotropy = wanted;
9351 Ok(())
9352 }
9353
9354 /// The anisotropy in force, after the clamp
9355 /// [`set_anisotropy`](Self::set_anisotropy) applied.
9356 ///
9357 /// The read-back half, on [`render_scale`](Self::render_scale)'s terms.
9358 #[must_use]
9359 pub const fn anisotropy(&self) -> f32 {
9360 self.anisotropy
9361 }
9362
9363 /// The anisotropy the base-colour page's sampler is created with on a
9364 /// device of `caps`: [`DEFAULT_ANISOTROPY`] clamped to
9365 /// [`Limits::max_sampler_anisotropy`](crcbl_hal::Limits) where
9366 /// [`Features::SAMPLER_ANISOTROPY`] was granted, and `1.0` where it was
9367 /// not.
9368 ///
9369 /// **Granted, not supported.** The feature is optional at every open site
9370 /// — [`Features::GPU_DRIVEN`] does not carry it — and a device opened
9371 /// without asking refuses a sampler above one even on hardware that has
9372 /// it, which is the shape every backend's `create_sampler` documents. So
9373 /// the question is what this device was opened *with*, and a caller that
9374 /// wants the plan's default has to name the feature beside the others it
9375 /// asks for. `crcbl-webgpu` withholds the feature and reports a ceiling of
9376 /// one, so a browser samples isotropically until `docs/backlog.md`'s
9377 /// ceiling decision is taken.
9378 #[must_use]
9379 pub fn anisotropy_for(caps: &DeviceCaps) -> f32 {
9380 if caps.features.contains(Features::SAMPLER_ANISOTROPY) {
9381 DEFAULT_ANISOTROPY.min(caps.limits.max_sampler_anisotropy)
9382 } else {
9383 1.0
9384 }
9385 }
9386
9387 /// The base-colour page's sampler at `anisotropy`, which the caller has
9388 /// already held to the device — [`anisotropy_for`](Self::anisotropy_for)
9389 /// at build, [`set_anisotropy`](Self::set_anisotropy)'s clamp after.
9390 ///
9391 /// **Trilinear over the whole chain, anisotropic where the device is** —
9392 /// topic 43's filtering rung: a minified surface
9393 /// reads the level its footprint matches instead of shimmering through
9394 /// level 0, a magnified one blends four texels instead of stepping between
9395 /// them, and a surface at a grazing angle keeps its detail along the long
9396 /// axis of its footprint rather than blurring to the short one. A second
9397 /// sampler object rather than sharing the tonemap's, so a capture names
9398 /// each for what it filters.
9399 ///
9400 /// **`Repeat`, not `ClampToEdge`**, and that is what `mesh.slang`'s
9401 /// `TILING_PHYSICAL` needs: a physical UV runs to `world_extent /
9402 /// tile_metres`, past `0..1` on any face wider than one tile, and only a
9403 /// wrapping address mode makes the page tile across it rather than
9404 /// smearing its edge row. `TILING_AUTHORED` is unaffected — its UV is the
9405 /// vertex's, which the meshes author inside `0..1`, so a wrapped and a
9406 /// clamped read return the same nearest texel for it.
9407 fn create_page_sampler(
9408 device: &dyn Device,
9409 anisotropy: f32,
9410 ) -> Result<SamplerHandle, HalError> {
9411 device.create_sampler(&SamplerDesc {
9412 label: Some("material base colour"),
9413 mag_filter: FilterMode::Linear,
9414 min_filter: FilterMode::Linear,
9415 mip_filter: FilterMode::Linear,
9416 address_mode: [SamplerAddressMode::Repeat; 3],
9417 anisotropy,
9418 ..SamplerDesc::default()
9419 })
9420 }
9421
9422 /// The extent a frame handed `target` is actually drawn at.
9423 ///
9424 /// Rounds rather than truncates, and floors at one texel in each dimension:
9425 /// a zero here would reach a transient image description, and an image of
9426 /// zero extent is a device error rather than a small frame. A caller who
9427 /// minimised the window already hands a zero extent through, and that path
9428 /// is unchanged — `max(1)` on a zero is one either way.
9429 fn internal_extent(&self, target: (u32, u32)) -> (u32, u32) {
9430 if self.render_scale >= 1.0 {
9431 return target;
9432 }
9433 let scale = f64::from(self.render_scale);
9434 (
9435 ((f64::from(target.0) * scale).round() as u32).max(1),
9436 ((f64::from(target.1) * scale).round() as u32).max(1),
9437 )
9438 }
9439
9440 /// The exposure in force, after the clamp
9441 /// [`set_exposure`](Self::set_exposure) applied.
9442 ///
9443 /// The read-back half, on [`ground_grid`](Self::ground_grid)'s terms: what a
9444 /// caller wants is the number the frame is drawn with, not the one it asked
9445 /// for — which is also what makes a multiplicative step land on the end of
9446 /// the range rather than run past it.
9447 #[must_use]
9448 pub const fn exposure(&self) -> f32 {
9449 self.exposure
9450 }
9451
9452 /// Whether `device` can draw the wireframe view at all.
9453 ///
9454 /// The question [`set_wireframe`](Self::set_wireframe) answers with an
9455 /// error, asked **before** anything is switched on — so an application can
9456 /// tell its user that this device has no wireframe rather than binding a key
9457 /// that fails, and can say so once at start-up instead of on every press.
9458 /// WebGPU has no line fill mode at all, so the browser is the case this
9459 /// exists for and not a hypothetical.
9460 ///
9461 /// An associated function rather than a method: it is a fact about the
9462 /// device, and a caller wants it before it has decided anything.
9463 #[must_use]
9464 pub fn supports_wireframe(device: &dyn Device) -> bool {
9465 device.caps().supports(Features::POLYGON_MODE_LINE)
9466 }
9467
9468 /// Asks every camera's cull to drop what is hidden or too small to see —
9469 /// topic 03 §3.3's occlusion cull and its
9470 /// small-feature test. See [`crate::occlusion_cull`].
9471 ///
9472 /// [`OcclusionCulling::occlusion`] **changes no pixel**: the first phase
9473 /// guesses from the previous frame's depth, the second tests every rejected
9474 /// instance against this frame's, and only the second's rejections are
9475 /// dropped. [`OcclusionCulling::small_feature_pixels`] does change pixels,
9476 /// and is off unless a threshold is named.
9477 ///
9478 /// Taken from the next [`begin_frame`](Self::begin_frame), and combined with
9479 /// the `r_occlusion_cull` and `r_small_feature_px` console switches — either
9480 /// side turning a cull on turns it on. A wireframe frame culls by the frustum
9481 /// alone, because a wireframe shows the edges a depth test would hide.
9482 pub fn set_occlusion_culling(&mut self, culling: OcclusionCulling) {
9483 self.occlusion_culling = culling;
9484 }
9485
9486 /// Whether a point light's shadow cull tags each caster with the faces of
9487 /// its cube it reaches, so each face draws only those — **on** by default.
9488 ///
9489 /// Off is the cull this replaced: one test against the light's box, and
9490 /// every caster in it drawn into all six faces for the rasteriser to clip.
9491 /// The two write the same atlas, texel for texel — the six faces' pyramids
9492 /// tile the box, so a caster a face drops has no texel in that face's tile —
9493 /// and the switch exists so a test can hold them against each other and a
9494 /// price can be read off both.
9495 pub fn set_point_face_culls(&mut self, on: bool) {
9496 self.point_face_culls = on;
9497 }
9498
9499 /// **A test hook**: from the next [`begin_frame`](Self::begin_frame),
9500 /// rewrites every block the shadow atlas's depth pass is fed with `tamper`
9501 /// on its way to the GPU, or stops doing so with [`None`] — the default,
9502 /// and the only value a frame outside a test runs under.
9503 ///
9504 /// Applied **after** the atlas cache has read the blocks, so the rewrite is
9505 /// invisible to the decision whether to redraw a map and visible only to the
9506 /// depth pass that draws it. That is what makes it a probe of the shaders:
9507 /// `crcbl`'s `mesh_e2e` `shadow_block_reads` draws the atlas with each
9508 /// [`UniformsReader::ColourOnly`] entry of [`FRAME_UNIFORMS_READERS`]
9509 /// perturbed through here and holds the depth to the untampered frame's, bit
9510 /// for bit. It reaches the atlas's views alone — not the probe updater's
9511 /// shadows-off writes, which draw nothing into the atlas.
9512 pub fn set_shadow_view_tamper(&mut self, tamper: Option<fn(&mut mesh::FrameUniforms)>) {
9513 self.shadow_view_tamper = tamper;
9514 }
9515
9516 /// What [`set_occlusion_culling`](Self::set_occlusion_culling) last asked
9517 /// for, before the console switches and the wireframe are applied.
9518 #[must_use]
9519 pub const fn occlusion_culling(&self) -> OcclusionCulling {
9520 self.occlusion_culling
9521 }
9522
9523 /// The culls the next frame runs: [`occlusion_culling`](Self::occlusion_culling)
9524 /// with the console switches applied, and nothing on a wireframe frame.
9525 #[must_use]
9526 pub fn resolved_occlusion_culling(&self) -> OcclusionCulling {
9527 if self.wireframe_on {
9528 return OcclusionCulling::OFF;
9529 }
9530 let console_pixels = crate::occlusion_cull::r_small_feature_px.get_f32();
9531 OcclusionCulling {
9532 occlusion: self.occlusion_culling.occlusion
9533 || crate::occlusion_cull::r_occlusion_cull.get_bool(),
9534 small_feature_pixels: self
9535 .occlusion_culling
9536 .small_feature_pixels
9537 .or((console_pixels > 0.0).then_some(console_pixels)),
9538 }
9539 }
9540
9541 /// Draws the scene's triangles as lines, or goes back to filling them.
9542 ///
9543 /// **Off by default.** Every sample and every golden image predates the
9544 /// view, so a renderer nobody has called this on records exactly the frame
9545 /// it always did.
9546 ///
9547 /// # What it is, and what it is not
9548 ///
9549 /// The **colour pass** alone changes fill mode. The depth prepass and the
9550 /// shadow cascades keep drawing filled triangles, because they are what the
9551 /// occlusion pair and the shadow lookups read and depth drawn as lines is
9552 /// depth with holes in it. So a wireframe frame is the same geometry, the
9553 /// same shading and the same lights, rasterised as edges: what was inside a
9554 /// triangle becomes the clear colour, and what was on its edge stays lit.
9555 ///
9556 /// # It is built on the first `true`
9557 ///
9558 /// The pipeline is compiled here rather than beside the filled one at
9559 /// [`with_scene`](Self::with_scene), and that is the trade this
9560 /// call makes: one pipeline compile on the first press — a hitch, in a view
9561 /// the user just asked for — against a second compile in the start-up of
9562 /// every sample, golden run and headless test that never asks for one. Later
9563 /// calls only flip the switch, and a `false` leaves the pipeline built, for
9564 /// [`set_ground_grid`](Self::set_ground_grid)'s reason: releasing something
9565 /// the frames in flight may still be recording against is what
9566 /// [`destroy`](Self::destroy) — which already requires an idle device — is
9567 /// for.
9568 ///
9569 /// # Errors
9570 ///
9571 /// [`HalError::UnsupportedFeatures`] naming
9572 /// [`Features::POLYGON_MODE_LINE`](crcbl_hal::Features::POLYGON_MODE_LINE)
9573 /// when `on` is `true` on a device that has not got it — ask
9574 /// [`supports_wireframe`](Self::supports_wireframe) first. Refused rather
9575 /// than quietly filled: a caller who asked for a wireframe and got a solid
9576 /// frame back with no error has no way to tell that from a wireframe of a
9577 /// solid-looking model.
9578 ///
9579 /// [`HalError`] from the pipeline otherwise. **Nothing is left switched on
9580 /// when either happens**: the view stays as it was.
9581 pub fn set_wireframe(&mut self, device: &dyn Device, on: bool) -> Result<(), HalError> {
9582 if !on {
9583 self.wireframe_on = false;
9584 return Ok(());
9585 }
9586 if self.wireframe_pipeline.is_none() {
9587 if !Self::supports_wireframe(device) {
9588 return Err(HalError::UnsupportedFeatures {
9589 missing: Features::POLYGON_MODE_LINE,
9590 });
9591 }
9592 let modules = MeshModules::new(device, self.emit, self.culls_clusters)?;
9593 let [single, double] = MeshModules::sided(|cull| {
9594 modules.color_pipeline(
9595 device,
9596 self.mesh_pipeline_layout,
9597 PolygonMode::Line,
9598 cull,
9599 "wireframe",
9600 )
9601 });
9602 modules.destroy(device);
9603 // **Both or neither.** A caller that got one twin back would draw a
9604 // frame missing every double-sided surface and nothing would say
9605 // so; released here rather than kept, because `destroy` is what
9606 // releases what this field holds and it holds nothing yet.
9607 let pipelines = match (single, double) {
9608 (Ok(single), Ok(double)) => SidedPipelines { single, double },
9609 (Ok(built), Err(error)) | (Err(error), Ok(built)) => {
9610 device.destroy_graphics_pipeline(built);
9611 return Err(error);
9612 }
9613 (Err(error), Err(_)) => return Err(error),
9614 };
9615 self.wireframe_pipeline = Some(pipelines);
9616 }
9617 self.wireframe_on = true;
9618 Ok(())
9619 }
9620
9621 /// Whether the colour pass draws lines instead of filled triangles.
9622 ///
9623 /// The read-back half of [`set_wireframe`](Self::set_wireframe), and the
9624 /// observable a test asking "is this frame a wireframe" wants: a renderer
9625 /// that built the pipeline and then switched it off answers `false`, because
9626 /// what it draws is what the question is about.
9627 #[must_use]
9628 pub const fn wireframe(&self) -> bool {
9629 self.wireframe_on
9630 }
9631
9632 /// Draws each surface's **world-space** normal instead of shading it, so a
9633 /// modeller can see whether the normals a document carries are sane.
9634 ///
9635 /// **Off by default**, on [`set_wireframe`](Self::set_wireframe)'s terms: it
9636 /// is a tool's view of a document, and every sample and every golden image
9637 /// predates it. It takes effect on the next
9638 /// [`begin_frame`](Self::begin_frame), which is what writes the block.
9639 ///
9640 /// # What the colours mean
9641 ///
9642 /// The conventional encoding, `n * 0.5 + 0.5` into RGB: +X reads red, +Y
9643 /// green, +Z blue, and a face whose winding was inverted reads the
9644 /// **complement** of the colour it should have. A missing or degenerate
9645 /// normal reads as whatever the vertex data actually holds rather than as the
9646 /// plausible shading a light would have given it, which is the point.
9647 ///
9648 /// # World space, not view space
9649 ///
9650 /// The two diagnose different things and this one is world space, so a face
9651 /// keeps its colour while the camera orbits: "is this face inverted" is then
9652 /// something a modeller *sees*, instead of inferring it from a picture that
9653 /// re-colours whenever they move. View-space normals answer the other
9654 /// question — is this normal smooth, is this seam split — by re-colouring on
9655 /// purpose, and they are not a thing this block could express anyway: it
9656 /// carries `view_proj` and no separate view matrix, so there is no rotation in
9657 /// the shader to take a normal into eye space with.
9658 ///
9659 /// # It builds nothing and adds no pass
9660 ///
9661 /// Unlike the wireframe, which needs a second pipeline and so a device that
9662 /// can build one: this is one lane of the frame's uniform block — see
9663 /// [`FrameUniforms::NORMALS_VIEW_ON`] — read by a branch in the fragment
9664 /// stage every device already runs. There is nothing to refuse and nothing to
9665 /// release, which is why it cannot fail and there is no `supports_` probe
9666 /// beside it.
9667 ///
9668 /// The tonemap still applies: at
9669 /// [`DEFAULT_EXPOSURE`](crcbl_shaders::tonemap::DEFAULT_EXPOSURE) its operator
9670 /// is the identity on `0..=1` and the encoded normal reaches the swapchain
9671 /// exactly, and at any other exposure the picture is scaled per channel — so
9672 /// which channel dominates a face never changes, but a caller reading exact
9673 /// values wants [`set_exposure`](Self::set_exposure) left alone.
9674 ///
9675 /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
9676 pub const fn set_normals_view(&mut self, on: bool) {
9677 self.normals_view = on;
9678 }
9679
9680 /// Sets the exponential height fog the colour pass composites over every
9681 /// shaded surface.
9682 ///
9683 /// Topic 43 §4's cheapest large win: distance
9684 /// reads as distance, a valley fills while a hilltop stays clear, and it
9685 /// costs four numbers in a block every pipeline already binds.
9686 ///
9687 /// # It adds no pass and cannot fail
9688 ///
9689 /// On [`set_normals_view`](Self::set_normals_view)'s terms exactly — two
9690 /// rows of the frame's uniform block, read by arithmetic in the fragment
9691 /// stage every device already runs. There is nothing to build, so there is
9692 /// nothing to refuse and no `supports_` probe beside it.
9693 ///
9694 /// # Off is exactly off
9695 ///
9696 /// [`Fog::NONE`] is the default and a zero density is an *exact* identity,
9697 /// not an approximate one: the optical depth is zero, its transmittance is
9698 /// exactly one, and `mesh.slang` composites as `lit * t + fog * (1 - t)`
9699 /// rather than as a `lerp`, which at `t == 1` would return
9700 /// `fog + (lit - fog)` and lose the low bits of an HDR radiance far from
9701 /// the fog colour. So this feature moves no frame it is not switched on
9702 /// for.
9703 ///
9704 /// # What it does not fog
9705 ///
9706 /// The screen-space reflections `ssr_blur.slang` adds **after** this pass,
9707 /// which arrive unfogged onto an already-fogged surface — see
9708 /// `docs/backlog.md`. Fog is applied where the radiance is finished, and
9709 /// the reflection composite is one pass later.
9710 pub const fn set_fog(&mut self, fog: Fog) {
9711 self.fog = fog;
9712 }
9713
9714 /// Lights the scene with a gradient sky, on top of whatever ambient and
9715 /// irradiance grid it already has.
9716 ///
9717 /// Topic 43 §8's rung. [`Sky`] is three
9718 /// radiances — zenith, horizon, ground — and what reaches a surface is that
9719 /// gradient projected onto the L1 basis the probe grid already uses, so a
9720 /// surface facing up receives the sky and one facing down the ground's
9721 /// bounce. Three colours, no extra pass.
9722 ///
9723 /// # It adds no pass and cannot fail
9724 ///
9725 /// On [`set_fog`](Self::set_fog)'s terms exactly — three rows of the
9726 /// frame's uniform block and three dot products in a fragment stage every
9727 /// device already runs. Nothing to build, so nothing to refuse and no
9728 /// `supports_` probe beside it.
9729 ///
9730 /// # Off is exactly off
9731 ///
9732 /// [`Sky::NONE`] is the default and a black gradient projects to every
9733 /// coefficient zero — each is a product with a zero factor — so the
9734 /// fragment stage adds `max(0, 0)` and the ambient sum is the one it was
9735 /// before this existed, bit for bit.
9736 ///
9737 /// # What it does not do
9738 ///
9739 /// **Draw anything.** The background is still the scene target's clear
9740 /// colour, and a scene lit by a sky it cannot see is what this rung leaves
9741 /// behind until the pass that draws the gradient lands. The environment
9742 /// `ssr.slang` falls back to on a missed ray is still the probe grid's, so
9743 /// a mirror under a sky still reflects whatever the probes hold.
9744 pub const fn set_sky(&mut self, sky: Sky) {
9745 self.sky = sky;
9746 }
9747
9748 /// Replaces the gradient with Hillaire's atmosphere, or `None` to put the
9749 /// gradient back.
9750 ///
9751 /// Topic 43 §8. A frame with an atmosphere takes
9752 /// it for all three of the things a sky is: the background the sky pass
9753 /// draws, the L1 ambient term `mesh.slang` adds, and the environment
9754 /// `ssr.slang` falls back to when a ray hits nothing. The
9755 /// [`Sky`] a caller may also have set is not read on those frames.
9756 ///
9757 /// # What it costs
9758 ///
9759 /// **A march on the host, not on the device.** The first
9760 /// [`begin_frame`](Self::begin_frame) after this is called marches
9761 /// [`crcbl_shaders::atmosphere::SkyView`] whole, which is tens of
9762 /// milliseconds of CPU — a renderer with no LUT has no sky, so that one is
9763 /// paid where it is asked for. Every later move of the sun is marched
9764 /// [`SKY_VIEW_BUILD_ROWS`] rows per frame with the last finished LUT still
9765 /// drawn, so no frame after the first pays the whole march;
9766 /// `refresh_sky_view` is where that is written down, including what a sun
9767 /// that moves *every* frame gets. A frame whose
9768 /// sun has not moved costs the comparison that finds nothing to do and
9769 /// nothing else: the LUT's two projections are cached beside it. The device
9770 /// pays four buffer loads and a blend, which is what the gradient pays.
9771 ///
9772 /// # Off is exactly off
9773 ///
9774 /// `None` is the default, and a renderer nobody calls this on writes the
9775 /// same block, adds the same passes and draws the same frame it did before
9776 /// this existed — `sky.slang`'s arm is
9777 /// [`crcbl_shaders::sky::ATMOSPHERE_OFF`], which is exactly zero.
9778 ///
9779 /// # What it does not do
9780 ///
9781 /// **Draw the sun.** The LUT holds the scattered sky and not the disc, as
9782 /// the paper's does; the sun itself is the [`DirectionalLight`] the forward
9783 /// pass already shades with, and pointing the two the same way is the
9784 /// caller's job.
9785 ///
9786 /// **Put the air in front of a surface.** That is the paper's third LUT and
9787 /// this engine's froxel column, and neither reads this.
9788 pub fn set_atmosphere(&mut self, atmosphere: Option<Atmosphere>) {
9789 self.atmosphere = atmosphere;
9790 }
9791
9792 /// The bodies of water every view draws — `docs/plan/55-water.md`'s rung 1,
9793 /// and this crate's `water` module for how.
9794 ///
9795 /// Replaces whatever was set before. Each body is meshed here, by
9796 /// [`crcbl_water::surface_mesh`], and the result is uploaded to each frame
9797 /// slot as that slot next begins, so the call touches no device and a frame
9798 /// still in flight keeps the buffers it was submitted with.
9799 ///
9800 /// # Off is exactly off
9801 ///
9802 /// An empty slice is the default, and a renderer with no bodies records no
9803 /// water pass at all: the frame it draws is the one it drew before this
9804 /// existed, bit for bit. Water is content, not a
9805 /// [`RenderEffects`] bit, on [`set_sky`](Self::set_sky)'s terms.
9806 ///
9807 /// # Errors
9808 ///
9809 /// [`crcbl_water::BodyError`] for the first body that cannot be meshed —
9810 /// too few points, a non-finite coordinate, an outline that crosses itself,
9811 /// a negative coefficient — and then **nothing is replaced**: the bodies set
9812 /// before this call go on drawing.
9813 pub fn set_water(
9814 &mut self,
9815 bodies: &[crcbl_water::WaterBody],
9816 ) -> Result<(), crcbl_water::BodyError> {
9817 self.water.set(bodies)
9818 }
9819
9820 /// The bodies of water this renderer draws, as they were last set.
9821 #[must_use]
9822 pub fn water(&self) -> &[crcbl_water::WaterBody] {
9823 self.water.bodies()
9824 }
9825
9826 /// The field of grass every view draws — `docs/plan/57-grass.md`'s rungs G1
9827 /// and G3, and this crate's `grass` module for how.
9828 ///
9829 /// Replaces whatever was set before. The field's ground, cover map, blade
9830 /// table and per-tile blocks are uploaded here, and the buffers a dispatch
9831 /// writes are created here; a field replaced while a frame is in flight
9832 /// leaves its resources alive until the ring has come round, so the call is
9833 /// safe at any point between frames.
9834 ///
9835 /// # Off is exactly off
9836 ///
9837 /// [`None`] is the default, and a renderer with no field records no grass
9838 /// pass at all: the frame it draws is the one it drew before this existed,
9839 /// bit for bit. Grass is content, not a [`RenderEffects`] bit, on
9840 /// [`set_water`](Self::set_water)'s terms.
9841 ///
9842 /// # Errors
9843 ///
9844 /// [`crate::grass::SetError::Field`] for a description the field itself
9845 /// refuses — no tiles, a zero texel scale, an empty blade table — and then
9846 /// **nothing is replaced**: the field set before this call goes on drawing.
9847 /// [`crate::grass::SetError::Hal`] for a seam call that failed, on the same
9848 /// terms.
9849 pub fn set_grass(
9850 &mut self,
9851 device: &dyn Device,
9852 queue: QueueHandle,
9853 field: Option<&crate::grass::GrassField>,
9854 ) -> Result<(), crate::grass::SetError> {
9855 self.grass.set(device, queue, field)
9856 }
9857
9858 /// The field of grass this renderer draws, as it was last set.
9859 #[must_use]
9860 pub fn grass(&self) -> Option<&crate::grass::GrassField> {
9861 self.grass.field()
9862 }
9863
9864 /// The two buffers the grass generation pass writes, or [`None`] for a
9865 /// renderer with no field.
9866 ///
9867 /// What `crcbl`'s `render_e2e` copies back to check the placement blade by
9868 /// blade and to read each slot's instance count, on
9869 /// [`froxel_buffers`](Self::froxel_buffers)' terms — see
9870 /// [`crate::grass::GrassBuffers`] for the layout. They hold whatever the
9871 /// last frame that generated left there, which for a field nobody has drawn
9872 /// yet is undefined rather than empty.
9873 #[must_use]
9874 pub fn grass_buffers(&self) -> Option<crate::grass::GrassBuffers> {
9875 self.grass.buffers()
9876 }
9877
9878 /// The two authored wind layers `docs/plan/56-wind.md`'s decision 1 names,
9879 /// as the GPU copy of the field samples them.
9880 ///
9881 /// [`None`] restores the calm placeholder: one texel of no deflection and
9882 /// one of zero intensity, which is what makes a field with no weather set
9883 /// stand still. A replaced pair waits for the ring exactly as a replaced
9884 /// field does.
9885 ///
9886 /// # Errors
9887 ///
9888 /// [`crate::grass::WindLayerError`] for a layer that is not four bytes a
9889 /// texel of the grid it came with, or a seam call that failed.
9890 pub fn set_wind_layers(
9891 &mut self,
9892 device: &dyn Device,
9893 queue: QueueHandle,
9894 layers: Option<&crate::grass::WindLayers>,
9895 ) -> Result<(), crate::grass::WindLayerError> {
9896 self.grass.set_wind_layers(device, queue, layers)
9897 }
9898
9899 /// The wind's uniform block for the frames from here on —
9900 /// `crcbl_wind::WindField::gpu_params`, which is where the authoritative
9901 /// `f64` formula is narrowed to `f32`.
9902 ///
9903 /// Everything in it is camera-relative or already wrapped, so a caller
9904 /// writes it once per frame from the field's own state and never from a
9905 /// world-scale coordinate. The default is a base speed of zero, which is
9906 /// calm.
9907 pub const fn set_wind(&mut self, params: crcbl_shaders::wind::WindParams) {
9908 self.wind = params;
9909 }
9910
9911 /// The wind block this renderer writes, as it was last set.
9912 #[must_use]
9913 pub const fn wind(&self) -> crcbl_shaders::wind::WindParams {
9914 self.wind
9915 }
9916
9917 /// The atmosphere this renderer draws, if it has one.
9918 #[must_use]
9919 pub const fn atmosphere(&self) -> Option<Atmosphere> {
9920 self.atmosphere
9921 }
9922
9923 /// Draws each cluster tinted by the DAG level it was decimated to, instead
9924 /// of shading it.
9925 ///
9926 /// **The picture cluster LOD's whole claim rests on**: one mesh spanning
9927 /// several levels across its own surface is a statement a test can assert
9928 /// and nobody can see, and this is what makes it visible. The mesh path
9929 /// tints per cluster; the two indirect paths select one level per instance
9930 /// and have no per-cluster level at all, so they draw one flat grey — which
9931 /// is the comparison rather than a shortfall.
9932 ///
9933 /// Costs what [`set_normals_view`](Self::set_normals_view) costs: one lane
9934 /// of the frame's uniform block, read by a branch every device already runs.
9935 /// Nothing to build, nothing to refuse, nothing to release.
9936 ///
9937 /// **Wins over the normals view when both are on**, because the two share a
9938 /// lane and the fragment stage tests this one first.
9939 pub const fn set_lod_view(&mut self, on: bool) {
9940 self.lod_view = on;
9941 }
9942
9943 /// Whether the colour pass tints clusters by their DAG level.
9944 ///
9945 /// **What was asked for, not what is drawn.** The three debug views share
9946 /// one lane and resolve in one order, so a renderer with this and
9947 /// [`set_heatmap`](Self::set_heatmap) both on draws the heatmap and still
9948 /// answers `true` here — the caller's setting is what a caller's toggle has
9949 /// to read back, and [`debug_view`](Self::debug_view) is what says which one
9950 /// the frame actually took.
9951 #[must_use]
9952 pub const fn lod_view(&self) -> bool {
9953 self.lod_view
9954 }
9955
9956 /// Shades each cluster by the **projected screen-space error** the LOD
9957 /// selection judged it on, instead of shading it.
9958 ///
9959 /// The LOD tint's sibling, and the other half of topic 25's
9960 /// pair: [`set_lod_view`](Self::set_lod_view) answers "which level am I
9961 /// looking at", and this answers "how close to the budget is this, and where
9962 /// is the selection about to switch". The number is the one
9963 /// `draw_gen.slang`'s `group_is_expanded` compared against the budget — a
9964 /// cluster's *producing* group's error, projected from this frame's eye at
9965 /// this frame's pixels per unit.
9966 ///
9967 /// # What the colours mean
9968 ///
9969 /// A ramp that climbs in luminance from a cold floor to white, with a hue
9970 /// break at each of the two budgets: the hold budget where the hysteresis
9971 /// band starts, and the expand budget at the top, which is white. So the two
9972 /// budgets draw themselves as contour lines across the surface, and
9973 /// "brighter is closer to switching" reads even in a greyscale screenshot.
9974 /// `mesh_cluster.slang`'s `HEAT_UNDER_LOW` carries the ramp in full, and
9975 /// `crcbl_shaders`' `the_heatmap_ramp_climbs_in_luminance` is what holds it
9976 /// to being readable as an ordering.
9977 ///
9978 /// A cluster nothing simplified — the original surface, at the bottom of the
9979 /// DAG — costs exactly zero and takes the ramp's floor.
9980 ///
9981 /// # Mesh path only, and that is the capability rather than a shortfall
9982 ///
9983 /// A per-cluster error exists only where selection is per cluster.
9984 /// [`GeometryPath::IndirectCount`] and [`GeometryPath::IndirectPerBatch`]
9985 /// choose one level per *instance*, so there is no per-cluster number for
9986 /// them to shade by and `mesh.slang`'s vertex stage writes the same flat grey
9987 /// the LOD tint gets. Standing the two beside each other is the comparison.
9988 ///
9989 /// # It builds nothing and adds no pass
9990 ///
9991 /// One lane of the frame's uniform block, on
9992 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly — plus one
9993 /// storage-buffer read in the mesh stage, which the mesh path's layout
9994 /// already carries. Nothing to build, nothing to refuse, nothing to release.
9995 ///
9996 /// **Wins over both the LOD tint and the normals view when several are on**;
9997 /// see [`debug_view`](Self::debug_view), which is that order stated once.
9998 ///
9999 /// [`GeometryPath::IndirectCount`]: crcbl_hal::GeometryPath::IndirectCount
10000 /// [`GeometryPath::IndirectPerBatch`]: crcbl_hal::GeometryPath::IndirectPerBatch
10001 pub const fn set_heatmap(&mut self, on: bool) {
10002 self.heatmap = on;
10003 }
10004
10005 /// Whether the colour pass shades clusters by their projected error.
10006 ///
10007 /// **What was asked for, not what is drawn**, on
10008 /// [`lod_view`](Self::lod_view)'s terms.
10009 #[must_use]
10010 pub const fn heatmap(&self) -> bool {
10011 self.heatmap
10012 }
10013
10014 /// Draws the ambient-occlusion channel alone, as grey, instead of shading.
10015 ///
10016 /// One is white and fully occluded is black — the buffer the forward pass
10017 /// multiplies its ambient term by, shown as itself. **This is how the AO
10018 /// ladder — GTAO against the eight-tap hemisphere — is compared at all:** a
10019 /// composited frame shows occlusion times albedo times ambient, and a
10020 /// difference in the first is not separable from a difference in the other
10021 /// two by looking at the result.
10022 ///
10023 /// # What it draws with occlusion switched off
10024 ///
10025 /// White, everywhere. A frame without
10026 /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 white image in place of
10027 /// a computed channel, and this view shows that image rather than pretending
10028 /// to a channel nothing computed — "no occlusion was computed" and "nothing
10029 /// occludes here" are the same value to the shading, and the view does not
10030 /// get to disagree with the shading about it.
10031 ///
10032 /// # It builds nothing and adds no pass
10033 ///
10034 /// One lane of the frame's uniform block, on
10035 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly. Unlike the
10036 /// tint and the heatmap it needs nothing from the geometry stage, so it
10037 /// draws on every [`GeometryPath`] rather than on
10038 /// the mesh-shader one alone.
10039 ///
10040 /// **Wins over every other view when several are on**; see
10041 /// [`debug_view`](Self::debug_view), which is that order stated once.
10042 pub const fn set_occlusion_view(&mut self, on: bool) {
10043 self.occlusion_view = on;
10044 }
10045
10046 /// Whether the colour pass draws the occlusion channel instead of shading.
10047 ///
10048 /// **What was asked for, not what is drawn**, on
10049 /// [`lod_view`](Self::lod_view)'s terms.
10050 #[must_use]
10051 pub const fn occlusion_view(&self) -> bool {
10052 self.occlusion_view
10053 }
10054
10055 /// Draws each fragment's motion vector instead of shading it.
10056 ///
10057 /// The two components are stretched by
10058 /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) and centred
10059 /// on grey, into red and green, with blue left at zero. A pixel at rest is
10060 /// grey in both channels to within one half-float step —
10061 /// [`MOTION_VIEW_SCALE`](crcbl_shaders::mesh::MOTION_VIEW_SCALE) says why
10062 /// not exactly — and a surface travelling right and down the screen
10063 /// brightens both.
10064 ///
10065 /// # It is the motion-vector target's only reader today
10066 ///
10067 /// The forward pass writes a motion vector into a third colour attachment on
10068 /// every frame — see [`crate::targets::motion`] — and no pass reads it
10069 /// yet; TAA (`docs/backlog.md`) is the first that will. This
10070 /// view is therefore what says the subtraction behind it is the right one,
10071 /// which is why it exists ahead of a consumer.
10072 ///
10073 /// # It builds nothing and adds no pass
10074 ///
10075 /// One lane of the frame's uniform block, on
10076 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10077 /// the occlusion view it needs nothing from the geometry stage that a
10078 /// shaded frame does not already produce — so it draws on every
10079 /// [`GeometryPath`].
10080 ///
10081 /// **Wins over every other view when several are on**; see
10082 /// [`debug_view`](Self::debug_view), which is that order stated once.
10083 pub const fn set_motion_view(&mut self, on: bool) {
10084 self.motion_view = on;
10085 }
10086
10087 /// Whether the colour pass draws the motion vector instead of shading.
10088 ///
10089 /// **What was asked for, not what is drawn**, on
10090 /// [`lod_view`](Self::lod_view)'s terms.
10091 #[must_use]
10092 pub const fn motion_view(&self) -> bool {
10093 self.motion_view
10094 }
10095
10096 /// Draws the occlusion channel's **bent direction** instead of shading.
10097 ///
10098 /// The three channels beside the visibility scalar, passed through as the
10099 /// colour: the conventional `n * 0.5 + 0.5`, so +X reads red, +Y green and
10100 /// +Z blue, which is the mapping
10101 /// [`set_normals_view`](Self::set_normals_view) already uses for a surface
10102 /// normal. A fragment the occlusion pass had no direction for reads as the
10103 /// mid grey the zero sentinel encodes to.
10104 ///
10105 /// # What it is for
10106 ///
10107 /// The bent direction is what the ambient term is sampled *along*, and a
10108 /// composited frame cannot show it: ambient times albedo times a
10109 /// direction-dependent irradiance is one colour, and a direction that is
10110 /// subtly wrong looks like a lighting choice. This draws the direction
10111 /// alone, which is how a corner that leans the wrong way out of its own
10112 /// wall is a thing a reviewer sees rather than infers.
10113 ///
10114 /// # What it draws with occlusion switched off
10115 ///
10116 /// Mid grey, everywhere. A frame without
10117 /// [`RenderEffects::AMBIENT_OCCLUSION`] binds a 1×1 placeholder holding
10118 /// [`BENT_NORMAL_NONE`](crcbl_shaders::ssao::BENT_NORMAL_NONE) in those
10119 /// three channels, and this view shows that image rather than pretending to
10120 /// a direction nothing computed — which is the same answer the shading
10121 /// takes, since `mesh.slang` reads that sentinel as "use the shading
10122 /// normal".
10123 ///
10124 /// # It builds nothing and adds no pass
10125 ///
10126 /// One lane of the frame's uniform block, on
10127 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10128 /// the occlusion view it needs nothing from the geometry stage — so it
10129 /// draws on every [`GeometryPath`].
10130 ///
10131 /// **Wins over every other view when several are on**; see
10132 /// [`debug_view`](Self::debug_view), which is that order stated once.
10133 pub const fn set_bent_normal_view(&mut self, on: bool) {
10134 self.bent_normal_view = on;
10135 }
10136
10137 /// Whether the colour pass draws the bent direction instead of shading.
10138 ///
10139 /// **What was asked for, not what is drawn**, on
10140 /// [`lod_view`](Self::lod_view)'s terms.
10141 #[must_use]
10142 pub const fn bent_normal_view(&self) -> bool {
10143 self.bent_normal_view
10144 }
10145
10146 /// Tints the shaded picture by the **cascade** each sun-lit fragment's
10147 /// shadow was sampled from.
10148 ///
10149 /// Topic 45's eighth decision made the cascade switch a
10150 /// band rather than a step, and this is the picture that band is judged in:
10151 /// each fragment's shading multiplied by
10152 /// [`CASCADE_TINTS`](crcbl_shaders::mesh::CASCADE_TINTS) of the cascade it
10153 /// selected, and inside the band by the *blend* of the two — the same weight
10154 /// the visibility itself was mixed with. So the boundary reads as a
10155 /// gradient, and a seam where two cascades disagree shows up as a step in
10156 /// the gradient rather than as a ring somebody has to already suspect.
10157 ///
10158 /// # It keeps the shaded picture, which is why it loses to every other view
10159 ///
10160 /// Every other view replaces the frame; this one multiplies it, so the geometry
10161 /// stays readable underneath and the shadow the cascades produced is still
10162 /// in the picture being coloured. That is also what puts it last in
10163 /// [`debug_view`](Self::debug_view)'s order: with a replacing view on there
10164 /// is no shading left for a tint to reach.
10165 ///
10166 /// # What it draws where no cascade covers a fragment
10167 ///
10168 /// Nothing at all —
10169 /// [`CASCADE_TINT_NONE`](crcbl_shaders::mesh::CASCADE_TINT_NONE) is white.
10170 /// A surface facing away from the sun and one past the last cascade's reach
10171 /// are both that, because neither was sampled through a cascade, and a
10172 /// frame drawn without [`RenderEffects::SHADOWS`](crate::RenderEffects::SHADOWS) is
10173 /// white everywhere for the same reason. Colouring those would be inventing
10174 /// a cascade for a pixel no map covers.
10175 ///
10176 /// # It builds nothing and adds no pass
10177 ///
10178 /// One lane of the frame's uniform block, on
10179 /// [`set_normals_view`](Self::set_normals_view)'s terms exactly, and like
10180 /// the occlusion view it needs nothing from the geometry stage — so it draws
10181 /// on every [`GeometryPath`].
10182 pub const fn set_cascade_view(&mut self, on: bool) {
10183 self.cascade_view = on;
10184 }
10185
10186 /// Whether the colour pass tints the picture by the sun's cascades.
10187 ///
10188 /// **What was asked for, not what is drawn**, on
10189 /// [`lod_view`](Self::lod_view)'s terms — and here that gap is the usual
10190 /// case rather than the corner one: this view loses to every other one, so a
10191 /// renderer with any of them also on answers `true` here and draws that one.
10192 #[must_use]
10193 pub const fn cascade_view(&self) -> bool {
10194 self.cascade_view
10195 }
10196
10197 /// Draws the **shadow atlas itself** over the finished frame: the
10198 /// `D32Float` image `crate::shadow` budgets, letterboxed at its own aspect,
10199 /// each texel's stored depth as a grey and a border round every occupied
10200 /// slot.
10201 ///
10202 /// Sundial's atlas viewer, and the answer to a
10203 /// question no other view can be asked: which slot holds which map, and
10204 /// which slots hold nothing. A tile that was never rendered into, or
10205 /// rendered at the wrong viewport, lights a scene *fully* — so the frame it
10206 /// produces is plausible and every golden blessed from it passes. Here it is
10207 /// a rectangle that is visibly empty.
10208 ///
10209 /// # It is a pass, and it is the only debug view that is
10210 ///
10211 /// Every other view rides in one lane of the frame's uniform block and is a
10212 /// branch in `mesh.slang`, because every other view is a function of the
10213 /// fragment being shaded. The atlas is not: it is one image the whole frame
10214 /// shares. So this switch adds `crate::atlas_view`'s full-screen pass to
10215 /// the frame instead — after the tonemap, in display space, for that
10216 /// module's reason — and the frame block is byte-identical either way.
10217 ///
10218 /// # Where it resolves, and what it costs when it is off
10219 ///
10220 /// Below every replacing view and above
10221 /// [`set_cascade_view`](Self::set_cascade_view)'s tint — see
10222 /// [`debug_view`](Self::debug_view), which is that order stated once. A
10223 /// frame that resolved anything else records **no pass**, no pipeline bind
10224 /// and no block read, which is what makes the off position bit-identical on
10225 /// `crate::sky_pass`'s terms.
10226 pub const fn set_atlas_view(&mut self, on: bool) {
10227 self.atlas_view = on;
10228 }
10229
10230 /// Whether the frame draws the shadow atlas over the picture.
10231 ///
10232 /// **What was asked for, not what is drawn**, on
10233 /// [`lod_view`](Self::lod_view)'s terms: a renderer with a replacing view
10234 /// also on answers `true` here and draws that one.
10235 #[must_use]
10236 pub const fn atlas_view(&self) -> bool {
10237 self.atlas_view
10238 }
10239
10240 /// Pins the eye topic 25's selection is projected from, so the
10241 /// cut stops following the camera.
10242 ///
10243 /// [`None`] is the default and means "the camera's own eye", which is what
10244 /// every frame before this existed did. `Some(eye)` selects detail for a
10245 /// viewer standing at `eye` while the frame is still drawn, culled and lit
10246 /// from wherever the camera actually is.
10247 ///
10248 /// # What it is for
10249 ///
10250 /// Per-cluster LOD is only checkable from somewhere other than the point
10251 /// that chose it. Looked at from the selecting eye, a cut that is far too
10252 /// coarse and a cut that is exactly right produce the same silhouette —
10253 /// that is what a screen-space error budget *means* — so the one viewpoint
10254 /// where a wrong cut cannot be seen is the viewpoint every unfrozen frame is
10255 /// judged from. Pin the eye and fly away from it, and the boundaries between
10256 /// levels become geometry a reviewer can walk up to and look at edge-on.
10257 ///
10258 /// # Only the selection freezes
10259 ///
10260 /// The frame has three places a viewer position is read, and this moves
10261 /// exactly one of them:
10262 ///
10263 /// * **the selection** — `draw_gen.slang`'s `select_level`, which reads
10264 /// `DrawGenParams::camera_position` and is the only thing that decides the
10265 /// cut. It writes the group hysteresis state that the mesh path's
10266 /// amplification stage then descends, so freezing this one field freezes
10267 /// the cut on the per-cluster path and the two indirect paths alike. This
10268 /// is what moves.
10269 /// * **the frustum culls** — `cull.slang`'s instance test and
10270 /// `mesh_cluster.slang`'s per-cluster one, whose planes are extracted from
10271 /// the frame's own view-projection and never read a camera position at
10272 /// all. Unaffected, and it has to be: a frame culled against a frustum the
10273 /// reviewer has flown out of would draw nothing.
10274 /// * **the normal cone** — `mesh_cluster.slang`'s `cluster_survives`, which
10275 /// reads [`FrameUniforms::camera_position`] and asks which way a cluster
10276 /// faces *relative to the viewer*. That question is about the eye the
10277 /// picture is drawn from, not the eye it was selected for; frozen, a
10278 /// reviewer who flew round to the other side of the face would have every
10279 /// cluster now facing them rejected for facing away from a viewpoint
10280 /// nobody is standing at. It stays live.
10281 ///
10282 /// The split is not new. `DrawGenParams::camera_position` and
10283 /// [`FrameUniforms::camera_position`] are already separate fields carrying
10284 /// different values on a shadow cascade — that one holds the sun while this
10285 /// one stays the camera, because detail is denominated in the camera's
10286 /// pixels and facing is asked about the light. This freezes the same seam
10287 /// from the other side, and needs no new binding, no new shader input and no
10288 /// shader change of any kind.
10289 ///
10290 /// # It freezes the cascades' selection too
10291 ///
10292 /// [`begin_frame`](Self::begin_frame) hands the same eye to every shadow
10293 /// cascade's draw generator, because a cascade selects detail for the
10294 /// *camera* — see [`SHADOW_LOD_BIAS`]. A frozen camera cut over a live
10295 /// shadow cut would be a shadow silhouette sliding under a fixed one, which
10296 /// is a difference in the picture that belongs to neither.
10297 ///
10298 /// # The heatmap reads the live eye, and says so
10299 ///
10300 /// [`set_heatmap`](Self::set_heatmap) shades a cluster by its producing
10301 /// group's projected error, computed in the mesh stage from
10302 /// [`FrameUniforms::camera_position`] — the eye that stays live. So under a
10303 /// frozen selection the two overlays answer different questions: the cut is
10304 /// the one chosen at the pinned eye, and the heat is what the error would be
10305 /// if it were chosen from here now. That is readable — flying towards the
10306 /// face brightens the clusters the frozen cut is not refining, which is the
10307 /// selection's sensitivity made visible — but it does mean the ramp's
10308 /// contours stop coinciding with the level boundaries while frozen.
10309 /// [`set_lod_view`](Self::set_lod_view) is the overlay that composes
10310 /// unconditionally: a cluster's level is a property of the cut and of
10311 /// nothing else.
10312 ///
10313 /// Carrying the pinned eye into the mesh stage as well would need a second
10314 /// position in the frame block, which is a new shader input in every backend
10315 /// for one overlay's benefit; `docs/backlog.md` holds that trade-off.
10316 ///
10317 /// [`FrameUniforms::camera_position`]: crcbl_shaders::mesh::FrameUniforms::camera_position
10318 pub const fn set_frozen_selection_eye(&mut self, eye: Option<Vec3>) {
10319 self.frozen_selection_eye = eye;
10320 }
10321
10322 /// Where the selection is pinned, or [`None`] while it follows the camera.
10323 ///
10324 /// The read-back half of
10325 /// [`set_frozen_selection_eye`](Self::set_frozen_selection_eye), and what a
10326 /// debug panel says "frozen at" out of — "frozen" without the position is a
10327 /// row nobody can act on.
10328 #[must_use]
10329 pub const fn frozen_selection_eye(&self) -> Option<Vec3> {
10330 self.frozen_selection_eye
10331 }
10332
10333 /// Which of the debug views the next frame will actually draw.
10334 ///
10335 /// **The one place the precedence is decided**, and every other statement of
10336 /// it in this crate reads it back from here. The switches ride in one float
10337 /// lane of the frame block — see
10338 /// [`FrameUniforms::HEATMAP_VIEW_ON`](crcbl_shaders::mesh::FrameUniforms::HEATMAP_VIEW_ON)
10339 /// — and the shaders test the outermost threshold first, so a sentinel for
10340 /// an outer view clears every threshold below it. Resolving here rather than
10341 /// letting each caller guess is what stops "which view is on" being answered
10342 /// differently by a menu row, a debug panel and the picture.
10343 #[must_use]
10344 pub const fn debug_view(&self) -> DebugView {
10345 if self.bent_normal_view {
10346 DebugView::BentNormal
10347 } else if self.motion_view {
10348 DebugView::Motion
10349 } else if self.occlusion_view {
10350 DebugView::AmbientOcclusion
10351 } else if self.heatmap {
10352 DebugView::Heatmap
10353 } else if self.lod_view {
10354 DebugView::LodTint
10355 } else if self.normals_view {
10356 DebugView::Normals
10357 } else if self.atlas_view {
10358 // **Below every view above it, and above the tint below.**
10359 //
10360 // Below, because every branch before this one is a question about
10361 // the *picture* — a cluster's error, a surface's normal, the
10362 // occlusion channel — and this one is not a picture of the scene at
10363 // all. A caller who left the atlas up and then asked for normals has
10364 // asked to look at the frame again, and the frame is what the branch
10365 // above draws; the atlas is one keystroke away and is not lost by
10366 // being deferred to.
10367 //
10368 // Above, because the cascade tint multiplies the shaded picture and
10369 // this replaces it: a tint on a frame the atlas overwrote would be a
10370 // tint on the atlas, which is a colour standing for nothing.
10371 DebugView::ShadowAtlas
10372 } else if self.cascade_view {
10373 // **Innermost, and the only view that sits below the others rather
10374 // than above them.** Every branch before this one draws something
10375 // *instead of* the shaded picture and returns before the shading; a
10376 // cascade tint is a multiply on that shading, so there is nothing
10377 // for it to modulate while one of them is showing and a caller with
10378 // both on has asked for the picture the outer one draws. The lane
10379 // says the same thing from the other end — the cascade sentinel is
10380 // negative, so it clears none of the shaders' thresholds — and
10381 // `crcbl_shaders`'
10382 // `the_cascade_view_threshold_lies_below_every_replacing_view` is
10383 // what holds that half.
10384 DebugView::Cascades
10385 } else {
10386 DebugView::Shaded
10387 }
10388 }
10389
10390 /// [`debug_view`](Self::debug_view) as the value the frame block's lane
10391 /// carries.
10392 const fn debug_view_lane(&self) -> f32 {
10393 match self.debug_view() {
10394 DebugView::BentNormal => mesh::FrameUniforms::BENT_NORMAL_VIEW_ON,
10395 DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
10396 DebugView::AmbientOcclusion => mesh::FrameUniforms::OCCLUSION_VIEW_ON,
10397 DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
10398 DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
10399 DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
10400 DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
10401 // **The off sentinel, and it is not an omission.** This view is a
10402 // pass rather than a branch in `mesh.slang` — see
10403 // [`crate::atlas_view`] — so the colour pass draws exactly the
10404 // shaded picture it always drew and the pass afterwards replaces it.
10405 // A lane of its own would be a threshold no shader tests.
10406 DebugView::ShadowAtlas | DebugView::Shaded => mesh::FrameUniforms::NORMALS_VIEW_OFF,
10407 }
10408 }
10409
10410 /// Whether the colour pass draws world-space normals instead of shading.
10411 ///
10412 /// The read-back half of [`set_normals_view`](Self::set_normals_view), on
10413 /// [`wireframe`](Self::wireframe)'s terms: what it draws is what the question
10414 /// is about.
10415 #[must_use]
10416 pub const fn normals_view(&self) -> bool {
10417 self.normals_view
10418 }
10419
10420 /// The cull and draw-argument passes, and the buffers they produce.
10421 ///
10422 /// What a caller reads the culling statistics out of — topic 03 §3.6's
10423 /// delayed readback ring is [`DrawGen::visible_count`] — and what
10424 /// `crcbl-vk`'s end-to-end suite copies back to check the generated
10425 /// arguments against the draws this pass used to record itself.
10426 #[must_use]
10427 pub const fn draws(&self) -> &DrawGen {
10428 &self.primary.draws
10429 }
10430
10431 /// `frame`'s auto-exposure measurement: the bins the histogram pass filled
10432 /// and the exposure the reduce wrote out of them.
10433 ///
10434 /// What `crcbl`'s `mesh_e2e` copies back to check the histogram bin by bin
10435 /// against `crcbl_shaders::exposure`, on [`draws`](Self::draws)' terms — see
10436 /// [`ExposureBuffers`]. Both hold whatever the last frame that measured left
10437 /// there, so a frame drawn without
10438 /// [`RenderEffects::AUTO_EXPOSURE`](crate::RenderEffects::AUTO_EXPOSURE)
10439 /// hands back the frame before it rather than nothing.
10440 ///
10441 /// # Panics
10442 ///
10443 /// If `frame` is not a slot this renderer was built with.
10444 #[must_use]
10445 pub fn exposure_buffers(&self, frame: usize) -> ExposureBuffers {
10446 self.primary.auto_exposure.buffers(frame)
10447 }
10448
10449 /// `frame`'s froxel column: the buffers the froxel volume's
10450 /// three passes write, and the block they read.
10451 ///
10452 /// What `crcbl`'s `mesh_e2e` copies back to check the column froxel by
10453 /// froxel against `crcbl_shaders::volumetric`, on
10454 /// [`draws`](Self::draws)' terms — see [`FroxelBuffers`].
10455 ///
10456 /// # Panics
10457 ///
10458 /// If `frame` is not a slot this renderer was built with.
10459 #[must_use]
10460 pub fn froxel_buffers(&self, frame: usize) -> FroxelBuffers {
10461 self.primary.volumetric.buffers(frame)
10462 }
10463
10464 /// The three layers a caller supplies to the toggle resolution order — see
10465 /// [`crate::effects`].
10466 ///
10467 /// Read back rather than only written, so a caller changing one layer does
10468 /// not have to remember the other two: take this, edit the field it owns,
10469 /// hand it back to [`set_effect_request`](Self::set_effect_request).
10470 #[must_use]
10471 pub const fn effect_request(&self) -> EffectRequest {
10472 self.effect_request
10473 }
10474
10475 /// Replaces all three requested layers, and resolves them at the next
10476 /// [`begin_frame`](Self::begin_frame).
10477 ///
10478 /// **The frame in flight does not move.** `begin_frame` freezes what it
10479 /// resolved and [`add_passes`](Self::add_passes) records that, because the
10480 /// two halves of a frame have to agree about which culls were parametrised:
10481 /// `begin_frame` skips a shadow cull's parameter write when shadows are off
10482 /// and `add_passes` skips its dispatch, and a request landing between the two
10483 /// would dispatch a cull against numbers nothing zeroed.
10484 pub const fn set_effect_request(&mut self, request: EffectRequest) {
10485 self.effect_request = request;
10486 }
10487
10488 /// Replaces the **camera** layer with what `stack` asks for, and leaves the
10489 /// other three where they are.
10490 ///
10491 /// The file half of [`crate::stack`] reaching the renderer: a view that has
10492 /// a render stack writes it here, and the player's `[engine.video]` clamp,
10493 /// the antialiasing rung they picked and any programmatic override are
10494 /// untouched — which is the property that makes the four layers four rather
10495 /// than one. A caller that wants to move more than this layer builds an
10496 /// [`EffectRequest`] and uses
10497 /// [`set_effect_request`](Self::set_effect_request).
10498 ///
10499 /// **The frame in flight does not move**, on `set_effect_request`'s terms
10500 /// and for its reason: this writes the request and
10501 /// [`begin_frame`](Self::begin_frame) is what resolves it.
10502 pub const fn set_camera_stack(&mut self, stack: &CameraStack) {
10503 self.effect_request.camera = stack.compile();
10504 }
10505
10506 /// What the frame the last [`begin_frame`](Self::begin_frame) opened draws.
10507 ///
10508 /// The resolved set, not a layer: every effect in it has survived the
10509 /// camera's stack, the player's quality clamp, any programmatic override and
10510 /// the device — which is the one question a test asking "did this frame have
10511 /// shadows in it" wants answered.
10512 ///
10513 /// [`RenderEffects::all`] before the first frame, which is what a renderer
10514 /// nobody has changed would draw.
10515 #[must_use]
10516 pub const fn effects(&self) -> RenderEffects {
10517 self.frame_effects
10518 }
10519
10520 /// What a frame begun **now** would draw: the whole order applied to the
10521 /// current request.
10522 ///
10523 /// [`effects`](Self::effects)' question one frame earlier, and the one a
10524 /// caller reporting its own configuration wants — a debug panel built at
10525 /// startup has no frame behind it yet, and printing what the last one drew
10526 /// would print a default.
10527 ///
10528 /// **A debug view takes the antialiasing resolve off** — either tier of it
10529 /// — whatever the four layers said. Those views are readouts rather than
10530 /// pictures — a pixel's colour *is* the cluster's projected error or its
10531 /// DAG level, read back against a legend — and a filter that blends two
10532 /// clusters' shades invents a ramp position no cluster occupies.
10533 /// `apps/quarry`'s heatmap and LOD tests are the consumers that count a
10534 /// frame's distinct colours.
10535 #[must_use]
10536 pub fn resolved_effects(&self) -> RenderEffects {
10537 let resolved = self.effect_request.resolve(self.device_effects);
10538 if matches!(self.debug_view(), DebugView::Shaded) {
10539 resolved
10540 } else {
10541 // **Both tiers**, because the slot is what a readout cannot have
10542 // rather than one filter in particular.
10543 resolved.difference(RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2))
10544 }
10545 }
10546
10547 /// Which tonemap operator the next frame runs:
10548 /// [`tonemap_curve`](Self::tonemap_curve)'s answer for a shaded frame, and
10549 /// the clamp for a readout.
10550 ///
10551 /// **[`resolved_effects`](Self::resolved_effects)' argument, applied to the
10552 /// operator instead of to the resolve.** A debug view's pixels *are* data —
10553 /// an encoded normal, an occlusion channel, a cascade's colour code — and a
10554 /// curve is a monotone remapping of every one of them. `apps/alcove`'s
10555 /// `--bent-view` reads a normal back and compares it against the geometry's
10556 /// own, which under ACES is 49 code values out; the clamp is the identity on
10557 /// `0..=1`, so it is the operator that leaves a readout readable. A caller
10558 /// that wants a curved readout has none, deliberately: there is no reading
10559 /// it would make easier.
10560 #[must_use]
10561 pub const fn resolved_tonemap_curve(&self) -> tonemap::TonemapCurve {
10562 if matches!(self.debug_view(), DebugView::Shaded) {
10563 self.tonemap_curve
10564 } else {
10565 tonemap::TonemapCurve::Clamp
10566 }
10567 }
10568
10569 /// Which effects this **device** permits, which is the fourth layer and
10570 /// clamps last.
10571 ///
10572 /// Every one of them today — see [`ForwardRenderer::device_effects`], which
10573 /// is where that is argued per effect rather than asserted.
10574 #[must_use]
10575 pub const fn device_effects(&self) -> RenderEffects {
10576 self.device_effects
10577 }
10578
10579 /// Which [`GeometryPath`] this renderer was **built for** — not what the
10580 /// device reports, but what it actually built.
10581 ///
10582 /// The device may prefer a path below its capability ceiling when a higher
10583 /// one uses emulation. This reports the preference actually built, rather
10584 /// than the ceiling: [`GeometryPath::MeshShader`] here means
10585 /// `build` created a mesh pipeline out of `mesh_cluster.slang` and its
10586 /// cluster buffers, and created **no** raster pipeline for the pass to fall
10587 /// back to. So a frame this renderer drew came out of a mesh stage, and a
10588 /// silent degradation is not a state it has — which is the claim a golden
10589 /// image on its own could never make, because a fall-through draws the same
10590 /// picture.
10591 #[must_use]
10592 pub const fn geometry_path(&self) -> GeometryPath {
10593 match self.emit {
10594 EmitTail::Mesh => GeometryPath::MeshShader,
10595 EmitTail::Count => GeometryPath::IndirectCount,
10596 EmitTail::PerBatch => GeometryPath::IndirectPerBatch,
10597 }
10598 }
10599
10600 /// Whether this renderer **built** §3.5's per-cluster cull — an
10601 /// amplification stage in front of the mesh stage, rejecting a surviving
10602 /// instance's back-facing and off-screen clusters.
10603 ///
10604 /// `false` on the two indirect tails, which draw index ranges and have no
10605 /// stage to put it in, and on a device with `Features::MESH_SHADER` and no
10606 /// `Features::TASK_SHADER` — a real and supported state, not a degradation:
10607 /// that device draws every cluster of every surviving instance and the
10608 /// picture is the same one.
10609 ///
10610 /// The instance cull runs on every path either way, and is unaffected by
10611 /// this.
10612 ///
10613 /// It is asked of the renderer rather than of the device for
10614 /// [`ForwardRenderer::geometry_path`]'s reason: this reports what was
10615 /// built, so `true` means
10616 /// [`DrawGen::visible_count`](crate::draw_gen::DrawGen::visible_count)'s
10617 /// cluster word is a number the frame produced rather than the zero the
10618 /// clearing pass left.
10619 #[must_use]
10620 pub const fn culls_clusters(&self) -> bool {
10621 self.culls_clusters
10622 }
10623
10624 /// Whether this renderer can choose **which level** of a
10625 /// [`Geometry::Dag`] mesh an object is drawn at, and therefore whether
10626 /// [`ForwardRenderer::add_instance`] may be given one at all.
10627 ///
10628 /// Topic 25's selection happens in the amplification stage where
10629 /// there is one, and in the cull pass where the tail is indirect and a level
10630 /// is an ordinary index range. **One device shape has neither**: a mesh stage
10631 /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10632 /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) draws through
10633 /// `mesh_cluster.slang`'s un-amplified `meshMain`, which emits every cluster
10634 /// of the bucket — and a DAG's bucket is every level end to end, so the frame
10635 /// is several overlapping copies of one surface. That is a real and supported
10636 /// device state rather than a degradation, so this reports it instead of
10637 /// refusing to build.
10638 ///
10639 /// A [`Geometry::Flat`] mesh is one level and is unaffected: its clusters
10640 /// carry [`ClusterSelect::ALWAYS`] and every path draws it from every camera,
10641 /// which is why this is asked only before placing a DAG.
10642 ///
10643 /// Asked of the renderer rather than of the device for
10644 /// [`ForwardRenderer::culls_clusters`]' reason: it reports what was built.
10645 ///
10646 /// [`ClusterSelect::ALWAYS`]: crcbl_shaders::cluster_select::ClusterSelect::ALWAYS
10647 #[must_use]
10648 pub const fn selects_levels(&self) -> bool {
10649 !self.emit.is_mesh() || self.culls_clusters
10650 }
10651
10652 /// Which frame-in-flight slot the last [`ForwardRenderer::begin_frame`]
10653 /// rotated to, which is the slot every per-frame buffer is indexed by.
10654 #[must_use]
10655 pub const fn frame(&self) -> usize {
10656 self.frame
10657 }
10658
10659 /// What the last [`add_passes`](Self::add_passes) recorded, and what it
10660 /// cannot know.
10661 ///
10662 /// Zero draws until a frame has been built: this reports what was recorded,
10663 /// not what a frame would record.
10664 ///
10665 /// # The triangles are [`None`] here, on every geometry path
10666 ///
10667 /// Every draw this renderer records except the full-screen passes' and the
10668 /// debug draw layer's is **indirect**:
10669 /// the instance count and the index range live in the argument buffer
10670 /// `draw_gen.slang` wrote, so the CPU records the call and learns nothing
10671 /// about what it covered. That is true of
10672 /// [`GeometryPath::MeshShader`] and of
10673 /// both indirect tails alike — the three differ in which call is recorded,
10674 /// not in who decides the counts — so
10675 /// [`FrameCounters::triangles`](crate::counters::FrameCounters::triangles)
10676 /// is [`None`] whatever the device supports. Nothing counts a triangle on
10677 /// the GPU either, and a cluster count times a nominal triangles-per-cluster
10678 /// would read as authoritative and be neither.
10679 ///
10680 /// # The instances drawn come back off the GPU, a few frames late
10681 ///
10682 /// [`FrameCounters::drawn`](crate::counters::FrameCounters::drawn) is
10683 /// `cull.slang`'s survivor count, off [`crate::cull_stats`]'s delayed ring,
10684 /// plus the frame's direct draws — the ones here whose instance the CPU
10685 /// knows about, and the ones that are also in
10686 /// [`instances`](crate::counters::FrameCounters::instances). So the pair is
10687 /// comparable: the same quantity submitted and kept.
10688 ///
10689 /// **The camera's cull alone.** The shadow culls test other frustums and
10690 /// their survivors are counted into buffers of their own; adding them here
10691 /// would give a "drawn" larger than "submitted" on any frame with a shadow
10692 /// in it.
10693 ///
10694 /// It is [`None`] — the row says `indirect` — for the first few frames of a
10695 /// renderer's life, while the ring has not come round, and for good on a
10696 /// device that would not give out a readback.
10697 /// [`cull_frame`](crate::counters::FrameCounters::cull_frame) is which frame
10698 /// the number is about whenever there is one.
10699 ///
10700 /// [`FrameCounters::instances`](crate::counters::FrameCounters::instances)
10701 /// is known and is the plan's "submitted" half: the live instances
10702 /// [`add_passes`](Self::add_passes) hands the cull dispatches, plus the
10703 /// frame's direct draws — every full-screen pass's triangle and the debug
10704 /// draw layer's line list.
10705 #[must_use]
10706 pub fn counters(&self) -> FrameCounters {
10707 if self.recorded_draws == 0 {
10708 return FrameCounters::default();
10709 }
10710 let stats = self.cull_stats();
10711 let direct = self.direct_draws();
10712 FrameCounters {
10713 draws: self.recorded_draws,
10714 instances: self.instances.len() as u64 + direct,
10715 // Each direct draw is submitted and drawn, and none of them is in
10716 // the cull's count — they are draws of one instance, added on both
10717 // sides so the two halves of the row measure the same thing. Off the
10718 // frame that *was* recorded rather than off a constant, so a frame
10719 // with an effect switched off does not count a triangle it never
10720 // submitted.
10721 // Less what the occlusion cull's second phase rejected, which were
10722 // survivors of the frustum and were not drawn.
10723 drawn: stats
10724 .map(|stats| stats.instances.saturating_sub(stats.occlusion.late_rejects) + direct),
10725 triangles: None,
10726 // The survivors alone: the panel row is "clusters drawn", and the
10727 // frustum and cone rejection counts beside them are a different
10728 // question — `CullStats::clusters` carries all three for a caller
10729 // that wants the split, which `apps/quarry`'s own panel row is.
10730 clusters: stats
10731 .and_then(|stats| stats.clusters)
10732 .map(|cull| cull.survivors),
10733 cull_frame: stats.map(|stats| stats.frame),
10734 }
10735 }
10736
10737 /// The draws this renderer records **directly** — the ones whose instance
10738 /// the CPU knows about, as opposed to the indirect calls whose counts live
10739 /// in a buffer a shader wrote.
10740 ///
10741 /// Every full-screen pass's over-sized triangle, plus the debug draw
10742 /// layer's line list on a frame that has one. One instance each, which is
10743 /// why [`counters`](Self::counters) adds this to both halves of its
10744 /// submitted/drawn pair.
10745 fn direct_draws(&self) -> u64 {
10746 self.recorded_fullscreen * FULLSCREEN_DRAWS
10747 + self.recorded_debug_draw
10748 + self.recorded_tile_clears
10749 + self.recorded_water_draws
10750 }
10751
10752 /// What the camera's cull kept, on the frame the ring has reached.
10753 ///
10754 /// Topic 03 §3.6's one permitted readback, and [`None`] until it has come
10755 /// round — see [`crate::cull_stats`] for the latency and for what makes it
10756 /// free of any wait. [`counters`](Self::counters) is where this reaches the
10757 /// panel; it is exposed on its own because the frame number and the cluster
10758 /// word are both things a test asserts about directly.
10759 #[must_use]
10760 pub fn cull_stats(&self) -> Option<crate::cull_stats::CullStats> {
10761 self.cull_stats.as_ref().and_then(CullStatsRing::latest)
10762 }
10763
10764 /// Describes the imported swapchain image the frame ends in.
10765 ///
10766 /// A helper rather than something every caller writes, because getting
10767 /// `initial`/`final_state` wrong is exactly the hand-written barrier this
10768 /// slice removed: an acquired image's contents are undefined, and the
10769 /// compositor may only be handed one in [`ResourceState::Present`].
10770 #[must_use]
10771 pub fn present_target(
10772 image: crcbl_hal::ImageHandle,
10773 view: ImageViewHandle,
10774 format: Format,
10775 extent: (u32, u32),
10776 ) -> ImportedImage {
10777 ImportedImage {
10778 image,
10779 view,
10780 format,
10781 extent,
10782 initial: ResourceState::Undefined,
10783 // The acquire's semaphore, not a barrier, is what orders this frame
10784 // after the last use of the image — which is what makes `Undefined`
10785 // honest here and what makes it uncheckable. See `InitialClaim`.
10786 claim: InitialClaim::Acquired,
10787 final_state: ResourceState::Present,
10788 }
10789 }
10790
10791 /// Releases everything, in dependency order. The device must be idle.
10792 pub fn destroy(self, device: &dyn Device) {
10793 if let Some(stats) = self.cull_stats {
10794 stats.destroy(device);
10795 }
10796 // The cameras first: their groups name the scene's buffers, pages and
10797 // atlas below, and they own nothing the scene's groups name.
10798 for view in self.views.into_iter().flatten() {
10799 view.destroy(device);
10800 }
10801 self.primary.destroy(device);
10802 // After every view, whose grass and water groups name these buffers.
10803 self.grass.destroy(device);
10804 self.water.destroy(device);
10805 device.destroy_sampler(self.sampler);
10806 device.destroy_graphics_pipeline(self.tonemap_pipeline);
10807 device.destroy_pipeline_layout(self.tonemap_pipeline_layout);
10808 device.destroy_bind_group_layout(self.tonemap_layout);
10809
10810 for pipelines in [
10811 self.shadow_pipeline,
10812 self.depth_masked_pipeline,
10813 self.rsm_pipeline,
10814 ] {
10815 device.destroy_graphics_pipeline(pipelines.single);
10816 device.destroy_graphics_pipeline(pipelines.double);
10817 }
10818 device.destroy_graphics_pipeline(self.shadow_clear_pipeline);
10819 for groups in self.shadow_groups {
10820 for group in groups {
10821 device.destroy_bind_group(group);
10822 }
10823 }
10824 for buffers in self.shadow_uniforms {
10825 for buffer in buffers {
10826 device.destroy_buffer(buffer);
10827 }
10828 }
10829 for buffers in self.shadow_selection {
10830 for buffer in buffers {
10831 device.destroy_buffer(buffer);
10832 }
10833 }
10834 for draws in self.shadow_draws {
10835 draws.destroy(device);
10836 }
10837 device.destroy_sampler(self.shadow_sampler);
10838 device.destroy_image_view(self.shadow_atlas_view);
10839 device.destroy_image(self.shadow_atlas);
10840 device.destroy_image_view(self.shadow_placeholder_view);
10841 device.destroy_image(self.shadow_placeholder);
10842
10843 if let Some(grid) = self.ground_grid {
10844 grid.destroy(device);
10845 }
10846 // Nothing to release on a renderer nobody drew a segment through — see
10847 // [`crate::debug_draw`], whose pipeline is built on first use.
10848 self.debug_draw.destroy(device);
10849 self.atlas_viewer.destroy(device);
10850 self.ambient_occlusion_placeholder.destroy(device);
10851 self.contact_shadow_placeholder.destroy(device);
10852 self.probe_visibility_placeholder.destroy(device);
10853 if let Some(captured) = self.probe_visibility {
10854 captured.destroy(device);
10855 }
10856 self.specular_dfg.destroy(device);
10857 self.ltc_table.destroy(device);
10858 self.normal_page.destroy(device);
10859 self.mro_page.destroy(device);
10860 self.emissive_page.destroy(device);
10861
10862 device.destroy_graphics_pipeline(self.mesh_pipeline.single);
10863 device.destroy_graphics_pipeline(self.mesh_pipeline.double);
10864 // The one place the wireframe pair is released — `set_wireframe(.., false)`
10865 // deliberately is not, because this call is the one that requires an
10866 // idle device.
10867 if let Some(pipelines) = self.wireframe_pipeline {
10868 device.destroy_graphics_pipeline(pipelines.single);
10869 device.destroy_graphics_pipeline(pipelines.double);
10870 }
10871 device.destroy_pipeline_layout(self.mesh_pipeline_layout);
10872 device.destroy_bind_group_layout(self.mesh_layout);
10873 self.base_color_page.destroy(device);
10874 device.destroy_sampler(self.base_color_sampler);
10875 for retired in self.retired_pages {
10876 retired.destroy(device);
10877 }
10878 device.destroy_buffer(self.draw_constants);
10879 if let Some(clusters) = self.clusters {
10880 clusters.destroy(device);
10881 }
10882 // Before the probe table, because its bind groups name that table's
10883 // rows — the same ordering the light grid is under above.
10884 if let Some(gather) = self.probe_gather {
10885 gather.destroy(device);
10886 }
10887 self.probes.destroy(device);
10888 self.materials.destroy(device);
10889 self.instances.destroy(device);
10890 self.pool.destroy(device);
10891 }
10892}
10893
10894/// What the shadow pass a frame recorded would leave the image holding, held
10895/// until the frame after can say whether its body ran.
10896///
10897/// Topic 45's static-caching rung, per group: recording a pass
10898/// is not drawing one, so nothing here is believed until
10899/// [`ForwardRenderer::shadow_pass_ran`] carries this [`ShadowCommit::id`] back
10900/// out of the graph.
10901#[derive(Clone, Debug)]
10902struct ShadowCommit {
10903 /// The [`ForwardRenderer::shadow_pass_id`] the body publishes.
10904 id: u64,
10905 /// `[group]`: what the group's entry of
10906 /// [`ForwardRenderer::shadow_group_held`] becomes for every group the pass
10907 /// redraws, and [`None`] for the groups it holds.
10908 groups: Vec<Option<(u64, Vec3, f32)>>,
10909 /// The layout the pass draws under, where it clears the whole attachment —
10910 /// and [`None`] where it loads, because a loading pass leaves every tile it
10911 /// does not redraw exactly as it found it.
10912 layout: Option<Vec<shadow::TileRect>>,
10913}
10914
10915/// The shader modules a mesh pipeline is built from, with its entry points
10916/// already resolved.
10917///
10918/// **A type rather than a run of locals in `build`** because there are now two
10919/// callers: `build`, which makes the colour pipeline and its depth-only twin,
10920/// and [`ForwardRenderer::set_wireframe`], which makes the colour pipeline again
10921/// in [`PolygonMode::Line`] long after `build` released its modules. The
10922/// alternative was a second copy of a descriptor that names two modules, their
10923/// entry points, the colour targets and a depth state — the pair that drifts.
10924///
10925/// Short-lived: created, used to build pipelines, and [`MeshModules::destroy`]ed
10926/// in the same function. A module is not needed once the pipeline exists.
10927struct MeshModules {
10928 /// `mesh.slang`'s module — the vertex stage on the indirect path, and the
10929 /// fragment stage on both.
10930 mesh: ShaderModuleHandle,
10931 /// `vertexMain`, unused on the mesh-shader path.
10932 vertex: &'static str,
10933 /// `depthVertexMain`, which [`MeshModules::depth_pipeline`] takes in
10934 /// [`MeshModules::vertex`]'s place: the same transform off stream 0 of the
10935 /// vertex pool and no attribute region at all. Unused on the mesh-shader
10936 /// path, where the geometry stage is `mesh_cluster.slang`'s either way.
10937 depth_vertex: &'static str,
10938 /// `depthClearVertexMain`, which [`MeshModules::depth_clear_pipeline`]
10939 /// builds the tile clear from: three corners off `SV_VertexID` and no input
10940 /// at all, so it resets one tile of the atlas without reading a vertex.
10941 ///
10942 /// **The same stage on every path**, unlike the two above: a device with a
10943 /// mesh stage still has a vertex stage, and a clear that produced no
10944 /// geometry is a primitive, not a cluster.
10945 depth_clear_vertex: &'static str,
10946 fragment: &'static str,
10947 /// `depthMaskedFragmentMain`, which [`MeshModules::depth_masked_pipeline`]
10948 /// puts *behind* [`MeshModules::vertex`] — the alpha mask and no target at
10949 /// all.
10950 ///
10951 /// **The same stage on both paths**, unlike the two vertex entry points
10952 /// above: it reads `mesh.slang`'s own `VertexOutput`, which is what
10953 /// `vertexMain` writes on the raster path and what `mesh_cluster.slang`'s
10954 /// mesh stage writes on the mesh one. So the cutout is one comparison in one
10955 /// place rather than one per geometry path.
10956 depth_masked_fragment: &'static str,
10957 /// `rsmFragmentMain`, which [`MeshModules::rsm_pipeline`] takes in
10958 /// [`MeshModules::fragment`]'s place: the same geometry stage, three targets
10959 /// describing the surface rather than shading it.
10960 ///
10961 /// **The reason the shaded stage above is looked up by name.** A module with
10962 /// two fragment entry points has no unambiguous one, which is what `entry`
10963 /// answers `None` for.
10964 rsm_fragment: &'static str,
10965 /// `mesh_cluster.slang`'s, on the mesh-shader path alone.
10966 cluster: Option<ClusterStages>,
10967}
10968
10969/// The geometry half of a mesh-shader pipeline: `mesh_cluster.slang`'s module
10970/// and the stages taken out of it.
10971struct ClusterStages {
10972 /// The module the mesh stage is built from, and the one the task stage is,
10973 /// which are **two modules rather than one**.
10974 ///
10975 /// `mesh_cluster.slang` compiles to a combined module carrying every entry
10976 /// point and to one module per stage, and these are the per-stage ones. A
10977 /// module holding a task entry point and its mesh partner carries two
10978 /// `TaskPayloadWorkgroupEXT` variables — the task writes one, the mesh stage
10979 /// reads the other — and an NVIDIA driver then delivers a payload of zeroes,
10980 /// which draws cluster 0 of instance slot 0 of every bucket and nothing
10981 /// else. See `crcbl_shaders::EntryPoint`.
10982 mesh_module: ShaderModuleHandle,
10983 /// The task stage's own module, on the same terms. [`None`] exactly when
10984 /// [`task`](Self::task) is.
10985 task_module: Option<ShaderModuleHandle>,
10986 /// Which of the module's two mesh entry points this path builds — the
10987 /// amplified one where the device has a task stage to feed it.
10988 mesh: &'static str,
10989 /// §3.5's per-cluster cull, where the device has the stage to run it in.
10990 /// [`None`] is not a degradation: `meshMain` draws the same picture out of
10991 /// the same clusters, having rejected none of them, which is what a device
10992 /// with [`Features::MESH_SHADER`](crcbl_hal::Features::MESH_SHADER) and no
10993 /// [`Features::TASK_SHADER`](crcbl_hal::Features::TASK_SHADER) gets.
10994 task: Option<&'static str>,
10995}
10996
10997impl MeshModules {
10998 /// **Three targets, one fragment stage.** `mesh.slang`'s `FragmentOutput`
10999 /// writes the shaded colour, then topic 47's
11000 /// reflectivity channel, then topic 43 §9's motion
11001 /// vector — and both pipeline shapes name that same entry point, so each
11002 /// target is one more element of this array and not a second pipeline, a
11003 /// second entry point or a new interpolant. The refusal the AO section
11004 /// records was about the depth prepass, which has no fragment stage and no
11005 /// colour target at all; it does not reach this array.
11006 ///
11007 /// Element order is `SV_Target` order, and each format is the one the
11008 /// matching `TransientImageDesc` creates: a pipeline built for a format the
11009 /// attachment is not in is a validation error on WebGPU and a silent
11010 /// reinterpretation elsewhere.
11011 const COLOR_TARGETS: [ColorTargetState; 3] = [
11012 ColorTargetState::opaque(Format::Rgba16Float),
11013 ColorTargetState::opaque(Format::Rgba8Unorm),
11014 ColorTargetState::opaque(MOTION_FORMAT),
11015 ];
11016
11017 /// **Three targets again, and a different three.** `mesh.slang`'s
11018 /// `RsmOutput` writes the surface's diffuse albedo, its world normal encoded
11019 /// `n * 0.5 + 0.5`, and its world position with a coverage flag in `w` —
11020 /// which is what the irradiance probes' gather needs of a
11021 /// texel and nothing more.
11022 ///
11023 /// Element order is `SV_Target` order and each format is the one the
11024 /// matching description in [`crate::rsm`] creates: a pipeline built for a
11025 /// format the attachment is not in is a validation error on WebGPU and a
11026 /// silent reinterpretation elsewhere. `the_targets_carry_the_formats_the_shader_writes`
11027 /// in that module is the other half of the pair.
11028 const RSM_TARGETS: [ColorTargetState; 3] = [
11029 ColorTargetState::opaque(Format::Rgba16Float),
11030 ColorTargetState::opaque(Format::Rgba8Unorm),
11031 ColorTargetState::opaque(Format::Rgba32Float),
11032 ];
11033
11034 /// Invocations per mesh workgroup, which is `mesh_cluster.slang`'s
11035 /// `[numthreads(THREADS, 1, 1)]` — and `THREADS` is
11036 /// `MAX_CLUSTER_VERTICES`, one lane per vertex a cluster can hold.
11037 ///
11038 /// Taken from the crate that owns the shader source rather than written
11039 /// out, as
11040 /// [`MeshPipelineDesc::mesh_workgroup_size`](crcbl_hal::MeshPipelineDesc::mesh_workgroup_size)
11041 /// requires: only Metal reads this field, so a literal that disagreed with
11042 /// the shader would launch the wrong number of threads on one backend and
11043 /// nowhere else.
11044 const MESH_WORKGROUP_SIZE: [u32; 3] =
11045 [crcbl_shaders::meshlet::MAX_CLUSTER_VERTICES as u32, 1, 1];
11046
11047 /// Invocations per task workgroup: `taskMain` is
11048 /// `[numthreads(TASK_LANES, 1, 1)]`, one lane per (cluster, instance slot)
11049 /// pair of its chunk. Taken from the crate that owns the shader, on
11050 /// [`MESH_WORKGROUP_SIZE`](Self::MESH_WORKGROUP_SIZE)'s terms.
11051 const TASK_WORKGROUP_SIZE: [u32; 3] = [crcbl_shaders::meshlet::TASK_LANES, 1, 1];
11052
11053 /// Loads whichever modules `emit` needs and resolves their entry points.
11054 ///
11055 /// # Errors
11056 ///
11057 /// [`HalError::ShaderCompilation`] if the committed manifest names no such
11058 /// entry point, and [`HalError`] from either module. A failure after the
11059 /// first module was created releases it rather than leaking it.
11060 fn new(device: &dyn Device, emit: EmitTail, culls_clusters: bool) -> Result<Self, HalError> {
11061 // Entry points resolved before the module exists: a manifest that
11062 // disagreed with the SPIR-V would otherwise fail inside the descriptor
11063 // literal, with the module already created and nothing holding it.
11064 //
11065 // **The vertex stage is named rather than looked up by stage**, for
11066 // `mesh_cluster.slang`'s reason below: since the depth-only stage landed
11067 // this module has two vertex entry points, and a stage lookup answers
11068 // `None` for two matches. Which of the two a pipeline names is the whole
11069 // of what the split-stream vertex pool bought.
11070 let vertex = named_entry(&MESH, "vertexMain", Stage::Vertex)?;
11071 let depth_vertex = named_entry(&MESH, "depthVertexMain", Stage::Vertex)?;
11072 let depth_clear_vertex = named_entry(&MESH, "depthClearVertexMain", Stage::Vertex)?;
11073 // **Named rather than looked up by stage, on the vertex entry points'
11074 // terms exactly.** Since the irradiance probes' updater
11075 // landed, this module has *two* fragment entry points — the shaded one
11076 // and `rsmFragmentMain` — and `entry` answers `None` for two matches, so
11077 // a stage lookup here refuses the build outright with "exposes no
11078 // unambiguous Fragment entry point".
11079 let fragment = named_entry(&MESH, "fragmentMain", Stage::Fragment)?;
11080 let depth_masked_fragment = named_entry(&MESH, "depthMaskedFragmentMain", Stage::Fragment)?;
11081 let rsm_fragment = named_entry(&MESH, "rsmFragmentMain", Stage::Fragment)?;
11082 // **Named rather than looked up by stage**, because the module has two
11083 // mesh entry points and a stage lookup would refuse an ambiguous one —
11084 // see `named_entry`. Which of the two this names is the whole of the
11085 // amplification decision.
11086 let cluster_stages = emit
11087 .is_mesh()
11088 .then(|| {
11089 let mesh = named_entry(
11090 &MESH_CLUSTER,
11091 if culls_clusters {
11092 "amplifiedMeshMain"
11093 } else {
11094 "meshMain"
11095 },
11096 Stage::Mesh,
11097 )?;
11098 let task = culls_clusters
11099 .then(|| named_entry(&MESH_CLUSTER, "taskMain", Stage::Task))
11100 .transpose()?;
11101 Ok::<_, HalError>((mesh, task))
11102 })
11103 .transpose()?;
11104
11105 let mesh = device.create_shader_module(&ShaderModuleDesc {
11106 label: Some("mesh.slang"),
11107 spirv: MESH.spirv(),
11108 wgsl: MESH.wgsl(),
11109 msl: MESH.msl(),
11110 // **Both containers, and still one module.** A DXIL container holds
11111 // exactly one entry point, so this is a list where its three
11112 // neighbours are single artifacts; the backend that consumes it
11113 // picks the container named by the stage it is building. Nothing
11114 // here branches on a backend, and the three that ignore DXIL see
11115 // the same module they always did.
11116 dxil: &MESH.dxil_containers(),
11117 })?;
11118 let cluster = match cluster_stages {
11119 None => None,
11120 Some((cluster_mesh, task)) => {
11121 // **The mesh stage's module is `mesh_cluster.slang`; the
11122 // fragment stage's is still `mesh.slang`'s.** A pipeline takes a
11123 // module per stage, so the shading — Lambert, the GGX lobe, the
11124 // material row, the page sample — is the same code both paths
11125 // run rather than a copy that agrees today.
11126 // `mesh_cluster.slang`'s header carries the argument, and its
11127 // `VertexOutput` is what the two agree through.
11128 // **One module per stage, each carrying that stage's own
11129 // SPIR-V.** Only the SPIR-V differs between them: MSL is one
11130 // artifact per source whatever the stage, and a DXIL container
11131 // is already per entry point, so both are handed over unchanged
11132 // and the backends that read them see what they always did.
11133 let stage_module = |entry_point: &str| {
11134 device.create_shader_module(&ShaderModuleDesc {
11135 label: Some("mesh_cluster.slang"),
11136 // The combined module where this stage has none of its
11137 // own, which is every stage of every other shader.
11138 spirv: MESH_CLUSTER
11139 .spirv_for(entry_point)
11140 .unwrap_or_else(|| MESH_CLUSTER.spirv()),
11141 // `None`, and it is the whole reason this is a second
11142 // file: WGSL cannot express a mesh stage at all.
11143 wgsl: MESH_CLUSTER.wgsl(),
11144 msl: MESH_CLUSTER.msl(),
11145 dxil: &MESH_CLUSTER.dxil_containers(),
11146 })
11147 };
11148 let mesh_module = match stage_module(cluster_mesh) {
11149 Ok(module) => module,
11150 Err(error) => {
11151 device.destroy_shader_module(mesh);
11152 return Err(error);
11153 }
11154 };
11155 let task_module = match task.map(stage_module).transpose() {
11156 Ok(module) => module,
11157 Err(error) => {
11158 device.destroy_shader_module(mesh);
11159 device.destroy_shader_module(mesh_module);
11160 return Err(error);
11161 }
11162 };
11163 Some(ClusterStages {
11164 mesh_module,
11165 task_module,
11166 mesh: cluster_mesh,
11167 task,
11168 })
11169 }
11170 };
11171 Ok(Self {
11172 mesh,
11173 vertex,
11174 depth_vertex,
11175 depth_clear_vertex,
11176 fragment,
11177 depth_masked_fragment,
11178 rsm_fragment,
11179 cluster,
11180 })
11181 }
11182
11183 /// The rasteriser state every pipeline shape here shares, because the only
11184 /// things that differ between them are which stage produces the geometry and
11185 /// which side of it survives.
11186 ///
11187 /// [`CullMode::Back`] is what a single-sided bucket asks for, and it has
11188 /// been on from the first mesh. The cube's winding is asserted by
11189 /// `crcbl-shaders`' own tests, so a face that vanished would be a *test*
11190 /// failure rather than a debugging session — and a mesh drawn without
11191 /// culling would let a winding mistake survive into P7's geometry pool. The
11192 /// mesh stage emits its corner triples in the index buffer's own order, so
11193 /// the winding it produces is the same one.
11194 ///
11195 /// [`CullMode::None`] is what a double-sided bucket asks for — glTF 2.0
11196 /// §3.9.6's first half — and the twin built with it is the only way a back
11197 /// face reaches `mesh.slang` at all. See [`SidedPipelines`].
11198 fn primitive(polygon_mode: PolygonMode, cull_mode: CullMode) -> PrimitiveState {
11199 PrimitiveState {
11200 cull_mode,
11201 polygon_mode,
11202 ..PrimitiveState::default()
11203 }
11204 }
11205
11206 /// What a pipeline built with `cull` adds to its label, so a capture and
11207 /// `crcbl_hal::null`'s recorder tell a [`SidedPipelines::double`] twin from
11208 /// the [`SidedPipelines::single`] it was built beside.
11209 ///
11210 /// Empty for the culling modes, because those pipelines' labels are the ones
11211 /// every existing capture and every test lookup already names.
11212 fn side_label(cull: CullMode) -> &'static str {
11213 match cull {
11214 CullMode::None => " double-sided",
11215 CullMode::Front | CullMode::Back => "",
11216 }
11217 }
11218
11219 /// Both sides of one pipeline shape, single-sided first, **created and not
11220 /// yet unwrapped**.
11221 ///
11222 /// The results rather than the pair, because that is the discipline `build`
11223 /// keeps for every pipeline it makes: everything is created while the
11224 /// modules are alive, the modules are released once, and only then is each
11225 /// successful result handed to rollback before any error is propagated. A
11226 /// helper that unwrapped here would have to drop a handle it had already
11227 /// created when its twin failed, and nothing would ever destroy it.
11228 fn sided(
11229 mut build: impl FnMut(CullMode) -> Result<GraphicsPipelineHandle, HalError>,
11230 ) -> [Result<GraphicsPipelineHandle, HalError>; 2] {
11231 [build(CullMode::Back), build(CullMode::None)]
11232 }
11233
11234 /// Milestone 3's depth test, and the seam's default is already reversed-Z:
11235 /// `Greater` against `D32Float`, writes on. The clear value that agrees with
11236 /// it comes from the graph (`PassBuilder::clear_depth`), and the projection
11237 /// matrix that agrees with **both** comes from [`crate::camera`].
11238 fn depth_stencil() -> Option<DepthStencilState> {
11239 Some(DepthStencilState::default())
11240 }
11241
11242 /// The colour pass's depth state, which is not the same shape as
11243 /// [`MeshModules::depth_stencil`] because the depth prepass has already
11244 /// drawn this geometry.
11245 ///
11246 /// **Filled: [`DepthStencilState::equal_depth_read_only`], so the shading is
11247 /// paid for once per pixel.** The prepass runs the same draws through
11248 /// `depthVertexMain` — or, on the mesh path, through the very same geometry
11249 /// stage — so the depth already in the attachment is this pass's own answer,
11250 /// and a `GreaterOrEqual` test with writes off keeps exactly the fragments
11251 /// that would have won the write. What it removes is the clustered-forward
11252 /// shading of every fragment a nearer one goes on to cover.
11253 ///
11254 /// **Lines: the writing default, because a wireframe is not the geometry the
11255 /// prepass drew.** [`PolygonMode::Line`] rasterises the triangle's edges,
11256 /// and an edge pixel's depth is interpolated along the line rather than
11257 /// across the face, so testing it for equality against a filled prepass
11258 /// rejects most of the wireframe. That frame keeps the pass shape this pass
11259 /// had before the prepass existed — see the colour pass's depth attachment,
11260 /// which branches on the same condition.
11261 fn color_depth_stencil(polygon_mode: PolygonMode) -> Option<DepthStencilState> {
11262 match polygon_mode {
11263 PolygonMode::Fill => Some(DepthStencilState::equal_depth_read_only(Format::D32Float)),
11264 _ => Self::depth_stencil(),
11265 }
11266 }
11267
11268 /// The colour pass's pipeline, filled or wireframe, culling back faces or
11269 /// nothing.
11270 ///
11271 /// `label` names the caller — `"forward"` for the frame's own, `"wireframe"`
11272 /// for [`ForwardRenderer::set_wireframe`]'s — and [`MeshModules::side_label`]
11273 /// names the side, so a capture tells all four apart.
11274 fn color_pipeline(
11275 &self,
11276 device: &dyn Device,
11277 layout: PipelineLayoutHandle,
11278 polygon_mode: PolygonMode,
11279 cull: CullMode,
11280 label: &str,
11281 ) -> Result<GraphicsPipelineHandle, HalError> {
11282 let primitive = Self::primitive(polygon_mode, cull);
11283 let depth_stencil = Self::color_depth_stencil(polygon_mode);
11284 let side = Self::side_label(cull);
11285 let fragment = Some(ShaderEntry {
11286 module: self.mesh,
11287 entry_point: self.fragment,
11288 });
11289 match self.cluster.as_ref() {
11290 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11291 label: Some(&format!("{label}{side} mesh cluster")),
11292 layout,
11293 task: cluster
11294 .task
11295 .zip(cluster.task_module)
11296 .map(|(entry_point, module)| ShaderEntry {
11297 module,
11298 entry_point,
11299 }),
11300 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11301 mesh: ShaderEntry {
11302 module: cluster.mesh_module,
11303 entry_point: cluster.mesh,
11304 },
11305 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11306 fragment,
11307 primitive,
11308 depth_stencil,
11309 multisample: MultisampleState::default(),
11310 color_targets: &Self::COLOR_TARGETS,
11311 }),
11312 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11313 label: Some(&format!("{label}{side} mesh")),
11314 layout,
11315 vertex: ShaderEntry {
11316 module: self.mesh,
11317 entry_point: self.vertex,
11318 },
11319 fragment,
11320 primitive,
11321 depth_stencil,
11322 multisample: MultisampleState::default(),
11323 color_targets: &Self::COLOR_TARGETS,
11324 }),
11325 }
11326 }
11327
11328 /// The depth-only twin of [`MeshModules::color_pipeline`], built out of the
11329 /// same modules and the same layout: no fragment stage, no colour target,
11330 /// and a vertex stage that fetches stream 0 of the vertex pool alone.
11331 ///
11332 /// **The transform is identical and the fetch is not, which is the point.**
11333 /// Topic 18 asks for a shadow pass "identical on every `GeometryPath` —
11334 /// depth pass plus whatever emit tail the device selected", and what makes
11335 /// that work is a frame block whose `view_proj` is the cascade's matrix
11336 /// rather than a second transform path: a cascade that disagreed with the
11337 /// colour pass about where a vertex is would produce shadows that do not
11338 /// line up with their casters, which is indistinguishable from a bias
11339 /// problem. `depthVertexMain` is that same clip position written the same
11340 /// way, with everything the discarded varyings needed — the attribute
11341 /// region and the previous frame's position — left unread;
11342 /// topic 43 §2 split the pool for exactly this
11343 /// pass, and this is where it is spent.
11344 ///
11345 /// **The mesh-shader path still runs the colour pipeline's geometry
11346 /// stage.** `mesh_cluster.slang` emits one `VertexOutput`, so a depth-only
11347 /// mesh stage is a second entry point in that module and its own rung; a
11348 /// device with a mesh stage goes on reading whole vertices here.
11349 ///
11350 /// Always [`PolygonMode::Fill`]: it fills the shadow atlas and the depth
11351 /// prepass, and depth drawn as lines is depth with holes in it — which the
11352 /// occlusion pair would read as geometry that is not there.
11353 fn depth_pipeline(
11354 &self,
11355 device: &dyn Device,
11356 layout: PipelineLayoutHandle,
11357 cull: CullMode,
11358 ) -> Result<GraphicsPipelineHandle, HalError> {
11359 let primitive = Self::primitive(PolygonMode::Fill, cull);
11360 let side = Self::side_label(cull);
11361 match self.cluster.as_ref() {
11362 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11363 label: Some(&format!("shadow cascade{side} mesh cluster")),
11364 layout,
11365 task: cluster
11366 .task
11367 .zip(cluster.task_module)
11368 .map(|(entry_point, module)| ShaderEntry {
11369 module,
11370 entry_point,
11371 }),
11372 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11373 mesh: ShaderEntry {
11374 module: cluster.mesh_module,
11375 entry_point: cluster.mesh,
11376 },
11377 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11378 fragment: None,
11379 primitive,
11380 depth_stencil: Self::depth_stencil(),
11381 multisample: MultisampleState::default(),
11382 color_targets: &[],
11383 }),
11384 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11385 label: Some(&format!("shadow cascade{side}")),
11386 layout,
11387 vertex: ShaderEntry {
11388 module: self.mesh,
11389 entry_point: self.depth_vertex,
11390 },
11391 fragment: None,
11392 primitive,
11393 depth_stencil: Self::depth_stencil(),
11394 multisample: MultisampleState::default(),
11395 color_targets: &[],
11396 }),
11397 }
11398 }
11399
11400 /// [`MeshModules::depth_pipeline`] with an alpha mask in it: the same depth
11401 /// state and the same absent colour targets, `depthMaskedFragmentMain`
11402 /// behind the geometry stage, and [`MeshModules::vertex`] in
11403 /// [`MeshModules::depth_vertex`]'s place.
11404 ///
11405 /// Topic 43 §3's cutout, in the two passes that
11406 /// write depth without shading. A masked instance drawn through the pipeline
11407 /// above writes its full silhouette: it occludes itself through the hole it
11408 /// can see through, and it casts the shadow of a leaf that has none.
11409 ///
11410 /// **The vertex stage is the colour pass's, and it has to be.** A cutout
11411 /// needs the UV, which lives in the attribute region `depthVertexMain`
11412 /// exists not to read — so this stage reads a whole vertex, exactly as
11413 /// [`MeshModules::rsm_pipeline`] does beside it and for the same reason.
11414 /// What that buys is one fragment entry point for both geometry paths: the
11415 /// mesh path already emits `mesh.slang`'s `VertexOutput`, so the mask is
11416 /// compared in one place rather than once per path.
11417 ///
11418 /// **Which draws are recorded with it is the bucket's own material mode**,
11419 /// not the frame's — see [`ForwardRenderer::depth_partitions`]. A scene that
11420 /// masks nothing has no bucket in this partition, records through the
11421 /// pipeline above with no fragment stage anywhere, and costs exactly what it
11422 /// cost before this one existed; a scene that masks one mesh pays the
11423 /// fragment stage for that mesh's draws alone.
11424 fn depth_masked_pipeline(
11425 &self,
11426 device: &dyn Device,
11427 layout: PipelineLayoutHandle,
11428 cull: CullMode,
11429 ) -> Result<GraphicsPipelineHandle, HalError> {
11430 let primitive = Self::primitive(PolygonMode::Fill, cull);
11431 let side = Self::side_label(cull);
11432 let fragment = Some(ShaderEntry {
11433 module: self.mesh,
11434 entry_point: self.depth_masked_fragment,
11435 });
11436 match self.cluster.as_ref() {
11437 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11438 label: Some(&format!("shadow cascade masked{side} mesh cluster")),
11439 layout,
11440 task: cluster
11441 .task
11442 .zip(cluster.task_module)
11443 .map(|(entry_point, module)| ShaderEntry {
11444 module,
11445 entry_point,
11446 }),
11447 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11448 mesh: ShaderEntry {
11449 module: cluster.mesh_module,
11450 entry_point: cluster.mesh,
11451 },
11452 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11453 fragment,
11454 primitive,
11455 depth_stencil: Self::depth_stencil(),
11456 multisample: MultisampleState::default(),
11457 color_targets: &[],
11458 }),
11459 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11460 label: Some(&format!("shadow cascade masked{side}")),
11461 layout,
11462 vertex: ShaderEntry {
11463 module: self.mesh,
11464 entry_point: self.vertex,
11465 },
11466 fragment,
11467 primitive,
11468 depth_stencil: Self::depth_stencil(),
11469 multisample: MultisampleState::default(),
11470 color_targets: &[],
11471 }),
11472 }
11473 }
11474
11475 /// The reflective shadow map's pipeline: the colour pipeline's geometry
11476 /// stage, `rsmFragmentMain` in the shaded stage's place, and
11477 /// [`MeshModules::RSM_TARGETS`] in [`MeshModules::COLOR_TARGETS`]'s.
11478 ///
11479 /// The irradiance probes' updater draws the sun's near
11480 /// cascade a second time through this — see [`crate::rsm`], which owns the
11481 /// attachments, and `ForwardRenderer::add_shadow_pass`, which records the
11482 /// pass out of that cascade's own bind group and its own already-generated
11483 /// draws.
11484 ///
11485 /// **[`MeshModules::vertex`] and not [`MeshModules::depth_vertex`]**, unlike
11486 /// the cascade this rides beside: a fragment stage that writes a world
11487 /// position, a normal and an albedo needs the varyings `depthVertexMain`
11488 /// exists to leave unread. On the mesh path it is the very same geometry
11489 /// stage the colour pass runs, for the reason `depth_pipeline` gives.
11490 ///
11491 /// **Its own depth, written**, rather than the colour pass's read-only
11492 /// equality test: nothing has drawn this view's depth before it, and the
11493 /// pass is what decides which surface a texel of the map holds.
11494 fn rsm_pipeline(
11495 &self,
11496 device: &dyn Device,
11497 layout: PipelineLayoutHandle,
11498 cull: CullMode,
11499 ) -> Result<GraphicsPipelineHandle, HalError> {
11500 let primitive = Self::primitive(PolygonMode::Fill, cull);
11501 let side = Self::side_label(cull);
11502 let fragment = Some(ShaderEntry {
11503 module: self.mesh,
11504 entry_point: self.rsm_fragment,
11505 });
11506 match self.cluster.as_ref() {
11507 Some(cluster) => device.create_mesh_pipeline(&MeshPipelineDesc {
11508 label: Some(&format!("rsm{side} mesh cluster")),
11509 layout,
11510 task: cluster
11511 .task
11512 .zip(cluster.task_module)
11513 .map(|(entry_point, module)| ShaderEntry {
11514 module,
11515 entry_point,
11516 }),
11517 task_workgroup_size: Self::TASK_WORKGROUP_SIZE,
11518 mesh: ShaderEntry {
11519 module: cluster.mesh_module,
11520 entry_point: cluster.mesh,
11521 },
11522 mesh_workgroup_size: Self::MESH_WORKGROUP_SIZE,
11523 fragment,
11524 primitive,
11525 depth_stencil: Self::depth_stencil(),
11526 multisample: MultisampleState::default(),
11527 color_targets: &Self::RSM_TARGETS,
11528 }),
11529 None => device.create_graphics_pipeline(&GraphicsPipelineDesc {
11530 label: Some(&format!("rsm{side}")),
11531 layout,
11532 vertex: ShaderEntry {
11533 module: self.mesh,
11534 entry_point: self.vertex,
11535 },
11536 fragment,
11537 primitive,
11538 depth_stencil: Self::depth_stencil(),
11539 multisample: MultisampleState::default(),
11540 color_targets: &Self::RSM_TARGETS,
11541 }),
11542 }
11543 }
11544
11545 /// The pipeline that resets one tile of the shadow atlas, so a pass can keep
11546 /// some tiles and redraw others.
11547 ///
11548 /// Topic 45's cadence rung needs a tile cleared on its own,
11549 /// and the attachment's [`LoadOp`] cannot do it — a clear there covers the
11550 /// whole image, and the region-bounded forms are not portable. This is the
11551 /// portable statement of the same thing: `mesh.slang`'s
11552 /// `depthClearVertexMain` covers the viewport the shadow pass has already
11553 /// set over the tile, and the depth state below writes
11554 /// [`depth::CLEAR`](crcbl_hal::depth) over whatever was there.
11555 ///
11556 /// **[`CompareOp::Always`] and writes on**, which is the pair that makes it a
11557 /// clear rather than a draw: the tile holds the previous frame's depths, and
11558 /// under the engine's [`CompareOp::Greater`] a clear value of zero would
11559 /// fail against every one of them and leave the tile exactly as it was.
11560 ///
11561 /// **[`CullMode::None`]**, unlike [`MeshModules::primitive`]: the triangle
11562 /// is generated from `SV_VertexID` rather than wound by an artist, so a
11563 /// culling rule meant for scene geometry would decide whether the clear
11564 /// happens at all.
11565 ///
11566 /// **A vertex pipeline on every path**, including the mesh-shader one: a
11567 /// device with a mesh stage still has a vertex stage, and the clear has no
11568 /// clusters to descend.
11569 fn depth_clear_pipeline(
11570 &self,
11571 device: &dyn Device,
11572 layout: PipelineLayoutHandle,
11573 ) -> Result<GraphicsPipelineHandle, HalError> {
11574 device.create_graphics_pipeline(&GraphicsPipelineDesc {
11575 label: Some("shadow tile clear"),
11576 // The mesh layout, so binding this pipeline in the middle of the
11577 // shadow pass does not disturb the bind group the draws around it
11578 // are recorded with. The stage reads none of it.
11579 layout,
11580 vertex: ShaderEntry {
11581 module: self.mesh,
11582 entry_point: self.depth_clear_vertex,
11583 },
11584 fragment: None,
11585 primitive: PrimitiveState {
11586 cull_mode: CullMode::None,
11587 polygon_mode: PolygonMode::Fill,
11588 ..PrimitiveState::default()
11589 },
11590 depth_stencil: Some(DepthStencilState {
11591 depth_compare: CompareOp::Always,
11592 ..DepthStencilState::default()
11593 }),
11594 multisample: MultisampleState::default(),
11595 color_targets: &[],
11596 })
11597 }
11598
11599 /// Releases every module. The pipelines built from them stay valid.
11600 fn destroy(self, device: &dyn Device) {
11601 device.destroy_shader_module(self.mesh);
11602 if let Some(cluster) = self.cluster {
11603 device.destroy_shader_module(cluster.mesh_module);
11604 if let Some(task) = cluster.task_module {
11605 device.destroy_shader_module(task);
11606 }
11607 }
11608 }
11609}
11610
11611/// The entry point for `stage`, or an error naming the shader.
11612///
11613/// Unreachable in practice — `crcbl-shaders`' own tests assert both modules
11614/// expose both stages — but the alternative is an `expect` in engine code.
11615fn entry(shader: &crcbl_shaders::Shader, stage: Stage) -> Result<&'static str, HalError> {
11616 shader.entry_point(stage).ok_or_else(|| {
11617 HalError::ShaderCompilation(format!(
11618 "{}.slang exposes no unambiguous {stage:?} entry point; the committed SPIR-V and its \
11619 manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11620 shader.name()
11621 ))
11622 })
11623}
11624
11625/// The entry point called `name`, checked to be `stage`'s.
11626///
11627/// [`entry`] cannot serve `mesh_cluster.slang`: it has **two** mesh entry
11628/// points — one behind the amplification stage and one without it — and a
11629/// lookup by stage answers `None` for two matches rather than picking one, for
11630/// the good reason that picking one would draw the wrong geometry.
11631///
11632/// The stage is still checked rather than taken on trust: a name that resolved
11633/// to the wrong stage would be a pipeline built with an amplification stage in
11634/// its mesh slot, and the failure would arrive as a driver error rather than as
11635/// this sentence.
11636pub(crate) fn named_entry(
11637 shader: &crcbl_shaders::Shader,
11638 name: &'static str,
11639 stage: Stage,
11640) -> Result<&'static str, HalError> {
11641 let found = shader
11642 .entry_points()
11643 .iter()
11644 .find(|entry| entry.name() == name && entry.stage() == stage);
11645 found.map(crcbl_shaders::EntryPoint::name).ok_or_else(|| {
11646 HalError::ShaderCompilation(format!(
11647 "{}.slang exposes no {stage:?} entry point called `{name}`; the committed SPIR-V and \
11648 its manifest disagree, which crates/crcbl-shaders/tools/compile-shaders.sh would fix",
11649 shader.name()
11650 ))
11651 })
11652}
11653
11654// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
11655#[cfg(all(test, not(target_arch = "wasm32")))]
11656mod tests {
11657 mod instance_upload;
11658 mod load_service;
11659 mod page_reload;
11660 mod shadow_reach;
11661
11662 use super::*;
11663 use crate::effects::{Antialiasing, EffectOverride};
11664 use crate::scene::{
11665 DEMO_CUBE, DEMO_DUNES, DEMO_OPEN_BOX, DEMO_PYRAMID, DEMO_TEXTURED, DEMO_TINTED,
11666 DEMO_UNTINTED,
11667 };
11668 use crcbl_hal::null::{Event, NullInstance, ObjectKind, Recorder};
11669 use crcbl_hal::{DeviceDesc, DrawIndirect, Features, Instance, QueueKind};
11670
11671 #[test]
11672 fn refused_mesh_color_pipelines_release_successful_depth_pipelines() {
11673 let recorder = Recorder::new();
11674 let mut limits = crcbl_hal::Limits::desktop();
11675 limits.max_color_attachments = 2;
11676 let features = Features::COMPUTE | Features::MESH_SHADER;
11677 let instance = NullInstance::new(crcbl_hal::DeviceCaps { features, limits })
11678 .with_recorder(recorder.clone());
11679 let device = instance
11680 .create_device(&DeviceDesc {
11681 label: None,
11682 adapter: crcbl_hal::AdapterId(0),
11683 required_features: features,
11684 optional_features: Features::empty(),
11685 compatible_surface: None,
11686 })
11687 .unwrap();
11688 let queue = device.queue(QueueKind::Graphics).unwrap();
11689 let before = recorder.total_live_objects();
11690 let error = ForwardRenderer::with_scene_on_path(
11691 device.as_ref(),
11692 queue,
11693 Format::Rgba8UnormSrgb,
11694 &scene::demo(),
11695 GeometryPath::MeshShader,
11696 )
11697 .expect_err("three-target color pipelines must be refused");
11698 assert!(
11699 error
11700 .to_string()
11701 .contains("3 colour targets exceeds max_color_attachments 2"),
11702 "{error}"
11703 );
11704 assert!(
11705 recorder.events().iter().any(|event| matches!(
11706 event,
11707 Event::Created {
11708 kind: ObjectKind::GraphicsPipeline,
11709 ..
11710 }
11711 )),
11712 "the refusal must exercise cleanup of successful pipelines"
11713 );
11714 assert_eq!(
11715 recorder.total_live_objects(),
11716 before,
11717 "partial pipeline construction leaked resources"
11718 );
11719 recorder.assert_valid();
11720 }
11721
11722 #[test]
11723 fn exact_geometry_path_overrides_preference_and_default_keeps_it() {
11724 let recorder = Recorder::new();
11725 let instance = NullInstance::gpu_driven()
11726 .with_geometry_preference(GeometryPath::IndirectPerBatch)
11727 .with_recorder(recorder.clone());
11728 let device = instance
11729 .create_device(&DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)))
11730 .unwrap();
11731 let queue = device.queue(QueueKind::Graphics).unwrap();
11732 assert_eq!(device.caps().geometry_path(), GeometryPath::IndirectCount);
11733 let default = ForwardRenderer::with_scene(
11734 device.as_ref(),
11735 queue,
11736 Format::Rgba8UnormSrgb,
11737 &scene::demo(),
11738 )
11739 .unwrap();
11740 assert_eq!(default.geometry_path(), GeometryPath::IndirectPerBatch);
11741 default.destroy(device.as_ref());
11742 recorder.clear();
11743 let mut exact = ForwardRenderer::with_scene_on_path(
11744 device.as_ref(),
11745 queue,
11746 Format::Rgba8UnormSrgb,
11747 &scene::demo(),
11748 GeometryPath::IndirectCount,
11749 )
11750 .unwrap();
11751 assert_eq!(exact.geometry_path(), GeometryPath::IndirectCount);
11752 let rendered = frame(device.as_ref(), &mut exact, queue);
11753 let commands = commands_in_pass(&recorder, "forward");
11754 assert!(commands.iter().any(|command| matches!(
11755 command,
11756 crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
11757 )));
11758 assert!(
11759 !commands
11760 .iter()
11761 .any(|command| matches!(command, crcbl_hal::null::Command::DrawIndexedIndirect(_)))
11762 );
11763 rendered.finish(device.as_ref(), exact);
11764 }
11765
11766 /// **A device with a draw index draws a range of buckets per call, and one
11767 /// without it a call per bucket** — both indirect tails, read off the
11768 /// recorded stream of a whole frame.
11769 ///
11770 /// The ranged frame records one bind and one multi-draw per range in the
11771 /// depth prepass, whose draws together cover every bucket exactly once,
11772 /// and no count draw anywhere; the per-bucket frame records the call per
11773 /// bucket it always did. Both frames' counters are what they recorded.
11774 #[test]
11775 fn a_draw_index_puts_the_geometry_passes_on_a_call_per_range() {
11776 use crcbl_hal::null::Command;
11777
11778 for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11779 for ranged in [false, true] {
11780 let optional = if ranged {
11781 Features::GPU_DRIVEN | Features::DRAW_INDEX
11782 } else {
11783 DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features
11784 };
11785 let (recorder, device, queue) = open_with(optional);
11786 let mut renderer = ForwardRenderer::with_scene_on_path(
11787 device.as_ref(),
11788 queue,
11789 Format::Rgba8UnormSrgb,
11790 &scene::demo(),
11791 path,
11792 )
11793 .expect("the demo scene builds");
11794 assert_eq!(renderer.range_limit.is_some(), ranged, "{path:?}");
11795 let buckets = renderer.bucket_modes.len();
11796 assert!(buckets > 1, "one bucket packs into one call either way");
11797 let rendered = frame(device.as_ref(), &mut renderer, queue);
11798
11799 let commands = commands_in_pass(&recorder, "depth-prepass");
11800 let binds = commands
11801 .iter()
11802 .filter(|command| matches!(command, Command::BindGroup { slot: 0, .. }))
11803 .count();
11804 let draws: Vec<u32> = commands
11805 .iter()
11806 .filter_map(|command| match command {
11807 Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11808 Command::DrawIndexedIndirectCount(draw) => {
11809 assert!(!ranged, "{path:?}: a ranged pass records no count draw");
11810 assert_eq!(draw.max_draw_count, 1);
11811 Some(1)
11812 }
11813 _ => None,
11814 })
11815 .collect();
11816 assert_eq!(binds, draws.len(), "{path:?}: one bind per call");
11817 assert_eq!(
11818 draws.iter().sum::<u32>() as usize,
11819 buckets,
11820 "{path:?}: every bucket drawn once"
11821 );
11822 if ranged {
11823 assert!(
11824 draws.len() < buckets,
11825 "{path:?}: {draws:?} is a call per bucket over {buckets} buckets"
11826 );
11827 } else {
11828 assert_eq!(draws, vec![1; buckets], "{path:?}");
11829 }
11830 assert!(
11831 !recorder
11832 .commands()
11833 .iter()
11834 .any(|command| ranged
11835 && matches!(command, Command::DrawIndexedIndirectCount(_))),
11836 "{path:?}: a ranged frame records no count draw"
11837 );
11838 assert_eq!(
11839 renderer.counters().draws,
11840 recorded_draws(&recorder) as u64,
11841 "{path:?}, ranged {ranged}"
11842 );
11843 rendered.finish(device.as_ref(), renderer);
11844 recorder.assert_valid();
11845 }
11846 }
11847 }
11848
11849 /// **A scene holding every material mode draws each pipeline's buckets as
11850 /// one ranged call**, because the bucket table is numbered mode-major: the
11851 /// depth prepass records one call per depth pipeline and the colour pass
11852 /// one per sided pipeline, on both indirect tails.
11853 ///
11854 /// Numbered mesh by mesh, the same scene alternates modes bucket by bucket
11855 /// and every partition's runs are one bucket long, so the prepass would
11856 /// record a call per bucket — the counts below are what tell the two
11857 /// numberings apart, and the sums are what say every bucket still drew.
11858 #[test]
11859 fn every_mode_partition_of_a_ranged_frame_is_one_call() {
11860 use crcbl_hal::null::Command;
11861 use crcbl_shaders::mesh::GpuMaterial;
11862
11863 let scene = {
11864 let mut scene = crate::scene::demo();
11865 while scene.materials.len() < 4 {
11866 scene.materials.push(GpuMaterial::UNTINTED);
11867 }
11868 let rows = [
11869 0,
11870 GpuMaterial::ALPHA_MODE_MASK,
11871 GpuMaterial::DOUBLE_SIDED,
11872 GpuMaterial::MODE_MASK,
11873 ];
11874 for (row, flags) in scene.materials.iter_mut().zip(rows) {
11875 row.flags = flags;
11876 }
11877 scene
11878 };
11879 for path in [GeometryPath::IndirectCount, GeometryPath::IndirectPerBatch] {
11880 let (recorder, device, queue) = open_with(Features::GPU_DRIVEN | Features::DRAW_INDEX);
11881 let mut renderer = ForwardRenderer::with_scene_on_path(
11882 device.as_ref(),
11883 queue,
11884 Format::Rgba8UnormSrgb,
11885 &scene,
11886 path,
11887 )
11888 .expect("the four-mode demo builds");
11889 assert!(renderer.range_limit.is_some(), "{path:?}");
11890 let buckets = renderer.bucket_modes.len();
11891 let per_mode = buckets / DEPTH_MODES.len();
11892 assert_eq!(
11893 per_mode * DEPTH_MODES.len(),
11894 buckets,
11895 "{path:?}: four twins"
11896 );
11897 assert!(
11898 per_mode > 1,
11899 "{path:?}: a mode of one bucket is one call under either numbering"
11900 );
11901 let rendered = frame(device.as_ref(), &mut renderer, queue);
11902
11903 let draws = |label: &str| -> Vec<u32> {
11904 commands_in_pass(&recorder, label)
11905 .iter()
11906 .filter_map(|command| match command {
11907 Command::DrawIndexedIndirect(draw) => Some(draw.draw_count),
11908 _ => None,
11909 })
11910 .collect()
11911 };
11912 let prepass = draws("depth-prepass");
11913 assert_eq!(
11914 prepass,
11915 vec![u32::try_from(per_mode).expect("a few buckets"); DEPTH_MODES.len()],
11916 "{path:?}: one call per depth pipeline, each a whole mode"
11917 );
11918 let forward = draws("forward");
11919 assert_eq!(
11920 forward,
11921 vec![u32::try_from(2 * per_mode).expect("a few buckets"); 2],
11922 "{path:?}: one call per sided pipeline, each two adjacent modes"
11923 );
11924 rendered.finish(device.as_ref(), renderer);
11925 recorder.assert_valid();
11926 }
11927 }
11928
11929 /// **Behind an amplification stage the mesh tail records one flat call per
11930 /// partition, and without one a range of buckets per call on a device with
11931 /// a draw index and a call per bucket without** — read off the recorded
11932 /// stream of a whole frame.
11933 ///
11934 /// The flat calls are [`flat_dispatch_calls`]: one structure each, the
11935 /// colour pass's sided segments in region 0, under the segment's first
11936 /// bucket's block — whatever the bucket count, and whether or not the
11937 /// device granted a draw index, which the flat call does not read. Without
11938 /// the stage the colour pass's calls, unrolled a structure at a time, are
11939 /// exactly the per-bucket dispatches [`mesh_dispatch_calls`] names — every
11940 /// bucket's own extents, each once. Either way the counters are what the
11941 /// frame recorded.
11942 #[test]
11943 fn the_mesh_tail_records_a_flat_call_per_partition_behind_a_task_stage() {
11944 use crcbl_hal::null::Command;
11945
11946 // `None` is the demo scene; `Some(n)` is `n` copies of its cube, one
11947 // bucket each, in one material mode — so one run of `n` buckets.
11948 for cubes in [None, Some(4), Some(33)] {
11949 for task in [Features::TASK_SHADER, Features::empty()] {
11950 for ranged in [false, true] {
11951 let case = format!("{cubes:?} cubes, {task:?}, ranged {ranged}");
11952 let recorder = Recorder::new();
11953 let optional = if ranged {
11954 task | Features::DRAW_INDEX
11955 } else {
11956 task
11957 };
11958 let (device, queue) = open_mesh_path(&recorder, optional);
11959 let mut scene = scene::demo();
11960 if let Some(cubes) = cubes {
11961 scene.meshes = vec![scene.meshes[DEMO_CUBE].clone(); cubes as usize];
11962 scene.capacities.meshes = cubes;
11963 scene.capacities.vertices =
11964 cubes * crcbl_shaders::mesh::CUBE_VERTEX_COUNT as u32;
11965 scene.capacities.indices =
11966 cubes * crcbl_shaders::mesh::CUBE_INDEX_COUNT as u32;
11967 }
11968 let mut renderer = ForwardRenderer::with_scene_on_path(
11969 device.as_ref(),
11970 queue,
11971 Format::Rgba8UnormSrgb,
11972 &scene,
11973 GeometryPath::MeshShader,
11974 )
11975 .expect("the mesh renderer builds");
11976 assert_eq!(renderer.range_limit.is_some(), ranged, "{case}");
11977 assert_eq!(renderer.culls_clusters(), !task.is_empty(), "{case}");
11978 let buckets = renderer.bucket_constants.len();
11979 assert!(buckets > 1, "one bucket packs into one call either way");
11980 let rendered = frame(device.as_ref(), &mut renderer, queue);
11981
11982 let commands = commands_in_pass(&recorder, "forward");
11983 let bound: Vec<u32> = commands
11984 .iter()
11985 .filter_map(|command| match command {
11986 Command::BindGroup {
11987 slot: 0,
11988 dynamic_offsets,
11989 ..
11990 } => Some(dynamic_offsets[0]),
11991 _ => None,
11992 })
11993 .collect();
11994 let calls: Vec<DrawIndirect> = commands
11995 .iter()
11996 .filter_map(|command| match command {
11997 Command::DrawMeshTasksIndirect(draw) => Some(*draw),
11998 Command::DrawMeshTasks { .. }
11999 | Command::DrawIndexedIndirect(_)
12000 | Command::DrawIndexedIndirectCount(_) => {
12001 panic!("{case}: the mesh tail recorded {command:?}")
12002 }
12003 _ => None,
12004 })
12005 .collect();
12006 assert_eq!(bound.len(), calls.len(), "{case}: one bind per call");
12007 assert!(
12008 calls
12009 .iter()
12010 .all(|call| call.stride
12011 == crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32),
12012 "{case}: one structure a bucket, or a flat call's one"
12013 );
12014 if task.is_empty() {
12015 // Each call a structure at a time: what a call per
12016 // bucket would have recorded for the buckets it
12017 // stands for.
12018 let mut unrolled: Vec<DrawIndirect> = calls
12019 .iter()
12020 .flat_map(|call| {
12021 (0..call.draw_count).map(|draw| DrawIndirect {
12022 offset: call.offset + u64::from(draw) * u64::from(call.stride),
12023 draw_count: 1,
12024 ..*call
12025 })
12026 })
12027 .collect();
12028 unrolled.sort_by_key(|draw| draw.offset);
12029 assert_eq!(
12030 unrolled,
12031 mesh_dispatch_calls(&renderer),
12032 "{case}: every bucket's own extents, each once"
12033 );
12034 let counts: Vec<u32> = calls.iter().map(|call| call.draw_count).collect();
12035 match (ranged, cubes) {
12036 (false, _) => assert_eq!(counts, vec![1; buckets], "{case}"),
12037 (true, Some(cubes)) => assert_eq!(counts, vec![cubes], "{case}"),
12038 (true, None) => assert!(
12039 calls.len() < buckets,
12040 "{case}: {counts:?} is a call per bucket over {buckets} buckets"
12041 ),
12042 }
12043 } else {
12044 let (expected, firsts) = flat_dispatch_calls(
12045 &renderer,
12046 crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED,
12047 );
12048 assert_eq!(calls, expected, "{case}: one flat call per sided partition");
12049 assert_eq!(
12050 bound,
12051 firsts
12052 .iter()
12053 .map(|&bucket| renderer.bucket_constants[bucket as usize])
12054 .collect::<Vec<_>>(),
12055 "{case}: each under its segment's first bucket's block"
12056 );
12057 }
12058 assert_eq!(
12059 renderer.counters().draws,
12060 recorded_draws(&recorder) as u64,
12061 "{case}"
12062 );
12063 rendered.finish(device.as_ref(), renderer);
12064 recorder.assert_valid();
12065 }
12066 }
12067 }
12068 }
12069
12070 /// **Draw `d` of a ranged mesh call reads the words bucket `first + d`'s own
12071 /// block carries**, in every draw region.
12072 ///
12073 /// The host half of `mesh_cluster.slang`'s "One call for a range of
12074 /// buckets": a ranged call binds its first bucket's block alone, and the
12075 /// SPIR-V stages add the draw index to its `start_at` and `bucket` and to
12076 /// the two table words it names. So each bucket's block has to sit one word
12077 /// past the one before in all four, and the table words have to hold the
12078 /// bucket's own cluster base and count — read out of the bytes that reached
12079 /// the device, since a block written wrong leaves the renderer's fields
12080 /// right.
12081 #[test]
12082 fn a_mesh_block_names_the_words_a_ranged_draw_reads() {
12083 let recorder = Recorder::new();
12084 let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
12085 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12086 .expect("the mesh renderer builds");
12087 let blocks = recorder
12088 .buffer_bytes(renderer.draw_constants)
12089 .expect("the blocks are live");
12090 let tables = recorder
12091 .buffer_bytes(renderer.primary.draws.tables())
12092 .expect("the tables are live");
12093 let word = |bytes: &[u8], at: usize| {
12094 u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes"))
12095 };
12096 let buckets = renderer.bucket_constants.len();
12097 assert!(buckets > 1, "a range needs two buckets to step between");
12098 let bucket_count = u32::try_from(buckets).expect("a few buckets");
12099 let stride = renderer.bucket_constants[1] - renderer.bucket_constants[0];
12100 let block = |region: u32, bucket: u32| {
12101 let at = ((region * bucket_count + bucket) * stride) as usize;
12102 let field = |index: usize| word(&blocks, at + index * 4);
12103 crcbl_shaders::meshlet::ClusterDrawConstants {
12104 start_at: field(0),
12105 cluster_base: field(1),
12106 cluster_count: field(2),
12107 bucket: field(3),
12108 group_stride: field(4),
12109 level_groups_at: field(5),
12110 cluster_base_at: field(6),
12111 cluster_count_at: field(7),
12112 chunk_starts_at: field(8),
12113 chunk_starts_end: field(9),
12114 }
12115 };
12116 let mut bases = Vec::new();
12117 for region in 0..crcbl_shaders::draw_gen::DRAW_REGIONS {
12118 let first = block(region, 0);
12119 for bucket in 0..bucket_count {
12120 let own = block(region, bucket);
12121 assert_eq!(
12122 word(&tables, own.cluster_base_at as usize * 4),
12123 own.cluster_base,
12124 "region {region} bucket {bucket}: the base word holds the base"
12125 );
12126 assert_eq!(
12127 word(&tables, own.cluster_count_at as usize * 4),
12128 own.cluster_count,
12129 "region {region} bucket {bucket}: the count word holds the count"
12130 );
12131 // What draw `bucket` of a call bound at bucket 0's block reads
12132 // — and a flat call's workgroup that found bucket `bucket` by
12133 // searching the chunk starts from bucket 0's word to the
12134 // region's end.
12135 assert_eq!(
12136 (
12137 first.start_at + bucket,
12138 first.bucket + bucket,
12139 first.cluster_base_at + bucket,
12140 first.cluster_count_at + bucket,
12141 first.group_stride,
12142 first.level_groups_at,
12143 first.chunk_starts_at + bucket,
12144 first.chunk_starts_end,
12145 ),
12146 (
12147 own.start_at,
12148 own.bucket,
12149 own.cluster_base_at,
12150 own.cluster_count_at,
12151 own.group_stride,
12152 own.level_groups_at,
12153 own.chunk_starts_at,
12154 own.chunk_starts_end,
12155 ),
12156 "region {region} bucket {bucket}"
12157 );
12158 assert_eq!(
12159 own.chunk_starts_at,
12160 crcbl_shaders::draw_gen::chunk_start_word(
12161 renderer.primary.draws.visible_capacity(),
12162 bucket_count,
12163 region,
12164 bucket,
12165 ),
12166 "region {region} bucket {bucket}: the word draw_gen writes its chunks' start into"
12167 );
12168 assert_eq!(
12169 own.chunk_starts_end - own.chunk_starts_at,
12170 bucket_count - bucket,
12171 "region {region} bucket {bucket}: the search ends at the region's end word"
12172 );
12173 if region == 0 {
12174 bases.push(own.cluster_base);
12175 }
12176 }
12177 }
12178 assert!(
12179 bases.windows(2).any(|pair| pair[0] != pair[1]),
12180 "the buckets' meshes start at different clusters, so a range reading its \
12181 first bucket's base for every draw would be seen: {bases:?}"
12182 );
12183 renderer.destroy(device.as_ref());
12184 recorder.assert_valid();
12185 }
12186
12187 #[test]
12188 fn exact_geometry_path_builds_supported_tails_and_refuses_missing_features_without_allocating()
12189 {
12190 for features in [
12191 Features::GPU_DRIVEN,
12192 Features::COMPUTE | Features::MESH_SHADER,
12193 ] {
12194 let recorder = Recorder::new();
12195 let instance = NullInstance::new(crcbl_hal::DeviceCaps {
12196 features,
12197 limits: crcbl_hal::Limits::desktop(),
12198 })
12199 .with_recorder(recorder.clone());
12200 let device = instance
12201 .create_device(&DeviceDesc {
12202 label: None,
12203 adapter: crcbl_hal::AdapterId(0),
12204 required_features: Features::COMPUTE,
12205 optional_features: features,
12206 compatible_surface: None,
12207 })
12208 .expect("null device opens");
12209 let queue = device.queue(QueueKind::Graphics).unwrap();
12210 for (path, required) in [
12211 (GeometryPath::IndirectPerBatch, Features::empty()),
12212 (GeometryPath::IndirectCount, Features::DRAW_INDIRECT_COUNT),
12213 (GeometryPath::MeshShader, Features::MESH_SHADER),
12214 ] {
12215 recorder.clear();
12216 let result = ForwardRenderer::with_scene_on_path(
12217 device.as_ref(),
12218 queue,
12219 Format::Rgba8UnormSrgb,
12220 &scene::demo(),
12221 path,
12222 );
12223 if features.contains(required) {
12224 let renderer = result.expect("supported exact tail builds");
12225 assert_eq!(renderer.geometry_path(), path);
12226 renderer.destroy(device.as_ref());
12227 } else {
12228 assert!(
12229 matches!(result, Err(HalError::UnsupportedFeatures { missing }) if missing == required)
12230 );
12231 assert!(
12232 recorder.events().is_empty(),
12233 "unsupported selection must not touch device objects"
12234 );
12235 }
12236 recorder.assert_valid();
12237 }
12238 }
12239 }
12240
12241 pub(super) fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
12242 open_with(DeviceDesc::for_adapter(crcbl_hal::AdapterId(0)).optional_features)
12243 }
12244
12245 /// [`open`] asking for `optional_features` instead of
12246 /// [`DeviceDesc::for_adapter`]'s.
12247 ///
12248 /// The null preset *has* more than the default request asks for, and a
12249 /// granted feature set is the intersection of the two — so this is how a test
12250 /// reaches a device with something the ordinary one lacks. What it exists for
12251 /// is [`Features::POLYGON_MODE_LINE`]: with the default request, `open`'s
12252 /// device has no line fill mode, which is the other half of the wireframe
12253 /// pair of tests below.
12254 fn open_with(optional_features: Features) -> (Recorder, Box<dyn Device>, QueueHandle) {
12255 let recorder = Recorder::new();
12256 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
12257 let adapter = instance.adapters().remove(0);
12258 let device = instance
12259 .create_device(&DeviceDesc {
12260 optional_features,
12261 ..DeviceDesc::for_adapter(adapter.id)
12262 })
12263 .expect("the null backend always opens");
12264 let queue = device.queue(QueueKind::Graphics).expect("always present");
12265 (recorder, device, queue)
12266 }
12267
12268 /// Puts one of [`scene::demo`]'s meshes in the frame the way a caller does.
12269 ///
12270 /// **Insertion order is what the caller decides**, and it is load-bearing:
12271 /// the slot an object lands in is topic 25's hysteresis key. So
12272 /// every test below places its objects in the order the frame used to hold
12273 /// them — the cube first, wherever there is one.
12274 fn place_demo(
12275 renderer: &mut ForwardRenderer,
12276 mesh: usize,
12277 material: usize,
12278 transform: Mat4,
12279 ) -> InstanceHandle {
12280 renderer
12281 .add_instance(&InstanceDesc {
12282 mesh,
12283 material,
12284 transform,
12285 })
12286 .expect("a pool of thousands has room for a handful of objects")
12287 }
12288
12289 /// [`scene::demo`]'s cube, placed **first** so it takes the pool slot it has
12290 /// always had.
12291 ///
12292 /// `begin_frame` used to write this object for every caller; the tests below
12293 /// that are about a frame with something in it place it themselves now.
12294 pub(super) fn place_cube(renderer: &mut ForwardRenderer, transform: Mat4) -> InstanceHandle {
12295 place_demo(renderer, DEMO_CUBE, DEMO_UNTINTED, transform)
12296 }
12297
12298 /// The whole renderer builds and tears down against a backend with no
12299 /// driver, which is what makes it testable on every CI leg.
12300 #[test]
12301 fn the_forward_renderer_builds_and_leaks_nothing() {
12302 let (recorder, device, queue) = open();
12303 let before = recorder.total_live_objects();
12304 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
12305 .expect("the null backend accepts every descriptor");
12306 assert_eq!(renderer.target_format(), Format::Rgba8UnormSrgb);
12307 assert!(recorder.total_live_objects() > before);
12308 renderer.destroy(device.as_ref());
12309 assert_eq!(
12310 recorder.total_live_objects(),
12311 before,
12312 "every object created must be destroyed"
12313 );
12314 recorder.assert_valid();
12315 }
12316
12317 /// The uniform ring really rotates, or a spinning cube is a
12318 /// read-after-write hazard across submissions.
12319 #[test]
12320 fn the_uniform_ring_rotates() {
12321 let (_, device, queue) = open();
12322 let mut renderer =
12323 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12324 let camera = Camera::default();
12325 let light = DirectionalLight::default();
12326
12327 let mut seen = Vec::new();
12328 for _ in 0..FRAMES_IN_FLIGHT * 2 {
12329 renderer
12330 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12331 .expect("write");
12332 seen.push(renderer.primary.uniforms[renderer.frame]);
12333 }
12334 assert_ne!(
12335 seen[0], seen[1],
12336 "consecutive frames must not share a buffer"
12337 );
12338 assert_eq!(seen[0], seen[FRAMES_IN_FLIGHT], "and the ring must wrap");
12339 renderer.destroy(device.as_ref());
12340 }
12341
12342 /// **The tonemap's block is a ring too, and it carries the exposure the
12343 /// caller set.**
12344 ///
12345 /// The bytes are the observable rather than the field, because the field is
12346 /// what a renderer that never wired the block up would also have: the claim
12347 /// is that the number reaches the buffer `tonemap.slang` reads, and only the
12348 /// null recorder's write log can say so.
12349 ///
12350 /// The default is checked first — a renderer nobody has called
12351 /// [`ForwardRenderer::set_exposure`] on writes the value the shader's
12352 /// `EXPOSURE` constant held, under
12353 /// [`ForwardRenderer::set_tonemap_curve`]'s own default.
12354 #[test]
12355 fn the_tonemap_block_holds_the_exposure_and_rotates_with_the_frame() {
12356 let (recorder, device, queue) = open();
12357 let mut renderer =
12358 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12359 let camera = Camera::default();
12360 let light = DirectionalLight::default();
12361
12362 renderer
12363 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12364 .expect("write");
12365 assert_eq!(
12366 recorder
12367 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12368 .expect("begin_frame wrote the block"),
12369 crcbl_shaders::tonemap::TonemapParams {
12370 exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12371 curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12372 auto_exposure: false,
12373 coverage_alpha: false,
12374 }
12375 .to_bytes(),
12376 "an untouched renderer must write the exposure the constant used to hold, \
12377 under the operator this renderer starts on",
12378 );
12379
12380 // A value that is neither the default nor a bound, so a block left at
12381 // either would fail.
12382 renderer.set_exposure(3.5);
12383 let mut slots = Vec::new();
12384 for _ in 0..FRAMES_IN_FLIGHT * 2 {
12385 renderer
12386 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12387 .expect("write");
12388 slots.push(renderer.primary.tonemap_uniforms[renderer.frame]);
12389 assert_eq!(
12390 recorder
12391 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12392 .expect("begin_frame wrote the block"),
12393 crcbl_shaders::tonemap::TonemapParams {
12394 exposure: 3.5,
12395 curve: crcbl_shaders::tonemap::TonemapCurve::Aces,
12396 auto_exposure: false,
12397 coverage_alpha: false,
12398 }
12399 .to_bytes(),
12400 "the frame's own block must carry the exposure in force",
12401 );
12402 }
12403 assert_ne!(
12404 slots[0], slots[1],
12405 "consecutive frames must not share a block"
12406 );
12407 assert_eq!(slots[0], slots[FRAMES_IN_FLIGHT], "and the ring must wrap");
12408
12409 renderer.destroy(device.as_ref());
12410 }
12411
12412 /// **The curve reaches the block, and a caller can move it off the
12413 /// default.**
12414 ///
12415 /// The selector is a lane of the same ring the exposure rides in, and a lane
12416 /// nothing wrote would read as
12417 /// [`TonemapCurve::Clamp`](crcbl_shaders::tonemap::TonemapCurve::Clamp)
12418 /// whatever a caller asked for — a setter that compiles, a frame that looks
12419 /// right, and a curve that never runs. Since the renderer now *starts* on
12420 /// the fit, that failure would read as a working default, so the check runs
12421 /// in both directions: the untouched block carries the fit, and asking for
12422 /// the clamp changes the bytes on every frame of the ring.
12423 #[test]
12424 fn the_tonemap_block_carries_the_curve_a_caller_selected() {
12425 use crcbl_shaders::tonemap::TonemapCurve;
12426
12427 let (recorder, device, queue) = open();
12428 let mut renderer =
12429 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12430 let camera = Camera::default();
12431 let light = DirectionalLight::default();
12432
12433 assert_eq!(
12434 renderer.tonemap_curve(),
12435 TonemapCurve::Aces,
12436 "a renderer nobody configured must run the operator the goldens were blessed under",
12437 );
12438 renderer
12439 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12440 .expect("write");
12441 let by_default = recorder
12442 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12443 .expect("begin_frame wrote the block");
12444
12445 renderer.set_tonemap_curve(TonemapCurve::Clamp);
12446 assert_eq!(renderer.tonemap_curve(), TonemapCurve::Clamp);
12447 for _ in 0..FRAMES_IN_FLIGHT * 2 {
12448 renderer
12449 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12450 .expect("write");
12451 let written = recorder
12452 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12453 .expect("begin_frame wrote the block");
12454 assert_eq!(
12455 written,
12456 crcbl_shaders::tonemap::TonemapParams {
12457 exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12458 curve: TonemapCurve::Clamp,
12459 auto_exposure: false,
12460 coverage_alpha: false,
12461 }
12462 .to_bytes(),
12463 "every frame of the ring must carry the selected curve",
12464 );
12465 assert_ne!(
12466 written, by_default,
12467 "and it must differ from the block a default renderer writes",
12468 );
12469 }
12470
12471 // **A readout runs the clamp whatever was selected**, and the selection
12472 // survives it: the caller's curve is still the caller's, the frame's is
12473 // the identity, and the shaded frame after gets the curve back. Asked of
12474 // the fit, which is the selection a readout has something to lose under.
12475 renderer.set_tonemap_curve(TonemapCurve::Aces);
12476 renderer.set_normals_view(true);
12477 assert_eq!(renderer.tonemap_curve(), TonemapCurve::Aces);
12478 assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Clamp);
12479 renderer
12480 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12481 .expect("write");
12482 assert_eq!(
12483 recorder
12484 .buffer_bytes(renderer.primary.tonemap_uniforms[renderer.frame])
12485 .expect("begin_frame wrote the block"),
12486 crcbl_shaders::tonemap::TonemapParams {
12487 exposure: crcbl_shaders::tonemap::DEFAULT_EXPOSURE,
12488 curve: TonemapCurve::Clamp,
12489 auto_exposure: false,
12490 coverage_alpha: false,
12491 }
12492 .to_bytes(),
12493 "a debug view's block must carry the clamp, since its pixels are data",
12494 );
12495 renderer.set_normals_view(false);
12496 assert_eq!(renderer.resolved_tonemap_curve(), TonemapCurve::Aces);
12497
12498 renderer.destroy(device.as_ref());
12499 }
12500
12501 /// **The exposure is clamped where it is set**, so no caller can reach a
12502 /// frame it cannot get back from.
12503 ///
12504 /// Each case is a different way of leaving the range, and the NaN one is the
12505 /// reason [`ForwardRenderer::set_exposure`] does not use `f32::clamp`: that
12506 /// propagates a NaN into the block, which is a frame of NaN pixels with no
12507 /// key to press to escape it.
12508 #[test]
12509 fn the_exposure_setter_clamps_to_a_range_a_caller_can_come_back_from() {
12510 let (_, device, queue) = open();
12511 let mut renderer =
12512 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12513 assert!(
12514 (renderer.exposure() - crcbl_shaders::tonemap::DEFAULT_EXPOSURE).abs() < f32::EPSILON,
12515 "the default is {}",
12516 renderer.exposure(),
12517 );
12518
12519 for (asked, expected) in [
12520 (2.0, 2.0),
12521 (EXPOSURE_MAX * 4.0, EXPOSURE_MAX),
12522 (f32::INFINITY, EXPOSURE_MAX),
12523 (EXPOSURE_MIN / 4.0, EXPOSURE_MIN),
12524 (0.0, EXPOSURE_MIN),
12525 (-8.0, EXPOSURE_MIN),
12526 (f32::NEG_INFINITY, EXPOSURE_MIN),
12527 (f32::NAN, EXPOSURE_MIN),
12528 ] {
12529 renderer.set_exposure(asked);
12530 assert!(
12531 (renderer.exposure() - expected).abs() < f32::EPSILON,
12532 "{asked} was clamped to {}, not {expected}",
12533 renderer.exposure(),
12534 );
12535 }
12536
12537 renderer.destroy(device.as_ref());
12538 }
12539
12540 /// **The debug views resolve in one order, however they are set.**
12541 ///
12542 /// Every one of them rides in one float lane and the shaders test the
12543 /// outermost threshold first, so a renderer with two switches on draws
12544 /// exactly one picture — and which one has to be a rule rather than
12545 /// whichever branch a caller's setter happened to run last. Every
12546 /// combination of the switches is walked, because a precedence written as an
12547 /// `if` chain is right for most of them by accident: a chain in the wrong
12548 /// order agrees with this one on every combination where at most one switch
12549 /// is set.
12550 ///
12551 /// **The two innermost views are the exception the walk is worth most for.**
12552 /// [`DebugView::Cascades`] keeps the shaded picture rather than replacing
12553 /// it, so it resolves *last* and its sentinel runs the other way down the
12554 /// lane; [`DebugView::ShadowAtlas`] resolves just above it and carries the
12555 /// *off* sentinel, because it is a pass rather than a branch. Every
12556 /// combination where either is set beside a replacing view is a combination
12557 /// an order written any other way answers differently, and there is no
12558 /// single-switch case that could tell them apart.
12559 ///
12560 /// [`ForwardRenderer::debug_view`] is asserted beside the lane, so the value
12561 /// a panel reads back and the value the shader branches on cannot drift —
12562 /// they are the same function.
12563 #[test]
12564 fn the_debug_views_resolve_in_one_order_however_they_are_set() {
12565 // `w` of the second `float4` of the block — the lane
12566 // `the_normals_view_moves_the_ambients_last_lane_and_no_other_byte`
12567 // spells out, and for its reason.
12568 const AMBIENT_W: usize = 64 + 16 + 12;
12569
12570 let (recorder, device, queue) = open();
12571 let mut renderer =
12572 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12573 let camera = Camera::default();
12574 let light = DirectionalLight::default();
12575
12576 for bent in [false, true] {
12577 for motion in [false, true] {
12578 for occlusion in [false, true] {
12579 for heatmap in [false, true] {
12580 for lod in [false, true] {
12581 for normals in [false, true] {
12582 for (atlas, cascades) in
12583 [false, true].into_iter().flat_map(|atlas| {
12584 [false, true].map(|cascades| (atlas, cascades))
12585 })
12586 {
12587 renderer.set_bent_normal_view(bent);
12588 renderer.set_motion_view(motion);
12589 renderer.set_occlusion_view(occlusion);
12590 renderer.set_heatmap(heatmap);
12591 renderer.set_lod_view(lod);
12592 renderer.set_normals_view(normals);
12593 renderer.set_atlas_view(atlas);
12594 renderer.set_cascade_view(cascades);
12595 let set = format!(
12596 "bent={bent} motion={motion} occlusion={occlusion} \
12597 heatmap={heatmap} lod={lod} normals={normals} \
12598 atlas={atlas} cascades={cascades}"
12599 );
12600 // Each switch reads back what it was set to, whatever
12601 // the others are: a caller's toggle is about the
12602 // caller's setting, and only `debug_view` is about the
12603 // picture.
12604 assert_eq!(renderer.bent_normal_view(), bent);
12605 assert_eq!(renderer.motion_view(), motion);
12606 assert_eq!(renderer.occlusion_view(), occlusion);
12607 assert_eq!(renderer.heatmap(), heatmap);
12608 assert_eq!(renderer.lod_view(), lod);
12609 assert_eq!(renderer.normals_view(), normals);
12610 assert_eq!(renderer.atlas_view(), atlas);
12611 assert_eq!(renderer.cascade_view(), cascades);
12612
12613 let expected = if bent {
12614 DebugView::BentNormal
12615 } else if motion {
12616 DebugView::Motion
12617 } else if occlusion {
12618 DebugView::AmbientOcclusion
12619 } else if heatmap {
12620 DebugView::Heatmap
12621 } else if lod {
12622 DebugView::LodTint
12623 } else if normals {
12624 DebugView::Normals
12625 } else if atlas {
12626 // **Below every replacing view above and
12627 // above the tint below**, which is the
12628 // half of this order no single-switch
12629 // case reaches: with a replacing view
12630 // also set the frame is that view's, and
12631 // with the tint also set the frame is the
12632 // atlas.
12633 DebugView::ShadowAtlas
12634 } else if cascades {
12635 // **Last, which is the half of this order a
12636 // chain in any other arrangement would get
12637 // right by accident.** The cascade tint is a
12638 // multiply on the shaded picture, so every
12639 // combination that also names a replacing
12640 // view has to resolve to *that* view — and
12641 // those are exactly the combinations an
12642 // `if cascades` written one line higher
12643 // would answer differently.
12644 DebugView::Cascades
12645 } else {
12646 DebugView::Shaded
12647 };
12648 assert_eq!(renderer.debug_view(), expected, "{set}");
12649
12650 renderer
12651 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12652 .expect("write");
12653 let block = recorder
12654 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12655 .expect("begin_frame wrote the block");
12656 let sentinel = match expected {
12657 DebugView::BentNormal => {
12658 mesh::FrameUniforms::BENT_NORMAL_VIEW_ON
12659 }
12660 DebugView::Motion => mesh::FrameUniforms::MOTION_VIEW_ON,
12661 DebugView::AmbientOcclusion => {
12662 mesh::FrameUniforms::OCCLUSION_VIEW_ON
12663 }
12664 DebugView::Heatmap => mesh::FrameUniforms::HEATMAP_VIEW_ON,
12665 DebugView::LodTint => mesh::FrameUniforms::LOD_VIEW_ON,
12666 DebugView::Normals => mesh::FrameUniforms::NORMALS_VIEW_ON,
12667 DebugView::Cascades => mesh::FrameUniforms::CASCADE_VIEW_ON,
12668 // **The atlas view carries the *off*
12669 // sentinel**, which is what makes this
12670 // assertion say something rather than
12671 // restate `debug_view_lane`: the colour
12672 // pass draws the shaded picture and
12673 // `crate::atlas_view`'s pass replaces
12674 // it, so a lane of its own here would be
12675 // a threshold no shader tests.
12676 DebugView::ShadowAtlas | DebugView::Shaded => {
12677 mesh::FrameUniforms::NORMALS_VIEW_OFF
12678 }
12679 };
12680 assert_eq!(
12681 &block[AMBIENT_W..AMBIENT_W + 4],
12682 &sentinel.to_le_bytes(),
12683 "{set} resolved to {expected:?}, and the lane says otherwise"
12684 );
12685 // And the resolve comes off for every one of them:
12686 // these frames are read back as data, so their colours
12687 // have to stay the ones the shader wrote — see
12688 // `resolved_effects`. The whole slot rather than one
12689 // tier of it, because which tier the default carries
12690 // is not what this is about.
12691 assert_eq!(
12692 renderer.effects().intersects(Antialiasing::SLOT),
12693 expected == DebugView::Shaded,
12694 "{set}"
12695 );
12696 }
12697 }
12698 }
12699 }
12700 }
12701 }
12702 }
12703
12704 renderer.destroy(device.as_ref());
12705 }
12706
12707 /// **The atlas viewer records one pass, and only on the frame it is the view
12708 /// showing.**
12709 ///
12710 /// The mechanism no other check in this file can see. Every other debug view
12711 /// is a lane of the frame block, so
12712 /// [`the_debug_views_resolve_in_one_order_however_they_are_set`] observes it
12713 /// by reading four bytes; this one is a *pass*, and "the pass was recorded"
12714 /// is a claim about the command stream and about nothing else. A switch that
12715 /// resolved correctly and recorded nothing would satisfy every other
12716 /// assertion in this module and draw the frame unchanged.
12717 ///
12718 /// Three arms, and the third is the one that makes the first two mean
12719 /// something:
12720 ///
12721 /// * off — no pass at all, which is what makes the off position
12722 /// bit-identical for every golden in this workspace;
12723 /// * on — the pass, with the full-screen triangle in it;
12724 /// * on **beside a replacing view** — no pass, because
12725 /// [`ForwardRenderer::debug_view`] resolved to that view and the atlas is
12726 /// not what this frame draws. That is the half a `self.atlas_view` read at
12727 /// the recording site would get wrong while passing both arms above.
12728 ///
12729 /// [`the_debug_views_resolve_in_one_order_however_they_are_set`]: fn@the_debug_views_resolve_in_one_order_however_they_are_set
12730 /// **The shadow atlas viewer replaces the tonemap and the ground grid, and
12731 /// the draw count follows.**
12732 ///
12733 /// The viewer fills every display pixel with a `DontCare` load, so a
12734 /// tonemapped frame or a grid recorded under it is stored and discarded.
12735 /// The pass counts go red if either comes back; the counter goes red if
12736 /// `counters` still charges the frame for the triangles it no longer
12737 /// records.
12738 #[test]
12739 fn the_atlas_viewer_replaces_the_display_passes_and_the_count_follows() {
12740 let (recorder, device, queue) = open();
12741 let mut renderer =
12742 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12743 renderer
12744 .set_ground_grid(device.as_ref(), Some(GridStyle::default()))
12745 .expect("the null backend builds every pipeline");
12746 renderer.set_atlas_view(true);
12747 assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12748
12749 let viewing = frame(device.as_ref(), &mut renderer, queue);
12750 let opened = |label: &str| {
12751 recorder
12752 .commands()
12753 .iter()
12754 .filter(|command| {
12755 matches!(command.opens_pass(), Some((_, Some(recorded))) if recorded == label)
12756 })
12757 .count()
12758 };
12759 assert_eq!(opened(crate::atlas_view::LABEL), 1);
12760 assert_eq!(opened("tonemap"), 0, "the viewer discards the tonemap");
12761 assert_eq!(opened("grid"), 0, "and the grid drawn over it");
12762 assert_eq!(
12763 renderer.counters().draws,
12764 recorded_draws(&recorder) as u64,
12765 "the counter charges the frame for exactly the draws it recorded"
12766 );
12767 viewing.finish(device.as_ref(), renderer);
12768 }
12769
12770 #[test]
12771 fn the_atlas_viewer_records_its_pass_only_when_it_is_the_view_showing() {
12772 use crcbl_hal::null::Command;
12773
12774 let (recorder, device, queue) = open();
12775 let device = device.as_ref();
12776 let mut renderer =
12777 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
12778 let (camera, sun) = (Camera::default(), DirectionalLight::default());
12779
12780 // How many times the viewer's pass was opened since `from`, which is
12781 // where the previous arm's commands ended.
12782 let opened = |from: usize| {
12783 recorder.commands()[from..]
12784 .iter()
12785 .filter(|command| {
12786 matches!(
12787 command.opens_pass(),
12788 Some((_, Some(recorded))) if recorded == crate::atlas_view::LABEL
12789 )
12790 })
12791 .count()
12792 };
12793
12794 let shaded = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12795 assert_eq!(
12796 opened(0),
12797 0,
12798 "a frame drawing the shaded picture recorded the atlas viewer's pass"
12799 );
12800 let after_shaded = recorder.commands().len();
12801 shaded.release(device);
12802
12803 renderer.set_atlas_view(true);
12804 assert_eq!(renderer.debug_view(), DebugView::ShadowAtlas);
12805 let viewing = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12806 assert_eq!(
12807 opened(after_shaded),
12808 1,
12809 "the atlas viewer is on and its pass was not recorded exactly once"
12810 );
12811 // And what it recorded is the over-sized triangle and nothing else: a
12812 // pass that bound a pipeline and drew no vertices would open above and
12813 // leave the frame the tonemap wrote.
12814 let drawn: Vec<(u32, u32)> = commands_in_pass(&recorder, crate::atlas_view::LABEL)
12815 .into_iter()
12816 .filter_map(|command| match command {
12817 Command::Draw {
12818 vertices,
12819 instances,
12820 } => Some((
12821 vertices.end - vertices.start,
12822 instances.end - instances.start,
12823 )),
12824 _ => None,
12825 })
12826 .collect();
12827 assert_eq!(drawn, vec![(crate::atlas_view::FULLSCREEN_VERTICES, 1)]);
12828 let after_viewing = recorder.commands().len();
12829 viewing.release(device);
12830
12831 // The switch left on, and a replacing view asked for over the top of it.
12832 renderer.set_normals_view(true);
12833 assert_eq!(
12834 renderer.debug_view(),
12835 DebugView::Normals,
12836 "the atlas view does not lose to a replacing view, so the arm below asks nothing"
12837 );
12838 let normals = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
12839 assert_eq!(
12840 opened(after_viewing),
12841 0,
12842 "the frame resolved to the normals view and still recorded the atlas viewer's \
12843 pass over the top of it"
12844 );
12845 normals.release(device);
12846
12847 renderer.destroy(device);
12848 }
12849
12850 /// **The heatmap moves the ambient's last lane and no other byte**, and
12851 /// switching it off puts the block back.
12852 ///
12853 /// The normals view's assertion below, for the outermost of the three: the
12854 /// overlay costs one lane, so every golden image ever blessed is untouched
12855 /// by the feature existing. The `lod_params` row the heatmap reads is
12856 /// written every frame whether it is on or not — it is the numbers the
12857 /// selection used — so this compares two frames of the *same* camera and
12858 /// budget, where that row is equal on both sides and any byte outside the
12859 /// lane is a real difference.
12860 #[test]
12861 fn the_heatmap_moves_the_ambients_last_lane_and_no_other_byte() {
12862 const AMBIENT_W: usize = 64 + 16 + 12;
12863
12864 // Held for the whole comparison, and it is not this check's own knob:
12865 // `r_shadow_filter` and `r_shadow_split` land in the block's
12866 // `shadow_filter` row on every `begin_frame`, and the filter checks in
12867 // this module move them under this lock while `cargo test` runs the
12868 // module's checks as threads of one process. Two frames read either side
12869 // of such a move differ at that row, which is outside every lane below —
12870 // one run in twelve, measured 2026-09-04.
12871 let _filter = shadow_filter_switch();
12872 let (recorder, device, queue) = open();
12873 let mut renderer =
12874 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12875 let camera = Camera::default();
12876 let light = DirectionalLight::default();
12877 let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12878 renderer
12879 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12880 .expect("write");
12881 recorder
12882 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12883 .expect("begin_frame wrote the block")
12884 };
12885
12886 assert!(
12887 !renderer.heatmap(),
12888 "the heatmap has to be off in a renderer nobody has asked",
12889 );
12890 let shaded = block(&mut renderer);
12891 assert_eq!(
12892 &shaded[AMBIENT_W..AMBIENT_W + 4],
12893 &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12894 "an untouched renderer must write the value every golden image was blessed with",
12895 );
12896
12897 renderer.set_heatmap(true);
12898 let heatmap = block(&mut renderer);
12899 assert_eq!(
12900 &heatmap[AMBIENT_W..AMBIENT_W + 4],
12901 &mesh::FrameUniforms::HEATMAP_VIEW_ON.to_le_bytes(),
12902 "the switch has to reach the lane the mesh stage branches on",
12903 );
12904 let outside: Vec<usize> = shaded
12905 .iter()
12906 .zip(heatmap.iter())
12907 .enumerate()
12908 .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
12909 .map(|(at, _)| at)
12910 .collect();
12911 assert!(
12912 outside.is_empty(),
12913 "the frame block changed at {outside:?}, which is outside the heatmap's own lane",
12914 );
12915
12916 renderer.set_heatmap(false);
12917 assert_eq!(
12918 block(&mut renderer),
12919 shaded,
12920 "switching the view off has to put the block back, not just stop reporting it",
12921 );
12922
12923 renderer.destroy(device.as_ref());
12924 }
12925
12926 /// **The normals view moves one lane of the frame block and nothing else.**
12927 ///
12928 /// The mechanism, at the level a null device can observe it: which bytes of
12929 /// the buffer `mesh.slang` reads changed. A field on the renderer would say
12930 /// only that a flag moved; the block is what the shader actually branches on.
12931 ///
12932 /// Four claims, and each rules out a different way of passing wrongly:
12933 ///
12934 /// * an untouched renderer writes [`FrameUniforms::NORMALS_VIEW_OFF`] — which
12935 /// is what makes every golden image untouched by this feature;
12936 /// * switching on writes [`FrameUniforms::NORMALS_VIEW_ON`] into the lane the
12937 /// shader reads, at the offset `std140` puts it at rather than at one this
12938 /// test picked;
12939 /// * **those four bytes are the only ones that moved**, so the switch did not
12940 /// come at the cost of the ambient colour beside it or of any matrix;
12941 /// * and switching off puts the block back exactly, so the view is a toggle
12942 /// rather than a one-way door.
12943 ///
12944 /// [`FrameUniforms::NORMALS_VIEW_OFF`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_OFF
12945 /// [`FrameUniforms::NORMALS_VIEW_ON`]: crcbl_shaders::mesh::FrameUniforms::NORMALS_VIEW_ON
12946 #[test]
12947 fn the_normals_view_moves_the_ambients_last_lane_and_no_other_byte() {
12948 // `w` of the second `float4` of the block: one `float4x4`, one `float4`,
12949 // then three floats of ambient colour. Spelled as the sum rather than as
12950 // `92` so that a member arriving before it is a compile-time question
12951 // about `FrameUniforms`' own layout and not a silent read of a matrix.
12952 const AMBIENT_W: usize = 64 + 16 + 12;
12953
12954 // Held for the whole comparison, and it is not this check's own knob:
12955 // `r_shadow_filter` and `r_shadow_split` land in the block's
12956 // `shadow_filter` row on every `begin_frame`, and the filter checks in
12957 // this module move them under this lock while `cargo test` runs the
12958 // module's checks as threads of one process. Two frames read either side
12959 // of such a move differ at that row, which is outside every lane below —
12960 // one run in twelve, measured 2026-09-04.
12961 let _filter = shadow_filter_switch();
12962 let (recorder, device, queue) = open();
12963 let mut renderer =
12964 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
12965 let camera = Camera::default();
12966 let light = DirectionalLight::default();
12967 let block = |renderer: &mut ForwardRenderer| -> Vec<u8> {
12968 renderer
12969 .begin_frame(device.as_ref(), &camera, &light, (64, 48))
12970 .expect("write");
12971 recorder
12972 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
12973 .expect("begin_frame wrote the block")
12974 };
12975
12976 assert!(
12977 !renderer.normals_view(),
12978 "the normals view has to be off in a renderer nobody has asked",
12979 );
12980 let shaded = block(&mut renderer);
12981 assert_eq!(
12982 &shaded[AMBIENT_W..AMBIENT_W + 4],
12983 &mesh::FrameUniforms::NORMALS_VIEW_OFF.to_le_bytes(),
12984 "an untouched renderer must write the value every golden image was blessed with",
12985 );
12986
12987 renderer.set_normals_view(true);
12988 assert!(renderer.normals_view());
12989 let normals = block(&mut renderer);
12990 assert_eq!(
12991 &normals[AMBIENT_W..AMBIENT_W + 4],
12992 &mesh::FrameUniforms::NORMALS_VIEW_ON.to_le_bytes(),
12993 "the switch has to reach the lane the fragment stage branches on",
12994 );
12995 // The bytes that moved, and they all have to be inside the lane — not
12996 // *all* of the lane, because `0.0f` and `1.0f` share their two low bytes
12997 // and an equality against the whole range would be a test about IEEE 754
12998 // rather than about the block.
12999 let outside: Vec<usize> = shaded
13000 .iter()
13001 .zip(normals.iter())
13002 .enumerate()
13003 .filter(|(at, (was, now))| was != now && !(AMBIENT_W..AMBIENT_W + 4).contains(at))
13004 .map(|(at, _)| at)
13005 .collect();
13006 assert!(
13007 outside.is_empty(),
13008 "the frame block changed at {outside:?}, which is outside the normals view's own lane",
13009 );
13010
13011 renderer.set_normals_view(false);
13012 assert!(!renderer.normals_view());
13013 assert_eq!(
13014 block(&mut renderer),
13015 shaded,
13016 "switching the view off has to put the block back, not just stop reporting it",
13017 );
13018
13019 renderer.destroy(device.as_ref());
13020 }
13021
13022 /// **A frame uploads the instances a caller moved, and a frame nobody moved
13023 /// anything in uploads nothing at all.**
13024 ///
13025 /// The second half is the stronger claim and it is the one that needed the
13026 /// cube to become an ordinary instance: `begin_frame` used to take the
13027 /// cube's transform as an argument and write it into the pool every frame,
13028 /// so that slot was dirty in every ring slot forever and a motionless scene
13029 /// paid a spinning one's transfer. The bytes were identical, so no golden
13030 /// image could ever have shown it — the recorder's write log is the only
13031 /// place the difference is visible.
13032 ///
13033 /// The pyramid is here so that "only the one that moved" is a claim about a
13034 /// choice: with one instance in the array, uploading it and uploading
13035 /// everything are the same event.
13036 #[test]
13037 fn only_the_instance_that_moved_is_uploaded() {
13038 let (recorder, device, queue) = open();
13039 let mut renderer =
13040 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13041 let instance_buffers = renderer.instances.buffers().to_vec();
13042 let cube = place_cube(&mut renderer, Mat4::IDENTITY);
13043 place_demo(
13044 &mut renderer,
13045 DEMO_PYRAMID,
13046 DEMO_UNTINTED,
13047 Mat4::from_translation(Vec3::X),
13048 );
13049
13050 // Both instances are dirty in *every* slot when they are inserted, so
13051 // the first frames upload both however well delta upload works. The ring
13052 // has to be walked right through before an upload is evidence about the
13053 // delta rather than about initialisation.
13054 let frame = |renderer: &mut ForwardRenderer| {
13055 renderer
13056 .begin_frame(
13057 device.as_ref(),
13058 &Camera::default(),
13059 &DirectionalLight::default(),
13060 (64, 48),
13061 )
13062 .expect("write");
13063 };
13064 for _ in 0..FRAMES_IN_FLIGHT {
13065 frame(&mut renderer);
13066 }
13067 let instance_writes = |from: usize| -> Vec<(u64, usize)> {
13068 recorder
13069 .events()
13070 .into_iter()
13071 .skip(from)
13072 .filter_map(|event| match event {
13073 crcbl_hal::null::Event::BufferWritten {
13074 buffer,
13075 offset,
13076 len,
13077 } if instance_buffers.contains(&buffer) => Some((offset, len)),
13078 _ => None,
13079 })
13080 .collect()
13081 };
13082
13083 let before = recorder.events().len();
13084 frame(&mut renderer);
13085 assert_eq!(
13086 instance_writes(before),
13087 [],
13088 "a frame in which nothing moved must upload no instance bytes at all"
13089 );
13090
13091 let before = recorder.events().len();
13092 let model = ForwardRenderer::spin(1.25);
13093 renderer.set_instance(
13094 cube,
13095 &InstanceDesc {
13096 mesh: DEMO_CUBE,
13097 material: DEMO_UNTINTED,
13098 transform: model,
13099 },
13100 );
13101 frame(&mut renderer);
13102 assert_eq!(
13103 renderer
13104 .instances
13105 .get(cube)
13106 .expect("the cube is live")
13107 .transform,
13108 model.to_cols_array(),
13109 "the model matrix must land in the instance, not the uniform block"
13110 );
13111 let cube_at = u64::from(renderer.instances.index(cube).expect("the cube is live"))
13112 * crcbl_shaders::mesh::INSTANCE_STRIDE as u64;
13113 assert_eq!(
13114 instance_writes(before),
13115 [(cube_at, crcbl_shaders::mesh::INSTANCE_STRIDE)],
13116 "a steady-state frame must upload exactly the one instance that changed"
13117 );
13118
13119 renderer.destroy(device.as_ref());
13120 recorder.assert_valid();
13121 }
13122
13123 /// **An object takes one pool slot, a rewrite keeps it, and a removal gives
13124 /// it back for the next object to reuse.**
13125 ///
13126 /// The three-call bookkeeping every caller of the instance API depends on,
13127 /// checked on the pool rather than on the recorder. A `set_instance` that
13128 /// inserted instead would take a fresh slot per call — the pool exhausted in
13129 /// a few thousand frames of a caller that writes a transform per frame, which
13130 /// is what every sample does — and every slot it abandoned would stay
13131 /// **live**, so the frame would draw a copy of the object at each transform
13132 /// it had ever been given. Neither is something a golden image would show
13133 /// until the pool ran out.
13134 ///
13135 /// `only_the_instance_that_moved_is_uploaded` is the delta half of this and
13136 /// reads the recorder; this is the bookkeeping half and reads the pool, which
13137 /// is where an abandoned slot would still be counted.
13138 ///
13139 /// Run over every mesh of [`scene::demo`], because the DAG is the one whose
13140 /// slot carries topic 25's hysteresis state — the reuse below is
13141 /// exactly what [`ForwardRenderer::add_instance`] documents as inheriting a
13142 /// previous occupant's expanded groups.
13143 #[test]
13144 fn an_object_takes_one_slot_and_a_removal_gives_it_back() {
13145 for mesh in [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES] {
13146 let (recorder, device, queue) = open();
13147 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
13148 .expect("built");
13149 // The null backend takes an indirect tail, so the DAG is placeable
13150 // here; the arm that cannot select a level refuses before an
13151 // application ever calls this.
13152 assert!(
13153 renderer.selects_levels(),
13154 "an indirect tail chooses a level for every mesh, DAG included"
13155 );
13156 // What the pool holds before anything is placed, which is nothing: a
13157 // renderer places no object of its own any more.
13158 let resident = renderer.instances.len();
13159 assert_eq!(resident, 0, "a fresh renderer holds no objects");
13160
13161 let first = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
13162 let handle = place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13163 assert_eq!(
13164 renderer.instances.len(),
13165 resident + 1,
13166 "mesh {mesh}: add_instance takes one slot"
13167 );
13168
13169 // The rewrite is the whole test: the same handle, the same slot
13170 // count, and the new transform in it.
13171 let second = Mat4::from_translation(Vec3::new(-4.0, 5.0, -6.0));
13172 renderer.set_instance(
13173 handle,
13174 &InstanceDesc {
13175 mesh,
13176 material: DEMO_UNTINTED,
13177 transform: second,
13178 },
13179 );
13180 assert_eq!(
13181 renderer.instances.len(),
13182 resident + 1,
13183 "mesh {mesh}: set_instance must rewrite its instance, not insert a second"
13184 );
13185 assert_eq!(
13186 renderer.instances.slot_count(),
13187 u32::try_from(resident + 1).expect("a handful of instances"),
13188 "mesh {mesh}: set_instance must not have reached past the slot it holds"
13189 );
13190 assert_eq!(
13191 renderer
13192 .instances
13193 .get(handle)
13194 .unwrap_or_else(|| panic!("mesh {mesh}: the instance is live"))
13195 .transform,
13196 second.to_cols_array(),
13197 "mesh {mesh}: set_instance must have written the second transform"
13198 );
13199
13200 // And a removal gives the slot back, so a caller toggling an object
13201 // is not a leak either.
13202 renderer.remove_instance(handle);
13203 assert_eq!(
13204 renderer.instances.len(),
13205 resident,
13206 "mesh {mesh}: remove_instance must free the slot rather than hide the object"
13207 );
13208 place_demo(&mut renderer, mesh, DEMO_UNTINTED, first);
13209 assert_eq!(
13210 renderer.instances.slot_count(),
13211 u32::try_from(resident + 1).expect("a handful of instances"),
13212 "mesh {mesh}: the object after a removal must reuse the freed slot"
13213 );
13214
13215 renderer.destroy(device.as_ref());
13216 recorder.assert_valid();
13217 }
13218 }
13219
13220 /// **The description resolves to the ids the renderer used to hand itself**:
13221 /// one table entry per description mesh, in description order, with the DAG
13222 /// occupying one per level after them — and every level's vertex base
13223 /// measured from level 0's, which is zero.
13224 ///
13225 /// Upload order is what decides a mesh id, and `cull.slang` reads a bounding
13226 /// box out of the entry the *instance* names. So a description walked in
13227 /// another order, or a DAG whose levels landed among the flat meshes, would
13228 /// leave every instance naming a mesh that is not its own: the cube culled
13229 /// against the pyramid's box, the dunes patch drawn as an open box. Every
13230 /// one of those is a frame that still looks like a frame.
13231 ///
13232 /// The bases are asserted against the table bytes rather than against
13233 /// `ResidentMesh`, because the table is what the GPU reads.
13234 #[test]
13235 fn the_description_resolves_to_the_ids_it_was_written_in() {
13236 let (recorder, device, queue) = open();
13237 let renderer =
13238 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13239
13240 assert_eq!(
13241 renderer.mesh_ids,
13242 [0, 1, 2, 3],
13243 "the four description meshes take the first four table entries, in order"
13244 );
13245
13246 // The DAG's coarser levels follow level 0, so a cut that spans them
13247 // reads entries the flat meshes never occupied.
13248 let scene = scene::demo();
13249 let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13250 panic!("the demo description's fourth mesh is the DAG");
13251 };
13252 let level_ids: Vec<u32> = (0..dag.levels.len())
13253 .map(|level| renderer.mesh_ids[DEMO_DUNES] + level as u32)
13254 .collect();
13255 assert!(
13256 level_ids
13257 .iter()
13258 .all(|&id| id > renderer.mesh_ids[DEMO_OPEN_BOX]),
13259 "every dunes level is past the flat residents: {level_ids:?}"
13260 );
13261
13262 // **Level 0 is at the pool's own first vertex**, which is what makes
13263 // every `ClusterSelect::vertex_base` a non-negative offset from it — the
13264 // sum the mesh stage forms with the instance's own base.
13265 let entries: Vec<crcbl_shaders::mesh::GpuMesh> = level_ids
13266 .iter()
13267 .map(|&id| mesh_entry(&recorder, &renderer, id))
13268 .collect();
13269 let level_zero = entries[0].base_vertex;
13270 assert_eq!(
13271 level_zero,
13272 mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_OPEN_BOX]).base_vertex
13273 + crcbl_shaders::mesh::OPEN_BOX_VERTEX_COUNT as u32,
13274 "the DAG starts where the last flat resident ends"
13275 );
13276 let bases: Vec<u32> = entries
13277 .iter()
13278 .map(|entry| {
13279 entry
13280 .base_vertex
13281 .checked_sub(level_zero)
13282 .expect("a level below level 0 would wrap the offset a cluster carries")
13283 })
13284 .collect();
13285 assert_eq!(
13286 bases[0], 0,
13287 "level 0 is the base every other is measured from"
13288 );
13289 assert!(
13290 bases.windows(2).all(|pair| pair[0] < pair[1]),
13291 "each level starts past the one below it: {bases:?}"
13292 );
13293
13294 renderer.destroy(device.as_ref());
13295 recorder.assert_valid();
13296 }
13297
13298 /// **A description that is not [`scene::demo`]: five meshes and two DAGs.**
13299 ///
13300 /// [`ForwardRenderer::with_scene`] is written for any mesh count and any
13301 /// number of DAGs, and until this nothing had put either through it — every
13302 /// golden image and every end-to-end run is `scene::demo()`, whose four
13303 /// meshes hold one DAG between them.
13304 ///
13305 /// What only a second DAG exercises is the **concatenation**: `level_groups`
13306 /// is every DAG's groups laid end to end and a DAG reaches its own run
13307 /// through the `first_group` offset handed to `ClusterDag::selection_records`,
13308 /// which is zero for the first one and therefore invisible while there is
13309 /// only one. A second DAG whose records still named the first's groups would
13310 /// descend a hierarchy belonging to another surface — a cut that is a
13311 /// plausible picture and matches no assertion the CPU makes about the frame.
13312 ///
13313 /// On the mesh path, because that is where the offset is *used*: an indirect
13314 /// tail takes a uniform cut and builds no [`ClusterSelect`] records at all.
13315 ///
13316 /// [`ClusterSelect`]: crcbl_shaders::cluster_select::ClusterSelect
13317 #[test]
13318 fn a_second_dag_reaches_its_own_groups_and_not_the_first_s() {
13319 use crcbl_shaders::cluster_select::{CLUSTER_SELECT_STRIDE, ClusterSelect};
13320
13321 let recorder = Recorder::new();
13322 let (device, queue) = open_mesh_path(&recorder, Features::TASK_SHADER);
13323
13324 // The engine has one DAG, so a second one is a second copy of it. That
13325 // is the whole point: two DAGs whose *groups* are alike is the case
13326 // where reaching the wrong run still produces a cut, and so the case a
13327 // frame comparison could never catch.
13328 let mut scene = scene::demo();
13329 let mut again = scene.meshes[DEMO_DUNES].clone();
13330 again.label = "dunes again".into();
13331 scene.meshes.push(again);
13332 // Room for the second copy. Doubling rather than measuring, because the
13333 // number that matters is that the description carries its own sizes at
13334 // all — see `Capacities`, which is the caller's to choose.
13335 scene.capacities.vertices *= 2;
13336 scene.capacities.indices *= 2;
13337 let second_dag = scene.meshes.len() - 1;
13338
13339 let Geometry::Dag { dag, .. } = &scene.meshes[DEMO_DUNES].geometry else {
13340 panic!("the demo description's fourth mesh is the DAG");
13341 };
13342 let levels = dag.levels.len();
13343 let groups = dag.level_groups().len();
13344 assert!(groups > 0, "a DAG with no groups would select nothing");
13345
13346 let mut renderer =
13347 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13348 .expect("a five-mesh description with two DAGs is one this can make resident");
13349
13350 // Every level of both is its own table entry, laid down in description
13351 // order, so the second DAG's level 0 is a whole hierarchy past the
13352 // first's.
13353 assert_eq!(
13354 renderer.mesh_ids.len(),
13355 scene.meshes.len(),
13356 "one id per description mesh, whatever the count"
13357 );
13358 assert_eq!(
13359 renderer.mesh_ids[second_dag],
13360 renderer.mesh_ids[DEMO_DUNES] + levels as u32,
13361 "the second DAG's level 0 starts past every level of the first"
13362 );
13363
13364 // **The hysteresis state is per instance per resident group**, and
13365 // `group_stride` is what says how many groups that is. One DAG made this
13366 // number a single hierarchy's; two is what tells a stride that sums from
13367 // one that took the first answer it found.
13368 assert_eq!(
13369 renderer.primary.draws.group_stride(),
13370 u32::try_from(groups * 2).expect("a few dozen groups per DAG"),
13371 "every resident DAG's groups are in the stride, not just the first's"
13372 );
13373
13374 // The records themselves: which group each cluster produces and which
13375 // contains it, as the amplification stage reads them.
13376 let clusters = renderer
13377 .clusters
13378 .as_ref()
13379 .expect("the mesh path builds a cluster pool");
13380 let selection = recorder
13381 .buffer_bytes(clusters.selection())
13382 .expect("the selection records are live");
13383 // Entries are laid down in description order, a flat mesh taking one and
13384 // a DAG one per level — so the second DAG's start a hierarchy past the
13385 // first's, which start past the three flat residents.
13386 let first_entry = DEMO_DUNES;
13387 let record = |entry: usize| -> Vec<ClusterSelect> {
13388 let range = clusters.range(entry).expect("one range per entry");
13389 (range.base..range.base + range.count)
13390 .map(|cluster| {
13391 let at = cluster as usize * CLUSTER_SELECT_STRIDE;
13392 ClusterSelect::from_bytes(
13393 selection[at..at + CLUSTER_SELECT_STRIDE]
13394 .try_into()
13395 .expect("one whole record"),
13396 )
13397 })
13398 .collect()
13399 };
13400 // The named group of every record that has one, per DAG — and the count,
13401 // because a comparison over an empty set is a check that cannot fail.
13402 let named = |base: usize| -> Vec<u32> {
13403 (base..base + levels)
13404 .flat_map(record)
13405 .flat_map(|select| {
13406 let producer = (select.flags & ClusterSelect::HAS_PRODUCER != 0)
13407 .then_some(select.producer_group);
13408 let container = (select.flags & ClusterSelect::HAS_CONTAINER != 0)
13409 .then_some(select.container_group);
13410 producer.into_iter().chain(container)
13411 })
13412 .collect()
13413 };
13414 let boundary = u32::try_from(groups).expect("a few dozen groups per DAG");
13415 let first = named(first_entry);
13416 let second = named(first_entry + levels);
13417 assert!(
13418 !first.is_empty() && first.len() == second.len(),
13419 "the two copies must name the same number of groups: {} against {}",
13420 first.len(),
13421 second.len()
13422 );
13423 assert!(
13424 first.iter().all(|&group| group < boundary),
13425 "the first DAG's records stay inside its own run: {first:?}"
13426 );
13427 assert!(
13428 second
13429 .iter()
13430 .all(|&group| (boundary..boundary * 2).contains(&group)),
13431 "the second DAG's records must name the groups past the first's, and \
13432 `first_group` is the only thing that puts them there: {second:?}"
13433 );
13434
13435 // And both are placeable through the runtime API, which is what a
13436 // description of a shape no `set_*` method names is *for*.
13437 let place = |renderer: &mut ForwardRenderer, mesh: usize, x: f32| {
13438 renderer
13439 .add_instance(&InstanceDesc {
13440 mesh,
13441 material: DEMO_UNTINTED,
13442 transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)),
13443 })
13444 .expect("the pool has room")
13445 };
13446 let near = place(&mut renderer, DEMO_DUNES, -64.0);
13447 let far = place(&mut renderer, second_dag, 64.0);
13448 let index = |handle| {
13449 renderer
13450 .instances
13451 .index(handle)
13452 .expect("a just-added instance is live")
13453 };
13454 assert_ne!(
13455 index(near),
13456 index(far),
13457 "two instances take two slots, and the index is the hysteresis key"
13458 );
13459 assert_eq!(
13460 renderer.instances.get(far).expect("live").mesh,
13461 renderer.mesh_ids[second_dag],
13462 "an InstanceDesc's mesh index resolves through the description, not through \
13463 a table id the caller cannot know"
13464 );
13465
13466 renderer.destroy(device.as_ref());
13467 recorder.assert_valid();
13468 }
13469
13470 /// **A description the renderer cannot make resident is refused before the
13471 /// first device object exists**, so a rejection leaks nothing.
13472 ///
13473 /// `build` hands the geometry pool and the material table to the rollback
13474 /// and then creates a dozen objects with `?` between them. A check that ran
13475 /// part way down that list would be a new early exit on the wrong side of a
13476 /// handover, and the pool would go with it — which is exactly the leak
13477 /// `Rollback` exists to prevent and which
13478 /// `the_forward_renderer_builds_and_leaks_nothing` cannot see, because it
13479 /// only walks the happy path.
13480 ///
13481 /// Each arm below is a *different* refusal, so a check that stopped running
13482 /// would show up as one arm leaking rather than as all of them — and each
13483 /// names a fragment of the message it must be refused *with*, or an arm
13484 /// would pass on some other check's answer.
13485 /// **A description with no meshes is refused by name**, before anything
13486 /// is created, rather than reaching the mesh table's sizing with nothing
13487 /// to size it from.
13488 #[test]
13489 fn a_scene_with_no_meshes_is_refused_by_name() {
13490 let (recorder, device, queue) = open();
13491 let before = recorder.total_live_objects();
13492 let mut scene = scene::demo();
13493 scene.meshes.clear();
13494 let error =
13495 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13496 .expect_err("a scene of no meshes must be refused");
13497 assert!(
13498 error.to_string().contains("at least one mesh"),
13499 "the refusal says what is missing: {error}"
13500 );
13501 assert_eq!(
13502 recorder.total_live_objects(),
13503 before,
13504 "the refusal created something"
13505 );
13506 }
13507
13508 #[test]
13509 fn a_refused_description_creates_nothing_at_all() {
13510 /// One way of writing a description the renderer cannot build, and the
13511 /// words that say it was this refusal rather than another.
13512 type Break = (&'static str, fn(&mut SceneDesc<'static>), &'static str);
13513
13514 let cases: [Break; 9] = [
13515 (
13516 "a row naming a layer the page has not got",
13517 |scene| {
13518 scene.materials[DEMO_TEXTURED].base_color_texture = 7;
13519 },
13520 "material row 2 samples base-colour page layer 7",
13521 ),
13522 // And the same on the two kinds rung 3 added, because `check_scene`
13523 // reads a different column of the row for each: a check written per
13524 // kind is only worth what its arms cover, and a column nobody broke
13525 // here could be read out of the wrong material field for ever.
13526 // `demo` names no layer of either, so any index at all is past the
13527 // end.
13528 (
13529 "a row naming a packed-page layer the page has not got",
13530 |scene| {
13531 scene.materials[DEMO_TEXTURED].metallic_roughness_occlusion_texture = 3;
13532 },
13533 "material row 2 samples metallic-roughness-occlusion page layer 3",
13534 ),
13535 (
13536 "a row naming an emissive layer the page has not got",
13537 |scene| {
13538 scene.materials[DEMO_TEXTURED].emissive_texture = 3;
13539 },
13540 "material row 2 samples emissive page layer 3",
13541 ),
13542 // The one page refusal a caller can actually spell: `push_layer`
13543 // takes bytes it cannot measure against the extent.
13544 (
13545 "a page layer of the wrong length",
13546 |scene| {
13547 scene.page = scene::PageDesc::empty();
13548 scene
13549 .page
13550 .set_extent(PageKind::BaseColor, scene::PAGE_EXTENT);
13551 scene.page.push_layer(PageKind::BaseColor, vec![0x00; 4]);
13552 scene.materials[DEMO_TEXTURED].base_color_texture = scene::CHECKER_LAYER;
13553 },
13554 "base-colour page layer 0 carries 4 bytes",
13555 ),
13556 (
13557 "a DAG level with no vertices",
13558 |scene| {
13559 let Geometry::Dag { levels, .. } = &mut scene.meshes[DEMO_DUNES].geometry
13560 else {
13561 panic!("the demo description's fourth mesh is the DAG");
13562 };
13563 levels.pop();
13564 },
13565 "vertex array(s) for a DAG of",
13566 ),
13567 // The four capacities, each of which is a pool a caller sized and
13568 // a description outgrew. Written as a capacity the description is
13569 // too large for rather than as a description too large for the
13570 // default, because that is the shape of the mistake: the numbers on
13571 // `Capacities` are the ones an application picks.
13572 (
13573 "more vertices than the pool holds",
13574 |scene| {
13575 scene.capacities.vertices = 1;
13576 },
13577 "the vertex pool holds 1 and the description needs",
13578 ),
13579 (
13580 "more indices than the pool holds",
13581 |scene| {
13582 scene.capacities.indices = 1;
13583 },
13584 "the index pool holds 1 and the description needs",
13585 ),
13586 (
13587 "more meshes than the table holds",
13588 |scene| {
13589 scene.capacities.meshes = 1;
13590 },
13591 "the mesh table holds 1 and the description needs",
13592 ),
13593 (
13594 "more material rows than the table holds",
13595 |scene| {
13596 scene.capacities.materials = 2;
13597 },
13598 "the material table holds 2 and the description needs 3",
13599 ),
13600 ];
13601
13602 for (what, break_it, says) in cases {
13603 let (recorder, device, queue) = open();
13604 let before = recorder.total_live_objects();
13605 let mut scene = scene::demo();
13606 break_it(&mut scene);
13607 let error =
13608 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13609 .expect_err(&format!("{what} must be refused"));
13610 assert!(
13611 matches!(error, HalError::InvalidDescriptor(_)),
13612 "{what} must be refused as an invalid descriptor, not as {error:?}"
13613 );
13614 assert!(
13615 error.to_string().contains(says),
13616 "{what} must be refused with a message saying so, and this one says {error}"
13617 );
13618 assert_eq!(
13619 recorder.total_live_objects(),
13620 before,
13621 "{what} was refused after something had been created, and the rollback \
13622 is the only thing that could have released it"
13623 );
13624 recorder.assert_valid();
13625 }
13626
13627 // **And the refusal that is not free**, which is the half of the
13628 // handover every arm above walks past: `check_scene` settles what the
13629 // whole description says, and what one mesh's *bytes* say is the pool's,
13630 // which only sees them one upload at a time. Vertex bytes that are not a
13631 // whole number of vertices reach `MeshPool::upload` — so the third of
13632 // the four meshes is refused with the pool created, two device-local
13633 // buffers in it and the first two meshes already staged into them.
13634 // `build_geometry` is what releases that, and it can only do so because
13635 // the pool is not the rollback's until it has returned.
13636 let (recorder, device, queue) = open();
13637 let before = recorder.total_live_objects();
13638 // So the count below is this build's and not `open`'s.
13639 recorder.clear();
13640 let mut scene = scene::demo();
13641 let Geometry::Flat { vertices, .. } = &mut scene.meshes[DEMO_OPEN_BOX].geometry else {
13642 panic!("the demo description's third mesh is flat");
13643 };
13644 vertices.to_mut().push(0);
13645 let error =
13646 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13647 .expect_err("a mesh of part of a vertex must be refused");
13648 assert!(
13649 error.to_string().contains("is not a whole number of"),
13650 "the pool's own refusal reaches the caller with its numbers, and this \
13651 one says {error}"
13652 );
13653 assert!(
13654 recorder
13655 .events()
13656 .iter()
13657 .any(|event| matches!(event, crcbl_hal::null::Event::Created { .. })),
13658 "this arm is evidence about the rollback only if the refusal came after \
13659 something had been created"
13660 );
13661 assert_eq!(
13662 recorder.total_live_objects(),
13663 before,
13664 "a mesh refused part way through the list left the geometry pool behind, \
13665 which is exactly what `build_geometry` being self-cleaning is for"
13666 );
13667 recorder.assert_valid();
13668 }
13669
13670 /// **The one capacity a description cannot be checked against, and the one
13671 /// an application is expected to handle while it runs.**
13672 ///
13673 /// Every other number on [`scene::Capacities`] sizes something the
13674 /// description fills once, so `check_scene` refuses an over-large one before
13675 /// a device object exists. Objects are placed at any point in a renderer's
13676 /// life, so the only honest answer for that one is the error
13677 /// [`ForwardRenderer::add_instance`] returns — and it returns
13678 /// [`InstancePoolError`] rather than a [`HalError`], so the capacity and
13679 /// what is in it survive to the caller that chose them.
13680 ///
13681 /// It also gives [`Capacities::instances`](scene::Capacities::instances) a
13682 /// value of its own rather than the default, which is what makes the pool
13683 /// fillable at all: a renderer that ignored the number the description
13684 /// carries and reserved the default would draw every frame in the tree
13685 /// identically and refuse nothing here.
13686 #[test]
13687 fn a_full_instance_pool_reaches_the_application_that_sized_it() {
13688 let (recorder, device, queue) = open();
13689 let mut scene = scene::demo();
13690 scene.capacities.instances = 2;
13691 let mut renderer =
13692 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13693 .expect("a scene with room for two objects builds");
13694 let place = |renderer: &mut ForwardRenderer| {
13695 renderer.add_instance(&InstanceDesc {
13696 mesh: DEMO_CUBE,
13697 material: DEMO_UNTINTED,
13698 transform: Mat4::IDENTITY,
13699 })
13700 };
13701 place(&mut renderer).expect("the first of two");
13702 place(&mut renderer).expect("the second of two");
13703 let error = place(&mut renderer).expect_err("a third object has no slot to go in");
13704 assert!(
13705 matches!(
13706 error,
13707 InstancePoolError::PoolFull {
13708 capacity: 2,
13709 in_use: 2
13710 }
13711 ),
13712 "a full pool must reach the caller as a full pool, with the capacity it \
13713 chose; this arrived as {error}"
13714 );
13715 renderer.destroy(device.as_ref());
13716 recorder.assert_valid();
13717 }
13718
13719 /// **One mesh and one material row is a scene, and it draws.**
13720 ///
13721 /// The floor is gone. `with_scene` used to refuse anything shorter than
13722 /// [`scene::demo`] — four meshes and three rows — because the five `set_*`
13723 /// demo wrappers named those entries by position, and the renderer's own
13724 /// `dunes_clusters` and `dunes_level_buckets` indexed the description at
13725 /// `DEMO_DUNES` besides. So an application's own description was not merely
13726 /// refused: with the check removed it would have panicked out of `build`.
13727 ///
13728 /// A frame is recorded rather than only a build, because that is where the
13729 /// positional indexing was: the bucket table, the cluster ranges and the
13730 /// draw-argument blocks are all one-per-description-mesh, and a renderer that
13731 /// still assumed four would come apart here rather than at `with_scene`.
13732 #[test]
13733 fn a_description_smaller_than_the_demo_is_a_scene() {
13734 use std::borrow::Cow;
13735
13736 let scene = SceneDesc {
13737 meshes: vec![scene::MeshDesc {
13738 label: Cow::Borrowed("the only mesh"),
13739 geometry: Geometry::Flat {
13740 vertices: Cow::Owned(crcbl_shaders::mesh::cube_vertex_bytes()),
13741 uv_range: crcbl_shaders::mesh::demo_uv_range(),
13742 indices: Cow::Owned(crcbl_shaders::mesh::cube_indices()),
13743 clusters: crcbl_shaders::meshlet::cube_clusters(),
13744 flags: 0,
13745 },
13746 }],
13747 materials: vec![mesh::GpuMaterial::UNTINTED],
13748 page: scene::PageDesc::empty(),
13749 probes: scene::ProbeGrid::default(),
13750 capacities: scene::Capacities::default(),
13751 };
13752 assert!(
13753 scene.meshes.len() < scene::demo().meshes.len()
13754 && scene.materials.len() < scene::demo().materials.len(),
13755 "this description must be smaller than the demo's in both, or it says nothing \
13756 about the floor"
13757 );
13758
13759 let (recorder, device, queue) = open();
13760 let mut renderer =
13761 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13762 .expect("one mesh and one row is a description the renderer can hold");
13763 assert_eq!(
13764 renderer.mesh_ids,
13765 [0],
13766 "the one description mesh takes the one table entry"
13767 );
13768 assert_eq!(
13769 renderer.bucket_constants.len(),
13770 1,
13771 "one bucket per description mesh, and there is one"
13772 );
13773 renderer
13774 .add_instance(&InstanceDesc {
13775 mesh: 0,
13776 material: 0,
13777 transform: Mat4::IDENTITY,
13778 })
13779 .expect("an empty pool has room for the only object");
13780 let recorded = frame(device.as_ref(), &mut renderer, queue);
13781 assert_eq!(
13782 commands_in_pass(&recorder, "forward")
13783 .into_iter()
13784 .filter(|command| matches!(
13785 command,
13786 crcbl_hal::null::Command::DrawIndexedIndirectCount(_)
13787 ))
13788 .count(),
13789 1,
13790 "a one-mesh scene records the one bucket's indirect call"
13791 );
13792 recorded.finish(device.as_ref(), renderer);
13793 }
13794
13795 /// **A description that exactly fills what it reserved is built, not
13796 /// refused.**
13797 ///
13798 /// The other side of the capacity check, and the side nothing else in the
13799 /// tree can fail on: every other scene reserves far more than it holds, so a
13800 /// comparison written `>=` instead of `>` would pass the whole suite and
13801 /// refuse only the application that had sized its pools exactly right.
13802 ///
13803 /// The two capacities asserted here are the two a caller can size without
13804 /// re-deriving anything the renderer knows: one mesh table entry per
13805 /// [`Geometry::levels`], which is what that method is documented to answer,
13806 /// and one row per material. The four rows share one comparison, so they
13807 /// stand or fall together.
13808 #[test]
13809 fn a_description_that_exactly_fits_its_capacities_is_built() {
13810 let (recorder, device, queue) = open();
13811 let mut scene = scene::demo();
13812 scene.capacities.meshes = scene
13813 .meshes
13814 .iter()
13815 .map(|desc| u32::try_from(desc.geometry.levels()).expect("a few levels"))
13816 .sum();
13817 scene.capacities.materials =
13818 u32::try_from(scene.materials.len()).expect("a few material rows");
13819 let renderer =
13820 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13821 .expect("a description that fits exactly is not too large for itself");
13822 renderer.destroy(device.as_ref());
13823 recorder.assert_valid();
13824 }
13825
13826 /// **The level tables cover every mesh-table slot an instance can name**,
13827 /// not only the slots the description filled.
13828 ///
13829 /// `draw_gen.slang`'s `mesh_levels_of` reads `gen.mesh_levels_at + mesh *
13830 /// MESH_LEVELS_WORDS` with no bound, and says in its own doc comment that
13831 /// "every entry an instance can name is filled". An instance's mesh id is a
13832 /// bare table index, so a table sized to the description alone makes that
13833 /// read land in whatever the packer put next for any slot the description
13834 /// left empty.
13835 ///
13836 /// Growing the capacity by a known number of slots grows the tables buffer
13837 /// by exactly what those slots occupy: one `MeshLevels` record and one
13838 /// `level_meshes` word each. The arithmetic is the assertion, so nothing
13839 /// here is a number to keep in step by hand.
13840 #[test]
13841 fn the_level_tables_cover_every_slot_the_mesh_table_has() {
13842 const EXTRA: u32 = 4;
13843
13844 let sized = |extra: u32| {
13845 let (recorder, device, queue) = open();
13846 let mut scene = scene::demo();
13847 scene.capacities.meshes += extra;
13848 let renderer =
13849 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
13850 .expect("a description with room to spare");
13851 let size = recorder
13852 .buffer_bytes(renderer.primary.draws.tables())
13853 .expect("the table buffer is live")
13854 .len();
13855 renderer.destroy(device.as_ref());
13856 recorder.assert_valid();
13857 size
13858 };
13859
13860 let grown = sized(EXTRA) - sized(0);
13861 let want = EXTRA as usize * (crcbl_shaders::level_select::MESH_LEVELS_STRIDE + 4);
13862 assert_eq!(
13863 grown, want,
13864 "{EXTRA} more table slots must add {EXTRA} more selection records and {EXTRA} more \
13865 level words, and added {grown} bytes"
13866 );
13867 }
13868
13869 /// The property the whole arrangement exists for: the pool's second
13870 /// resident is **not** at base vertex zero, so a frame containing it is a
13871 /// frame that fails if the base is lost between the pool and the shader.
13872 ///
13873 /// Read out of the **mesh table** rather than out of a renderer field,
13874 /// because the table is where a generated draw's index range comes from:
13875 /// `draw_gen.slang` builds every argument structure out of these bytes and
13876 /// nothing on the CPU is consulted.
13877 ///
13878 /// Without this the pass is back where it started — one mesh, base 0, and a
13879 /// base-vertex bug that no picture can show.
13880 #[test]
13881 fn the_second_mesh_lands_past_the_first() {
13882 let (recorder, device, queue) = open();
13883 let renderer =
13884 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13885 let cube = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_CUBE]);
13886 let pyramid = mesh_entry(&recorder, &renderer, renderer.mesh_ids[DEMO_PYRAMID]);
13887
13888 assert_eq!(cube.base_vertex, 0, "the cube is first");
13889 assert_eq!(
13890 pyramid.base_vertex as usize,
13891 crcbl_shaders::mesh::CUBE_VERTEX_COUNT,
13892 "the pyramid must start where the cube ends, or the pools are not \
13893 suballocating at all"
13894 );
13895 assert_eq!(
13896 pyramid.index_count as usize,
13897 crcbl_shaders::mesh::PYRAMID_INDEX_COUNT,
13898 "and the entry carries the whole range, which is what the draw-argument \
13899 pass builds its arguments out of"
13900 );
13901 // And the two buckets read different constant blocks, or both would walk
13902 // the same run of instances.
13903 assert_ne!(
13904 renderer.bucket_constants[DEMO_CUBE], renderer.bucket_constants[DEMO_PYRAMID],
13905 "each bucket needs a block of its own"
13906 );
13907 renderer.destroy(device.as_ref());
13908 }
13909
13910 /// **Each bucket's block points at that bucket's own run**, and the runs do
13911 /// not overlap.
13912 ///
13913 /// This is what replaced "the block names an instance": a draw covers
13914 /// however many instances survived culling, so what it can say for itself is
13915 /// only where to find its slice of the survivors. Two buckets naming one
13916 /// start word would draw each other's objects — with the *right* geometry,
13917 /// because the index range comes from the arguments, which is exactly the
13918 /// kind of plausible wrong picture a golden image struggles with.
13919 ///
13920 /// Read out of the bytes that reached the device rather than out of the
13921 /// renderer's own fields, because the failure is a block written wrong and
13922 /// the field would still be right.
13923 #[test]
13924 fn each_bucket_walks_its_own_run_of_survivors() {
13925 let (recorder, device, queue) = open();
13926 let renderer =
13927 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
13928 let blocks = recorder
13929 .buffer_bytes(renderer.draw_constants)
13930 .expect("the blocks are live");
13931 let start_word_at = |offset: u32| {
13932 let at = offset as usize;
13933 u32::from_le_bytes(blocks[at..at + 4].try_into().expect("four bytes"))
13934 };
13935
13936 let draws = &renderer.primary.draws;
13937 let cube = start_word_at(renderer.bucket_constants[DEMO_CUBE]);
13938 let pyramid = start_word_at(renderer.bucket_constants[DEMO_PYRAMID]);
13939 // **Behind the survivors, their routes and the runs**, which share the
13940 // buffer: a block naming a word inside the runs would have the draw read
13941 // an instance index as its start, and one inside the survivor list or
13942 // the routes a start that is the same instances in a different order, or
13943 // a bucket number — both of which draw a plausible picture.
13944 assert_eq!(
13945 cube,
13946 draws.runs_at() + draws.visible_capacity(),
13947 "the first bucket's start word is the first word past one capacity of runs"
13948 );
13949 assert_eq!(
13950 pyramid,
13951 cube + (DEMO_PYRAMID - DEMO_CUBE) as u32,
13952 "and the second's is a word later — a start per bucket, not a run per bucket"
13953 );
13954 assert_eq!(
13955 cube,
13956 draws.bucket_start_word(DEMO_CUBE as u32),
13957 "the block carries what `DrawGen::bucket_start_word` says, because a reader \
13958 copying a run back uses that accessor and the shader uses this block"
13959 );
13960 renderer.destroy(device.as_ref());
13961 }
13962
13963 /// **An instance's record carries its material's mode**, in the bits
13964 /// `draw_gen.slang` routes by.
13965 ///
13966 /// The host half of the per-bucket split, and the half no picture and no
13967 /// pipeline bind can show: the bucket table can be perfectly twinned and
13968 /// every partition bound to the right pipeline while every instance still
13969 /// answers mode zero, in which case the masked twins are empty, the cutout
13970 /// partition draws nothing, and a cutout casts a solid shadow. The record is
13971 /// where that is decided.
13972 ///
13973 /// Both directions, so the check is shown to discriminate: the opaque
13974 /// instance's mode bits have to be **clear**, or a writer that set them
13975 /// unconditionally would satisfy a one-sided assertion. And the two records
13976 /// are asserted to differ in `flags` and nothing else, so this is about the
13977 /// mode rather than about two unrelated instances.
13978 #[test]
13979 fn an_instances_record_carries_its_materials_mode() {
13980 let masked_scene = {
13981 let mut scene = crate::scene::demo();
13982 scene.materials[DEMO_TINTED].flags = crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
13983 scene
13984 };
13985 let (recorder, device, queue) = open();
13986 let device = device.as_ref();
13987 let mut renderer =
13988 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &masked_scene)
13989 .expect("the null backend accepts the demo description");
13990 let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
13991 let opaque = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
13992 let masked = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
13993
13994 let record = |handle: InstanceHandle| {
13995 renderer
13996 .instances
13997 .get(handle)
13998 .expect("the instance was inserted and is live")
13999 };
14000 let opaque = record(opaque);
14001 let masked = record(masked);
14002 assert_eq!(
14003 opaque.material_mode(),
14004 0,
14005 "an opaque material's instance carries no mode bits, or every instance in the tree \
14006 routes to a cutout bucket"
14007 );
14008 assert_eq!(
14009 masked.material_mode(),
14010 crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK,
14011 "and a masked material's instance carries its mode, or it scatters into the opaque \
14012 twin and the depth passes write its full silhouette"
14013 );
14014 assert_eq!(
14015 mesh::GpuInstance {
14016 flags: opaque.flags,
14017 material: opaque.material,
14018 ..masked
14019 },
14020 opaque,
14021 "the two records differ in the mode bits and the material id and in nothing else"
14022 );
14023
14024 renderer.destroy(device);
14025 recorder.assert_valid();
14026 }
14027
14028 /// **A scene whose materials are all opaque gets exactly the bucket table
14029 /// it had before material modes existed** — one bucket per (mesh, level),
14030 /// and no twin.
14031 ///
14032 /// The zero-cost half of the per-bucket split, and the one a null device can
14033 /// state exactly. A bucket is not free: every pass records one indirect call
14034 /// per bucket per view, and every generator holds a run start per bucket. So
14035 /// a table that twinned unconditionally would double the recorded draws of
14036 /// every demo and every golden in this tree, none of which mask anything.
14037 ///
14038 /// The oracle is [`level_buckets`](ForwardRenderer::level_buckets), which is
14039 /// built from a mesh's own level count rather than from the table's length —
14040 /// so a build that emitted a twin per mesh has more buckets than levels and
14041 /// this says so. And the twinned scenes below are asserted to be exactly as
14042 /// many times as long as they hold modes, or the comparison would pass on a
14043 /// renderer that had stopped twinning at all.
14044 ///
14045 /// # A twin per mode the scene **holds**, not per mode that exists
14046 ///
14047 /// [`DEPTH_MODES`] has four entries and a bucket is not free — every pass
14048 /// records one indirect call per bucket — so the rule that matters is which
14049 /// values the description's own materials carry. Two rows of two modes are
14050 /// two twins whichever two they are, and the pair below says so both ways:
14051 /// three modes across three rows is three, and three rows collapsed onto two
14052 /// *values* is two even though between them they set both mode bits.
14053 #[test]
14054 fn an_all_opaque_scene_keeps_one_bucket_per_mesh_level() {
14055 use crcbl_shaders::mesh::GpuMaterial;
14056
14057 let (recorder, device, queue) = open();
14058 let device = device.as_ref();
14059 let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
14060 // The uniform-cut path, where a DAG is one bucket per level. The mesh
14061 // path folds a DAG into one bucket and reports no level buckets at all,
14062 // which would leave the oracle below empty.
14063 assert!(
14064 !renderer.emit.is_mesh(),
14065 "this preset built a mesh-shader path, whose level buckets are empty"
14066 );
14067 let levels: usize = (0..crate::scene::demo().meshes.len())
14068 .map(|mesh| renderer.level_buckets(mesh).len())
14069 .sum();
14070 assert!(levels > 0, "the demo has meshes, so it has levels");
14071 assert_eq!(
14072 renderer.bucket_constants.len(),
14073 levels,
14074 "an all-opaque scene's bucket table is one bucket per (mesh, level) and no mode \
14075 twin: {levels} level(s) against {} bucket(s)",
14076 renderer.bucket_constants.len()
14077 );
14078 assert_eq!(
14079 renderer.bucket_modes,
14080 vec![0; levels],
14081 "and every one of them draws the OPAQUE mode"
14082 );
14083 let opaque_meshes = renderer.draw_tables.bucket_meshes.clone();
14084 let opaque_level_buckets: Vec<Vec<u32>> = (0..crate::scene::demo().meshes.len())
14085 .map(|mesh| renderer.level_buckets(mesh).to_vec())
14086 .collect();
14087 renderer.destroy(device);
14088 recorder.assert_valid();
14089
14090 // Every arrangement worth stating, as the modes its material rows carry
14091 // and the number of twins that has to produce. The demo has three rows;
14092 // a fourth is appended where four distinct modes are wanted, which
14093 // nothing instances and which therefore changes nothing but the mode
14094 // set.
14095 for (rows, modes, what) in [
14096 (
14097 vec![GpuMaterial::ALPHA_MODE_MASK, 0, 0],
14098 2,
14099 "one masked row beside two opaque ones",
14100 ),
14101 (
14102 vec![GpuMaterial::DOUBLE_SIDED, 0, 0],
14103 2,
14104 "one double-sided row beside two opaque ones",
14105 ),
14106 (
14107 vec![GpuMaterial::ALPHA_MODE_MASK, GpuMaterial::DOUBLE_SIDED, 0],
14108 3,
14109 "a masked row, a double-sided one and an opaque one",
14110 ),
14111 (
14112 vec![
14113 GpuMaterial::ALPHA_MODE_MASK,
14114 GpuMaterial::DOUBLE_SIDED,
14115 GpuMaterial::ALPHA_MODE_MASK,
14116 ],
14117 2,
14118 "three rows carrying two mode values between them — both mode bits are set \
14119 somewhere and neither row is opaque, so a rule counting bits rather than \
14120 values would say three",
14121 ),
14122 (
14123 vec![
14124 0,
14125 GpuMaterial::ALPHA_MODE_MASK,
14126 GpuMaterial::DOUBLE_SIDED,
14127 GpuMaterial::MODE_MASK,
14128 ],
14129 4,
14130 "one row of each mode, which is the only arrangement that pays for four",
14131 ),
14132 ] {
14133 let scene = {
14134 let mut scene = crate::scene::demo();
14135 while scene.materials.len() < rows.len() {
14136 scene.materials.push(GpuMaterial::UNTINTED);
14137 }
14138 for (row, flags) in scene.materials.iter_mut().zip(&rows) {
14139 row.flags = *flags;
14140 }
14141 scene
14142 };
14143 let (recorder, device, queue) = open();
14144 let device = device.as_ref();
14145 let twinned =
14146 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
14147 .expect("the null backend accepts the demo description");
14148 assert_eq!(
14149 twinned.bucket_constants.len(),
14150 modes * levels,
14151 "{what}: {modes} mode(s) over {levels} level(s) is {} bucket(s), and the table \
14152 has {}",
14153 modes * levels,
14154 twinned.bucket_constants.len()
14155 );
14156 // The modes present, as a set — which is the claim, since the order
14157 // is `DEPTH_MODES`' and the count above already pins the length.
14158 let held: std::collections::BTreeSet<u32> =
14159 twinned.bucket_modes.iter().copied().collect();
14160 let want: std::collections::BTreeSet<u32> = rows.iter().copied().collect();
14161 assert_eq!(
14162 held, want,
14163 "{what}: the table twins the modes its materials carry and no others"
14164 );
14165 for mode in &held {
14166 assert_eq!(
14167 twinned
14168 .bucket_modes
14169 .iter()
14170 .filter(|held| *held == mode)
14171 .count(),
14172 levels,
14173 "{what}: every mode present gets every mesh's levels once"
14174 );
14175 }
14176 // **Mode-major**: each held mode is one contiguous run of the
14177 // all-opaque table, in `DEPTH_MODES` order, so a pipeline's
14178 // partition is one range of buckets.
14179 let held_in_order: Vec<u32> = DEPTH_MODES
14180 .into_iter()
14181 .filter(|mode| held.contains(mode))
14182 .collect();
14183 assert_eq!(
14184 twinned.bucket_modes,
14185 held_in_order
14186 .iter()
14187 .flat_map(|mode| std::iter::repeat_n(*mode, levels))
14188 .collect::<Vec<_>>(),
14189 "{what}: every bucket of one mode is contiguous, modes in DEPTH_MODES order"
14190 );
14191 assert_eq!(
14192 twinned.draw_tables.bucket_meshes,
14193 opaque_meshes.repeat(held_in_order.len()),
14194 "{what}: each mode's run is the all-opaque table, mesh by mesh"
14195 );
14196 for (mesh, opaque) in opaque_level_buckets.iter().enumerate() {
14197 assert_eq!(
14198 twinned.level_buckets(mesh),
14199 opaque.as_slice(),
14200 "{what}: mesh {mesh}'s level buckets are the first mode's run"
14201 );
14202 }
14203 // And the `(mesh, mode) → bucket` lookup the scatter routes through
14204 // sends every key to its mode's run, at the mesh's own offset.
14205 let lookup = crcbl_shaders::draw_gen::bucket_lookup(
14206 &twinned.draw_tables.bucket_meshes,
14207 &twinned.bucket_modes,
14208 )
14209 .expect("a small lookup");
14210 for (slot, mode) in held_in_order.iter().enumerate() {
14211 for (offset, mesh) in opaque_meshes.iter().enumerate() {
14212 let key = 1 + (*mesh * crcbl_shaders::draw_gen::MATERIAL_MODES + *mode);
14213 assert_eq!(
14214 lookup[key as usize] as usize,
14215 slot * levels + offset,
14216 "{what}: mesh {mesh} in mode {mode}"
14217 );
14218 }
14219 }
14220 twinned.destroy(device);
14221 recorder.assert_valid();
14222 }
14223 }
14224
14225 /// **The two pyramids differ in exactly one field, and it is the material
14226 /// id — which names a row holding a different colour and a different
14227 /// roughness.**
14228 ///
14229 /// The whole of what §3.2's table buys, stated as the two things that have
14230 /// to be true at once. Placed at the *same* transform, so "differ only in
14231 /// material" is literal rather than nearly: same mesh id, same matrix, same
14232 /// flags, and a `GpuInstance` comparison that would fail on any other
14233 /// field. And the ids they carry name rows the device actually holds —
14234 /// asserted on the bytes in the buffer, because a table the renderer agrees
14235 /// with itself about is not a table a shader can read.
14236 ///
14237 /// The two rows are asserted to differ, or the pair would be evidence of
14238 /// nothing: two instances naming two rows of the same colour draw the same
14239 /// picture whether or not either id was ever used.
14240 #[test]
14241 fn the_two_pyramids_differ_only_in_their_material() {
14242 let (recorder, device, queue) = open();
14243 let mut renderer =
14244 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14245 let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14246 let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14247 let tinted_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TINTED, at);
14248
14249 let instance = |handle: InstanceHandle| {
14250 renderer
14251 .instances
14252 .get(handle)
14253 .expect("the instance was inserted and is live")
14254 };
14255 let plain = instance(plain_handle);
14256 let tinted = instance(tinted_handle);
14257 assert_ne!(
14258 plain.material, tinted.material,
14259 "the two pyramids must not share a material row"
14260 );
14261 assert_eq!(
14262 mesh::GpuInstance {
14263 material: tinted.material,
14264 ..plain
14265 },
14266 tinted,
14267 "the two instances must differ in the material id and in nothing else"
14268 );
14269
14270 let bytes = recorder
14271 .buffer_bytes(renderer.materials.buffer())
14272 .expect("the table is live");
14273 let row = |index: u32| {
14274 let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14275 mesh::GpuMaterial::from_bytes(
14276 bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14277 .try_into()
14278 .expect("one row"),
14279 )
14280 };
14281 assert_eq!(
14282 row(plain.material),
14283 mesh::GpuMaterial::UNTINTED,
14284 "the plain pyramid's row must be the factor that changes nothing"
14285 );
14286 assert_eq!(
14287 row(tinted.material),
14288 mesh::GpuMaterial {
14289 base_color: scene::PYRAMID_TINT,
14290 roughness: scene::PYRAMID_ROUGHNESS,
14291 ..mesh::GpuMaterial::UNTINTED
14292 },
14293 "the tinted pyramid's row must be the tint and the tighter lobe"
14294 );
14295 // The shading half of that row, on its own: a roughness equal to the
14296 // neutral row's would leave `crcbl`'s render e2e comparing one lobe
14297 // against itself, and that test would go green on a shader that had
14298 // never read the column.
14299 assert_ne!(
14300 row(plain.material).roughness,
14301 row(tinted.material).roughness,
14302 "the two rows must differ in roughness, or the highlight the render e2e measures \
14303 is not attributable to the material"
14304 );
14305 assert_ne!(
14306 row(plain.material),
14307 row(tinted.material),
14308 "two rows holding the same colour would make the pair prove nothing"
14309 );
14310 // And the tint is the *only* thing that differs between them: a row that
14311 // also changed its page layer would make this pair evidence about two
14312 // columns at once, which is what the third pyramid exists to avoid.
14313 assert_eq!(
14314 row(plain.material).base_color_texture,
14315 row(tinted.material).base_color_texture,
14316 "the factor pair must sample the same page layer"
14317 );
14318
14319 // And the second pyramid leaves the frame the way the first does: the
14320 // instance is removed, not a draw skipped.
14321 renderer.remove_instance(tinted_handle);
14322 assert!(
14323 renderer.instances.get(tinted_handle).is_none(),
14324 "the instance must be given back, or an object nobody asked for stays in the scene"
14325 );
14326
14327 renderer.destroy(device.as_ref());
14328 }
14329
14330 /// **The same claim one column along: the plain and textured pyramids
14331 /// differ in exactly one field, and the rows it names differ in exactly one
14332 /// column — the base-colour page layer.**
14333 ///
14334 /// [`the_two_pyramids_differ_only_in_their_material`]'s argument for §3.2's
14335 /// *texture indices* rather than its *factors*. The factors of the two rows
14336 /// are asserted **equal** here, which is the half that makes the pair
14337 /// evidence about the texture at all: a textured row that also carried a
14338 /// tint would draw a different picture for a reason the frame could not
14339 /// distinguish from the tinted pyramid's.
14340 ///
14341 /// The layer numbers are asserted against the page the renderer actually
14342 /// uploaded, so a row naming a layer that does not exist is caught here
14343 /// rather than as an out-of-range sample on a device.
14344 #[test]
14345 fn the_textured_pyramid_differs_only_in_its_page_layer() {
14346 let (recorder, device, queue) = open();
14347 let mut renderer =
14348 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
14349 let at = Mat4::from_translation(Vec3::new(-1.0, 0.0, 0.0));
14350 let plain_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14351 let textured_handle = place_demo(&mut renderer, DEMO_PYRAMID, DEMO_TEXTURED, at);
14352
14353 let instance = |handle: InstanceHandle| {
14354 renderer
14355 .instances
14356 .get(handle)
14357 .expect("the instance was inserted and is live")
14358 };
14359 let plain = instance(plain_handle);
14360 let textured = instance(textured_handle);
14361 assert_ne!(
14362 plain.material, textured.material,
14363 "the two pyramids must not share a material row"
14364 );
14365 assert_eq!(
14366 mesh::GpuInstance {
14367 material: textured.material,
14368 ..plain
14369 },
14370 textured,
14371 "the two instances must differ in the material id and in nothing else"
14372 );
14373
14374 let bytes = recorder
14375 .buffer_bytes(renderer.materials.buffer())
14376 .expect("the table is live");
14377 let row = |index: u32| {
14378 let at = index as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14379 mesh::GpuMaterial::from_bytes(
14380 bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14381 .try_into()
14382 .expect("one row"),
14383 )
14384 };
14385 assert_eq!(
14386 row(plain.material).base_color,
14387 row(textured.material).base_color,
14388 "the texture pair must share a factor, or the pair is evidence about both columns"
14389 );
14390 assert_eq!(
14391 row(plain.material).base_color_texture,
14392 mesh::GpuMaterial::NO_PAGE
14393 );
14394 assert_eq!(
14395 row(textured.material).base_color_texture,
14396 scene::CHECKER_LAYER
14397 );
14398 assert_ne!(
14399 row(plain.material),
14400 row(textured.material),
14401 "two rows naming the same layer would make the pair prove nothing"
14402 );
14403 // The layer that number names is a layer the page has, and it is not
14404 // one flat colour — a checker of one repeated texel would pass every
14405 // assertion above and draw the picture the untextured row draws.
14406 let page = scene::demo().page;
14407 let layers = page.layers(PageKind::BaseColor);
14408 assert!(
14409 (scene::CHECKER_LAYER as usize) < layers.len(),
14410 "layer {} is past the end of a {}-layer page, which is an out-of-range sample \
14411 nothing below the seam would report",
14412 scene::CHECKER_LAYER,
14413 layers.len()
14414 );
14415 let checker = &layers[scene::CHECKER_LAYER as usize];
14416 assert!(
14417 checker
14418 .as_chunks::<4>()
14419 .0
14420 .iter()
14421 .any(|texel| texel != &checker[..4]),
14422 "a flat checker layer would shade the textured row exactly as the untextured \
14423 one shades, and the pair would prove nothing"
14424 );
14425
14426 renderer.remove_instance(textured_handle);
14427 assert!(
14428 renderer.instances.get(textured_handle).is_none(),
14429 "the instance must be given back, or an object nobody asked for stays in the scene"
14430 );
14431
14432 renderer.destroy(device.as_ref());
14433 }
14434
14435 /// **A [`PageKind`] nothing names costs one texel**, not `extent² × 4` bytes
14436 /// and a third again for its chain.
14437 ///
14438 /// This is what row (d) bought, and it is the half of it no picture can
14439 /// show: the frame a scene with no normal map draws is byte-identical either
14440 /// way, because `mesh.slang` returns before it fetches. What changes is the
14441 /// image the renderer created, and the copies into it are where that is
14442 /// visible. `crcbl/tests/mesh_e2e/normal_map.rs`'s
14443 /// `no_normal_map_returns_the_surface_normal_exactly_and_the_neutral_texel_does_not`
14444 /// is the device-side half saying the frame did not move.
14445 ///
14446 /// [`scene::demo`] is the scene: every one of its rows carries
14447 /// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) in the normal column, and it is
14448 /// the description every golden in this tree is a variation of.
14449 ///
14450 /// # Sabotage
14451 ///
14452 /// The empty-kind arm of the upload loop uploading a full 64² neutral layer
14453 /// and its chain instead of the placeholder — the shape this replaced. Red
14454 /// on 2026-09-06 with `"a description with no normal map must upload the
14455 /// one-texel placeholder, and this copied 7 level(s) at [Extent3d { width:
14456 /// 64, height: 64, depth_or_layers: 1 }, … ] — a burned neutral layer costs
14457 /// extent² × 4 bytes and a third again for its chain, on every scene in the
14458 /// tree"`.
14459 #[test]
14460 fn a_page_kind_nothing_names_costs_one_texel() {
14461 use crcbl_hal::null::Command;
14462
14463 let scene = scene::demo();
14464 assert!(
14465 scene
14466 .materials
14467 .iter()
14468 .all(|row| row.normal_texture == mesh::GpuMaterial::NO_PAGE),
14469 "a row naming a normal layer would make the description one that *does* name \
14470 the page, and this test would be about the other case"
14471 );
14472 assert!(
14473 scene.page.layers(PageKind::Normal).is_empty()
14474 && scene.page.extent(PageKind::BaseColor) > 1,
14475 "the description must name no normal layer while naming base-colour ones, or \
14476 a placeholder-sized copy says nothing about which page it landed in"
14477 );
14478
14479 let (recorder, device, queue) = open();
14480 let renderer =
14481 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14482 .expect("a description naming no normal page is one this can make resident");
14483
14484 let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14485 .commands()
14486 .into_iter()
14487 .filter_map(|command| match command {
14488 Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14489 Some(copy)
14490 }
14491 _ => None,
14492 })
14493 .collect();
14494 let extents: Vec<crcbl_hal::Extent3d> =
14495 copies.iter().map(|copy| copy.image_extent).collect();
14496 assert_eq!(
14497 extents,
14498 vec![crcbl_hal::Extent3d::d2(1, 1)],
14499 "a description with no normal map must upload the one-texel placeholder, and \
14500 this copied {} level(s) at {extents:?} — a burned neutral layer costs \
14501 extent² × 4 bytes and a third again for its chain, on every scene in the tree",
14502 copies.len()
14503 );
14504
14505 // The placeholder is one layer, and the graph declaration says so: a
14506 // caller importing this page to write a layer of its own would get
14507 // `ImportDeclarationConflict` against an extent that was not 1×1.
14508 assert_eq!(
14509 renderer.normal_page_import().extent,
14510 (1, 1),
14511 "the declaration names the placeholder's extent, not the base-colour page's"
14512 );
14513 renderer.destroy(device.as_ref());
14514 }
14515
14516 /// **A page and a material table that are the caller's own, not
14517 /// [`scene::demo`]'s**: a different extent per kind, more layers than the
14518 /// demo page holds, a normal page the demo does not have at all, and rows
14519 /// past the three the demo writes.
14520 ///
14521 /// Every other scene in the tree is `scene::demo()` — with a mesh appended,
14522 /// at most — so until this nothing had put an app-supplied *layer* or an
14523 /// app-supplied *row* through [`ForwardRenderer::with_scene`] at all. A
14524 /// build that uploaded the demo's two layers and stopped, or that inserted
14525 /// its three rows and stopped, would leave every golden byte-identical and
14526 /// pass every other assertion in this module: the demo scene cannot tell a
14527 /// table filled from the description from one filled up to the description's
14528 /// third row.
14529 ///
14530 /// Read off the recorder rather than off the description, because the
14531 /// description is the input. The copies are what reached the image and the
14532 /// table buffer is what the shader indexes, and neither is a restatement of
14533 /// what was handed in.
14534 #[test]
14535 fn an_app_page_and_table_reach_the_device_whole() {
14536 use crcbl_hal::null::Command;
14537
14538 /// Not [`scene::PAGE_EXTENT`], so an extent that had been compiled in
14539 /// rather than read off the page shows up as a copy of the wrong size.
14540 const APP_EXTENT: u32 = 4;
14541
14542 /// **Not [`APP_EXTENT`]**, which is the whole of what row (d)'s per-kind
14543 /// extent bought: a renderer that still sized the normal page from the
14544 /// base-colour page's number would copy this layer at 4² and the copy
14545 /// list below would say so.
14546 const APP_NORMAL_EXTENT: u32 = 2;
14547 let layer_bytes = APP_EXTENT as usize * APP_EXTENT as usize * 4;
14548
14549 // Three base-colour layers, each flat and each a value of its own: a
14550 // build that uploaded one layer twice, or that stopped short, is a
14551 // different sequence of copies. Then one normal layer at the other
14552 // extent, which the demo scene has no page for at all.
14553 let mut page = scene::PageDesc::empty();
14554 page.set_extent(PageKind::BaseColor, APP_EXTENT);
14555 page.set_extent(PageKind::Normal, APP_NORMAL_EXTENT);
14556 let app_layers: Vec<u32> = [0x11_u8, 0x22, 0x33]
14557 .into_iter()
14558 .map(|value| page.push_layer(PageKind::BaseColor, vec![value; layer_bytes]))
14559 .collect();
14560 let app_normal = page.push_layer(
14561 PageKind::Normal,
14562 scene::PageDesc::NEUTRAL_NORMAL
14563 .repeat(APP_NORMAL_EXTENT as usize * APP_NORMAL_EXTENT as usize),
14564 );
14565
14566 let mut scene = scene::demo();
14567 scene.page = page;
14568 // One row per appended layer, and each with a factor of its own as well,
14569 // so a row that landed at another row's id is not a row that happens to
14570 // look like it. The last of them names the normal layer too, so the
14571 // table carries a row through both pages.
14572 for (nth, &layer) in app_layers.iter().enumerate() {
14573 let shade = 0.25 * (nth as f32 + 1.0);
14574 let last = nth + 1 == app_layers.len();
14575 scene.materials.push(mesh::GpuMaterial {
14576 base_color: [shade, shade, shade, 1.0],
14577 base_color_texture: layer,
14578 normal_texture: if last {
14579 app_normal
14580 } else {
14581 mesh::GpuMaterial::NO_PAGE
14582 },
14583 ..mesh::GpuMaterial::UNTINTED
14584 });
14585 }
14586 assert!(
14587 scene.materials.len() > scene::demo().materials.len()
14588 && scene.page.layers(PageKind::BaseColor).len()
14589 > scene::demo().page.layers(PageKind::BaseColor).len(),
14590 "the description under test must exceed the demo's in both, or this is a \
14591 demo test wearing another name"
14592 );
14593 assert_eq!(
14594 scene::demo().page.extent(PageKind::Normal),
14595 0,
14596 "the demo scene must name no normal page, or the normal copies below are \
14597 evidence about the demo's page rather than the caller's"
14598 );
14599
14600 let (recorder, device, queue) = open();
14601 let mut renderer =
14602 ForwardRenderer::with_scene(device.as_ref(), queue, Format::Rgba8UnormSrgb, &scene)
14603 .expect("a page and a table of the caller's own are ones this can make resident");
14604
14605 // The page, layer by layer. Filtered by image because the build uploads
14606 // the ambient-occlusion placeholder through the same path.
14607 let copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14608 .commands()
14609 .into_iter()
14610 .filter_map(|command| match command {
14611 Command::CopyBufferToImage(copy)
14612 if copy.image == renderer.base_color_page.image =>
14613 {
14614 Some(copy)
14615 }
14616 _ => None,
14617 })
14618 .collect();
14619 // Every layer goes up with its chain — three levels for this extent —
14620 // so the copies are layer-major, level-minor, each at its level's own
14621 // extent.
14622 let levels = crcbl_hal::Extent3d::d2(APP_EXTENT, APP_EXTENT)
14623 .full_mip_levels(crcbl_hal::ImageType::D2);
14624 assert_eq!(levels, 3, "a 4² page has three levels down to one texel");
14625 let layer_count = u32::try_from(scene.page.layers(PageKind::BaseColor).len())
14626 .expect("a page of a few layers");
14627 assert_eq!(
14628 copies
14629 .iter()
14630 .map(|copy| (
14631 copy.image_subresource.base_layer,
14632 copy.image_subresource.mip
14633 ))
14634 .collect::<Vec<(u32, u32)>>(),
14635 (0..layer_count)
14636 .flat_map(|layer| (0..levels).map(move |level| (layer, level)))
14637 .collect::<Vec<(u32, u32)>>(),
14638 "every level of every layer the description carries must be copied into the page, \
14639 in order"
14640 );
14641 assert!(
14642 copies.iter().all(|copy| {
14643 let side = crate::mip::level_extent(APP_EXTENT, copy.image_subresource.mip);
14644 copy.image_extent == crcbl_hal::Extent3d::d2(side, side)
14645 }),
14646 "the page is the extent the caller wrote, not the demo's, halved per level: \
14647 {copies:?}"
14648 );
14649
14650 // The normal page, at **its own** extent. One layer, two levels for a
14651 // 2² image, and every copy sized from `APP_NORMAL_EXTENT` — a renderer
14652 // that carried one extent for both kinds would put this layer up at 4².
14653 let normal_copies: Vec<crcbl_hal::BufferImageCopy> = recorder
14654 .commands()
14655 .into_iter()
14656 .filter_map(|command| match command {
14657 Command::CopyBufferToImage(copy) if copy.image == renderer.normal_page.image => {
14658 Some(copy)
14659 }
14660 _ => None,
14661 })
14662 .collect();
14663 let normal_levels = crcbl_hal::Extent3d::d2(APP_NORMAL_EXTENT, APP_NORMAL_EXTENT)
14664 .full_mip_levels(crcbl_hal::ImageType::D2);
14665 assert_eq!(
14666 normal_copies
14667 .iter()
14668 .map(|copy| (
14669 copy.image_subresource.base_layer,
14670 copy.image_subresource.mip,
14671 copy.image_extent
14672 ))
14673 .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14674 (0..normal_levels)
14675 .map(|level| {
14676 let side = crate::mip::level_extent(APP_NORMAL_EXTENT, level);
14677 (0, level, crcbl_hal::Extent3d::d2(side, side))
14678 })
14679 .collect::<Vec<(u32, u32, crcbl_hal::Extent3d)>>(),
14680 "the normal page is the extent the caller wrote for *that* kind, halved per \
14681 level: {normal_copies:?}"
14682 );
14683 assert_eq!(
14684 renderer.normal_page_import().extent,
14685 (APP_NORMAL_EXTENT, APP_NORMAL_EXTENT),
14686 "the graph declaration names the normal page's own extent, or a caller \
14687 importing it to write a layer gets ImportDeclarationConflict"
14688 );
14689 assert_eq!(
14690 renderer.base_color_page_import().extent,
14691 (APP_EXTENT, APP_EXTENT),
14692 "and the base-colour declaration names its own, which is a different number"
14693 );
14694
14695 // The table, row by row, out of the buffer `mesh.slang` indexes.
14696 let bytes = recorder
14697 .buffer_bytes(renderer.materials.buffer())
14698 .expect("the table is live");
14699 let row = |id: u32| {
14700 let at = id as usize * crcbl_shaders::mesh::MATERIAL_STRIDE;
14701 mesh::GpuMaterial::from_bytes(
14702 bytes[at..at + crcbl_shaders::mesh::MATERIAL_STRIDE]
14703 .try_into()
14704 .expect("one row"),
14705 )
14706 };
14707 assert_eq!(
14708 renderer.material_ids.len(),
14709 scene.materials.len(),
14710 "one id per description row, whatever the count"
14711 );
14712 for (index, wrote) in scene.materials.iter().enumerate() {
14713 assert_eq!(
14714 &row(renderer.material_ids[index]),
14715 wrote,
14716 "description row {index} must be the row its id names"
14717 );
14718 }
14719
14720 // And a caller can place an object through a row only its own
14721 // description has, which is the whole point of the rows being the
14722 // caller's.
14723 let last = scene.materials.len() - 1;
14724 let handle = renderer
14725 .add_instance(&InstanceDesc {
14726 mesh: DEMO_CUBE,
14727 material: last,
14728 transform: Mat4::IDENTITY,
14729 })
14730 .expect("an empty pool of thousands has room for one object");
14731 assert_eq!(
14732 renderer
14733 .instances
14734 .get(handle)
14735 .expect("a just-added instance is live")
14736 .material,
14737 renderer.material_ids[last],
14738 "an InstanceDesc's material index resolves through the description, not \
14739 through a table id the caller cannot know"
14740 );
14741
14742 renderer.destroy(device.as_ref());
14743 recorder.assert_valid();
14744 }
14745
14746 /// **The frame records two compute dispatches and exactly one indirect draw
14747 /// per bucket — whatever is in the scene.**
14748 ///
14749 /// The property topic 03 opens with, checked on the recorded command stream:
14750 /// adding the pyramid adds an instance and changes no command. A pass that
14751 /// had kept a draw per object would record one command here and two there,
14752 /// which is what this used to assert and what the indirect path replaced.
14753 ///
14754 /// It also pins the arguments each call names: bucket `n` reads the `n`-th
14755 /// argument structure and the `n`-th count, at the stride every API fixed.
14756 /// Two calls pointing at one structure is a frame that draws one object
14757 /// twice.
14758 #[test]
14759 fn the_frame_records_one_indirect_call_per_bucket_whatever_the_scene_holds() {
14760 use crcbl_hal::null::Command;
14761
14762 for pyramid in [None, Some(Mat4::from_translation(Vec3::X))] {
14763 let (recorder, device, queue) = open();
14764 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14765 .expect("built");
14766 // The cube in both scenes, so the difference between them is the
14767 // pyramid alone. It also keeps both frames non-empty, and an empty
14768 // one would be a weaker comparison than this claims: `cull`'s
14769 // dispatch covers no workgroups when the pool is empty, and the pass
14770 // records nothing rather than a dispatch of zero — see
14771 // [`DrawGen::add_passes`].
14772 place_cube(&mut renderer, Mat4::IDENTITY);
14773 if let Some(at) = pyramid {
14774 place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, at);
14775 }
14776 let frame = frame(device.as_ref(), &mut renderer, queue);
14777
14778 let stride = crcbl_shaders::draw_gen::DRAW_ARGS_SIZE as u32;
14779 let expected: Vec<(u32, u64, u64)> = (0..renderer.bucket_constants.len())
14780 .map(|bucket| {
14781 (
14782 renderer.bucket_constants[bucket],
14783 bucket as u64 * u64::from(stride),
14784 bucket as u64 * 4,
14785 )
14786 })
14787 .collect();
14788
14789 // The dynamic offset last bound before each draw, paired with the
14790 // offsets that draw read its arguments and its count from.
14791 let mut offset = None;
14792 let mut seen: Vec<(u32, u64, u64)> = Vec::new();
14793 let mut dispatches = 0;
14794 for command in recorder.commands() {
14795 if matches!(command, Command::Dispatch { .. }) {
14796 dispatches += 1;
14797 }
14798 }
14799 for command in commands_in_pass(&recorder, "forward") {
14800 match command {
14801 Command::BindGroup {
14802 slot: 0,
14803 dynamic_offsets,
14804 ..
14805 } => offset = dynamic_offsets.first().copied(),
14806 Command::DrawIndexedIndirectCount(draw) => {
14807 assert_eq!(draw.stride, stride, "sizeof(VkDrawIndexedIndirectCommand)");
14808 assert_eq!(
14809 draw.max_draw_count, 1,
14810 "one argument structure per bucket, so one is the ceiling"
14811 );
14812 seen.push((
14813 offset.expect("a draw is preceded by its constant block"),
14814 draw.args_offset,
14815 draw.count_offset,
14816 ));
14817 }
14818 Command::DrawIndexed { .. } => {
14819 panic!("the forward pass must not record a CPU-counted draw any more")
14820 }
14821 _ => {}
14822 }
14823 }
14824 assert_eq!(
14825 dispatches,
14826 DrawGen::DISPATCHES as usize * (1 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
14827 "the clearing pass, the cull pass and the draw-argument pass's three, in \
14828 front of the draws — once for the camera and once per shadow cascade — plus \
14829 topic 18's one clustering dispatch, which is the camera's alone because a \
14830 cascade shades nothing, plus the resolve's own"
14831 );
14832 assert_eq!(
14833 seen, expected,
14834 "with pyramid = {pyramid:?}, the pass must record one indirect call per \
14835 bucket, each pointing at its own arguments, its own count and its own \
14836 block"
14837 );
14838
14839 frame.finish(device.as_ref(), renderer);
14840 }
14841 }
14842
14843 /// **The two `GeometryPath` arms record different calls and nothing else
14844 /// differs.**
14845 ///
14846 /// A device with a GPU-side count takes it from GPU memory; one without —
14847 /// Metal, whose API has multi-draw-indirect and no count buffer — reads each
14848 /// bucket's one argument structure unconditionally. Same buckets, same
14849 /// arguments, same block: the tail is the only thing that moves, which is
14850 /// what topic 03 means by "the lesser path is
14851 /// a constraint on data layout, not a separate renderer".
14852 ///
14853 /// Both presets are run here rather than only the one this machine has,
14854 /// because the arm a device never selects is the arm nothing tests.
14855 #[test]
14856 fn each_geometry_path_records_its_own_indirect_call() {
14857 use crcbl_hal::null::Command;
14858
14859 for (preset, path, counted) in [
14860 (
14861 NullInstance::gpu_driven(),
14862 GeometryPath::IndirectCount,
14863 true,
14864 ),
14865 (
14866 NullInstance::portable(),
14867 GeometryPath::IndirectPerBatch,
14868 false,
14869 ),
14870 ] {
14871 let recorder = Recorder::new();
14872 let instance = preset.with_recorder(recorder.clone());
14873 let adapter = instance.adapters().remove(0);
14874 assert_eq!(
14875 instance
14876 .adapter_caps(adapter.id)
14877 .expect("the null backend describes its adapter")
14878 .geometry_path(),
14879 path,
14880 "the preset must select the path this arm is about"
14881 );
14882 // `DeviceDesc::for_adapter` requires a timeline semaphore, which the
14883 // portable preset does not have; the forward pass does not need one
14884 // either, so this asks for what it uses. The optional set matters:
14885 // a device is opened with the features it *asked* for, and the path
14886 // is derived from those rather than from the adapter's.
14887 let device = instance
14888 .create_device(&DeviceDesc {
14889 label: None,
14890 adapter: adapter.id,
14891 required_features: Features::COMPUTE,
14892 optional_features: Features::GPU_DRIVEN,
14893 compatible_surface: None,
14894 })
14895 .expect("the null backend always opens");
14896 assert_eq!(
14897 device.caps().geometry_path(),
14898 path,
14899 "and the opened device still selects it"
14900 );
14901 let queue = device.queue(QueueKind::Graphics).expect("always present");
14902 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
14903 .expect("built");
14904 let frame = frame(device.as_ref(), &mut renderer, queue);
14905
14906 let mut counted_calls = 0;
14907 let mut per_batch_calls = 0;
14908 for command in commands_in_pass(&recorder, "forward") {
14909 match command {
14910 Command::DrawIndexedIndirectCount(_) => counted_calls += 1,
14911 Command::DrawIndexedIndirect(draw) => {
14912 assert_eq!(
14913 draw.draw_count, 1,
14914 "one argument structure per bucket, read unconditionally"
14915 );
14916 per_batch_calls += 1;
14917 }
14918 _ => {}
14919 }
14920 }
14921 let buckets = renderer.bucket_constants.len();
14922 let (expected_counted, expected_per_batch) =
14923 if counted { (buckets, 0) } else { (0, buckets) };
14924 assert_eq!(
14925 (counted_calls, per_batch_calls),
14926 (expected_counted, expected_per_batch),
14927 "{path:?} must record one call of its own kind per bucket and none of the other"
14928 );
14929
14930 frame.finish(device.as_ref(), renderer);
14931 }
14932 }
14933
14934 /// Serialises the two checks that move
14935 /// [`r_debug_draw`](crate::debug_draw::r_debug_draw), and puts it back
14936 /// afterwards.
14937 ///
14938 /// A [`ConVar`](crcbl_console::ConVar) is process-global by design, and
14939 /// `cargo test` runs a crate's tests as threads of *one* process: two checks
14940 /// that move the switch are then two writers to one cell, which shows up as
14941 /// a flake rather than as a failure anybody can read.
14942 /// `crcbl::debug_view::for_test` is the same shape one crate up and there
14943 /// for the same reason; this one is smaller because nothing outside these
14944 /// two tests ever writes the cell.
14945 fn debug_draw_switch() -> DebugDrawSwitch {
14946 let guard = DEBUG_DRAW_SWITCH
14947 .lock()
14948 .unwrap_or_else(std::sync::PoisonError::into_inner);
14949 let switch = DebugDrawSwitch { _guard: guard };
14950 switch.set(false);
14951 switch
14952 }
14953
14954 /// What [`debug_draw_switch`] hands back: the switch is this thread's until
14955 /// it drops, and it goes back off when it does.
14956 struct DebugDrawSwitch {
14957 _guard: std::sync::MutexGuard<'static, ()>,
14958 }
14959
14960 impl DebugDrawSwitch {
14961 /// Moves the switch.
14962 fn set(&self, on: bool) {
14963 crate::debug_draw::r_debug_draw
14964 .set(&crcbl_console::Value::Bool(on))
14965 .expect("`r_debug_draw` is a writable bool");
14966 }
14967 }
14968
14969 impl Drop for DebugDrawSwitch {
14970 fn drop(&mut self) {
14971 // Off at both ends, so a check that panicked mid-way does not hand
14972 // the next holder a switched-on layer.
14973 self.set(false);
14974 }
14975 }
14976
14977 /// [`debug_draw_switch`]'s lock.
14978 ///
14979 /// **First of the two**, when a test takes this and [`ssao_blur_switch`]
14980 /// both — see that function for what the opposite order cost.
14981 static DEBUG_DRAW_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
14982
14983 /// Takes `r_ssao_blur_passes` for this thread and puts it back at its
14984 /// default when the guard drops.
14985 ///
14986 /// [`debug_draw_switch`]'s shape exactly, for its reason: a plain
14987 /// `cargo test` run shares one process between tests, and a variable this
14988 /// one left moved is a frame the next test did not ask for.
14989 ///
14990 /// **Every test whose assertion depends on the shape of a frame takes this,
14991 /// not only the one that moves the count.** The variable is a process
14992 /// global and `cargo test` runs this module's tests on threads that share
14993 /// it, so a frame built while
14994 /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] holds two blurs
14995 /// carries an `ssao-blur-2` pass, a full-screen triangle and a pipeline bind
14996 /// that the test building it never asked for. Taking the guard both
14997 /// serialises against that test and pins the count for the frames this one
14998 /// builds.
14999 ///
15000 /// Two shapes need it, and the second is easy to miss. A test comparing a
15001 /// frame against a **literal pass list** breaks whenever the count is two.
15002 /// A test comparing **two frames it built itself** — a difference in draws,
15003 /// an equality between pass lists, a "one pass longer" claim — breaks only
15004 /// when the count *moves between them*, which is a narrower window and why
15005 /// this reproduced at roughly one run in eight rather than every run.
15006 ///
15007 /// Both were established by experiment on 2026-09-01 rather than by
15008 /// reading: pinning the count at two reddens the first shape, and making
15009 /// `crate::ssao::blur_passes` alternate reddens the second.
15010 ///
15011 /// **A test taking this and [`debug_draw_switch`] takes that one first.**
15012 /// These are two plain mutexes with no ordering between them, so two tests
15013 /// acquiring both in opposite orders deadlock — which is not a hazard this
15014 /// comment is guessing at: adding the guard to the two debug-draw tests
15015 /// above their existing one did exactly that on 2026-09-01, and turned a
15016 /// 0.2 second suite into one that had not finished in ten minutes. It is
15017 /// invisible in a single-threaded run, where the same suite passes in a
15018 /// second, so `--test-threads=1` is not a check for it.
15019 ///
15020 /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`]: fn@a_second_occlusion_blur_is_a_pass_the_frame_records
15021 pub(super) fn ssao_blur_switch() -> SsaoBlurSwitch {
15022 let guard = SSAO_BLUR_SWITCH
15023 .lock()
15024 .unwrap_or_else(std::sync::PoisonError::into_inner);
15025 let switch = SsaoBlurSwitch { _guard: guard };
15026 switch.set(1);
15027 switch
15028 }
15029
15030 /// What [`ssao_blur_switch`] hands back.
15031 pub(super) struct SsaoBlurSwitch {
15032 _guard: std::sync::MutexGuard<'static, ()>,
15033 }
15034
15035 impl SsaoBlurSwitch {
15036 /// Asks for `passes` of them.
15037 fn set(&self, passes: i64) {
15038 crate::ssao::r_ssao_blur_passes
15039 .set(&crcbl_console::Value::Int(passes))
15040 .expect("`r_ssao_blur_passes` is a writable int in range");
15041 }
15042 }
15043
15044 impl Drop for SsaoBlurSwitch {
15045 fn drop(&mut self) {
15046 // Back to the shipping count at both ends, so a check that panicked
15047 // mid-way does not hand the next holder a three-pass frame.
15048 self.set(1);
15049 }
15050 }
15051
15052 /// [`ssao_blur_switch`]'s lock.
15053 static SSAO_BLUR_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15054
15055 /// Takes `r_ssao_split` for this thread and puts it back when the guard
15056 /// drops.
15057 ///
15058 /// [`ssao_blur_switch`]'s shape exactly, for its reason. The seam is what
15059 /// makes the occlusion chain record its second march, so a test about the
15060 /// widest frame a renderer can produce has to hold this as well as the blur
15061 /// count — see `crate::ssao`'s `r_ssao_split`.
15062 pub(super) fn ssao_split_switch() -> SsaoSplitSwitch {
15063 let guard = SSAO_SPLIT_SWITCH
15064 .lock()
15065 .unwrap_or_else(std::sync::PoisonError::into_inner);
15066 let switch = SsaoSplitSwitch { _guard: guard };
15067 switch.set(0.0);
15068 switch
15069 }
15070
15071 /// What [`ssao_split_switch`] hands back.
15072 pub(super) struct SsaoSplitSwitch {
15073 _guard: std::sync::MutexGuard<'static, ()>,
15074 }
15075
15076 impl SsaoSplitSwitch {
15077 /// Asks for a seam at `at`, or for none at zero.
15078 fn set(&self, at: f32) {
15079 crate::ssao::r_ssao_split
15080 .set(&crcbl_console::Value::Float(at))
15081 .expect("`r_ssao_split` is a writable float in range");
15082 }
15083 }
15084
15085 impl Drop for SsaoSplitSwitch {
15086 fn drop(&mut self) {
15087 // Back to the default at both ends, so a check that panicked
15088 // mid-way does not hand the next holder a comparing frame.
15089 self.set(0.0);
15090 }
15091 }
15092
15093 /// [`ssao_split_switch`]'s lock.
15094 static SSAO_SPLIT_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15095
15096 /// Takes `r_shadow_filter` and `r_shadow_split` for this thread and puts
15097 /// them both back at their defaults when the guard drops.
15098 ///
15099 /// [`ssao_split_switch`]'s shape, with two variables under one lock because
15100 /// they are read into one row of one block — `crate::shadow::FILTER_SWITCH`
15101 /// is where that is argued, and why the lock lives there rather than beside
15102 /// this function: `crate::shadow`'s own tests move the same two.
15103 fn shadow_filter_switch() -> ShadowFilterSwitch {
15104 let guard = crate::shadow::FILTER_SWITCH
15105 .lock()
15106 .unwrap_or_else(std::sync::PoisonError::into_inner);
15107 let switch = ShadowFilterSwitch { _guard: guard };
15108 switch.reset();
15109 switch
15110 }
15111
15112 /// What [`shadow_filter_switch`] hands back.
15113 struct ShadowFilterSwitch {
15114 _guard: std::sync::MutexGuard<'static, ()>,
15115 }
15116
15117 impl ShadowFilterSwitch {
15118 /// Asks for `filter` on the near side of the seam.
15119 fn filter(&self, filter: shadow::Filter) {
15120 crate::shadow::r_shadow_filter
15121 .set(&crcbl_console::Value::Enum(filter.label()))
15122 .expect("`r_shadow_filter` is a writable enum in the set");
15123 }
15124
15125 /// Asks for a seam at `at`, or for none at zero.
15126 fn seam(&self, at: f32) {
15127 crate::shadow::r_shadow_split
15128 .set(&crcbl_console::Value::Float(at))
15129 .expect("`r_shadow_split` is a writable float in range");
15130 }
15131
15132 /// Asks for `texels` of constant bias.
15133 fn bias(&self, texels: f32) {
15134 crate::shadow::r_shadow_bias
15135 .set(&crcbl_console::Value::Float(texels))
15136 .expect("`r_shadow_bias` is a writable float in range");
15137 }
15138
15139 /// Asks for `texels` of normal offset.
15140 fn offset(&self, texels: f32) {
15141 crate::shadow::r_shadow_normal_offset
15142 .set(&crcbl_console::Value::Float(texels))
15143 .expect("`r_shadow_normal_offset` is a writable float in range");
15144 }
15145
15146 /// Back to the frame every golden was blessed as.
15147 fn reset(&self) {
15148 self.filter(shadow::shipped_filter());
15149 self.seam(0.0);
15150 self.bias(shipped_float(&crate::shadow::r_shadow_bias));
15151 self.offset(shipped_float(&crate::shadow::r_shadow_normal_offset));
15152 }
15153 }
15154
15155 /// The float `var` declares as its default — what a frame nobody typed at
15156 /// is drawn with, read off the variable rather than written down here.
15157 fn shipped_float(var: &crcbl_console::ConVar) -> f32 {
15158 match var.default() {
15159 crcbl_console::Value::Float(shipped) => *shipped,
15160 other => panic!("`{}` defaults to {other:?}, not to a float", var.name()),
15161 }
15162 }
15163
15164 impl Drop for ShadowFilterSwitch {
15165 fn drop(&mut self) {
15166 // Back to the defaults at both ends, so a check that panicked
15167 // mid-way does not hand the next holder a comparing frame.
15168 self.reset();
15169 }
15170 }
15171
15172 /// Takes `r_ssao_slices` for this thread and puts it back at its default
15173 /// when the guard drops.
15174 ///
15175 /// [`ssao_blur_switch`]'s shape exactly, for its reason: a plain
15176 /// `cargo test` run shares one process between tests, and a variable this
15177 /// one left moved is a frame the next test did not ask for.
15178 fn ssao_slice_switch() -> SsaoSliceSwitch {
15179 let guard = SSAO_SLICE_SWITCH
15180 .lock()
15181 .unwrap_or_else(std::sync::PoisonError::into_inner);
15182 let switch = SsaoSliceSwitch { _guard: guard };
15183 switch.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15184 switch
15185 }
15186
15187 /// What [`ssao_slice_switch`] hands back.
15188 struct SsaoSliceSwitch {
15189 _guard: std::sync::MutexGuard<'static, ()>,
15190 }
15191
15192 impl SsaoSliceSwitch {
15193 /// Asks each pixel for `slices` of them.
15194 fn set(&self, slices: i64) {
15195 crate::ssao::r_ssao_slices
15196 .set(&crcbl_console::Value::Int(slices))
15197 .expect("`r_ssao_slices` is a writable int in range");
15198 }
15199 }
15200
15201 impl Drop for SsaoSliceSwitch {
15202 fn drop(&mut self) {
15203 // Back to the shipping count at both ends, so a check that panicked
15204 // mid-way does not hand the next holder a four-slice frame — which
15205 // is a frame every golden in this workspace was blessed without.
15206 self.set(i64::from(ssao::SLICE_COUNT_DEFAULT));
15207 }
15208 }
15209
15210 /// [`ssao_slice_switch`]'s lock.
15211 static SSAO_SLICE_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
15212
15213 /// Takes `r_ssao_technique` for this thread and puts it back at its default
15214 /// when the guard drops.
15215 ///
15216 /// [`ssao_blur_switch`]'s shape exactly, for its reason — and this one moves
15217 /// a **pipeline** rather than a lane of a uniform block, so a frame that
15218 /// picked it up from another thread's test gathers through a shader that
15219 /// test never selected.
15220 ///
15221 /// **Its lock lives in `crate::ssao`** rather than beside this function, and
15222 /// it is the one switch here whose does: `ssao`'s own
15223 /// `the_seams_other_side_is_the_technique_that_ships` moves the same
15224 /// variable, and a second mutex would serialise neither against the other.
15225 /// See `crate::ssao::TECHNIQUE_SWITCH` for where it sits in the order.
15226 fn ssao_technique_switch() -> SsaoTechniqueSwitch {
15227 let guard = crate::ssao::TECHNIQUE_SWITCH
15228 .lock()
15229 .unwrap_or_else(std::sync::PoisonError::into_inner);
15230 let switch = SsaoTechniqueSwitch { _guard: guard };
15231 switch.set(shipped_technique_name());
15232 switch
15233 }
15234
15235 /// The technique name the chain ships, and the one
15236 /// [`ssao_technique_switch`] restores.
15237 ///
15238 /// **Read off the variable rather than written down**, which is
15239 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
15240 /// rule about the slice count and for its reason: which value ships is a
15241 /// thing that moves, and a test naming the wrong one would be comparing the
15242 /// shipped configuration against itself.
15243 ///
15244 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
15245 fn shipped_technique_name() -> &'static str {
15246 match crate::ssao::r_ssao_technique.default() {
15247 crcbl_console::Value::Enum(name) => name,
15248 other => panic!("`r_ssao_technique` defaults to {other:?}, not to a technique name"),
15249 }
15250 }
15251
15252 /// A name from the variable's own set that is **not** the one it ships.
15253 ///
15254 /// [`shipped_technique_name`]'s clause from the other side: the tests below
15255 /// need a technique to move the console to, and picking it out of the
15256 /// declared set is what keeps them from naming one the variable does not
15257 /// offer — or, if a third arrived, from silently going on comparing the
15258 /// same two.
15259 fn other_technique_name() -> &'static str {
15260 let crcbl_console::Kind::Enum(names) = crate::ssao::r_ssao_technique.kind() else {
15261 panic!("`r_ssao_technique` is an enum variable");
15262 };
15263 let ships = shipped_technique_name();
15264 names
15265 .iter()
15266 .copied()
15267 .find(|name| *name != ships)
15268 .expect("`r_ssao_technique` offers a technique other than the one it ships")
15269 }
15270
15271 /// What [`ssao_technique_switch`] hands back.
15272 struct SsaoTechniqueSwitch {
15273 _guard: std::sync::MutexGuard<'static, ()>,
15274 }
15275
15276 impl SsaoTechniqueSwitch {
15277 /// Asks for the gather `name` selects.
15278 fn set(&self, name: &'static str) {
15279 crate::ssao::r_ssao_technique
15280 .set(&crcbl_console::Value::Enum(name))
15281 .expect("`r_ssao_technique` is a writable enum in the set");
15282 }
15283 }
15284
15285 impl Drop for SsaoTechniqueSwitch {
15286 fn drop(&mut self) {
15287 // Back to what ships at both ends, so a check that panicked mid-way
15288 // does not hand the next holder a frame gathered through the cheap
15289 // tier — which is a frame no golden in this workspace was blessed
15290 // on.
15291 self.set(shipped_technique_name());
15292 }
15293 }
15294
15295 /// Every draw the recorded stream holds, whichever call recorded it.
15296 ///
15297 /// Not scoped to a pass, unlike [`commands_in_pass`]: what
15298 /// [`ForwardRenderer::counters`] claims is a count over the *whole* frame, so
15299 /// the thing to compare it against is the whole frame.
15300 fn recorded_draws(recorder: &Recorder) -> usize {
15301 use crcbl_hal::null::Command;
15302
15303 recorder
15304 .commands()
15305 .into_iter()
15306 .filter(|command| {
15307 matches!(
15308 command,
15309 Command::Draw { .. }
15310 | Command::DrawIndexed { .. }
15311 | Command::DrawIndirect(_)
15312 | Command::DrawIndexedIndirect(_)
15313 | Command::DrawIndirectCount(_)
15314 | Command::DrawIndexedIndirectCount(_)
15315 | Command::DrawMeshTasks { .. }
15316 | Command::DrawMeshTasksIndirect(_)
15317 )
15318 })
15319 .count()
15320 }
15321
15322 /// **The draw count is what the frame recorded, and the two GPU-side
15323 /// counters are `None` rather than a guess.**
15324 ///
15325 /// Both halves matter and both are checked here against something that
15326 /// moves. The draws are compared with the recorded stream, so a count that
15327 /// forgot the shadow pass's share or the tonemap's triangle fails. The
15328 /// instances are read before and after a pyramid is put in the pool, so a
15329 /// counter wired to a constant — or to the pool's *capacity*, which does not
15330 /// move — fails too.
15331 ///
15332 /// `drawn` and `triangles` are asserted [`None`] **on the frames this test
15333 /// runs**, which are inside [`CULL_STATS_FLOOR`]: nothing has come
15334 /// back off the GPU yet, and a `drawn` that was `Some` here would be a
15335 /// number invented before any readback landed. That is the assertion that
15336 /// catches the tempting version of this method: an instance count taken from
15337 /// the pool and reported as "drawn" would read as a culling win of exactly
15338 /// zero on every frame, which is the number the whole cull exists to change.
15339 /// What happens once the ring *has* come round is the test below.
15340 #[test]
15341 fn the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know() {
15342 let _blurs = ssao_blur_switch();
15343 let (recorder, device, queue) = open();
15344 let mut renderer =
15345 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15346
15347 // Before any frame: nothing recorded, and said as a known zero.
15348 assert_eq!(renderer.counters(), FrameCounters::default());
15349
15350 let first = frame(device.as_ref(), &mut renderer, queue);
15351 let counters = renderer.counters();
15352 assert_eq!(
15353 counters.draws,
15354 recorded_draws(&recorder) as u64,
15355 "the counter and the frame's recorded draws disagree",
15356 );
15357 // Derived from what the frame resolved rather than from a constant, so
15358 // this is still the every-effect frame's count and would follow a frame
15359 // that switched one off.
15360 let fullscreen = fullscreen_passes(
15361 renderer.effects(),
15362 TEST_EXTENT,
15363 false,
15364 renderer.frame_ssao_blurs,
15365 ) * FULLSCREEN_DRAWS;
15366 assert!(
15367 counters.draws > fullscreen,
15368 "a frame that recorded only its full-screen passes drew no scene",
15369 );
15370 assert_eq!(
15371 counters.instances,
15372 renderer.instances.len() as u64 + fullscreen,
15373 );
15374 assert_eq!(
15375 counters.drawn, None,
15376 "the ring has not come round, so there is no survivor count yet",
15377 );
15378 assert_eq!(counters.cull_frame, None, "and no frame to stamp it with");
15379 assert_eq!(counters.triangles, None);
15380 first.release(device.as_ref());
15381
15382 // A second scene: one more instance in the pool, and the counter moves
15383 // with it. The draws do not — one call per bucket whatever the scene
15384 // holds is what §3.3 is about, and this is where that shows.
15385 place_demo(&mut renderer, DEMO_PYRAMID, DEMO_UNTINTED, Mat4::IDENTITY);
15386 recorder.clear();
15387 let second = frame(device.as_ref(), &mut renderer, queue);
15388 let richer = renderer.counters();
15389 assert_eq!(
15390 richer.instances,
15391 counters.instances + 1,
15392 "an instance added to the pool must move the counter",
15393 );
15394 assert_eq!(
15395 richer.draws, counters.draws,
15396 "the recorded call count is independent of what the scene holds",
15397 );
15398 assert_eq!(richer.draws, recorded_draws(&recorder) as u64);
15399
15400 second.finish(device.as_ref(), renderer);
15401 }
15402
15403 /// **Once the ring has come round, `drawn` is a number and it says which
15404 /// frame it is from.**
15405 ///
15406 /// The other half of the test above: `indirect` while the readback is in
15407 /// flight, a count afterwards, and a `cull_frame` naming a frame several
15408 /// behind the one just recorded. The null backend executes no copy, so the
15409 /// *value* here is the full-screen passes' own draws and nothing else — what the cull
15410 /// really kept is asserted against a real GPU, in the umbrella crate's
15411 /// `tests/draw_gen_e2e/`, where a scene is culled on purpose.
15412 ///
15413 /// The frame number is the assertion with teeth here: a ring that read the
15414 /// slot it had just written would report the frame it is on, and a
15415 /// `cull_frame` left at `None` would put a latent number on the panel with
15416 /// nothing to say how old it is.
15417 #[test]
15418 fn the_culling_counters_arrive_a_few_frames_late_and_say_which_frame() {
15419 let (_recorder, device, queue) = open();
15420 let mut renderer =
15421 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15422
15423 let mut frames = Vec::new();
15424 for _ in 0..CULL_STATS_FLOOR {
15425 frames.push(frame(device.as_ref(), &mut renderer, queue));
15426 assert_eq!(
15427 renderer.counters().drawn,
15428 None,
15429 "no readback has even been polled yet, so there is nothing back",
15430 );
15431 }
15432
15433 frames.push(frame(device.as_ref(), &mut renderer, queue));
15434 let counters = renderer.counters();
15435 assert_eq!(
15436 counters.drawn,
15437 Some(
15438 fullscreen_passes(
15439 renderer.effects(),
15440 TEST_EXTENT,
15441 false,
15442 renderer.frame_ssao_blurs,
15443 ) * FULLSCREEN_DRAWS,
15444 ),
15445 "the survivor count the null backend produced is zero, plus one instance per \
15446 full-screen pass — which is on both sides of the row",
15447 );
15448 assert_eq!(
15449 counters.cull_frame,
15450 Some(1),
15451 "the report is the frame whose copy answered, not the frame just recorded",
15452 );
15453 assert_eq!(renderer.cull_stats().expect("a readback answered").frame, 1,);
15454
15455 for frame in frames {
15456 frame.release(device.as_ref());
15457 }
15458 renderer.destroy(device.as_ref());
15459 }
15460
15461 /// The frames a culling counter cannot possibly have arrived in.
15462 ///
15463 /// Two: the copy is recorded on one frame and the readback for it requested
15464 /// on the next, so the earliest frame that can poll anything is the third.
15465 /// A device that answers its first poll — the null backend, and every native
15466 /// one — reports there; a browser answers later, which is why this is a
15467 /// floor rather than a latency. See [`crate::cull_stats`].
15468 const CULL_STATS_FLOOR: usize = 2;
15469
15470 /// **A light that takes a shadow tile moves the draw count**, because the
15471 /// shadow pass records one call per bucket per occupied view.
15472 ///
15473 /// The observable a `recorded_draws` comparison alone would miss: a
15474 /// `counters` that counted only the colour pass and the tonemap agrees with
15475 /// nothing here, and one that hard-coded the cascades agrees with the first
15476 /// frame and not the second.
15477 #[test]
15478 fn a_light_that_takes_a_shadow_tile_moves_the_draw_count() {
15479 let (recorder, device, queue) = open();
15480 let mut renderer =
15481 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
15482
15483 let dark = frame(device.as_ref(), &mut renderer, queue);
15484 let without = renderer.counters().draws;
15485 assert_eq!(without, recorded_draws(&recorder) as u64);
15486 dark.release(device.as_ref());
15487
15488 renderer.set_lights(&[shadowable_spot(0.0)]);
15489 recorder.clear();
15490 let lit = frame(device.as_ref(), &mut renderer, queue);
15491 let with = renderer.counters().draws;
15492 assert!(
15493 with > without,
15494 "a shadow-casting light adds a view and therefore draws: {with} against {without}",
15495 );
15496 assert_eq!(
15497 with,
15498 recorded_draws(&recorder) as u64,
15499 "and the counter still matches the stream",
15500 );
15501 lit.finish(device.as_ref(), renderer);
15502 }
15503
15504 /// Opens a null device offering `optional` on top of the mesh path, and
15505 /// asserts it really selected that path.
15506 ///
15507 /// Asked for rather than merely reported, because a device grants what it
15508 /// enabled: leaving mesh shaders out of the optional set opens a device on
15509 /// an indirect tail and tests nothing.
15510 ///
15511 /// The adapter has [`Features::DRAW_INDEX`] too, which a device is granted
15512 /// only where `optional` asks for it — so a test that does not gets the
15513 /// mesh tail's call per bucket.
15514 fn open_mesh_path(recorder: &Recorder, optional: Features) -> (Box<dyn Device>, QueueHandle) {
15515 let caps = crcbl_hal::DeviceCaps {
15516 features: Features::GPU_DRIVEN
15517 | Features::MESH_SHADER
15518 | Features::TASK_SHADER
15519 | Features::DRAW_INDEX,
15520 limits: crcbl_hal::Limits::desktop(),
15521 };
15522 let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15523 let adapter = instance.adapters().remove(0);
15524 assert_eq!(
15525 instance
15526 .adapter_caps(adapter.id)
15527 .expect("the null backend describes its adapter")
15528 .geometry_path(),
15529 GeometryPath::MeshShader,
15530 "a device with mesh shaders selects them, which is the case this is about"
15531 );
15532 let device = instance
15533 .create_device(&DeviceDesc {
15534 label: None,
15535 adapter: adapter.id,
15536 required_features: Features::COMPUTE,
15537 optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER | optional,
15538 compatible_surface: None,
15539 })
15540 .expect("the null backend always opens");
15541 assert_eq!(
15542 device.caps().geometry_path(),
15543 GeometryPath::MeshShader,
15544 "and the opened device still selects it"
15545 );
15546 let queue = device.queue(QueueKind::Graphics).expect("always present");
15547 (device, queue)
15548 }
15549
15550 /// **The four material pages are created with the format their contents
15551 /// call for, and it is only a *colour* that is sRGB.**
15552 ///
15553 /// Topic 44's rung 2 calls this the classic PBR bug and
15554 /// says why it survives review: a base-colour texel and an emissive one are
15555 /// sRGB-encoded *colours*, which is what glTF defines them as, and a normal
15556 /// texel and a packed occlusion-roughness-metallic one are *numbers* — so
15557 /// decoding either of those through the sRGB curve is wrong by a gamma and
15558 /// looks merely like a surface bumpier or shinier than the author drew.
15559 /// Nothing in a frame reports it, no golden comparison can name it, and the
15560 /// four constants sit a few lines apart with the wrong one compiling.
15561 ///
15562 /// So this is the whole guard, and it is three claims rather than one: that
15563 /// each constant is the one it should be, that
15564 /// [`PageKind::format`] — which is what the upload loop actually calls —
15565 /// answers with it, and, the half that would otherwise be a check that
15566 /// cannot fail, that the format each page is *created* with is the format
15567 /// its `ImportedImage` declares. A declaration naming a format the image is
15568 /// not in picks the wrong aspects in a barrier.
15569 #[test]
15570 fn the_page_formats_split_colour_from_number() {
15571 assert_eq!(BASE_COLOR_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15572 assert_eq!(EMISSIVE_PAGE_FORMAT, Format::Rgba8UnormSrgb);
15573 assert_eq!(NORMAL_PAGE_FORMAT, Format::Rgba8Unorm);
15574 assert_eq!(MRO_PAGE_FORMAT, Format::Rgba8Unorm);
15575 // Through the dispatch the upload loop actually calls, rather than the
15576 // constants alone: one loop creates every image now, and a `format` arm
15577 // pointed at the wrong constant is the way that loop gets it wrong.
15578 assert_eq!(PageKind::BaseColor.format(), BASE_COLOR_PAGE_FORMAT);
15579 assert_eq!(PageKind::Normal.format(), NORMAL_PAGE_FORMAT);
15580 assert_eq!(
15581 PageKind::MetallicRoughnessOcclusion.format(),
15582 MRO_PAGE_FORMAT
15583 );
15584 assert_eq!(PageKind::Emissive.format(), EMISSIVE_PAGE_FORMAT);
15585 assert_ne!(
15586 BASE_COLOR_PAGE_FORMAT, NORMAL_PAGE_FORMAT,
15587 "a normal page created sRGB decodes every texel through a gamma it never had"
15588 );
15589 assert_ne!(
15590 EMISSIVE_PAGE_FORMAT, MRO_PAGE_FORMAT,
15591 "a packed roughness page created sRGB shades every surface smoother than authored"
15592 );
15593
15594 let (recorder, device, queue) = open();
15595 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15596 .expect("the forward renderer builds on the null backend");
15597 assert_eq!(
15598 renderer.base_color_page_import().format,
15599 BASE_COLOR_PAGE_FORMAT
15600 );
15601 assert_eq!(renderer.normal_page_import().format, NORMAL_PAGE_FORMAT);
15602 assert_eq!(renderer.mro_page_import().format, MRO_PAGE_FORMAT);
15603 assert_eq!(renderer.emissive_page_import().format, EMISSIVE_PAGE_FORMAT);
15604 // And they really are four images, not one bound four times — which is
15605 // the other way a page could be "linear" and still be sampled through
15606 // the sRGB one.
15607 let created = [
15608 renderer.base_color_page(),
15609 renderer.normal_page(),
15610 renderer.mro_page(),
15611 renderer.emissive_page(),
15612 ];
15613 for (at, page) in created.iter().enumerate() {
15614 for other in &created[at + 1..] {
15615 assert_ne!(page.image, other.image, "two page kinds share one image");
15616 assert_ne!(page.view, other.view, "two page kinds share one view");
15617 }
15618 }
15619 // The labels come off the recorder rather than off the handles, so this
15620 // is evidence about what the device was asked to create.
15621 let images: Vec<String> = recorder
15622 .events()
15623 .into_iter()
15624 .filter_map(|event| match event {
15625 Event::Created {
15626 kind: ObjectKind::Image,
15627 label: Some(label),
15628 } => Some(label),
15629 _ => None,
15630 })
15631 .collect();
15632 for kind in PageKind::ALL {
15633 let page = kind.upload_label();
15634 assert!(
15635 images.iter().any(|label| label == page),
15636 "no image was created for the {page} page, and it is {images:?} that were"
15637 );
15638 }
15639 renderer.destroy(device.as_ref());
15640 }
15641
15642 /// Compare native argument indices from the shipped entry points with the
15643 /// actual renderer layout. A shared fragment buffer must have the same index
15644 /// even when geometry introduces additional resources in another module.
15645 #[test]
15646 fn mesh_pipeline_buffers_match_native_shader_arguments() {
15647 for optional in [Features::TASK_SHADER, Features::empty()] {
15648 let recorder = Recorder::new();
15649 let (device, queue) = open_mesh_path(&recorder, optional);
15650 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15651 .expect("the mesh renderer builds");
15652 let (_, entries) = recorder
15653 .bind_group_layouts_created()
15654 .into_iter()
15655 .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15656 .expect("the actual mesh layout");
15657 let mut buffers: Vec<_> = entries
15658 .iter()
15659 .filter(|entry| {
15660 matches!(
15661 entry.kind,
15662 BindingKind::UniformBuffer { .. } | BindingKind::StorageBuffer { .. }
15663 )
15664 })
15665 .collect();
15666 buffers.sort_by_key(|entry| entry.binding);
15667 assert_eq!(buffers.len(), 20, "the native buffer budget is unchanged");
15668 for (source, shader, names) in [
15669 (
15670 include_str!("../../crcbl-shaders/shaders/mesh.slang"),
15671 &MESH,
15672 &["fragmentMain"][..],
15673 ),
15674 (
15675 include_str!("../../crcbl-shaders/shaders/mesh_cluster.slang"),
15676 &MESH_CLUSTER,
15677 &["meshMain", "taskMain", "amplifiedMeshMain"][..],
15678 ),
15679 ] {
15680 let declarations: Vec<_> = source.lines().collect();
15681 let bindings: Vec<_> = declarations
15682 .windows(2)
15683 .filter_map(|lines| {
15684 let binding = lines[0]
15685 .trim()
15686 .strip_prefix("[[vk::binding(")?
15687 .split(',')
15688 .next()?
15689 .parse::<u32>()
15690 .ok()?;
15691 // The name is the last word before the D3D12 register.
15692 let name = lines[1]
15693 .split(" D3D12_REGISTER(")
15694 .next()?
15695 .split_whitespace()
15696 .last()?
15697 .trim_end_matches(';');
15698 Some((name, binding))
15699 })
15700 .collect();
15701 for name in names {
15702 let signature = shader
15703 .msl()
15704 .expect("committed native shader")
15705 .lines()
15706 .find(|line| line.starts_with("[[") && line.contains(&format!(" {name}(")))
15707 .expect("native entry signature");
15708 let mut checked = 0;
15709 for argument in signature.split(", ") {
15710 let Some((declaration, tail)) = argument.split_once(" [[buffer(") else {
15711 continue;
15712 };
15713 let native: usize = tail.split(')').next().unwrap().parse().unwrap();
15714 let variable = declaration.split_whitespace().last().unwrap();
15715 let variable = variable.rsplit_once('_').map_or(variable, |(base, _)| base);
15716 let binding = bindings
15717 .iter()
15718 .find(|(candidate, _)| *candidate == variable)
15719 .unwrap_or_else(|| panic!("unknown {name} buffer {variable}"))
15720 .1;
15721 let expected = buffers
15722 .iter()
15723 .position(|entry| entry.binding == binding)
15724 .expect("shader binding exists in the renderer layout");
15725 assert_eq!(
15726 native, expected,
15727 "{name}: {variable}, logical binding {binding}, native shader vs global layout"
15728 );
15729 checked += 1;
15730 }
15731 assert!(
15732 checked >= 10,
15733 "entry parsing must cover the complete buffer interface"
15734 );
15735 }
15736 }
15737 renderer.destroy(device.as_ref());
15738 }
15739 }
15740
15741 #[test]
15742 fn the_mesh_layout_declares_the_same_bindings_with_and_without_a_task_stage() {
15743 let mut declared: Vec<Vec<(u32, BindingKind)>> = Vec::new();
15744 for optional in [Features::TASK_SHADER, Features::empty()] {
15745 let recorder = Recorder::new();
15746 let (device, queue) = open_mesh_path(&recorder, optional);
15747 let renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15748 .expect("the forward renderer builds on both device shapes");
15749 assert_eq!(
15750 renderer.culls_clusters(),
15751 optional.contains(Features::TASK_SHADER),
15752 "the two arms must actually differ, or this compares a device with itself"
15753 );
15754 let (label, entries) = recorder
15755 .bind_group_layouts_created()
15756 .into_iter()
15757 .find(|(label, _)| label.as_deref() == Some(MESH_LAYOUT_LABEL))
15758 .expect("the mesh pass declares its layout by name");
15759 assert_eq!(label.as_deref(), Some(MESH_LAYOUT_LABEL));
15760 declared.push(
15761 entries
15762 .iter()
15763 .map(|entry| (entry.binding, entry.kind))
15764 .collect(),
15765 );
15766 }
15767
15768 let [amplified, plain] = declared
15769 .try_into()
15770 .unwrap_or_else(|_| unreachable!("two arms were run"));
15771 assert_eq!(
15772 amplified, plain,
15773 "the mesh layout's bindings changed with the task stage, which moves every Metal \
15774 argument-table index above the difference"
15775 );
15776 // These mesh declarations remain present without a task stage.
15777 for binding in [
15778 CLUSTER_CULL_BINDING,
15779 CLUSTER_CULL_STATS_BINDING,
15780 CLUSTER_SELECT_BINDING,
15781 CLUSTER_SELECTION_BINDING,
15782 CLUSTER_GROUP_STATE_BINDING,
15783 ] {
15784 assert!(
15785 plain.iter().any(|(number, _)| *number == binding),
15786 "binding {binding} is declared by mesh_cluster.slang and must be in the layout"
15787 );
15788 }
15789 // Logical gaps consume no native slots. The complete shader union must
15790 // remain sorted, and every mesh-only buffer follows the fragment prefix.
15791 let numbers: Vec<u32> = plain.iter().map(|(binding, _)| *binding).collect();
15792 let expected: Vec<u32> = (0..=8).chain(15..=16).chain(20..=40).collect();
15793 assert_eq!(
15794 numbers, expected,
15795 "the complete sparse shader binding union"
15796 );
15797 }
15798
15799 /// **`Features::TASK_SHADER` is what decides whether §3.5's per-cluster cull
15800 /// is built, and a device without it still draws.**
15801 ///
15802 /// The two capabilities are separate, and the adapter above offers both — so
15803 /// asking for one and not the other is a device state a real driver has and
15804 /// this can reach. Neither arm is a skip:
15805 ///
15806 /// * With the task stage, the renderer builds the amplification stage and
15807 /// [`ForwardRenderer::culls_clusters`] says so. The null backend refuses a
15808 /// task stage on a device without the flag, so an arm that computed this
15809 /// wrongly would fail to build rather than pass quietly. It records one
15810 /// flat call per partition — [`flat_dispatch_calls`].
15811 /// * Without it, the renderer builds `meshMain` — the un-amplified entry
15812 /// point — and draws every cluster of every surviving instance, one
15813 /// indirect dispatch per bucket reading its own extents.
15814 #[test]
15815 fn the_task_stage_is_built_only_where_the_device_has_one() {
15816 use crcbl_hal::null::Command;
15817
15818 for (optional, expected) in [(Features::TASK_SHADER, true), (Features::empty(), false)] {
15819 let recorder = Recorder::new();
15820 let (device, queue) = open_mesh_path(&recorder, optional);
15821 let mut renderer = ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
15822 .expect("the forward renderer builds on both device shapes");
15823 assert_eq!(
15824 device.caps().supports(Features::TASK_SHADER),
15825 expected,
15826 "the device must actually differ between the arms, or both test the same thing"
15827 );
15828 assert_eq!(
15829 renderer.culls_clusters(),
15830 expected,
15831 "the amplification stage is built exactly where the device has one"
15832 );
15833 assert_eq!(
15834 renderer.geometry_path(),
15835 GeometryPath::MeshShader,
15836 "both arms are the mesh path; only the stage in front of it differs"
15837 );
15838
15839 let frame = frame(device.as_ref(), &mut renderer, queue);
15840 // After the frame, because the buffer named is the slot the frame
15841 // rotated to — asking before it names the previous slot's ring
15842 // entry and the comparison is against a buffer nothing drew from.
15843 let expected = if expected {
15844 flat_dispatch_calls(&renderer, crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED).0
15845 } else {
15846 mesh_dispatch_calls(&renderer)
15847 };
15848
15849 let dispatched: Vec<DrawIndirect> = commands_in_pass(&recorder, "forward")
15850 .into_iter()
15851 .filter_map(|command| match command {
15852 Command::DrawMeshTasksIndirect(draw) => Some(draw),
15853 _ => None,
15854 })
15855 .collect();
15856 assert_eq!(
15857 dispatched, expected,
15858 "a flat call per partition behind the stage, and a dispatch per bucket reading \
15859 its own extents without it"
15860 );
15861
15862 frame.finish(device.as_ref(), renderer);
15863 }
15864 }
15865
15866 /// The flat calls a pass splitting the bucket table by the material-mode
15867 /// bits `key` records behind a task stage, in region 0, in partition order
15868 /// — one per segment the table holds buckets of — and each segment's first
15869 /// bucket, whose block the call binds.
15870 ///
15871 /// The offsets from [`crcbl_shaders::draw_gen::flat_args_word`] over the
15872 /// camera generator's own region count rather than from
15873 /// `DrawGen::flat_args_offset`, for [`mesh_dispatch_calls`]' reason.
15874 fn flat_dispatch_calls(renderer: &ForwardRenderer, key: u32) -> (Vec<DrawIndirect>, Vec<u32>) {
15875 let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15876 let buckets = u32::try_from(renderer.bucket_constants.len()).expect("a few buckets");
15877 let regions = renderer.primary.draws.mode().regions();
15878 let segments = crcbl_shaders::draw_gen::flat_segments(&renderer.bucket_modes);
15879 let values: Vec<u32> = if key == crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED {
15880 vec![0, key]
15881 } else {
15882 DEPTH_MODES.to_vec()
15883 };
15884 values
15885 .into_iter()
15886 .filter(|value| {
15887 renderer
15888 .bucket_modes
15889 .iter()
15890 .any(|mode| mode & key == *value)
15891 })
15892 .map(|value| {
15893 let segment = crcbl_shaders::draw_gen::flat_segment(key, value)
15894 .expect("a split every pass makes");
15895 (
15896 DrawIndirect {
15897 args: renderer.primary.draws.mesh_args(renderer.frame),
15898 offset: u64::from(crcbl_shaders::draw_gen::flat_args_word(
15899 buckets, regions, 0, segment, 0,
15900 )) * 4,
15901 draw_count: 1,
15902 stride,
15903 },
15904 segments[segment as usize].0,
15905 )
15906 })
15907 .unzip()
15908 }
15909
15910 /// The [`DrawIndirect`] the mesh path must record for each bucket, in bucket
15911 /// order.
15912 ///
15913 /// Built from the buffer the draw-argument pass writes and the stride the
15914 /// APIs fixed, so a test comparing against it is asserting that the call
15915 /// reads *this frame's* arguments at *this bucket's* offset — the two ways
15916 /// an indirect dispatch goes wrong while still dispatching something.
15917 ///
15918 /// **The offsets are multiplied out here rather than asked of
15919 /// [`DrawGen::mesh_args_offset`]**, which is the difference between a
15920 /// comparison and a tautology: an offset function that returned zero for
15921 /// every bucket would agree with itself, and three calls onto one structure
15922 /// is a frame that draws one bucket's geometry three times.
15923 fn mesh_dispatch_calls(renderer: &ForwardRenderer) -> Vec<DrawIndirect> {
15924 let stride = crcbl_shaders::draw_gen::MESH_ARGS_SIZE as u32;
15925 // The extents share a buffer with the one draw count per bucket that
15926 // precedes them, so every offset is that far in. Written out from the
15927 // bucket count here rather than taken from `DrawGen::mesh_args_offset`,
15928 // for the reason above: a base of zero is exactly the mistake this
15929 // comparison exists to catch, and it would agree with itself.
15930 let counts_bytes = renderer.bucket_constants.len() as u64 * 4;
15931 (0..renderer.bucket_constants.len())
15932 .map(|bucket| DrawIndirect {
15933 args: renderer.primary.draws.mesh_args(renderer.frame),
15934 offset: counts_bytes + bucket as u64 * u64::from(stride),
15935 draw_count: 1,
15936 stride,
15937 })
15938 .collect()
15939 }
15940
15941 /// **A device selecting [`GeometryPath::MeshShader`] draws through a mesh
15942 /// pipeline, and records no indirect draw and no index-buffer bind at all.**
15943 ///
15944 /// The three halves are one claim. That it dispatched says the path is
15945 /// wired; that it recorded *no* `DrawIndexedIndirect` of either kind says it
15946 /// did not quietly fall through to a tail that draws the same picture; and
15947 /// that it bound no index buffer says the geometry really came out of the
15948 /// cluster records rather than out of the index pool. Until 2026-08 this
15949 /// device degraded and logged that it had, which is exactly the shape —
15950 /// "not implemented" arriving as a passing frame — the three together rule
15951 /// out.
15952 ///
15953 /// **The extents are not here to be checked, and that is the point.** They
15954 /// are three words the draw-argument pass writes, so what this can pin is
15955 /// the call reading *this* bucket's structure out of *this* frame's buffer
15956 /// — and the CPU-side half of the x extent, the per-bucket cluster table
15957 /// the host uploaded, which the null backend keeps the bytes of. What the
15958 /// GPU then makes of it needs a GPU: `crcbl-vk`'s
15959 /// `the_mesh_dispatch_extent_is_the_culled_instance_count` reads the
15960 /// arguments back.
15961 #[test]
15962 fn a_mesh_shader_device_draws_through_a_mesh_pipeline() {
15963 use crcbl_hal::null::Command;
15964
15965 let recorder = Recorder::new();
15966 let caps = crcbl_hal::DeviceCaps {
15967 features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15968 limits: crcbl_hal::Limits::desktop(),
15969 };
15970 let instance = NullInstance::new(caps).with_recorder(recorder.clone());
15971 let adapter = instance.adapters().remove(0);
15972 assert_eq!(
15973 instance
15974 .adapter_caps(adapter.id)
15975 .expect("the null backend describes its adapter")
15976 .geometry_path(),
15977 GeometryPath::MeshShader,
15978 "a device with mesh shaders selects them, which is the case this is about"
15979 );
15980 let device = instance
15981 .create_device(&DeviceDesc {
15982 label: None,
15983 adapter: adapter.id,
15984 required_features: Features::COMPUTE,
15985 // Asked for, because a device reports what it enabled: leaving
15986 // mesh shaders out of the optional set would open a device that
15987 // selects an indirect path outright and test nothing.
15988 optional_features: Features::GPU_DRIVEN | Features::MESH_SHADER,
15989 compatible_surface: None,
15990 })
15991 .expect("the null backend always opens");
15992 assert_eq!(
15993 device.caps().geometry_path(),
15994 GeometryPath::MeshShader,
15995 "and the opened device still selects it"
15996 );
15997 let queue = device.queue(QueueKind::Graphics).expect("always present");
15998 let mut renderer =
15999 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16000 assert_eq!(
16001 renderer.geometry_path(),
16002 GeometryPath::MeshShader,
16003 "the renderer must have *built* the mesh path, not merely been offered it"
16004 );
16005 let frame = frame(device.as_ref(), &mut renderer, queue);
16006 let expected = mesh_dispatch_calls(&renderer);
16007 // The table is written once at build, into a host-visible buffer the
16008 // null backend keeps the bytes of — so it is readable whether or not a
16009 // shader ever ran. It shares that buffer with the four other tables the
16010 // draw-argument pass reads, so the region has to be cut out at the
16011 // offset the renderer told the shader about rather than at zero.
16012 let table_bytes = recorder
16013 .buffer_bytes(renderer.primary.draws.tables())
16014 .expect("the table buffer is one of this recorder's buffers");
16015 let clusters_at = renderer.primary.draws.table_offsets().bucket_clusters_at as usize * 4;
16016 let clusters: Vec<u32> = table_bytes[clusters_at..]
16017 .as_chunks::<4>()
16018 .0
16019 .iter()
16020 .take(renderer.bucket_constants.len())
16021 .map(|word| u32::from_le_bytes(*word))
16022 .collect();
16023
16024 let mut dispatched = Vec::new();
16025 let mut index_binds = 0;
16026 for command in commands_in_pass(&recorder, "forward") {
16027 match command {
16028 Command::DrawMeshTasksIndirect(draw) => dispatched.push(draw),
16029 Command::DrawMeshTasks { .. } => panic!(
16030 "the mesh path recorded a CPU-sized dispatch, which is the extent \
16031 the instance cull is supposed to have taken over"
16032 ),
16033 Command::DrawIndexedIndirectCount(_) | Command::DrawIndexedIndirect(_) => {
16034 panic!(
16035 "the mesh path recorded an indirect draw, which is the silent \
16036 fall-through this test exists to rule out"
16037 )
16038 }
16039 Command::BindIndexBuffer { .. } => index_binds += 1,
16040 _ => {}
16041 }
16042 }
16043 assert_eq!(
16044 dispatched, expected,
16045 "one indirect dispatch per bucket, each reading its own argument structure \
16046 out of this frame's buffer"
16047 );
16048 assert_eq!(
16049 clusters.len(),
16050 renderer.bucket_constants.len(),
16051 "one x extent per bucket: {clusters:?}"
16052 );
16053 assert!(
16054 clusters.iter().all(|&count| count > 0),
16055 "a bucket with no clusters dispatches nothing, whatever the arguments say: \
16056 {clusters:?}"
16057 );
16058 // **The x extents are not all the same number**, which is what makes
16059 // the table a statement about each bucket's own mesh. Two
16060 // single-cluster meshes would let a table hard-coded to one cluster
16061 // pass; the open box is five, one per face.
16062 assert_eq!(
16063 clusters[DEMO_OPEN_BOX] as usize,
16064 crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
16065 "the open box dispatches one workgroup per face, and that is the only \
16066 resident whose cluster count is not one: {clusters:?}"
16067 );
16068 assert_eq!(
16069 index_binds, 0,
16070 "a mesh pipeline has no index buffer; binding one would mean the geometry \
16071 came from the index pool after all"
16072 );
16073
16074 frame.finish(device.as_ref(), renderer);
16075 }
16076
16077 /// **The cull pass is told the camera the frame is drawn with**, and how
16078 /// many array elements to walk.
16079 ///
16080 /// Both halves fail silently: a frustum from a different aspect ratio culls
16081 /// geometry that is on screen, and an instance count short of the pool's
16082 /// high-water mark stops testing the instances above a freed slot. Neither
16083 /// is visible in a picture until something disappears from an edge.
16084 #[test]
16085 fn the_cull_pass_gets_this_frame_s_camera_and_every_occupied_slot() {
16086 let (recorder, device, queue) = open();
16087 let mut renderer =
16088 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16089 // The cube first and the pyramid above it, because the second half of
16090 // this test frees the lower slot and asks what the walk still covers.
16091 let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16092 place_demo(
16093 &mut renderer,
16094 DEMO_PYRAMID,
16095 DEMO_UNTINTED,
16096 Mat4::from_translation(Vec3::X),
16097 );
16098
16099 let camera = Camera {
16100 eye: Vec3::new(1.6, 1.2, 2.2),
16101 ..Camera::default()
16102 };
16103 let extent = (256u32, 192u32);
16104 renderer
16105 .begin_frame(
16106 device.as_ref(),
16107 &camera,
16108 &DirectionalLight::default(),
16109 extent,
16110 )
16111 .expect("write");
16112
16113 let aspect = extent.0 as f32 / extent.1 as f32;
16114 let expected = crate::cull::Frustum::from_view_projection(camera.view_projection(aspect));
16115 let written = recorder
16116 .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16117 .expect("this frame's cull parameters are live");
16118 assert_eq!(
16119 &written[..crcbl_shaders::cull::PARAMS_SIZE],
16120 &crcbl_shaders::cull::Params {
16121 planes: expected.planes.map(|plane| plane.to_array()),
16122 instance_count: 2,
16123 capacity: scene::Capacities::default().instances,
16124 hidden_view: ViewId::PRIMARY.hidden_bit(),
16125 ..crcbl_shaders::cull::Params::default()
16126 }
16127 .to_bytes()[..],
16128 "the cull block must carry this frame's own frustum, the pool's whole \
16129 occupied range, and the visible list's capacity"
16130 );
16131
16132 // And the high-water mark is what is written, not the live count: remove
16133 // the cube and the pyramid above it still has to be tested.
16134 renderer.remove_instance(cube);
16135 renderer
16136 .begin_frame(
16137 device.as_ref(),
16138 &camera,
16139 &DirectionalLight::default(),
16140 extent,
16141 )
16142 .expect("write");
16143 let written = recorder
16144 .buffer_bytes(renderer.primary.draws.cull_params(renderer.frame))
16145 .expect("live");
16146 assert_eq!(
16147 u32::from_le_bytes(written[96..100].try_into().expect("four bytes")),
16148 2,
16149 "one live instance, two occupied slots — a walk of one would never \
16150 reach the pyramid"
16151 );
16152
16153 renderer.destroy(device.as_ref());
16154 recorder.assert_valid();
16155 }
16156
16157 /// **Every counter both compute passes add to is zeroed by a pass of its
16158 /// own, before either of them runs.**
16159 ///
16160 /// The two shaders only ever increment, so a counter carrying the previous
16161 /// frame's total makes a bucket's argument structure claim more instances
16162 /// than its run holds — which draws whatever the run's stale tail happens to
16163 /// name.
16164 ///
16165 /// # This once read the bytes back, and no longer can
16166 ///
16167 /// It used to poison every counter with `0xAB` and assert `begin_frame`
16168 /// had written zeroes over them — the poison being the whole test, because
16169 /// the null backend runs no shader and a counter nothing wrote reads as the
16170 /// zero it was created with. The counters are device-local now, so nothing
16171 /// on the host writes them and [`Recorder::buffer_bytes`] holds nothing for
16172 /// them: the zero is a dispatch inside the frame, and a backend that runs no
16173 /// shader cannot observe it at all.
16174 ///
16175 /// So the poison moved to where a shader actually runs — `crcbl-vk`'s
16176 /// `draw_gen` end-to-end fills them with a sentinel and reads back the
16177 /// generated arguments — and what is checkable *here* is the schedule: that
16178 /// the frame contains the clearing pass, that it writes exactly those
16179 /// buffers, and that the graph orders the two accumulating passes after it.
16180 /// Each of the counts below goes red if a buffer is dropped from the
16181 /// clearing pass, and the pass list goes red if the pass leaves the frame.
16182 #[test]
16183 fn every_frame_starts_from_zeroed_counters() {
16184 let (recorder, device, queue) = open();
16185 let mut renderer =
16186 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16187 place_cube(&mut renderer, Mat4::IDENTITY);
16188 let imported = swapchain_image(device.as_ref());
16189 // Twice round the ring, because a slot cleared only on its first use is
16190 // exactly the failure this is about.
16191 for round in 0..FRAMES_IN_FLIGHT * 2 {
16192 renderer
16193 .begin_frame(
16194 device.as_ref(),
16195 &Camera::default(),
16196 &DirectionalLight::default(),
16197 (64, 48),
16198 )
16199 .expect("write");
16200 let mut graph = crate::RenderGraph::new(queue);
16201 let target = graph.import_image("target", imported);
16202 let pool = crate::TransientPool::new();
16203 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16204 let compiled = graph.compile(&pool).expect("a legal frame");
16205
16206 let clear = &compiled.passes()[0];
16207 assert_eq!(
16208 clear.label(),
16209 "clear-counters",
16210 "round {round}: the zero has to be written before anything adds to it"
16211 );
16212 let barriers = &clear.barriers().buffers;
16213 assert_eq!(
16214 barriers.len(),
16215 3,
16216 "round {round}: the survivor count, the draw arguments, and the buffer \
16217 holding both the draw counts and the mesh-dispatch arguments, and \
16218 nothing else: {barriers:?}"
16219 );
16220 assert!(
16221 barriers
16222 .iter()
16223 .all(|barrier| barrier.to == ResourceState::ShaderReadWrite),
16224 "round {round}: every one of them is written by this pass: {barriers:?}"
16225 );
16226 // The ones the frame leaves as indirect arguments are the two a
16227 // driver reads; the survivor count rests in a shader read. That
16228 // split is what names them without a handle to compare.
16229 assert_eq!(
16230 barriers
16231 .iter()
16232 .filter(|barrier| barrier.from == ResourceState::IndirectArgument)
16233 .count(),
16234 2,
16235 "round {round}: out of the state a draw read them in: {barriers:?}"
16236 );
16237
16238 let after = |label: &str| {
16239 compiled
16240 .passes()
16241 .iter()
16242 .find(|pass| pass.label() == label)
16243 .unwrap_or_else(|| panic!("round {round}: no `{label}` pass"))
16244 .barriers()
16245 .buffers
16246 .iter()
16247 .filter(|barrier| {
16248 barrier.from == ResourceState::ShaderReadWrite
16249 && barrier.to == ResourceState::ShaderReadWrite
16250 })
16251 .count()
16252 };
16253 assert_eq!(
16254 after("cull"),
16255 1,
16256 "round {round}: the survivor count reaches the cull pass's atomic behind a \
16257 barrier on the write that zeroed it"
16258 );
16259 assert_eq!(
16260 after("draw-args"),
16261 4,
16262 "round {round}: and so do the draw arguments and the buffer holding the \
16263 draw counts beside the mesh-dispatch arguments — plus the survivor list, \
16264 which the cull pass has just written and this pass reads through the same \
16265 descriptor it scatters the runs into, and `docs/notes/rendering.md`'s \
16266 hysteresis state, which the clearing pass does *not* zero and which is \
16267 behind the same kind of barrier for the opposite reason: it is the one \
16268 buffer here carrying a value out of the previous frame, so what it needs \
16269 ordering against is that frame rather than this one's clear"
16270 );
16271 // **And the prefix sum and the scatter behind barriers of their own**,
16272 // on every buffer the stage before them wrote. This is what orders
16273 // them on a device that runs undeclared commands in any order — see
16274 // `DrawGen::add_passes` — and what three dispatches in one pass
16275 // silently lacked.
16276 for label in ["draw-starts", "draw-scatter"] {
16277 assert_eq!(
16278 after(label),
16279 4,
16280 "round {round}: `{label}` reads what the pass before it wrote, so every \
16281 buffer they share is ordered behind a barrier"
16282 );
16283 }
16284
16285 // The compiled graph borrows the renderer's pass bodies, so it has
16286 // to go before the next frame borrows the renderer again.
16287 drop(compiled);
16288 }
16289 renderer.destroy(device.as_ref());
16290 device.destroy_image_view(imported.view);
16291 device.destroy_image(imported.image);
16292 recorder.assert_valid();
16293 }
16294
16295 /// **A frame with no instances leaves out every generator's cull and
16296 /// scatter passes**, and keeps the clear and the two stages that write each
16297 /// bucket's arguments.
16298 ///
16299 /// An empty pass is not a harmless no-op on Metal: the backend opens an
16300 /// encoder for every graph pass and strict validation rejects ending one
16301 /// with no work — see `DrawGen::add_passes`. Each count below goes red if
16302 /// an empty pass comes back, or if a pass a zero-draw frame needs drops out.
16303 #[test]
16304 fn a_frame_with_no_instances_omits_the_empty_draw_generation_passes() {
16305 let (recorder, device, queue) = open();
16306 let mut renderer =
16307 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16308 renderer
16309 .begin_frame(
16310 device.as_ref(),
16311 &Camera::default(),
16312 &DirectionalLight::default(),
16313 (64, 48),
16314 )
16315 .expect("write");
16316 let imported = swapchain_image(device.as_ref());
16317 let mut graph = crate::RenderGraph::new(queue);
16318 let target = graph.import_image("target", imported);
16319 let pool = crate::TransientPool::new();
16320 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16321 let compiled = graph.compile(&pool).expect("a legal frame");
16322
16323 let count = |label: &str| {
16324 compiled
16325 .passes()
16326 .iter()
16327 .filter(|pass| pass.label() == label)
16328 .count()
16329 };
16330 // The camera's generator and one per shadow cascade.
16331 let generators = 1 + shadow::CASCADES;
16332 for label in ["clear-counters", "draw-args", "draw-starts"] {
16333 assert_eq!(
16334 count(label),
16335 generators,
16336 "`{label}` still has work with nothing to draw: the clear erases the \
16337 previous frame's counts and the argument stages write zero draws"
16338 );
16339 }
16340 for label in ["cull", "draw-scatter"] {
16341 assert_eq!(
16342 count(label),
16343 0,
16344 "`{label}` has no workgroups to dispatch with no instances"
16345 );
16346 }
16347
16348 drop(compiled);
16349 renderer.destroy(device.as_ref());
16350 device.destroy_image_view(imported.view);
16351 device.destroy_image(imported.image);
16352 recorder.assert_valid();
16353 }
16354
16355 /// **The graph transitions the generated arguments into
16356 /// [`ResourceState::IndirectArgument`] before the draws read them**, and the
16357 /// runs into a shader read.
16358 ///
16359 /// The seam calls this the single most important barrier in a GPU-driven
16360 /// frame and says its absence produces "sometimes nothing draws" — which is
16361 /// exactly the failure a golden image on one driver would not catch. It is
16362 /// asserted on the compiled graph, which is pure and needs no device.
16363 #[test]
16364 fn the_graph_barriers_the_arguments_into_place_before_the_draws() {
16365 let _blurs = ssao_blur_switch();
16366 let (recorder, device, queue) = open();
16367 let mut renderer =
16368 ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb).expect("built");
16369 place_cube(&mut renderer, Mat4::IDENTITY);
16370 renderer
16371 .begin_frame(
16372 device.as_ref(),
16373 &Camera::default(),
16374 &DirectionalLight::default(),
16375 (64, 48),
16376 )
16377 .expect("write");
16378
16379 let imported = swapchain_image(device.as_ref());
16380 let mut graph = crate::RenderGraph::new(queue);
16381 let target = graph.import_image("target", imported);
16382 let pool = crate::TransientPool::new();
16383 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16384 let compiled = graph.compile(&pool).expect("a legal frame");
16385
16386 let passes: Vec<String> = compiled
16387 .passes()
16388 .iter()
16389 .map(|pass| pass.label().to_string())
16390 .collect();
16391 // The camera's five compute passes and topic 18's clustering dispatch,
16392 // then five per shadow cascade, then the depth-only pass they feed and
16393 // the colour pass that samples it.
16394 //
16395 // **The clustering pass is after the camera's clearing dispatch**, and
16396 // that is the ordering the overflow counter depends on: the clearing
16397 // pass zeroes the statistics word this one adds to, and both declare
16398 // the same buffer, so the graph is what puts the barrier between them.
16399 let mut expected: Vec<String> = Vec::new();
16400 for cascade in 0..=shadow::CASCADES {
16401 expected.extend(
16402 [
16403 "clear-counters",
16404 "cull",
16405 "draw-args",
16406 "draw-starts",
16407 "draw-scatter",
16408 ]
16409 .into_iter()
16410 .map(str::to_string),
16411 );
16412 if cascade == 0 {
16413 expected.push("light-cluster".to_string());
16414 }
16415 }
16416 // And the culling-statistics copy **last**, after every pass that adds
16417 // to the buffer it reads — the cull dispatch, the clustering pass and
16418 // the amplification stage inside the colour pass.
16419 expected.extend(
16420 [
16421 "shadow",
16422 "depth-prepass",
16423 "ssao",
16424 "ssao-blur",
16425 // The reconstruction that ends the occlusion chain, between the
16426 // blur it reads and the pass that binds what it wrote — see
16427 // [`crate::ssao`]'s header on why the first two run smaller than
16428 // the frame and this one does not.
16429 "ssao-upsample",
16430 "forward",
16431 // The pyramid the march climbs, between the pass that wrote
16432 // level 0 and the pass that reads the chain. Two levels at this
16433 // extent, written out for the reason `crate::bloom`'s chain is
16434 // in the toggle test below: a table generated from
16435 // `crate::hiz::levels_for` could not fail.
16436 "hiz-1",
16437 "hiz-2",
16438 "ssr",
16439 "ssr-blur",
16440 "tonemap",
16441 // The resolve `RenderEffects::DEFAULT_STACK` carries, which is
16442 // CMAA2's three rather than FXAA's one —
16443 // `each_effect_toggle_removes_exactly_the_passes_it_owns` is
16444 // where the swap between the two tiers is pinned.
16445 "cmaa2-edges",
16446 "cmaa2-shapes",
16447 "cmaa2-apply",
16448 "cull-stats-readback",
16449 ]
16450 .into_iter()
16451 .map(str::to_string),
16452 );
16453 assert_eq!(
16454 passes, expected,
16455 "each cull's five compute passes come first, and in that order"
16456 );
16457
16458 // **The depth prepass, not the colour pass**, and that is what says the
16459 // prepass really is the first thing to draw from the camera's cull: it is
16460 // where the draw buffers leave the compute pass's writes. The colour pass
16461 // below then needs none of these, because they are already in the state it
16462 // wants — which is the assertion after it.
16463 let prepass = compiled
16464 .passes()
16465 .iter()
16466 .find(|pass| pass.label() == "depth-prepass")
16467 .expect("the pass list above");
16468 let into_indirect = prepass
16469 .barriers()
16470 .buffers
16471 .iter()
16472 .filter(|barrier| barrier.to == ResourceState::IndirectArgument)
16473 .count();
16474 assert_eq!(
16475 into_indirect,
16476 2,
16477 "the arguments and the count, out of the compute pass's writes and into \
16478 the state a draw reads them in: {:?}",
16479 prepass.barriers().buffers
16480 );
16481 assert!(
16482 prepass.barriers().buffers.iter().any(|barrier| {
16483 barrier.from == ResourceState::ShaderReadWrite
16484 && barrier.to == ResourceState::ShaderRead
16485 }),
16486 "and the runs, which the vertex stage reads: {:?}",
16487 prepass.barriers().buffers
16488 );
16489
16490 let forward = compiled
16491 .passes()
16492 .iter()
16493 .find(|pass| pass.label() == "forward")
16494 .expect("the pass list above");
16495 assert!(
16496 forward
16497 .barriers()
16498 .buffers
16499 .iter()
16500 .all(|barrier| barrier.to != ResourceState::IndirectArgument),
16501 "the prepass draws from the same arguments, so the colour pass finds them \
16502 already in the state it wants — a barrier here would mean something between \
16503 the two put them back: {:?}",
16504 forward.barriers().buffers
16505 );
16506 // What the colour pass *does* still have to be given: the froxel grid,
16507 // which no earlier pass reads.
16508 assert!(
16509 forward.barriers().buffers.iter().any(|barrier| {
16510 barrier.from == ResourceState::ShaderReadWrite
16511 && barrier.to == ResourceState::ShaderRead
16512 }),
16513 "and the froxel grid, which its fragment stage reads: {:?}",
16514 forward.barriers().buffers
16515 );
16516
16517 let draw_args = compiled
16518 .passes()
16519 .iter()
16520 .find(|pass| pass.label() == "draw-args")
16521 .expect("the pass list above");
16522 assert!(
16523 draw_args.barriers().buffers.iter().any(|barrier| {
16524 barrier.from == ResourceState::ShaderReadWrite
16525 && barrier.to == ResourceState::ShaderRead
16526 }),
16527 "and the visible list is ordered after the cull pass wrote it: {:?}",
16528 draw_args.barriers().buffers
16529 );
16530
16531 // The compiled graph borrows the renderer's pass bodies, so it has to go
16532 // before the renderer does.
16533 drop(compiled);
16534 renderer.destroy(device.as_ref());
16535 device.destroy_image_view(imported.view);
16536 device.destroy_image(imported.image);
16537 recorder.assert_valid();
16538 }
16539
16540 /// One more frame than the uniform ring is deep, so at least one lap both
16541 /// reuses a slot and follows a lap that already sampled the atlas.
16542 const SHADOW_LAPS: usize = FRAMES_IN_FLIGHT + 1;
16543
16544 /// **Every frame's first barrier on the shadow atlas names what the previous
16545 /// frame left it in**, and the same for its placeholder.
16546 ///
16547 /// # Why this cannot be read off one frame
16548 ///
16549 /// The atlas is neither a transient nor a swapchain image. The pool never
16550 /// hands one out and has no description to size it from, and no acquire
16551 /// semaphore sits between one frame's use of it and the next — so
16552 /// [`ForwardRenderer::add_passes`] *declares* it, and the declaration is what
16553 /// makes the transition true.
16554 ///
16555 /// What it declares is [`imported_state`], the pool's record of what the
16556 /// last graph to *execute* left the image in, so [`InitialClaim::Tracked`]
16557 /// can only ever find the two agreeing for this one import — deliberately,
16558 /// because a declaration and an audit reading one value cannot drift apart
16559 /// the way a renderer-held copy of it could. The audit still has teeth
16560 /// elsewhere in this frame: `ssao-placeholder` and `probes` declare a
16561 /// constant, and `the_guard_still_catches_an_engine_import_that_lies` is
16562 /// what shows it fires on those.
16563 ///
16564 /// So neither mechanism says anything about the barriers on either side of
16565 /// the declaration — whether the frame that ran actually reached the state
16566 /// the ledger now claims, and whether the next frame's first barrier comes
16567 /// out of it — which is what the stream below is for.
16568 ///
16569 /// Declaring [`ResourceState::Undefined`] on a frame after the first is the
16570 /// failure this catches. It expands to `srcStageMask = NONE,
16571 /// srcAccessMask = NONE` (`crcbl_vk::conv::state_masks`), so the transition
16572 /// into the depth-only pass's attachment state orders against nothing — while
16573 /// the previous frame's colour pass is still sampling the very same image.
16574 /// Vulkan reports it as `SYNC-HAZARD-WRITE-AFTER-READ` with
16575 /// `read_barriers: 0`; every other backend resolves it however the driver
16576 /// likes.
16577 ///
16578 /// # Why the command stream is the observable
16579 ///
16580 /// Nothing above the seam can see a wrong declaration: the frame still
16581 /// renders, the golden still matches, and no state is ever read back. So this
16582 /// replays the recorded stream with a tracker, which is the same check a
16583 /// validation layer performs and needs no GPU at all — the shape
16584 /// `crcbl::screenshot`'s
16585 /// `every_readback_barrier_declares_the_state_the_image_is_actually_in` uses.
16586 /// One difference: `Undefined` is **not** waved through after the first
16587 /// touch. It is true for a swapchain image because the acquire's semaphore
16588 /// makes it true, and there is no such semaphore here.
16589 #[test]
16590 fn the_shadow_atlas_enters_each_frame_in_the_state_the_last_one_left_it() {
16591 use crcbl_hal::null::Command;
16592
16593 let (recorder, device, queue) = open();
16594 let device = device.as_ref();
16595 let mut renderer =
16596 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16597 let atlas = renderer.shadow_atlas();
16598 let placeholder = renderer.shadow_placeholder;
16599 let mut pool = crate::TransientPool::new();
16600 let imported = swapchain_image(device);
16601 let mut recorded = Vec::with_capacity(SHADOW_LAPS);
16602
16603 for lap in 0..SHADOW_LAPS {
16604 renderer
16605 .begin_frame(
16606 device,
16607 &Camera::default(),
16608 // **A different sun each lap**, so every lap redraws the
16609 // atlas: this is a test about the barrier a frame that
16610 // writes the image declares, and a lap that cached would
16611 // record no pass and no transition at all. See
16612 // [`moving_sun`].
16613 &moving_sun(u32::try_from(lap).expect("a handful of laps")),
16614 (64, 48),
16615 )
16616 .expect("write");
16617 let mut graph = crate::RenderGraph::new(queue);
16618 let target = graph.import_image("target", imported);
16619 renderer.add_passes(&mut graph, &pool, target, (64, 48));
16620 let compiled = graph.compile(&pool).expect("a legal frame");
16621 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
16622 label: Some("shadow lap"),
16623 queue,
16624 });
16625 compiled
16626 .execute(device, &mut pool, encoder.as_mut(), None)
16627 .expect("the graph executed");
16628 recorded.push(encoder.finish().expect("recording succeeded"));
16629 }
16630
16631 // The two images the renderer owns across frames. A transient's state is
16632 // the pool's business and the fake swapchain image's is the acquire's, so
16633 // neither belongs in here.
16634 let mut tracked = [
16635 (atlas, ResourceState::Undefined),
16636 (placeholder, ResourceState::Undefined),
16637 ];
16638 let mut atlas_writes = 0usize;
16639 let mut named = 0usize;
16640 for command in recorder.commands() {
16641 let Command::Barrier { images, .. } = command else {
16642 continue;
16643 };
16644 for barrier in images {
16645 let Some((_, state)) = tracked
16646 .iter_mut()
16647 .find(|(handle, _)| *handle == barrier.image)
16648 else {
16649 continue;
16650 };
16651 assert_eq!(
16652 barrier.from, *state,
16653 "a barrier declared {:?} -> {:?} on an image the frame before it left in \
16654 {:?}. `Undefined` carries no source scope, so a transition declaring it \
16655 orders against nothing and the previous frame's sampled read is still in \
16656 flight underneath it.",
16657 barrier.from, barrier.to, *state
16658 );
16659 if barrier.image == atlas && barrier.to == ResourceState::DepthStencilWrite {
16660 atlas_writes += 1;
16661 }
16662 *state = barrier.to;
16663 named += 1;
16664 }
16665 }
16666
16667 // Both halves of the loop above are silent on an empty stream, so the
16668 // shape it walked is asserted rather than assumed: one transition into
16669 // the depth-only pass's attachment state per lap, the last one included.
16670 assert_eq!(
16671 atlas_writes, SHADOW_LAPS,
16672 "{named} barrier(s) named the atlas or its placeholder across {SHADOW_LAPS} laps, \
16673 {atlas_writes} of them taking the atlas into DepthStencilWrite — every lap moved \
16674 the sun, so every lap redraws the atlas, and anything else means the loop above \
16675 asserted on a stream that does not contain the transition it is about"
16676 );
16677 let (_, ended) = tracked[0];
16678 assert_eq!(
16679 ended,
16680 ResourceState::ShaderRead,
16681 "the import promises to hand the atlas back in the state the next frame declares"
16682 );
16683
16684 renderer.destroy(device);
16685 for commands in recorded {
16686 device.destroy_command_buffer(commands);
16687 }
16688 pool.destroy(device);
16689 device.destroy_image_view(imported.view);
16690 device.destroy_image(imported.image);
16691 recorder.assert_valid();
16692 }
16693
16694 /// A renderer with a shadowed spot beside the sun's cascades and a caster
16695 /// for both to draw, which is the smallest scene the atlas cache has
16696 /// anything to say about: without a light tile the only maps are the
16697 /// cascades, and without a caster every tile is a clear.
16698 fn shadow_cache_scene(
16699 device: &dyn Device,
16700 queue: QueueHandle,
16701 ) -> (ForwardRenderer, InstanceHandle) {
16702 let mut renderer =
16703 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
16704 // Pinned, on `set_shadow_cadence`'s own terms: the console's two limits
16705 // are process-global and `the_console_moves_both_limits` holds them at
16706 // a four-frame hold and three faces a frame for the length of its
16707 // check. A cache test reading the console inside that window reports
16708 // "did not settle" — seen in the wild on 2026-09-04, and reproduced by
16709 // holding both limits at those values inside the arm's own process,
16710 // which the pin makes harmless.
16711 renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
16712 let cube = place_cube(&mut renderer, Mat4::IDENTITY);
16713 renderer.set_lights(&[shadowable_spot(-1.0)]);
16714 (renderer, cube)
16715 }
16716
16717 /// Draws one frame and answers whether it drew the shadow atlas, **read two
16718 /// ways that have to agree**.
16719 ///
16720 /// [`ForwardRenderer::shadow_atlas_cached`] is the renderer's own claim and
16721 /// the recorded stream is what the device was actually told; either on its
16722 /// own would be satisfied by a renderer that reported one thing and did the
16723 /// other, which is precisely the failure a cache has. `seen` is the cursor
16724 /// into the cumulative recorder, so each call reads its own frame.
16725 fn drew_the_atlas(
16726 recorder: &Recorder,
16727 seen: &mut usize,
16728 device: &dyn Device,
16729 renderer: &mut ForwardRenderer,
16730 queue: QueueHandle,
16731 camera: &Camera,
16732 sun: &DirectionalLight,
16733 ) -> bool {
16734 let drawn = frame_seen_from(device, renderer, queue, camera, sun);
16735 let claimed = renderer.shadow_atlas_cached();
16736 let commands = recorder.commands();
16737 let opened = commands[*seen..].iter().any(|command| {
16738 command
16739 .opens_pass()
16740 .is_some_and(|(_, label)| label == Some("shadow"))
16741 });
16742 *seen = commands.len();
16743 drawn.release(device);
16744 assert_eq!(
16745 opened,
16746 !claimed,
16747 "the renderer reports cached = {claimed} and its frame {} a pass labelled `shadow`",
16748 if opened { "opened" } else { "opened no" }
16749 );
16750 opened
16751 }
16752
16753 #[test]
16754 fn shadow_preparation_retains_empty_scratch_after_redraw_and_cached_frames() {
16755 let (recorder, device, queue) = open();
16756 let device = device.as_ref();
16757 let (mut renderer, _) = shadow_cache_scene(device, queue);
16758 let camera = Camera::default();
16759 let sun = DirectionalLight::default();
16760 let mut seen = 0;
16761 assert!(drew_the_atlas(
16762 &recorder,
16763 &mut seen,
16764 device,
16765 &mut renderer,
16766 queue,
16767 &camera,
16768 &sun
16769 ));
16770 let capacity = (
16771 renderer.shadow_prepare_views.capacity(),
16772 renderer.shadow_prepare_culls.capacity(),
16773 );
16774 assert!(capacity.0 >= SHADOW_VIEWS && capacity.1 >= SHADOW_CULLS);
16775 assert!(renderer.shadow_prepare_views.is_empty());
16776 assert!(renderer.shadow_prepare_culls.is_empty());
16777 for _ in 0..FRAMES_IN_FLIGHT {
16778 assert!(!drew_the_atlas(
16779 &recorder,
16780 &mut seen,
16781 device,
16782 &mut renderer,
16783 queue,
16784 &camera,
16785 &sun
16786 ));
16787 assert!(renderer.shadow_prepare_views.is_empty());
16788 assert!(renderer.shadow_prepare_culls.is_empty());
16789 assert_eq!(
16790 (
16791 renderer.shadow_prepare_views.capacity(),
16792 renderer.shadow_prepare_culls.capacity()
16793 ),
16794 capacity
16795 );
16796 }
16797 for (step, view) in [0, 1, shadow_view(0, 0)].into_iter().enumerate() {
16798 // The spot moves for its own view and the camera for the cascades',
16799 // which are fitted to it: a moved spot alone is no input of theirs.
16800 renderer.set_lights(&[shadowable_spot(-2.0 - step as f32)]);
16801 let camera = Camera {
16802 eye: camera.eye + Vec3::X * 0.1 * (step + 1) as f32,
16803 ..camera
16804 };
16805 let slot = (renderer.frame + 1) % FRAMES_IN_FLIGHT;
16806 let short = device
16807 .create_buffer(&BufferDesc {
16808 label: Some("refused shadow scratch test upload"),
16809 size: std::mem::size_of::<f32>() as u64,
16810 usage: BufferUsage::UNIFORM,
16811 memory: MemoryLocation::HostUpload,
16812 })
16813 .unwrap();
16814 let original = std::mem::replace(&mut renderer.shadow_uniforms[slot][view], short);
16815 let before = recorder.buffer_bytes(short).unwrap();
16816 let result = renderer.begin_frame(device, &camera, &sun, TEST_EXTENT);
16817 renderer.shadow_uniforms[slot][view] = original;
16818 assert!(
16819 matches!(result, Err(HalError::InvalidDescriptor(ref cause)) if cause.contains("exceeds")),
16820 "observe a refused shadow uniform: {result:?}"
16821 );
16822 assert_eq!(recorder.buffer_bytes(short).unwrap(), before);
16823 assert!(!recorder.events().iter().any(
16824 |event| matches!(event, Event::BufferWritten { buffer, .. } if *buffer == short)
16825 ));
16826 assert!(renderer.shadow_prepare_views.is_empty());
16827 assert!(renderer.shadow_prepare_culls.is_empty());
16828 assert_eq!(
16829 (
16830 renderer.shadow_prepare_views.capacity(),
16831 renderer.shadow_prepare_culls.capacity()
16832 ),
16833 capacity
16834 );
16835 let refused_inputs = renderer.shadow_group_inputs.clone();
16836 device.destroy_buffer(short);
16837 recorder.assert_valid();
16838 assert!(drew_the_atlas(
16839 &recorder,
16840 &mut seen,
16841 device,
16842 &mut renderer,
16843 queue,
16844 &camera,
16845 &sun
16846 ));
16847 assert_eq!(renderer.shadow_group_inputs, refused_inputs);
16848 assert!(renderer.shadow_prepare_views.is_empty());
16849 assert!(renderer.shadow_prepare_culls.is_empty());
16850 assert_eq!(
16851 (
16852 renderer.shadow_prepare_views.capacity(),
16853 renderer.shadow_prepare_culls.capacity()
16854 ),
16855 capacity
16856 );
16857 assert!(!drew_the_atlas(
16858 &recorder,
16859 &mut seen,
16860 device,
16861 &mut renderer,
16862 queue,
16863 &camera,
16864 &sun
16865 ));
16866 }
16867 renderer.destroy(device);
16868 recorder.assert_valid();
16869 assert_eq!(recorder.total_live_objects(), 0);
16870 }
16871
16872 /// **A frame over a scene nothing moved in does not draw the shadow atlas
16873 /// again**, and what it saves is the whole of the atlas's work.
16874 ///
16875 /// Topic 45's static-caching rung, and the observable it
16876 /// otherwise has none for: the map a cached frame samples is byte for byte
16877 /// the map the frame before it sampled, so no golden image and no readback
16878 /// can tell the two frames apart. The recorded command stream can — and the
16879 /// dispatch count is the half that says the *culls* went with the pass,
16880 /// rather than the frame still paying for the draws it decided not to
16881 /// record.
16882 #[test]
16883 fn a_frame_over_a_still_scene_does_not_draw_the_shadow_atlas_again() {
16884 use crcbl_hal::null::Command;
16885
16886 // The blur count is a process-global console variable, and the frame's
16887 // draw count below includes the full-screen triangle each blur records
16888 // — so a concurrent test holding `r_ssao_blur_passes` at two would move
16889 // it under this one. Held rather than merely read, which is the
16890 // convention that variable's own test set.
16891 let _blurs = ssao_blur_switch();
16892 let (recorder, device, queue) = open();
16893 let device = device.as_ref();
16894 let (mut renderer, _) = shadow_cache_scene(device, queue);
16895 let camera = Camera::default();
16896 let sun = DirectionalLight::default();
16897
16898 let mut seen = 0usize;
16899 let dispatches = |recorder: &Recorder, from: usize| {
16900 recorder.commands()[from..]
16901 .iter()
16902 .filter(|command| matches!(command, Command::Dispatch { .. }))
16903 .count()
16904 };
16905
16906 let at = seen;
16907 assert!(
16908 drew_the_atlas(
16909 &recorder,
16910 &mut seen,
16911 device,
16912 &mut renderer,
16913 queue,
16914 &camera,
16915 &sun
16916 ),
16917 "the first frame of all has to draw the atlas: nothing has put anything in it"
16918 );
16919 let first = dispatches(&recorder, at);
16920 let drawing_draws = renderer.counters().draws;
16921 let buckets = renderer.bucket_constants.len() as u64;
16922 assert!(
16923 renderer.shadow_lights().base_of(0).is_some(),
16924 "the spot must hold a run for the count below to include a light slot's cull"
16925 );
16926 // The camera's own draw generation and topic 18's clustering dispatch,
16927 // plus a generation per cascade and one for the spot's slot.
16928 assert_eq!(
16929 first,
16930 DrawGen::DISPATCHES as usize * (2 + shadow::CASCADES) + 1 + RESOLVE_DISPATCHES,
16931 "the drawing frame did not record the culls this test is about skipping"
16932 );
16933
16934 for round in 0..3 {
16935 let at = seen;
16936 assert!(
16937 !drew_the_atlas(
16938 &recorder,
16939 &mut seen,
16940 device,
16941 &mut renderer,
16942 queue,
16943 &camera,
16944 &sun
16945 ),
16946 "round {round} redrew an atlas nothing had changed"
16947 );
16948 assert_eq!(
16949 dispatches(&recorder, at),
16950 DrawGen::DISPATCHES as usize + 1 + RESOLVE_DISPATCHES,
16951 "round {round} kept a shadow cull it had no pass to feed"
16952 );
16953 assert_eq!(
16954 drawing_draws - renderer.counters().draws,
16955 (shadow::CASCADES + 1) as u64 * buckets,
16956 "round {round}: the frame's own draw count did not lose exactly the atlas's \
16957 calls — one per bucket per cascade, and one per bucket for the spot's tile"
16958 );
16959 }
16960
16961 renderer.destroy(device);
16962 recorder.assert_valid();
16963 }
16964
16965 /// A cadence that holds every map one rung down for a frame, with the whole
16966 /// atlas's worth of tiles to spend.
16967 ///
16968 /// Pinned through [`ForwardRenderer::set_shadow_cadence`] rather than set on
16969 /// the console: [`shadow::r_shadow_cadence`] is process-global and the
16970 /// shadow pass is in every frame's pass list, so a test that moved it would
16971 /// change the frame every other test in this module draws.
16972 const HOLD_TWO: shadow::Cadence = shadow::Cadence {
16973 hold: 2,
16974 faces: shadow::TILES,
16975 };
16976
16977 /// How the shadow pass loaded its depth attachment, over the commands from
16978 /// `from` on, and [`None`] where the frame recorded no such pass.
16979 ///
16980 /// **The observable the tile clear otherwise has none for.** A frame that
16981 /// kept a tile and a frame that redrew every one of them sample maps that
16982 /// may be identical, so nothing in the picture separates them; this is the
16983 /// declaration that says which the device was told.
16984 fn shadow_pass_depth_load(recorder: &Recorder, from: usize) -> Option<LoadOp> {
16985 use crcbl_hal::null::Command;
16986
16987 recorder.commands()[from..].iter().find_map(|command| {
16988 let Command::BeginRenderPass {
16989 label,
16990 depth_stencil_attachment,
16991 ..
16992 } = command
16993 else {
16994 return None;
16995 };
16996 if label.as_deref() != Some("shadow") {
16997 return None;
16998 }
16999 depth_stencil_attachment
17000 .as_ref()
17001 .map(|attachment| attachment.depth_load)
17002 })
17003 }
17004
17005 /// Direct draws recorded inside the shadow pass, over the commands from
17006 /// `from` on — which is one per tile the pass reset itself, the atlas's
17007 /// geometry being drawn indirectly.
17008 fn tile_clears_in_the_shadow_pass(recorder: &Recorder, from: usize) -> usize {
17009 use crcbl_hal::null::Command;
17010
17011 let mut inside = false;
17012 let mut clears = 0;
17013 for command in &recorder.commands()[from..] {
17014 if let Some((_, label)) = command.opens_pass() {
17015 inside = label == Some("shadow");
17016 continue;
17017 }
17018 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
17019 inside = false;
17020 continue;
17021 }
17022 if inside && matches!(command, Command::Draw { .. }) {
17023 clears += 1;
17024 }
17025 }
17026 clears
17027 }
17028
17029 /// **The far cascade is redrawn every second frame and the near one every
17030 /// frame**, on a scene where the eye moves and so every map is out of date.
17031 ///
17032 /// Topic 45's cadence rung, and the observable it otherwise
17033 /// has none for: a held map draws a shadow one frame behind its caster,
17034 /// which is a plausible picture and one a golden accepts.
17035 ///
17036 /// The eye moves by a fraction of a cascade's own reach, so no frame is a
17037 /// reset — that is asserted rather than assumed, because a reset would make
17038 /// every frame redraw everything and this test would pass by having
17039 /// switched the cadence off.
17040 #[test]
17041 fn the_far_cascade_is_held_on_the_frames_between_its_turns() {
17042 let _blurs = ssao_blur_switch();
17043 let (recorder, device, queue) = open();
17044 let device = device.as_ref();
17045 let (mut renderer, _) = shadow_cache_scene(device, queue);
17046 let sun = DirectionalLight::default();
17047 renderer.set_shadow_cadence(Some(HOLD_TWO));
17048
17049 const FRAMES: usize = 8;
17050 let mut near = 0;
17051 let mut far = 0;
17052 for step in 0..FRAMES {
17053 #[expect(
17054 clippy::cast_precision_loss,
17055 reason = "a handful of frames, and the step is what is wanted"
17056 )]
17057 let camera = Camera {
17058 eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17059 ..Camera::default()
17060 };
17061 let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17062 assert_eq!(
17063 renderer.shadow_cadence_reset(),
17064 step == 0,
17065 "frame {step}: only the first frame has an atlas to lay out, and a reset \
17066 after it would redraw everything and leave nothing for the cadence to hold"
17067 );
17068 near += usize::from(renderer.shadow_cascade_redrawn(0));
17069 far += usize::from(renderer.shadow_cascade_redrawn(1));
17070 drawn.release(device);
17071 }
17072 assert_eq!(
17073 near, FRAMES,
17074 "the near cascade is fitted to the eye and is on the top rung: every frame"
17075 );
17076 assert_eq!(
17077 far,
17078 FRAMES / 2,
17079 "the far cascade is one rung down, so every second frame"
17080 );
17081
17082 renderer.destroy(device);
17083 recorder.assert_valid();
17084 }
17085
17086 /// **A frame that keeps a tile loads the attachment and resets the tiles it
17087 /// redraws itself**, and a frame that keeps none clears it — which is what
17088 /// shipped.
17089 ///
17090 /// The half of the cadence a redraw count cannot see: holding a tile is only
17091 /// worth anything if the tile survives, and the one clear this seam has
17092 /// covers the whole image. A frame that loaded and reset nothing would draw
17093 /// into tiles still holding the last frame's depths, and under reversed-Z a
17094 /// caster that moved away would go on occluding.
17095 #[test]
17096 fn a_frame_that_keeps_a_tile_loads_the_attachment_and_resets_the_rest() {
17097 let _blurs = ssao_blur_switch();
17098 let (recorder, device, queue) = open();
17099 let device = device.as_ref();
17100 let (mut renderer, _) = shadow_cache_scene(device, queue);
17101 let sun = DirectionalLight::default();
17102
17103 // The first frame lays the atlas out, so it clears and redraws
17104 // everything whatever the console says.
17105 let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17106 first.release(device);
17107 assert_eq!(
17108 shadow_pass_depth_load(&recorder, 0),
17109 Some(LoadOp::Clear),
17110 "the frame that lays the atlas out has nothing to keep"
17111 );
17112 assert_eq!(
17113 tile_clears_in_the_shadow_pass(&recorder, 0),
17114 0,
17115 "and so resets no tile of its own"
17116 );
17117
17118 renderer.set_shadow_cadence(Some(HOLD_TWO));
17119 let mut seen = recorder.commands().len();
17120 let mut loaded = 0;
17121 for step in 1..4 {
17122 #[expect(
17123 clippy::cast_precision_loss,
17124 reason = "a handful of frames, and the step is what is wanted"
17125 )]
17126 let camera = Camera {
17127 eye: Camera::default().eye + Vec3::X * 0.05 * step as f32,
17128 ..Camera::default()
17129 };
17130 let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17131 let load = shadow_pass_depth_load(&recorder, seen).expect("a shadow pass");
17132 let clears = tile_clears_in_the_shadow_pass(&recorder, seen);
17133 let faces = renderer.shadow_faces_redrawn() as usize;
17134 if load == LoadOp::Load {
17135 loaded += 1;
17136 assert_eq!(
17137 clears, faces,
17138 "frame {step} loaded the attachment and reset {clears} of the {faces} \
17139 tiles it redrew"
17140 );
17141 assert!(
17142 faces < shadow::TILES,
17143 "frame {step} loaded an attachment while redrawing every tile"
17144 );
17145 } else {
17146 assert_eq!(
17147 clears, 0,
17148 "frame {step} cleared the attachment and reset {clears} tiles again"
17149 );
17150 }
17151 seen = recorder.commands().len();
17152 drawn.release(device);
17153 }
17154 assert!(
17155 loaded > 0,
17156 "no frame kept a tile, so nothing here is about the load path"
17157 );
17158
17159 renderer.destroy(device);
17160 recorder.assert_valid();
17161 }
17162
17163 /// A point light costs the budget every face it draws, not one.
17164 ///
17165 /// **The half of the budget its name is about.** `shadow_faces_redrawn` is
17166 /// a sum over the groups a frame redrew of the maps each of them owns, and
17167 /// a point light owns [`shadow::POINT_FACES`] of them. Every other check
17168 /// here is built on the sun and a spot, which own one map each — so a face
17169 /// count that answered `1` for every group would satisfy all of them, and
17170 /// did: collapsing it passed the whole of `crcbl-render` and the mesh e2e
17171 /// suite. This is what binds on the difference.
17172 #[test]
17173 fn a_point_light_costs_the_budget_every_face_it_draws() {
17174 let _blurs = ssao_blur_switch();
17175 let (_recorder, device, queue) = open();
17176 let device = device.as_ref();
17177 let mut renderer =
17178 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17179 let _cube = place_cube(&mut renderer, Mat4::IDENTITY);
17180 renderer.set_lights(&[shadowable_point(-1.0)]);
17181 let sun = DirectionalLight::default();
17182
17183 // Every group is forced on the first frame — the image has held none of
17184 // them — so this counts what a full redraw actually costs.
17185 renderer.set_shadow_cadence(Some(shadow::Cadence::EVERY_FRAME));
17186 let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17187 first.release(device);
17188 let point_faces = u32::try_from(shadow::POINT_FACES).expect("a handful of faces");
17189 assert!(
17190 renderer.shadow_lights().base_of(0).is_some(),
17191 "the point must hold a run of tiles, or there is no multi-face group to count"
17192 );
17193 assert!(
17194 renderer.shadow_faces_redrawn() >= point_faces,
17195 "a frame that redrew a point light's whole cube reported {} faces, fewer than the \
17196 {point_faces} it owns — so the budget is counting groups rather than the maps they \
17197 draw, and a cube would slip past a budget of one",
17198 renderer.shadow_faces_redrawn()
17199 );
17200 }
17201
17202 /// **A frame never redraws more tiles than the budget allows**, and every
17203 /// map still gets its turn.
17204 ///
17205 /// The starvation half is what makes this more than an inequality: a
17206 /// schedule that spent the budget on the same maps every frame would satisfy
17207 /// the bound and never draw the rest at all.
17208 #[test]
17209 fn the_face_budget_bounds_a_frame_and_starves_no_map() {
17210 let _blurs = ssao_blur_switch();
17211 let (recorder, device, queue) = open();
17212 let device = device.as_ref();
17213 let (mut renderer, _) = shadow_cache_scene(device, queue);
17214 let sun = DirectionalLight::default();
17215
17216 let first = frame_seen_from(device, &mut renderer, queue, &Camera::default(), &sun);
17217 first.release(device);
17218 assert!(
17219 renderer.shadow_lights().base_of(0).is_some(),
17220 "the spot must hold a run, or the budget has only the cascades to bind on"
17221 );
17222
17223 // One tile a frame: the two cascades and the spot's map cannot all fit,
17224 // so something is held on every frame of the run below.
17225 const BUDGET: u32 = 1;
17226 renderer.set_shadow_cadence(Some(shadow::Cadence {
17227 hold: 1,
17228 faces: BUDGET as usize,
17229 }));
17230 const FRAMES: usize = 12;
17231 let mut drew = [0usize; 3];
17232 for step in 1..=FRAMES {
17233 #[expect(
17234 clippy::cast_precision_loss,
17235 reason = "a handful of frames, and the step is what is wanted"
17236 )]
17237 let camera = Camera {
17238 eye: Camera::default().eye + Vec3::X * 0.02 * step as f32,
17239 ..Camera::default()
17240 };
17241 // The spot drifts too: its map is not fitted to the camera, so a
17242 // moving eye alone leaves it up to date and asking for nothing.
17243 #[expect(
17244 clippy::cast_precision_loss,
17245 reason = "a handful of frames, and the step is what is wanted"
17246 )]
17247 renderer.set_lights(&[shadowable_spot(-1.0 + 0.01 * step as f32)]);
17248 let drawn = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17249 assert!(
17250 renderer.shadow_faces_redrawn() <= BUDGET,
17251 "frame {step} redrew {} tiles against a budget of {BUDGET}",
17252 renderer.shadow_faces_redrawn()
17253 );
17254 drew[0] += usize::from(renderer.shadow_cascade_redrawn(0));
17255 drew[1] += usize::from(renderer.shadow_cascade_redrawn(1));
17256 drew[2] += usize::from(renderer.shadow_slot_redrawn(0));
17257 drawn.release(device);
17258 }
17259 for (map, count) in drew.iter().enumerate() {
17260 assert!(
17261 *count > 0,
17262 "map {map} was never redrawn in {FRAMES} frames under a budget of \
17263 {BUDGET}: {drew:?}"
17264 );
17265 }
17266
17267 renderer.destroy(device);
17268 recorder.assert_valid();
17269 }
17270
17271 /// **A light that jumps further than its own radius resets the cadence**,
17272 /// and one that drifts inside it does not.
17273 ///
17274 /// Topic 45's "a moving light or camera cut resets it",
17275 /// made precise: a map whose centre has moved past the map's own reach is
17276 /// not a frame out of date, it is about somewhere else — so it is redrawn on
17277 /// the frame that notices rather than when its turn comes round. Both arms,
17278 /// because a reset that fired on every move would be the cadence switched
17279 /// off.
17280 #[test]
17281 fn a_light_that_jumps_past_its_own_radius_resets_the_cadence() {
17282 let _blurs = ssao_blur_switch();
17283 let (recorder, device, queue) = open();
17284 let device = device.as_ref();
17285 let (mut renderer, _) = shadow_cache_scene(device, queue);
17286 let sun = DirectionalLight::default();
17287 let camera = Camera::default();
17288 // The coarsest hold there is, so a redraw of the spot's map on the
17289 // frames below is the reset and not its turn.
17290 renderer.set_shadow_cadence(Some(shadow::Cadence {
17291 hold: 8,
17292 faces: shadow::TILES,
17293 }));
17294
17295 let mut settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17296 settle.release(device);
17297 for _ in 0..2 {
17298 settle = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17299 settle.release(device);
17300 }
17301 assert!(
17302 !renderer.shadow_cadence_reset(),
17303 "the scene has settled, so nothing is about somewhere else"
17304 );
17305
17306 // A drift well inside the light's own radius: out of date, not moved.
17307 renderer.set_lights(&[shadowable_spot(-1.0 + 0.5)]);
17308 let drifted = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17309 drifted.release(device);
17310 assert!(
17311 !renderer.shadow_cadence_reset(),
17312 "a light that moved a sixteenth of its radius is a map a frame out of date"
17313 );
17314
17315 // And a jump past it. `shadowable_spot`'s radius is what the reach is
17316 // taken from, so this is a light standing where its own map says
17317 // nothing.
17318 renderer.set_lights(&[shadowable_spot(-1.0 + 40.0)]);
17319 let jumped = frame_seen_from(device, &mut renderer, queue, &camera, &sun);
17320 jumped.release(device);
17321 assert!(
17322 renderer.shadow_cadence_reset(),
17323 "a light that jumped five times its own radius must not hold its map"
17324 );
17325 assert!(
17326 renderer.shadow_slot_redrawn(0),
17327 "and the reset is only a reset if the map is actually redrawn"
17328 );
17329
17330 renderer.destroy(device);
17331 recorder.assert_valid();
17332 }
17333
17334 /// **A console knob about *sampling* the atlas does not redraw it.**
17335 ///
17336 /// `r_shadow_filter` and `r_shadow_split` decide how the colour pass reads
17337 /// a map, and `r_shadow_bias` and `r_shadow_normal_offset` how far from a
17338 /// receiver it reads — and not one byte of what the depth pass writes into
17339 /// it is any of theirs. Yet the
17340 /// shadow views' blocks are the frame's block spread, and the cache record
17341 /// is those blocks' bytes — so until the views zeroed the row, a person
17342 /// typing `r_shadow_filter box` redrew every map in the atlas for nothing,
17343 /// and in this crate's own test process the filter tests moving that cell
17344 /// redrew the atlas under `each_thing_the_atlas_is_drawn_from_redraws_it`
17345 /// once in every five or six workspace runs on 2026-09-04. Holding the lock
17346 /// here is what makes the move below the only one in flight.
17347 #[test]
17348 fn a_moved_shadow_filter_leaves_a_still_atlas_alone() {
17349 let switch = shadow_filter_switch();
17350 let (recorder, device, queue) = open();
17351 let device = device.as_ref();
17352 let (mut renderer, _) = shadow_cache_scene(device, queue);
17353 let camera = Camera::default();
17354 let sun = DirectionalLight::default();
17355 let mut seen = 0usize;
17356 assert!(
17357 drew_the_atlas(
17358 &recorder,
17359 &mut seen,
17360 device,
17361 &mut renderer,
17362 queue,
17363 &camera,
17364 &sun
17365 ),
17366 "the first frame of all draws the atlas"
17367 );
17368 assert!(
17369 !drew_the_atlas(
17370 &recorder,
17371 &mut seen,
17372 device,
17373 &mut renderer,
17374 queue,
17375 &camera,
17376 &sun
17377 ),
17378 "a still second frame has to hold it, or the move below proves nothing"
17379 );
17380
17381 switch.filter(shadow::Filter::Box);
17382 switch.seam(0.5);
17383 assert!(
17384 !drew_the_atlas(
17385 &recorder,
17386 &mut seen,
17387 device,
17388 &mut renderer,
17389 queue,
17390 &camera,
17391 &sun
17392 ),
17393 "`r_shadow_filter` and `r_shadow_split` moved and the atlas was drawn again: a \
17394 sampling knob reached the record of what the maps were drawn from"
17395 );
17396
17397 // The bias pair sits in a different row of the same block, and the
17398 // second row it reaches is `Cascades::params`, which is rebuilt every
17399 // frame — so this is the arm that says the *whole* row is kept out of
17400 // the record rather than the one lane the filter is in.
17401 switch.bias(8.0);
17402 switch.offset(8.0);
17403 assert!(
17404 !drew_the_atlas(
17405 &recorder,
17406 &mut seen,
17407 device,
17408 &mut renderer,
17409 queue,
17410 &camera,
17411 &sun
17412 ),
17413 "`r_shadow_bias` and `r_shadow_normal_offset` moved and the atlas was drawn again: \
17414 the bias row reached the record of what the maps were drawn from"
17415 );
17416
17417 renderer.destroy(device);
17418 recorder.assert_valid();
17419 }
17420
17421 /// **Every input the atlas is drawn from redraws it**, one at a time.
17422 ///
17423 /// The half that stops "cached everything, for ever" from passing every
17424 /// assertion above. Each arm moves exactly one thing and asserts the next
17425 /// frame draws again — and then holds still and asserts it stops, so an arm
17426 /// cannot pass by having broken the cache outright.
17427 ///
17428 /// The camera is in here because it is not obvious: a shadow map is drawn
17429 /// from a light, not from the eye. But a cascade is fitted to the camera's
17430 /// own frustum, and every shadow cull selects a DAG's detail at the camera's
17431 /// pixels — `SHADOW_LOD_BIAS` — so a moved eye is a different cascade, and a
17432 /// different light map wherever a DAG is in the light's cull.
17433 /// `shadow_reach`'s tests are the other half: what a moved eye or a moved
17434 /// caster must *not* redraw.
17435 ///
17436 /// `settles` is how many still frames it takes to go quiet again, and it is
17437 /// two for exactly one arm: `InstancePool`'s carry-forward puts a moved
17438 /// instance's `previous_transform` back at rest on the frame *after* the
17439 /// move, and that is a write, which is a change this record cannot tell
17440 /// from any other. See `InstancePool::take_written`, which says so.
17441 #[test]
17442 fn each_thing_the_atlas_is_drawn_from_redraws_it() {
17443 let camera = Camera::default();
17444 let sun = DirectionalLight::default();
17445 let moved_camera = Camera {
17446 eye: camera.eye + Vec3::X * 4.0,
17447 ..camera
17448 };
17449 type Change = fn(&mut ForwardRenderer, InstanceHandle);
17450 let arms: [(&str, Change, &Camera, &DirectionalLight, usize); 4] = [
17451 (
17452 "a caster moved",
17453 |renderer, cube| {
17454 renderer.set_instance(
17455 cube,
17456 &InstanceDesc {
17457 mesh: DEMO_CUBE,
17458 material: DEMO_UNTINTED,
17459 transform: Mat4::from_translation(Vec3::X),
17460 },
17461 );
17462 },
17463 &camera,
17464 &sun,
17465 2,
17466 ),
17467 (
17468 "a caster removed",
17469 |renderer, cube| renderer.remove_instance(cube),
17470 &camera,
17471 &sun,
17472 1,
17473 ),
17474 (
17475 "the light moved",
17476 |renderer, _| renderer.set_lights(&[shadowable_spot(1.5)]),
17477 &camera,
17478 &sun,
17479 1,
17480 ),
17481 ("the camera moved", |_, _| {}, &moved_camera, &sun, 1),
17482 ];
17483
17484 for (what, change, camera, sun, settles) in arms {
17485 let (recorder, device, queue) = open();
17486 let device = device.as_ref();
17487 let (mut renderer, cube) = shadow_cache_scene(device, queue);
17488 let mut seen = 0usize;
17489 // Two frames, so the atlas is drawn and then held: the arm's own
17490 // assertion is about a frame that would otherwise have cached.
17491 for round in 0..2 {
17492 let drew = drew_the_atlas(
17493 &recorder,
17494 &mut seen,
17495 device,
17496 &mut renderer,
17497 queue,
17498 &Camera::default(),
17499 &DirectionalLight::default(),
17500 );
17501 assert_eq!(
17502 drew,
17503 round == 0,
17504 "{what}: the still frames before the change did not settle"
17505 );
17506 }
17507
17508 change(&mut renderer, cube);
17509 assert!(
17510 drew_the_atlas(
17511 &recorder,
17512 &mut seen,
17513 device,
17514 &mut renderer,
17515 queue,
17516 camera,
17517 sun
17518 ),
17519 "{what} and the atlas was not drawn again"
17520 );
17521 // And it goes quiet again in exactly `settles` frames, so the arm
17522 // cannot pass by having broken the cache rather than by having
17523 // invalidated it — and a change that started redrawing for ever
17524 // fails here rather than going unnoticed.
17525 for round in 0..settles {
17526 assert_eq!(
17527 drew_the_atlas(
17528 &recorder,
17529 &mut seen,
17530 device,
17531 &mut renderer,
17532 queue,
17533 camera,
17534 sun
17535 ),
17536 round + 1 < settles,
17537 "{what}: the still frames after the change did not settle in {settles}"
17538 );
17539 }
17540
17541 renderer.destroy(device);
17542 recorder.assert_valid();
17543 }
17544 }
17545
17546 /// **A frame with a skinned object in it always redraws the atlas**, and
17547 /// that is a limit written down rather than a gap.
17548 ///
17549 /// A skinned caster's vertices are produced by a compute dispatch into the
17550 /// pool, so there is nothing on the host to compare: the palette a caller
17551 /// hands over is not the geometry, and the geometry is never read back. The
17552 /// honest answer is to redraw, and the dishonest one is a map of a pose the
17553 /// character has left.
17554 #[test]
17555 fn a_frame_with_a_skinned_object_never_caches_the_atlas() {
17556 let (recorder, device, queue) = open();
17557 let device = device.as_ref();
17558 let mut fixture = SkinnedFixture::build(device, queue);
17559 fixture.renderer.set_lights(&[shadowable_spot(-1.0)]);
17560 let imported = swapchain_image_at(device, TEST_EXTENT);
17561 let mut pool = crate::TransientPool::new();
17562
17563 // The same palette and the same plan every lap, so nothing a host-side
17564 // comparison could see has moved.
17565 for lap in 0..3 {
17566 fixture.begin(device);
17567 let mut graph = crate::RenderGraph::new(queue);
17568 let target = graph.import_image("target", imported);
17569 fixture.renderer.add_skinned_passes(
17570 &mut graph,
17571 &pool,
17572 target,
17573 TEST_EXTENT,
17574 &fixture.skinning,
17575 );
17576 let compiled = graph.compile(&pool).expect("a legal frame");
17577 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17578 label: Some("skinned lap"),
17579 queue,
17580 });
17581 compiled
17582 .execute(device, &mut pool, encoder.as_mut(), None)
17583 .expect("the graph executed");
17584 device.destroy_command_buffer(encoder.finish().expect("recording succeeded"));
17585 assert!(
17586 !fixture.renderer.shadow_atlas_cached(),
17587 "lap {lap} held a shadow map of a pose no host-side comparison can vouch for"
17588 );
17589 }
17590
17591 fixture.destroy(device);
17592 pool.destroy(device);
17593 device.destroy_image_view(imported.view);
17594 device.destroy_image(imported.image);
17595 recorder.assert_valid();
17596 }
17597
17598 /// **Switching the shadows off clears the atlas once, and then holds the
17599 /// clear**, which is the same cache answering a frame that draws nothing.
17600 ///
17601 /// The switched-off frame is not itself a cached frame: the pass has to run
17602 /// to write the reversed-Z clear that makes every comparison come back lit,
17603 /// and the image holds the last drawn maps until it does. What *is* cached
17604 /// is every frame after it, and the record for a switched-off frame is
17605 /// deliberately blind to the camera and the casters, because nothing about
17606 /// them reaches an atlas nothing draws into.
17607 #[test]
17608 fn switching_the_shadows_off_clears_the_atlas_once_and_then_holds_it() {
17609 let (recorder, device, queue) = open();
17610 let device = device.as_ref();
17611 let (mut renderer, cube) = shadow_cache_scene(device, queue);
17612 let camera = Camera::default();
17613 let sun = DirectionalLight::default();
17614 let mut seen = 0usize;
17615
17616 assert!(
17617 drew_the_atlas(
17618 &recorder,
17619 &mut seen,
17620 device,
17621 &mut renderer,
17622 queue,
17623 &camera,
17624 &sun
17625 ),
17626 "the first frame draws the maps"
17627 );
17628 renderer.set_effect_request(EffectRequest {
17629 programmatic: EffectOverride::none().force(RenderEffects::SHADOWS, Some(false)),
17630 ..EffectRequest::default()
17631 });
17632 assert!(
17633 drew_the_atlas(
17634 &recorder,
17635 &mut seen,
17636 device,
17637 &mut renderer,
17638 queue,
17639 &camera,
17640 &sun
17641 ),
17642 "the frame that switched the shadows off has to run the pass that clears the maps \
17643 out of the image"
17644 );
17645 assert!(
17646 !drew_the_atlas(
17647 &recorder,
17648 &mut seen,
17649 device,
17650 &mut renderer,
17651 queue,
17652 &camera,
17653 &sun
17654 ),
17655 "a second switched-off frame cleared an atlas that was already clear"
17656 );
17657 // And nothing about the scene reaches a frame that draws no map: the
17658 // caster moves and the atlas is still the clear it was.
17659 renderer.set_instance(
17660 cube,
17661 &InstanceDesc {
17662 mesh: DEMO_CUBE,
17663 material: DEMO_UNTINTED,
17664 transform: Mat4::from_translation(Vec3::X),
17665 },
17666 );
17667 assert!(
17668 !drew_the_atlas(
17669 &recorder,
17670 &mut seen,
17671 device,
17672 &mut renderer,
17673 queue,
17674 &camera,
17675 &sun
17676 ),
17677 "a caster moved with the shadows off, and the frame cleared the atlas over again"
17678 );
17679
17680 renderer.set_effect_request(EffectRequest::default());
17681 assert!(
17682 drew_the_atlas(
17683 &recorder,
17684 &mut seen,
17685 device,
17686 &mut renderer,
17687 queue,
17688 &camera,
17689 &sun
17690 ),
17691 "switching the shadows back on has to draw the maps the clear replaced"
17692 );
17693
17694 renderer.destroy(device);
17695 recorder.assert_valid();
17696 }
17697
17698 /// **A frame the graph refuses leaves the shadow atlas where it was.**
17699 ///
17700 /// [`RenderGraph::compile`] returns a [`Result`], so a frame can be
17701 /// described in full and then thrown away, and
17702 /// [`CompiledGraph::execute`](crate::CompiledGraph::execute) — the only
17703 /// thing that writes the pool's ledger — never runs. That is the case a
17704 /// renderer-held `ResourceState`, stepped forward while the passes were
17705 /// declared, gets wrong: it would already say [`ResourceState::ShaderRead`]
17706 /// for an image no barrier has touched, and [`InitialClaim::Tracked`] cannot
17707 /// object, because with nothing recorded there is nothing to contradict. The
17708 /// guard would be silent on precisely the drift it exists to find, which is
17709 /// why [`imported_state`] reads the ledger instead of a second copy of it.
17710 ///
17711 /// The observable is the first barrier the *next* frame records on the
17712 /// atlas. `Undefined -> DepthStencilWrite` is the transition an image
17713 /// nothing has written needs; `ShaderRead -> DepthStencilWrite` names an old
17714 /// layout the image was never in, which is a layout mismatch on every
17715 /// backend and a discarded image on some.
17716 #[test]
17717 fn a_refused_frame_leaves_the_shadow_atlas_where_it_was() {
17718 use crcbl_hal::null::Command;
17719
17720 let (recorder, device, queue) = open();
17721 let device = device.as_ref();
17722 let mut renderer =
17723 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17724 let atlas = renderer.shadow_atlas();
17725 let placeholder = renderer.shadow_placeholder;
17726 let mut pool = crate::TransientPool::new();
17727 let imported = swapchain_image(device);
17728
17729 // The refused frame: every pass a real frame declares, and beside them
17730 // one transient nothing reads or writes. `compile` answers
17731 // `UnusedTransient` and the whole description — the shadow atlas's
17732 // import included — is dropped without a command being recorded.
17733 renderer
17734 .begin_frame(
17735 device,
17736 &Camera::default(),
17737 &DirectionalLight::default(),
17738 (64, 48),
17739 )
17740 .expect("write");
17741 {
17742 let mut graph = crate::RenderGraph::new(queue);
17743 let target = graph.import_image("target", imported);
17744 renderer.add_passes(&mut graph, &pool, target, (64, 48));
17745 graph.create_image("orphan", crate::targets::scene_color((64, 48)));
17746 let refused = graph
17747 .compile(&pool)
17748 .expect_err("a transient no pass declares");
17749 assert!(
17750 matches!(refused, crate::GraphError::UnusedTransient { .. }),
17751 "the frame has to be refused for the reason this test is about — a graph that \
17752 compiled would go on to execute and the ledger would be written after all: \
17753 {refused:?}"
17754 );
17755 }
17756 assert_eq!(
17757 pool.imported_image_use(atlas),
17758 None,
17759 "nothing executed, so the ledger has nothing to say about the atlas — this is the \
17760 emptiness `InitialClaim::Tracked` cannot check against"
17761 );
17762
17763 // And the frame after it, which does run.
17764 renderer
17765 .begin_frame(
17766 device,
17767 &Camera::default(),
17768 &DirectionalLight::default(),
17769 (64, 48),
17770 )
17771 .expect("write");
17772 let mut graph = crate::RenderGraph::new(queue);
17773 let target = graph.import_image("target", imported);
17774 renderer.add_passes(&mut graph, &pool, target, (64, 48));
17775 let compiled = graph.compile(&pool).expect("a legal frame");
17776 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17777 label: Some("frame after a refusal"),
17778 queue,
17779 });
17780 compiled
17781 .execute(device, &mut pool, encoder.as_mut(), None)
17782 .expect("the graph executed");
17783 let commands = encoder.finish().expect("recording succeeded");
17784
17785 // The first barrier each of the two images gets. Only the refused frame
17786 // ran before this one and it recorded nothing, so these are the frame's
17787 // opening transitions.
17788 let mut opened: Vec<(crcbl_hal::ImageHandle, ResourceState, ResourceState)> = Vec::new();
17789 for command in recorder.commands() {
17790 let Command::Barrier { images, .. } = command else {
17791 continue;
17792 };
17793 for barrier in images {
17794 if barrier.image != atlas && barrier.image != placeholder {
17795 continue;
17796 }
17797 if opened.iter().any(|(image, _, _)| *image == barrier.image) {
17798 continue;
17799 }
17800 opened.push((barrier.image, barrier.from, barrier.to));
17801 }
17802 }
17803 for (image, from, to) in &opened {
17804 assert_eq!(
17805 *from,
17806 ResourceState::Undefined,
17807 "a barrier declared {from:?} -> {to:?} on an image the refused frame never gave a \
17808 layout to. The declaration is what makes the transition true, so one that has \
17809 moved on without an executed frame behind it names a source scope and an old \
17810 layout the image was never in — and the ledger is empty, so nothing refuses it \
17811 either. Image {image:?}"
17812 );
17813 }
17814 // The loop above is silent on an empty list and on a short one, and a
17815 // wrong declaration shortens it: an image declared in the state it is
17816 // wanted in needs no transition, so it drops out of the stream
17817 // altogether rather than appearing with the wrong source.
17818 assert_eq!(
17819 opened.len(),
17820 2,
17821 "the atlas and its placeholder are both imported every frame and both are wanted in a \
17822 state they are not in, so both have to be barriered: {opened:?}"
17823 );
17824 assert!(
17825 opened
17826 .iter()
17827 .any(|(image, _, to)| *image == atlas && *to == ResourceState::DepthStencilWrite),
17828 "and the atlas's is the shadow pass taking it as a depth attachment: {opened:?}"
17829 );
17830
17831 renderer.destroy(device);
17832 device.destroy_command_buffer(commands);
17833 pool.destroy(device);
17834 device.destroy_image_view(imported.view);
17835 device.destroy_image(imported.image);
17836 recorder.assert_valid();
17837 }
17838
17839 /// **The import audit still refuses an engine site whose declaration is
17840 /// wrong**, now that the shadow atlas's is read out of the same ledger it is
17841 /// checked against.
17842 ///
17843 /// That pair is deliberately circular and this test is what keeps it from
17844 /// swallowing the guard whole: `shadow-atlas` and `shadow-placeholder` say
17845 /// what [`imported_state`] just read, so [`InitialClaim::Tracked`] can only
17846 /// ever find them agreeing — their safety comes from there being one answer
17847 /// rather than from the check. Every *other* import in the frame declares a
17848 /// constant, and `ssao-placeholder` is the one this drives a ledger entry
17849 /// away from: uploaded into [`ResourceState::ShaderRead`] at build and
17850 /// declared so on every frame, so a graph that leaves it somewhere else is a
17851 /// declaration the next `compile` has to refuse.
17852 #[test]
17853 fn the_guard_still_catches_an_engine_import_that_lies() {
17854 let (recorder, device, queue) = open();
17855 let device = device.as_ref();
17856 let mut renderer =
17857 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
17858 let mut pool = crate::TransientPool::new();
17859 let imported = swapchain_image(device);
17860 let occlusion = renderer.ambient_occlusion_placeholder.image;
17861
17862 // A graph of this test's own, which moves the renderer's occlusion
17863 // placeholder somewhere `add_passes` does not expect. Same image handle,
17864 // so the entry it leaves in the ledger is the one the next `compile`
17865 // reads for `ssao-placeholder`.
17866 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
17867 label: Some("move the placeholder"),
17868 queue,
17869 });
17870 {
17871 let mut graph = crate::RenderGraph::new(queue);
17872 let moved = graph.import_image(
17873 "moved-placeholder",
17874 ImportedImage {
17875 image: occlusion,
17876 view: renderer.ambient_occlusion_placeholder.view,
17877 format: Format::Rgba8Unorm,
17878 extent: (1, 1),
17879 initial: ResourceState::ShaderRead,
17880 claim: InitialClaim::Tracked,
17881 final_state: ResourceState::TransferSrc,
17882 },
17883 );
17884 graph
17885 .add_copy_pass("read the placeholder")
17886 .use_image(moved, ResourceState::TransferSrc)
17887 .execute(|_| {});
17888 graph
17889 .compile(&pool)
17890 .expect("a legal frame")
17891 .execute(device, &mut pool, encoder.as_mut(), None)
17892 .expect("the graph executed");
17893 }
17894 let commands = encoder.finish().expect("recording succeeded");
17895 assert_eq!(
17896 pool.imported_image_use(occlusion),
17897 Some(ResourceState::TransferSrc),
17898 "the ledger has to have moved for the frame below to have anything to disagree with"
17899 );
17900
17901 renderer
17902 .begin_frame(
17903 device,
17904 &Camera::default(),
17905 &DirectionalLight::default(),
17906 (64, 48),
17907 )
17908 .expect("write");
17909 let mut graph = crate::RenderGraph::new(queue);
17910 let target = graph.import_image("target", imported);
17911 renderer.add_passes(&mut graph, &pool, target, (64, 48));
17912 let refused = graph
17913 .compile(&pool)
17914 .expect_err("`ssao-placeholder` declares a constant the ledger no longer agrees with");
17915 let crate::GraphError::ImportStateMismatch {
17916 resource,
17917 declared,
17918 left,
17919 } = &refused
17920 else {
17921 panic!("the audit has to name the import it refused, not merely fail: {refused:?}");
17922 };
17923 assert_eq!(resource, "ssao-placeholder");
17924 assert_eq!(*declared, ResourceState::ShaderRead);
17925 assert_eq!(*left, ResourceState::TransferSrc);
17926
17927 renderer.destroy(device);
17928 device.destroy_command_buffer(commands);
17929 pool.destroy(device);
17930 device.destroy_image_view(imported.view);
17931 device.destroy_image(imported.image);
17932 recorder.assert_valid();
17933 }
17934
17935 /// Compiles one frame and names the passes it turned out to be, in order.
17936 ///
17937 /// Compiled and not executed: what a pass costs is not the question here,
17938 /// only which of them the frame declared. Names rather than a count since
17939 /// the toggles landed — a count says a frame lost two passes and a list says
17940 /// *which* two, which is the difference between "the switch did something"
17941 /// and "the switch did the thing it is for".
17942 fn passes_in_a_frame(
17943 device: &dyn Device,
17944 queue: QueueHandle,
17945 renderer: &mut ForwardRenderer,
17946 imported: ImportedImage,
17947 pool: &crate::TransientPool,
17948 extent: (u32, u32),
17949 ) -> Vec<String> {
17950 renderer
17951 .begin_frame(
17952 device,
17953 &Camera::default(),
17954 &DirectionalLight::default(),
17955 extent,
17956 )
17957 .expect("write");
17958 let mut graph = crate::RenderGraph::new(queue);
17959 let target = graph.import_image("target", imported);
17960 renderer.add_passes(&mut graph, pool, target, extent);
17961 graph
17962 .compile(pool)
17963 .expect("a legal frame")
17964 .passes()
17965 .iter()
17966 .map(|pass| pass.label().to_string())
17967 .collect()
17968 }
17969
17970 /// A spot at `x` that [`shadow::Selection`] will give a tile: finite, a
17971 /// radius, a direction and a cone well inside the widest one allowed.
17972 /// A shadowed point light, which is [`shadow::POINT_FACES`] maps rather
17973 /// than one.
17974 ///
17975 /// The spot beside it is one tile and one face, so a scene built only from
17976 /// spots cannot tell a budget counting **faces** from one counting groups —
17977 /// which is what this exists to give a check something to bind on.
17978 fn shadowable_point(x: f32) -> Light {
17979 Light::Point(crate::light::PointLight {
17980 position: Vec3::new(x, 2.0, 0.0),
17981 radius: 8.0,
17982 color: Vec3::ONE,
17983 fill: false,
17984 })
17985 }
17986
17987 fn shadowable_spot(x: f32) -> Light {
17988 Light::Spot(crate::light::SpotLight {
17989 position: Vec3::new(x, 2.0, 0.0),
17990 radius: 8.0,
17991 color: Vec3::ONE,
17992 direction: -Vec3::Y,
17993 inner_angle: 0.3,
17994 outer_angle: 0.6,
17995 fill: false,
17996 })
17997 }
17998
17999 /// The page's anisotropy is the plan's default clamped to the device, and
18000 /// one on a device that was not granted the feature — whatever its limit
18001 /// says.
18002 ///
18003 /// The last arm is the one worth having: `gate_limits_on_features` narrows
18004 /// a declined feature's limit on `crcbl-vk`, but a backend that did not
18005 /// would report sixteen beside an absent feature, and a clamp that read the
18006 /// limit alone would ask for a sampler the device refuses.
18007 #[test]
18008 fn the_anisotropy_is_the_default_clamped_to_what_the_device_granted() {
18009 let caps = |features: Features, max_sampler_anisotropy: f32| DeviceCaps {
18010 features,
18011 limits: crcbl_hal::Limits {
18012 max_sampler_anisotropy,
18013 ..crcbl_hal::Limits::desktop()
18014 },
18015 };
18016 let granted = Features::SAMPLER_ANISOTROPY;
18017 assert!(
18018 (ForwardRenderer::anisotropy_for(&caps(granted, 16.0)) - DEFAULT_ANISOTROPY).abs()
18019 < f32::EPSILON,
18020 "a device above the default gets the default"
18021 );
18022 assert!(
18023 (ForwardRenderer::anisotropy_for(&caps(granted, 4.0)) - 4.0).abs() < f32::EPSILON,
18024 "a device below the default gets its own limit"
18025 );
18026 assert!(
18027 (ForwardRenderer::anisotropy_for(&caps(Features::empty(), 16.0)) - 1.0).abs()
18028 < f32::EPSILON,
18029 "a device that was not granted the feature gets one, whatever its limit says"
18030 );
18031 }
18032
18033 /// A new anisotropy is a new sampler, and every slot moves onto it at its
18034 /// own frame — the old one living until the last slot has left it.
18035 ///
18036 /// Counted on the null recorder rather than looked at: the sampler count
18037 /// rises by one at the call, holds through every slot's frame but the
18038 /// last, and falls back there, while the live group count never moves at
18039 /// all — every rebuilt group replaced one. A rebuild that leaked, one that
18040 /// destroyed a group a slot in flight still held, and one that never
18041 /// happened each move one of those counts; a second lap of the ring
18042 /// creating any group at all would be a rebuild that did not know it was
18043 /// done.
18044 #[test]
18045 fn a_new_anisotropy_moves_each_slot_at_its_own_frame_and_retires_the_old() {
18046 let (recorder, device, queue) =
18047 open_with(Features::GPU_DRIVEN.union(Features::SAMPLER_ANISOTROPY));
18048 let device = device.as_ref();
18049 let mut renderer =
18050 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18051 assert!(
18052 (renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON,
18053 "a renderer nobody has called the setter on samples at the default"
18054 );
18055 let samplers = recorder.live_objects(ObjectKind::Sampler);
18056 let groups = recorder.live_objects(ObjectKind::BindGroup);
18057 let groups_created = || {
18058 recorder
18059 .events()
18060 .iter()
18061 .filter(|event| {
18062 matches!(
18063 event,
18064 Event::Created {
18065 kind: ObjectKind::BindGroup,
18066 ..
18067 }
18068 )
18069 })
18070 .count()
18071 };
18072
18073 renderer
18074 .set_anisotropy(device, DEFAULT_ANISOTROPY)
18075 .expect("the device allows it");
18076 assert_eq!(
18077 recorder.live_objects(ObjectKind::Sampler),
18078 samplers,
18079 "the value in force creates nothing"
18080 );
18081
18082 renderer
18083 .set_anisotropy(device, 4.0)
18084 .expect("the device allows it");
18085 assert!((renderer.anisotropy() - 4.0).abs() < f32::EPSILON);
18086 assert_eq!(
18087 recorder.live_objects(ObjectKind::Sampler),
18088 samplers + 1,
18089 "the new sampler stands beside the one every slot still names"
18090 );
18091 assert_eq!(
18092 recorder.live_objects(ObjectKind::BindGroup),
18093 groups,
18094 "no group moves until its slot's frame"
18095 );
18096
18097 for round in 0..FRAMES_IN_FLIGHT {
18098 renderer
18099 .begin_frame(
18100 device,
18101 &Camera::default(),
18102 &DirectionalLight::default(),
18103 (64, 48),
18104 )
18105 .expect("write");
18106 let expected = if round + 1 < FRAMES_IN_FLIGHT {
18107 samplers + 1
18108 } else {
18109 samplers
18110 };
18111 assert_eq!(
18112 recorder.live_objects(ObjectKind::Sampler),
18113 expected,
18114 "round {round}: the replaced sampler lives until the last slot has left it"
18115 );
18116 assert_eq!(
18117 recorder.live_objects(ObjectKind::BindGroup),
18118 groups,
18119 "round {round}: every rebuilt group replaced one"
18120 );
18121 }
18122 let created = groups_created();
18123 for _ in 0..FRAMES_IN_FLIGHT {
18124 renderer
18125 .begin_frame(
18126 device,
18127 &Camera::default(),
18128 &DirectionalLight::default(),
18129 (64, 48),
18130 )
18131 .expect("write");
18132 }
18133 assert_eq!(
18134 groups_created(),
18135 created,
18136 "a slot already on the sampler in force rebuilds nothing"
18137 );
18138
18139 // The clamp: the device's ceiling above it, off below one, the default
18140 // for a value that is not a number.
18141 let ceiling = device.caps().limits.max_sampler_anisotropy;
18142 renderer
18143 .set_anisotropy(device, ceiling * 4.0)
18144 .expect("clamped to what the device allows");
18145 assert!((renderer.anisotropy() - ceiling).abs() < f32::EPSILON);
18146 renderer
18147 .set_anisotropy(device, 0.0)
18148 .expect("one is the value that turns it off");
18149 assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18150 renderer
18151 .set_anisotropy(device, f32::NAN)
18152 .expect("the default is a sampler the device allows");
18153 assert!((renderer.anisotropy() - DEFAULT_ANISOTROPY).abs() < f32::EPSILON);
18154
18155 recorder.assert_valid();
18156 renderer.destroy(device);
18157 assert_eq!(
18158 recorder.live_objects(ObjectKind::Sampler),
18159 0,
18160 "the samplers no slot ever adopted went with the renderer"
18161 );
18162 }
18163
18164 /// A device without the feature samples isotropically whatever is asked:
18165 /// the ceiling is one, so the clamp lands on the value already in force and
18166 /// no sampler is created that `create_sampler` would refuse.
18167 #[test]
18168 fn a_device_without_the_feature_keeps_the_page_isotropic_whatever_is_asked() {
18169 let (recorder, device, queue) = open();
18170 let device = device.as_ref();
18171 assert!(
18172 !device
18173 .caps()
18174 .features
18175 .contains(Features::SAMPLER_ANISOTROPY),
18176 "the default request does not name the feature"
18177 );
18178 let mut renderer =
18179 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18180 assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18181 let samplers = recorder.live_objects(ObjectKind::Sampler);
18182
18183 renderer
18184 .set_anisotropy(device, DEFAULT_ANISOTROPY)
18185 .expect("asks for nothing the device lacks");
18186 assert!((renderer.anisotropy() - 1.0).abs() < f32::EPSILON);
18187 assert_eq!(recorder.live_objects(ObjectKind::Sampler), samplers);
18188 renderer.destroy(device);
18189 }
18190
18191 /// The knob clamps to the range it documents, in both directions and on a
18192 /// value that is neither.
18193 ///
18194 /// **The `NaN` arm is the one worth having.** A slider that divided by a
18195 /// zero, or a settings file that carried a nonsense string, reaches this
18196 /// with a value that fails every comparison it is put through — so a naive
18197 /// `clamp` would keep it, `internal_extent` would multiply by it, and the
18198 /// `as u32` below would produce a zero extent and a device error a long way
18199 /// from here.
18200 #[test]
18201 fn the_render_scale_is_clamped_to_the_range_it_documents() {
18202 let (recorder, device, queue) = open();
18203 let device = device.as_ref();
18204 let mut renderer =
18205 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18206
18207 assert!(
18208 (renderer.render_scale() - 1.0).abs() < f32::EPSILON,
18209 "a renderer nobody has called the setter on draws at full scale"
18210 );
18211
18212 renderer.set_render_scale(0.5);
18213 assert!((renderer.render_scale() - 0.5).abs() < f32::EPSILON);
18214
18215 // Above one is supersampling, which this filter is the wrong one for.
18216 renderer.set_render_scale(2.0);
18217 assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18218
18219 renderer.set_render_scale(0.01);
18220 assert!((renderer.render_scale() - MIN_RENDER_SCALE).abs() < f32::EPSILON);
18221
18222 renderer.set_render_scale(f32::NAN);
18223 assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18224 renderer.set_render_scale(f32::INFINITY);
18225 assert!((renderer.render_scale() - 1.0).abs() < f32::EPSILON);
18226
18227 renderer.destroy(device);
18228 recorder.assert_valid();
18229 }
18230
18231 /// The internal extent is the target rounded, never zero, and is the target
18232 /// itself at full scale.
18233 ///
18234 /// **The floor is not decoration.** A transient image of zero extent is a
18235 /// device error rather than a small frame, and a 4×3 target at the minimum
18236 /// scale is exactly the arithmetic that would produce one.
18237 #[test]
18238 fn the_internal_extent_rounds_and_never_reaches_zero() {
18239 let (recorder, device, queue) = open();
18240 let device = device.as_ref();
18241 let mut renderer =
18242 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18243
18244 assert_eq!(
18245 renderer.internal_extent((1920, 1080)),
18246 (1920, 1080),
18247 "full scale is the absence of the feature, not a resize by one"
18248 );
18249
18250 renderer.set_render_scale(0.5);
18251 assert_eq!(renderer.internal_extent((1920, 1080)), (960, 540));
18252
18253 // Rounds rather than truncating: 1920 * 0.7 is 1344, and 1080 * 0.7 is
18254 // 756 — both exact — so a target that does *not* divide evenly is what
18255 // shows the rounding. 1281 * 0.7 = 896.7.
18256 renderer.set_render_scale(0.7);
18257 assert_eq!(renderer.internal_extent((1281, 1080)), (897, 756));
18258
18259 renderer.set_render_scale(MIN_RENDER_SCALE);
18260 assert_eq!(renderer.internal_extent((4, 3)), (1, 1));
18261 assert_eq!(
18262 renderer.internal_extent((0, 0)),
18263 (1, 1),
18264 "a minimised window is the caller's zero extent, and this may not \
18265 pass it through as one"
18266 );
18267
18268 renderer.destroy(device);
18269 recorder.assert_valid();
18270 }
18271
18272 /// **The upscale is a pass below full scale and is not there above it**, and
18273 /// the frame is otherwise the same list.
18274 ///
18275 /// This is the observable the knob is: everything else about it — the
18276 /// clamps, the rounding — is arithmetic that could be right while the frame
18277 /// went on being drawn at the caller's extent. What says the feature works
18278 /// is that the pass appears, that it appears **last**, and that switching it
18279 /// off leaves the frame that was there before it existed.
18280 #[test]
18281 fn the_upscale_is_the_last_pass_and_only_below_full_scale() {
18282 let _blurs = ssao_blur_switch();
18283 let (recorder, device, queue) = open();
18284 let device = device.as_ref();
18285 let mut renderer =
18286 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18287 let imported = swapchain_image_at(device, TEST_EXTENT);
18288 let pool = crate::TransientPool::new();
18289
18290 let full = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18291 assert!(
18292 !full.contains(&"upscale".to_string()),
18293 "a frame at full scale has no upscale in it: {full:?}"
18294 );
18295
18296 renderer.set_render_scale(0.5);
18297 let scaled = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18298 assert_eq!(
18299 scaled.iter().filter(|label| *label == "upscale").count(),
18300 1,
18301 "a scaled frame records exactly one upscale: {scaled:?}"
18302 );
18303 // Last of the passes that draw. The statistics copy is genuinely after
18304 // it and says so — see the comment on `add_copy_pass`'s placement.
18305 let upscale = scaled
18306 .iter()
18307 .position(|label| label == "upscale")
18308 .expect("the assertion above");
18309 let tonemap = scaled
18310 .iter()
18311 .position(|label| label == "tonemap")
18312 .expect("every frame tonemaps");
18313 assert!(
18314 upscale > tonemap,
18315 "the upscale carries what the post chain ended with: {scaled:?}"
18316 );
18317
18318 // **The pyramid gets shorter, and that is the evidence the rest of the
18319 // frame really is smaller.** Everything above this is about the last
18320 // pass; a knob that added an upscale while going on rendering at the
18321 // caller's extent would pass every one of those assertions and save
18322 // nothing. `crate::hiz`'s chain is as long as the extent allows, so the
18323 // level count is a number read out of the frame that can only be the
18324 // internal extent's.
18325 let levels = |passes: &[String]| {
18326 passes
18327 .iter()
18328 .filter(|label| label.starts_with("hiz-"))
18329 .count()
18330 };
18331 let internal = renderer.internal_extent(TEST_EXTENT);
18332 assert_eq!(levels(&full), crate::hiz::levels_for(TEST_EXTENT) as usize);
18333 assert_eq!(levels(&scaled), crate::hiz::levels_for(internal) as usize);
18334 assert!(
18335 levels(&scaled) < levels(&full),
18336 "at this extent the halved frame has to lose a level, or this \
18337 assertion is not looking at anything: {scaled:?}"
18338 );
18339
18340 // And nothing else moved: an upscale is a pass added to the frame, not a
18341 // frame rebuilt around one. The pyramid is the one part that is a
18342 // function of the extent, so it is compared by the count above and
18343 // dropped from the list here.
18344 let without_hiz = |passes: &[String]| -> Vec<String> {
18345 passes
18346 .iter()
18347 .filter(|label| !label.starts_with("hiz-") && *label != "upscale")
18348 .cloned()
18349 .collect()
18350 };
18351 assert_eq!(
18352 without_hiz(&scaled),
18353 without_hiz(&full),
18354 "the scaled frame is the full-scale frame, one pass longer and one \
18355 pyramid shorter"
18356 );
18357
18358 renderer.set_render_scale(1.0);
18359 let back = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
18360 assert_eq!(
18361 back, full,
18362 "the knob goes back, which is what a settings slider does"
18363 );
18364
18365 renderer.destroy(device);
18366 device.destroy_image_view(imported.view);
18367 device.destroy_image(imported.image);
18368 recorder.assert_valid();
18369 }
18370
18371 /// **A skinned-frame overlay receives the display and depth images at the
18372 /// internal extent, before either resolve reconstructs the target.**
18373 ///
18374 /// The callback's own pass attaches the display and depth it received. That
18375 /// makes matching dimensions a graph invariant rather than a comparison of
18376 /// numbers the callback could have been handed without ever using the
18377 /// images; changing either id to a target-sized image makes compilation
18378 /// refuse the mismatched attachments.
18379 #[test]
18380 fn an_overlay_uses_the_internal_display_and_depth_before_the_resolves() {
18381 let (recorder, device, queue) = open();
18382 let device = device.as_ref();
18383 let mut fixture = SkinnedFixture::build(device, queue);
18384 fixture.renderer.set_render_scale(0.5);
18385 fixture.renderer.set_effect_request(EffectRequest {
18386 antialiasing: Some(Antialiasing::Fxaa),
18387 ..EffectRequest::default()
18388 });
18389 fixture.begin(device);
18390 let internal_extent = fixture.renderer.internal_extent(TEST_EXTENT);
18391
18392 let imported = swapchain_image_at(device, TEST_EXTENT);
18393 let mut pool = crate::TransientPool::new();
18394 {
18395 let mut graph = crate::RenderGraph::new(queue);
18396 let target = graph.import_image("target", imported);
18397 let mut received = None;
18398 fixture.renderer.add_skinned_passes_with_overlay(
18399 &mut graph,
18400 &pool,
18401 target,
18402 TEST_EXTENT,
18403 &fixture.skinning,
18404 |graph, targets| {
18405 received = Some(targets);
18406 graph
18407 .add_render_pass("overlay-probe")
18408 .color(
18409 targets.display,
18410 LoadOp::Load,
18411 StoreOp::Store,
18412 crcbl_hal::ClearValue::default(),
18413 )
18414 .depth_read(targets.depth)
18415 .execute(|_| {});
18416 },
18417 );
18418 let received = received.expect("the overlay callback runs while the frame is built");
18419 assert_eq!(
18420 received.internal_extent, internal_extent,
18421 "the overlay receives the extent its display and depth attachments have"
18422 );
18423
18424 let compiled = graph.compile(&pool).expect("the shared attachments match");
18425 let labels: Vec<&str> = compiled.passes().iter().map(|pass| pass.label()).collect();
18426 let overlay = labels
18427 .iter()
18428 .position(|label| *label == "overlay-probe")
18429 .expect("the callback's pass is part of the frame");
18430 let fxaa = labels
18431 .iter()
18432 .position(|label| *label == "fxaa")
18433 .expect("the requested resolve is part of the frame");
18434 let upscale = labels
18435 .iter()
18436 .position(|label| *label == "upscale")
18437 .expect("the half-scale frame reconstructs its target");
18438 assert!(
18439 overlay < fxaa && overlay < upscale,
18440 "the overlay must write display before its resolve and upscale: {labels:?}"
18441 );
18442 }
18443
18444 fixture.destroy(device);
18445 pool.destroy(device);
18446 device.destroy_image_view(imported.view);
18447 device.destroy_image(imported.image);
18448 recorder.assert_valid();
18449 }
18450
18451 /// **[`ForwardRenderer::MAX_PASSES`] bounds the frame, and lands on it.**
18452 ///
18453 /// It is what a caller sizes [`PassTimers`](crate::PassTimers) with, so both
18454 /// halves matter: a bound under the widest frame times part of it and drops
18455 /// the rest, and a bound well over it buys query sets nothing ever writes.
18456 /// A shadowable spot per light slot fills every one of them, which is the
18457 /// most culls a frame can run and so the widest frame there is — it must land
18458 /// exactly on the constant, and the frame with no shadowed light at all must
18459 /// be short of it by exactly the culls those slots would have added.
18460 ///
18461 /// The ground grid is switched on for **both** frames, because the widest
18462 /// frame is the one that has it: it is off by default and not a
18463 /// [`RenderEffects`] bit, so nothing else here would put its pass in. The
18464 /// debug draw layer is on for both frames for the same reason, and it needs
18465 /// a segment appended before each rather than one switch, because
18466 /// [`begin_frame`](ForwardRenderer::begin_frame) clears its buffer.
18467 ///
18468 /// **And the frames are drawn at [`WIDEST_EXTENT`] rather than at
18469 /// [`TEST_EXTENT`], with every effect forced on and the render scale off
18470 /// full.** The bloom chain's length is a function of the extent the frame is
18471 /// drawn at — see [`crate::bloom`] — so the widest frame this renderer
18472 /// records is a *large* one, and a bound checked against a 64×48 frame would
18473 /// sit six passes above what that frame runs and this assertion would have
18474 /// to be a `<=`. It is an `==` on purpose: a bound well over the widest
18475 /// frame buys query sets nothing writes, and only an exact comparison
18476 /// notices.
18477 ///
18478 /// **The render scale is what makes those two requirements compose.** The
18479 /// upscale is a pass only below full scale, and below full scale the chain
18480 /// runs at the *internal* extent — so a frame with both is one whose
18481 /// internal extent is the longest chain's, and whose target is larger than
18482 /// that. Halving a target of 2048×1024 is what arranges it, and the two
18483 /// assertions below check the arrangement rather than trusting it.
18484 ///
18485 /// [`WIDEST_EXTENT`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
18486 #[test]
18487 fn the_pass_bound_is_the_widest_frame_the_renderer_records() {
18488 /// The extent whose bloom chain is the longest [`crate::bloom`] will
18489 /// build: six halvings of 512 leave sixteen by eight, which is still at
18490 /// or above that module's floor. The widest frame is drawn at this,
18491 /// which is why it is the internal one and not the target.
18492 const WIDEST_INTERNAL: (u32, u32) = (1024, 512);
18493 /// Half, so the frame records an upscale and draws at
18494 /// [`WIDEST_INTERNAL`].
18495 const WIDEST_SCALE: f32 = 0.5;
18496 /// The caller's extent: twice [`WIDEST_INTERNAL`] in each dimension.
18497 const WIDEST_EXTENT: (u32, u32) = (WIDEST_INTERNAL.0 * 2, WIDEST_INTERNAL.1 * 2);
18498
18499 let (recorder, device, queue) = open();
18500 let device = device.as_ref();
18501 // **A scene whose probes ask to be updated**, because the widest frame
18502 // is the one with every pass in it and
18503 // the irradiance probes' two are recorded by a volume
18504 // rather than by an effect bit — the ground grid's argument exactly. A
18505 // renderer built on the demo's empty grid records neither, and the bound
18506 // would then be checked against a frame that could not reach it.
18507 let mut scene = scene::demo();
18508 scene.capacities.probes = 1;
18509 scene.probes = scene::ProbeGrid {
18510 volume: crcbl_shaders::probe::ProbeVolume {
18511 origin: [0.0; 3],
18512 inv_spacing: [1.0; 3],
18513 counts: [1, 1, 1],
18514 levels: 1,
18515 steps: crcbl_shaders::probe::ProbeSteps::default(),
18516 },
18517 probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
18518 update: ProbeUpdate::EveryFrame,
18519 };
18520 let mut renderer =
18521 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, &scene)
18522 .expect("built");
18523 // A maximum-width graph must include actual instances to cull.
18524 place_cube(&mut renderer, Mat4::IDENTITY);
18525 renderer
18526 .set_ground_grid(device, Some(GridStyle::default()))
18527 .expect("the null backend builds every pipeline");
18528 // **And the occlusion cull**, whose late prepass, farthest pyramid and
18529 // three late compute passes are the ground grid's kind of pass: off
18530 // unless a caller asks, and in the widest frame when one does.
18531 renderer.set_occlusion_culling(OcclusionCulling {
18532 occlusion: true,
18533 small_feature_pixels: None,
18534 });
18535 // **A body of water**, on the ground grid's terms: content rather than
18536 // an effect bit, so the widest frame is one a caller gave water to, and
18537 // `Water::PASSES` is in the bound for it.
18538 renderer
18539 .set_water(&[crcbl_water::WaterBody {
18540 outline: vec![[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]],
18541 level: 0.0,
18542 medium: crcbl_water::Medium {
18543 absorption: [0.4, 0.1, 0.05],
18544 scattering: [0.01, 0.01, 0.01],
18545 },
18546 }])
18547 .expect("a square meshes");
18548 // **A field of grass**, on the water body's terms exactly: content
18549 // rather than an effect bit, so the widest frame is one a caller gave a
18550 // field to and `Grass::PASSES` is in the bound for it.
18551 renderer
18552 .set_grass(
18553 device,
18554 queue,
18555 Some(
18556 &crate::grass::GrassField::new(
18557 [1, 1],
18558 4.0,
18559 [-2.0, -2.0],
18560 50.0,
18561 crate::grass::Heightfield {
18562 texels: [4, 4],
18563 metres_per_texel: 1.0,
18564 origin: [-2.0, -2.0],
18565 heights: vec![0.0; 16],
18566 },
18567 crate::grass::CoverMap {
18568 texels: [4, 4],
18569 metres_per_texel: 1.0,
18570 origin: [-2.0, -2.0],
18571 cover: vec![[255, 0]; 16],
18572 },
18573 // A shell row and a mesh blade row, so the widest
18574 // frame records every look's draw the grass pass has.
18575 [
18576 crate::grass::BladeLook::Shells,
18577 crate::grass::BladeLook::Blades,
18578 ]
18579 .map(|look| crate::grass::BladeType {
18580 root_color: [0.05, 0.1, 0.02],
18581 tip_color: [0.3, 0.5, 0.1],
18582 height: 0.3,
18583 half_width: 0.03,
18584 height_spread: 0.3,
18585 width_spread: 0.2,
18586 look,
18587 style: crate::grass::BladeStyle::PLAIN,
18588 shape: crate::grass::BladeShape::STRAIGHT,
18589 clumping: crate::grass::Clumping::NONE,
18590 })
18591 .to_vec(),
18592 )
18593 .expect("a real field"),
18594 ),
18595 )
18596 .expect("the null backend uploads every map");
18597 renderer.set_render_scale(WIDEST_SCALE);
18598 assert_eq!(
18599 renderer.internal_extent(WIDEST_EXTENT),
18600 WIDEST_INTERNAL,
18601 "the scale has to take the target to the extent whose chain is the \
18602 longest one, or the bound below is checked against a frame that \
18603 could not reach it"
18604 );
18605 // **Both post effects forced on.** Neither is in the default camera
18606 // stack — see [`RenderEffects::DEFAULT_STACK`], which leaves the lens out
18607 // for one reason and the resolve out for another — and the widest frame
18608 // is the one that has every effect in it, the ground grid's argument
18609 // exactly.
18610 renderer.set_effect_request(EffectRequest {
18611 programmatic: EffectOverride::none().force(OUTSIDE_THE_DEFAULT, Some(true)),
18612 ..EffectRequest::default()
18613 });
18614 let imported = swapchain_image_at(device, WIDEST_EXTENT);
18615 let mut pool = crate::TransientPool::new();
18616
18617 // The debug draw layer on for both frames below, because it is a pass
18618 // the bound counts and no effect bit switches on — the ground grid's
18619 // argument again. A segment before each, since `begin_frame` clears the
18620 // buffer: the layer is immediate mode.
18621 let switch = debug_draw_switch();
18622 switch.set(true);
18623 // And the occlusion pair's second blur, for exactly that reason: it is a
18624 // pass [`Ssao::MAX_PASSES`] counts and no effect bit switches on, so a
18625 // frame at the shipping count comes one short of the bound and this test
18626 // would be asserting the bound against a frame that could not reach it.
18627 let blurs = ssao_blur_switch();
18628 blurs.set(i64::from(Ssao::MAX_BLUR_PASSES));
18629 // And the comparison seam, which is the occlusion chain's other
18630 // conditional pass — see `crate::ssao`'s `r_ssao_split`. Held for the
18631 // same reason the blur count is: the bound counts a frame that compares,
18632 // so a frame that does not could never reach it.
18633 let split = ssao_split_switch();
18634 split.set(0.5);
18635 renderer
18636 .debug_draw()
18637 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18638 let bare =
18639 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18640 assert_eq!(
18641 crate::bloom::mips_for(WIDEST_INTERNAL),
18642 crate::bloom::MAX_MIPS,
18643 "the widest frame has to be one whose chain is the longest one there \
18644 is, or the bound below is checked against a frame that could not \
18645 reach it"
18646 );
18647 assert!(
18648 bare < ForwardRenderer::MAX_PASSES as usize,
18649 "a frame with no shadowed light runs {bare} passes, which is already the \
18650 bound of {} — then the bound does not cover the slots this scene left free",
18651 ForwardRenderer::MAX_PASSES
18652 );
18653
18654 // One spot per slot, spaced so no two of them share an influence — the
18655 // list has to fill every slot or the bound below is checked against a
18656 // frame that could not reach it.
18657 #[expect(
18658 clippy::cast_precision_loss,
18659 reason = "a handful of slots, and the value is only a position"
18660 )]
18661 let spots: Vec<Light> = (0..shadow::LIGHT_SLOTS)
18662 .map(|slot| shadowable_spot(1.0 + slot as f32))
18663 .collect();
18664 renderer.set_lights(&spots);
18665 renderer
18666 .debug_draw()
18667 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
18668 let widest =
18669 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, WIDEST_EXTENT).len();
18670 assert_eq!(
18671 renderer.shadow_lights.slots().iter().flatten().count(),
18672 shadow::LIGHT_SLOTS,
18673 "the spots must actually hold every slot, or this is the bare frame again \
18674 under another name"
18675 );
18676 assert_eq!(
18677 widest,
18678 ForwardRenderer::MAX_PASSES as usize,
18679 "the widest frame is what the bound is for"
18680 );
18681 assert_eq!(
18682 widest - bare,
18683 DrawGen::MAX_PASSES as usize * shadow::LIGHT_SLOTS,
18684 "a filled slot costs a cull's passes and nothing else"
18685 );
18686
18687 renderer.destroy(device);
18688 pool.destroy(device);
18689 device.destroy_image_view(imported.view);
18690 device.destroy_image(imported.image);
18691 recorder.assert_valid();
18692 }
18693
18694 /// **A toggle reaches the recorded frame, and takes exactly its own passes
18695 /// with it.**
18696 ///
18697 /// The observable is the compiled pass list, because the thing that could
18698 /// otherwise be true is that the switch is stored and read by nothing: a
18699 /// renderer holding `SHADOWS` clear and recording every shadow cull anyway
18700 /// draws a frame that looks right, reports the right effect set, and has not
18701 /// switched anything off.
18702 ///
18703 /// So each arm compares the whole list rather than its length. Two passes
18704 /// fewer is satisfied by removing the wrong two, and it is satisfied by a
18705 /// frame that lost its tonemap.
18706 ///
18707 /// The shadow arm is the one that cannot be written by name — a cascade's
18708 /// cull passes are labelled exactly as the camera's are — so it is written as
18709 /// its two halves instead: the count moves by a cull's worth per cascade and
18710 /// per filled light slot, and everything from the `shadow` pass onwards is
18711 /// unchanged. The `shadow` pass itself **stays**, because it is what writes
18712 /// the clear that reads as "fully lit".
18713 #[test]
18714 fn each_effect_toggle_removes_exactly_the_passes_it_owns() {
18715 let _blurs = ssao_blur_switch();
18716 let (recorder, device, queue) = open();
18717 let device = device.as_ref();
18718 let mut renderer =
18719 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18720 place_cube(&mut renderer, Mat4::IDENTITY);
18721 // One shadowed light beside the cascades, so the shadow arm below covers
18722 // a light slot's cull as well as a cascade's.
18723 renderer.set_lights(&[shadowable_spot(-1.0)]);
18724 let imported = swapchain_image(device);
18725 let mut pool = crate::TransientPool::new();
18726
18727 // [`OUTSIDE_THE_DEFAULT`] forced on and then `off` forced off, on
18728 // [`frame_switching_off`]'s terms exactly: the default camera stack
18729 // leaves both of them out — see [`RenderEffects::DEFAULT_STACK`] — so a
18730 // control built on the default alone would have nothing for their arms
18731 // to remove. `force` clears the other side, so an arm whose `off` is one
18732 // of them still resolves to off.
18733 //
18734 // [`frame_switching_off`]: fn@frame_switching_off
18735 let without = |renderer: &mut ForwardRenderer, off: RenderEffects| {
18736 renderer.set_effect_request(EffectRequest {
18737 programmatic: EffectOverride::none()
18738 .force(OUTSIDE_THE_DEFAULT, Some(true))
18739 .force(off, Some(false)),
18740 ..EffectRequest::default()
18741 });
18742 passes_in_a_frame(device, queue, renderer, imported, &pool, TEST_EXTENT)
18743 };
18744
18745 let all_on = without(&mut renderer, RenderEffects::empty());
18746 assert_eq!(
18747 renderer.effects(),
18748 RenderEffects::all(),
18749 "the control frame has to be the every-effect one"
18750 );
18751 assert_eq!(
18752 renderer.shadow_lights.slots().iter().flatten().count(),
18753 1,
18754 "the spot must actually hold a slot, or the shadow arm below is only about cascades"
18755 );
18756
18757 // **None of the three leaves anything behind it**, and for the same
18758 // reason: nothing reads what it would have written. The occlusion pair's
18759 // reader binds the 1×1 white placeholder instead — `mesh.slang` clamps
18760 // its `Load` into it — and the reflection pair's and the chain's readers
18761 // both tonemap whatever image they would have read anyway.
18762 //
18763 // The chain's labels are written out rather than built from
18764 // `crate::bloom`'s arithmetic, because a table generated from the code
18765 // under test cannot fail: it is `TEST_EXTENT`'s two levels — two
18766 // downsamples, the one upsample between them, and the composite — and if
18767 // that extent moves this is the assertion that says so.
18768 for (off, gone) in [
18769 (
18770 RenderEffects::AMBIENT_OCCLUSION,
18771 ["ssao", "ssao-blur", "ssao-upsample"].as_slice(),
18772 ),
18773 (
18774 RenderEffects::CONTACT_SHADOWS,
18775 // One pass and no blur — `crate::contact_shadows`'s header says
18776 // why the occlusion pair's second pass has no counterpart here.
18777 ["contact-shadows"].as_slice(),
18778 ),
18779 (
18780 RenderEffects::REFLECTIONS,
18781 // **The pyramid goes with the march**, which is the whole of
18782 // what makes it an optimisation rather than a resource: it is
18783 // recorded on the frames that reflect and on no others. Two
18784 // levels at `TEST_EXTENT`, written out on the chain's terms
18785 // above.
18786 ["hiz-1", "hiz-2", "ssr", "ssr-blur"].as_slice(),
18787 ),
18788 (
18789 RenderEffects::BLOOM,
18790 [
18791 "bloom-down-1",
18792 "bloom-down-2",
18793 "bloom-up-1",
18794 "bloom-composite",
18795 ]
18796 .as_slice(),
18797 ),
18798 (
18799 RenderEffects::AUTO_EXPOSURE,
18800 // All three go together and the tonemap stays: the pass reads
18801 // the measurement only when the block says to, and the block
18802 // says so on exactly the frames these three ran on.
18803 ["exposure-clear", "exposure-histogram", "exposure-reduce"].as_slice(),
18804 ),
18805 ] {
18806 let labels = without(&mut renderer, off);
18807 assert_eq!(
18808 renderer.effects(),
18809 RenderEffects::all().difference(off),
18810 "{off:?}: the frame must have resolved to the set the request asked for"
18811 );
18812 // **The control frame has to contain what this arm removes**, and
18813 // that is not a restatement of the comparison below: the comparison
18814 // builds `expected` by filtering `gone` out of `all_on`, so an arm
18815 // naming a pass the control never recorded filters nothing, matches,
18816 // and passes whether the effect draws anything or not. Removing the
18817 // resolve pass entirely left this loop green until this assertion
18818 // existed.
18819 for label in gone {
18820 assert!(
18821 all_on.iter().any(|recorded| recorded == label),
18822 "{off:?}: the every-effect frame does not record `{label}`, so removing it \
18823 below proves nothing: {all_on:#?}"
18824 );
18825 }
18826 let expected: Vec<String> = all_on
18827 .iter()
18828 .filter(|label| !gone.contains(&label.as_str()))
18829 .cloned()
18830 .collect();
18831 assert_eq!(
18832 labels, expected,
18833 "{off:?}: the frame must lose {gone:?}, gain nothing in their place, and keep \
18834 every other pass"
18835 );
18836 }
18837
18838 // **The two antialiasing tiers share one resolve slot**, so neither is
18839 // a plain removal and neither belongs in the loop above: switching
18840 // CMAA2 off while FXAA stays on swaps three passes for one rather than
18841 // losing three, and the loop's "gain nothing in their place" comparison
18842 // is exactly what that violates. Three frames say it instead.
18843 let both = all_on.clone();
18844 let cheap = without(&mut renderer, RenderEffects::CMAA2);
18845 let neither = without(
18846 &mut renderer,
18847 RenderEffects::CMAA2.union(RenderEffects::ANTIALIASING),
18848 );
18849 const CMAA2_PASSES: [&str; 3] = ["cmaa2-edges", "cmaa2-shapes", "cmaa2-apply"];
18850 let resolve_of = |labels: &[String]| -> Vec<String> {
18851 labels
18852 .iter()
18853 .filter(|label| *label == "fxaa" || CMAA2_PASSES.contains(&label.as_str()))
18854 .cloned()
18855 .collect()
18856 };
18857 let without_resolve = |labels: &[String]| -> Vec<String> {
18858 labels
18859 .iter()
18860 .filter(|label| *label != "fxaa" && !CMAA2_PASSES.contains(&label.as_str()))
18861 .cloned()
18862 .collect()
18863 };
18864 assert_eq!(
18865 resolve_of(&both),
18866 CMAA2_PASSES.map(str::to_string).to_vec(),
18867 "with both bits set the higher tier takes the slot and the cheap one \
18868 records nothing"
18869 );
18870 assert_eq!(
18871 resolve_of(&cheap),
18872 vec!["fxaa".to_string()],
18873 "with only the cheap bit set the slot is FXAA's"
18874 );
18875 assert!(
18876 resolve_of(&neither).is_empty(),
18877 "with neither bit set the frame has no resolve at all: {neither:#?}"
18878 );
18879 // And nothing else moved: the tiers swap in one slot rather than
18880 // rebuilding the frame around themselves.
18881 assert_eq!(without_resolve(&both), without_resolve(&cheap));
18882 assert_eq!(without_resolve(&both), without_resolve(&neither));
18883 // The slot is where the ordering argument puts it — directly after the
18884 // last pass that writes the display image, which at this extent is the
18885 // tonemap.
18886 for labels in [&both, &cheap] {
18887 let at = labels
18888 .iter()
18889 .position(|label| label == "tonemap")
18890 .expect("a frame has to reach the swapchain");
18891 assert_eq!(
18892 &labels[at + 1..=at + resolve_of(labels).len()],
18893 resolve_of(labels).as_slice(),
18894 "the resolve must follow the tonemap: {labels:#?}"
18895 );
18896 }
18897
18898 let no_shadows = without(&mut renderer, RenderEffects::SHADOWS);
18899 assert_eq!(
18900 renderer.effects(),
18901 RenderEffects::all().difference(RenderEffects::SHADOWS),
18902 );
18903 assert_eq!(
18904 all_on.len() - no_shadows.len(),
18905 DrawGen::MAX_PASSES as usize * (shadow::CASCADES + 1),
18906 "shadows off must drop a cull's passes per cascade and per filled slot"
18907 );
18908 let from_the_atlas = |labels: &[String]| {
18909 let at = labels
18910 .iter()
18911 .position(|label| label == "shadow")
18912 .expect("the atlas pass is recorded whether or not anything draws into it");
18913 labels[at..].to_vec()
18914 };
18915 assert_eq!(
18916 from_the_atlas(&no_shadows),
18917 from_the_atlas(&all_on),
18918 "only the culls go: the atlas pass and everything after it are unchanged"
18919 );
18920
18921 renderer.destroy(device);
18922 pool.destroy(device);
18923 device.destroy_image_view(imported.view);
18924 device.destroy_image(imported.image);
18925 recorder.assert_valid();
18926 }
18927
18928 /// **The contact march is a pass a frame records only when it was asked
18929 /// for, and the mask it writes is what the forward pass then reads.**
18930 ///
18931 /// Two observables, because either alone is satisfied by a mistake the other
18932 /// one catches:
18933 ///
18934 /// * **The compiled pass list.** `contact-shadows` appears between the
18935 /// prepass whose depth it marches and the forward pass that binds it, and
18936 /// appears at all only on the frame that asked. The toggle test above
18937 /// already says a frame loses this pass and nothing else; what is added
18938 /// here is *where* it sits, which is the half a set comparison cannot see
18939 /// — a march recorded after the pass that reads it compiles and draws a
18940 /// mask nothing ever looks at.
18941 /// * **The forward pass's own barriers.** On the frame that marched, one
18942 /// more image is transitioned into [`ResourceState::ShaderRead`] before
18943 /// the forward pass opens than on the frame that did not — which is the
18944 /// mask leaving the colour attachment it was written as. That is what says
18945 /// the pass's output reaches the shading, rather than being written into a
18946 /// transient and dropped while the shader goes on reading the 1×1
18947 /// placeholder. The placeholder is imported in `ShaderRead` already and
18948 /// needs no transition, so it contributes nothing to this count and the
18949 /// difference is exactly the mask.
18950 ///
18951 /// [`RenderEffects::CONTACT_SHADOWS`] is out of the default camera stack
18952 /// while its re-bless is pending — see that constant — so the `on` frame has
18953 /// to force it and the `off` frame is what a view saying nothing draws.
18954 #[test]
18955 fn the_contact_march_is_recorded_only_when_asked_and_its_mask_reaches_the_forward_pass() {
18956 let (recorder, device, queue) = open();
18957 let device = device.as_ref();
18958 let mut renderer =
18959 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
18960 let imported = swapchain_image(device);
18961 let mut pool = crate::TransientPool::new();
18962
18963 let frame = |renderer: &mut ForwardRenderer, on: bool| -> (Vec<String>, usize) {
18964 renderer.set_effect_request(EffectRequest {
18965 programmatic: EffectOverride::none()
18966 .force(RenderEffects::CONTACT_SHADOWS, Some(on)),
18967 ..EffectRequest::default()
18968 });
18969 renderer
18970 .begin_frame(
18971 device,
18972 &Camera::default(),
18973 &DirectionalLight::default(),
18974 TEST_EXTENT,
18975 )
18976 .expect("write");
18977 let mut graph = crate::RenderGraph::new(queue);
18978 let target = graph.import_image("target", imported);
18979 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
18980 let compiled = graph.compile(&pool).expect("a legal frame");
18981 let labels: Vec<String> = compiled
18982 .passes()
18983 .iter()
18984 .map(|pass| pass.label().to_string())
18985 .collect();
18986 let readable = compiled
18987 .passes()
18988 .iter()
18989 .find(|pass| pass.label() == "forward")
18990 .expect("every frame draws its geometry")
18991 .barriers()
18992 .images
18993 .iter()
18994 .filter(|barrier| barrier.to == ResourceState::ShaderRead)
18995 .count();
18996 (labels, readable)
18997 };
18998
18999 let (marched, marched_reads) = frame(&mut renderer, true);
19000 assert!(
19001 renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19002 "the forced frame has to have resolved with the bit set"
19003 );
19004 let (bare, bare_reads) = frame(&mut renderer, false);
19005 assert!(
19006 !renderer.effects().contains(RenderEffects::CONTACT_SHADOWS),
19007 "and the control frame without it"
19008 );
19009
19010 assert!(
19011 !bare.iter().any(|label| label == "contact-shadows"),
19012 "a frame that did not ask must record no march at all: {bare:#?}"
19013 );
19014 let at = |labels: &[String], wanted: &str| {
19015 labels
19016 .iter()
19017 .position(|label| label == wanted)
19018 .unwrap_or_else(|| panic!("no `{wanted}` pass in {labels:#?}"))
19019 };
19020 let march = at(&marched, "contact-shadows");
19021 assert!(
19022 march > at(&marched, "depth-prepass"),
19023 "the march reads the prepass's depth, so it cannot precede it: {marched:#?}"
19024 );
19025 assert!(
19026 march < at(&marched, "forward"),
19027 "and the forward pass binds what it wrote, so it cannot follow it: {marched:#?}"
19028 );
19029
19030 assert_eq!(
19031 marched_reads,
19032 bare_reads + 1,
19033 "the forward pass has to take one more image into `ShaderRead` on the frame that \
19034 marched — the mask. Equal counts mean the pass wrote a transient the shading \
19035 never reads."
19036 );
19037
19038 renderer.destroy(device);
19039 pool.destroy(device);
19040 device.destroy_image_view(imported.view);
19041 device.destroy_image(imported.image);
19042 recorder.assert_valid();
19043 }
19044
19045 /// **The ground grid is off until a caller asks, and then it is the last
19046 /// pass of the frame — after the tonemap.**
19047 ///
19048 /// Three claims and each is a separate way to get this wrong. Off by default
19049 /// is what keeps every sample and every golden image where they were. *After
19050 /// the tonemap* is the placement decision: added a line earlier it would
19051 /// draw into the HDR scene colour and be tonemapped like geometry, which
19052 /// compiles, draws a grid, and gives it a colour that moves with the
19053 /// exposure. And switching it off again has to remove the pass, not merely
19054 /// stop reporting it.
19055 ///
19056 /// The whole list is compared rather than its length, for the reason the
19057 /// effect-toggle test gives: one more pass is satisfied by gaining the wrong
19058 /// one.
19059 #[test]
19060 fn the_ground_grid_is_opt_in_and_lands_after_the_tonemap() {
19061 let _blurs = ssao_blur_switch();
19062 let (recorder, device, queue) = open();
19063 let device = device.as_ref();
19064 let mut renderer =
19065 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19066 let imported = swapchain_image(device);
19067 let mut pool = crate::TransientPool::new();
19068
19069 let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19070 assert!(
19071 renderer.ground_grid().is_none(),
19072 "a renderer nobody asked has no grid"
19073 );
19074 assert!(
19075 !off.contains(&"grid".to_string()),
19076 "the grid must not be in a frame nobody asked for it in: {off:#?}"
19077 );
19078
19079 renderer
19080 .set_ground_grid(device, Some(GridStyle::default()))
19081 .expect("the null backend builds every pipeline");
19082 assert_eq!(renderer.ground_grid(), Some(&GridStyle::default()));
19083 let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19084
19085 let mut expected = off.clone();
19086 // The statistics copy is added after every render pass and stays last —
19087 // see `add_passes`. So the grid goes in front of it, which is directly
19088 // after the tonemap.
19089 let tonemap = expected
19090 .iter()
19091 .position(|label| label == "tonemap")
19092 .expect("a frame has to reach the swapchain");
19093 expected.insert(tonemap + 1, "grid".to_string());
19094 assert_eq!(
19095 on, expected,
19096 "the grid must be the one pass gained, and it must sit after the tonemap"
19097 );
19098
19099 renderer
19100 .set_ground_grid(device, None)
19101 .expect("switching off builds nothing");
19102 assert!(renderer.ground_grid().is_none());
19103 assert_eq!(
19104 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
19105 off,
19106 "switching the grid off has to remove its pass, not just stop reporting it"
19107 );
19108
19109 renderer.destroy(device);
19110 pool.destroy(device);
19111 device.destroy_image_view(imported.view);
19112 device.destroy_image(imported.image);
19113 recorder.assert_valid();
19114 }
19115
19116 /// **A second occlusion blur is a pass the frame records, an image it takes
19117 /// out of the pool, and a triangle its counter reports** — or it is a switch
19118 /// that does nothing.
19119 ///
19120 /// `crcbl`'s `forward_e2e::occlusion` measures what the second blur is worth
19121 /// by driving the pipelines itself, so nothing there would notice that a
19122 /// real frame never records it. The three things below are what a frame has
19123 /// to do differently, and each of them fails silently on its own: a missing
19124 /// pass draws a slightly rougher picture, a missing image is a bind of the
19125 /// wrong one, and a counter short by one is a number nobody reads until it
19126 /// is quoted.
19127 ///
19128 /// **This test owns `r_ssao_blur_passes` for its duration**, through
19129 /// [`ssao_blur_switch`] and for [`debug_draw_switch`]'s reason.
19130 /// The id [`Ssao::add_passes`] hands back is the reconstruction's target,
19131 /// whichever blur ran into it.
19132 ///
19133 /// **The one thing about that chain no other check can see.** The pass list
19134 /// is identical either way, the graph accepts a written-and-never-read
19135 /// transient without complaint, and every golden is at one blur where the
19136 /// two blur answers coincide — so a frame bound to the wrong image draws
19137 /// something nobody would question, which is exactly what the function's
19138 /// own doc warns about. Verified 2026-08-31 by returning `blurred` from the
19139 /// two-blur arm: `crcbl-render`'s unit tests, the forward and mesh e2e
19140 /// suites and lantern's golden all stayed green.
19141 ///
19142 /// **Since the halving it is a second silent failure and a louder one.**
19143 /// Every working image is [`crate::ssao::half_extent`] of the frame, so a
19144 /// returned working id is not merely a rougher channel — it is an image a
19145 /// quarter of the size bound where `mesh.slang` reads at `SV_Position`,
19146 /// which its clamp turns into occlusion smeared over the top-left quarter of
19147 /// the frame rather than into an error.
19148 #[test]
19149 fn the_occlusion_id_handed_back_is_the_reconstruction_target() {
19150 let (_recorder, device, queue) = open();
19151 let device = device.as_ref();
19152 let mut ssao = Ssao::new(device, 1, ForwardRenderer::build_fullscreen).expect("built");
19153 let gathered = crate::ssao::half_extent(TEST_EXTENT);
19154
19155 let one = {
19156 let mut graph = crate::RenderGraph::new(queue);
19157 let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19158 let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19159 let blurred =
19160 graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19161 let upsampled = graph.create_image(
19162 "ssao-upsampled",
19163 crate::targets::ambient_occlusion(TEST_EXTENT),
19164 );
19165 let got = ssao.add_passes(
19166 &mut graph,
19167 0,
19168 TEST_EXTENT,
19169 depth,
19170 crate::ssao::OcclusionImages {
19171 raw,
19172 blurred,
19173 again: None,
19174 upsampled,
19175 },
19176 );
19177 (got == upsampled, got == blurred || got == raw)
19178 };
19179 assert!(one.0, "one blur finishes in the reconstruction's image");
19180 assert!(
19181 !one.1,
19182 "and never in one of the half-extent images the chain worked in"
19183 );
19184
19185 let two = {
19186 let mut graph = crate::RenderGraph::new(queue);
19187 let depth = graph.create_image("scene-depth", crate::targets::scene_depth(TEST_EXTENT));
19188 let raw = graph.create_image("ssao", crate::targets::ambient_occlusion(gathered));
19189 let blurred =
19190 graph.create_image("ssao-blurred", crate::targets::ambient_occlusion(gathered));
19191 let again = graph.create_image(
19192 "ssao-blurred-2",
19193 crate::targets::ambient_occlusion(gathered),
19194 );
19195 let upsampled = graph.create_image(
19196 "ssao-upsampled",
19197 crate::targets::ambient_occlusion(TEST_EXTENT),
19198 );
19199 let got = ssao.add_passes(
19200 &mut graph,
19201 0,
19202 TEST_EXTENT,
19203 depth,
19204 crate::ssao::OcclusionImages {
19205 raw,
19206 blurred,
19207 again: Some(again),
19208 upsampled,
19209 },
19210 );
19211 (got == upsampled, got == again || got == blurred)
19212 };
19213 assert!(
19214 two.0,
19215 "two blurs finish in the reconstruction's image as well, which is the id the forward \
19216 pass binds"
19217 );
19218 assert!(
19219 !two.1,
19220 "and not in a blur's own image -- a frame bound to one of those is a frame nobody \
19221 would question"
19222 );
19223 }
19224
19225 /// **The gather runs at half the frame and the reconstruction runs at all
19226 /// of it** — or the halving is a description nobody rendered into.
19227 ///
19228 /// The pass list cannot see this: three passes with the right labels in the
19229 /// right order is exactly what a chain that halved nothing would record. The
19230 /// **render area** is where the halving is observable, and the graph derives
19231 /// it from each pass's colour attachment — so this is the check that the
19232 /// transients [`ForwardRenderer::add_passes`] created are the ones
19233 /// [`crate::ssao::half_extent`] sized, and that the reconstruction was given
19234 /// the frame-sized one.
19235 ///
19236 /// Neither mistake is an error anywhere else. Working images at the frame's
19237 /// extent are four times the march and a reconstruction reading the corner
19238 /// of its input; a frame-sized image handed to the march and a half-sized
19239 /// one to the forward pass is occlusion smeared over a quarter of the
19240 /// picture by `mesh.slang`'s clamp. Both are pictures.
19241 ///
19242 /// **This test owns `r_ssao_blur_passes` for its duration**, through
19243 /// [`ssao_blur_switch`] and for that function's second reason: it looks the
19244 /// occlusion chain's passes up by name, and a second blur arriving from
19245 /// another thread's switch is a pass this frame did not ask for.
19246 #[test]
19247 fn the_occlusion_chain_gathers_at_half_the_frame_and_reconstructs_at_all_of_it() {
19248 let _switch = ssao_blur_switch();
19249
19250 let (recorder, device, queue) = open();
19251 let device = device.as_ref();
19252 let mut renderer =
19253 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19254 let imported = swapchain_image(device);
19255 let mut pool = crate::TransientPool::new();
19256 renderer
19257 .begin_frame(
19258 device,
19259 &Camera::default(),
19260 &DirectionalLight::default(),
19261 TEST_EXTENT,
19262 )
19263 .expect("write");
19264 let mut graph = crate::RenderGraph::new(queue);
19265 let target = graph.import_image("target", imported);
19266 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
19267 let compiled = graph.compile(&pool).expect("a legal frame");
19268 let area_of = |label: &str| {
19269 let pass = compiled
19270 .passes()
19271 .iter()
19272 .find(|pass| pass.label() == label)
19273 .unwrap_or_else(|| panic!("the frame records no `{label}` pass at all"));
19274 let area = pass.render_area();
19275 (area.width, area.height)
19276 };
19277
19278 let gathered = crate::ssao::half_extent(TEST_EXTENT);
19279 assert_ne!(
19280 gathered, TEST_EXTENT,
19281 "the fixture extent has to halve to something else, or every assertion below holds \
19282 of a chain that halved nothing"
19283 );
19284 assert_eq!(
19285 area_of("ssao"),
19286 gathered,
19287 "the march has to run over the gather extent"
19288 );
19289 assert_eq!(
19290 area_of("ssao-blur"),
19291 gathered,
19292 "and so does the blur over what the march wrote"
19293 );
19294 assert_eq!(
19295 area_of("ssao-upsample"),
19296 TEST_EXTENT,
19297 "the reconstruction writes the channel `mesh.slang` reads at `SV_Position`, so it \
19298 runs at the frame's own extent"
19299 );
19300
19301 drop(compiled);
19302 renderer.destroy(device);
19303 pool.destroy(device);
19304 device.destroy_image_view(imported.view);
19305 device.destroy_image(imported.image);
19306 recorder.assert_valid();
19307 }
19308
19309 /// **The comparison seam records a second march, scissored to the columns
19310 /// the first one was kept off.**
19311 ///
19312 /// `crate::split`'s geometry, read off the encoder rather than off the code
19313 /// that drove it: two passes, and two `SetScissor` rectangles that tile the
19314 /// gather extent between them.
19315 ///
19316 /// **What this cannot see is which block each march bound.** The reference
19317 /// backend records a bind group as a handle and a layout, not as the
19318 /// resources behind it, so pointing both marches at one buffer leaves this
19319 /// test green — measured, by doing exactly that. The group inequality below
19320 /// is kept because it is free and would catch the two marches sharing a
19321 /// cache, which is a different fault; what covers the blocks is
19322 /// `crate::ssao`'s `the_seams_other_side_is_what_the_chain_ships`, and what
19323 /// is not covered at all is the wiring between them. `docs/backlog.md`
19324 /// carries that gap.
19325 ///
19326 /// **The control is the same frame without a seam**, and it is what makes
19327 /// the assertions mean anything: a chain that scissored unconditionally
19328 /// would satisfy every claim below and change every golden in the workspace,
19329 /// so the frame nobody asked to compare has to record one march and set no
19330 /// rectangle at all.
19331 ///
19332 /// Holds [`ssao_split_switch`] for [`ssao_blur_switch`]'s reason: the seam
19333 /// is process-wide state and a frame that picked one up from another
19334 /// thread's test is a frame with a pass this one did not ask for.
19335 #[test]
19336 fn the_comparison_seam_marches_twice_over_columns_that_tile_the_gather() {
19337 use crcbl_hal::null::Command;
19338
19339 let _blurs = ssao_blur_switch();
19340 let split = ssao_split_switch();
19341 // Third, after the two above: the only other test that takes this one
19342 // takes it alone, so this is the whole order and there is no cycle in
19343 // it. Moved below, because two blocks holding the same scalars are
19344 // equal whatever the seam did.
19345 let slices = ssao_slice_switch();
19346 // The count the seam's far side reads, and one that is not it. Read off
19347 // the variable rather than written down: which end of the range ships
19348 // has changed once already, and a test naming the wrong end would be
19349 // comparing the shipped configuration against itself.
19350 let ships = match crate::ssao::r_ssao_slices.default() {
19351 crcbl_console::Value::Int(count) => *count,
19352 other => panic!("`r_ssao_slices` defaults to {other:?}, which is not a count"),
19353 };
19354 let moved = if ships == i64::from(ssao::SLICE_COUNT_MAX) {
19355 i64::from(ssao::SLICE_COUNT_DEFAULT)
19356 } else {
19357 i64::from(ssao::SLICE_COUNT_MAX)
19358 };
19359 assert_ne!(
19360 ships, moved,
19361 "the two slice counts this compares are one count, so the blocks below would differ \
19362 by nothing whatever the seam did"
19363 );
19364 slices.set(ships);
19365
19366 let gathered = crate::ssao::half_extent(TEST_EXTENT);
19367 // One entry per march the frame recorded: the last rectangle that pass
19368 // left the scissor at, and the group it bound.
19369 //
19370 // **The last and not the only one.** The graph opens every pass with a
19371 // scissor over the whole render area, so a march that sets none of its
19372 // own still records one — which is why "did it scissor at all" is not
19373 // the question and "what did it end up cropped to" is.
19374 let marches = |recorder: &Recorder, from: usize| {
19375 let mut inside = false;
19376 let mut found: Vec<(crcbl_hal::Rect2d, crcbl_hal::BindGroupHandle)> = Vec::new();
19377 let mut rect = None;
19378 let mut group = None;
19379 for command in &recorder.commands()[from..] {
19380 if let Some((_, label)) = command.opens_pass() {
19381 inside = matches!(label, Some("ssao" | "ssao-shipped"));
19382 (rect, group) = (None, None);
19383 continue;
19384 }
19385 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19386 if let (true, Some(rect), Some(group)) = (inside, rect, group) {
19387 found.push((rect, group));
19388 }
19389 inside = false;
19390 continue;
19391 }
19392 if !inside {
19393 continue;
19394 }
19395 match command {
19396 Command::SetScissor(at) => rect = Some(*at),
19397 Command::BindGroup { group: bound, .. } => group = Some(*bound),
19398 _ => {}
19399 }
19400 }
19401 found
19402 };
19403
19404 let (recorder, device, queue) = open();
19405 let device = device.as_ref();
19406 let mut renderer =
19407 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19408
19409 split.set(0.0);
19410 let alone = frame_seen_from(
19411 device,
19412 &mut renderer,
19413 queue,
19414 &Camera::default(),
19415 &DirectionalLight::default(),
19416 );
19417 let plain = marches(&recorder, 0);
19418 let after = recorder.commands().len();
19419 let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19420 let (uncompared_console, uncompared_shipped) = (
19421 recorder.buffer_bytes(console).expect("the console's block"),
19422 recorder.buffer_bytes(shipped).expect("the seam's block"),
19423 );
19424 alone.release(device);
19425
19426 split.set(0.5);
19427 slices.set(moved);
19428 let frame = frame_seen_from(
19429 device,
19430 &mut renderer,
19431 queue,
19432 &Camera::default(),
19433 &DirectionalLight::default(),
19434 );
19435 let compared = marches(&recorder, after);
19436 let (console, shipped) = renderer.primary.ssao.blocks(renderer.frame);
19437 let (compared_console, compared_shipped) = (
19438 recorder.buffer_bytes(console).expect("the console's block"),
19439 recorder.buffer_bytes(shipped).expect("the seam's block"),
19440 );
19441 frame.finish(device, renderer);
19442
19443 assert_eq!(
19444 plain.len(),
19445 1,
19446 "a frame comparing nothing recorded {} march(es); the seam is off, so there is one",
19447 plain.len()
19448 );
19449 assert_eq!(
19450 (
19451 plain[0].0.x,
19452 plain[0].0.y,
19453 plain[0].0.width,
19454 plain[0].0.height
19455 ),
19456 (0, 0, gathered.0, gathered.1),
19457 "a frame comparing nothing left its march cropped to something other than the whole \
19458 gather extent {gathered:?} — so the chain crops whether or not anybody asked it to, \
19459 and every golden in this workspace was blessed on a frame that does not"
19460 );
19461
19462 assert_eq!(
19463 compared.len(),
19464 2,
19465 "a frame comparing two configurations recorded {} march(es)",
19466 compared.len()
19467 );
19468 let (left, right) = (compared[0].0, compared[1].0);
19469 assert_eq!(
19470 (left.x, left.y, right.y),
19471 (0, 0, 0),
19472 "both halves start at the top and the left one at the edge"
19473 );
19474 assert_eq!(
19475 i64::from(right.x),
19476 i64::from(left.width),
19477 "the second march starts where the first one ended, or a column is drawn twice"
19478 );
19479 assert_eq!(
19480 (left.width + right.width, left.height, right.height),
19481 (gathered.0, gathered.1, gathered.1),
19482 "the two rectangles have to cover the gather extent {gathered:?} exactly"
19483 );
19484 assert!(
19485 left.width < gathered.0 && right.width < gathered.0,
19486 "one half covers the whole extent, so the other draws over it and the seam is a \
19487 rectangle that crops nothing"
19488 );
19489 assert_ne!(
19490 compared[0].1, compared[1].1,
19491 "the two marches bound one group, so they cannot be reading two blocks"
19492 );
19493
19494 // How far the reference backend can follow the far side. It will say
19495 // what bytes a buffer holds and it will not say which buffer a group
19496 // names, so the two together are "there are two blocks, and they differ
19497 // by the knob that was moved" — not "the right march read the right
19498 // one". Pointing both marches at one buffer still passes; see this
19499 // module's entry in `docs/backlog.md`.
19500 assert_eq!(
19501 uncompared_console, uncompared_shipped,
19502 "the console sat at its defaults and the two blocks still differ, so the seam's far \
19503 side is not this frame with the shipped scalars — it is another frame"
19504 );
19505 assert_ne!(
19506 compared_console, compared_shipped,
19507 "one slice count was moved off the shipped one and both blocks still hold the same \
19508 bytes, so a comparison shows the same picture twice"
19509 );
19510
19511 recorder.assert_valid();
19512 }
19513
19514 /// Every gather pipeline the frame bound, in the order the marches ran.
19515 ///
19516 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]'s
19517 /// `marches` closure asking the other question of the same stream: that one
19518 /// reads the scissor and the group, and this one reads the pipeline. Only
19519 /// the `ssao` and `ssao-shipped` passes are looked at, because every other
19520 /// pass in the chain binds a pipeline too and a filter over the whole stream
19521 /// would be counting blurs.
19522 ///
19523 /// [`the_comparison_seam_marches_twice_over_columns_that_tile_the_gather`]: fn@the_comparison_seam_marches_twice_over_columns_that_tile_the_gather
19524 fn gathers_bound(recorder: &Recorder, from: usize) -> Vec<crcbl_hal::GraphicsPipelineHandle> {
19525 use crcbl_hal::null::Command;
19526
19527 let mut inside = false;
19528 let mut found = Vec::new();
19529 for command in &recorder.commands()[from..] {
19530 if let Some((_, label)) = command.opens_pass() {
19531 inside = matches!(label, Some("ssao" | "ssao-shipped"));
19532 continue;
19533 }
19534 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
19535 inside = false;
19536 continue;
19537 }
19538 if let (true, Command::BindGraphicsPipeline(pipeline)) = (inside, command) {
19539 found.push(*pipeline);
19540 }
19541 }
19542 found
19543 }
19544
19545 /// **`r_ssao_technique` decides which shader the gather runs**, read off the
19546 /// pipeline the `ssao` pass bound.
19547 ///
19548 /// The observable `docs/backlog.md` says the uniform block cannot have. The
19549 /// reference backend records a bind group as a handle and a layout rather
19550 /// than as the resources behind it, so nothing can ask which *block* a march
19551 /// read — but a pipeline is recorded as itself, so which *technique* a march
19552 /// ran is a question this backend answers. `Ssao::gathers` is what names the
19553 /// two, so this is an equality against the pipeline built from each shader
19554 /// rather than an inequality that any two handles would satisfy.
19555 ///
19556 /// **The default arm is the load-bearing half.** A selector that read the
19557 /// wrong variable, or a `pipeline_for` whose arms were swapped, would still
19558 /// change the frame when the console moved; what would go with it is every
19559 /// golden in this workspace, which is blessed on the technique that ships.
19560 ///
19561 /// Holds [`ssao_blur_switch`] for its own reason and
19562 /// [`ssao_technique_switch`] third, after it and [`ssao_split_switch`] —
19563 /// see `crate::ssao::TECHNIQUE_SWITCH` on the order.
19564 #[test]
19565 fn the_occlusion_technique_picks_the_gathers_pipeline() {
19566 let _blurs = ssao_blur_switch();
19567 let _seam = ssao_split_switch();
19568 let technique = ssao_technique_switch();
19569 // The name to move to, taken out of the variable's own set — see
19570 // `other_technique_name`.
19571 let other = other_technique_name();
19572
19573 let (recorder, device, queue) = open();
19574 let device = device.as_ref();
19575 let mut renderer =
19576 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19577 let (ships, cheap) = renderer.primary.ssao.gathers();
19578 assert_ne!(
19579 ships, cheap,
19580 "the renderer built one gather pipeline for both techniques, so nothing below can \
19581 tell them apart"
19582 );
19583
19584 let shipped = frame_seen_from(
19585 device,
19586 &mut renderer,
19587 queue,
19588 &Camera::default(),
19589 &DirectionalLight::default(),
19590 );
19591 let by_default = gathers_bound(&recorder, 0);
19592 let after = recorder.commands().len();
19593 shipped.release(device);
19594
19595 technique.set(other);
19596 let moved_frame = frame_seen_from(
19597 device,
19598 &mut renderer,
19599 queue,
19600 &Camera::default(),
19601 &DirectionalLight::default(),
19602 );
19603 let moved = gathers_bound(&recorder, after);
19604 moved_frame.finish(device, renderer);
19605
19606 assert_eq!(
19607 by_default,
19608 vec![ships],
19609 "a frame nobody has touched the console on gathered through something other than \
19610 `ssao.slang`'s pipeline, which is what every golden in this workspace was blessed on"
19611 );
19612 assert_eq!(
19613 moved,
19614 vec![cheap],
19615 "`r_ssao_technique {other}` left the frame gathering through the pipeline \
19616 it gathered through before, so the selector reaches nothing"
19617 );
19618 recorder.assert_valid();
19619 }
19620
19621 /// **The comparison seam's two marches run two techniques**, which is what
19622 /// the seam was built for.
19623 ///
19624 /// Alcove's second milestone is SSAO and GTAO in
19625 /// one frame, and this is that claim as a pair of pipeline handles: with the
19626 /// technique moved the near side runs the cheap tier and the far side the
19627 /// one that ships, and with it at its default both marches run the same
19628 /// shader and the seam separates nothing.
19629 ///
19630 /// **The control is the frame at the default**, and it is what makes the
19631 /// first half mean anything: a far side that always ran `ssao.slang` would
19632 /// satisfy the inequality below whatever `shipped_technique` did, and a
19633 /// chain that had simply forgotten to pass the far side a pipeline of its
19634 /// own would too.
19635 #[test]
19636 fn the_comparison_seam_marches_through_two_techniques() {
19637 let _blurs = ssao_blur_switch();
19638 let seam = ssao_split_switch();
19639 let technique = ssao_technique_switch();
19640 let other = other_technique_name();
19641
19642 let (recorder, device, queue) = open();
19643 let device = device.as_ref();
19644 let mut renderer =
19645 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19646 let (ships, cheap) = renderer.primary.ssao.gathers();
19647
19648 seam.set(0.5);
19649 let compared = frame_seen_from(
19650 device,
19651 &mut renderer,
19652 queue,
19653 &Camera::default(),
19654 &DirectionalLight::default(),
19655 );
19656 let one_technique = gathers_bound(&recorder, 0);
19657 let after = recorder.commands().len();
19658 compared.release(device);
19659
19660 technique.set(other);
19661 let frame = frame_seen_from(
19662 device,
19663 &mut renderer,
19664 queue,
19665 &Camera::default(),
19666 &DirectionalLight::default(),
19667 );
19668 let two_techniques = gathers_bound(&recorder, after);
19669 frame.finish(device, renderer);
19670
19671 assert_eq!(
19672 one_technique,
19673 vec![ships, ships],
19674 "a seam with the technique at its default has to march the shipped gather twice — \
19675 both sides read `shipped`'s configuration, and the picture is one technique either \
19676 side of a line"
19677 );
19678 assert_eq!(
19679 two_techniques,
19680 vec![cheap, ships],
19681 "with `r_ssao_technique {other}` the near side has to run the cheap tier \
19682 and the far side what ships; the far side follows the variable's *default*, exactly \
19683 as the four scalars do"
19684 );
19685 recorder.assert_valid();
19686 }
19687
19688 /// **The frame block carries the console's shadow filter on the near side
19689 /// of the seam, the shipped one on the far side, and the column
19690 /// [`crate::split::halves`] counted.**
19691 ///
19692 /// [`the_comparison_seam_marches_through_two_techniques`]'s claim for the
19693 /// other seam, and it has to be a claim about *bytes* rather than about
19694 /// pass handles: the occlusion chain compares two pipelines and this
19695 /// compares two arms of one, so there is nothing in the pass list to look
19696 /// at. What a person sees is decided entirely by the row this asserts.
19697 ///
19698 /// **The frame at the default is the control**, and it is what makes the
19699 /// rest mean anything: a block that always wrote the shipped filter into
19700 /// both lanes would satisfy the third case's far side whatever
19701 /// `shipped_filter` did, and one that copied the near lane into the far one
19702 /// would satisfy the first two.
19703 ///
19704 /// The column is compared against `halves`' own answer rather than against
19705 /// a number written here, which is the seam module's whole point: a test
19706 /// that multiplied the fraction by the width itself would be a second
19707 /// opinion about the rounding, and the floor is exactly what that module's
19708 /// `the_seam_takes_the_floor_of_the_column_it_asks_for` exists to pin.
19709 ///
19710 /// [`the_comparison_seam_marches_through_two_techniques`]: fn@the_comparison_seam_marches_through_two_techniques
19711 #[test]
19712 fn the_frame_block_carries_a_shadow_filter_for_each_side_of_the_seam() {
19713 let switch = shadow_filter_switch();
19714
19715 let (recorder, device, queue) = open();
19716 let device = device.as_ref();
19717 let mut renderer =
19718 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19719
19720 // The seam is counted over the extent the scene is *drawn* at, which is
19721 // what `SV_Position.x` is denominated in — not the caller's window.
19722 let internal = renderer.internal_extent(TEST_EXTENT);
19723 let (left, _) = crate::split::halves(internal, 0.5).expect("a seam down the middle");
19724 assert!(
19725 left.width > 0,
19726 "a seam with no columns on one side would make every assertion below hold of a \
19727 frame that compares nothing"
19728 );
19729
19730 let ships = shadow::shipped_filter();
19731 let other = shadow::Filter::Box;
19732 assert_ne!(
19733 other.mode(),
19734 ships.mode(),
19735 "the filter this test moves the console to is the one that ships, so the seam it \
19736 asks for compares one kernel against itself"
19737 );
19738
19739 let draw = |renderer: &mut ForwardRenderer| {
19740 renderer
19741 .begin_frame(
19742 device,
19743 &Camera::default(),
19744 &DirectionalLight::default(),
19745 TEST_EXTENT,
19746 )
19747 .expect("write");
19748 let bytes = recorder
19749 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
19750 .expect("this frame's uniform block is live");
19751 let at = mesh::FRAME_UNIFORMS_SIZE - 16;
19752 core::array::from_fn(|lane| {
19753 u32::from_le_bytes(
19754 bytes[at + lane * 4..at + lane * 4 + 4]
19755 .try_into()
19756 .expect("four bytes"),
19757 )
19758 })
19759 };
19760
19761 let shipped: [u32; 4] = draw(&mut renderer);
19762 assert_eq!(
19763 shipped,
19764 [ships.mode(), ships.mode(), 0, 0],
19765 "a frame nobody has touched the console on must carry the shipped filter in both \
19766 lanes and no column, which is the row every golden in this workspace was blessed \
19767 under"
19768 );
19769
19770 switch.filter(other);
19771 let unsplit: [u32; 4] = draw(&mut renderer);
19772 assert_eq!(
19773 unsplit,
19774 [other.mode(), other.mode(), 0, 0],
19775 "`r_shadow_filter {}` with no seam has to reach every pixel, so both lanes carry it",
19776 other.label()
19777 );
19778
19779 switch.seam(0.5);
19780 let compared: [u32; 4] = draw(&mut renderer);
19781 assert_eq!(
19782 compared,
19783 [other.mode(), ships.mode(), left.width, 0],
19784 "a seam at 0.5 has to put the console's filter left of `halves`' column and the \
19785 shipped one right of it; the far side follows the variable's *default*, exactly \
19786 as the occlusion chain's does"
19787 );
19788
19789 renderer.destroy(device);
19790 recorder.assert_valid();
19791 }
19792
19793 #[test]
19794 fn a_second_occlusion_blur_is_a_pass_the_frame_records() {
19795 let switch = ssao_blur_switch();
19796
19797 let (recorder, device, queue) = open();
19798 let device = device.as_ref();
19799 let mut renderer =
19800 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19801 let imported = swapchain_image(device);
19802 let pool = crate::TransientPool::new();
19803
19804 let once = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19805 let counted_once = renderer.counters().instances;
19806 assert!(
19807 once.contains(&"ssao-blur".to_string()),
19808 "the shipping frame has to blur once, or the arm below is about a frame with no \
19809 occlusion in it at all: {once:#?}"
19810 );
19811 assert!(
19812 !once.contains(&"ssao-blur-2".to_string()),
19813 "a frame nobody moved the switch for must record one blur: {once:#?}"
19814 );
19815
19816 switch.set(2);
19817 let twice = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
19818 let counted_twice = renderer.counters().instances;
19819 assert!(
19820 twice.contains(&"ssao-blur-2".to_string()),
19821 "`r_ssao_blur_passes 2` must put a second blur in the frame: {twice:#?}"
19822 );
19823 assert_eq!(
19824 twice.len(),
19825 once.len() + 1,
19826 "the second blur is the only pass that may join the frame: {twice:#?}"
19827 );
19828 assert_eq!(
19829 counted_twice,
19830 counted_once + FULLSCREEN_DRAWS,
19831 "the frame recorded a full-screen triangle its counter did not report"
19832 );
19833
19834 // The pass has to write somewhere the forward pass then reads, and the
19835 // graph is what would refuse a frame that bound an image nothing wrote.
19836 // `passes_in_a_frame` compiles rather than executes, so this is the
19837 // check that the third transient was requested at all.
19838 assert!(
19839 twice.iter().any(|pass| pass == "forward"),
19840 "the frame still has to reach its forward pass: {twice:#?}"
19841 );
19842 recorder.assert_valid();
19843 }
19844
19845 /// Every host-written buffer at the end of a whole ring of frames, keyed by
19846 /// the handle written and holding what that handle last held.
19847 ///
19848 /// A whole ring rather than one frame, because the blocks a frame writes are
19849 /// themselves rings — a buffer per frame in flight, [`Ssao`]'s among them —
19850 /// so one frame touches one slot of each and two single-frame batches would
19851 /// be comparing different buffers. A ring writes every slot, so two batches'
19852 /// keys line up and a difference between them is a difference in *bytes*.
19853 ///
19854 /// Only the events this call appends are read, so a caller can take one
19855 /// batch after another off the same recorder.
19856 fn host_buffers_over_a_ring(
19857 recorder: &Recorder,
19858 device: &dyn Device,
19859 renderer: &mut ForwardRenderer,
19860 queue: QueueHandle,
19861 ) -> std::collections::BTreeMap<u64, Vec<u8>> {
19862 let from = recorder.events().len();
19863 for _ in 0..FRAMES_IN_FLIGHT {
19864 frame(device, renderer, queue).release(device);
19865 }
19866 recorder.events()[from..]
19867 .iter()
19868 .filter_map(|event| match event {
19869 Event::BufferWritten { buffer, .. } => Some(*buffer),
19870 _ => None,
19871 })
19872 .map(|buffer| {
19873 let bytes = recorder
19874 .buffer_bytes(buffer)
19875 .expect("the stream only names buffers this recorder created");
19876 (buffer.to_bits(), bytes)
19877 })
19878 .collect()
19879 }
19880
19881 /// **`r_ssao_slices` reaches the block `ssao.slang` reads, on every frame of
19882 /// the ring, and moves nothing else in the frame.**
19883 ///
19884 /// The device test drives the two occlusion pipelines directly and
19885 /// [`a_second_occlusion_blur_is_a_pass_the_frame_records`] moves the *blur*
19886 /// count, so until this the slice count was a variable with a `get_i64` and
19887 /// no evidence that a rendered frame ever carried it: `slice_count` could
19888 /// have returned its default unconditionally and every check in this
19889 /// workspace would still be green.
19890 ///
19891 /// So the observable is the bytes, taken off the null recorder's write log
19892 /// after a whole ring of frames at each setting and compared **by handle**.
19893 /// Two claims come out of that comparison and both are load-bearing:
19894 ///
19895 /// * **Some block moved** — every ring slot, in fact, which is what says the
19896 /// count reaches the frame at all rather than only the slot the last frame
19897 /// happened to land in.
19898 /// * **Every block that moved, moved only there.** A frame is a few dozen
19899 /// host writes and the slice count has business with exactly one word of
19900 /// one of them; a setting that perturbed a matrix, an instance or a shadow
19901 /// view would be drawing a different frame for a reason nobody asked for,
19902 /// and the "at least one differs" half alone would pass on it happily.
19903 ///
19904 /// **Holds every switch whose row is in a block it compares**, in the lock
19905 /// order: the two batches are compared byte for byte over every host
19906 /// buffer the frame writes, so any console row another test moves between
19907 /// them — the blur count, the seam, the technique, the shadow filter, or
19908 /// `crate::ssao`'s own mover of the params block — reads here as "some
19909 /// other write moving". [`ssao_technique_switch`] is the one that
19910 /// serialises against that mover.
19911 #[test]
19912 fn four_slices_reach_the_frame_the_shader_reads() {
19913 let _blurs = ssao_blur_switch();
19914 let _seam = ssao_split_switch();
19915 let switch = ssao_slice_switch();
19916 let _technique = ssao_technique_switch();
19917 let _filter = shadow_filter_switch();
19918
19919 let (recorder, device, queue) = open();
19920 let device = device.as_ref();
19921 let mut renderer =
19922 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
19923
19924 // A ring rendered before either batch is taken, because the two below
19925 // are compared by handle and the renderer's opening frame writes blocks
19926 // no later frame writes again: it fills a cold shadow atlas, so the
19927 // shadow views' uniform blocks and the draw-generation blocks of the
19928 // cascades that were drawn are written once and never again while the
19929 // cache holds. Those would be in the first batch and missing from the
19930 // second, and a key that is only in one of them is a difference this
19931 // test cannot say anything about.
19932 for _ in 0..FRAMES_IN_FLIGHT {
19933 frame(device, &mut renderer, queue).release(device);
19934 }
19935 let shipping = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
19936 switch.set(i64::from(ssao::SLICE_COUNT_MAX));
19937 let asked = host_buffers_over_a_ring(&recorder, device, &mut renderer, queue);
19938 assert_eq!(
19939 shipping.keys().collect::<Vec<_>>(),
19940 asked.keys().collect::<Vec<_>>(),
19941 "the two batches must write the same buffers, or they are not comparable",
19942 );
19943
19944 // Which bytes moving the count alone is allowed to move, asked of
19945 // `SsaoParams::to_bytes` rather than written here as an offset: the
19946 // block's layout is `crcbl_shaders::ssao`'s, and a field inserted ahead
19947 // of the count would leave a number spelled here pointing at the radius.
19948 let block_of = |slices| {
19949 ssao::SsaoParams {
19950 inv_proj: [0.0; 16],
19951 proj: [0.0; 16],
19952 inv_view: [0.0; 16],
19953 radius: 0.0,
19954 slices,
19955 intensity: ssao::INTENSITY_DEFAULT,
19956 bent_normals: crate::ssao::bent_normals(),
19957 }
19958 .to_bytes()
19959 };
19960 let at_shipping = block_of(ssao::SLICE_COUNT_DEFAULT);
19961 let at_max = block_of(ssao::SLICE_COUNT_MAX);
19962 let count_word: Vec<usize> = (0..ssao::PARAMS_SIZE)
19963 .filter(|at| at_shipping[*at] != at_max[*at])
19964 .collect();
19965
19966 let mut moved = 0;
19967 for (handle, before) in &shipping {
19968 let after = &asked[handle];
19969 if before == after {
19970 continue;
19971 }
19972 moved += 1;
19973 let mut only_the_count = before.clone();
19974 for at in &count_word {
19975 assert_eq!(
19976 before[*at], at_shipping[*at],
19977 "buffer {handle} differs between the batches but did not go in holding the \
19978 shipping slice count, so this is some other write moving",
19979 );
19980 only_the_count[*at] = at_max[*at];
19981 }
19982 assert_eq!(
19983 after, &only_the_count,
19984 "buffer {handle} moved somewhere other than the slice count's word: the setting \
19985 is perturbing a block it has no business in",
19986 );
19987 }
19988 assert_eq!(
19989 moved, FRAMES_IN_FLIGHT,
19990 "`r_ssao_slices 4` must reach every slot of the occlusion ring; a count that moved \
19991 none of them is a console variable no rendered frame reads",
19992 );
19993
19994 renderer.destroy(device);
19995 recorder.assert_valid();
19996 }
19997
19998 /// **The debug draw layer costs a frame nothing until something is appended
19999 /// *and* the console switch is on, and then it is the pass immediately
20000 /// before the tonemap.**
20001 ///
20002 /// Four claims, and each is a separate way to get this wrong.
20003 ///
20004 /// * **Off by default** is what keeps every golden image in the workspace
20005 /// where it was blessed.
20006 /// * **A segment appended while the switch is off records nothing**, so a
20007 /// system may append unconditionally.
20008 /// * **The switch on with an empty buffer records nothing either** — this is
20009 /// the "costs nothing when empty" claim as a check rather than a sentence:
20010 /// the compiled pass list is compared whole against the frame drawn before
20011 /// the layer was switched on, so a pass that clears, blits or barriers
20012 /// anything would show up here.
20013 /// * **Before the tonemap**, which is
20014 /// `docs/plan/18-render-features.md`'s interaction rule and the opposite of
20015 /// the ground grid above. Recorded a line later it would draw into the
20016 /// display-space target and be free of the exposure, which compiles and
20017 /// draws lines and is the wrong picture.
20018 ///
20019 /// And the fifth, which is what "immediate mode" means: the frame *after*
20020 /// the one that appended records nothing again, because
20021 /// [`ForwardRenderer::begin_frame`] cleared the buffer.
20022 ///
20023 /// The whole list is compared rather than its length, for the ground grid
20024 /// test's reason: one more pass is satisfied by gaining the wrong one.
20025 ///
20026 /// **This test owns `r_debug_draw` for its duration**, through
20027 /// [`debug_draw_switch`]: a plain `cargo test` run shares one process
20028 /// between tests, so the two checks here that move it have to take turns.
20029 /// `cargo nextest`, which CI runs, gives each a process of its own and needs
20030 /// none of it.
20031 #[test]
20032 fn the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap() {
20033 let switch = debug_draw_switch();
20034 let _blurs = ssao_blur_switch();
20035
20036 let (recorder, device, queue) = open();
20037 let device = device.as_ref();
20038 let mut renderer =
20039 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20040 let imported = swapchain_image(device);
20041 let mut pool = crate::TransientPool::new();
20042
20043 assert!(
20044 !crate::DebugDraw::enabled(),
20045 "the layer must be off before anything switches it on, or every claim below is \
20046 about a different default"
20047 );
20048 let off = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20049 assert!(
20050 !off.contains(&"debug-draw".to_string()),
20051 "the layer must not be in a frame nobody switched it on for: {off:#?}"
20052 );
20053
20054 renderer
20055 .debug_draw()
20056 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20057 assert_eq!(
20058 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20059 off,
20060 "a segment appended while the switch is off must record no pass"
20061 );
20062
20063 switch.set(true);
20064 assert_eq!(
20065 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20066 off,
20067 "the switch on with an empty buffer must record the frame the layer's absence would"
20068 );
20069
20070 renderer
20071 .debug_draw()
20072 .aabb(-Vec3::ONE, Vec3::ONE, [0.0, 1.0, 0.0, 1.0]);
20073 let on = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
20074 let mut expected = off.clone();
20075 let tonemap = expected
20076 .iter()
20077 .position(|label| label == "tonemap")
20078 .expect("a frame has to reach the swapchain");
20079 expected.insert(tonemap, "debug-draw".to_string());
20080 assert_eq!(
20081 on, expected,
20082 "the layer must be the one pass gained, and it must sit before the tonemap"
20083 );
20084
20085 assert_eq!(
20086 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT),
20087 off,
20088 "the buffer is immediate mode: the frame after the one that appended must record \
20089 nothing"
20090 );
20091
20092 switch.set(false);
20093 renderer.destroy(device);
20094 pool.destroy(device);
20095 device.destroy_image_view(imported.view);
20096 device.destroy_image(imported.image);
20097 recorder.assert_valid();
20098 }
20099
20100 /// **The debug draw layer's own call is counted in the frame's draws.**
20101 ///
20102 /// [`ForwardRenderer::counters`]' draw count is compared against the
20103 /// commands the null backend actually recorded, which is the same instrument
20104 /// `the_forward_counters_are_the_recorded_draws_and_admit_what_they_cannot_know`
20105 /// uses — so a layer whose line list was recorded and not counted fails here
20106 /// rather than quietly making every panel's draw row one short.
20107 ///
20108 /// Both directions are asserted: the frame that drew a segment records one
20109 /// more draw than the frame before it, *and* the counter moved by the same
20110 /// one. A count wired to a constant satisfies neither.
20111 ///
20112 /// It owns `r_debug_draw` for its duration, on
20113 /// `the_debug_draw_layer_is_off_by_default_and_lands_before_the_tonemap`'s
20114 /// terms.
20115 #[test]
20116 fn the_debug_draw_layers_call_is_counted_in_the_frames_draws() {
20117 let switch = debug_draw_switch();
20118 let _blurs = ssao_blur_switch();
20119
20120 let (recorder, device, queue) = open();
20121 let device = device.as_ref();
20122 let mut renderer =
20123 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20124
20125 // A different sun in each of the two frames, so both of them redraw the
20126 // shadow atlas: the claim below is that the layer's own call is the one
20127 // draw the second frame gained, and a second frame that cached its
20128 // atlas would have lost the atlas's draws at the same time. See
20129 // [`moving_sun`].
20130 let quiet = frame_moving_the_sun(device, &mut renderer, queue, 0);
20131 let without = renderer.counters().draws;
20132 assert_eq!(
20133 without,
20134 recorded_draws(&recorder) as u64,
20135 "the counter and the frame's recorded draws disagree before the layer draws at all"
20136 );
20137 quiet.release(device);
20138
20139 switch.set(true);
20140 renderer
20141 .debug_draw()
20142 .line(Vec3::ZERO, Vec3::X, [1.0, 1.0, 1.0, 1.0]);
20143 let drawn = frame_moving_the_sun(device, &mut renderer, queue, 1);
20144 let with = renderer.counters().draws;
20145 assert_eq!(
20146 with,
20147 without + 1,
20148 "the layer records one draw, so the count has to move by one"
20149 );
20150 assert_eq!(
20151 recorded_draws(&recorder) as u64,
20152 without + with,
20153 "the two frames' recorded draws and the two counts disagree, so the layer's call is \
20154 counted somewhere it was not recorded or recorded somewhere it was not counted"
20155 );
20156
20157 switch.set(false);
20158 drawn.finish(device, renderer);
20159 recorder.assert_valid();
20160 }
20161
20162 /// **The depth-only passes run the depth-only entry point, and the colour
20163 /// pass does not.**
20164 ///
20165 /// Topic 43 §2 split the vertex pool so a pass
20166 /// that wants a clip position and no more could fetch stream 0 alone, and
20167 /// [`MeshModules::depth_pipeline`] naming `mesh.slang`'s `depthVertexMain`
20168 /// is the whole of how that split is spent. **Nothing else in the tree sees
20169 /// it.** `crcbl_shaders::mesh`'s
20170 /// `the_depth_entry_point_fetches_the_position_stream_alone` reads the
20171 /// compiled artifact and would pass with the entry point built and unused;
20172 /// no golden moves, because the two stages compute the same clip position on
20173 /// purpose; the render graph records a legal frame either way; and the
20174 /// measured price says nothing — pointing this pipeline back at `vertexMain`
20175 /// cost the depth prepass about a tenth more on lavapipe and nothing to
20176 /// three figures on an RX 7900 XTX, measured 2026-08-31. So the wiring is
20177 /// asserted here, against the reference backend, which records the entry
20178 /// point a pipeline names precisely so this question has an answer.
20179 ///
20180 /// **Both halves, so the check is shown to discriminate.** A lookup that
20181 /// answered `depthVertexMain` for every pipeline would satisfy the first
20182 /// assertion alone, and the colour pipeline is the one that must *not* have
20183 /// moved. The labels are the descriptors' own and are what the two are told
20184 /// apart by, so a renamed pipeline fails at the `expect` rather than
20185 /// silently matching nothing.
20186 #[test]
20187 fn the_depth_pipeline_names_the_depth_only_vertex_stage_and_the_colour_one_does_not() {
20188 let (recorder, device, queue) = open();
20189 let device = device.as_ref();
20190 let renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20191 // A mesh stage has no vertex entry point to name, and this whole rung is
20192 // about the raster arm — see [`MeshModules::depth_pipeline`]. The null
20193 // preset reports no `Features::MESH_SHADER`, so this is what it built;
20194 // asserted rather than assumed, because a preset that grew the feature
20195 // would leave every assertion below looking for pipelines that do not
20196 // exist.
20197 assert_ne!(
20198 renderer.geometry_path(),
20199 crcbl_hal::GeometryPath::MeshShader,
20200 "this device built a mesh-shader path, whose geometry stage names no vertex \
20201 entry point at all"
20202 );
20203
20204 let pipelines = recorder.graphics_pipeline_vertex_entries();
20205 let entry_of = |label: &str| -> String {
20206 let found: Vec<&str> = pipelines
20207 .iter()
20208 .filter(|(name, _)| name.as_deref() == Some(label))
20209 .map(|(_, entry)| entry.as_str())
20210 .collect();
20211 assert_eq!(
20212 found.len(),
20213 1,
20214 "the renderer built {} pipeline(s) labelled `{label}`, out of {pipelines:?}",
20215 found.len()
20216 );
20217 found[0].to_owned()
20218 };
20219
20220 assert_eq!(
20221 entry_of("shadow cascade"),
20222 "depthVertexMain",
20223 "the shadow atlas and the depth prepass share this pipeline, and it is the one \
20224 that reads the position stream alone"
20225 );
20226 assert_eq!(
20227 entry_of("forward mesh"),
20228 "vertexMain",
20229 "the colour pass needs every attribute the depth pass skips, so it is the entry \
20230 point that reads a whole vertex"
20231 );
20232 assert_eq!(
20233 entry_of("shadow cascade masked"),
20234 "vertexMain",
20235 "the cutout twin has to read a whole vertex: the UV it samples the mask from lives \
20236 in the attribute region `depthVertexMain` exists not to read"
20237 );
20238
20239 renderer.destroy(device);
20240 recorder.assert_valid();
20241 }
20242
20243 /// **A masked material moves that mesh's depth draws onto the cutout
20244 /// pipeline, and moves nothing else.**
20245 ///
20246 /// The mechanism is which pipeline handle the recorded stream binds and
20247 /// which buckets' indirect calls follow each bind — the wireframe test's
20248 /// observable, for the same reason: a field saying a mode was read would
20249 /// prove the flag was read, not that the frame changed.
20250 ///
20251 /// Four claims, and each rules out a different way of passing wrongly:
20252 ///
20253 /// * a scene with nothing masked binds the vertex-only pipeline and
20254 /// **never** the cutout one, which is the "an opaque frame costs what it
20255 /// always did" claim at the level a null device can see it;
20256 /// * a scene with one masked row binds **both** in the depth prepass and
20257 /// both in the shadow atlas — a per-frame choice binds one or the other,
20258 /// never the pair;
20259 /// * the calls following each bind are exactly that mode's buckets, in
20260 /// bucket order, read off the argument offsets the draws name. A split
20261 /// that bound both pipelines and drew every bucket under each would
20262 /// satisfy the claim above and double the frame's draws;
20263 /// * and folding the two handles together — then collapsing the runs of
20264 /// equal binds the fold creates — leaves the two frames' bind streams
20265 /// **equal**, so the colour pass, the tile clears and the reflective
20266 /// shadow map are all where they were. A change that had also moved the
20267 /// colour pass would satisfy the first three and fail this.
20268 ///
20269 /// The two scenes differ in one flags word and nothing else.
20270 #[test]
20271 fn a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline() {
20272 use crcbl_hal::null::Command;
20273
20274 // The occlusion blur count is a process-global console variable and a
20275 // frame binds one pipeline per blur, so a concurrent test moving it
20276 // would put a bind in one of these frames and not the other — the
20277 // wireframe test's hazard exactly.
20278 let _blurs = ssao_blur_switch();
20279
20280 let masked_scene = {
20281 let mut scene = crate::scene::demo();
20282 scene.materials[DEMO_UNTINTED].flags =
20283 crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK;
20284 scene
20285 };
20286
20287 /// What one scene's frame reveals: the bucket count and each bucket's
20288 /// mode, how often each depth pipeline was bound, the (pipeline, bucket)
20289 /// pairs the depth prepass and the shadow atlas recorded, and the whole
20290 /// bind stream with the two depth handles folded into one.
20291 struct Recorded {
20292 modes: Vec<u32>,
20293 cutouts: usize,
20294 plains: usize,
20295 prepass: Vec<(bool, u32)>,
20296 atlas: Vec<(bool, u32)>,
20297 folded: Vec<GraphicsPipelineHandle>,
20298 }
20299
20300 // One frame each, from two renderers rather than two frames from one:
20301 // a bucket table is fixed at build, and two builds keep the frames'
20302 // shadow-atlas state identical — both are a first frame.
20303 let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20304 let (recorder, device, queue) = open();
20305 let device = device.as_ref();
20306 let mut renderer =
20307 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20308 .expect("the null backend accepts the demo description");
20309 place_cube(&mut renderer, Mat4::IDENTITY);
20310 let imported = swapchain_image(device);
20311 let mut pool = crate::TransientPool::new();
20312 renderer
20313 .begin_frame(
20314 device,
20315 &Camera::default(),
20316 &DirectionalLight::default(),
20317 (64, 48),
20318 )
20319 .expect("write");
20320 let mut graph = crate::RenderGraph::new(queue);
20321 let target = graph.import_image("target", imported);
20322 renderer.add_passes(&mut graph, &pool, target, (64, 48));
20323 let compiled = graph.compile(&pool).expect("a legal frame");
20324 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20325 label: Some("alpha mask lap"),
20326 queue,
20327 });
20328 compiled
20329 .execute(device, &mut pool, encoder.as_mut(), None)
20330 .expect("the graph executed");
20331 encoder.finish().expect("recording succeeded");
20332 let plain = renderer.shadow_pipeline.single;
20333 let cutout = renderer.depth_masked_pipeline.single;
20334 assert_ne!(
20335 plain, cutout,
20336 "the two depth pipelines have to be two objects, or nothing below discriminates"
20337 );
20338 // Which bucket a draw is, recovered from the argument offset it
20339 // names — the offsets are the renderer's own accessor, so a call
20340 // pointing at the wrong bucket has no entry here at all.
20341 let bucket_of = |args_offset: u64| -> u32 {
20342 (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20343 .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20344 .unwrap_or_else(|| {
20345 panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20346 })
20347 };
20348 // Per depth pass: the pipeline in force at each indirect call and
20349 // the bucket that call drew, in the order they were recorded.
20350 let pass_calls = |label: &str| -> Vec<(bool, u32)> {
20351 let mut current = None;
20352 let mut out = Vec::new();
20353 for command in commands_in_pass(&recorder, label) {
20354 match command {
20355 Command::BindGraphicsPipeline(handle) => current = Some(handle),
20356 Command::DrawIndexedIndirectCount(draw) => {
20357 let handle = current.expect("a draw follows a pipeline bind");
20358 assert!(
20359 handle == plain || handle == cutout,
20360 "a depth pass drew under a pipeline that is neither depth one"
20361 );
20362 out.push((handle == cutout, bucket_of(draw.args_offset)));
20363 }
20364 _ => {}
20365 }
20366 }
20367 out
20368 };
20369 let prepass = pass_calls("depth-prepass");
20370 let atlas = pass_calls("shadow");
20371 let binds: Vec<GraphicsPipelineHandle> = recorder
20372 .commands()
20373 .iter()
20374 .filter_map(|command| match command {
20375 Command::BindGraphicsPipeline(handle) => Some(*handle),
20376 _ => None,
20377 })
20378 .collect();
20379 let cutouts = binds.iter().filter(|handle| **handle == cutout).count();
20380 let plains = binds.iter().filter(|handle| **handle == plain).count();
20381 let mut folded: Vec<GraphicsPipelineHandle> = Vec::with_capacity(binds.len());
20382 for handle in binds {
20383 let handle = if handle == cutout { plain } else { handle };
20384 // The fold turns the masked frame's `plain, cutout` pair into
20385 // `plain, plain`; collapsing a run of equal binds is what makes
20386 // the two streams comparable without hiding a bind of anything
20387 // else, since no pass in either frame binds two *different*
20388 // pipelines that the fold could bring together.
20389 if folded.last() != Some(&handle) {
20390 folded.push(handle);
20391 }
20392 }
20393 let modes = renderer.bucket_modes.clone();
20394 renderer.destroy(device);
20395 recorder.assert_valid();
20396 Recorded {
20397 modes,
20398 cutouts,
20399 plains,
20400 prepass,
20401 atlas,
20402 folded,
20403 }
20404 };
20405
20406 let opaque = bound(&crate::scene::demo());
20407 let masked = bound(&masked_scene);
20408
20409 assert_eq!(
20410 opaque.cutouts, 0,
20411 "a scene with nothing masked must never bind the cutout pipeline"
20412 );
20413 assert!(
20414 opaque.plains > 0,
20415 "a scene with nothing masked must bind the vertex-only pipeline, or the assertion \
20416 above is about a frame with no depth pass in it"
20417 );
20418 assert!(
20419 opaque.modes.iter().all(|mode| *mode == 0),
20420 "and every one of its buckets is opaque: {:?}",
20421 opaque.modes
20422 );
20423 assert_eq!(
20424 opaque.prepass.iter().filter(|(cutout, _)| *cutout).count(),
20425 0,
20426 "so no opaque draw is recorded under the cutout pipeline"
20427 );
20428
20429 assert!(
20430 masked.cutouts > 0 && masked.plains > 0,
20431 "a masked scene must bind **both** depth pipelines — {} cutout and {} plain — or \
20432 the choice is still per frame",
20433 masked.cutouts,
20434 masked.plains
20435 );
20436 // What each depth pass should have recorded: every opaque bucket under
20437 // the plain pipeline in bucket order, then every masked one under the
20438 // cutout, which is the partition order `depth_partitions` lays down.
20439 let want: Vec<(bool, u32)> = [false, true]
20440 .into_iter()
20441 .flat_map(|cutout| {
20442 masked
20443 .modes
20444 .iter()
20445 .enumerate()
20446 .filter(move |(_, mode)| {
20447 (**mode == crcbl_shaders::mesh::GpuMaterial::ALPHA_MODE_MASK) == cutout
20448 })
20449 .map(move |(bucket, _)| (cutout, u32::try_from(bucket).expect("a few buckets")))
20450 })
20451 .collect();
20452 assert!(
20453 want.iter().any(|(cutout, _)| *cutout) && want.iter().any(|(cutout, _)| !*cutout),
20454 "the masked demo has to hold buckets of both modes, or this compares one partition \
20455 against itself: {:?}",
20456 masked.modes
20457 );
20458 assert_eq!(
20459 masked.prepass, want,
20460 "the depth prepass must record each bucket once, under the pipeline its own mode \
20461 asked for"
20462 );
20463 // The atlas draws every bucket once per occupied view, and the
20464 // partition is **outside** the view loop — one pipeline bind covers
20465 // every view of that mode — so its stream is each partition's bucket
20466 // list repeated once per view.
20467 let views = masked.atlas.len() / want.len();
20468 assert!(
20469 views > 0 && masked.atlas.len() % want.len() == 0,
20470 "the shadow atlas recorded {} calls over {} buckets, which is not a whole number \
20471 of views",
20472 masked.atlas.len(),
20473 want.len()
20474 );
20475 let mut atlas_want: Vec<(bool, u32)> = Vec::with_capacity(masked.atlas.len());
20476 for cutout in [false, true] {
20477 let partition: Vec<(bool, u32)> = want
20478 .iter()
20479 .copied()
20480 .filter(|(mode, _)| *mode == cutout)
20481 .collect();
20482 for _ in 0..views {
20483 atlas_want.extend_from_slice(&partition);
20484 }
20485 }
20486 assert_eq!(
20487 masked.atlas, atlas_want,
20488 "and every shadow view draws both partitions, each under its own pipeline"
20489 );
20490
20491 assert_eq!(
20492 masked.folded, opaque.folded,
20493 "the frame gained or lost a pipeline bind beyond the cutout twin beside a plain one"
20494 );
20495 }
20496
20497 /// **A double-sided material moves every pass's draws for its own buckets
20498 /// onto the `CullMode::None` twins, and moves nothing else.**
20499 ///
20500 /// [`a_masked_material_moves_its_own_meshs_depth_draws_onto_the_cutout_pipeline`]'s
20501 /// claim for glTF's other mode, and it is wider by construction: an alpha
20502 /// mask is cut inside a fragment stage, so only the two depth-only passes
20503 /// route around it, while a cull mode is a pipeline state and **every** pass
20504 /// that draws the surface has to route around it — the colour pass, both
20505 /// depth passes and the two reflective shadow maps.
20506 ///
20507 /// So this walks the whole recorded stream rather than two named passes:
20508 /// every render pass that recorded an indirect draw is read back as the
20509 /// (side, bucket) pairs it recorded, and each of the four claims below is
20510 /// about all of them at once.
20511 ///
20512 /// * a scene with nothing double-sided binds **no** cull-none twin
20513 /// anywhere, which is the "an all-single-sided frame costs what it always
20514 /// did" claim at the level a null device can see it;
20515 /// * a scene with one double-sided row binds a twin in every pass that
20516 /// draws — a frame that had only routed the colour pass would satisfy
20517 /// nothing below, and one that had only routed the depth passes would
20518 /// draw a surface the prepass wrote no depth for;
20519 /// * the calls following each bind are exactly that side's buckets, in
20520 /// bucket order. A split that bound both pipelines and drew every bucket
20521 /// under each would satisfy the claim above and double the frame's draws;
20522 /// * and folding each twin onto the pipeline it is a twin of — then
20523 /// collapsing the runs of equal binds the fold creates — leaves the two
20524 /// frames' bind streams **equal**, so nothing else in the frame moved.
20525 ///
20526 /// The two scenes differ in one flags word and nothing else.
20527 ///
20528 /// [`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
20529 #[test]
20530 fn a_double_sided_material_moves_every_passs_draws_onto_the_cull_none_twins() {
20531 use crcbl_hal::null::Command;
20532
20533 // The occlusion blur count is a process-global console variable and a
20534 // frame binds one pipeline per blur — the masked test's hazard exactly.
20535 let _blurs = ssao_blur_switch();
20536
20537 // **A scene whose probes ask to be updated**, because the reflective
20538 // shadow maps are recorded by a volume rather than by an effect bit —
20539 // and they are two of the five passes this claim is about. The demo's
20540 // empty grid records neither, which would leave the widest half of the
20541 // routing unchecked.
20542 let scene_with_probes = || {
20543 let mut scene = crate::scene::demo();
20544 scene.capacities.probes = 1;
20545 scene.probes = crate::scene::ProbeGrid {
20546 volume: crcbl_shaders::probe::ProbeVolume {
20547 origin: [0.0; 3],
20548 inv_spacing: [1.0; 3],
20549 counts: [1, 1, 1],
20550 levels: 1,
20551 steps: crcbl_shaders::probe::ProbeSteps::default(),
20552 },
20553 probes: vec![crcbl_shaders::probe::GpuProbe::ZERO],
20554 update: ProbeUpdate::EveryFrame,
20555 };
20556 scene
20557 };
20558 let single_scene = scene_with_probes();
20559 let double_scene = {
20560 let mut scene = scene_with_probes();
20561 scene.materials[DEMO_UNTINTED].flags = crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED;
20562 scene
20563 };
20564
20565 /// What one scene's frame reveals: each bucket's mode, how often a
20566 /// cull-none twin was bound at all, every drawing pass's (side, bucket)
20567 /// pairs in record order, and the whole bind stream with each twin
20568 /// folded onto the pipeline it twins.
20569 struct Recorded {
20570 modes: Vec<u32>,
20571 twins_bound: usize,
20572 passes: Vec<(String, Vec<(bool, u32)>)>,
20573 folded: Vec<GraphicsPipelineHandle>,
20574 }
20575
20576 // One frame each, from two renderers rather than two frames from one, on
20577 // the masked test's terms: a bucket table is fixed at build, and two
20578 // builds keep both frames a first frame.
20579 let bound = |scene: &crate::scene::SceneDesc<'_>| -> Recorded {
20580 let (recorder, device, queue) = open();
20581 let device = device.as_ref();
20582 let mut renderer =
20583 ForwardRenderer::with_scene(device, queue, Format::Rgba8UnormSrgb, scene)
20584 .expect("the null backend accepts the demo description");
20585 assert!(
20586 !renderer.emit.is_mesh(),
20587 "this preset built a mesh-shader path, whose draws carry no argument offset to \
20588 recover a bucket from"
20589 );
20590 place_cube(&mut renderer, Mat4::IDENTITY);
20591 // **One shadowed spot**, so the punctual reflective shadow map has a
20592 // face to draw into: the pass is recorded on every frame but its
20593 // view loop is empty without one, and an empty loop records no draw
20594 // for the claim below to be about.
20595 renderer.set_lights(&[crate::Light::Spot(crate::SpotLight {
20596 position: Vec3::new(0.0, 2.0, 0.0),
20597 radius: 8.0,
20598 color: Vec3::splat(4.0),
20599 direction: Vec3::NEG_Y,
20600 inner_angle: 0.3,
20601 outer_angle: 0.6,
20602 fill: false,
20603 })]);
20604 let imported = swapchain_image(device);
20605 let mut pool = crate::TransientPool::new();
20606 renderer
20607 .begin_frame(
20608 device,
20609 &Camera::default(),
20610 &DirectionalLight::default(),
20611 (64, 48),
20612 )
20613 .expect("write");
20614 let mut graph = crate::RenderGraph::new(queue);
20615 let target = graph.import_image("target", imported);
20616 renderer.add_passes(&mut graph, &pool, target, (64, 48));
20617 let compiled = graph.compile(&pool).expect("a legal frame");
20618 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20619 label: Some("double sided lap"),
20620 queue,
20621 });
20622 compiled
20623 .execute(device, &mut pool, encoder.as_mut(), None)
20624 .expect("the graph executed");
20625 encoder.finish().expect("recording succeeded");
20626
20627 // Every twin and the pipeline it twins, so a bind can be reported as
20628 // a side and folded back. Asserted distinct, or nothing here
20629 // discriminates.
20630 let sided = [
20631 renderer.mesh_pipeline,
20632 renderer.shadow_pipeline,
20633 renderer.depth_masked_pipeline,
20634 renderer.rsm_pipeline,
20635 ];
20636 for pair in sided {
20637 assert_ne!(
20638 pair.single, pair.double,
20639 "a pipeline and its cull-none twin have to be two objects"
20640 );
20641 }
20642 let twin_of = |handle: GraphicsPipelineHandle| -> Option<GraphicsPipelineHandle> {
20643 sided
20644 .iter()
20645 .find(|pair| pair.double == handle)
20646 .map(|pair| pair.single)
20647 };
20648 let bucket_of = |args_offset: u64| -> u32 {
20649 (0..u32::try_from(renderer.bucket_constants.len()).expect("a few buckets"))
20650 .find(|bucket| renderer.primary.draws.args_offset(*bucket) == args_offset)
20651 .unwrap_or_else(|| {
20652 panic!("a draw read its arguments at {args_offset}, which is no bucket's")
20653 })
20654 };
20655
20656 let mut passes: Vec<(String, Vec<(bool, u32)>)> = Vec::new();
20657 let mut folded: Vec<GraphicsPipelineHandle> = Vec::new();
20658 let mut twins_bound = 0usize;
20659 let mut current: Option<GraphicsPipelineHandle> = None;
20660 let mut label: Option<String> = None;
20661 let mut calls: Vec<(bool, u32)> = Vec::new();
20662 let commands = recorder.commands();
20663 for command in &commands {
20664 match command {
20665 Command::BeginRenderPass { label: name, .. } => {
20666 label = name.clone();
20667 calls = Vec::new();
20668 }
20669 Command::EndRenderPass => {
20670 if !calls.is_empty() {
20671 passes.push((
20672 label.clone().expect("every pass here is labelled"),
20673 std::mem::take(&mut calls),
20674 ));
20675 }
20676 }
20677 Command::BindGraphicsPipeline(handle) => {
20678 current = Some(*handle);
20679 if twin_of(*handle).is_some() {
20680 twins_bound += 1;
20681 }
20682 // The fold turns a `single, double` pair into
20683 // `single, single`; collapsing a run of equal binds is
20684 // what makes the two streams comparable without hiding
20685 // a bind of anything else.
20686 let folded_handle = twin_of(*handle).unwrap_or(*handle);
20687 if folded.last() != Some(&folded_handle) {
20688 folded.push(folded_handle);
20689 }
20690 }
20691 Command::DrawIndexedIndirectCount(draw) => {
20692 let handle = current.expect("a draw follows a pipeline bind");
20693 calls.push((twin_of(handle).is_some(), bucket_of(draw.args_offset)));
20694 }
20695 Command::DrawIndexedIndirect(draw) => {
20696 let handle = current.expect("a draw follows a pipeline bind");
20697 calls.push((twin_of(handle).is_some(), bucket_of(draw.offset)));
20698 }
20699 _ => {}
20700 }
20701 }
20702 let modes = renderer.bucket_modes.clone();
20703 renderer.destroy(device);
20704 pool.destroy(device);
20705 device.destroy_image_view(imported.view);
20706 device.destroy_image(imported.image);
20707 recorder.assert_valid();
20708 Recorded {
20709 modes,
20710 twins_bound,
20711 passes,
20712 folded,
20713 }
20714 };
20715
20716 let single = bound(&single_scene);
20717 let double = bound(&double_scene);
20718
20719 assert_eq!(
20720 single.twins_bound, 0,
20721 "a scene with nothing double-sided must never bind a cull-none twin"
20722 );
20723 // Named rather than counted, because the claim is that **every** pass
20724 // that draws the surface routes: a frame that had quietly stopped
20725 // recording one of them would satisfy a count and leave that pass's
20726 // routing unchecked for ever.
20727 let drawing: Vec<&str> = single
20728 .passes
20729 .iter()
20730 .map(|(name, _)| name.as_str())
20731 .collect();
20732 for pass in ["shadow", "depth-prepass", "forward", "rsm", "rsm-punctual"] {
20733 assert!(
20734 drawing.contains(&pass),
20735 "`{pass}` drew nothing in this frame, so its routing is unchecked: {drawing:?}"
20736 );
20737 }
20738 assert!(
20739 double.twins_bound > 0,
20740 "a double-sided scene must bind the cull-none twins"
20741 );
20742 assert_eq!(
20743 double
20744 .passes
20745 .iter()
20746 .map(|(name, _)| name)
20747 .collect::<Vec<_>>(),
20748 single
20749 .passes
20750 .iter()
20751 .map(|(name, _)| name)
20752 .collect::<Vec<_>>(),
20753 "the two frames must draw in the same passes, or they are not comparable"
20754 );
20755
20756 // What each drawing pass should have recorded: every single-sided bucket
20757 // under the plain pipeline in bucket order, then every double-sided one
20758 // under the twin — the partition order `sided_partitions` lays down —
20759 // repeated once per view for a pass that draws several.
20760 let want: Vec<(bool, u32)> = [false, true]
20761 .into_iter()
20762 .flat_map(|twin| {
20763 double
20764 .modes
20765 .iter()
20766 .enumerate()
20767 .filter(move |(_, mode)| {
20768 (**mode & crcbl_shaders::mesh::GpuMaterial::DOUBLE_SIDED != 0) == twin
20769 })
20770 .map(move |(bucket, _)| (twin, u32::try_from(bucket).expect("a few buckets")))
20771 })
20772 .collect();
20773 assert!(
20774 want.iter().any(|(twin, _)| *twin) && want.iter().any(|(twin, _)| !*twin),
20775 "the double-sided demo has to hold buckets of both sides, or this compares one \
20776 partition against itself: {:?}",
20777 double.modes
20778 );
20779 for (name, calls) in &double.passes {
20780 let views = calls.len() / want.len();
20781 assert!(
20782 views > 0 && calls.len() % want.len() == 0,
20783 "`{name}` recorded {} call(s) over {} bucket(s), which is not a whole number of \
20784 views",
20785 calls.len(),
20786 want.len()
20787 );
20788 // The partition is **outside** any view loop — one pipeline bind
20789 // covers every view of that side — so the stream is each partition's
20790 // bucket list repeated once per view.
20791 let mut expected: Vec<(bool, u32)> = Vec::with_capacity(calls.len());
20792 for twin in [false, true] {
20793 let partition: Vec<(bool, u32)> = want
20794 .iter()
20795 .copied()
20796 .filter(|(side, _)| *side == twin)
20797 .collect();
20798 for _ in 0..views {
20799 expected.extend_from_slice(&partition);
20800 }
20801 }
20802 assert_eq!(
20803 *calls, expected,
20804 "`{name}` must record each bucket once per view, under the pipeline its own \
20805 side asked for"
20806 );
20807 }
20808
20809 assert_eq!(
20810 double.folded, single.folded,
20811 "the frame gained or lost a pipeline bind beyond a cull-none twin beside the \
20812 pipeline it twins"
20813 );
20814 }
20815
20816 /// **The wireframe view swaps the colour pass's pipeline and nothing else.**
20817 ///
20818 /// The mechanism, at the level a null device can observe it: which pipeline
20819 /// handle each pass of the recorded stream binds. A field on the renderer
20820 /// would say only that a flag moved — this says the *frame* moved, and says
20821 /// which part of it did.
20822 ///
20823 /// Four claims, and each rules out a different way of passing wrongly:
20824 ///
20825 /// * the filled pipeline is bound on a frame nobody asked, and the wireframe
20826 /// one does not exist;
20827 /// * switching on **removes** the filled pipeline from the stream — a second
20828 /// pipeline that was built and never bound would still leave it there;
20829 /// * every other pipeline the frame binds is unchanged, so the depth prepass
20830 /// and the shadow cascades are still filling triangles;
20831 /// * and switching off puts the stream back exactly, so the view is a toggle
20832 /// rather than a one-way door.
20833 #[test]
20834 fn the_wireframe_view_swaps_the_colour_passs_pipeline_and_no_other() {
20835 use crcbl_hal::null::Command;
20836
20837 // The pipelines a frame binds include one per occlusion blur, and the
20838 // blur count is a process-global console variable — so a concurrent
20839 // test holding `r_ssao_blur_passes` at two adds a bind to one of the
20840 // frames below and not to the others. It reddened this assertion on
20841 // 2026-08-31 under a workspace `cargo test`.
20842 let _blurs = ssao_blur_switch();
20843 let (recorder, device, queue) =
20844 open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20845 let device = device.as_ref();
20846 assert!(
20847 ForwardRenderer::supports_wireframe(device),
20848 "this test needs the line fill mode, and asked the device for it",
20849 );
20850 let mut renderer =
20851 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20852 place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20853 let imported = swapchain_image(device);
20854 let mut pool = crate::TransientPool::new();
20855
20856 // The pipelines one frame binds, in record order. Cumulative recorder,
20857 // so each call takes the tail its own frame added.
20858 let mut seen = 0usize;
20859 // A different sun each lap, so the shadow atlas is redrawn in every one
20860 // of them: the comparison below is "which pipelines did this frame
20861 // bind", and a lap that cached its atlas would bind the depth-only
20862 // pipeline one fewer time for a reason that has nothing to do with the
20863 // wireframe. See [`moving_sun`].
20864 let mut lap = 0u32;
20865 let mut pipelines_in_a_frame = |renderer: &mut ForwardRenderer, pool: &mut _| {
20866 lap += 1;
20867 renderer
20868 .begin_frame(device, &Camera::default(), &moving_sun(lap), (64, 48))
20869 .expect("write");
20870 let mut graph = crate::RenderGraph::new(queue);
20871 let target = graph.import_image("target", imported);
20872 renderer.add_passes(&mut graph, pool, target, (64, 48));
20873 let compiled = graph.compile(pool).expect("a legal frame");
20874 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
20875 label: Some("wireframe lap"),
20876 queue,
20877 });
20878 compiled
20879 .execute(device, pool, encoder.as_mut(), None)
20880 .expect("the graph executed");
20881 encoder.finish().expect("recording succeeded");
20882 let commands = recorder.commands();
20883 let bound: Vec<GraphicsPipelineHandle> = commands[seen..]
20884 .iter()
20885 .filter_map(|command| match command {
20886 Command::BindGraphicsPipeline(handle) => Some(*handle),
20887 _ => None,
20888 })
20889 .collect();
20890 seen = commands.len();
20891 bound
20892 };
20893
20894 let filled = renderer.mesh_pipeline.single;
20895 let off = pipelines_in_a_frame(&mut renderer, &mut pool);
20896 assert!(
20897 off.contains(&filled),
20898 "a frame nobody asked has to bind the filled pipeline: {off:?}",
20899 );
20900 assert!(!renderer.wireframe());
20901 assert!(
20902 renderer.wireframe_pipeline.is_none(),
20903 "the wireframe pipeline must not be built until it is asked for",
20904 );
20905
20906 renderer
20907 .set_wireframe(device, true)
20908 .expect("a device with the line fill mode builds it");
20909 assert!(renderer.wireframe());
20910 let lines = renderer
20911 .wireframe_pipeline
20912 .expect("switching on is what builds it")
20913 .single;
20914 let on = pipelines_in_a_frame(&mut renderer, &mut pool);
20915 assert!(
20916 !on.contains(&filled),
20917 "the colour pass still bound the filled pipeline: {on:?}",
20918 );
20919 assert_eq!(
20920 on.iter().filter(|handle| **handle == lines).count(),
20921 1,
20922 "the wireframe pipeline has to be bound exactly once — by the colour pass: {on:?}",
20923 );
20924 let substituted: Vec<GraphicsPipelineHandle> = on
20925 .iter()
20926 .map(|handle| if *handle == lines { filled } else { *handle })
20927 .collect();
20928 assert_eq!(
20929 substituted, off,
20930 "the frame gained or lost a pipeline bind beyond the colour pass's: {on:?} against \
20931 {off:?}",
20932 );
20933
20934 renderer
20935 .set_wireframe(device, false)
20936 .expect("switching off builds nothing");
20937 assert!(!renderer.wireframe());
20938 assert_eq!(
20939 pipelines_in_a_frame(&mut renderer, &mut pool),
20940 off,
20941 "switching the view off has to put the filled pipeline back, not just stop reporting \
20942 it",
20943 );
20944
20945 renderer.destroy(device);
20946 pool.destroy(device);
20947 device.destroy_image_view(imported.view);
20948 device.destroy_image(imported.image);
20949 recorder.assert_valid();
20950 }
20951
20952 /// **The colour pass tests against the prepass's depth instead of clearing
20953 /// and rewriting it, so each pixel is shaded once** — and a wireframe frame
20954 /// does the opposite, because lines do not reproduce a filled prepass.
20955 ///
20956 /// Both halves have to hold together or the frame is wrong in one of two
20957 /// ways, so both are asserted here. The attachment alone read-only while the
20958 /// pipeline still wrote would be a pipeline writing to a read-only
20959 /// attachment; the pipeline alone on `GreaterOrEqual` against an attachment
20960 /// this pass had just *cleared* would reject every fragment and draw a black
20961 /// frame. Neither shows up as an error — the first is a validation message
20962 /// on one backend and undefined behaviour on the rest, the second is a
20963 /// picture — which is why the observable is read off the compiled graph and
20964 /// off the pipeline state rather than off a screenshot.
20965 #[test]
20966 fn the_colour_pass_shades_once_per_pixel_against_the_prepasss_depth() {
20967 let (recorder, device, queue) =
20968 open_with(Features::GPU_DRIVEN | Features::POLYGON_MODE_LINE);
20969 let device = device.as_ref();
20970 let mut renderer =
20971 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
20972 place_demo(&mut renderer, DEMO_CUBE, DEMO_UNTINTED, Mat4::IDENTITY);
20973 let imported = swapchain_image(device);
20974 let mut pool = crate::TransientPool::new();
20975
20976 // Each pass's depth attachment, off the graph's own dump: the label it
20977 // was declared under, and the `load`/`store`/`write` triple the backend
20978 // is handed. A pass with no depth attachment contributes nothing, which
20979 // is what makes the lookup below a search rather than an index.
20980 let depth_of = |renderer: &mut ForwardRenderer, pool: &mut _, label: &str| {
20981 renderer
20982 .begin_frame(
20983 device,
20984 &Camera::default(),
20985 &DirectionalLight::default(),
20986 (64, 48),
20987 )
20988 .expect("write");
20989 let mut graph = crate::RenderGraph::new(queue);
20990 let target = graph.import_image("target", imported);
20991 renderer.add_passes(&mut graph, pool, target, (64, 48));
20992 let dump = graph.compile(pool).expect("a legal frame").dump();
20993 let mut pass = String::new();
20994 let mut found = None;
20995 for line in dump.lines() {
20996 if let Some(rest) = line.split(" pass \"").nth(1) {
20997 pass = rest.trim_end_matches('"').to_string();
20998 if let Some((name, _)) = pass.split_once('"') {
20999 pass = name.to_string();
21000 }
21001 }
21002 if pass == label
21003 && let Some(at) = line.find("depth load=")
21004 {
21005 // Without the slot note the dump appends: which physical
21006 // image the transient landed on is aliasing's business, not
21007 // this assertion's.
21008 let role = &line[at..];
21009 let role = role.split_once(" [").map_or(role, |(head, _)| head);
21010 found = Some(role.trim().to_string());
21011 }
21012 }
21013 found.unwrap_or_else(|| panic!("no depth attachment on `{label}`:\n{dump}"))
21014 };
21015
21016 assert_eq!(
21017 depth_of(&mut renderer, &mut pool, "depth-prepass"),
21018 "depth load=Clear store=Store write=yes",
21019 "the prepass is what puts the depth there, so it clears, writes and keeps it",
21020 );
21021 assert_eq!(
21022 depth_of(&mut renderer, &mut pool, "forward"),
21023 "depth load=Load store=Store write=no",
21024 "and the colour pass reads it: a clear here would throw away the prepass and \
21025 pay for the overdraw again, and a write would be a second pass writing the \
21026 same values",
21027 );
21028 assert_eq!(
21029 MeshModules::color_depth_stencil(PolygonMode::Fill),
21030 Some(DepthStencilState {
21031 format: Format::D32Float,
21032 depth_write: false,
21033 depth_compare: CompareOp::GreaterOrEqual,
21034 stencil: None,
21035 bias: DepthBias::default(),
21036 }),
21037 "and the pipeline agrees with the attachment: equality against the prepass, \
21038 reachable only through the `OrEqual` under reversed-Z",
21039 );
21040
21041 renderer
21042 .set_wireframe(device, true)
21043 .expect("this device was asked for the line fill mode");
21044 assert_eq!(
21045 depth_of(&mut renderer, &mut pool, "forward"),
21046 "depth load=Clear store=Store write=yes",
21047 "a wireframe frame keeps the old shape: `PolygonMode::Line` interpolates depth \
21048 along the edge rather than across the face, so testing it against a filled \
21049 prepass rejects most of the wireframe — and *loading* that depth under the \
21050 writing default's `Greater` would reject all of it",
21051 );
21052 assert_eq!(
21053 MeshModules::color_depth_stencil(PolygonMode::Line),
21054 MeshModules::depth_stencil(),
21055 "which is the writing default, the same state the depth-only twin uses",
21056 );
21057
21058 renderer.destroy(device);
21059 pool.destroy(device);
21060 device.destroy_image_view(imported.view);
21061 device.destroy_image(imported.image);
21062 recorder.assert_valid();
21063 }
21064
21065 /// **A device with no line fill mode is refused, not quietly filled.**
21066 ///
21067 /// The failure this rules out is the silent one: a caller who binds a key to
21068 /// this, presses it, and gets the solid frame back with nothing anywhere
21069 /// saying why — which on a model whose silhouette hides its interior is
21070 /// indistinguishable from a wireframe that worked. WebGPU is the real device
21071 /// this happens on; `open`'s null device stands in for it, because
21072 /// [`DeviceDesc::for_adapter`] asks for
21073 /// [`Features::GPU_DRIVEN`] and nothing else.
21074 #[test]
21075 fn a_device_without_the_line_fill_mode_refuses_the_wireframe_rather_than_filling_it() {
21076 let (recorder, device, queue) = open();
21077 let device = device.as_ref();
21078 assert!(
21079 !ForwardRenderer::supports_wireframe(device),
21080 "this device was not asked for the line fill mode, so it must not report it",
21081 );
21082 let mut renderer =
21083 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21084
21085 let refused = renderer
21086 .set_wireframe(device, true)
21087 .expect_err("a device without the feature has to say so");
21088 assert!(
21089 matches!(
21090 refused,
21091 HalError::UnsupportedFeatures { missing } if missing == Features::POLYGON_MODE_LINE
21092 ),
21093 "the refusal has to name the feature to go and look up, and is {refused:?}",
21094 );
21095 assert!(
21096 !renderer.wireframe(),
21097 "a refused request must leave the view off rather than half on",
21098 );
21099 assert!(
21100 renderer.wireframe_pipeline.is_none(),
21101 "nothing may be left behind by a refusal",
21102 );
21103 // And switching *off* is still fine on such a device: it builds nothing.
21104 renderer
21105 .set_wireframe(device, false)
21106 .expect("switching off asks the device for nothing");
21107
21108 renderer.destroy(device);
21109 recorder.assert_valid();
21110 }
21111
21112 /// The grid's own full-screen triangle is counted as submitted, and only
21113 /// while it is on.
21114 ///
21115 /// [`FrameCounters::instances`] is the "submitted" half of the debug panel's
21116 /// row, and every full-screen pass in the frame contributes one — so a grid
21117 /// that drew and was not counted makes that row disagree with the frame by
21118 /// exactly one triangle, silently.
21119 #[test]
21120 fn the_grids_triangle_is_counted_only_while_it_is_on() {
21121 let _blurs = ssao_blur_switch();
21122 let (recorder, device, queue) = open();
21123 let device = device.as_ref();
21124 let mut renderer =
21125 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21126 let imported = swapchain_image(device);
21127 let mut pool = crate::TransientPool::new();
21128
21129 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21130 let off = renderer.counters();
21131
21132 renderer
21133 .set_ground_grid(device, Some(GridStyle::default()))
21134 .expect("the null backend builds every pipeline");
21135 passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
21136 let on = renderer.counters();
21137
21138 assert_eq!(
21139 on.draws - off.draws,
21140 FULLSCREEN_DRAWS,
21141 "the grid records exactly one draw"
21142 );
21143 assert_eq!(
21144 on.instances - off.instances,
21145 FULLSCREEN_DRAWS,
21146 "and exactly one submitted instance"
21147 );
21148
21149 renderer.destroy(device);
21150 pool.destroy(device);
21151 device.destroy_image_view(imported.view);
21152 device.destroy_image(imported.image);
21153 recorder.assert_valid();
21154 }
21155
21156 /// One frame on a device of its own, under an override switching `off`.
21157 ///
21158 /// **A device of its own per arm**, because a [`Recorder`] accumulates for a
21159 /// device's whole life: asking "did the atlas pass draw" of a recorder that
21160 /// has seen two frames answers about both of them, and the arm that matters
21161 /// most here is the one whose answer must be zero.
21162 ///
21163 /// Returns what the frame reported and what its atlas pass actually drew.
21164 fn frame_switching_off(off: RenderEffects) -> (FrameCounters, u64, usize) {
21165 use crcbl_hal::null::Command;
21166
21167 let recorder = Recorder::new();
21168 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21169 let adapter = instance.adapters().remove(0);
21170 let opened = instance
21171 .create_device(&DeviceDesc::for_adapter(adapter.id))
21172 .expect("the null backend always opens");
21173 let device = opened.as_ref();
21174 let queue = opened.queue(QueueKind::Graphics).expect("always present");
21175 let mut renderer =
21176 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21177 // A shadowed light beside the cascades, so the atlas pass has draws to
21178 // lose rather than being empty either way.
21179 renderer.set_lights(&[shadowable_spot(-1.0)]);
21180 // **[`OUTSIDE_THE_DEFAULT`] forced on, then `off` forced off.** The default
21181 // camera stack leaves both of them out — see
21182 // [`RenderEffects::DEFAULT_STACK`] — so a control frame built on the
21183 // default alone would be measuring three effects and calling it five,
21184 // and their arms below would be switching off something already off.
21185 // `force` clears the other side, so an arm whose `off` is one of them
21186 // still resolves to off.
21187 renderer.set_effect_request(EffectRequest {
21188 programmatic: EffectOverride::none()
21189 .force(OUTSIDE_THE_DEFAULT, Some(true))
21190 .force(off, Some(false)),
21191 ..EffectRequest::default()
21192 });
21193
21194 let recorded = frame(device, &mut renderer, queue);
21195 assert_eq!(
21196 renderer.effects(),
21197 RenderEffects::all().difference(off),
21198 "the frame must have resolved to the set the request asked for"
21199 );
21200 let counters = renderer.counters();
21201 let instances = renderer.instances.len() as u64;
21202 let atlas_draws = commands_in_pass(&recorder, "shadow")
21203 .into_iter()
21204 .filter(|command| {
21205 matches!(
21206 command,
21207 Command::DrawIndexedIndirect(_)
21208 | Command::DrawIndexedIndirectCount(_)
21209 | Command::DrawMeshTasksIndirect(_)
21210 )
21211 })
21212 .count();
21213 assert_eq!(
21214 counters.draws,
21215 recorded_draws(&recorder) as u64,
21216 "the counter and the frame's own recorded stream must agree, whatever is switched off"
21217 );
21218 recorded.finish(device, renderer);
21219 recorder.assert_valid();
21220 (counters, instances, atlas_draws)
21221 }
21222
21223 /// **A switched-off effect is work the frame did not record**, and a frame
21224 /// that still executes with the placeholder bound in place of what it lost.
21225 ///
21226 /// The other half of the pass-list test above, and the half a pass list
21227 /// cannot make: the `shadow` pass is still *there* with shadows off, so the
21228 /// question is whether it drew. That answer comes off the recorded command
21229 /// stream, which is a different instrument from `recorded_draws` — the number
21230 /// under test.
21231 ///
21232 /// Executed rather than only compiled, because the occlusion switch changes
21233 /// which image the forward pass has bound. A frame that declared a read of a
21234 /// transient it never created, or bound a view the graph never realised,
21235 /// fails here and compiles perfectly.
21236 #[test]
21237 fn a_switched_off_effect_is_work_the_frame_did_not_record() {
21238 let _blurs = ssao_blur_switch();
21239 let (control, instances, atlas_draws) = frame_switching_off(RenderEffects::empty());
21240 assert!(
21241 atlas_draws > 0,
21242 "with shadows on the atlas pass has to draw something, or turning it off means \
21243 nothing"
21244 );
21245 assert_eq!(
21246 control.instances,
21247 instances
21248 + fullscreen_passes(
21249 RenderEffects::all(),
21250 TEST_EXTENT,
21251 false,
21252 crate::ssao::blur_passes(),
21253 ) * FULLSCREEN_DRAWS,
21254 "the control frame submits one triangle per full-screen pass"
21255 );
21256
21257 // Each pair is one full-screen triangle per pass, and the atlas is
21258 // untouched by either.
21259 for (off, fewer) in [
21260 (
21261 RenderEffects::AMBIENT_OCCLUSION,
21262 u64::from(Ssao::passes(crate::ssao::blur_passes())),
21263 ),
21264 // The contact march's one pass, and a constant rather than a
21265 // function of anything: it has no blur behind it and no chain.
21266 (
21267 RenderEffects::CONTACT_SHADOWS,
21268 u64::from(ContactShadows::PASSES),
21269 ),
21270 // The march's two passes and the reductions that feed them, which
21271 // is what makes this arm's number a function of the extent the way
21272 // the chain's below is.
21273 (
21274 RenderEffects::REFLECTIONS,
21275 u64::from(Ssr::PASSES) + u64::from(crate::hiz::levels_for(TEST_EXTENT)),
21276 ),
21277 // Not a constant, unlike the occlusion pair above: the chain's
21278 // length is a function of the extent, and this is what it is at
21279 // `TEST_EXTENT`.
21280 (
21281 RenderEffects::BLOOM,
21282 u64::from(Bloom::passes_for(TEST_EXTENT)),
21283 ),
21284 ] {
21285 let (counters, instances, atlas) = frame_switching_off(off);
21286 assert_eq!(
21287 counters.draws,
21288 control.draws - fewer * FULLSCREEN_DRAWS,
21289 "{off:?}: the frame must record one draw fewer per pass it did not add"
21290 );
21291 assert_eq!(
21292 counters.instances,
21293 instances
21294 + fullscreen_passes(
21295 RenderEffects::all().difference(off),
21296 TEST_EXTENT,
21297 false,
21298 crate::ssao::blur_passes(),
21299 ) * FULLSCREEN_DRAWS,
21300 "{off:?}: and must not report as submitted a triangle it never submitted"
21301 );
21302 assert_eq!(
21303 atlas, atlas_draws,
21304 "{off:?}: a screen-space effect must not touch the shadow atlas"
21305 );
21306 }
21307
21308 // Shadows: the atlas pass survives and draws nothing at all, which is
21309 // the mechanism — a cleared reversed-Z atlas reads as fully lit.
21310 let (counters, _, atlas) = frame_switching_off(RenderEffects::SHADOWS);
21311 assert_eq!(
21312 atlas, 0,
21313 "with shadows off the atlas pass must record its clear and no draw"
21314 );
21315 assert_eq!(
21316 counters.draws,
21317 control.draws - atlas_draws as u64,
21318 "and the frame must record exactly the atlas pass's draws fewer"
21319 );
21320 }
21321
21322 /// **Every pass the frame records gets a row in the report, except the ones
21323 /// that open no scope.**
21324 ///
21325 /// The observable the bound exists for: the samples' hand-picked capacity
21326 /// timed the first eight passes of a fourteen-pass frame and reported eight
21327 /// rows, which reads exactly like a frame that has eight passes. Sized from
21328 /// [`MAX_TIMED_PASSES`](crate::MAX_TIMED_PASSES), the report names every
21329 /// pass the graph compiled, in order — so a bound one short of the frame
21330 /// makes this list short too.
21331 ///
21332 /// A [`PassKind::Copy`](crate::graph::PassKind::Copy) is filtered out of the
21333 /// expectation rather than expected to be missing by accident. The seam
21334 /// takes a timestamp only where a pass opens and closes and a copy opens
21335 /// nothing, so `PassTimers` gives it no query pair and no row — a row
21336 /// reading 0.000 ms would be a measurement nobody made.
21337 #[test]
21338 fn every_pass_of_the_frame_gets_a_timing_row() {
21339 let _blurs = ssao_blur_switch();
21340 // And the comparison seam, so the frame this checks carries the
21341 // occlusion chain's second march: `docs/plan/ROADMAP.md`'s S4D row asks
21342 // for a *per-technique* cost, and what makes that true is this test's
21343 // own claim — every pass that opens a scope gets a row — applied to a
21344 // frame that compares. See `crate::ssao`'s `r_ssao_split`.
21345 let split = ssao_split_switch();
21346 split.set(0.5);
21347 let recorder = Recorder::new();
21348 let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
21349 let adapter = instance.adapters().remove(0);
21350 // `TIMESTAMP_QUERY` is not part of `GPU_DRIVEN` — topic 10's browsers
21351 // may lack it — so a device that wants timers has to ask for it, and
21352 // `open` above, which uses `DeviceDesc::for_adapter`, does not.
21353 let opened = instance
21354 .create_device(&DeviceDesc {
21355 label: Some("timed frame"),
21356 adapter: adapter.id,
21357 required_features: Features::GPU_DRIVEN,
21358 optional_features: Features::TIMESTAMP_QUERY,
21359 compatible_surface: None,
21360 })
21361 .expect("the null backend always opens");
21362 let queue = opened.queue(QueueKind::Graphics).expect("always present");
21363 let device = opened.as_ref();
21364 let mut renderer =
21365 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
21366 renderer.set_lights(&[shadowable_spot(-1.0), shadowable_spot(1.0)]);
21367 let mut timers = crate::PassTimers::new(device, FRAMES_IN_FLIGHT, crate::MAX_TIMED_PASSES)
21368 .expect("the tier A null adapter has timestamp queries");
21369 let imported = swapchain_image(device);
21370 let mut pool = crate::TransientPool::new();
21371 let mut recorded = Vec::new();
21372 let mut compiled_labels = Vec::new();
21373
21374 // The ring is one slot longer than the frames in flight and resolves a
21375 // slot only when it comes round again, so the first frame's report is
21376 // that many frames behind it — see the [`timing`](crate::timing) docs.
21377 for _ in 0..FRAMES_IN_FLIGHT + 2 {
21378 renderer
21379 .begin_frame(
21380 device,
21381 &Camera::default(),
21382 &DirectionalLight::default(),
21383 (64, 48),
21384 )
21385 .expect("write");
21386 let mut graph = crate::RenderGraph::new(queue);
21387 let target = graph.import_image("target", imported);
21388 renderer.add_passes(&mut graph, &pool, target, (64, 48));
21389 let compiled = graph.compile(&pool).expect("a legal frame");
21390 if compiled_labels.is_empty() {
21391 compiled_labels = compiled
21392 .passes()
21393 .iter()
21394 .filter(|pass| pass.kind() != crate::graph::PassKind::Copy)
21395 .map(|pass| pass.label().to_string())
21396 .collect();
21397 }
21398 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
21399 label: Some("timed frame"),
21400 queue,
21401 });
21402 compiled
21403 .execute(device, &mut pool, encoder.as_mut(), Some(&mut timers))
21404 .expect("the graph executed");
21405 recorded.push(encoder.finish().expect("recording succeeded"));
21406 }
21407
21408 let reported: Vec<&str> = timers
21409 .latest()
21410 .passes
21411 .iter()
21412 .map(|timing| timing.label.as_str())
21413 .collect();
21414 // Anti-vacuity for the seam held above: a frame that did not compare
21415 // would satisfy the equality below and say nothing about a
21416 // per-technique cost, because there would be one technique in it.
21417 for label in ["ssao", "ssao-shipped"] {
21418 assert!(
21419 compiled_labels.iter().any(|pass| pass == label),
21420 "the frame compiled no `{label}` pass, so the seam did not reach it and this \
21421 test says nothing about a comparison having a cost per side. Its passes: \
21422 {compiled_labels:?}"
21423 );
21424 }
21425 assert_eq!(
21426 reported,
21427 compiled_labels,
21428 "the report must name every pass the frame compiled that opens a scope, in order \
21429 — {} of {} timed with a capacity of {}",
21430 reported.len(),
21431 compiled_labels.len(),
21432 timers.capacity()
21433 );
21434
21435 timers.destroy(device);
21436 renderer.destroy(device);
21437 for commands in recorded {
21438 device.destroy_command_buffer(commands);
21439 }
21440 pool.destroy(device);
21441 device.destroy_image_view(imported.view);
21442 device.destroy_image(imported.image);
21443 recorder.assert_valid();
21444 }
21445
21446 /// One mesh-table entry, decoded from the bytes that reached the device.
21447 fn mesh_entry(
21448 recorder: &Recorder,
21449 renderer: &ForwardRenderer,
21450 id: u32,
21451 ) -> crcbl_shaders::mesh::GpuMesh {
21452 let table = recorder
21453 .buffer_bytes(renderer.pool.table_buffer())
21454 .expect("the table is live");
21455 let at = id as usize * crcbl_shaders::mesh::MESH_ENTRY_STRIDE;
21456 crcbl_shaders::mesh::GpuMesh::from_bytes(
21457 table[at..at + crcbl_shaders::mesh::MESH_ENTRY_STRIDE]
21458 .try_into()
21459 .expect("one whole entry"),
21460 )
21461 }
21462
21463 // --- skinning: the seam a caller draws a skinned mesh through -----------
21464
21465 /// A renderer with [`scene::demo`]'s cube reserved for skinning, and a
21466 /// [`Skinning`] built against that renderer's own vertex pool.
21467 struct SkinnedFixture {
21468 renderer: ForwardRenderer,
21469 skinning: Skinning,
21470 skinned: SkinnedMesh,
21471 palette: Vec<Mat4>,
21472 bindings: Vec<crcbl_shaders::skinning::SkinBinding>,
21473 }
21474
21475 impl SkinnedFixture {
21476 fn build(device: &dyn Device, queue: QueueHandle) -> Self {
21477 let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
21478 .expect("the null backend accepts every descriptor");
21479 let skinned = renderer
21480 .reserve_skinned(DEMO_CUBE)
21481 .expect("a default pool has room for two halves of a cube");
21482 let skinning = Skinning::new(
21483 device,
21484 &crate::skinning::SkinningDesc {
21485 label: Some("skinned fixture"),
21486 frames: FRAMES_IN_FLIGHT,
21487 ranges: 1,
21488 joints: 1,
21489 bindings: skinned.vertex_count(),
21490 // The renderer's own pool, which is the whole of what makes
21491 // the dispatch's output reachable by its draws.
21492 vertices: renderer.vertex_buffer(),
21493 attribute_base: renderer.attribute_base(),
21494 },
21495 )
21496 .expect("the null backend accepts every descriptor");
21497 let bindings = vec![
21498 crcbl_shaders::skinning::SkinBinding {
21499 joints: [0; crcbl_shaders::skinning::JOINTS_PER_VERTEX],
21500 weights: [1.0, 0.0, 0.0, 0.0],
21501 };
21502 skinned.vertex_count() as usize
21503 ];
21504 Self {
21505 renderer,
21506 skinning,
21507 skinned,
21508 palette: vec![Mat4::IDENTITY],
21509 bindings,
21510 }
21511 }
21512
21513 /// One skinned frame's `begin_skinned_frame`, with this fixture's single
21514 /// range.
21515 fn begin(&mut self, device: &dyn Device) {
21516 let range = self.skinned.skin_range(&self.palette, &self.bindings);
21517 self.renderer
21518 .begin_skinned_frame(
21519 device,
21520 &mut self.skinning,
21521 &[range],
21522 &Camera::default(),
21523 &DirectionalLight::default(),
21524 TEST_EXTENT,
21525 )
21526 .expect("a legal skinning plan");
21527 }
21528
21529 fn destroy(mut self, device: &dyn Device) {
21530 self.renderer.release_skinned(self.skinned);
21531 self.skinning.destroy(device);
21532 self.renderer.destroy(device);
21533 }
21534 }
21535
21536 /// How many times the host wrote the mesh-table entry `id` names.
21537 fn table_writes(recorder: &Recorder, renderer: &ForwardRenderer, id: u32) -> usize {
21538 let table = renderer.pool.table_buffer();
21539 let at = u64::from(id) * crcbl_shaders::mesh::MESH_ENTRY_STRIDE as u64;
21540 recorder
21541 .events()
21542 .into_iter()
21543 .filter(|event| {
21544 matches!(
21545 event,
21546 crcbl_hal::null::Event::BufferWritten { buffer, offset, .. }
21547 if *buffer == table && *offset == at
21548 )
21549 })
21550 .count()
21551 }
21552
21553 /// The record `handle` names, out of the ring buffer **this frame draws
21554 /// from** rather than out of the pool's host mirror.
21555 ///
21556 /// A mirror and a buffer that disagree is exactly the defect a re-pointing
21557 /// design can have, so every claim about a skinned instance's bases is read
21558 /// off the bytes a shader would.
21559 fn instance_record(
21560 recorder: &Recorder,
21561 renderer: &ForwardRenderer,
21562 handle: InstanceHandle,
21563 ) -> mesh::GpuInstance {
21564 let buffer = renderer.instances.buffers()[renderer.frame()];
21565 let bytes = recorder.buffer_bytes(buffer).expect("the ring is live");
21566 let index = renderer
21567 .instances
21568 .index(handle)
21569 .expect("the object is live") as usize;
21570 let at = index * mesh::INSTANCE_STRIDE;
21571 mesh::GpuInstance::from_bytes(
21572 bytes[at..at + mesh::INSTANCE_STRIDE]
21573 .try_into()
21574 .expect("one whole instance"),
21575 )
21576 }
21577
21578 /// **A skinned primitive takes no mesh-table entry of its own, and nothing
21579 /// rewrites the one it draws through.**
21580 ///
21581 /// [`crate::mesh_pool`]'s table is one host-visible buffer rather than a ring
21582 /// precisely because nothing rewrites an entry between frames, so a design
21583 /// that re-pointed an entry at the half a frame writes would be wrong only
21584 /// on the frames that overlap — which is to say invisibly. What alternates
21585 /// instead is a field of the *instance*, and instances go through a ring.
21586 ///
21587 /// So a skinned object draws through the source mesh's own entry: the same
21588 /// id [`add_instance`](ForwardRenderer::add_instance) would give it, still
21589 /// carrying the bind pose's base vertex, still written exactly once after
21590 /// four skinned frames. That shared entry is also what lets one mesh be
21591 /// drawn skinned and unskinned in the same frame.
21592 #[test]
21593 fn a_skinned_mesh_takes_no_table_entry_and_rewrites_none() {
21594 let (recorder, device, queue) = open();
21595 let device = device.as_ref();
21596 let mut fixture = SkinnedFixture::build(device, queue);
21597
21598 let bind_pose_id = fixture.renderer.mesh_ids[DEMO_CUBE];
21599 assert_eq!(
21600 fixture.skinned.mesh_id(),
21601 bind_pose_id,
21602 "a skinned instance names the mesh it was deformed from, so the bucket, the level \
21603 tables and the bounding box all resolve as the bind pose's"
21604 );
21605
21606 let bind_pose = mesh_entry(&recorder, &fixture.renderer, bind_pose_id);
21607 assert_eq!(
21608 bind_pose.base_vertex,
21609 fixture.skinned.input_base(),
21610 "the entry goes on naming the bind pose the dispatch reads, not either half it \
21611 writes"
21612 );
21613 for parity in 0..2 {
21614 assert_ne!(
21615 fixture.skinned.region().base(parity),
21616 bind_pose.base_vertex,
21617 "half {parity} must not be the bind pose, which the kernel reads while it \
21618 writes them"
21619 );
21620 }
21621 assert_ne!(
21622 fixture.skinned.region().base(0),
21623 fixture.skinned.region().base(1),
21624 "the two halves are separate reservations, or the ping-pong is one buffer"
21625 );
21626
21627 // Counted before the frames rather than compared against a literal:
21628 // `MeshPool::new` clears the whole table with one write at offset zero,
21629 // which lands on this entry too, so the number here is the pool's
21630 // start-up and not this test's business. What the loop below has to
21631 // leave alone is whatever it is.
21632 let writes_before = table_writes(&recorder, &fixture.renderer, bind_pose_id);
21633 assert!(
21634 writes_before > 0,
21635 "the entry was written at least once before any frame ran, or the counter below \
21636 is counting nothing and the comparison after the frames is vacuous"
21637 );
21638
21639 // Four frames, which is two of each parity: enough that a design
21640 // rewriting an entry per frame would have written four more times.
21641 let imported = swapchain_image_at(device, TEST_EXTENT);
21642 let mut pool = crate::TransientPool::new();
21643 for _ in 0..4 {
21644 fixture.begin(device);
21645 let mut graph = crate::RenderGraph::new(queue);
21646 let target = graph.import_image("target", imported);
21647 fixture.renderer.add_skinned_passes(
21648 &mut graph,
21649 &pool,
21650 target,
21651 TEST_EXTENT,
21652 &fixture.skinning,
21653 );
21654 graph.compile(&pool).expect("a legal frame");
21655 }
21656
21657 assert_eq!(
21658 table_writes(&recorder, &fixture.renderer, bind_pose_id),
21659 writes_before,
21660 "entry {bind_pose_id} was written again by a skinned frame; the whole reason this \
21661 table is one buffer rather than a ring is that nothing rewrites an entry between \
21662 frames"
21663 );
21664
21665 fixture.destroy(device);
21666 pool.destroy(device);
21667 device.destroy_image_view(imported.view);
21668 device.destroy_image(imported.image);
21669 recorder.assert_valid();
21670 }
21671
21672 /// **A skinned object's recorded base vertex follows the parity of the frame
21673 /// it is drawn in**, and it carries the bit that makes a shader read it.
21674 ///
21675 /// The other half of the design: the table entry never moves, so what has to
21676 /// alternate is a field of the *instance* — and it has to alternate in the
21677 /// buffer the frame actually draws from, which is why this reads the
21678 /// instance ring's bytes rather than the host's mirror.
21679 ///
21680 /// Three claims, and the last two are what stop the first being vacuous. The
21681 /// base must be the one this frame's parity names; the record must carry
21682 /// [`GpuInstance::BASE_VERTEX_OVERRIDE`](mesh::GpuInstance::BASE_VERTEX_OVERRIDE),
21683 /// without which the raster stages read the mesh entry and the field is
21684 /// decoration; and two consecutive frames must have named **different**
21685 /// halves, without which a renderer ignoring the parity entirely would pass.
21686 #[test]
21687 fn a_skinned_draw_carries_the_base_the_frames_dispatch_filled() {
21688 let (recorder, device, queue) = open();
21689 let device = device.as_ref();
21690 let mut fixture = SkinnedFixture::build(device, queue);
21691 let handle = fixture
21692 .renderer
21693 .add_skinned_instance(&SkinnedInstanceDesc {
21694 mesh: &fixture.skinned,
21695 material: DEMO_UNTINTED,
21696 transform: Mat4::IDENTITY,
21697 })
21698 .expect("a pool of thousands has room for one object");
21699
21700 let mut carried = Vec::new();
21701 for _ in 0..2 {
21702 fixture.begin(device);
21703 let parity = fixture.skinning.parity();
21704 let instance = instance_record(&recorder, &fixture.renderer, handle);
21705 assert_eq!(
21706 instance.base_vertex,
21707 fixture.skinned.region().base(parity),
21708 "the buffer this frame draws from must carry the base parity {parity} writes"
21709 );
21710 assert_eq!(
21711 instance.flags & mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21712 mesh::GpuInstance::BASE_VERTEX_OVERRIDE,
21713 "without the bit the raster stages resolve the mesh entry's base and this \
21714 field is never read"
21715 );
21716 assert_eq!(
21717 instance.mesh, fixture.renderer.mesh_ids[DEMO_CUBE],
21718 "and the record still names the source mesh, which is what its bucket, its \
21719 levels and its bounding box resolve through"
21720 );
21721 carried.push(instance.base_vertex);
21722 }
21723 assert_ne!(
21724 carried[0], carried[1],
21725 "two consecutive frames must have drawn different halves, or a renderer that \
21726 ignored the parity entirely would pass this"
21727 );
21728
21729 fixture.destroy(device);
21730 recorder.assert_valid();
21731 }
21732
21733 /// **A skinned object's record names the half the frame before it filled**,
21734 /// and it starts at rest.
21735 ///
21736 /// The other half of a skinned motion vector. The base above is where a
21737 /// fragment *is*; this is where it *was*, and without it the geometry stages
21738 /// put the previous transform through this frame's deformed vertex — so a
21739 /// limb that swung reports the motion of the body it hangs off. See
21740 /// [`GpuInstance::previous_base_vertex`](mesh::GpuInstance::previous_base_vertex).
21741 ///
21742 /// Four claims, and the first and last are what stop the middle two being a
21743 /// restatement of the parity:
21744 ///
21745 /// * the **first** frame of a fresh object writes the base it draws out of,
21746 /// because the other half holds whatever its reservation came with and a
21747 /// motion vector against undefined vertices is worse than no motion;
21748 /// * the frames after it write
21749 /// [`SkinnedRegion::previous_base`](crate::skinning::SkinnedRegion::previous_base),
21750 /// which must also **differ** from the base they draw out of — a renderer
21751 /// that wrote the current base into both lanes would satisfy every "it is
21752 /// a legal base" reading of this and leave every skinned instance at rest;
21753 /// * and moving the object onto a **different region** puts it back at rest
21754 /// for one frame, because the halves it now names are two runs it has
21755 /// never been drawn out of.
21756 #[test]
21757 fn a_skinned_draw_carries_the_previous_half_and_starts_at_rest() {
21758 let (recorder, device, queue) = open();
21759 let device = device.as_ref();
21760 let mut fixture = SkinnedFixture::build(device, queue);
21761 let handle = fixture
21762 .renderer
21763 .add_skinned_instance(&SkinnedInstanceDesc {
21764 mesh: &fixture.skinned,
21765 material: DEMO_UNTINTED,
21766 transform: Mat4::IDENTITY,
21767 })
21768 .expect("a pool of thousands has room for one object");
21769
21770 for frame in 1..=3u32 {
21771 fixture.begin(device);
21772 let parity = fixture.skinning.parity();
21773 let instance = instance_record(&recorder, &fixture.renderer, handle);
21774 assert_eq!(
21775 instance.base_vertex,
21776 fixture.skinned.region().base(parity),
21777 "frame {frame} must draw out of the half parity {parity} fills"
21778 );
21779 if frame == 1 {
21780 assert_eq!(
21781 instance.previous_base_vertex, instance.base_vertex,
21782 "a fresh object has no previous deformation, so its first frame owes rest \
21783 rather than a half no dispatch has written"
21784 );
21785 } else {
21786 assert_eq!(
21787 instance.previous_base_vertex,
21788 fixture.skinned.region().previous_base(parity),
21789 "frame {frame} must subtract against the half the frame before it filled"
21790 );
21791 assert_ne!(
21792 instance.previous_base_vertex, instance.base_vertex,
21793 "frame {frame} named one half twice, which is every skinned fragment at \
21794 rest however far its surface moved"
21795 );
21796 }
21797 }
21798
21799 // The same object, moved onto a region it has never been drawn out of:
21800 // both halves are runs no dispatch of this object's has filled, so the
21801 // rule that put the first frame at rest applies again.
21802 let second = fixture
21803 .renderer
21804 .reserve_skinned(DEMO_CUBE)
21805 .expect("a default pool has room for two more halves of a cube");
21806 assert_ne!(
21807 second.region().base(0),
21808 fixture.skinned.region().base(0),
21809 "the second reservation is the same two runs as the first, so nothing below is \
21810 about a change of region at all"
21811 );
21812 fixture.renderer.set_skinned_instance(
21813 handle,
21814 &SkinnedInstanceDesc {
21815 mesh: &second,
21816 material: DEMO_UNTINTED,
21817 transform: Mat4::IDENTITY,
21818 },
21819 );
21820
21821 for frame in 1..=2u32 {
21822 fixture.begin(device);
21823 let parity = fixture.skinning.parity();
21824 let instance = instance_record(&recorder, &fixture.renderer, handle);
21825 assert_eq!(
21826 instance.base_vertex,
21827 second.region().base(parity),
21828 "frame {frame} after the move must draw out of the new region"
21829 );
21830 if frame == 1 {
21831 assert_eq!(
21832 instance.previous_base_vertex, instance.base_vertex,
21833 "the first frame on a new region owes rest, exactly as a fresh object does"
21834 );
21835 } else {
21836 assert_eq!(
21837 instance.previous_base_vertex,
21838 second.region().previous_base(parity),
21839 "and the frame after it is subtracting against the new region's other half"
21840 );
21841 }
21842 }
21843
21844 fixture.renderer.release_skinned(second);
21845 fixture.destroy(device);
21846 recorder.assert_valid();
21847 }
21848
21849 /// **A skinned object that moves carries the transform it moved from**, and
21850 /// the frame after it is back at rest.
21851 ///
21852 /// The transform half of a skinned motion vector, and the half the
21853 /// per-frame re-point used to erase: it rewrote the record through
21854 /// [`InstancePool::set`], which fills the previous transform out of the
21855 /// record it overwrites — and that record already held this frame's
21856 /// transform, because
21857 /// [`set_skinned_instance`](ForwardRenderer::set_skinned_instance) had put
21858 /// it there. Every skinned instance then read `previous_transform ==
21859 /// transform` on every frame, so a character that walked contributed
21860 /// nothing to the motion target from the walk, only from its deformation.
21861 /// [`InstancePool::set_bases`] is what the re-point goes through instead.
21862 ///
21863 /// Both frames are the claim. Without the second, a re-point that wrote
21864 /// some *other* stale transform into the field would pass; and the second
21865 /// is the pool's own rest rule reaching a skinned object at all, which a
21866 /// re-point that kept enrolling the element every frame would suppress
21867 /// for ever.
21868 ///
21869 /// Read out of the ring buffer the frame draws from, on
21870 /// [`instance_record`]'s terms.
21871 #[test]
21872 fn a_skinned_instance_that_moves_carries_the_transform_it_moved_from() {
21873 let (recorder, device, queue) = open();
21874 let device = device.as_ref();
21875 let mut fixture = SkinnedFixture::build(device, queue);
21876 let handle = fixture
21877 .renderer
21878 .add_skinned_instance(&SkinnedInstanceDesc {
21879 mesh: &fixture.skinned,
21880 material: DEMO_UNTINTED,
21881 transform: Mat4::IDENTITY,
21882 })
21883 .expect("a pool of thousands has room for one object");
21884
21885 // Two frames standing still, so the history the move is measured
21886 // against is a settled record rather than a fresh one.
21887 fixture.begin(device);
21888 fixture.begin(device);
21889
21890 let moved = Mat4::from_translation(Vec3::new(5.0, 0.0, 0.0));
21891 fixture.renderer.set_skinned_instance(
21892 handle,
21893 &SkinnedInstanceDesc {
21894 mesh: &fixture.skinned,
21895 material: DEMO_UNTINTED,
21896 transform: moved,
21897 },
21898 );
21899 fixture.begin(device);
21900 let instance = instance_record(&recorder, &fixture.renderer, handle);
21901 assert_eq!(
21902 instance.transform,
21903 moved.to_cols_array(),
21904 "the frame that moved the object must draw it where it arrived"
21905 );
21906 assert_eq!(
21907 instance.previous_transform,
21908 Mat4::IDENTITY.to_cols_array(),
21909 "and it must say where from — a previous transform equal to the current one is \
21910 the re-point having overwritten the move"
21911 );
21912
21913 fixture.begin(device);
21914 let settled = instance_record(&recorder, &fixture.renderer, handle);
21915 assert_eq!(
21916 settled.transform,
21917 moved.to_cols_array(),
21918 "nothing moved it again"
21919 );
21920 assert_eq!(
21921 settled.previous_transform, settled.transform,
21922 "so the frame after the move owes rest; a re-point that enrolled the element \
21923 every frame would keep it reporting the move for ever"
21924 );
21925
21926 fixture.destroy(device);
21927 recorder.assert_valid();
21928 }
21929
21930 /// **The graph barriers the skinning dispatch's write before every pass that
21931 /// pulls vertices**, and it does so because `add_skinned_passes` added the
21932 /// dispatch itself rather than trusting a caller to.
21933 ///
21934 /// Pass order alone would not settle it — a dispatch that ran first and was
21935 /// never barriered is the exact defect, and it produces a correct-looking
21936 /// frame on a desktop driver. So the transition out of
21937 /// [`ResourceState::ShaderReadWrite`] is named: there must be exactly one,
21938 /// it must sit after the dispatch, and it must sit at or before the first of
21939 /// the three passes that draw.
21940 #[test]
21941 fn the_skinning_dispatch_is_barriered_before_every_pass_that_draws() {
21942 let (recorder, device, queue) = open();
21943 let device = device.as_ref();
21944 let mut fixture = SkinnedFixture::build(device, queue);
21945 place_cube(&mut fixture.renderer, Mat4::IDENTITY);
21946 fixture
21947 .renderer
21948 .add_skinned_instance(&SkinnedInstanceDesc {
21949 mesh: &fixture.skinned,
21950 material: DEMO_UNTINTED,
21951 transform: Mat4::IDENTITY,
21952 })
21953 .expect("room for one object");
21954 fixture.begin(device);
21955
21956 let imported = swapchain_image_at(device, TEST_EXTENT);
21957 let mut pool = crate::TransientPool::new();
21958 let mut graph = crate::RenderGraph::new(queue);
21959 let target = graph.import_image("target", imported);
21960 // The same node `Skinning::add_pass` imports — one handle is one node —
21961 // so the barriers below can be named rather than guessed at.
21962 let vertices = graph.import_buffer(
21963 "vertex-pool",
21964 ImportedBuffer {
21965 buffer: fixture.renderer.vertex_buffer(),
21966 initial: ResourceState::ShaderRead,
21967 final_state: ResourceState::ShaderRead,
21968 },
21969 );
21970 fixture.renderer.add_skinned_passes(
21971 &mut graph,
21972 &pool,
21973 target,
21974 TEST_EXTENT,
21975 &fixture.skinning,
21976 );
21977 let compiled = graph.compile(&pool).expect("a legal frame");
21978 let labels: Vec<&str> = compiled
21979 .passes()
21980 .iter()
21981 .map(crate::graph::CompiledPass::label)
21982 .collect();
21983
21984 let dispatch = labels
21985 .iter()
21986 .position(|label| *label == "skinning")
21987 .expect("add_skinned_passes adds the dispatch itself");
21988 let drawing: Vec<usize> = ["shadow", "depth-prepass", "forward"]
21989 .into_iter()
21990 .map(|wanted| {
21991 labels
21992 .iter()
21993 .position(|label| *label == wanted)
21994 .unwrap_or_else(|| panic!("the frame draws through {wanted}: {labels:?}"))
21995 })
21996 .collect();
21997 for (label, at) in ["shadow", "depth-prepass", "forward"]
21998 .into_iter()
21999 .zip(&drawing)
22000 {
22001 assert!(
22002 dispatch < *at,
22003 "the dispatch is at {dispatch} and {label} at {at}: {labels:?}"
22004 );
22005 }
22006
22007 // Each drawing pass declares the read for itself, and this is asserted
22008 // per pass rather than left to the single barrier below. The graph
22009 // transitions the region once, before the first reader, and a later
22010 // pass that never declared the read finds it already in the state it
22011 // wanted — so dropping the declaration from `forward` alone changes no
22012 // barrier and moves no label, and every assertion in this test still
22013 // passes. What it does drop is that pass's *dependency* on the
22014 // dispatch, which is the only thing keeping the two in this order.
22015 for (label, at) in ["shadow", "depth-prepass", "forward"]
22016 .into_iter()
22017 .zip(&drawing)
22018 {
22019 assert!(
22020 compiled.passes()[*at].reads_buffer(vertices),
22021 "{label} draws skinned vertices and must declare that it reads them, or \
22022 nothing but declaration order keeps it after the dispatch"
22023 );
22024 }
22025
22026 let released: Vec<usize> = compiled
22027 .passes()
22028 .iter()
22029 .enumerate()
22030 .filter(|(_, pass)| {
22031 pass.barriers().buffers.iter().any(|barrier| {
22032 barrier.buffer == vertices
22033 && barrier.from == ResourceState::ShaderReadWrite
22034 && barrier.to == ResourceState::ShaderRead
22035 })
22036 })
22037 .map(|(at, _)| at)
22038 .collect();
22039 assert_eq!(
22040 released.len(),
22041 1,
22042 "exactly one transition out of the dispatch's write: {released:?} in {labels:?}"
22043 );
22044 let barrier = released[0];
22045 let first_draw = *drawing.iter().min().expect("three passes");
22046 assert!(
22047 dispatch < barrier && barrier <= first_draw,
22048 "the barrier is at {barrier}, the dispatch at {dispatch} and the first pass that \
22049 draws at {first_draw} — a draw that reads the region before the write is made \
22050 visible is the whole defect this seam exists to prevent"
22051 );
22052
22053 drop(compiled);
22054 fixture.destroy(device);
22055 pool.destroy(device);
22056 device.destroy_image_view(imported.view);
22057 device.destroy_image(imported.image);
22058 recorder.assert_valid();
22059 }
22060
22061 /// A frame with nothing to skin adds no dispatch and declares no read, and
22062 /// is the frame [`ForwardRenderer::add_passes`] would have built.
22063 #[test]
22064 fn a_frame_with_no_skinned_range_is_the_frame_add_passes_builds() {
22065 let _blurs = ssao_blur_switch();
22066 let (recorder, device, queue) = open();
22067 let device = device.as_ref();
22068 let mut fixture = SkinnedFixture::build(device, queue);
22069 place_cube(&mut fixture.renderer, Mat4::IDENTITY);
22070
22071 let imported = swapchain_image_at(device, TEST_EXTENT);
22072 let pool = crate::TransientPool::new();
22073 let mut skinned_labels = Vec::new();
22074 for _ in 0..1 {
22075 fixture
22076 .renderer
22077 .begin_skinned_frame(
22078 device,
22079 &mut fixture.skinning,
22080 &[],
22081 &Camera::default(),
22082 &DirectionalLight::default(),
22083 TEST_EXTENT,
22084 )
22085 .expect("an empty plan is a legal one");
22086 let mut graph = crate::RenderGraph::new(queue);
22087 let target = graph.import_image("target", imported);
22088 fixture.renderer.add_skinned_passes(
22089 &mut graph,
22090 &pool,
22091 target,
22092 TEST_EXTENT,
22093 &fixture.skinning,
22094 );
22095 skinned_labels = graph
22096 .compile(&pool)
22097 .expect("a legal frame")
22098 .passes()
22099 .iter()
22100 .map(|pass| pass.label().to_string())
22101 .collect();
22102 }
22103 let plain = passes_in_a_frame(
22104 device,
22105 queue,
22106 &mut fixture.renderer,
22107 imported,
22108 &pool,
22109 TEST_EXTENT,
22110 );
22111 assert_eq!(
22112 skinned_labels, plain,
22113 "a frame with nothing to skin must cost the vertex pool no barrier at all"
22114 );
22115
22116 fixture.destroy(device);
22117 let mut pool = pool;
22118 pool.destroy(device);
22119 device.destroy_image_view(imported.view);
22120 device.destroy_image(imported.image);
22121 recorder.assert_valid();
22122 }
22123
22124 /// One frame recorded end to end: `begin_frame`, the graph, and an encoder
22125 /// the commands land in.
22126 ///
22127 /// Returned rather than cleaned up here because the caller reads the
22128 /// recorder afterwards, and everything below must outlive that.
22129 struct Frame {
22130 imported: ImportedImage,
22131 pool: crate::TransientPool,
22132 commands: crcbl_hal::CommandBufferHandle,
22133 }
22134
22135 impl Frame {
22136 /// Releases the frame and the image it drew into, leaving the renderer
22137 /// alive for another one.
22138 fn release(self, device: &dyn Device) {
22139 device.destroy_command_buffer(self.commands);
22140 let mut pool = self.pool;
22141 pool.destroy(device);
22142 device.destroy_image_view(self.imported.view);
22143 device.destroy_image(self.imported.image);
22144 }
22145
22146 /// Releases the frame, the renderer and the image it drew into.
22147 fn finish(self, device: &dyn Device, renderer: ForwardRenderer) {
22148 self.release(device);
22149 renderer.destroy(device);
22150 }
22151 }
22152
22153 /// Everything one labelled pass recorded, and nothing any other pass did.
22154 ///
22155 /// **Every draw assertion below is scoped through this**, and the reason is
22156 /// topic 18: the frame now records the same indirect call the colour pass
22157 /// records once per shadow cascade as well, out of that cascade's own
22158 /// arguments. A test filtering the whole stream for `DrawIndexedIndirect`
22159 /// would see one per cascade as well as the colour pass's, and could not
22160 /// say which pass any of them belonged to — so "the forward pass records one
22161 /// call per bucket" would become a claim about a total, which a shadow pass
22162 /// recording the wrong thing could satisfy.
22163 /// The compute dispatches a default frame's **resolve** records, which
22164 /// every dispatch count in this module sees and none of them is about.
22165 ///
22166 /// `RenderEffects::DEFAULT_STACK` carries `CMAA2`, whose edge detect and
22167 /// shape classification are dispatches; its apply is a draw and does not
22168 /// count here. `each_effect_toggle_removes_exactly_the_passes_it_owns` is
22169 /// what pins the resolve's pass list itself, so a tier that grew a dispatch
22170 /// fails there first and arrives here as a second red rather than as a
22171 /// silent skew.
22172 const RESOLVE_DISPATCHES: usize = 2;
22173
22174 fn commands_in_pass(
22175 recorder: &crcbl_hal::null::Recorder,
22176 label: &str,
22177 ) -> Vec<crcbl_hal::null::Command> {
22178 use crcbl_hal::null::Command;
22179
22180 let mut inside = false;
22181 let mut out = Vec::new();
22182 for command in recorder.commands() {
22183 if let Some((_, recorded)) = command.opens_pass() {
22184 inside = recorded == Some(label);
22185 continue;
22186 }
22187 if matches!(command, Command::EndRenderPass | Command::EndComputePass) {
22188 inside = false;
22189 continue;
22190 }
22191 if inside {
22192 out.push(command);
22193 }
22194 }
22195 assert!(!out.is_empty(), "no pass labelled `{label}` recorded work");
22196 out
22197 }
22198
22199 /// The extent every helper frame in this module is drawn at.
22200 ///
22201 /// Named since the bloom chain, whose length is a function of it — see
22202 /// [`crate::bloom`] — so a test comparing a pass count against
22203 /// [`fullscreen_passes`] has to ask about the same size the frame was drawn
22204 /// at. Small on purpose: two chain levels is enough for every arm here, and
22205 /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`] is the one
22206 /// test that needs a frame large enough for six.
22207 ///
22208 /// [`the_pass_bound_is_the_widest_frame_the_renderer_records`]: fn@the_pass_bound_is_the_widest_frame_the_renderer_records
22209 const TEST_EXTENT: (u32, u32) = (64, 48);
22210
22211 /// The effects a caller has to ask for, because the default stack leaves
22212 /// them out — see [`RenderEffects::DEFAULT_STACK`].
22213 ///
22214 /// Named rather than written out at each of the three sites that force them
22215 /// on, because the point of those sites is "every effect there is" and the
22216 /// bug they exist to catch is a new effect joining the set and one site
22217 /// still measuring the old one while calling it the whole stack. They are
22218 /// held out of the default for different reasons — [`crate::effects`] gives
22219 /// each, and [`RenderEffects::CONTACT_SHADOWS`]'s is the only one that is a
22220 /// pending re-bless rather than a decision — and share only that a test
22221 /// wanting the widest frame must ask.
22222 ///
22223 /// **Named for what it is rather than for what most of it is**: the set held
22224 /// four post passes and a resolve when it was `POST_EFFECTS`, and the contact
22225 /// march is neither.
22226 const OUTSIDE_THE_DEFAULT: RenderEffects = RenderEffects::BLOOM
22227 .union(RenderEffects::ANTIALIASING)
22228 .union(RenderEffects::VOLUMETRIC_FOG)
22229 .union(RenderEffects::AUTO_EXPOSURE)
22230 .union(RenderEffects::CMAA2)
22231 .union(RenderEffects::CONTACT_SHADOWS);
22232
22233 /// Every effect this renderer draws is either in the default stack or in
22234 /// [`OUTSIDE_THE_DEFAULT`].
22235 ///
22236 /// The guard on the three sites above: they force [`OUTSIDE_THE_DEFAULT`] on and
22237 /// call the result "every effect", which is only true while nothing else is
22238 /// held out. An effect added outside the default stack and not added
22239 /// here makes this red before it makes a pass-list assertion red — which is
22240 /// the useful order, since a pass list going red says a label moved and this
22241 /// says what actually happened.
22242 #[test]
22243 fn forcing_the_post_effects_on_reaches_every_effect_there_is() {
22244 assert_eq!(
22245 RenderEffects::DEFAULT_STACK.union(OUTSIDE_THE_DEFAULT),
22246 RenderEffects::all(),
22247 "an effect outside the default stack that no test forces on is an effect \
22248 the every-effect frames below have never drawn"
22249 );
22250 }
22251
22252 /// The default sun, turned a little further round for each `lap`.
22253 ///
22254 /// Topic 45's static-caching rung means a second frame over
22255 /// a scene nothing moved in records **no shadow pass at all** — see
22256 /// [`ForwardRenderer::shadow_atlas_cached`]. That is the feature, and it is
22257 /// a difference that every A/B drawing two frames from one renderer would
22258 /// otherwise be measuring on top of the one it is about. Turning the sun is
22259 /// the smallest input the atlas depends on: the cascades are refitted, so
22260 /// the atlas is redrawn, and no pass, pipeline or draw of the frame moves
22261 /// with it.
22262 ///
22263 /// Lap zero is [`DirectionalLight::default`] exactly, so a test whose first
22264 /// frame is the ordinary one keeps the frame every other test draws.
22265 fn moving_sun(lap: u32) -> DirectionalLight {
22266 let sun = DirectionalLight::default();
22267 // A degree a lap, about the axis the default direction is not parallel
22268 // to. Small enough that every cascade still sees the scene, and large
22269 // enough that the snapped cascade origin actually moves.
22270 let turn = Mat4::from_rotation_y(
22271 f32::from(u16::try_from(lap).expect("a handful of laps")) * std::f32::consts::PI
22272 / 180.0,
22273 );
22274 DirectionalLight {
22275 direction: turn.transform_vector3(sun.direction).normalize(),
22276 ..sun
22277 }
22278 }
22279
22280 /// [`frame`] drawn under [`moving_sun`], so this frame's shadow atlas is
22281 /// not the one the lap before it left in the image.
22282 fn frame_moving_the_sun(
22283 device: &dyn Device,
22284 renderer: &mut ForwardRenderer,
22285 queue: QueueHandle,
22286 lap: u32,
22287 ) -> Frame {
22288 frame_lit_by(device, renderer, queue, &moving_sun(lap))
22289 }
22290
22291 fn frame(device: &dyn Device, renderer: &mut ForwardRenderer, queue: QueueHandle) -> Frame {
22292 frame_lit_by(device, renderer, queue, &DirectionalLight::default())
22293 }
22294
22295 fn frame_lit_by(
22296 device: &dyn Device,
22297 renderer: &mut ForwardRenderer,
22298 queue: QueueHandle,
22299 sun: &DirectionalLight,
22300 ) -> Frame {
22301 frame_seen_from(device, renderer, queue, &Camera::default(), sun)
22302 }
22303
22304 fn frame_seen_from(
22305 device: &dyn Device,
22306 renderer: &mut ForwardRenderer,
22307 queue: QueueHandle,
22308 camera: &Camera,
22309 sun: &DirectionalLight,
22310 ) -> Frame {
22311 renderer
22312 .begin_frame(device, camera, sun, TEST_EXTENT)
22313 .expect("write");
22314 let imported = swapchain_image(device);
22315 let mut graph = crate::RenderGraph::new(queue);
22316 let target = graph.import_image("target", imported);
22317 let mut pool = crate::TransientPool::new();
22318 renderer.add_passes(&mut graph, &pool, target, TEST_EXTENT);
22319 let compiled = graph.compile(&pool).expect("a legal frame");
22320 let mut encoder = device.create_command_encoder(&crcbl_hal::CommandEncoderDesc {
22321 label: Some("forward frame"),
22322 queue,
22323 });
22324 compiled
22325 .execute(device, &mut pool, encoder.as_mut(), None)
22326 .expect("the graph executed");
22327 let commands = encoder.finish().expect("recording succeeded");
22328 Frame {
22329 imported,
22330 pool,
22331 commands,
22332 }
22333 }
22334
22335 /// A stand-in for the acquired swapchain image the frame normally ends in,
22336 /// at [`TEST_EXTENT`].
22337 fn swapchain_image(device: &dyn Device) -> ImportedImage {
22338 swapchain_image_at(device, TEST_EXTENT)
22339 }
22340
22341 /// The same, at an extent of the caller's choosing.
22342 ///
22343 /// A frame's attachments must all be one size — the graph refuses a pass
22344 /// whose colour target and depth disagree — so a test drawing at anything
22345 /// but [`TEST_EXTENT`] has to import a target of that size too.
22346 pub(super) fn swapchain_image_at(device: &dyn Device, extent: (u32, u32)) -> ImportedImage {
22347 let format = Format::Rgba8UnormSrgb;
22348 let image = device
22349 .create_image(&crcbl_hal::ImageDesc {
22350 label: Some("fake swapchain image"),
22351 image_type: crcbl_hal::ImageType::D2,
22352 extent: crcbl_hal::Extent3d::d2(extent.0, extent.1),
22353 format,
22354 mip_levels: 1,
22355 samples: 1,
22356 usage: crcbl_hal::ImageUsage::COLOR_ATTACHMENT | crcbl_hal::ImageUsage::PRESENT,
22357 })
22358 .expect("an image");
22359 let view = device
22360 .create_image_view(&crcbl_hal::ImageViewDesc {
22361 label: Some("fake swapchain view"),
22362 image,
22363 view_type: crcbl_hal::ImageViewType::D2,
22364 format,
22365 range: crcbl_hal::ImageSubresourceRange::all(format),
22366 })
22367 .expect("a view");
22368 ForwardRenderer::present_target(image, view, format, extent)
22369 }
22370
22371 /// The spin is a rotation: no scale, no shear, so the cube neither grows
22372 /// nor mirrors as it turns, and every mesh golden blessed at a `spin` is a
22373 /// picture of one cube.
22374 ///
22375 /// That is also what keeps those goldens insensitive to `mesh.slang`'s
22376 /// `normal_basis`. A matrix with orthonormal rows and a positive
22377 /// determinant is its own cofactor matrix, to within a rounding step, so
22378 /// the vertex stage writes the normals it wrote when it multiplied by the
22379 /// bare 3×3 — see [`crcbl_shaders::mesh::GpuInstance::transform`], which no
22380 /// longer requires a caller to be rigid at all.
22381 #[test]
22382 fn the_spin_matrix_stays_rigid() {
22383 for seconds in [0.0f32, 0.5, 3.25, 100.0] {
22384 let model = ForwardRenderer::spin(seconds);
22385 let basis = glam::Mat3::from_mat4(model);
22386 let product = basis * basis.transpose();
22387 for (row, expected) in [
22388 (product.x_axis, Vec3::X),
22389 (product.y_axis, Vec3::Y),
22390 (product.z_axis, Vec3::Z),
22391 ] {
22392 assert!(
22393 (row - expected).length() < 1e-5,
22394 "the spin at {seconds}s is not orthonormal: {product:?}"
22395 );
22396 }
22397 assert!((model.determinant() - 1.0).abs() < 1e-5, "at {seconds}s");
22398 }
22399 // And it actually moves.
22400 assert_ne!(ForwardRenderer::spin(0.0), ForwardRenderer::spin(1.0));
22401 }
22402
22403 /// The swapchain import says what a swapchain image actually needs, which is
22404 /// the knowledge the hand-written barriers used to carry.
22405 #[test]
22406 fn the_present_target_starts_undefined_and_ends_presentable() {
22407 let mut pool: crcbl_core::Pool<u8> = crcbl_core::Pool::new();
22408 let image = pool.insert(0).cast();
22409 let view = pool.insert(0).cast();
22410 let imported =
22411 ForwardRenderer::present_target(image, view, Format::Bgra8UnormSrgb, (1280, 720));
22412 assert_eq!(imported.initial, ResourceState::Undefined);
22413 assert_eq!(imported.final_state, ResourceState::Present);
22414 assert_eq!(imported.extent, (1280, 720));
22415 }
22416
22417 /// The scene target is `Rgba16Float`, and the depth target is the
22418 /// reversed-Z format. Both are locked decisions and both are cheap to pin.
22419 #[test]
22420 fn the_scene_targets_are_hdr_and_reversed_z() {
22421 let color = crate::targets::scene_color((64, 48));
22422 assert_eq!(color.format, Format::Rgba16Float);
22423 assert!(color.format.is_hdr_capable());
22424 assert!(color.usage.contains(crcbl_hal::ImageUsage::SAMPLED));
22425
22426 let depth = crate::targets::scene_depth((64, 48));
22427 assert_eq!(depth.format, Format::D32Float);
22428 assert_eq!(
22429 DepthStencilState::default().depth_compare,
22430 crcbl_hal::CompareOp::Greater
22431 );
22432 }
22433
22434 /// A sun ten degrees or so above the horizon, and one further round: two
22435 /// atmospheres whose LUTs are nowhere near each other, so a comparison
22436 /// between them cannot pass by the two skies being alike.
22437 ///
22438 /// Spelled as directions rather than as angles for
22439 /// `crcbl_shaders::atmosphere`'s reason — nothing here takes a `sin` of its
22440 /// own — and normalised by `Atmosphere::parameters` on the way in.
22441 const MOVED_SUN: Atmosphere = Atmosphere {
22442 sun_direction: Vec3::new(1.0, 0.2, 0.0),
22443 ..Atmosphere::NOON
22444 };
22445
22446 /// [`MOVED_SUN`] again, further round and lower.
22447 const MOVED_AGAIN: Atmosphere = Atmosphere {
22448 sun_direction: Vec3::new(1.0, 0.05, 0.5),
22449 ..Atmosphere::NOON
22450 };
22451
22452 /// Frames the striped march takes to cross the LUT.
22453 const MARCH_FRAMES: usize = crcbl_shaders::atmosphere::SKY_VIEW_HEIGHT / SKY_VIEW_BUILD_ROWS;
22454
22455 /// The bytes the most recent sky-view LUT upload put on the device.
22456 ///
22457 /// `crate::sky_pass` writes the whole buffer at offset zero on every frame
22458 /// that has an atmosphere, into the slot that frame is using — so the last
22459 /// write to any of the ring's buffers is the LUT the frame just recorded
22460 /// would draw. That is the only place the presented LUT is observable: the
22461 /// renderer's own copy is what a test could assert about instead, and it
22462 /// would then be asserting about the thing rather than about what reached
22463 /// the device.
22464 fn presented_lut(recorder: &Recorder, luts: &[BufferHandle]) -> Vec<u8> {
22465 recorder
22466 .events()
22467 .into_iter()
22468 .rev()
22469 .find_map(|event| match event {
22470 crcbl_hal::null::Event::BufferWritten { buffer, .. } if luts.contains(&buffer) => {
22471 recorder.buffer_bytes(buffer)
22472 }
22473 _ => None,
22474 })
22475 .expect("a frame with an atmosphere uploads a sky-view LUT")
22476 }
22477
22478 /// A renderer with an atmosphere set and its first LUT marched, and the
22479 /// buffers that LUT reaches the device through.
22480 ///
22481 /// The three tests below all start here: the first march is synchronous, so
22482 /// one frame is what it takes to have a sky to be stale about.
22483 fn with_marched_atmosphere(
22484 device: &dyn Device,
22485 queue: QueueHandle,
22486 atmosphere: Atmosphere,
22487 ) -> (ForwardRenderer, Vec<BufferHandle>) {
22488 let mut renderer = ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb)
22489 .expect("the null backend builds a renderer");
22490 let luts = renderer.primary.sky_pass.luts().to_vec();
22491 renderer.set_atmosphere(Some(atmosphere));
22492 atmosphere_frame(&mut renderer, device);
22493 (renderer, luts)
22494 }
22495
22496 /// One frame of the atmosphere tests: nothing is drawn, and `begin_frame`
22497 /// is what writes the blocks and steps the march.
22498 fn atmosphere_frame(renderer: &mut ForwardRenderer, device: &dyn Device) {
22499 renderer
22500 .begin_frame(
22501 device,
22502 &Camera::default(),
22503 &DirectionalLight::default(),
22504 (64, 48),
22505 )
22506 .expect("the frame's blocks are written");
22507 }
22508
22509 /// A sun that moved is marched a stripe per frame, and every frame until it
22510 /// is finished still uploads the LUT of the sun before it.
22511 ///
22512 /// **The amortisation, from the device's side.** Before this, one
22513 /// `begin_frame` marched the whole LUT, so a scene that swept its sun paid
22514 /// tens of milliseconds of CPU in every frame. The claim now is three
22515 /// things at once, and only the middle one is about performance: the march
22516 /// advances by `SKY_VIEW_BUILD_ROWS` per frame, the bytes reaching the
22517 /// device meanwhile are the *previous* sun's rather than a half-marched
22518 /// sky, and the new sun's LUT arrives whole on the frame the march ends.
22519 ///
22520 /// **And the aerial-perspective LUT keeps the same pace**: it rides the
22521 /// same stripes, so it too uploads the previous sun's air on every frame
22522 /// of the march and the new sun's on the frame that ends it — the lag
22523 /// behind a moving sun is [`MARCH_FRAMES`] for both, and the two never
22524 /// reach the device a sun apart.
22525 #[test]
22526 fn a_moving_sun_is_marched_a_stripe_per_frame() {
22527 let (recorder, device, queue) = open();
22528 let (mut renderer, luts) =
22529 with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22530 let aerials = renderer.primary.sky_pass.aerials().to_vec();
22531
22532 let before_view = SkyView::build(&Atmosphere::NOON.parameters());
22533 let after_view = SkyView::build(&MOVED_SUN.parameters());
22534 let before = before_view.rows();
22535 let after = after_view.rows();
22536 let (air_before, air_after) = (before_view.aerial().rows(), after_view.aerial().rows());
22537 assert_ne!(
22538 before, after,
22539 "the two suns march to the same LUT, so nothing below distinguishes them"
22540 );
22541 assert_ne!(
22542 air_before, air_after,
22543 "the two suns march to the same air, so nothing below distinguishes them"
22544 );
22545 assert!(
22546 renderer.sky_view_build.is_none(),
22547 "the first march is synchronous, so no build is left in flight"
22548 );
22549 assert_eq!(
22550 presented_lut(&recorder, &luts),
22551 before,
22552 "the frame after `set_atmosphere` did not upload that sun's LUT"
22553 );
22554 assert_eq!(
22555 presented_lut(&recorder, &aerials),
22556 air_before,
22557 "the frame after `set_atmosphere` did not upload that sun's air"
22558 );
22559
22560 renderer.set_atmosphere(Some(MOVED_SUN));
22561 for step in 1..MARCH_FRAMES {
22562 atmosphere_frame(&mut renderer, device.as_ref());
22563 assert_eq!(
22564 renderer
22565 .sky_view_build
22566 .as_ref()
22567 .map(SkyViewBuild::rows_done),
22568 Some(step * SKY_VIEW_BUILD_ROWS),
22569 "frame {step} of the march is not a stripe further along than frame {} was",
22570 step - 1
22571 );
22572 assert_eq!(
22573 presented_lut(&recorder, &luts),
22574 before,
22575 "frame {step} of the march uploaded something other than the sky it is still \
22576 drawing"
22577 );
22578 assert_eq!(
22579 presented_lut(&recorder, &aerials),
22580 air_before,
22581 "frame {step} of the march uploaded air other than the sky it is still drawing's"
22582 );
22583 }
22584
22585 atmosphere_frame(&mut renderer, device.as_ref());
22586 assert!(
22587 renderer.sky_view_build.is_none(),
22588 "the march did not finish in the frames its own stripe says it takes"
22589 );
22590 assert_eq!(
22591 presented_lut(&recorder, &luts),
22592 after,
22593 "the frame that finished the march did not upload the new sun's LUT"
22594 );
22595 assert_eq!(
22596 presented_lut(&recorder, &aerials),
22597 air_after,
22598 "the frame that finished the march did not upload the new sun's air"
22599 );
22600 }
22601
22602 /// An atmosphere adds the composite for its air whether or not the fog
22603 /// effect is on, and the block tells the composite which halves to read.
22604 ///
22605 /// **The seam between the two volumes, on the renderer's side.** Three
22606 /// frames of one renderer: no atmosphere and the default stack, which has
22607 /// no fog effect in it — no composite at all, the frame drawn before the
22608 /// air existed; an atmosphere and the same stack — the composite and
22609 /// nothing of the column, and a block saying so; and an atmosphere with
22610 /// the fog effect forced on — all three passes, and a block saying both.
22611 /// The counters are held to the frame on the second: the composite is a
22612 /// full-screen triangle, and a frame that drew it and did not count it
22613 /// makes the debug panel's row disagree with the frame by one.
22614 #[test]
22615 fn an_atmosphere_composites_its_air_with_or_without_the_fog_effect() {
22616 let _blurs = ssao_blur_switch();
22617 let (recorder, device, queue) = open();
22618 let device = device.as_ref();
22619 let mut renderer =
22620 ForwardRenderer::new(device, queue, Format::Rgba8UnormSrgb).expect("built");
22621 let blocks: Vec<BufferHandle> = (0..FRAMES_IN_FLIGHT)
22622 .map(|frame| renderer.primary.volumetric.buffers(frame).params)
22623 .collect();
22624 let imported = swapchain_image(device);
22625 let mut pool = crate::TransientPool::new();
22626 let block = |recorder: &Recorder| {
22627 let bytes: [u8; crcbl_shaders::volumetric::PARAMS_SIZE] =
22628 presented_lut(recorder, &blocks)
22629 .try_into()
22630 .expect("the block is its own size");
22631 crcbl_shaders::volumetric::VolumetricParams::from_bytes(&bytes)
22632 };
22633 let column = ["volumetric-scatter", "volumetric-integrate"];
22634
22635 let bare = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22636 let before = renderer.counters();
22637 assert!(
22638 !bare.iter().any(|pass| pass.starts_with("volumetric")),
22639 "a frame with neither fog nor an atmosphere records {bare:?}"
22640 );
22641 let off = block(&recorder);
22642 assert_eq!(
22643 off.aerial_params,
22644 [0.0, 0.0, 0.0, crcbl_shaders::sky::ATMOSPHERE_OFF],
22645 "a frame with no atmosphere writes something into the aerial row"
22646 );
22647
22648 renderer.set_atmosphere(Some(Atmosphere::NOON));
22649 let air = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22650 assert!(
22651 air.iter().any(|pass| pass == "volumetric-composite")
22652 && !air.iter().any(|pass| column.contains(&pass.as_str())),
22653 "an atmosphere with the fog effect off records {air:?}, where it should composite its \
22654 air and run nothing of the column"
22655 );
22656 let after = renderer.counters();
22657 assert_eq!(
22658 after.draws - before.draws,
22659 (SkyPass::PASSES + u64::from(Volumetric::COMPOSITE_PASSES)) * FULLSCREEN_DRAWS,
22660 "the atmosphere's two full-screen passes — the sky and the air — are not both counted"
22661 );
22662 let aerial_only = block(&recorder);
22663 let sun = Atmosphere::NOON.parameters().sun_direction;
22664 assert_eq!(
22665 aerial_only.aerial_params,
22666 [sun[0], sun[1], sun[2], crcbl_shaders::sky::ATMOSPHERE_ON],
22667 "the aerial row does not carry the atmosphere's sun and its switch"
22668 );
22669 assert_eq!(
22670 aerial_only.fog_params[3],
22671 crcbl_shaders::volumetric::LOCAL_COLUMN_OFF,
22672 "the block tells the composite to read a column no pass filled"
22673 );
22674
22675 renderer.set_effect_request(EffectRequest {
22676 programmatic: EffectOverride::none().force(RenderEffects::VOLUMETRIC_FOG, Some(true)),
22677 ..EffectRequest::default()
22678 });
22679 let both = passes_in_a_frame(device, queue, &mut renderer, imported, &pool, TEST_EXTENT);
22680 assert!(
22681 column
22682 .iter()
22683 .chain(&["volumetric-composite"])
22684 .all(|name| both.iter().any(|pass| pass == name)),
22685 "an atmosphere with the fog effect on records {both:?}"
22686 );
22687 assert_eq!(
22688 block(&recorder).fog_params[3],
22689 crcbl_shaders::volumetric::LOCAL_COLUMN_ON,
22690 "the block tells the composite to skip a column the frame filled"
22691 );
22692
22693 renderer.destroy(device);
22694 pool.destroy(device);
22695 device.destroy_image_view(imported.view);
22696 device.destroy_image(imported.image);
22697 recorder.assert_valid();
22698 }
22699
22700 /// A sun that moves while a march is in flight restarts it from row zero.
22701 ///
22702 /// **The decision `refresh_sky_view` writes down**, and the reason a sun
22703 /// that moves every frame shows a frozen sky rather than a stuttering one:
22704 /// finishing a march for a sun that has already moved would swap in a LUT
22705 /// that is wrong on arrival. What is observable is the progress counter —
22706 /// a build that kept its rows would be two stripes along here rather than
22707 /// one — and the sun the build in flight names.
22708 #[test]
22709 fn a_sun_that_moves_mid_march_restarts_it() {
22710 let (recorder, device, queue) = open();
22711 let (mut renderer, luts) =
22712 with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22713 let before = SkyView::build(&Atmosphere::NOON.parameters()).rows();
22714
22715 renderer.set_atmosphere(Some(MOVED_SUN));
22716 atmosphere_frame(&mut renderer, device.as_ref());
22717 atmosphere_frame(&mut renderer, device.as_ref());
22718 assert_eq!(
22719 renderer
22720 .sky_view_build
22721 .as_ref()
22722 .map(SkyViewBuild::rows_done),
22723 Some(2 * SKY_VIEW_BUILD_ROWS),
22724 "two frames of marching did not leave two stripes marched"
22725 );
22726
22727 renderer.set_atmosphere(Some(MOVED_AGAIN));
22728 atmosphere_frame(&mut renderer, device.as_ref());
22729 assert_eq!(
22730 renderer
22731 .sky_view_build
22732 .as_ref()
22733 .map(SkyViewBuild::rows_done),
22734 Some(SKY_VIEW_BUILD_ROWS),
22735 "the march kept the rows it had marched for a sun that has since moved"
22736 );
22737 assert_eq!(
22738 renderer
22739 .sky_view_build
22740 .as_ref()
22741 .map(SkyViewBuild::atmosphere),
22742 Some(MOVED_AGAIN.parameters()),
22743 "the build in flight is marching a sun the caller has moved away from"
22744 );
22745 assert_eq!(
22746 presented_lut(&recorder, &luts),
22747 before,
22748 "a restart uploaded something other than the last LUT that finished"
22749 );
22750 }
22751
22752 /// A frame whose sun has not moved marches nothing and re-takes neither
22753 /// projection.
22754 ///
22755 /// **What `PresentedSky` is for.** `gradient_fit` and `irradiance` used to
22756 /// be taken from the LUT in every `begin_frame`, which is host work a still
22757 /// sun has no reason to pay. Both are now taken once, where the march
22758 /// finishes — so a sentinel written over the cached gradient survives a
22759 /// frame if and only if that frame took neither the march nor the
22760 /// projection again, and the same sentinel's bytes turn up in what the
22761 /// frame wrote, which is what says the cache is the thing being read.
22762 #[test]
22763 fn a_still_sun_marches_nothing_and_reprojects_nothing() {
22764 let (recorder, device, queue) = open();
22765 let (mut renderer, _luts) =
22766 with_marched_atmosphere(device.as_ref(), queue, Atmosphere::NOON);
22767
22768 let sentinel = crcbl_shaders::sky::SkyGradient {
22769 zenith: [0.125, 0.25, 0.375],
22770 horizon: [0.5, 0.625, 0.75],
22771 ground: [0.875, 1.125, 1.375],
22772 };
22773 let presented = renderer
22774 .sky_view
22775 .as_mut()
22776 .expect("the first frame marched a LUT");
22777 assert_ne!(
22778 presented.gradient, sentinel,
22779 "the sentinel is what the real projection already returns, so it proves nothing"
22780 );
22781 presented.gradient = sentinel;
22782
22783 let before = recorder.events().len();
22784 atmosphere_frame(&mut renderer, device.as_ref());
22785 assert_eq!(
22786 renderer
22787 .sky_view
22788 .as_ref()
22789 .map(|presented| presented.gradient),
22790 Some(sentinel),
22791 "a frame under a sun that has not moved re-took the projections"
22792 );
22793 assert!(
22794 renderer.sky_view_build.is_none(),
22795 "a frame under a sun that has not moved started a march"
22796 );
22797
22798 let wanted: Vec<u8> = sentinel
22799 .rows()
22800 .iter()
22801 .flatten()
22802 .flat_map(|value| value.to_le_bytes())
22803 .collect();
22804 let used = recorder
22805 .events()
22806 .into_iter()
22807 .skip(before)
22808 .filter_map(|event| match event {
22809 crcbl_hal::null::Event::BufferWritten { buffer, .. } => {
22810 recorder.buffer_bytes(buffer)
22811 }
22812 _ => None,
22813 })
22814 .any(|bytes| {
22815 bytes
22816 .windows(wanted.len())
22817 .any(|window| window == wanted.as_slice())
22818 });
22819 assert!(
22820 used,
22821 "the cached gradient reached no block this frame wrote, so the frame is not reading \
22822 the cache at all"
22823 );
22824 }
22825
22826 /// **The frame block's ambient rows carry the marched LUT's own L1
22827 /// projection**, and not the three-band fit's.
22828 ///
22829 /// `begin_frame` writes [`PresentedSky::irradiance`] into
22830 /// [`FrameUniforms::sky_sh_r`] and the two rows beside it, and until this
22831 /// test nothing read them back. The only reader of those rows is arithmetic
22832 /// in `mesh.slang`'s fragment stage, and no frame in the tree draws a
22833 /// surface under an atmosphere — `crcbl`'s
22834 /// `an_atmosphere_frame_is_the_host_lut` puts no geometry in its scene at
22835 /// all — so `PresentedSky::new` handed `view.gradient_fit().irradiance()`
22836 /// instead, the three-band fit's projection rather than the LUT's, was a
22837 /// swap `docs/backlog.md` recorded passing every suite in the tree on
22838 /// 2026-09-06.
22839 ///
22840 /// **Both halves are needed and the second is the sabotage's.** The rows
22841 /// equalling the LUT's projection is the wiring; the rows *differing* from
22842 /// the fit's is what makes the equality a claim about which projection
22843 /// arrived rather than about two numbers that happen to agree. The
22844 /// `assert_ne` above them is the anti-vacuity: a sun for which the two
22845 /// projections coincide would make this test pass under the swap.
22846 ///
22847 /// [`FrameUniforms::sky_sh_r`]: crcbl_shaders::mesh::FrameUniforms::sky_sh_r
22848 #[test]
22849 fn an_atmosphere_writes_the_luts_own_ambient_term() {
22850 /// The three rows, as the little-endian bytes `FrameUniforms::to_bytes`
22851 /// puts in the block.
22852 fn rows(probe: &crcbl_shaders::probe::GpuProbe) -> Vec<u8> {
22853 [probe.sh_r, probe.sh_g, probe.sh_b]
22854 .iter()
22855 .flatten()
22856 .flat_map(|value| value.to_le_bytes())
22857 .collect()
22858 }
22859
22860 let (recorder, device, queue) = open();
22861 let (renderer, _luts) = with_marched_atmosphere(device.as_ref(), queue, MOVED_SUN);
22862
22863 let view = SkyView::build(&MOVED_SUN.parameters());
22864 let marched = rows(&view.irradiance());
22865 let fitted = rows(&view.gradient_fit().irradiance());
22866 assert_ne!(
22867 marched, fitted,
22868 "this sun's LUT and its three-band fit project to the same rows, so a block \
22869 carrying either would satisfy the check below and the swap it exists for would \
22870 pass"
22871 );
22872
22873 let block = recorder
22874 .buffer_bytes(renderer.primary.uniforms[renderer.frame])
22875 .expect("a frame with an atmosphere writes its uniform block");
22876 let at = mesh::SKY_SH_R_OFFSET;
22877 assert_eq!(
22878 &block[at..at + marched.len()],
22879 marched.as_slice(),
22880 "the frame block's sky rows are not `SkyView::irradiance` of the LUT this frame \
22881 marched, so the ambient term the fragment stage evaluates comes from somewhere \
22882 else"
22883 );
22884 assert_ne!(
22885 &block[at..at + fitted.len()],
22886 fitted.as_slice(),
22887 "the frame block's sky rows are the gradient fit's projection — the LUT was \
22888 marched and then thrown away for the three-band approximation of it"
22889 );
22890
22891 renderer.destroy(device.as_ref());
22892 }
22893}