Skip to main content

crcbl_render/forward/
shadow_inputs.rs

1//! Complete logical input records for shadow-atlas group reuse.
2
3use super::ForwardRenderer;
4use crate::cull::{Aabb, Frustum};
5use crate::shadow;
6use crcbl_shaders::mesh::{self, GpuInstance, GpuMesh};
7use glam::{Mat4, Vec3};
8
9/// How much wider than its own world box an instance's footprint is taken to
10/// be, relative to the box's size and its distance from the origin, and in
11/// world units on top of that.
12///
13/// **Slack in the safe direction.** `cull.slang` tests the same box against the
14/// same planes in `f32`, and a host and a GPU can round one comparison two ways
15/// for a box that grazes a plane. A footprint that said "outside" where the cull
16/// said "inside" would hold a map the caster is in, so the host's box is the
17/// larger one: a caster grazing a light's frustum redraws that light's map when
18/// the cull may not have drawn it, never the other way round.
19const FOOTPRINT_SLACK: f32 = 1.0e-3;
20
21/// Where one element of the instance array can put depth into a shadow map, as
22/// the shadow culls would decide it.
23///
24/// **The cull's own question, asked on the host and answered conservatively.**
25/// `cull.slang` keeps an instance when it is live and its box —
26/// [`GpuInstance::cull_bounds`], the record's own or its mesh's — carried by
27/// its transform, reaches inside every plane of the cull's frustum — and only a
28/// kept instance draws. [`crate::cull::visible_instances`] is the same rule, and
29/// this is it with every doubt resolved towards "it could be anywhere".
30#[derive(Clone, Copy, Debug, Default, PartialEq)]
31pub(super) enum CasterFootprint {
32    /// Draws nothing: a slot no instance holds, or one whose
33    /// [`GpuInstance::LIVE`] bit is clear, which the cull asks before anything.
34    #[default]
35    Nowhere,
36    /// Draws only where this world box reaches, slack included.
37    Within(Aabb),
38    /// Could draw into any map: a skinned instance with no box of its own,
39    /// whose vertices are not its mesh's and so are bounded by nothing the host
40    /// holds, or a record whose mesh or transform gives no finite box.
41    Everywhere,
42}
43
44impl CasterFootprint {
45    /// The footprint of `record`, with its mesh looked up in `meshes`.
46    pub(super) fn of(record: &GpuInstance, meshes: &[GpuMesh]) -> Self {
47        if record.flags & GpuInstance::LIVE == 0 {
48            return Self::Nowhere;
49        }
50        // A mesh id with no entry, or an entry naming no mesh, is one the cull
51        // rejects; it is taken as everywhere all the same, because the cost of
52        // being wrong about an id nothing should name is a redraw.
53        let Some(mesh) = meshes
54            .get(record.mesh as usize)
55            .filter(|mesh| mesh.index_count > 0)
56        else {
57            return Self::Everywhere;
58        };
59        // The cull keeps a skinned instance with no box of its own whatever its
60        // mesh's box says — see `crate::cull::visible_instances` — because that
61        // box is its source mesh's and its vertices are a compute pass's.
62        let Some((min, max)) = record.cull_bounds(mesh) else {
63            return Self::Everywhere;
64        };
65        let world = Aabb {
66            min: Vec3::from_array(min),
67            max: Vec3::from_array(max),
68        }
69        .transformed(Mat4::from_cols_array(&record.transform));
70        let (center, extent) = (world.center(), world.half_extent());
71        let slack =
72            FOOTPRINT_SLACK * (1.0 + center.abs().max_element() + extent.abs().max_element());
73        if !(center.is_finite() && extent.is_finite() && slack.is_finite()) {
74            // A NaN would make every plane test false, which reads as "outside
75            // every frustum" — the one answer a footprint must never give by
76            // accident.
77            return Self::Everywhere;
78        }
79        Self::Within(Aabb {
80            min: world.min - Vec3::splat(slack),
81            max: world.max + Vec3::splat(slack),
82        })
83    }
84
85    /// Whether a cull against `frustum` could keep this instance.
86    pub(super) fn reaches(&self, frustum: &Frustum) -> bool {
87        match self {
88            Self::Nowhere => false,
89            Self::Within(bounds) => frustum.intersects(bounds),
90            Self::Everywhere => true,
91        }
92    }
93}
94
95/// The part of a shadow view's block the depth pass reads, with every other
96/// field zeroed.
97///
98/// **What the atlas is a function of, read off the shaders** rather than off
99/// the block's declaration. The atlas is drawn by `depth_pipeline` and
100/// `depth_masked_pipeline` alone: `mesh.slang`'s `depthVertexMain`, or its
101/// `vertexMain` ahead of `depthMaskedFragmentMain` for a cutout, or
102/// `mesh_cluster.slang`'s amplification and mesh stages on the mesh path, and
103/// `depthClearVertexMain` for a tile reset. Between them they read
104/// `view_proj`, `previous_view_proj`, `camera_position` — the light, for the
105/// normal-cone test — `lod_params`, `vertex_pool` and the debug view switch in
106/// `ambient.w`, and nothing else of `FrameUniforms`. Every other field is the
107/// colour pass's: the cascades' matrices and reaches, the light tiles', the
108/// froxel grid, the probes, the fog and the sky. Several of them are fitted to
109/// the camera, and carried into a light's record they redrew the light's maps
110/// whenever the camera moved.
111///
112/// A shader change that makes the depth pass read another field has to add it
113/// here, or a map drawn from a stale value of it will be held.
114/// [`FRAME_UNIFORMS_READERS`] is the same split as a table, and the two checks
115/// on it are what hold this function to the shaders: this module's tests hold
116/// the function to the table, and `crcbl`'s `mesh_e2e` `shadow_block_reads`
117/// holds the table to the atlas a device draws.
118fn depth_pass_reads(block: &mesh::FrameUniforms) -> mesh::FrameUniforms {
119    mesh::FrameUniforms {
120        view_proj: block.view_proj,
121        camera_position: block.camera_position,
122        ambient: [0.0, 0.0, 0.0, block.ambient[3]],
123        shadow_view_proj: [[0.0; 16]; mesh::SHADOW_CASCADES],
124        cascade_far: [0.0; 4],
125        shadow_params: [0.0; 4],
126        cluster_grid: [0; 4],
127        light_view_proj: [[0.0; 16]; mesh::SHADOW_LIGHT_TILES],
128        probes: crcbl_shaders::probe::ProbeVolume::default(),
129        lod_params: block.lod_params,
130        fog_params: [0.0; 4],
131        fog_color: [0.0; 4],
132        sky_sh_r: [0.0; 4],
133        sky_sh_g: [0.0; 4],
134        sky_sh_b: [0.0; 4],
135        previous_view_proj: block.previous_view_proj,
136        vertex_pool: block.vertex_pool,
137        shadow_atlas_rect: [[0.0; 4]; mesh::SHADOW_ATLAS_TILES],
138        shadow_filter: [0; 4],
139    }
140}
141
142/// Which pass reads a [`UniformsField`] of a shadow view's block.
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
144pub enum UniformsReader {
145    /// The atlas's depth pass reads it, so a held map's group record carries it
146    /// — `depth_pass_reads` keeps it.
147    DepthPass,
148    /// Only the colour pass reads it, so a change to it is no reason to redraw a
149    /// map — `depth_pass_reads` zeroes it.
150    ColourOnly,
151}
152
153/// One field of [`mesh::FrameUniforms`], or the lanes of one field that a
154/// single reader owns, as the shadow atlas's depth pass sees it.
155#[derive(Clone, Copy, Debug)]
156pub struct UniformsField {
157    /// The field's name, with the lanes after a dot where the field is split —
158    /// `ambient.xyz` and `ambient.w`.
159    pub name: &'static str,
160    /// Which pass reads it.
161    pub reader: UniformsReader,
162    /// Overwrites this field's lanes of a block with a value no frame writes
163    /// there, and leaves every other lane alone.
164    ///
165    /// A [`UniformsReader::DepthPass`] entry's overwrite is a *nudge* rather
166    /// than garbage — the view's depth pushed by a fraction, a lane toggled — so
167    /// that a device test perturbing it still draws geometry into the atlas to
168    /// compare.
169    pub perturb: fn(&mut mesh::FrameUniforms),
170}
171
172/// A matrix no view is drawn through: every element distinct, none of them a
173/// value a projection or an identity would hold.
174const GARBAGE_MATRIX: [f32; 16] = [
175    -279.375, 242.125, -204.875, 167.625, -130.375, 93.125, -55.875, 18.625, -18.625, 55.875,
176    -93.125, 130.375, -167.625, 204.875, -242.125, 279.375,
177];
178
179/// **Every field of a shadow view's block, and which pass reads it** — the
180/// split `depth_pass_reads` makes, as data a test can walk.
181///
182/// A test hook rather than anything the renderer runs: the renderer's own
183/// split is `depth_pass_reads`, and nothing in a frame reads this. Two tests
184/// do, and between them they close the loop that function's doc leaves to a
185/// reader of the shaders:
186///
187/// * **This module's tests** hold `depth_pass_reads` to the table — every
188///   depth-read entry moves its output, every colour-only one does not — and
189///   hold the table to the struct: every field is classified, a split field in
190///   every lane, and each entry's perturbation touches its own lanes alone.
191///   Adding a field to [`mesh::FrameUniforms`] stops them compiling until it is
192///   entered here.
193/// * **`crcbl`'s `mesh_e2e` `shadow_block_reads`** holds the table to the
194///   shaders: it draws the atlas on every geometry path with each colour-only
195///   entry perturbed in every block the depth pass is fed, through
196///   [`ForwardRenderer::set_shadow_view_tamper`], and asserts the depth it
197///   reads back is unchanged to the bit.
198///
199/// So a shader that starts reading a field listed as colour-only turns that
200/// device test red, and moving the field to the depth-read side here turns
201/// this module's test red until `depth_pass_reads` keeps it.
202pub const FRAME_UNIFORMS_READERS: &[UniformsField] = &[
203    UniformsField {
204        name: "view_proj",
205        reader: UniformsReader::DepthPass,
206        perturb: |block| block.view_proj[14] += 0.0625,
207    },
208    UniformsField {
209        name: "camera_position",
210        reader: UniformsReader::DepthPass,
211        perturb: |block| block.camera_position[0] += 3.0,
212    },
213    UniformsField {
214        name: "ambient.xyz",
215        reader: UniformsReader::ColourOnly,
216        perturb: |block| {
217            block.ambient[0] = -913.25;
218            block.ambient[1] = 4096.5;
219            block.ambient[2] = 0.007_812_5;
220        },
221    },
222    UniformsField {
223        name: "ambient.w",
224        reader: UniformsReader::DepthPass,
225        perturb: |block| block.ambient[3] = 1.0 - block.ambient[3],
226    },
227    UniformsField {
228        name: "shadow_view_proj",
229        reader: UniformsReader::ColourOnly,
230        perturb: |block| block.shadow_view_proj = [GARBAGE_MATRIX; mesh::SHADOW_CASCADES],
231    },
232    UniformsField {
233        name: "cascade_far",
234        reader: UniformsReader::ColourOnly,
235        perturb: |block| block.cascade_far = [-1.5e6, 3.0e-7, 777.0, -0.0],
236    },
237    UniformsField {
238        name: "shadow_params",
239        reader: UniformsReader::ColourOnly,
240        perturb: |block| block.shadow_params = [123.0, -456.0, 7.0e5, -8.0e-5],
241    },
242    UniformsField {
243        name: "cluster_grid",
244        reader: UniformsReader::ColourOnly,
245        perturb: |block| block.cluster_grid = [0xDEAD_BEEF, 0x0BAD_F00D, 0xFEED_FACE, 0x1234_5678],
246    },
247    UniformsField {
248        name: "light_view_proj",
249        reader: UniformsReader::ColourOnly,
250        perturb: |block| block.light_view_proj = [GARBAGE_MATRIX; mesh::SHADOW_LIGHT_TILES],
251    },
252    UniformsField {
253        name: "probes",
254        reader: UniformsReader::ColourOnly,
255        perturb: |block| {
256            block.probes = crcbl_shaders::probe::ProbeVolume {
257                origin: [-321.5, 654.25, -987.0],
258                inv_spacing: [13.0, -0.5, 1.0e4],
259                counts: [0xDEAD, 3, 0xBEEF],
260                levels: 0xFFFF_FFF0,
261                steps: [[-77_777, 31_337, i32::MIN]; crcbl_shaders::probe::PROBE_LEVELS],
262            };
263        },
264    },
265    UniformsField {
266        name: "lod_params",
267        reader: UniformsReader::DepthPass,
268        perturb: |block| block.lod_params[0] += 1.5,
269    },
270    UniformsField {
271        name: "fog_params",
272        reader: UniformsReader::ColourOnly,
273        perturb: |block| block.fog_params = [65_536.0, -2.5, 0.333, -1.0e-9],
274    },
275    UniformsField {
276        name: "fog_color",
277        reader: UniformsReader::ColourOnly,
278        perturb: |block| block.fog_color = [-4.0, 1.0e5, 0.125, -77.0],
279    },
280    UniformsField {
281        name: "sky_sh_r",
282        reader: UniformsReader::ColourOnly,
283        perturb: |block| block.sky_sh_r = [11.5, -22.5, 33.5, -44.5],
284    },
285    UniformsField {
286        name: "sky_sh_g",
287        reader: UniformsReader::ColourOnly,
288        perturb: |block| block.sky_sh_g = [-55.25, 66.25, -77.25, 88.25],
289    },
290    UniformsField {
291        name: "sky_sh_b",
292        reader: UniformsReader::ColourOnly,
293        perturb: |block| block.sky_sh_b = [99.0, -110.0, 121.0, -132.0],
294    },
295    UniformsField {
296        name: "previous_view_proj",
297        reader: UniformsReader::DepthPass,
298        perturb: |block| block.previous_view_proj[14] += 0.0625,
299    },
300    UniformsField {
301        name: "vertex_pool",
302        reader: UniformsReader::DepthPass,
303        perturb: |block| block.vertex_pool[0] ^= 0x40,
304    },
305    UniformsField {
306        name: "shadow_atlas_rect",
307        reader: UniformsReader::ColourOnly,
308        perturb: |block| {
309            block.shadow_atlas_rect = [[-3.5, 9.25, 1000.0, -0.125]; mesh::SHADOW_ATLAS_TILES]
310        },
311    },
312    UniformsField {
313        name: "shadow_filter",
314        reader: UniformsReader::ColourOnly,
315        perturb: |block| block.shadow_filter = [0xFFFF_FFFF, 0xDEAD_BEEF, 77, 0x8000_0000],
316    },
317];
318
319/// Moves `writes[group]` for every group whose cull any of `moved`'s
320/// footprints, before or after its write, could have been kept by.
321///
322/// Against **this frame's** frustum, and that is enough: a group's record
323/// carries its frustum too, so a group whose frustum moved since its maps were
324/// drawn already differs from them whatever this says. A group that culls
325/// nothing this frame — a free light slot, or every group on a frame with
326/// shadows off — is moved by any write, which costs nothing it had not already
327/// lost.
328///
329/// A function of the three rather than a method, because the frame that calls
330/// it is holding a closure over another of the renderer's fields.
331pub(super) fn shadow_groups_reached(
332    writes: &mut [u64],
333    moved: &[(CasterFootprint, CasterFootprint)],
334    culls: &[(usize, Frustum)],
335) {
336    for (group, count) in writes.iter_mut().enumerate() {
337        let frustum = culls
338            .iter()
339            .find(|(owner, _)| *owner == group)
340            .map(|(_, frustum)| frustum);
341        let reached = moved.iter().any(|(before, after)| {
342            frustum.is_none_or(|frustum| before.reaches(frustum) || after.reaches(frustum))
343        });
344        if reached {
345            *count = count.wrapping_add(1);
346        }
347    }
348}
349
350impl ForwardRenderer {
351    /// Takes the instance elements written since the last frame, and leaves in
352    /// [`ForwardRenderer::shadow_moved`] each one's footprint **before and
353    /// after** the write, for [`shadow_groups_reached`] to test against the
354    /// frame's culls once they are fitted.
355    ///
356    /// Before matters as much as after: a caster that walked out of a light's
357    /// cone leaves a shadow in the held map, and a caster removed from the scene
358    /// has a dead record now and a live one then. The before is the footprint
359    /// this kept in [`ForwardRenderer::shadow_footprints`] when it last ran,
360    /// and the after is the one the element's record gives now.
361    ///
362    /// It also keeps [`ForwardRenderer::shadow_dag_elements`] — the live
363    /// elements whose mesh has a DAG, whose cut the selection eye decides —
364    /// current.
365    pub(super) fn note_caster_writes(&mut self) {
366        let mut written = std::mem::take(&mut self.shadow_written);
367        written.clear();
368        self.shadow_moved.clear();
369        self.instances.take_written(&mut written);
370        if !written.is_empty() {
371            let meshes = self.pool.table_entries();
372            for &element in &written {
373                let index = element as usize;
374                if self.shadow_footprints.len() <= index {
375                    self.shadow_footprints
376                        .resize(index + 1, CasterFootprint::Nowhere);
377                }
378                let before = self.shadow_footprints[index];
379                let record = self.instances.record(element);
380                let after = record.map_or(CasterFootprint::Nowhere, |record| {
381                    CasterFootprint::of(&record, &meshes)
382                });
383                self.shadow_footprints[index] = after;
384                self.shadow_moved.push((before, after));
385                let selects_by_eye = record.is_some_and(|record| {
386                    record.flags & GpuInstance::LIVE != 0 && self.mesh_selects_by_eye(record.mesh)
387                });
388                if selects_by_eye {
389                    self.shadow_dag_elements.insert(element);
390                } else {
391                    self.shadow_dag_elements.remove(&element);
392                }
393            }
394        }
395        self.shadow_written = written;
396    }
397
398    /// Whether an instance naming mesh `mesh` has its level chosen from the
399    /// selection eye: a mesh with a DAG, whose groups `draw_gen.slang`'s
400    /// `select_level` projects from the eye. An id past the table is taken as
401    /// one that does.
402    fn mesh_selects_by_eye(&self, mesh: u32) -> bool {
403        self.draw_tables
404            .mesh_levels
405            .get(mesh as usize)
406            .is_none_or(|levels| levels.group_count > 0)
407    }
408
409    /// Everything one group of the shadow atlas is a function of, as bytes to
410    /// compare with the reading the image was last drawn from.
411    ///
412    /// A **group** is a cascade or a light slot's whole run of tiles — what one
413    /// cull covers and what [`crate::shadow::Cadence`] schedules. Per group rather than
414    /// per atlas since the cadence rung: a lamp that swings makes its own group's
415    /// reading differ and leaves every other group's alone, which is what lets
416    /// the frame redraw its tiles and hold the rest.
417    ///
418    /// # What is in it
419    ///
420    /// * **The group's view blocks, as the depth pass reads them, and its cull's
421    ///   frustum** — the values [`begin_frame_body`](Self::begin_frame_body) is
422    ///   about to write, cut down by [`depth_pass_reads`]. They carry the
423    ///   cascade's or the light's matrices, the light's position and this
424    ///   frame's shadow LOD budgets — so a light that moved, turned, changed
425    ///   radius or angle, or gained or lost a tile is a different reading, and so
426    ///   is a camera that moved *for a cascade*, because a cascade is fitted to
427    ///   it. The atlas rectangles are not in the blocks the depth pass reads;
428    ///   where a map lands is the layout, which is compared on its own and
429    ///   redraws everything when it moves.
430    /// * **The instance count**, which reaches the cull beside the frustum and is
431    ///   in no block.
432    /// * **The selection eye, where the group's cull reads it.** `draw_gen.slang`
433    ///   chooses a DAG mesh's level by projecting its groups' error from the eye,
434    ///   so the eye is an input to every group a DAG instance could be kept by:
435    ///   always for a cascade, and for a light slot when any live DAG element's
436    ///   footprint reaches its frustum. A light whose frustum holds flat meshes
437    ///   alone draws the same maps from any eye, and leaving the eye out is what
438    ///   lets it hold them while the camera moves. Not quantised: any move of the
439    ///   eye can move a group across its budget, and a quantum is a range of eyes
440    ///   over which a held map is a cut the cull would not have chosen.
441    /// * **[`ForwardRenderer::shadow_group_writes`]**, which moves for every
442    ///   instance write whose element's footprint, before or after it, reaches
443    ///   this group's frustum — see [`note_caster_writes`](Self::note_caster_writes) and
444    ///   [`shadow_groups_reached`].
445    ///   A transform, a mesh, a material, a removal or a skinned re-point all
446    ///   pass through [`crate::InstancePool::take_written`], and a write whose
447    ///   element could be kept by this group's cull neither before nor after it
448    ///   draws nothing into this group's maps either way.
449    ///
450    /// The bytes are the blocks' own `to_bytes` — the encoding the GPU reads —
451    /// rather than the objects' memory, so no padding and no `f32` bit pattern
452    /// nobody wrote is in the comparison. Two readings that differ by `-0.0`
453    /// against `0.0` compare unequal and redraw, which is the safe direction.
454    ///
455    /// A skinned frame is **not** in here and is not meant to be: a record that
456    /// merely carried "this frame skins" would still match the last skinned
457    /// frame's and cache. What carries a pose instead is the writes count above:
458    /// [`ForwardRenderer::point_skinned_instances`] writes every skinned object
459    /// on every skinned frame, so its box — or, without one, every group —
460    /// redraws each frame it is skinned.
461    ///
462    /// # What is deliberately not in it
463    ///
464    /// * **The mesh pool.** Its buffers are written by `build_geometry` and
465    ///   `residents` alone, both of which run inside
466    ///   [`with_scene`](Self::with_scene) before a renderer exists — this type
467    ///   exposes no way to upload or free a mesh afterwards. The one runtime
468    ///   caller of the suballocator is
469    ///   [`reserve_skinned`](Self::reserve_skinned), whose bytes are a skinned
470    ///   region's, and those are written only by a skinning dispatch, which
471    ///   reaches the record through the re-point writes above.
472    /// * **Whether the frame has shadows at all**, which is the atlas's *layout*
473    ///   rather than any group's reading: a frame with shadows off gives every
474    ///   group no views and no cull, so none of them reaches this function, and
475    ///   `begin_frame_body`'s empty layout is what makes such a frame clear the
476    ///   image once and cost nothing after.
477    /// * **Materials, samplers and the colour pipeline.** `depth_pipeline`
478    ///   names no fragment stage, so nothing the atlas holds is a function of
479    ///   them.
480    pub(super) fn shadow_group_record(
481        &self,
482        group: usize,
483        views: &[(usize, usize, mesh::FrameUniforms)],
484        culls: &[(usize, Frustum)],
485        eye: [f32; 3],
486        instance_count: u32,
487    ) -> Vec<u8> {
488        let view_count = views.iter().filter(|(owner, _, _)| *owner == group).count();
489        let cull_count = culls.iter().filter(|(owner, _)| *owner == group).count();
490        let reads_eye = group < shadow::CASCADES
491            || culls
492                .iter()
493                .find(|(owner, _)| *owner == group)
494                .is_none_or(|(_, frustum)| {
495                    self.shadow_dag_elements
496                        .iter()
497                        .any(|element| self.shadow_footprints[*element as usize].reaches(frustum))
498                });
499        let capacity = size_of::<u64>()
500            + size_of::<u32>()
501            + size_of::<u8>()
502            + if reads_eye { size_of::<[f32; 3]>() } else { 0 }
503            + view_count * (size_of::<u32>() + mesh::FRAME_UNIFORMS_SIZE)
504            + cull_count * (size_of::<u32>() + crate::cull::PLANE_COUNT * size_of::<[f32; 4]>());
505        let mut record = Vec::with_capacity(capacity);
506        record.extend_from_slice(&self.shadow_group_writes[group].to_le_bytes());
507        record.extend_from_slice(&instance_count.to_le_bytes());
508        record.push(u8::from(reads_eye));
509        if reads_eye {
510            for value in eye {
511                record.extend_from_slice(&value.to_le_bytes());
512            }
513        }
514        for (_, view, block) in views.iter().filter(|(owner, _, _)| *owner == group) {
515            record.extend_from_slice(&(*view as u32).to_le_bytes());
516            record.extend_from_slice(&depth_pass_reads(block).to_bytes());
517        }
518        for (cull, frustum) in culls.iter().filter(|(cull, _)| *cull == group) {
519            record.extend_from_slice(&(*cull as u32).to_le_bytes());
520            for plane in frustum.planes {
521                for value in plane.to_array() {
522                    record.extend_from_slice(&value.to_le_bytes());
523                }
524            }
525        }
526        record
527    }
528}
529
530// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
531#[cfg(all(test, not(target_arch = "wasm32")))]
532mod tests {
533    use super::super::SHADOW_CULLS;
534    use super::*;
535    use crate::scene;
536    use crcbl_hal::null::{NullInstance, Recorder};
537    use crcbl_hal::{AdapterId, DeviceDesc, Format, Instance, QueueKind};
538    use glam::{Vec3, Vec4};
539
540    /// A light group's index: the first light slot, past the cascades.
541    const LIGHT: usize = shadow::CASCADES;
542
543    /// A block whose every field holds something, so a field the record
544    /// dropped and a field it kept are told apart by changing it.
545    fn filled_block(id: usize, owner: usize) -> mesh::FrameUniforms {
546        let matrix = Mat4::from_scale(Vec3::splat(id as f32 + 1.0)).to_cols_array();
547        mesh::FrameUniforms {
548            view_proj: matrix,
549            camera_position: [0.0, 0.0, 2.0, 1.0],
550            ambient: [id as f32, -0.0, owner as f32, 1.0],
551            shadow_view_proj: [Mat4::IDENTITY.to_cols_array(); mesh::SHADOW_CASCADES],
552            cascade_far: [1.0, 2.0, 3.0, 4.0],
553            shadow_params: [0.5, 0.25, 0.0, 0.0],
554            cluster_grid: [1, 2, 3, 0],
555            light_view_proj: [Mat4::IDENTITY.to_cols_array(); mesh::SHADOW_LIGHT_TILES],
556            probes: crcbl_shaders::probe::ProbeVolume::default(),
557            lod_params: [3.0, 4.0, 5.0, 0.0],
558            fog_params: [0.1; 4],
559            fog_color: [0.2; 4],
560            sky_sh_r: [0.3; 4],
561            sky_sh_g: [0.4; 4],
562            sky_sh_b: [0.5; 4],
563            previous_view_proj: matrix,
564            vertex_pool: [11, 12, 13, 14],
565            shadow_atlas_rect: [[0.75; 4]; mesh::SHADOW_ATLAS_TILES],
566            shadow_filter: [1, 2, 3, 4],
567        }
568    }
569
570    #[test]
571    fn group_records_preserve_complete_bytes_and_selected_input_order() {
572        let recorder = Recorder::new();
573        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
574        let device = instance
575            .create_device(&DeviceDesc::for_adapter(AdapterId(0)))
576            .unwrap();
577        let queue = device.queue(QueueKind::Graphics).unwrap();
578        let mut renderer = ForwardRenderer::with_scene(
579            device.as_ref(),
580            queue,
581            Format::Rgba8UnormSrgb,
582            &scene::demo(),
583        )
584        .unwrap();
585        let mut views: Vec<_> = [
586            (LIGHT, 9),
587            (0, 3),
588            (LIGHT, 7),
589            (1, 4),
590            (LIGHT, 1),
591            (LIGHT, 8),
592            (LIGHT, 5),
593            (LIGHT, 6),
594        ]
595        .into_iter()
596        .map(|(owner, id)| (owner, id, filled_block(id, owner)))
597        .collect();
598        let mut culls: Vec<_> = [LIGHT, 0, 1, LIGHT]
599            .into_iter()
600            .map(|owner| {
601                (
602                    owner,
603                    Frustum {
604                        planes: std::array::from_fn(|i| {
605                            Vec4::new(owner as f32, i as f32, -0.0, 1.0)
606                        }),
607                    },
608                )
609            })
610            .collect();
611        let eye = [-0.0, 7.0, -9.0];
612        let count = u32::MAX;
613        renderer.shadow_group_writes = (0..SHADOW_CULLS as u64).map(|n| 40 + n).collect();
614        let expected = |writes: u64,
615                        with_eye: bool,
616                        group: usize,
617                        views: &[(usize, usize, mesh::FrameUniforms)],
618                        culls: &[(usize, Frustum)]| {
619            let mut bytes = Vec::new();
620            bytes.extend(writes.to_le_bytes());
621            bytes.extend(count.to_le_bytes());
622            bytes.push(u8::from(with_eye));
623            if with_eye {
624                bytes.extend(eye.into_iter().flat_map(f32::to_le_bytes));
625            }
626            for (owner, id, block) in views {
627                if *owner == group {
628                    bytes.extend((*id as u32).to_le_bytes());
629                    bytes.extend(depth_pass_reads(block).to_bytes());
630                }
631            }
632            for (owner, frustum) in culls {
633                if *owner == group {
634                    bytes.extend((*owner as u32).to_le_bytes());
635                    bytes.extend(
636                        frustum
637                            .planes
638                            .iter()
639                            .flat_map(|v| v.to_array())
640                            .flat_map(f32::to_le_bytes),
641                    );
642                }
643            }
644            bytes
645        };
646        for group in 0..SHADOW_CULLS {
647            let record = renderer.shadow_group_record(group, &views, &culls, eye, count);
648            // A cascade reads the eye always; a light slot culled against a
649            // frustum no DAG element reaches does not, and one that culls
650            // nothing this frame is taken to.
651            let with_eye = group < shadow::CASCADES || group > LIGHT;
652            assert_eq!(
653                record,
654                expected(40 + group as u64, with_eye, group, &views, &culls),
655                "group {group}"
656            );
657            assert_eq!(record.capacity(), record.len());
658        }
659
660        let original = renderer.shadow_group_record(LIGHT, &views, &culls, eye, count);
661        let cascade = renderer.shadow_group_record(0, &views, &culls, eye, count);
662        // The eye: a cascade's input, and not a flat-only light's.
663        assert_ne!(
664            cascade,
665            renderer.shadow_group_record(0, &views, &culls, [0.0, 7.0, -9.0], count)
666        );
667        assert_eq!(
668            original,
669            renderer.shadow_group_record(LIGHT, &views, &culls, [5.0, 7.0, -9.0], count),
670            "a light whose cull no DAG element reaches drew the same maps from any eye"
671        );
672        assert_ne!(
673            original,
674            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count - 1)
675        );
676
677        // Another group's blocks and culls are not this one's.
678        views[1].2.ambient[3] += 1.0;
679        culls[1].1.planes[0].x += 1.0;
680        assert_eq!(
681            original,
682            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
683        );
684
685        // Every field the depth pass reads is in the record, and none of the
686        // colour pass's is — which is what lets a light hold its maps while the
687        // camera, which several of them follow, moves.
688        for field in FRAME_UNIFORMS_READERS {
689            let saved = views[0].2;
690            (field.perturb)(&mut views[0].2);
691            let record = renderer.shadow_group_record(LIGHT, &views, &culls, eye, count);
692            match field.reader {
693                UniformsReader::DepthPass => assert_ne!(
694                    original, record,
695                    "the depth pass reads `{}` and the record did not change with it",
696                    field.name
697                ),
698                UniformsReader::ColourOnly => assert_eq!(
699                    original, record,
700                    "the depth pass reads nothing of `{}` and the record moved with it",
701                    field.name
702                ),
703            }
704            views[0].2 = saved;
705        }
706        // And every colour-only field at once.
707        let saved = views[0].2;
708        for field in FRAME_UNIFORMS_READERS {
709            if field.reader == UniformsReader::ColourOnly {
710                (field.perturb)(&mut views[0].2);
711            }
712        }
713        assert_eq!(
714            original,
715            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count),
716            "every colour-only field moved at once, and the record moved with them"
717        );
718        views[0].2 = saved;
719
720        views[0].1 += 1;
721        assert_ne!(
722            original,
723            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
724        );
725        views[0].1 -= 1;
726        culls[0].1.planes[0].z = 0.0;
727        assert_ne!(
728            original,
729            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
730        );
731        culls[0].1.planes[0].z = -0.0;
732        views.swap(0, 2);
733        assert_ne!(
734            original,
735            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
736        );
737        views.swap(0, 2);
738
739        // A write this group's cull could see.
740        renderer.shadow_group_writes[LIGHT] += 1;
741        let changed = renderer.shadow_group_record(LIGHT, &views, &culls, eye, count);
742        assert_ne!(original, changed);
743        assert_eq!(&original[size_of::<u64>()..], &changed[size_of::<u64>()..]);
744        renderer.shadow_group_writes[LIGHT] -= 1;
745
746        // A DAG element whose footprint reaches the light's frustum puts the
747        // eye into the light's record; one outside it does not.
748        let frustum = Frustum::from_view_projection(glam::camera::rh::proj::directx::orthographic(
749            -1.0, 1.0, -1.0, 1.0, 0.0, 10.0,
750        ));
751        culls[0].1 = frustum;
752        culls[3].1 = frustum;
753        let light = |renderer: &ForwardRenderer, eye| {
754            renderer.shadow_group_record(LIGHT, &views, &culls, eye, count)
755        };
756        let far_away = CasterFootprint::Within(Aabb {
757            min: Vec3::splat(100.0),
758            max: Vec3::splat(101.0),
759        });
760        renderer.shadow_footprints = vec![far_away];
761        renderer.shadow_dag_elements.insert(0);
762        assert_eq!(
763            light(&renderer, eye),
764            light(&renderer, [5.0, 7.0, -9.0]),
765            "a DAG element no cull of this light can keep chose no level in its maps"
766        );
767        renderer.shadow_footprints[0] = CasterFootprint::Within(Aabb {
768            min: Vec3::new(-0.5, -0.5, -5.0),
769            max: Vec3::new(0.5, 0.5, -4.0),
770        });
771        assert_ne!(
772            light(&renderer, eye),
773            light(&renderer, [5.0, 7.0, -9.0]),
774            "a DAG element inside the light's frustum has its level chosen from the eye"
775        );
776
777        renderer.destroy(device.as_ref());
778        recorder.assert_valid();
779        assert_eq!(recorder.total_live_objects(), 0);
780    }
781
782    /// Each of a block's fields, or a split field's lanes, by the name
783    /// [`FRAME_UNIFORMS_READERS`] gives it, with its value spelled out.
784    ///
785    /// **Exhaustive on purpose**: the destructure names every field and has no
786    /// `..`, so a field added to [`mesh::FrameUniforms`] stops this compiling
787    /// until it is listed here — and then
788    /// [`every_frame_uniforms_field_is_classified_and_depth_pass_reads_agrees`]
789    /// fails until the table classifies it.
790    fn lanes(block: &mesh::FrameUniforms) -> Vec<(&'static str, String)> {
791        let mesh::FrameUniforms {
792            view_proj,
793            camera_position,
794            ambient,
795            shadow_view_proj,
796            cascade_far,
797            shadow_params,
798            cluster_grid,
799            light_view_proj,
800            probes,
801            lod_params,
802            fog_params,
803            fog_color,
804            sky_sh_r,
805            sky_sh_g,
806            sky_sh_b,
807            previous_view_proj,
808            vertex_pool,
809            shadow_atlas_rect,
810            shadow_filter,
811        } = block;
812        // `Debug` rather than `==`, so a NaN lane equals itself and `-0.0` is
813        // not `0.0`: the question is whether the bits a shader reads moved.
814        vec![
815            ("view_proj", format!("{view_proj:?}")),
816            ("camera_position", format!("{camera_position:?}")),
817            ("ambient.xyz", format!("{:?}", &ambient[..3])),
818            ("ambient.w", format!("{:?}", ambient[3])),
819            ("shadow_view_proj", format!("{shadow_view_proj:?}")),
820            ("cascade_far", format!("{cascade_far:?}")),
821            ("shadow_params", format!("{shadow_params:?}")),
822            ("cluster_grid", format!("{cluster_grid:?}")),
823            ("light_view_proj", format!("{light_view_proj:?}")),
824            ("probes", format!("{probes:?}")),
825            ("lod_params", format!("{lod_params:?}")),
826            ("fog_params", format!("{fog_params:?}")),
827            ("fog_color", format!("{fog_color:?}")),
828            ("sky_sh_r", format!("{sky_sh_r:?}")),
829            ("sky_sh_g", format!("{sky_sh_g:?}")),
830            ("sky_sh_b", format!("{sky_sh_b:?}")),
831            ("previous_view_proj", format!("{previous_view_proj:?}")),
832            ("vertex_pool", format!("{vertex_pool:?}")),
833            ("shadow_atlas_rect", format!("{shadow_atlas_rect:?}")),
834            ("shadow_filter", format!("{shadow_filter:?}")),
835        ]
836    }
837
838    /// **[`FRAME_UNIFORMS_READERS`] classifies every lane of a block exactly
839    /// once, each entry perturbs its own lanes and no others, and
840    /// [`depth_pass_reads`] keeps exactly the depth-read ones.**
841    ///
842    /// The table is what `crcbl`'s `mesh_e2e` `shadow_block_reads` holds to the
843    /// shaders on a device, so this is the half that ties the function the
844    /// record is built from to what that test checked.
845    #[test]
846    fn every_frame_uniforms_field_is_classified_and_depth_pass_reads_agrees() {
847        let block = filled_block(3, LIGHT);
848        let before = lanes(&block);
849        let names: Vec<&str> = before.iter().map(|(name, _)| *name).collect();
850        let mut listed: Vec<&str> = FRAME_UNIFORMS_READERS
851            .iter()
852            .map(|field| field.name)
853            .collect();
854        listed.sort_unstable();
855        let mut expected = names.clone();
856        expected.sort_unstable();
857        assert_eq!(
858            listed, expected,
859            "the table must name every lane group of `FrameUniforms` exactly once"
860        );
861
862        let kept_before = lanes(&depth_pass_reads(&block));
863        for field in FRAME_UNIFORMS_READERS {
864            let mut perturbed = block;
865            (field.perturb)(&mut perturbed);
866            let after = lanes(&perturbed);
867            for ((name, was), (_, is)) in before.iter().zip(&after) {
868                if *name == field.name {
869                    assert_ne!(was, is, "`{name}`'s perturbation left it as it was");
870                } else {
871                    assert_eq!(
872                        was, is,
873                        "`{}`'s perturbation also moved `{name}`, so the device test would \
874                         blame the wrong field",
875                        field.name
876                    );
877                }
878            }
879
880            let kept_after = lanes(&depth_pass_reads(&perturbed));
881            let lane = |of: &[(&str, String)]| {
882                of.iter()
883                    .find(|(name, _)| *name == field.name)
884                    .map(|(_, value)| value.clone())
885                    .expect("every table name is a lane")
886            };
887            match field.reader {
888                UniformsReader::DepthPass => assert_eq!(
889                    lane(&kept_after),
890                    lane(&after),
891                    "`{}` is read by the depth pass and `depth_pass_reads` does not keep it",
892                    field.name
893                ),
894                UniformsReader::ColourOnly => assert_eq!(
895                    kept_before, kept_after,
896                    "`{}` is the colour pass's alone and `depth_pass_reads` keeps it",
897                    field.name
898                ),
899            }
900        }
901    }
902
903    /// A footprint is the cull's own question: dead is nowhere, skinned without
904    /// a box of its own is everywhere, skinned with one is that box, and a live
905    /// rigid instance is its mesh's box carried by its transform, never
906    /// smaller.
907    #[test]
908    fn a_footprint_is_the_cull_s_box_and_never_smaller() {
909        let cube = GpuMesh {
910            index_count: 36,
911            bounds_min: [-0.5; 3],
912            bounds_max: [0.5; 3],
913            ..GpuMesh::default()
914        };
915        let meshes = [cube, GpuMesh::default()];
916        let at = |x: f32| GpuInstance {
917            transform: Mat4::from_translation(Vec3::new(x, 0.0, 0.0)).to_cols_array(),
918            flags: GpuInstance::LIVE,
919            ..GpuInstance::default()
920        };
921        let CasterFootprint::Within(bounds) = CasterFootprint::of(&at(10.0), &meshes) else {
922            panic!("a live rigid instance of a real mesh has a box");
923        };
924        assert!(bounds.min.x < 9.5 && bounds.max.x > 10.5);
925        assert!(bounds.max.x < 10.6, "the slack is slack, not a second box");
926
927        let dead = GpuInstance {
928            flags: 0,
929            ..at(0.0)
930        };
931        assert_eq!(
932            CasterFootprint::of(&dead, &meshes),
933            CasterFootprint::Nowhere
934        );
935        let skinned = GpuInstance {
936            flags: GpuInstance::LIVE | GpuInstance::BASE_VERTEX_OVERRIDE,
937            ..at(0.0)
938        };
939        assert_eq!(
940            CasterFootprint::of(&skinned, &meshes),
941            CasterFootprint::Everywhere
942        );
943        // A skinned instance that carries a box of its own is that box — not
944        // its mesh's, which sits at the origin here — carried by its transform.
945        let bounded = GpuInstance {
946            flags: skinned.flags | GpuInstance::OWNS_BOUNDS,
947            bounds_min: [-1.0, 0.0, -1.0],
948            bounds_max: [1.0, 2.0, 1.0],
949            ..at(20.0)
950        };
951        let CasterFootprint::Within(bounds) = CasterFootprint::of(&bounded, &meshes) else {
952            panic!("a skinned instance with its own box has a footprint");
953        };
954        assert!(bounds.min.x < 19.0 && bounds.max.x > 21.0);
955        assert!(bounds.min.y < 0.0 && bounds.max.y > 2.0);
956        assert!(
957            bounds.max.y < 2.1 && bounds.min.x > 18.9,
958            "the footprint is the instance's own box, not a wider one"
959        );
960        for mesh in [1, 7] {
961            let unnamed = GpuInstance { mesh, ..at(0.0) };
962            assert_eq!(
963                CasterFootprint::of(&unnamed, &meshes),
964                CasterFootprint::Everywhere,
965                "mesh {mesh}"
966            );
967        }
968        let nan = GpuInstance {
969            transform: [f32::NAN; 16],
970            ..at(0.0)
971        };
972        assert_eq!(
973            CasterFootprint::of(&nan, &meshes),
974            CasterFootprint::Everywhere,
975            "a box of NaN would read as outside every frustum"
976        );
977    }
978
979    /// **A write reaches a group when its element could be kept by the group's
980    /// cull before the write or after it**, and a group culling nothing this
981    /// frame is reached by any write.
982    #[test]
983    fn a_write_reaches_the_groups_its_old_or_new_box_is_in() {
984        // A box one unit across either side of the origin, looking down -z.
985        let frustum = Frustum::from_view_projection(glam::camera::rh::proj::directx::orthographic(
986            -1.0, 1.0, -1.0, 1.0, 0.0, 10.0,
987        ));
988        let inside = CasterFootprint::Within(Aabb {
989            min: Vec3::new(-0.25, -0.25, -3.0),
990            max: Vec3::new(0.25, 0.25, -2.0),
991        });
992        let outside = CasterFootprint::Within(Aabb {
993            min: Vec3::new(5.0, 5.0, -3.0),
994            max: Vec3::new(6.0, 6.0, -2.0),
995        });
996        assert!(inside.reaches(&frustum) && !outside.reaches(&frustum));
997        let reached = |moved: &[(CasterFootprint, CasterFootprint)]| {
998            let mut writes = [0u64; 2];
999            // Group 0 culls against the box; group 1 culls nothing.
1000            shadow_groups_reached(&mut writes, moved, &[(0, frustum)]);
1001            writes
1002        };
1003        assert_eq!(reached(&[]), [0, 0], "no write reaches nothing");
1004        assert_eq!(reached(&[(inside, inside)]), [1, 1], "moved inside");
1005        assert_eq!(reached(&[(outside, outside)]), [0, 1], "moved outside");
1006        assert_eq!(reached(&[(inside, outside)]), [1, 1], "moved out of it");
1007        assert_eq!(reached(&[(outside, inside)]), [1, 1], "moved into it");
1008        assert_eq!(
1009            reached(&[(CasterFootprint::Nowhere, inside)]),
1010            [1, 1],
1011            "spawned inside"
1012        );
1013        assert_eq!(
1014            reached(&[(inside, CasterFootprint::Nowhere)]),
1015            [1, 1],
1016            "removed from inside"
1017        );
1018        assert_eq!(
1019            reached(&[
1020                (outside, outside),
1021                (CasterFootprint::Nowhere, CasterFootprint::Everywhere)
1022            ]),
1023            [1, 1],
1024            "a skinned element reaches every group"
1025        );
1026    }
1027}