Skip to main content

crcbl_render/cull/
occlusion.rs

1//! The occlusion, small-feature and point-light face tests: the reference
2//! implementation `cull.slang`'s `occlusionMain`, `lateMain` and face tags are
3//! checked against.
4//!
5//! ```text
6//!  depth prepass ──▶ DepthPyramid::reduce(Farthest) ──▶ levels 1..n
7//!                                                            │
8//!  instance box ──▶ project_box(view_proj) ──▶ ScreenBounds ─┴─▶ occluded
9//! ```
10//!
11//! Topic 03 §3.3's two-phase cull, on
12//! [`crate::cull`]'s terms: ordinary Rust, called by nothing in a frame, and
13//! there so a test can state the answer the GPU has to reach. Every function
14//! here is the shader's arithmetic in the shader's order, so a readback that
15//! disagrees is a bug in one of the two rather than a rounding difference —
16//! except at an exact boundary, where the four shader targets' own float
17//! contractions may land either side and a test places nothing.
18//!
19//! # The pyramid holds the farthest depth, not the nearest
20//!
21//! `shaders/hiz.slang`'s reflection pyramid keeps the **nearest** surface of each
22//! block, which is what a ray march skipping empty space needs. A cull needs the
23//! other bound: a box is hidden only if it is behind *every* surface drawn over
24//! the pixels it covers, and the farthest of those is the one to compare with.
25//! Under reversed-Z nearer is larger, so the farthest is a `min` and the far
26//! plane's `0.0` wins — one uncovered pixel in a block hides nothing behind it.
27//! [`Reduction`] names both so a test can show the nearest one hiding what is
28//! on screen.
29//!
30//! # Only the second phase has to be right
31//!
32//! The first phase tests against the **previous** frame's pyramid through the
33//! previous frame's matrix, and whatever it gets wrong — a disocclusion, a
34//! moved occluder, a camera cut — only decides what is drawn early. Everything
35//! it marks is tested again against this frame's early depth, which holds a
36//! subset of what the frame will hold, so a box hidden there is hidden in the
37//! finished frame. That second test is the one the pixel-identity contract
38//! rests on, and it is [`occluded`] here exactly as it is for the first.
39
40use crcbl_shaders::cull::{
41    ENTRY_FACE_SHIFT, ENTRY_OCCLUDED, ENTRY_RESCUED, FACE_COUNT, FACE_PLANES,
42    OCCLUSION_DEPTH_SLACK, OCCLUSION_GUARD_TEXELS, PROJECTION_LIMIT,
43};
44use crcbl_shaders::mesh::{GpuInstance, GpuMesh};
45use glam::{Mat3, Mat4, Vec3, Vec4};
46
47use super::Frustum;
48use crate::occlusion_cull::{level_extent, levels_for};
49
50/// Which bound of a block a [`DepthPyramid`] level keeps.
51#[derive(Clone, Copy, Debug, PartialEq, Eq)]
52pub enum Reduction {
53    /// The farthest surface — `hiz.slang`'s `farthestMain`, and the only one an
54    /// occlusion test may read.
55    Farthest,
56    /// The nearest surface — `hiz.slang`'s `fragmentMain`, the reflection
57    /// march's.
58    Nearest,
59}
60
61/// A depth pyramid on the CPU: levels `1..=levels_for(extent)` of a reversed-Z
62/// depth image, each reduced from the level above exactly as `hiz.slang` does.
63#[derive(Clone, Debug, PartialEq)]
64pub struct DepthPyramid {
65    extent: (u32, u32),
66    /// `levels[n - 1]` is level `n`, row-major.
67    levels: Vec<Vec<f32>>,
68}
69
70impl DepthPyramid {
71    /// Reduces `depth` — `extent.0 * extent.1` texels, row-major, top row first
72    /// — into every level [`levels_for`] allows.
73    ///
74    /// **`hiz.slang`'s reduction, tap for tap**: the destination texel's 2×2
75    /// block of the level above, clamped to its extent, and a third tap along an
76    /// odd axis so the last texel covers the row or column the halving floored
77    /// past.
78    ///
79    /// # Panics
80    ///
81    /// If `depth` is not `extent.0 * extent.1` long.
82    #[must_use]
83    pub fn reduce(depth: &[f32], extent: (u32, u32), reduction: Reduction) -> Self {
84        assert_eq!(
85            depth.len(),
86            extent.0 as usize * extent.1 as usize,
87            "a depth image of {extent:?} holds that many texels"
88        );
89        let combine = |a: f32, b: f32| match reduction {
90            Reduction::Farthest => a.min(b),
91            Reduction::Nearest => a.max(b),
92        };
93        let mut levels: Vec<Vec<f32>> = Vec::new();
94        for level in 1..=levels_for(extent) {
95            let (source_width, source_height) = level_extent(extent, level - 1);
96            let (width, height) = level_extent(extent, level);
97            let source: &[f32] = levels.last().map_or(depth, Vec::as_slice);
98            let load = |x: i64, y: i64| {
99                let x = x.clamp(0, i64::from(source_width) - 1) as usize;
100                let y = y.clamp(0, i64::from(source_height) - 1) as usize;
101                source[y * source_width as usize + x]
102            };
103            let odd_x = source_width & 1 == 1;
104            let odd_y = source_height & 1 == 1;
105            let mut out = Vec::with_capacity(width as usize * height as usize);
106            for y in 0..i64::from(height) {
107                for x in 0..i64::from(width) {
108                    let (bx, by) = (x * 2, y * 2);
109                    let mut value = load(bx, by);
110                    value = combine(value, load(bx + 1, by));
111                    value = combine(value, load(bx, by + 1));
112                    value = combine(value, load(bx + 1, by + 1));
113                    if odd_x {
114                        value = combine(value, load(bx + 2, by));
115                        value = combine(value, load(bx + 2, by + 1));
116                    }
117                    if odd_y {
118                        value = combine(value, load(bx, by + 2));
119                        value = combine(value, load(bx + 1, by + 2));
120                    }
121                    if odd_x && odd_y {
122                        value = combine(value, load(bx + 2, by + 2));
123                    }
124                    out.push(value);
125                }
126            }
127            levels.push(out);
128        }
129        Self { extent, levels }
130    }
131
132    /// A pyramid out of levels already reduced — a GPU pyramid read back —
133    /// over a prepass of `extent`, level 1 first.
134    ///
135    /// # Panics
136    ///
137    /// If `levels` is not [`levels_for`]`(extent)` long, or a level is not its
138    /// [`level_extent`]'s texel count.
139    #[must_use]
140    pub fn from_levels(extent: (u32, u32), levels: Vec<Vec<f32>>) -> Self {
141        assert_eq!(levels.len(), levels_for(extent) as usize, "a whole chain");
142        for (index, level) in levels.iter().enumerate() {
143            let (width, height) = level_extent(extent, index as u32 + 1);
144            assert_eq!(
145                level.len(),
146                width as usize * height as usize,
147                "level {}",
148                index + 1
149            );
150        }
151        Self { extent, levels }
152    }
153
154    /// Reduces `source` — one level of `(width, height)` texels — into the level
155    /// below it, by [`reduce`](Self::reduce)'s taps: what a test holds each GPU
156    /// level against the one above it with.
157    #[must_use]
158    pub fn reduce_level(source: &[f32], extent: (u32, u32), reduction: Reduction) -> Vec<f32> {
159        let chain = Self::reduce(source, extent, reduction);
160        chain.levels.into_iter().next().unwrap_or_default()
161    }
162
163    /// The prepass extent this pyramid was reduced from — its level 0.
164    #[must_use]
165    pub const fn extent(&self) -> (u32, u32) {
166        self.extent
167    }
168
169    /// How many levels it has, which is [`levels_for`] of its extent.
170    #[must_use]
171    pub fn levels(&self) -> u32 {
172        u32::try_from(self.levels.len()).unwrap_or(u32::MAX)
173    }
174
175    /// Level `level`'s texels, row-major.
176    ///
177    /// # Panics
178    ///
179    /// If `level` is zero or past [`levels`](Self::levels).
180    #[must_use]
181    pub fn level(&self, level: u32) -> &[f32] {
182        assert!(
183            level >= 1 && level <= self.levels(),
184            "level {level} of a {}-level pyramid",
185            self.levels()
186        );
187        &self.levels[level as usize - 1]
188    }
189
190    /// Level `level` at an integer texel, which the caller has clamped.
191    fn load(&self, level: u32, x: u32, y: u32) -> f32 {
192        let width = level_extent(self.extent, level).0;
193        self.levels[level as usize - 1][y as usize * width as usize + x as usize]
194    }
195}
196
197/// An instance's box in world space: the centre and half-extent `cull.slang`'s
198/// `world_box` computes, by the same conservative transform as
199/// [`Aabb::transformed`](super::Aabb::transformed).
200#[must_use]
201pub fn world_box(instance: &GpuInstance, mesh: &GpuMesh) -> (Vec3, Vec3) {
202    let min = Vec3::from_array(mesh.bounds_min);
203    let max = Vec3::from_array(mesh.bounds_max);
204    let local_center = (max + min) * 0.5;
205    let local_extent = (max - min) * 0.5;
206    let transform = Mat4::from_cols_array(&instance.transform);
207    let basis = Mat3::from_mat4(transform);
208    let absolute = Mat3::from_cols(basis.x_axis.abs(), basis.y_axis.abs(), basis.z_axis.abs());
209    (
210        transform.transform_point3(local_center),
211        absolute * local_extent,
212    )
213}
214
215/// A box projected onto a target: the pixel rectangle its corners span, with
216/// `(0, 0)` at the top left, and the nearest reversed-Z depth any corner has.
217#[derive(Clone, Copy, Debug, PartialEq)]
218pub struct ScreenBounds {
219    /// The rectangle's top-left corner, in pixels.
220    pub min: [f32; 2],
221    /// Its bottom-right corner.
222    pub max: [f32; 2],
223    /// The largest depth of the eight corners — under reversed-Z, the nearest.
224    pub nearest: f32,
225}
226
227/// Projects the box `center ± extent` through `view_projection` onto a target
228/// of `target` pixels — `cull.slang`'s `project_box`.
229///
230/// `None` where the shader's box is invalid: a corner on or behind the eye
231/// plane, in front of the near plane, or [`PROJECTION_LIMIT`] pixels or more
232/// from the origin. Every caller reads that as "not hidden, not small".
233#[must_use]
234pub fn project_box(
235    view_projection: Mat4,
236    center: Vec3,
237    extent: Vec3,
238    target: (u32, u32),
239) -> Option<ScreenBounds> {
240    let (width, height) = (target.0 as f32, target.1 as f32);
241    let mut bounds = ScreenBounds {
242        min: [PROJECTION_LIMIT; 2],
243        max: [-PROJECTION_LIMIT; 2],
244        nearest: 0.0,
245    };
246    for corner in 0..8u32 {
247        let side = Vec3::new(
248            if corner & 1 != 0 { 1.0 } else { -1.0 },
249            if corner & 2 != 0 { 1.0 } else { -1.0 },
250            if corner & 4 != 0 { 1.0 } else { -1.0 },
251        );
252        let clip = view_projection * (center + side * extent).extend(1.0);
253        // Named rather than negated in place, and written so a `NaN` fails:
254        // every comparison with one is false, which makes the box invalid.
255        let in_front = clip.w > 0.0;
256        if !in_front {
257            return None;
258        }
259        let depth = clip.z / clip.w;
260        let x = (clip.x / clip.w * 0.5 + 0.5) * width;
261        let y = (0.5 - clip.y / clip.w * 0.5) * height;
262        let behind_near = depth <= 1.0;
263        let on_the_page = x.abs() < PROJECTION_LIMIT && y.abs() < PROJECTION_LIMIT;
264        if !behind_near || !on_the_page {
265            return None;
266        }
267        bounds.min = [bounds.min[0].min(x), bounds.min[1].min(y)];
268        bounds.max = [bounds.max[0].max(x), bounds.max[1].max(y)];
269        bounds.nearest = bounds.nearest.max(depth);
270    }
271    Some(bounds)
272}
273
274/// Where [`occluded`] reads the pyramid for a box, before it compares anything:
275/// the level and the inclusive texel range.
276///
277/// Public so a test can say *which* texels decided a verdict rather than only
278/// what the verdict was.
279#[derive(Clone, Copy, Debug, PartialEq, Eq)]
280pub struct PyramidFootprint {
281    /// The level read, from 1.
282    pub level: u32,
283    /// The first and last texel column read.
284    pub columns: (u32, u32),
285    /// The first and last texel row read.
286    pub rows: (u32, u32),
287}
288
289/// The texels `cull.slang`'s `occluded` reads for `bounds` on a pyramid of
290/// `levels` levels over `target` — `None` for a rectangle entirely off the
291/// target, which is never hidden.
292///
293/// The rectangle is widened by [`OCCLUSION_GUARD_TEXELS`] and clamped to the
294/// target; the level is the finest from 1 up at which it spans at most two
295/// texels on each axis, or the deepest one there is.
296#[must_use]
297pub fn footprint(
298    bounds: &ScreenBounds,
299    target: (u32, u32),
300    levels: u32,
301) -> Option<PyramidFootprint> {
302    let (width, height) = (
303        i32::try_from(target.0).unwrap_or(i32::MAX),
304        i32::try_from(target.1).unwrap_or(i32::MAX),
305    );
306    // The same saturating float → int the shader's `int(floor(…))` performs on
307    // a value [`project_box`] has already kept inside the projection limit.
308    let x0 = bounds.min[0].floor() as i32 - OCCLUSION_GUARD_TEXELS;
309    let y0 = bounds.min[1].floor() as i32 - OCCLUSION_GUARD_TEXELS;
310    let x1 = bounds.max[0].floor() as i32 + OCCLUSION_GUARD_TEXELS;
311    let y1 = bounds.max[1].floor() as i32 + OCCLUSION_GUARD_TEXELS;
312    if x1 < 0 || y1 < 0 || x0 >= width || y0 >= height {
313        return None;
314    }
315    let left = x0.max(0) as u32;
316    let top = y0.max(0) as u32;
317    let right = x1.min(width - 1) as u32;
318    let bottom = y1.min(height - 1) as u32;
319    let mut level = 1;
320    while level < levels
321        && ((right >> level) - (left >> level) > 1 || (bottom >> level) - (top >> level) > 1)
322    {
323        level += 1;
324    }
325    let level_width = (target.0 >> level).max(1);
326    let level_height = (target.1 >> level).max(1);
327    Some(PyramidFootprint {
328        level,
329        columns: (
330            (left >> level).min(level_width - 1),
331            (right >> level).min(level_width - 1),
332        ),
333        rows: (
334            (top >> level).min(level_height - 1),
335            (bottom >> level).min(level_height - 1),
336        ),
337    })
338}
339
340/// Whether the box `center ± extent`, seen through `view_projection`, is hidden
341/// behind what `pyramid` holds — `cull.slang`'s `occluded`, and the test both
342/// occlusion phases run.
343///
344/// Hidden when the box's nearest corner, pushed nearer by
345/// [`OCCLUSION_DEPTH_SLACK`] of itself, is still farther than the farthest depth
346/// over every texel its footprint reads. Anything [`project_box`] refuses, and
347/// anything off the target, is not hidden.
348#[must_use]
349pub fn occluded(view_projection: Mat4, center: Vec3, extent: Vec3, pyramid: &DepthPyramid) -> bool {
350    if pyramid.levels() == 0 {
351        return false;
352    }
353    let Some(bounds) = project_box(view_projection, center, extent, pyramid.extent()) else {
354        return false;
355    };
356    let Some(footprint) = footprint(&bounds, pyramid.extent(), pyramid.levels()) else {
357        return false;
358    };
359    let mut farthest = 1.0f32;
360    for y in footprint.rows.0..=footprint.rows.1 {
361        for x in footprint.columns.0..=footprint.columns.1 {
362            farthest = farthest.min(pyramid.load(footprint.level, x, y));
363        }
364    }
365    bounds.nearest * (1.0 + OCCLUSION_DEPTH_SLACK) < farthest
366}
367
368/// Whether the box's projected longer side is under `pixels` —
369/// `occlusionMain`'s small-feature test. A box [`project_box`] refuses is not
370/// small.
371#[must_use]
372pub fn small_feature(
373    view_projection: Mat4,
374    center: Vec3,
375    extent: Vec3,
376    target: (u32, u32),
377    pixels: f32,
378) -> bool {
379    project_box(view_projection, center, extent, target).is_some_and(|bounds| {
380        (bounds.max[0] - bounds.min[0]).max(bounds.max[1] - bounds.min[1]) < pixels
381    })
382}
383
384/// What the first occlusion phase is given.
385#[derive(Clone, Copy, Debug)]
386pub struct EarlyInputs<'a> {
387    /// This frame's world → clip, which the small-feature test projects through.
388    pub view_projection: Mat4,
389    /// The previous frame's, which the occlusion test reprojects through.
390    pub previous_view_projection: Mat4,
391    /// The previous frame's farthest-depth pyramid, or `None` where there is no
392    /// history — which marks nothing.
393    pub history: Option<&'a DepthPyramid>,
394    /// The target the small-feature test measures in.
395    pub target: (u32, u32),
396    /// The small-feature threshold in pixels, or `None` where it is off.
397    pub small_feature_pixels: Option<f32>,
398}
399
400/// The survivor-list entries `cull.slang`'s `occlusionMain` writes, ascending:
401/// [`visible_instances`](super::visible_instances)' survivors less the small
402/// features, each tagged [`ENTRY_OCCLUDED`] where the previous frame's pyramid
403/// hides it.
404///
405/// A deforming instance — [`GpuInstance::BASE_VERTEX_OVERRIDE`] — is kept
406/// untagged, because its source bounds do not describe its vertices.
407#[must_use]
408pub fn early_entries(
409    frustum: &Frustum,
410    instances: &[GpuInstance],
411    meshes: &[GpuMesh],
412    hidden_view: u32,
413    inputs: &EarlyInputs<'_>,
414) -> Vec<u32> {
415    let mut entries = Vec::new();
416    for index in super::visible_instances(frustum, instances, meshes, hidden_view) {
417        let instance = &instances[index as usize];
418        if instance.flags & GpuInstance::BASE_VERTEX_OVERRIDE != 0 {
419            entries.push(index);
420            continue;
421        }
422        let mesh = &meshes[instance.mesh as usize];
423        let (center, extent) = world_box(instance, mesh);
424        if inputs.small_feature_pixels.is_some_and(|pixels| {
425            small_feature(
426                inputs.view_projection,
427                center,
428                extent,
429                inputs.target,
430                pixels,
431            )
432        }) {
433            continue;
434        }
435        let hidden = inputs.history.is_some_and(|pyramid| {
436            occluded(inputs.previous_view_projection, center, extent, pyramid)
437        });
438        entries.push(if hidden {
439            index | ENTRY_OCCLUDED
440        } else {
441            index
442        });
443    }
444    entries
445}
446
447/// What `cull.slang`'s `lateMain` leaves in an entry: an entry the first phase
448/// marked, tagged [`ENTRY_RESCUED`] if this frame's pyramid does not hide it.
449/// Any other entry is returned as it came.
450#[must_use]
451pub fn late_entry(
452    entry: u32,
453    instances: &[GpuInstance],
454    meshes: &[GpuMesh],
455    view_projection: Mat4,
456    pyramid: &DepthPyramid,
457) -> u32 {
458    if entry & ENTRY_OCCLUDED == 0 {
459        return entry;
460    }
461    let instance = &instances[(entry & crcbl_shaders::cull::ENTRY_INDEX_MASK) as usize];
462    let (center, extent) = world_box(instance, &meshes[instance.mesh as usize]);
463    if occluded(view_projection, center, extent, pyramid) {
464        entry
465    } else {
466        entry | ENTRY_RESCUED
467    }
468}
469
470/// Face `f`'s side planes: the first [`FACE_PLANES`] of the frustum of its
471/// view-projection, which are its pyramid's four sides.
472pub type FacePlanes = [[Vec4; FACE_PLANES]; FACE_COUNT];
473
474/// The six faces' side planes of a point light whose face `f` renders through
475/// `view_projections[f]`.
476///
477/// **Only the sides.** The near and far planes are dropped: a face's near plane
478/// excludes a sliver around the light that no face covers but the light's box
479/// does, and the far plane is the box's own. So the six pyramids tile every
480/// direction out of the light, and a box the light's cull kept reaches at least
481/// one of them.
482#[must_use]
483pub fn face_planes(view_projections: &[Mat4; FACE_COUNT]) -> FacePlanes {
484    view_projections.map(|matrix| {
485        let planes = Frustum::from_view_projection(matrix).planes;
486        [planes[0], planes[1], planes[2], planes[3]]
487    })
488}
489
490/// The face tags `cull.slang`'s `computeMain` adds to a survivor of a point
491/// light's cull under `CULL_FACES`: bit [`ENTRY_FACE_SHIFT`]` + f` for every
492/// face `f` whose four side planes the box reaches.
493#[must_use]
494pub fn face_tags(faces: &FacePlanes, center: Vec3, extent: Vec3) -> u32 {
495    let mut tags = 0;
496    for (face, planes) in faces.iter().enumerate() {
497        let inside = planes.iter().all(|plane| {
498            let normal = plane.truncate();
499            let radius = normal.abs().dot(extent);
500            normal.dot(center) + plane.w >= -radius
501        });
502        if inside {
503            tags |= 1 << (ENTRY_FACE_SHIFT as usize + face);
504        }
505    }
506    tags
507}
508
509/// The survivor-list entries a point light's cull writes, ascending:
510/// [`visible_instances`](super::visible_instances) against the light's box,
511/// each tagged by [`face_tags`] — or with every face, for a deforming instance.
512#[must_use]
513pub fn face_entries(
514    frustum: &Frustum,
515    faces: &FacePlanes,
516    instances: &[GpuInstance],
517    meshes: &[GpuMesh],
518) -> Vec<u32> {
519    super::visible_instances(frustum, instances, meshes, 0)
520        .into_iter()
521        .map(|index| {
522            let instance = &instances[index as usize];
523            if instance.flags & GpuInstance::BASE_VERTEX_OVERRIDE != 0 {
524                return index | (((1 << FACE_COUNT) - 1) << ENTRY_FACE_SHIFT);
525            }
526            let (center, extent) = world_box(instance, &meshes[instance.mesh as usize]);
527            index | face_tags(faces, center, extent)
528        })
529        .collect()
530}
531
532#[cfg(test)]
533mod tests;