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///
201/// The box is [`GpuInstance::cull_bounds`], so `None` is a deforming instance
202/// with no box of its own — `cull.slang`'s `has_box` refusing — which every
203/// caller keeps whole.
204#[must_use]
205pub fn world_box(instance: &GpuInstance, mesh: &GpuMesh) -> Option<(Vec3, Vec3)> {
206    let (min, max) = instance.cull_bounds(mesh)?;
207    let min = Vec3::from_array(min);
208    let max = Vec3::from_array(max);
209    let local_center = (max + min) * 0.5;
210    let local_extent = (max - min) * 0.5;
211    let transform = Mat4::from_cols_array(&instance.transform);
212    let basis = Mat3::from_mat4(transform);
213    let absolute = Mat3::from_cols(basis.x_axis.abs(), basis.y_axis.abs(), basis.z_axis.abs());
214    Some((
215        transform.transform_point3(local_center),
216        absolute * local_extent,
217    ))
218}
219
220/// A box projected onto a target: the pixel rectangle its corners span, with
221/// `(0, 0)` at the top left, and the nearest reversed-Z depth any corner has.
222#[derive(Clone, Copy, Debug, PartialEq)]
223pub struct ScreenBounds {
224    /// The rectangle's top-left corner, in pixels.
225    pub min: [f32; 2],
226    /// Its bottom-right corner.
227    pub max: [f32; 2],
228    /// The largest depth of the eight corners — under reversed-Z, the nearest.
229    pub nearest: f32,
230}
231
232/// Projects the box `center ± extent` through `view_projection` onto a target
233/// of `target` pixels — `cull.slang`'s `project_box`.
234///
235/// `None` where the shader's box is invalid: a corner on or behind the eye
236/// plane, in front of the near plane, or [`PROJECTION_LIMIT`] pixels or more
237/// from the origin. Every caller reads that as "not hidden, not small".
238#[must_use]
239pub fn project_box(
240    view_projection: Mat4,
241    center: Vec3,
242    extent: Vec3,
243    target: (u32, u32),
244) -> Option<ScreenBounds> {
245    let (width, height) = (target.0 as f32, target.1 as f32);
246    let mut bounds = ScreenBounds {
247        min: [PROJECTION_LIMIT; 2],
248        max: [-PROJECTION_LIMIT; 2],
249        nearest: 0.0,
250    };
251    for corner in 0..8u32 {
252        let side = Vec3::new(
253            if corner & 1 != 0 { 1.0 } else { -1.0 },
254            if corner & 2 != 0 { 1.0 } else { -1.0 },
255            if corner & 4 != 0 { 1.0 } else { -1.0 },
256        );
257        let clip = view_projection * (center + side * extent).extend(1.0);
258        // Named rather than negated in place, and written so a `NaN` fails:
259        // every comparison with one is false, which makes the box invalid.
260        let in_front = clip.w > 0.0;
261        if !in_front {
262            return None;
263        }
264        let depth = clip.z / clip.w;
265        let x = (clip.x / clip.w * 0.5 + 0.5) * width;
266        let y = (0.5 - clip.y / clip.w * 0.5) * height;
267        let behind_near = depth <= 1.0;
268        let on_the_page = x.abs() < PROJECTION_LIMIT && y.abs() < PROJECTION_LIMIT;
269        if !behind_near || !on_the_page {
270            return None;
271        }
272        bounds.min = [bounds.min[0].min(x), bounds.min[1].min(y)];
273        bounds.max = [bounds.max[0].max(x), bounds.max[1].max(y)];
274        bounds.nearest = bounds.nearest.max(depth);
275    }
276    Some(bounds)
277}
278
279/// Where [`occluded`] reads the pyramid for a box, before it compares anything:
280/// the level and the inclusive texel range.
281///
282/// Public so a test can say *which* texels decided a verdict rather than only
283/// what the verdict was.
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
285pub struct PyramidFootprint {
286    /// The level read, from 1.
287    pub level: u32,
288    /// The first and last texel column read.
289    pub columns: (u32, u32),
290    /// The first and last texel row read.
291    pub rows: (u32, u32),
292}
293
294/// The texels `cull.slang`'s `occluded` reads for `bounds` on a pyramid of
295/// `levels` levels over `target` — `None` for a rectangle entirely off the
296/// target, which is never hidden.
297///
298/// The rectangle is widened by [`OCCLUSION_GUARD_TEXELS`] and clamped to the
299/// target; the level is the finest from 1 up at which it spans at most two
300/// texels on each axis, or the deepest one there is.
301#[must_use]
302pub fn footprint(
303    bounds: &ScreenBounds,
304    target: (u32, u32),
305    levels: u32,
306) -> Option<PyramidFootprint> {
307    let (width, height) = (
308        i32::try_from(target.0).unwrap_or(i32::MAX),
309        i32::try_from(target.1).unwrap_or(i32::MAX),
310    );
311    // The same saturating float → int the shader's `int(floor(…))` performs on
312    // a value [`project_box`] has already kept inside the projection limit.
313    let x0 = bounds.min[0].floor() as i32 - OCCLUSION_GUARD_TEXELS;
314    let y0 = bounds.min[1].floor() as i32 - OCCLUSION_GUARD_TEXELS;
315    let x1 = bounds.max[0].floor() as i32 + OCCLUSION_GUARD_TEXELS;
316    let y1 = bounds.max[1].floor() as i32 + OCCLUSION_GUARD_TEXELS;
317    if x1 < 0 || y1 < 0 || x0 >= width || y0 >= height {
318        return None;
319    }
320    let left = x0.max(0) as u32;
321    let top = y0.max(0) as u32;
322    let right = x1.min(width - 1) as u32;
323    let bottom = y1.min(height - 1) as u32;
324    let mut level = 1;
325    while level < levels
326        && ((right >> level) - (left >> level) > 1 || (bottom >> level) - (top >> level) > 1)
327    {
328        level += 1;
329    }
330    let level_width = (target.0 >> level).max(1);
331    let level_height = (target.1 >> level).max(1);
332    Some(PyramidFootprint {
333        level,
334        columns: (
335            (left >> level).min(level_width - 1),
336            (right >> level).min(level_width - 1),
337        ),
338        rows: (
339            (top >> level).min(level_height - 1),
340            (bottom >> level).min(level_height - 1),
341        ),
342    })
343}
344
345/// Whether the box `center ± extent`, seen through `view_projection`, is hidden
346/// behind what `pyramid` holds — `cull.slang`'s `occluded`, and the test both
347/// occlusion phases run.
348///
349/// Hidden when the box's nearest corner, pushed nearer by
350/// [`OCCLUSION_DEPTH_SLACK`] of itself, is still farther than the farthest depth
351/// over every texel its footprint reads. Anything [`project_box`] refuses, and
352/// anything off the target, is not hidden.
353#[must_use]
354pub fn occluded(view_projection: Mat4, center: Vec3, extent: Vec3, pyramid: &DepthPyramid) -> bool {
355    if pyramid.levels() == 0 {
356        return false;
357    }
358    let Some(bounds) = project_box(view_projection, center, extent, pyramid.extent()) else {
359        return false;
360    };
361    let Some(footprint) = footprint(&bounds, pyramid.extent(), pyramid.levels()) else {
362        return false;
363    };
364    let mut farthest = 1.0f32;
365    for y in footprint.rows.0..=footprint.rows.1 {
366        for x in footprint.columns.0..=footprint.columns.1 {
367            farthest = farthest.min(pyramid.load(footprint.level, x, y));
368        }
369    }
370    bounds.nearest * (1.0 + OCCLUSION_DEPTH_SLACK) < farthest
371}
372
373/// Whether the box's projected longer side is under `pixels` —
374/// `occlusionMain`'s small-feature test. A box [`project_box`] refuses is not
375/// small.
376#[must_use]
377pub fn small_feature(
378    view_projection: Mat4,
379    center: Vec3,
380    extent: Vec3,
381    target: (u32, u32),
382    pixels: f32,
383) -> bool {
384    project_box(view_projection, center, extent, target).is_some_and(|bounds| {
385        (bounds.max[0] - bounds.min[0]).max(bounds.max[1] - bounds.min[1]) < pixels
386    })
387}
388
389/// What the first occlusion phase is given.
390#[derive(Clone, Copy, Debug)]
391pub struct EarlyInputs<'a> {
392    /// This frame's world → clip, which the small-feature test projects through.
393    pub view_projection: Mat4,
394    /// The previous frame's, which the occlusion test reprojects through.
395    pub previous_view_projection: Mat4,
396    /// The previous frame's farthest-depth pyramid, or `None` where there is no
397    /// history — which marks nothing.
398    pub history: Option<&'a DepthPyramid>,
399    /// The target the small-feature test measures in.
400    pub target: (u32, u32),
401    /// The small-feature threshold in pixels, or `None` where it is off.
402    pub small_feature_pixels: Option<f32>,
403}
404
405/// The survivor-list entries `cull.slang`'s `occlusionMain` writes, ascending:
406/// [`visible_instances`](super::visible_instances)' survivors less the small
407/// features, each tagged [`ENTRY_OCCLUDED`] where the previous frame's pyramid
408/// hides it.
409///
410/// A deforming instance — [`GpuInstance::BASE_VERTEX_OVERRIDE`] — with no box
411/// of its own is kept untagged, because its source bounds do not describe its
412/// vertices. One that carries a box is tested by it like any other.
413#[must_use]
414pub fn early_entries(
415    frustum: &Frustum,
416    instances: &[GpuInstance],
417    meshes: &[GpuMesh],
418    hidden_view: u32,
419    inputs: &EarlyInputs<'_>,
420) -> Vec<u32> {
421    let mut entries = Vec::new();
422    for index in super::visible_instances(frustum, instances, meshes, hidden_view) {
423        let instance = &instances[index as usize];
424        let Some((center, extent)) = world_box(instance, &meshes[instance.mesh as usize]) else {
425            entries.push(index);
426            continue;
427        };
428        if inputs.small_feature_pixels.is_some_and(|pixels| {
429            small_feature(
430                inputs.view_projection,
431                center,
432                extent,
433                inputs.target,
434                pixels,
435            )
436        }) {
437            continue;
438        }
439        let hidden = inputs.history.is_some_and(|pyramid| {
440            occluded(inputs.previous_view_projection, center, extent, pyramid)
441        });
442        entries.push(if hidden {
443            index | ENTRY_OCCLUDED
444        } else {
445            index
446        });
447    }
448    entries
449}
450
451/// What `cull.slang`'s `lateMain` leaves in an entry: an entry the first phase
452/// marked, tagged [`ENTRY_RESCUED`] if this frame's pyramid does not hide it.
453/// Any other entry is returned as it came.
454#[must_use]
455pub fn late_entry(
456    entry: u32,
457    instances: &[GpuInstance],
458    meshes: &[GpuMesh],
459    view_projection: Mat4,
460    pyramid: &DepthPyramid,
461) -> u32 {
462    if entry & ENTRY_OCCLUDED == 0 {
463        return entry;
464    }
465    let instance = &instances[(entry & crcbl_shaders::cull::ENTRY_INDEX_MASK) as usize];
466    // The first phase marks only an instance it had a box for, so `None` is an
467    // entry nothing here marked; rescuing it is the side that draws.
468    let hidden = world_box(instance, &meshes[instance.mesh as usize])
469        .is_some_and(|(center, extent)| occluded(view_projection, center, extent, pyramid));
470    if hidden { entry } else { entry | ENTRY_RESCUED }
471}
472
473/// Face `f`'s side planes: the first [`FACE_PLANES`] of the frustum of its
474/// view-projection, which are its pyramid's four sides.
475pub type FacePlanes = [[Vec4; FACE_PLANES]; FACE_COUNT];
476
477/// The six faces' side planes of a point light whose face `f` renders through
478/// `view_projections[f]`.
479///
480/// **Only the sides.** The near and far planes are dropped: a face's near plane
481/// excludes a sliver around the light that no face covers but the light's box
482/// does, and the far plane is the box's own. So the six pyramids tile every
483/// direction out of the light, and a box the light's cull kept reaches at least
484/// one of them.
485#[must_use]
486pub fn face_planes(view_projections: &[Mat4; FACE_COUNT]) -> FacePlanes {
487    view_projections.map(|matrix| {
488        let planes = Frustum::from_view_projection(matrix).planes;
489        [planes[0], planes[1], planes[2], planes[3]]
490    })
491}
492
493/// The face tags `cull.slang`'s `computeMain` adds to a survivor of a point
494/// light's cull under `CULL_FACES`: bit [`ENTRY_FACE_SHIFT`]` + f` for every
495/// face `f` whose four side planes the box reaches.
496#[must_use]
497pub fn face_tags(faces: &FacePlanes, center: Vec3, extent: Vec3) -> u32 {
498    let mut tags = 0;
499    for (face, planes) in faces.iter().enumerate() {
500        let inside = planes.iter().all(|plane| {
501            let normal = plane.truncate();
502            let radius = normal.abs().dot(extent);
503            normal.dot(center) + plane.w >= -radius
504        });
505        if inside {
506            tags |= 1 << (ENTRY_FACE_SHIFT as usize + face);
507        }
508    }
509    tags
510}
511
512/// The survivor-list entries a point light's cull writes, ascending:
513/// [`visible_instances`](super::visible_instances) against the light's box,
514/// each tagged by [`face_tags`] — or with every face, for a deforming instance
515/// with no box of its own.
516#[must_use]
517pub fn face_entries(
518    frustum: &Frustum,
519    faces: &FacePlanes,
520    instances: &[GpuInstance],
521    meshes: &[GpuMesh],
522) -> Vec<u32> {
523    super::visible_instances(frustum, instances, meshes, 0)
524        .into_iter()
525        .map(|index| {
526            let instance = &instances[index as usize];
527            world_box(instance, &meshes[instance.mesh as usize]).map_or(
528                index | (((1 << FACE_COUNT) - 1) << ENTRY_FACE_SHIFT),
529                |(center, extent)| index | face_tags(faces, center, extent),
530            )
531        })
532        .collect()
533}
534
535#[cfg(test)]
536mod tests;