Skip to main content

crcbl_render/
scene.rs

1//! What is resident in a frame, as host-side data an application writes and
2//! [`ForwardRenderer::with_scene`] consumes.
3//!
4//! ```text
5//! SceneDesc ──▶ ForwardRenderer::with_scene ──▶ pools, table, page, buckets
6//!  meshes                                        (fixed for the renderer's life)
7//!  materials
8//!  page
9//!  capacities
10//! ```
11//!
12//! # Why a description rather than calls
13//!
14//! The resident set is fixed at build and the *instances* of it are not, and
15//! that split is where the seam already was: [`MeshPool`](crate::mesh_pool),
16//! [`ClusterPool`](crate::cluster_pool), the bucket table and the page are
17//! created once and never grow, while
18//! [`InstancePool::insert`](crate::instance_pool::InstancePool::insert) is a
19//! per-frame path. A runtime `add_mesh` would mean recreating the camera's
20//! [`DrawGen`](crate::draw_gen::DrawGen) and every shadow one, plus every bind
21//! group naming their buffers, part way through a renderer's life — which is
22//! the streaming path `crate::mesh_pool`'s own docs assign to P9.
23//!
24//! So everything here is data, and none of it names a device: a description can
25//! be built, compared and unit-tested with no GPU in the room, and the renderer
26//! is what turns it into memory.
27//!
28//! # Order is load-bearing, in four places
29//!
30//! Nothing below is a list whose order is cosmetic, and three of the four fail
31//! silently — a plausible frame with the wrong pixels in it, which no assertion
32//! on the CPU can see.
33//!
34//! * **Material row 0 is what [`mesh::GpuInstance::default`] names**, so an
35//!   instance written without a material id shades through
36//!   [`SceneDesc::materials`]'s first entry. Put a tint there and every object
37//!   nobody assigned a material to is tinted.
38//! * **Mesh table ids come from upload order**, and `cull.slang` reads a
39//!   bounding box out of the entry the *instance* names — level 0's, for a DAG.
40//!   The renderer uploads [`SceneDesc::meshes`] in order, so a description's
41//!   own order is what the ids are.
42//! * **A page layer's index is its position in [`PageDesc`]**, counted per
43//!   [`PageKind`], and a material row's texture column is that number. A
44//!   producer that pushes its layers in one order and names them in another
45//!   shades every surface with somebody else's texture — a plausible frame,
46//!   built from the right images.
47//! * **One bucket per description mesh, in order**, because `draw_gen.slang`'s
48//!   scatter takes the first bucket whose mesh id matches. Two buckets naming
49//!   one mesh would leave the second drawing nothing forever, which the bucket
50//!   table being derived from this list is what prevents.
51//!
52//! # Instances are the other half, and they are calls rather than data
53//!
54//! What is resident is fixed; *where the objects are* is not. So an
55//! [`InstanceDesc`] is handed to [`ForwardRenderer::add_instance`] at any point
56//! in a renderer's life, and it names its mesh and its material by **index into
57//! the description above** rather than by a table id only the renderer knows.
58//!
59//! # The engine's own scene is a caller of this
60//!
61//! [`demo`] is the cube, the pyramid, the open box and the dunes DAG — what the
62//! renderer used to upload to itself — with the three material rows and the two
63//! page layers that make §3.2's columns observable.
64//! [`ForwardRenderer::new`] is `with_scene(&demo())` and nothing else, so the
65//! samples and the golden suite exercise the same path an application takes
66//! rather than a special case beside it.
67//!
68//! [`ForwardRenderer::add_instance`]: crate::forward::ForwardRenderer::add_instance
69//! [`ForwardRenderer::new`]: crate::forward::ForwardRenderer::new
70//! [`ForwardRenderer::with_scene`]: crate::forward::ForwardRenderer::with_scene
71
72mod bounds;
73
74pub use bounds::SceneBoundsError;
75
76use std::borrow::Cow;
77
78use crcbl_hal::HalError;
79use crcbl_shaders::cluster_dag::ClusterDag;
80use crcbl_shaders::mesh;
81use crcbl_shaders::meshlet::MeshClusters;
82use crcbl_shaders::probe;
83use crcbl_shaders::vertex::UvRange;
84use glam::Mat4;
85
86/// The second material's base colour, and the whole of what makes it visible.
87///
88/// A factor per channel with no two alike, so multiplying by it moves every
89/// colour it touches: a tint that left a channel at `1.0` would leave the
90/// pyramid's white base looking like a lighting difference, and one that left
91/// them equal would be a brightness change a shading bug could also produce.
92/// Carried by [`DEMO_TINTED`], which is the row a second instance of the pyramid
93/// mesh is placed through — the pair this exists for.
94pub const PYRAMID_TINT: [f32; 4] = [0.15, 0.45, 1.0, 1.0];
95
96/// The second material's roughness, and the whole of what makes the **shading**
97/// half of the row visible.
98///
99/// Well under [`mesh::GpuMaterial::UNTINTED`]'s, so the same lobe under the same
100/// sun draws a tight bright highlight here where the neutral row draws a broad
101/// faint one. Not lower still: a roughness near zero puts the whole lobe inside
102/// a handful of pixels, and a highlight a rasteriser can miss is not something
103/// a frame comparison can measure.
104///
105/// **This is the only place in the engine where two materials differ in a
106/// shading factor**, which is what makes
107/// `crcbl`'s `the_smooth_pyramid_holds_a_tighter_highlight_than_the_rough_one`
108/// possible at all — see [`demo`] for why the shading factor rides on that row
109/// rather than on a fourth.
110pub const PYRAMID_ROUGHNESS: f32 = 0.25;
111
112/// The base-colour page's extent, in texels — square, and **two**.
113///
114/// Topic 03 §3.2's
115/// [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) page is one image with a
116/// layer per material texture, and two texels a side is the smallest extent in
117/// which a layer can be something other than a flat colour. Small on purpose,
118/// and not only because this is demo content:
119///
120/// * A flat layer would make the golden suite pass with **no UV at all**. Four
121///   texels is what makes the texture coordinate observable, because a mesh
122///   whose UVs never varied would shade each face in one texel's colour.
123/// * Every texel boundary is a ramp the sampler blends across — it magnifies
124///   bilinear — and a ramp is where two rasterisers' UV interpolation shows up
125///   as a value difference. Four texels put **one** boundary across a face in
126///   each axis, at `0.5`, which is as far from a vertex as an edge can be. A
127///   denser checker would put a row of disagreeable pixels through every face
128///   for no more evidence.
129pub const PAGE_EXTENT: u32 = 2;
130
131/// Bytes in one layer of [`demo`]'s page: [`PAGE_EXTENT`]² RGBA texels.
132const PAGE_LAYER_BYTES: usize = (PAGE_EXTENT * PAGE_EXTENT) as usize * 4;
133
134/// The layer [`DEMO_TEXTURED`] shades with — the only one [`demo`]'s
135/// base-colour page carries.
136pub const CHECKER_LAYER: u32 = 0;
137
138/// [`CHECKER_LAYER`]: four **distinct** greys, one per texel.
139///
140/// Distinct rather than a two-value checker, for the reason `crcbl-vk`'s sprite
141/// suite records about its sheets: a two-value checker is symmetric under both a
142/// flipped U and a flipped V, so either mistake would produce the same picture.
143/// No two of these are equal, so any flip is a different frame.
144///
145/// Grey rather than coloured because the colour axis is already spoken for:
146/// [`PYRAMID_TINT`] is what proves the *factor* column, and a texture that also
147/// changed hue would make the two columns' evidence look alike.
148pub const CHECKER_TEXELS: [u8; PAGE_LAYER_BYTES] = [
149    0xFF, 0xFF, 0xFF, 0xFF, // (0, 0)
150    0xB0, 0xB0, 0xB0, 0xFF, // (1, 0)
151    0x70, 0x70, 0x70, 0xFF, // (0, 1)
152    0x30, 0x30, 0x30, 0xFF, // (1, 1)
153];
154
155/// How much of each pool a scene reserves, in objects.
156///
157/// Every one of these is device-local memory taken at start-up and **never
158/// grown**, which is the decision `crate::mesh_pool` argues in full: every bind
159/// group in the renderer names those buffers, so growing one would mean
160/// rewriting every descriptor mid-life. A caller sizes them for the scene it
161/// means to build; a scene that outgrows one is refused rather than resized.
162///
163/// [`Default`] is what the engine's own [`demo`] scene has always used.
164#[derive(Clone, Copy, Debug, PartialEq, Eq)]
165pub struct Capacities {
166    /// Vertices the geometry pool holds, across every resident mesh.
167    pub vertices: u32,
168    /// Indices the geometry pool holds. Four per vertex is the usual ratio for
169    /// indexed triangle soup, rounded up.
170    pub indices: u32,
171    /// Entries the mesh table holds.
172    ///
173    /// Distinct meshes, not instances of them: an object count sizes
174    /// [`instances`](Self::instances), and a mesh id names one entry here
175    /// however many instances carry it. **A DAG occupies one entry per level**,
176    /// because each level is a vertex range of its own.
177    pub meshes: u32,
178    /// Instances the instance pool holds, per frame in flight.
179    ///
180    /// Sized against topic 03's exit criterion — "sandbox scene: 10k+ instanced
181    /// meshes" — rather than against what is resident today.
182    ///
183    /// **Raising this is not linear in memory.** Topic 25's
184    /// hysteresis state is one word per instance per resident group per
185    /// [`DrawGen`](crate::draw_gen::DrawGen), and there is a generator for the
186    /// camera, one per shadow cascade and one per shadow light slot.
187    ///
188    /// The one capacity here that a description cannot be measured against,
189    /// because objects are placed while the renderer runs rather than at build:
190    /// filling it is
191    /// [`InstancePoolError::PoolFull`](crate::instance_pool::InstancePoolError::PoolFull)
192    /// from [`ForwardRenderer::add_instance`], which is where a caller finds out
193    /// it is this number that wants raising.
194    ///
195    /// [`ForwardRenderer::add_instance`]: crate::forward::ForwardRenderer::add_instance
196    pub instances: u32,
197    /// Rows the material table holds.
198    ///
199    /// Distinct materials, not instances of them — a material id names one row
200    /// however many instances carry it, which is the property that makes the
201    /// table worth having.
202    pub materials: u32,
203    /// Rows the light list holds — the sun and every
204    /// [`Light`](crate::light::Light) a caller sets.
205    ///
206    /// Overflowing this is refused rather than counted, because a light missing
207    /// from the list is missing from every froxel and no counter in the frame
208    /// would say so.
209    pub lights: u32,
210    /// Rows the irradiance probe table holds.
211    ///
212    /// One per probe of [`SceneDesc::probes`], which is a
213    /// description-measurable number like [`materials`](Self::materials) and is
214    /// refused at build rather than at runtime.
215    ///
216    /// **Zero is a scene with no probes**, which is what the engine's own
217    /// [`demo`] has: the table still holds one cleared row, because a buffer of
218    /// no bytes is not a buffer, and reading that row adds exactly nothing. The
219    /// default is deliberately not larger — a probe grid is authored, and
220    /// reserving device memory for one nobody wrote is memory taken from every
221    /// existing caller for a feature they have not used.
222    pub probes: u32,
223}
224
225impl Default for Capacities {
226    fn default() -> Self {
227        Self {
228            vertices: 64 * 1024,
229            indices: 256 * 1024,
230            meshes: 1024,
231            instances: 16 * 1024,
232            materials: 1024,
233            lights: 1024,
234            probes: 0,
235        }
236    }
237}
238
239/// Which of the renderer's material pages a layer belongs to.
240///
241/// The renderer creates one `D2Array` image per kind, and a material row indexes
242/// them separately: [`base_color_texture`] names a layer of
243/// [`BaseColor`](Self::BaseColor)'s image and [`normal_texture`] names one of
244/// [`Normal`](Self::Normal)'s. They are different formats, filtered by different
245/// filters, and sized by their own extents — so a layer number means nothing
246/// without the kind beside it, and this enum is what makes a caller write the
247/// kind down.
248///
249/// Topic 43 §2's rung 3 landed the other two kinds on
250/// 2026-09-06; the four here are the four page columns `mesh::GpuMaterial`
251/// carries and there is no fifth waiting.
252///
253/// [`base_color_texture`]: mesh::GpuMaterial::base_color_texture
254/// [`normal_texture`]: mesh::GpuMaterial::normal_texture
255#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
256pub enum PageKind {
257    /// The base-colour page: sRGB-encoded colour, which is what glTF defines a
258    /// `baseColorTexture` to be, created `Rgba8UnormSrgb` so the sampler decodes
259    /// it and mipped through the alpha-weighted filter that averages in linear
260    /// light.
261    BaseColor,
262    /// The normal page: tangent-space normals stored **linear**, as
263    /// `n * 0.5 + 0.5` per channel, created `Rgba8Unorm` so nothing puts them
264    /// through a transfer curve and mipped through the filter that averages the
265    /// decoded vectors and renormalises.
266    Normal,
267    /// The packed metallic-roughness-occlusion page, glTF 2.0's own channel
268    /// assignment: occlusion in `r`, roughness in `g`, metallic in `b`, and `a`
269    /// unread.
270    ///
271    /// **Linear**, created `Rgba8Unorm` for the normal page's reason exactly —
272    /// a roughness, a metalness and an occlusion are *numbers*, and an sRGB
273    /// decode over them is wrong by a gamma. glTF splits the same three across
274    /// `pbrMetallicRoughness.metallicRoughnessTexture` (`g` and `b`) and
275    /// `occlusionTexture` (`r`); one image carrying all three is what the two
276    /// share when an author packs them, which is what makes one page enough.
277    MetallicRoughnessOcclusion,
278    /// The emissive page: the radiance a surface emits, multiplied by
279    /// [`emissive`](mesh::GpuMaterial::emissive).
280    ///
281    /// **sRGB-encoded**, created `Rgba8UnormSrgb` — the one of the three new
282    /// halves that is a *colour* rather than a number, and glTF 2.0 §3.9.4
283    /// defines `emissiveTexture` as sRGB exactly as it defines the base-colour
284    /// one. The factor beside it is linear, and the two meeting in one product
285    /// is the trap the format removes.
286    Emissive,
287}
288
289impl PageKind {
290    /// Every kind, in the order a [`PageDesc`] stores them.
291    pub const ALL: [Self; 4] = [
292        Self::BaseColor,
293        Self::Normal,
294        Self::MetallicRoughnessOcclusion,
295        Self::Emissive,
296    ];
297
298    /// This kind's slot in [`PageDesc`]'s table.
299    #[must_use]
300    pub const fn index(self) -> usize {
301        match self {
302            Self::BaseColor => 0,
303            Self::Normal => 1,
304            Self::MetallicRoughnessOcclusion => 2,
305            Self::Emissive => 3,
306        }
307    }
308
309    /// How a refusal names this page — an adjective, read before the word
310    /// "page", so `check_scene`'s sentence reads the same for every kind.
311    #[must_use]
312    pub const fn label(self) -> &'static str {
313        match self {
314            Self::BaseColor => "base-colour",
315            Self::Normal => "normal",
316            Self::MetallicRoughnessOcclusion => "metallic-roughness-occlusion",
317            Self::Emissive => "emissive",
318        }
319    }
320}
321
322/// One page of [`PageDesc`]'s table: a square extent and the layers written at
323/// it.
324///
325/// Both zero is "no scene here names this page", which is what
326/// [`PageDesc::empty`] leaves every kind at and what makes the renderer create a
327/// placeholder texel rather than an image. `layers` is never non-empty at an
328/// extent of zero — [`PageDesc::push_layer`] refuses that — and the reverse,
329/// an extent set and nothing pushed, is a page nothing samples and is treated as
330/// empty at upload.
331#[derive(Clone, Debug, Default, PartialEq, Eq)]
332struct Page<'a> {
333    extent: u32,
334    layers: Vec<Cow<'a, [u8]>>,
335}
336
337/// §3.2's texture side: one `D2Array` image per [`PageKind`], whose layers a
338/// material row selects with that kind's own texture column.
339///
340/// One image with a layer per texture rather than an array of descriptors —
341/// [`ArrayPages`](crcbl_hal::BindingModel::ArrayPages) rather than
342/// [`Bindless`](crcbl_hal::BindingModel::Bindless) — because a layer index
343/// needs nothing of a device where a descriptor array needs
344/// [`DESCRIPTOR_INDEXING`](crcbl_hal::Features::DESCRIPTOR_INDEXING), which
345/// `crcbl-mtl` withdraws.
346///
347/// # A table over the kinds, each with an extent of its own
348///
349/// [`set_extent`](Self::set_extent) sizes one kind and
350/// [`push_layer`](Self::push_layer) appends into it, so a 512² normal page
351/// beside a 2048² base-colour page is two calls rather than a resample of one
352/// onto the other's size. A kind nothing names is left alone: it holds no
353/// layers, [`extent`](Self::extent) reports zero for it, and the renderer
354/// creates a single placeholder texel in its place rather than an `extent²`
355/// image nobody samples.
356///
357/// # Layer 0 is an ordinary layer, and where its old invariant went
358///
359/// Until topic 43 §2's row (d) this type **burned**
360/// layer 0 on both pages — an all-white texel on the base-colour page, the
361/// neutral normal on the other — because
362/// [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) was zero and a material naming no
363/// texture sampled it. Two arms of `check` existed to hold that:
364/// layer 0 is white, layer 0 is neutral.
365///
366/// `NO_PAGE` is `0xFFFF` now and `mesh.slang` tests it, so the neutral value is
367/// a literal in the fragment stage rather than a texel in an image, and both
368/// arms are gone with the layers they guarded. **That is a trade, and it is
369/// worth writing down which way it runs.** What it bought: a page nothing names
370/// costs one texel rather than `extent² × 4` bytes and a third again for its
371/// chain, on every scene in the tree; a producer numbers its layers from zero
372/// like any other array; and the two pages stopped having to be one size. What
373/// it sold: the invariant is no longer checkable on the host at all. A fragment
374/// that read a page for a row carrying `NO_PAGE` used to find white and draw the
375/// right frame anyway, and now it finds whatever the placeholder holds — which
376/// nothing but a *picture* can report. So `crate::forward`'s
377/// `PAGE_PLACEHOLDER_TEXEL` is magenta rather than white or black: the mistake
378/// this type used to absorb silently is one a golden now shows loudly.
379#[derive(Clone, Debug, Default, PartialEq, Eq)]
380pub struct PageDesc<'a> {
381    pages: [Page<'a>; PageKind::ALL.len()],
382}
383
384impl<'a> PageDesc<'a> {
385    /// The texel an all-white base-colour layer is filled with.
386    ///
387    /// The page is `Rgba8UnormSrgb` and `0xFF` is the one value that encoding
388    /// leaves alone, so the sampler returns exactly `1.0` — the same product a
389    /// material was shaded by before there was a page at all.
390    ///
391    /// **Nothing needs such a layer any more.** A material naming no texture
392    /// carries [`mesh::GpuMaterial::NO_PAGE`], which is out of band, and the
393    /// fragment stage multiplies by the literal `1.0` instead of by this. The
394    /// constant stays for the callers that want a white layer *deliberately* —
395    /// `crcbl/tests/mesh_e2e/base_color_page.rs` is the one that measured, on a
396    /// device, that the two routes shade a surface to the same bits, and
397    /// `crcbl/src/screenshot.rs`'s alpha mask keeps this RGB under a cut alpha.
398    pub const WHITE: u8 = 0xFF;
399
400    /// The neutral tangent-space normal texel: `(0.5, 0.5, 1.0)` in RGBA8,
401    /// which is topic 43 §2's neutral normal.
402    ///
403    /// # It is not exactly flat, and the shader is what makes "no map" exact
404    ///
405    /// An eight-bit unorm channel has no `0.5`: `0x80` decodes to `128 / 255`,
406    /// and `t * 2 - 1` turns that into `1 / 255` rather than zero — a tangent
407    /// space normal about a fifth of a degree off vertical. That is small and it
408    /// is not nothing, and this engine compares its goldens across four
409    /// backends with no tolerance, so a material sampling this texel and
410    /// perturbing by it would move every frame in the tree that draws a lit
411    /// surface. `mesh.slang`'s `shading_normal_of` therefore tests the layer
412    /// index against [`mesh::GpuMaterial::NO_PAGE`] and returns the surface
413    /// normal untouched;
414    /// `crcbl_shaders::mesh::a_neutral_normal_texel_is_not_exactly_flat`
415    /// measures the error this constant would otherwise introduce.
416    ///
417    /// So what a layer of this is *for* is the material that names it
418    /// explicitly and the read that runs off the end of an authored layer's
419    /// edge — a neutral texel is what those must find, rather than the
420    /// `(0, 0, 0)` an unwritten image holds, which decodes to a normal pointing
421    /// straight backwards.
422    pub const NEUTRAL_NORMAL: [u8; 4] = [0x80, 0x80, 0xFF, 0xFF];
423
424    /// A description that names no page at all: every kind empty, and nothing
425    /// but one placeholder texel apiece allocated on the device.
426    ///
427    /// A caller adds a page by sizing it with
428    /// [`set_extent`](Self::set_extent) and pushing layers into it with
429    /// [`push_layer`](Self::push_layer). A scene whose every material row
430    /// carries [`NO_PAGE`](mesh::GpuMaterial::NO_PAGE) — `apps/alcove` and
431    /// `apps/sundial` are both such scenes — stops here.
432    #[must_use]
433    pub fn empty() -> Self {
434        Self::default()
435    }
436
437    /// Sizes `kind`'s page: texels a side, square.
438    ///
439    /// Every layer of that kind is then exactly `extent² × 4` bytes, which
440    /// `check` is what enforces. The kinds are separate device
441    /// images and each carries its own number, so sizing one says nothing about
442    /// the other.
443    ///
444    /// # Panics
445    ///
446    /// If `extent` is zero, which is an image no device will create, or if
447    /// `kind` already holds a layer — those layers were authored against the
448    /// extent that was in force when they were pushed, and moving it under them
449    /// would refuse every one of them at `check` with a byte
450    /// count nobody wrote.
451    pub fn set_extent(&mut self, kind: PageKind, extent: u32) {
452        assert!(extent > 0, "a page must have at least one texel a side");
453        let page = &mut self.pages[kind.index()];
454        assert!(
455            page.layers.is_empty(),
456            "the {} page already holds {} layer(s) authored at {} texels a side",
457            kind.label(),
458            page.layers.len(),
459            page.extent
460        );
461        page.extent = extent;
462    }
463
464    /// Appends a layer to `kind` and returns its index — the number the
465    /// material row's own texture column carries.
466    ///
467    /// `texels` is RGBA8, row-major, and exactly `extent² × 4` bytes, which
468    /// [`ForwardRenderer::with_scene`](crate::forward::ForwardRenderer::with_scene)
469    /// checks before it uploads anything. What the bytes *mean* is the kind's,
470    /// and the four differ: a [`BaseColor`](PageKind::BaseColor) layer and an
471    /// [`Emissive`](PageKind::Emissive) one are sRGB-encoded, because both are
472    /// *colours* and that is what glTF defines those two textures to be, and
473    /// the renderer creates their images as `Rgba8UnormSrgb` so the sampler
474    /// decodes them; a [`Normal`](PageKind::Normal) layer and a
475    /// [`MetallicRoughnessOcclusion`](PageKind::MetallicRoughnessOcclusion) one
476    /// are **linear** numbers — a tangent-space normal encoded as
477    /// `n * 0.5 + 0.5` per channel, and glTF's packed occlusion, roughness and
478    /// metallic in `r`, `g` and `b` — and their images are `Rgba8Unorm` so
479    /// nothing decodes them at all. See each kind's own arm of `PageKind::format`
480    /// and topic 44's rung 2.
481    ///
482    /// # Panics
483    ///
484    /// If `kind` has no extent yet: a layer's length is only meaningful against
485    /// one, so [`set_extent`](Self::set_extent) comes first.
486    pub fn push_layer(&mut self, kind: PageKind, texels: impl Into<Cow<'a, [u8]>>) -> u32 {
487        let page = &mut self.pages[kind.index()];
488        assert!(
489            page.extent > 0,
490            "the {} page has no extent, so this layer's length would be measured against \
491             nothing: set_extent comes first",
492            kind.label()
493        );
494        let layer = u32::try_from(page.layers.len())
495            .unwrap_or_else(|_| unreachable!("a page of more layers than a u32 can name"));
496        page.layers.push(texels.into());
497        layer
498    }
499
500    /// `kind`'s texels a side, or **zero** when nothing has named that page.
501    #[must_use]
502    pub const fn extent(&self, kind: PageKind) -> u32 {
503        self.pages[kind.index()].extent
504    }
505
506    /// Every layer of `kind`, in order: element `n` is layer `n`.
507    #[must_use]
508    pub fn layers(&self, kind: PageKind) -> &[Cow<'a, [u8]>] {
509        &self.pages[kind.index()].layers
510    }
511
512    /// Whether this description can be uploaded as written, checked by
513    /// [`ForwardRenderer::with_scene`](crate::forward::ForwardRenderer::with_scene)
514    /// before it creates anything.
515    ///
516    /// Two things, and they fail for different reasons.
517    /// [`push_layer`](Self::push_layer) takes bytes it cannot measure against an
518    /// extent it does not see, so a layer of the wrong length is an ordinary
519    /// caller mistake. Layers at *no* extent, on the other hand, are unspellable
520    /// through this type's own methods — `set_extent` refuses zero and
521    /// `push_layer` refuses a page without one — so that arm is what would catch
522    /// a *second* constructor that let one through, which is why it is checked
523    /// here rather than asserted at construction.
524    ///
525    /// # Errors
526    ///
527    /// [`HalError::InvalidDescriptor`] naming the kind, the layer and what is
528    /// wrong with it.
529    pub(crate) fn check(&self) -> Result<(), HalError> {
530        for kind in PageKind::ALL {
531            let page = &self.pages[kind.index()];
532            if page.layers.is_empty() {
533                continue;
534            }
535            if page.extent == 0 {
536                return Err(HalError::InvalidDescriptor(format!(
537                    "the {} page carries {} layer(s) at no extent, so there is no image for \
538                     them to go into",
539                    kind.label(),
540                    page.layers.len()
541                )));
542            }
543            let texels = page.extent as usize * page.extent as usize * 4;
544            for (layer, bytes) in page.layers.iter().enumerate() {
545                if bytes.len() != texels {
546                    return Err(HalError::InvalidDescriptor(format!(
547                        "{} page layer {layer} carries {} bytes, and a {}×{} RGBA8 layer is \
548                         {texels}",
549                        kind.label(),
550                        bytes.len(),
551                        page.extent,
552                        page.extent
553                    )));
554                }
555            }
556        }
557        Ok(())
558    }
559}
560
561/// Who writes an irradiance volume's rows: the description that authored them,
562/// or the irradiance probes' every-frame updater.
563///
564/// # Why this is a field of the volume and not an effect bit or a console
565/// variable
566///
567/// **Not a [`RenderEffects`](crate::effects::RenderEffects) bit**: those are a
568/// frame-wide toggle with a settings key each — `every_effect_has_a_key_and_no_two_share_one`
569/// is what holds that pairing — and a new key shifts the options demo's fader
570/// indices in `web/tools/browser-e2e.mjs`. What decides whether a *volume* is
571/// updated is a property of that volume, not of the frame.
572///
573/// **Not a console variable**: a convar is process-global, and the pass-list
574/// tests run every scene of a fixture in one process. A scene's answer would
575/// then depend on what ran before it.
576///
577/// So it is a field, and [`Authored`](Self::Authored) is [`Default`]: a scene
578/// that says nothing records neither of the updater's two passes and pays
579/// nothing for them.
580#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
581pub enum ProbeUpdate {
582    /// The rows are the ones [`ProbeGrid::probes`] carries, uploaded once and
583    /// never written again.
584    ///
585    /// Every scene that existed before the updater, and every scene whose
586    /// lighting a golden pins: `crates/crcbl/tests/golden/probes.png` is the
587    /// anti-vacuity floor for the whole probe read path and stands on rows a
588    /// Rust mirror can predict.
589    #[default]
590    Authored,
591    /// The rows are overwritten every frame by the reflective-shadow-map
592    /// gather — `crcbl_render::rsm` draws the map and
593    /// `crcbl_render::probe_gather` reads it into the table.
594    ///
595    /// [`ProbeGrid::probes`] is then the volume's *size* rather than its
596    /// contents: the rows still have to be there, because the table is sized
597    /// from them and `check` holds the two to each other, but what a frame reads
598    /// is what the gather wrote.
599    ///
600    /// **It needs the sun's near cascade.** The map is the cascade's own draws
601    /// through the cascade's own matrix, so a frame drawing without
602    /// [`RenderEffects::SHADOWS`](crate::effects::RenderEffects::SHADOWS) — or
603    /// one whose shadow cadence held cascade 0 — records neither pass and leaves
604    /// the rows as the last gather wrote them. The renderer keeps cascade 0 off
605    /// the static-cache hold for exactly this reason, so the ordinary frame does
606    /// run it; a caller that has raised `r_shadow_cadence` past one has asked
607    /// for the cascade to be redrawn less often and gets a bounce that follows
608    /// it.
609    ///
610    /// **Probes outside the near cascade gather nothing.** The map covers
611    /// cascade 0's camera-following sphere, so a volume larger than that sphere
612    /// has rows the updater never reaches.
613    /// [`ForwardRenderer::follow_probe_volume`](crate::forward::ForwardRenderer::follow_probe_volume)
614    /// is what closes that for a volume small enough to follow the camera: it
615    /// re-centres each level on a tracked point by whole probe steps and moves
616    /// the position table the gather reads with it. A volume authored to cover
617    /// its whole scene has nowhere to step to and keeps the rows the cascade
618    /// cannot reach.
619    EveryFrame,
620}
621
622/// Topic 50's irradiance volume (`docs/notes/rendering.md`): where the probes
623/// are, and what each of them holds.
624///
625/// The diffuse half of global illumination. `mesh.slang`
626/// interpolates the grid trilinearly and **adds** the result to the flat ambient
627/// term, so a description with no probes draws the frame it always did — see
628/// [`crcbl_shaders::probe`], which is where the spherical harmonics live and
629/// where they are checked against the literature.
630///
631/// # The irradiance is authored, not baked
632///
633/// [`GpuProbe::accumulate`](probe::GpuProbe::accumulate) is how an application
634/// turns an environment into a row, and it is the only correct way to fill one.
635/// There is no bake tool, on a hard prerequisite rather than on taste: a gather
636/// bake casts rays at scene triangles, and this engine has no ray-triangle
637/// intersector and no BVH — `crcbl_phys`'s `query` module has ray-vs-sphere,
638/// ray-vs-AABB and ray-vs-capsule and nothing else.
639///
640/// # [`Default`] is the volume that changes no pixel
641///
642/// No probes and a grid of no extent, which is what every existing caller gets:
643/// the shader's fetch clamps onto the table's cleared first row and adds
644/// exactly zero. There is no branch anywhere selecting it, and no
645/// [`RenderEffects`](crate::effects::RenderEffects) bit — the off-switch is the
646/// scene.
647#[derive(Clone, Debug, Default, PartialEq)]
648pub struct ProbeGrid {
649    /// Where the grid is, how far apart its probes are, and how many there are
650    /// on each axis.
651    pub volume: probe::ProbeVolume,
652    /// What fills [`probes`](Self::probes) once the scene is running.
653    ///
654    /// [`ProbeUpdate::Authored`] by default, which is the frame every scene drew
655    /// before the updater landed.
656    pub update: ProbeUpdate,
657    /// One row per probe, the clipmap's levels one after another finest first
658    /// and **`x`-fastest** within each, each level's cells wrapped by its own
659    /// scroll offset:
660    /// [`ProbeVolume::row`](probe::ProbeVolume::row) is the index, and it is
661    /// `level_row(level) + (z · counts.y + y) · counts.x + x` for the volume as
662    /// authored, before anything has scrolled.
663    ///
664    /// Its length must be [`volume`](Self::volume)'s
665    /// [`total`](probe::ProbeVolume::total) — one level's worth *per level* —
666    /// which
667    /// [`ForwardRenderer::with_scene`](crate::forward::ForwardRenderer::with_scene)
668    /// checks before it creates anything, through this type's own `check`.
669    pub probes: Vec<probe::GpuProbe>,
670}
671
672impl ProbeGrid {
673    /// Whether this grid can be uploaded as written, checked by
674    /// [`ForwardRenderer::with_scene`](crate::forward::ForwardRenderer::with_scene)
675    /// before it creates anything.
676    ///
677    /// The one thing that has to hold: the volume's counts, multiplied out and
678    /// taken once per level, come to exactly as many rows as there are probes.
679    /// **That is what bounds the shader's fetch**, and it is not a tidiness —
680    /// `mesh.slang` addresses a cell through the counts and a level through the
681    /// rows one level holds, so a grid claiming more probes than it carries
682    /// would read rows the description never wrote, and one claiming fewer would
683    /// leave part of the volume unlit while the table held the light for it.
684    ///
685    /// # Errors
686    ///
687    /// [`HalError::InvalidDescriptor`] naming both numbers.
688    pub(crate) fn check(&self) -> Result<(), HalError> {
689        let total = self.volume.total() as usize;
690        if total == self.probes.len() {
691            return Ok(());
692        }
693        Err(HalError::InvalidDescriptor(format!(
694            "the probe grid is {}×{}×{} over {} level(s), which is {total} \
695             probe(s), and the description carries {}",
696            self.volume.counts[0],
697            self.volume.counts[1],
698            self.volume.counts[2],
699            self.volume.level_count(),
700            self.probes.len()
701        )))
702    }
703}
704
705/// One resident mesh's geometry, as the renderer needs it: triangles for a
706/// vertex stage, clusters for a mesh stage, and nothing else.
707///
708/// The clusters are supplied rather than built, because building them is
709/// `crcbl-scene`'s `build_meshlets` and the renderer must not depend on that
710/// crate — §3.5 makes the meshlet build a **bake step** for exactly that reason.
711#[derive(Clone, Debug, PartialEq)]
712pub enum Geometry<'a> {
713    /// A mesh with no level hierarchy: one vertex range, one index range, one
714    /// run of clusters, drawn from every camera.
715    Flat {
716        /// Vertices as [`mesh::MeshVertex`] bytes — [`mesh::VERTEX_STRIDE`] per
717        /// vertex, little-endian, exactly what
718        /// [`cube_vertex_bytes`](mesh::cube_vertex_bytes) produces.
719        ///
720        /// **Interleaved, which is not how the pool stores them.** A record is
721        /// a position and then its attributes; [`crate::MeshPool::upload`]
722        /// separates the two streams, so a caller describes geometry once and
723        /// the position region reaches the device contiguous.
724        vertices: Cow<'a, [u8]>,
725        /// The scale and offset every UV lane in `vertices` was quantised
726        /// against — [`UvRange::from_uvs`] over the mesh's float coordinates,
727        /// before any vertex was built.
728        ///
729        /// It has to travel with the bytes: a `unorm16` lane means nothing
730        /// without it, and the pool cannot recover it from lanes that are
731        /// already quantised. It reaches the shaders through
732        /// [`mesh::GpuMesh::uv_range`].
733        uv_range: UvRange,
734        /// Triangle indices into `vertices`, **mesh-relative**: the pool's base
735        /// vertex is added by the shader through the mesh table.
736        indices: Cow<'a, [u32]>,
737        /// The same triangles partitioned for a mesh stage. Read on
738        /// [`GeometryPath::MeshShader`](crcbl_hal::GeometryPath::MeshShader) and
739        /// on no other path.
740        clusters: MeshClusters,
741        /// Per-mesh bits for [`mesh::GpuMesh::flags`] — today only
742        /// [`MESH_AUTHORED_TANGENTS`](mesh::GpuMesh::MESH_AUTHORED_TANGENTS).
743        ///
744        /// **Zero is the honest value for a caller that builds its vertices
745        /// with [`mesh::MeshVertex::from_normal`]**, which is every mesh this
746        /// engine authors for itself: that constructor fills the frame with
747        /// [`orthonormal_basis`](crcbl_shaders::vertex::orthonormal_basis)'
748        /// stand-in, which is orthonormal and agrees with no UV
749        /// parameterisation, so a normal map read through it would be rotated by
750        /// an angle nobody chose. Setting the bit is a claim that these
751        /// vertices came from a real `TANGENT`, and the fragment stage takes the
752        /// caller at its word — the screen-space derivative frame is what it
753        /// falls back to otherwise.
754        flags: u32,
755    },
756    /// Topic 25's cluster DAG: several levels of one surface, each
757    /// its own vertex range, with the grouping that relates them.
758    ///
759    /// # A coarse level has no attributes, and the caller has to supply them
760    ///
761    /// `crcbl_scene::simplify` is **position-only** and says so in its own
762    /// module docs: a coarser level's vertices are wherever the collapses put
763    /// them and belong to no vertex of the level below, so the decimator carries
764    /// no normals and no UVs. [`ClusterDag`] therefore holds positions, and
765    /// this variant's `levels` is where the attributes come back — one
766    /// vertex-byte array per level, which the caller produces however it can.
767    ///
768    /// [`demo`]'s dunes patch can do it because the surface is analytic:
769    /// `crcbl_shaders::dunes::vertex_at` evaluates the height field at a
770    /// position rather than interpolating an attribute nothing recorded. An
771    /// application-supplied DAG needs attribute-aware simplification or
772    /// nearest-source attribute transfer, which is unbuilt topic 25 work — so
773    /// this variant is usable today only by a caller that can answer that
774    /// question for its own surface.
775    Dag {
776        /// The range every level's UV lanes were quantised against — **one for
777        /// all of them**.
778        ///
779        /// The mesh path resolves a row through the instance's mesh, which for
780        /// a DAG is level 0, so a coarser level's vertices are decoded through
781        /// level 0's range. A caller that quantised each level against its own
782        /// bounds would see the coarse levels' texture slide.
783        uv_range: UvRange,
784        /// Vertex bytes per level, finest first and **parallel to
785        /// [`dag.levels`](ClusterDag::levels)** — same length, and one vertex
786        /// per position of the level beside it.
787        levels: Vec<Cow<'a, [u8]>>,
788        /// The levels, their clusters, and the groups that relate them.
789        dag: ClusterDag,
790        /// Per-mesh bits for [`mesh::GpuMesh::flags`] — today only
791        /// [`MESH_AUTHORED_TANGENTS`](mesh::GpuMesh::MESH_AUTHORED_TANGENTS).
792        ///
793        /// **Zero is the honest value for a caller that builds its vertices
794        /// with [`mesh::MeshVertex::from_normal`]**, which is every mesh this
795        /// engine authors for itself: that constructor fills the frame with
796        /// [`orthonormal_basis`](crcbl_shaders::vertex::orthonormal_basis)'
797        /// stand-in, which is orthonormal and agrees with no UV
798        /// parameterisation, so a normal map read through it would be rotated by
799        /// an angle nobody chose. Setting the bit is a claim that these
800        /// vertices came from a real `TANGENT`, and the fragment stage takes the
801        /// caller at its word — the screen-space derivative frame is what it
802        /// falls back to otherwise.
803        flags: u32,
804    },
805}
806
807impl Geometry<'_> {
808    /// How many mesh table entries this geometry occupies: one for a flat mesh,
809    /// one per level for a DAG.
810    ///
811    /// Never zero, and it is what a description's mesh ids are spaced by.
812    #[must_use]
813    pub fn levels(&self) -> usize {
814        match self {
815            Self::Flat { .. } => 1,
816            Self::Dag { dag, .. } => dag.levels.len(),
817        }
818    }
819}
820
821/// One mesh a scene makes resident.
822#[derive(Clone, Debug, PartialEq)]
823pub struct MeshDesc<'a> {
824    /// Debug name. A DAG's levels are named `"{label} level {n}"`, so a capture
825    /// says which level a buffer belongs to.
826    pub label: Cow<'a, str>,
827    /// The triangles and clusters themselves.
828    pub geometry: Geometry<'a>,
829}
830
831/// Everything a [`ForwardRenderer`](crate::forward::ForwardRenderer) makes
832/// resident, and how much room it reserves for it.
833///
834/// Read once, at [`with_scene`](crate::forward::ForwardRenderer::with_scene),
835/// and never again: the pools it sizes are created there and none of them grows.
836/// The order of [`meshes`](Self::meshes) and [`materials`](Self::materials) is
837/// load-bearing — see the [module docs](self).
838#[derive(Clone, Debug, PartialEq)]
839pub struct SceneDesc<'a> {
840    /// The resident meshes, in the order their table ids are handed out.
841    pub meshes: Vec<MeshDesc<'a>>,
842    /// §3.2's material table, row by row. **Row 0 is what an instance written
843    /// without a material id names**, so it is the row every unassigned object
844    /// shades through.
845    pub materials: Vec<mesh::GpuMaterial>,
846    /// The base-colour page the rows above index.
847    pub page: PageDesc<'a>,
848    /// Topic 50's irradiance volume, **added** to the
849    /// flat ambient term wherever it covers.
850    ///
851    /// [`ProbeGrid::default`] is a grid of nothing and changes no pixel, which
852    /// is what a description that does not mention it gets.
853    pub probes: ProbeGrid,
854    /// How much room each pool reserves.
855    pub capacities: Capacities,
856}
857
858/// One object in the scene: which resident mesh it draws, which row it shades
859/// through, and where it is.
860///
861/// Handed to [`ForwardRenderer::add_instance`] and
862/// [`ForwardRenderer::set_instance`], at any point in a renderer's life — this
863/// is the half of the scene that is calls rather than data, for the reason the
864/// [module docs](self) open with.
865///
866/// # Both fields are description indices, not table ids
867///
868/// [`mesh`](Self::mesh) is an index into [`SceneDesc::meshes`] and
869/// [`material`](Self::material) one into [`SceneDesc::materials`] — the
870/// positions a caller wrote its own description in, which is the only numbering
871/// it has. Neither is the id the GPU reads: a DAG occupies one mesh table entry
872/// **per level**, so a description's fourth mesh is very often not table entry
873/// four, and an instance always names level 0's entry whatever level it ends up
874/// drawn at. The renderer holds that mapping and is what resolves it.
875///
876/// [`ForwardRenderer::add_instance`]: crate::forward::ForwardRenderer::add_instance
877/// [`ForwardRenderer::set_instance`]: crate::forward::ForwardRenderer::set_instance
878#[derive(Clone, Copy, Debug, PartialEq)]
879pub struct InstanceDesc {
880    /// Which [`SceneDesc::meshes`] entry this object draws.
881    pub mesh: usize,
882    /// Which [`SceneDesc::materials`] row it shades through.
883    ///
884    /// Row 0 is the one [`mesh::GpuInstance::default`] names, so it is what an
885    /// object shades through by omission — see [`SceneDesc::materials`].
886    pub material: usize,
887    /// Where it is: a model matrix, on [`mesh::GpuInstance::transform`]'s
888    /// terms — **any affine one**, non-uniform scale included, because the mesh
889    /// shaders build the normal transform out of it rather than assuming its
890    /// 3×3 is orthonormal.
891    pub transform: Mat4,
892}
893
894/// Where [`demo`]'s cube is in [`SceneDesc::meshes`], and therefore what an
895/// [`InstanceDesc::mesh`] naming it carries.
896///
897/// **Public because placing an object is the caller's job.** [`demo`] says what
898/// is resident and [`ForwardRenderer::add_instance`] is what puts one of those
899/// meshes in the frame, so a caller of the demo scene needs a name for the entry
900/// it is placing. A literal `0` would mean whatever the first entry happens to
901/// be, and that list's order is load-bearing in the four ways the
902/// [module docs](self) open with.
903///
904/// [`ForwardRenderer::add_instance`]: crate::forward::ForwardRenderer::add_instance
905pub const DEMO_CUBE: usize = 0;
906/// Where [`demo`]'s pyramid is, on [`DEMO_CUBE`]'s terms.
907pub const DEMO_PYRAMID: usize = 1;
908/// Where [`demo`]'s open box is, on [`DEMO_CUBE`]'s terms.
909pub const DEMO_OPEN_BOX: usize = 2;
910/// Where [`demo`]'s dunes patch is, on [`DEMO_CUBE`]'s terms.
911///
912/// The description's only [`Geometry::Dag`], so a caller placing it asks
913/// [`ForwardRenderer::culls_clusters`] first — see
914/// [`ForwardRenderer::add_instance`], which is where that condition is written
915/// down.
916///
917/// [`ForwardRenderer::add_instance`]: crate::forward::ForwardRenderer::add_instance
918/// [`ForwardRenderer::culls_clusters`]: crate::forward::ForwardRenderer::culls_clusters
919pub const DEMO_DUNES: usize = 3;
920
921/// [`demo`]'s neutral material row, and what an [`InstanceDesc::material`]
922/// naming it carries.
923///
924/// **Row 0 is not a convention this module may pick**: it is the row
925/// [`mesh::GpuInstance::default`] names, so it is what an instance written by
926/// omission shades through. See [`SceneDesc::materials`].
927pub const DEMO_UNTINTED: usize = 0;
928/// [`demo`]'s tinted row — [`PYRAMID_TINT`] and [`PYRAMID_ROUGHNESS`], on
929/// [`DEMO_UNTINTED`]'s terms.
930pub const DEMO_TINTED: usize = 1;
931/// [`demo`]'s textured row — [`CHECKER_LAYER`], on [`DEMO_UNTINTED`]'s terms.
932pub const DEMO_TEXTURED: usize = 2;
933
934/// The engine's own scene: the cube, the pyramid, the open box and the dunes
935/// DAG, with the three material rows and the two page layers the golden suite
936/// reads.
937///
938/// **This is what the renderer used to upload to itself**, moved out unchanged —
939/// [`ForwardRenderer::new`](crate::forward::ForwardRenderer::new) is
940/// `with_scene(&demo())`, so every existing caller draws the frame it always
941/// did.
942///
943/// # Why each mesh is here
944///
945/// * The **cube** is stage 2's rung 3, and the first
946///   resident of the pools.
947/// * The **pyramid** is second, so the pool's second resident is at a non-zero
948///   base vertex — the one thing that can tell a working base vertex from one
949///   silently cancelled out.
950/// * The **open box** is five clusters, one flat face each, four of them at a
951///   non-zero [`Meshlet::vertex_offset`](crcbl_shaders::meshlet::Meshlet::vertex_offset):
952///   the same argument one layer down, and the only resident whose cluster count
953///   is not one.
954/// * The **dunes patch** is the only one with a DAG, and it is analytic, which
955///   is what lets [`Geometry::Dag`] be filled in at all — see that variant.
956///
957/// # Why three material rows and not four
958///
959/// The three are one row and two edits of it, and no edit can be mistaken for
960/// another — which is what makes each of §3.2's columns its own evidence. The
961/// textured row differs from the untinted one in its page layer and nothing
962/// else. The tinted row differs in its base-colour factor and in
963/// [`PYRAMID_ROUGHNESS`], which is two columns rather than one, and the reason
964/// that is still separable is that the two do disjoint things to a frame: a
965/// factor cannot narrow a highlight and a roughness cannot tint a surface, so
966/// the colour assertions read one and the highlight assertion reads the other.
967///
968/// The roughness had to go on *that* row rather than on either of the others,
969/// and it is the geometry that decides it. `Scene::Cube` puts the tinted pyramid
970/// at `+X` and the default sun comes from `+X`, so its front face is the one
971/// place in that frame where a surface sits at the mirror direction — and a
972/// specular lobe's width is only legible where its peak actually lands. On the
973/// two left-hand pyramids the same pair of roughnesses draws very nearly the
974/// same face, which is exactly why the frame comparison uses them as its
975/// control.
976#[must_use]
977pub fn demo() -> SceneDesc<'static> {
978    let mut page = PageDesc::empty();
979    page.set_extent(PageKind::BaseColor, PAGE_EXTENT);
980    let checker = page.push_layer(PageKind::BaseColor, &CHECKER_TEXELS[..]);
981    debug_assert_eq!(
982        checker, CHECKER_LAYER,
983        "the checker is this page's first and only layer"
984    );
985
986    SceneDesc {
987        meshes: vec![
988            MeshDesc {
989                label: Cow::Borrowed("cube"),
990                geometry: Geometry::Flat {
991                    vertices: Cow::Owned(mesh::cube_vertex_bytes()),
992                    uv_range: mesh::demo_uv_range(),
993                    indices: Cow::Owned(mesh::cube_indices()),
994                    clusters: crcbl_shaders::meshlet::cube_clusters(),
995                    // **Unmarked, and every mesh below it too.**
996                    // `crcbl_shaders::mesh` builds these three out of positions,
997                    // normals and UVs — `MeshVertex::from_normal`, whose frame
998                    // is a stand-in — so none of them has a tangent that agrees
999                    // with its own texture coordinates. Claiming otherwise would
1000                    // point the fragment stage at eight bytes that mean nothing
1001                    // for sampling.
1002                    flags: 0,
1003                },
1004            },
1005            MeshDesc {
1006                label: Cow::Borrowed("pyramid"),
1007                geometry: Geometry::Flat {
1008                    vertices: Cow::Owned(mesh::pyramid_vertex_bytes()),
1009                    uv_range: mesh::demo_uv_range(),
1010                    indices: Cow::Owned(mesh::pyramid_indices()),
1011                    clusters: crcbl_shaders::meshlet::pyramid_clusters(),
1012                    flags: 0,
1013                },
1014            },
1015            MeshDesc {
1016                label: Cow::Borrowed("open box"),
1017                geometry: Geometry::Flat {
1018                    vertices: Cow::Owned(mesh::open_box_vertex_bytes()),
1019                    uv_range: mesh::demo_uv_range(),
1020                    indices: Cow::Owned(mesh::open_box_indices()),
1021                    clusters: crcbl_shaders::meshlet::open_box_clusters(),
1022                    flags: 0,
1023                },
1024            },
1025            MeshDesc {
1026                label: Cow::Borrowed("dunes"),
1027                geometry: dunes_geometry(),
1028            },
1029        ],
1030        materials: vec![
1031            // **First, so it is row 0** — which is what
1032            // `mesh::GpuInstance::default` names, and therefore what an
1033            // instance written without a material id shades with. The page
1034            // column is named rather than left to `UNTINTED`'s own, so the two
1035            // agreeing is a fact visible at the call site.
1036            mesh::GpuMaterial {
1037                base_color_texture: mesh::GpuMaterial::NO_PAGE,
1038                ..mesh::GpuMaterial::UNTINTED
1039            },
1040            mesh::GpuMaterial {
1041                base_color: PYRAMID_TINT,
1042                roughness: PYRAMID_ROUGHNESS,
1043                ..mesh::GpuMaterial::UNTINTED
1044            },
1045            mesh::GpuMaterial {
1046                base_color_texture: CHECKER_LAYER,
1047                ..mesh::GpuMaterial::UNTINTED
1048            },
1049        ],
1050        page,
1051        // **No probes**, and that is what keeps every golden in the tree
1052        // byte-identical: the grid is authored per scene, this description
1053        // authors none, and a grid of nothing adds exactly zero. The sample
1054        // that has one is `apps/lantern`'s room.
1055        probes: ProbeGrid::default(),
1056        capacities: Capacities::default(),
1057    }
1058}
1059
1060/// The dunes patch, level by level.
1061///
1062/// The geometry of a coarser level is positions and nothing else — the
1063/// decimator carries no attributes — so `dunes::vertex_at` is what turns each
1064/// into a vertex, by evaluating the surface rather than by interpolating an
1065/// attribute nothing recorded. See [`Geometry::Dag`], which is where that
1066/// constraint is stated for every caller.
1067fn dunes_geometry() -> Geometry<'static> {
1068    let dag = crcbl_shaders::cluster_dag::dunes_dag();
1069    let levels = dag
1070        .levels
1071        .iter()
1072        .map(|level| {
1073            let vertices: Vec<mesh::MeshVertex> = level
1074                .positions
1075                .iter()
1076                .map(|&position| crcbl_shaders::dunes::vertex_at(position))
1077                .collect();
1078            Cow::Owned(mesh::vertex_bytes(&vertices))
1079        })
1080        .collect();
1081    Geometry::Dag {
1082        // Every level's, because `dunes::vertex_at` maps the patch's extent
1083        // onto the unit square whatever the decimator did to a position — see
1084        // `crcbl_shaders::dunes::uv_range`.
1085        uv_range: crcbl_shaders::dunes::uv_range(),
1086        levels,
1087        dag,
1088        // Unmarked, for the three meshes above's reason: `dunes::vertex_at`
1089        // evaluates a height field and hands `MeshVertex::from_normal` a normal,
1090        // so the frame it encodes is the arbitrary stand-in.
1091        flags: 0,
1092    }
1093}
1094
1095#[cfg(test)]
1096mod tests {
1097    use super::*;
1098
1099    /// **Row 0 is [`mesh::GpuMaterial::UNTINTED`] naming no page**, and nothing
1100    /// else may take that place.
1101    ///
1102    /// It is the row [`mesh::GpuInstance::default`] names, so every instance
1103    /// written by omission shades through it. A description that inserted the
1104    /// tint first would put a blue factor and a tighter lobe on every object
1105    /// nobody assigned a material to — the two pyramids would swap materials,
1106    /// and the frame would still look like a frame.
1107    #[test]
1108    fn the_demo_scene_shades_by_omission_through_an_untinted_row() {
1109        let scene = demo();
1110        assert_eq!(
1111            usize::try_from(mesh::GpuInstance::default().material).expect("a table of three rows"),
1112            DEMO_UNTINTED,
1113            "the row a caller names by omission and the one it names by index are the same row"
1114        );
1115        assert_eq!(
1116            scene.materials[mesh::GpuInstance::default().material as usize],
1117            mesh::GpuMaterial {
1118                base_color_texture: mesh::GpuMaterial::NO_PAGE,
1119                ..mesh::GpuMaterial::UNTINTED
1120            },
1121            "row 0 is what an instance with no material id names"
1122        );
1123        // And the other two are edits of it that a frame can tell apart — a
1124        // second row equal to the first would make every pair the golden suite
1125        // compares prove nothing.
1126        assert_ne!(scene.materials[0], scene.materials[1]);
1127        assert_ne!(scene.materials[0], scene.materials[2]);
1128        assert_eq!(
1129            scene.materials[0].base_color, scene.materials[2].base_color,
1130            "the texture pair must share a factor, or it is evidence about two columns"
1131        );
1132    }
1133
1134    /// **[`PageDesc::empty`] allocates nothing, and the two kinds are sized and
1135    /// numbered apart.**
1136    ///
1137    /// The whole of what row (d) changed, in one place: a description starts
1138    /// with no page at all, a kind nothing names keeps an extent of zero, and
1139    /// each kind's layers count from zero on their own — so a row pointed at a
1140    /// base-colour layer number is not pointed at a normal layer that happens to
1141    /// exist.
1142    #[test]
1143    fn a_page_names_each_kind_apart_and_starts_naming_none() {
1144        let page = PageDesc::empty();
1145        for kind in PageKind::ALL {
1146            assert_eq!(page.extent(kind), 0, "{} starts unsized", kind.label());
1147            assert!(
1148                page.layers(kind).is_empty(),
1149                "{} starts empty",
1150                kind.label()
1151            );
1152        }
1153        page.check().expect("a description naming no page is legal");
1154
1155        // Two extents, and the smaller one is the normal page — the shape the
1156        // one shared extent could not describe at all.
1157        let mut page = PageDesc::empty();
1158        page.set_extent(PageKind::BaseColor, 4);
1159        page.set_extent(PageKind::Normal, 2);
1160        let colour = page.push_layer(PageKind::BaseColor, vec![0x11; 4 * 4 * 4]);
1161        let normal = page.push_layer(PageKind::Normal, vec![0x22; 2 * 2 * 4]);
1162        assert_eq!(
1163            (colour, normal),
1164            (0, 0),
1165            "each kind numbers its own layers, and both start at zero"
1166        );
1167        assert_eq!(
1168            (
1169                page.extent(PageKind::BaseColor),
1170                page.extent(PageKind::Normal)
1171            ),
1172            (4, 2),
1173            "one kind's extent says nothing about the other's"
1174        );
1175        assert_eq!(page.layers(PageKind::BaseColor)[0][0], 0x11);
1176        assert_eq!(page.layers(PageKind::Normal)[0][0], 0x22);
1177        page.check()
1178            .expect("two kinds at two extents, each layer its own extent's worth");
1179    }
1180
1181    /// **[`PageDesc::check`] refuses every page the renderer could not upload**,
1182    /// including the one shape no caller can spell, built here through the
1183    /// private fields no caller has.
1184    ///
1185    /// The length arm is an ordinary caller mistake: `push_layer` takes bytes it
1186    /// cannot measure. The no-extent arm is not spellable through the type's own
1187    /// methods at all — which is exactly why it is checked rather than asserted,
1188    /// and why it is built here from the fields.
1189    #[test]
1190    fn a_page_the_device_could_not_upload_is_refused() {
1191        // The shape that is right, which every wrong one below is one field
1192        // away from — and which is checked last, so a `check` that refused
1193        // everything could not pass this test.
1194        let good = || {
1195            let mut page = PageDesc::empty();
1196            for kind in PageKind::ALL {
1197                page.set_extent(kind, 2);
1198            }
1199            page
1200        };
1201
1202        for kind in PageKind::ALL {
1203            let mut short = good();
1204            short.push_layer(kind, vec![0x00; 4]);
1205            let refusal = short
1206                .check()
1207                .expect_err("a layer of the wrong length would upload another layer's texels");
1208            let HalError::InvalidDescriptor(said) = refusal else {
1209                panic!("a description is refused as a description");
1210            };
1211            assert!(
1212                said.contains(&format!("{} page layer 0 carries 4 bytes", kind.label())),
1213                "the refusal must name the kind and the layer, and it said {said:?}"
1214            );
1215
1216            // Layers at no extent: the pair `set_extent` and `push_layer`
1217            // between them make unreachable, and the arm that would catch a
1218            // second constructor letting one through.
1219            let mut unsized_page = PageDesc::empty();
1220            unsized_page.pages[kind.index()]
1221                .layers
1222                .push(Cow::Owned(vec![0x00; 2 * 2 * 4]));
1223            let refusal = unsized_page
1224                .check()
1225                .expect_err("layers at no extent name an image that was never sized");
1226            let HalError::InvalidDescriptor(said) = refusal else {
1227                panic!("a description is refused as a description");
1228            };
1229            assert!(
1230                said.contains(&format!(
1231                    "the {} page carries 1 layer(s) at no extent",
1232                    kind.label()
1233                )),
1234                "the refusal must name the kind, and it said {said:?}"
1235            );
1236        }
1237
1238        // Every layer is unconstrained but for its length, on every kind, so
1239        // the accepted shape carries two of each and nothing white or neutral
1240        // about any of them.
1241        let mut whole = good();
1242        for kind in PageKind::ALL {
1243            whole.push_layer(kind, vec![0x00; 2 * 2 * 4]);
1244            whole.push_layer(kind, vec![0x7B; 2 * 2 * 4]);
1245        }
1246        whole
1247            .check()
1248            .expect("two full-length layers on each kind is a page the renderer uploads");
1249    }
1250
1251    /// **[`demo`]'s page is its checker and nothing else**, at
1252    /// [`CHECKER_LAYER`], and it names no normal page at all.
1253    ///
1254    /// The layer number is the one [`DEMO_TEXTURED`] carries, so a page that
1255    /// pushed its checker anywhere else would shade that row through a layer the
1256    /// description does not have — refused at `with_scene` — or, worse, through
1257    /// one it does.
1258    #[test]
1259    fn the_demo_page_is_one_checker_layer_and_no_normal_page() {
1260        let page = demo().page;
1261        assert_eq!(page.extent(PageKind::BaseColor), PAGE_EXTENT);
1262        assert_eq!(
1263            page.layers(PageKind::BaseColor).len(),
1264            1,
1265            "the demo page is the checker alone: nothing burns a layer any more"
1266        );
1267        assert_eq!(
1268            page.layers(PageKind::BaseColor)[CHECKER_LAYER as usize].as_ref(),
1269            &CHECKER_TEXELS[..]
1270        );
1271        assert_eq!(
1272            demo().materials[DEMO_TEXTURED].base_color_texture,
1273            CHECKER_LAYER,
1274            "the textured row names the layer the page actually pushed"
1275        );
1276        assert_eq!(
1277            page.extent(PageKind::Normal),
1278            0,
1279            "nothing in the demo scene names a normal map, so that page is one \
1280             placeholder texel on the device"
1281        );
1282        page.check().expect("the demo page uploads as written");
1283    }
1284
1285    /// The description the renderer consumes really is the resident set it used
1286    /// to hold: four meshes in the order the mesh ids are handed out, with the
1287    /// DAG last and carrying a vertex array per level.
1288    #[test]
1289    fn the_demo_scene_describes_the_residents_in_upload_order() {
1290        let scene = demo();
1291        let labels: Vec<&str> = scene
1292            .meshes
1293            .iter()
1294            .map(|mesh| mesh.label.as_ref())
1295            .collect();
1296        assert_eq!(labels, ["cube", "pyramid", "open box", "dunes"]);
1297        // And each index a caller places one of them by names that entry. A
1298        // constant off by one puts an application's cube wherever the pyramid
1299        // is — a frame that draws, of the wrong mesh.
1300        assert_eq!(
1301            [DEMO_CUBE, DEMO_PYRAMID, DEMO_OPEN_BOX, DEMO_DUNES].map(|mesh| labels[mesh]),
1302            ["cube", "pyramid", "open box", "dunes"]
1303        );
1304        assert_eq!(
1305            scene.meshes[..3]
1306                .iter()
1307                .map(|mesh| mesh.geometry.levels())
1308                .collect::<Vec<_>>(),
1309            [1, 1, 1],
1310            "the flat residents are one mesh table entry each"
1311        );
1312
1313        let Geometry::Dag { levels, dag, .. } = &scene.meshes[3].geometry else {
1314            panic!("the dunes patch is the description's only DAG");
1315        };
1316        assert_eq!(
1317            levels.len(),
1318            dag.levels.len(),
1319            "a level with no vertices would draw its clusters out of the level below"
1320        );
1321        for (depth, (bytes, level)) in levels.iter().zip(&dag.levels).enumerate() {
1322            assert_eq!(
1323                bytes.len(),
1324                level.positions.len() * mesh::VERTEX_STRIDE,
1325                "level {depth} carries one vertex per position"
1326            );
1327        }
1328        assert!(
1329            dag.levels.len() > 1,
1330            "a one-level DAG is a flat mesh with extra steps, and would select nothing"
1331        );
1332    }
1333
1334    /// The capacities a description defaults to are the ones the renderer has
1335    /// always reserved. A default that moved would resize five device-local
1336    /// pools for every existing caller at once.
1337    #[test]
1338    fn the_default_capacities_are_the_ones_the_engine_shipped() {
1339        assert_eq!(
1340            Capacities::default(),
1341            Capacities {
1342                vertices: 64 * 1024,
1343                indices: 256 * 1024,
1344                meshes: 1024,
1345                instances: 16 * 1024,
1346                materials: 1024,
1347                lights: 1024,
1348                probes: 0,
1349            }
1350        );
1351        assert_eq!(demo().capacities, Capacities::default());
1352    }
1353
1354    /// **The engine's own scene has no probes**, which is the whole of why
1355    /// adding the grid moved no golden: an empty volume evaluates to exactly
1356    /// zero and the shader adds it to the ambient term.
1357    #[test]
1358    fn the_demo_scene_authors_no_probes() {
1359        let scene = demo();
1360        assert_eq!(scene.probes, ProbeGrid::default());
1361        assert!(scene.probes.probes.is_empty());
1362        assert_eq!(scene.probes.volume.total(), 0);
1363        assert_eq!(scene.capacities.probes, 0);
1364        scene
1365            .probes
1366            .check()
1367            .expect("an empty grid uploads as written");
1368    }
1369
1370    /// **A grid whose counts disagree with its rows is refused**, in both
1371    /// directions — the check that bounds the shader's fetch.
1372    #[test]
1373    fn a_grid_that_would_read_rows_it_does_not_carry_is_refused() {
1374        let two = vec![probe::GpuProbe::ZERO; 2];
1375        let claims_more = ProbeGrid {
1376            update: ProbeUpdate::Authored,
1377            volume: probe::ProbeVolume {
1378                counts: [2, 2, 1],
1379                ..probe::ProbeVolume::default()
1380            },
1381            probes: two.clone(),
1382        };
1383        claims_more
1384            .check()
1385            .expect_err("a 2×2×1 grid carrying two probes would read rows it never wrote");
1386
1387        let claims_fewer = ProbeGrid {
1388            update: ProbeUpdate::Authored,
1389            volume: probe::ProbeVolume {
1390                counts: [1, 1, 1],
1391                ..probe::ProbeVolume::default()
1392            },
1393            probes: two.clone(),
1394        };
1395        claims_fewer
1396            .check()
1397            .expect_err("a one-probe grid carrying two leaves one unreachable");
1398
1399        // And the shape that agrees is accepted, or the two refusals above
1400        // would pass on a check that refused everything.
1401        ProbeGrid {
1402            update: ProbeUpdate::Authored,
1403            volume: probe::ProbeVolume {
1404                counts: [2, 1, 1],
1405                inv_spacing: [1.0; 3],
1406                origin: [0.0; 3],
1407                levels: 1,
1408                steps: probe::ProbeSteps::default(),
1409            },
1410            probes: two.clone(),
1411        }
1412        .check()
1413        .expect("two probes on a 2×1×1 grid");
1414
1415        // **A level is a whole copy of the grid**, so a two-level clipmap of
1416        // the same counts needs twice the rows — a check that only multiplied
1417        // the counts would accept this pair the wrong way round.
1418        let clipmap = probe::ProbeVolume {
1419            counts: [2, 1, 1],
1420            inv_spacing: [1.0; 3],
1421            origin: [0.0; 3],
1422            levels: 2,
1423            steps: probe::ProbeSteps::default(),
1424        };
1425        ProbeGrid {
1426            update: ProbeUpdate::Authored,
1427            volume: clipmap,
1428            probes: two.clone(),
1429        }
1430        .check()
1431        .expect_err("a two-level clipmap of two probes a level needs four rows");
1432        ProbeGrid {
1433            update: ProbeUpdate::Authored,
1434            volume: clipmap,
1435            probes: vec![probe::GpuProbe::ZERO; 4],
1436        }
1437        .check()
1438        .expect("four rows fill a two-level clipmap of two probes a level");
1439    }
1440}