mod occlusion;
pub use occlusion::{
DepthPyramid, EarlyInputs, FacePlanes, PyramidFootprint, Reduction, ScreenBounds,
early_entries, face_entries, face_planes, face_tags, footprint, late_entry, occluded,
project_box, small_feature, world_box,
};
use crcbl_core::bounds::{max_lanes, min_lanes};
use crcbl_shaders::mesh::{GpuInstance, GpuMaterial, GpuMesh};
use crcbl_shaders::meshlet::ClusterBounds;
use glam::{Mat3, Mat4, Vec3, Vec4};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Aabb {
pub min: Vec3,
pub max: Vec3,
}
impl Aabb {
#[must_use]
pub fn from_points(points: impl IntoIterator<Item = Vec3>) -> Option<Self> {
let mut points = points.into_iter();
let first = points.next()?;
let mut bounds = Self {
min: first,
max: first,
};
for point in points {
bounds.min = min_lanes(bounds.min, point);
bounds.max = max_lanes(bounds.max, point);
}
Some(bounds)
}
#[must_use]
pub fn center(&self) -> Vec3 {
(self.max + self.min) * 0.5
}
#[must_use]
pub fn half_extent(&self) -> Vec3 {
(self.max - self.min) * 0.5
}
#[must_use]
pub fn transformed(&self, transform: Mat4) -> Self {
let center = transform.transform_point3(self.center());
let basis = Mat3::from_mat4(transform);
let absolute = Mat3::from_cols(basis.x_axis.abs(), basis.y_axis.abs(), basis.z_axis.abs());
let extent = absolute * self.half_extent();
Self {
min: center - extent,
max: center + extent,
}
}
}
pub const PLANE_COUNT: usize = crcbl_shaders::cull::PLANE_COUNT;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Frustum {
pub planes: [Vec4; PLANE_COUNT],
}
impl Frustum {
#[must_use]
pub fn from_view_projection(view_projection: Mat4) -> Self {
let row = |index: usize| view_projection.row(index);
let (x, y, z, w) = (row(0), row(1), row(2), row(3));
Self {
planes: [w + x, w - x, w + y, w - y, z, w - z],
}
}
#[must_use]
pub fn intersects(&self, bounds: &Aabb) -> bool {
let center = bounds.center();
let extent = bounds.half_extent();
self.planes.iter().all(|plane| {
let normal = plane.truncate();
let radius = normal.abs().dot(extent);
normal.dot(center) + plane.w >= -radius
})
}
#[must_use]
pub fn intersects_sphere(&self, center: Vec3, radius: f32) -> bool {
self.planes.iter().all(|plane| {
let normal = plane.truncate();
normal.dot(center) + plane.w >= -radius * normal.length()
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ClusterVerdict {
Kept,
RejectedByFrustum,
RejectedByCone,
}
#[must_use]
pub fn cluster_survives_cull(
frustum: &Frustum,
camera: Vec3,
transform: Mat4,
material_mode: u32,
bounds: &ClusterBounds,
) -> bool {
cluster_cull_verdict(frustum, camera, transform, material_mode, bounds) == ClusterVerdict::Kept
}
#[must_use]
pub fn cluster_cull_verdict(
frustum: &Frustum,
camera: Vec3,
transform: Mat4,
material_mode: u32,
bounds: &ClusterBounds,
) -> ClusterVerdict {
let basis = Mat3::from_mat4(transform);
let center = transform.transform_point3(Vec3::from_array(bounds.center));
let radius = bounds.radius * max_stretch(basis);
if !frustum.intersects_sphere(center, radius) {
return ClusterVerdict::RejectedByFrustum;
}
let axis = (basis * Vec3::from_array(bounds.cone_axis)).normalize_or_zero();
let to_center = center - camera;
let sine = (1.0 - bounds.cone_cutoff * bounds.cone_cutoff)
.max(0.0)
.sqrt();
let faces_away = cone_may_reject(material_mode)
&& preserves_angles(basis)
&& bounds.cone_cutoff > 0.0
&& axis.dot(to_center) > sine.mul_add(to_center.length(), radius);
if faces_away {
ClusterVerdict::RejectedByCone
} else {
ClusterVerdict::Kept
}
}
#[must_use]
pub const fn cone_may_reject(material_mode: u32) -> bool {
material_mode & GpuMaterial::DOUBLE_SIDED == 0
}
fn preserves_angles(basis: Mat3) -> bool {
let gram = basis.transpose() * basis;
let diagonal = [gram.x_axis.x, gram.y_axis.y, gram.z_axis.z];
let largest = diagonal.iter().copied().fold(0.0f32, f32::max);
if largest <= 0.0 {
return false;
}
let slack = ClusterBounds::SIMILARITY_TOLERANCE * largest;
let off_diagonal = [gram.x_axis.y, gram.x_axis.z, gram.y_axis.z];
off_diagonal.iter().all(|value| value.abs() <= slack)
&& diagonal.iter().all(|value| (largest - value) <= slack)
}
fn max_stretch(basis: Mat3) -> f32 {
let gram = basis.transpose() * basis;
let row_sum = |row: usize| {
(0..3)
.map(|column| gram.col(column)[row].abs())
.sum::<f32>()
};
(0..3).map(row_sum).fold(0.0f32, f32::max).sqrt()
}
#[must_use]
pub fn visible_instances(
frustum: &Frustum,
instances: &[GpuInstance],
meshes: &[GpuMesh],
hidden_view: u32,
) -> Vec<u32> {
let mut visible = Vec::new();
for (index, instance) in instances.iter().enumerate() {
if instance.flags & GpuInstance::LIVE == 0 {
continue;
}
if instance.flags & hidden_view != 0 {
continue;
}
let Some(mesh) = meshes.get(instance.mesh as usize) else {
continue;
};
if mesh.index_count == 0 {
continue;
}
let deforming = instance.flags & GpuInstance::BASE_VERTEX_OVERRIDE != 0;
let bounds = Aabb {
min: Vec3::from_array(mesh.bounds_min),
max: Vec3::from_array(mesh.bounds_max),
};
let world = bounds.transformed(Mat4::from_cols_array(&instance.transform));
if deforming || frustum.intersects(&world) {
visible.push(u32::try_from(index).unwrap_or_else(|_| {
unreachable!("an instance array is indexed by u32 everywhere else")
}));
}
}
visible
}
#[cfg(test)]
mod tests {
use super::*;
use crate::camera::{Camera, Projection};
use core::f32::consts::FRAC_PI_2;
fn frustum() -> Frustum {
Frustum::from_view_projection(Camera::default().view_projection(1.0))
}
fn unit_cube() -> GpuMesh {
GpuMesh {
base_vertex: 0,
base_index: 0,
index_count: 36,
bounds_min: [-0.5, -0.5, -0.5],
bounds_max: [0.5, 0.5, 0.5],
uv_range: crcbl_shaders::vertex::UvRange::default(),
flags: 0,
}
}
#[test]
fn a_nan_is_skipped_from_every_position_and_never_shrinks_the_box() {
let nan = Vec3::new(f32::NAN, 0.0, 0.0);
let low = Vec3::new(-1.0, -1.0, -1.0);
let high = Vec3::new(1.0, 1.0, 1.0);
let want = Aabb {
min: low,
max: high,
};
for (label, points) in [
("leading", vec![nan, low, high]),
("middle", vec![low, nan, high]),
("trailing", vec![low, high, nan]),
("before a finite point", vec![low, high, nan, low]),
] {
let box_ = Aabb::from_points(points).expect("not empty");
assert_eq!(
box_, want,
"a NaN {label} must be skipped, leaving exactly the box the finite points make"
);
}
let infinite = Aabb::from_points([low, Vec3::new(f32::INFINITY, 0.0, 0.0), high])
.expect("three points is not empty");
assert_eq!(
infinite.max.x,
f32::INFINITY,
"an infinity has a defined ordering, so it is real data and is kept — only the \
unorderable value is skipped"
);
let all_nan = Aabb::from_points([nan, nan]).expect("two points is not empty");
assert!(
all_nan.min.x.is_nan() && all_nan.max.x.is_nan(),
"with nothing finite to fall back to in that lane the NaN is all there is, so a wholly \
degenerate mesh still reports as non-finite rather than as a plausible box"
);
}
fn at(translation: Vec3) -> GpuInstance {
GpuInstance {
transform: Mat4::from_translation(translation).to_cols_array(),
flags: GpuInstance::LIVE,
..GpuInstance::default()
}
}
#[test]
fn a_box_at_the_origin_is_inside_the_default_camera() {
let bounds = Aabb {
min: Vec3::splat(-0.5),
max: Vec3::splat(0.5),
};
assert!(frustum().intersects(&bounds));
}
#[test]
fn a_box_pushed_past_any_one_plane_is_outside() {
let frustum = frustum();
let unit = Aabb {
min: Vec3::splat(-0.5),
max: Vec3::splat(0.5),
};
for (what, translation) in [
("right", Vec3::new(20.0, 0.0, 0.0)),
("left", Vec3::new(-20.0, 0.0, 0.0)),
("top", Vec3::new(0.0, 20.0, 0.0)),
("bottom", Vec3::new(0.0, -20.0, 0.0)),
("behind", Vec3::new(0.0, 0.0, 20.0)),
] {
let moved = unit.transformed(Mat4::from_translation(translation));
assert!(
!frustum.intersects(&moved),
"a box {what} of the frustum was not culled: {moved:?}"
);
}
}
#[test]
fn the_infinite_far_plane_is_degenerate_and_rejects_nothing() {
let frustum = frustum();
let far = frustum.planes[4];
assert_eq!(far.truncate(), Vec3::ZERO, "{far:?}");
assert!(far.w > 0.0, "so every point is on its inside: {far:?}");
let distant = Aabb {
min: Vec3::new(-0.5, -0.5, -10_000.5),
max: Vec3::new(0.5, 0.5, -9_999.5),
};
assert!(frustum.intersects(&distant));
let ortho = Frustum::from_view_projection(
Camera::default()
.with_projection(Projection::Orthographic {
half_height: 1.0,
near: 0.1,
far: 10.0,
})
.view_projection(1.0),
);
assert_ne!(ortho.planes[4].truncate(), Vec3::ZERO);
assert!(!ortho.intersects(&distant));
}
#[test]
fn a_rotated_box_grows() {
let unit = Aabb {
min: Vec3::new(-0.5, -0.5, -0.5),
max: Vec3::new(0.5, 0.5, 0.5),
};
let rotated = unit.transformed(Mat4::from_rotation_z(core::f32::consts::FRAC_PI_4));
let half = rotated.half_extent();
let expected = core::f32::consts::SQRT_2 / 2.0;
assert!(
(half.x - expected).abs() < 1e-5 && (half.y - expected).abs() < 1e-5,
"a 45° rotation of a unit box has half-extent {expected} in x and y, got {half:?}"
);
assert!(
(half.z - 0.5).abs() < 1e-6,
"the rotation axis is untouched: {half:?}"
);
let quarter = unit.transformed(Mat4::from_rotation_z(FRAC_PI_2));
assert!(
(quarter.half_extent() - Vec3::splat(0.5))
.abs()
.max_element()
< 1e-6,
"{:?}",
quarter.half_extent()
);
}
#[test]
fn a_rotation_can_bring_a_box_back_into_the_frustum() {
let frustum = frustum();
let bar = Aabb {
min: Vec3::new(-0.02, -1.0, -0.02),
max: Vec3::new(0.02, 1.0, 0.02),
};
let offset = Vec3::new(1.5, 0.0, 0.0);
let upright = bar.transformed(Mat4::from_translation(offset));
assert!(!frustum.intersects(&upright), "{upright:?}");
let laid_down =
bar.transformed(Mat4::from_translation(offset) * Mat4::from_rotation_z(FRAC_PI_2));
assert!(frustum.intersects(&laid_down), "{laid_down:?}");
}
#[test]
fn an_instance_without_the_live_bit_is_not_visible() {
let frustum = frustum();
let meshes = [unit_cube()];
let live = at(Vec3::ZERO);
let removed = GpuInstance {
flags: live.flags & !GpuInstance::LIVE,
..live
};
assert_eq!(
visible_instances(&frustum, &[live, removed], &meshes, 0),
vec![0],
"the live instance survives and its dead twin does not"
);
assert_eq!(
visible_instances(&frustum, &[removed, live], &meshes, 0),
vec![1]
);
assert!(
visible_instances(&frustum, &[GpuInstance::default()], &meshes, 0).is_empty(),
"a default instance is not live"
);
}
#[test]
fn an_instance_whose_mesh_entry_is_empty_is_not_visible() {
let frustum = frustum();
let meshes = [unit_cube(), GpuMesh::default()];
let instances = [
at(Vec3::ZERO),
GpuInstance {
mesh: 1,
..at(Vec3::ZERO)
},
GpuInstance {
mesh: 7,
..at(Vec3::ZERO)
},
];
assert_eq!(visible_instances(&frustum, &instances, &meshes, 0), vec![0]);
}
#[test]
fn a_skinned_instance_survives_when_its_source_bounds_are_outside() {
let source_outside = at(Vec3::X * 8.0);
assert!(
visible_instances(&frustum(), &[source_outside], &[unit_cube()], 0).is_empty(),
"the unskinned source bounds are outside the camera"
);
let skinned = GpuInstance {
flags: source_outside.flags | GpuInstance::BASE_VERTEX_OVERRIDE,
..source_outside
};
assert_eq!(
visible_instances(&frustum(), &[skinned], &[unit_cube()], 0),
vec![0],
"a palette may have moved the skinned vertices into view"
);
}
#[test]
fn a_hidden_instance_is_rejected_by_its_own_view_alone() {
let first = 1 << GpuInstance::HIDDEN_VIEWS_SHIFT;
let second = 1 << (GpuInstance::HIDDEN_VIEWS_SHIFT + 1);
let shown = at(Vec3::ZERO);
let hidden = GpuInstance {
flags: shown.flags | first,
..shown
};
let instances = [shown, hidden];
let meshes = [unit_cube()];
assert_eq!(
visible_instances(&frustum(), &instances, &meshes, first),
vec![0],
"the first view skips the instance hidden from it"
);
assert_eq!(
visible_instances(&frustum(), &instances, &meshes, second),
vec![0, 1],
"the second view still draws both"
);
assert_eq!(
visible_instances(&frustum(), &instances, &meshes, 0),
vec![0, 1],
"and a cull that is no view's rejects nothing on the mask"
);
}
#[test]
fn the_visible_set_follows_the_camera() {
let meshes = [unit_cube()];
let instances = [at(Vec3::ZERO), at(Vec3::new(6.0, 0.0, 0.0))];
let ahead = Frustum::from_view_projection(Camera::default().view_projection(1.0));
assert_eq!(visible_instances(&ahead, &instances, &meshes, 0), vec![0]);
let turned = Camera {
eye: Vec3::new(6.0, 0.0, 2.0),
target: Vec3::new(6.0, 0.0, 0.0),
..Camera::default()
};
assert_eq!(
visible_instances(
&Frustum::from_view_projection(turned.view_projection(1.0)),
&instances,
&meshes,
0
),
vec![1]
);
}
fn ahead(axis: Vec3, cutoff: f32, radius: f32) -> ClusterBounds {
ClusterBounds {
center: [0.0, 0.0, -10.0],
radius,
cone_axis: axis.normalize().to_array(),
cone_cutoff: cutoff,
}
}
const SINGLE_SIDED: u32 = 0;
fn survives_as(material_mode: u32, bounds: &ClusterBounds) -> bool {
cluster_survives_cull(
&frustum(),
Camera::default().eye,
Mat4::IDENTITY,
material_mode,
bounds,
)
}
fn survives(bounds: &ClusterBounds) -> bool {
survives_as(SINGLE_SIDED, bounds)
}
#[test]
fn a_cluster_is_kept_facing_the_camera_and_rejected_facing_away() {
assert!(
survives(&ahead(Vec3::Z, 1.0, 0.5)),
"a face turned towards the camera is what the cull must never reject"
);
assert!(
!survives(&ahead(Vec3::NEG_Z, 1.0, 0.5)),
"a face turned away is the whole point of the cone test"
);
}
#[test]
fn a_double_sided_instance_keeps_the_cluster_that_faces_away() {
let away = ahead(Vec3::NEG_Z, 1.0, 0.5);
assert!(
!survives_as(SINGLE_SIDED, &away),
"a single-sided face turned away puts nothing on the screen, so the cone is \
right to reject it"
);
assert!(
survives_as(GpuMaterial::DOUBLE_SIDED, &away),
"glTF 2.0 §3.9.6 draws the back face, so the cluster carrying it has to reach \
the mesh stage"
);
assert!(
!survives_as(GpuMaterial::ALPHA_MODE_MASK, &away),
"the alpha-mask bit says nothing about which sides are drawn"
);
assert!(
survives_as(GpuMaterial::MODE_MASK, &away),
"a cutout material may also be double-sided, and then it is double-sided"
);
let frustum = frustum();
let camera = Camera::default().eye;
assert_eq!(
cluster_cull_verdict(
&frustum,
camera,
Mat4::IDENTITY,
GpuMaterial::DOUBLE_SIDED,
&away
),
ClusterVerdict::Kept,
"a double-sided instance never answers RejectedByCone"
);
assert_eq!(
cluster_cull_verdict(
&frustum,
camera,
Mat4::from_translation(Vec3::new(40.0, 0.0, 0.0)),
GpuMaterial::DOUBLE_SIDED,
&away
),
ClusterVerdict::RejectedByFrustum,
"the frustum half is not the material's business and still culls"
);
}
#[test]
fn an_omnidirectional_cluster_is_never_cone_culled() {
for axis in [Vec3::Z, Vec3::NEG_Z, Vec3::X, Vec3::new(1.0, 2.0, -3.0)] {
assert!(
survives(&ahead(axis, ClusterBounds::OMNIDIRECTIONAL_CUTOFF, 0.5)),
"a cone spanning every direction holds a front-facing normal for \
every view, and {axis} is one of them"
);
}
assert!(survives(&ahead(Vec3::NEG_Z, 0.0, 0.5)));
}
#[test]
fn a_cluster_the_point_form_would_reject_survives_the_conservative_one() {
let axis = Vec3::new(0.526_782_7, 0.0, -0.85);
let cutoff = 0.6f32;
let bounds = ahead(axis, cutoff, 2.0);
let camera = Camera::default().eye;
let to_center = Vec3::from_array(bounds.center) - camera;
let sine = (1.0 - cutoff * cutoff).sqrt();
let projected = Vec3::from_array(bounds.cone_axis).dot(to_center);
assert!(
projected > sine * to_center.length(),
"the point-form rule must reject this cluster, or the contrast below \
is vacuous: {projected} against {}",
sine * to_center.length()
);
assert!(
survives(&bounds),
"the conservative rule must keep it — the radius term is the whole \
difference, and without it this cluster's front-facing triangles are \
a hole in the picture"
);
assert!(!survives(&ahead(axis, cutoff, 0.1)));
}
#[test]
fn a_cluster_outside_the_frustum_is_rejected_whichever_way_it_faces() {
let frustum = frustum();
let camera = Camera::default().eye;
let at = |center: [f32; 3]| ClusterBounds {
center,
radius: 0.5,
cone_axis: Vec3::Z.to_array(),
cone_cutoff: 1.0,
};
let survives = |bounds: &ClusterBounds| {
cluster_survives_cull(&frustum, camera, Mat4::IDENTITY, SINGLE_SIDED, bounds)
};
assert!(survives(&at([0.0, 0.0, -10.0])), "straight ahead");
assert!(
!survives(&at([0.0, 0.0, 20.0])),
"twenty units behind the eye is past the near plane"
);
assert!(
!survives(&at([40.0, 0.0, -10.0])),
"forty units to the right of a 45° frustum ten units deep is outside it"
);
}
#[test]
fn the_verdict_names_the_test_that_rejected_the_cluster() {
let frustum = frustum();
let camera = Camera::default().eye;
let facing = |center: [f32; 3]| ClusterBounds {
center,
radius: 0.5,
cone_axis: Vec3::Z.to_array(),
cone_cutoff: 1.0,
};
let away = ClusterBounds {
center: [0.0, 0.0, 0.0],
radius: 0.5,
cone_axis: [0.0, 0.0, -1.0],
cone_cutoff: 1.0,
};
let ahead = Mat4::from_translation(Vec3::new(0.0, 0.0, -10.0));
let aside = Mat4::from_translation(Vec3::new(40.0, 0.0, -10.0));
for (case, transform, bounds, expected) in [
(
"straight ahead and facing the camera",
Mat4::IDENTITY,
facing([0.0, 0.0, -10.0]),
ClusterVerdict::Kept,
),
(
"twenty units behind the eye, facing the camera",
Mat4::IDENTITY,
facing([0.0, 0.0, 20.0]),
ClusterVerdict::RejectedByFrustum,
),
(
"inside the frustum, facing away",
ahead,
away,
ClusterVerdict::RejectedByCone,
),
(
"outside the frustum and facing away — the frustum is asked first",
aside,
away,
ClusterVerdict::RejectedByFrustum,
),
] {
let verdict = cluster_cull_verdict(&frustum, camera, transform, SINGLE_SIDED, &bounds);
assert_eq!(verdict, expected, "{case}");
assert_eq!(
cluster_survives_cull(&frustum, camera, transform, SINGLE_SIDED, &bounds),
verdict == ClusterVerdict::Kept,
"{case}: the bool and the verdict disagree",
);
}
}
#[test]
fn the_instance_transform_moves_the_sphere_and_turns_the_cone() {
let frustum = frustum();
let camera = Camera::default().eye;
let bounds = ClusterBounds {
center: [0.0, 0.0, 0.0],
radius: 0.5,
cone_axis: [0.0, 0.0, -1.0],
cone_cutoff: 1.0,
};
let back = Mat4::from_translation(Vec3::new(0.0, 0.0, -10.0));
assert!(
!cluster_survives_cull(&frustum, camera, back, SINGLE_SIDED, &bounds),
"translation alone leaves it facing away"
);
let turned = back * Mat4::from_rotation_y(core::f32::consts::PI);
assert!(
cluster_survives_cull(&frustum, camera, turned, SINGLE_SIDED, &bounds),
"the cone axis must be transformed with the instance"
);
let aside = Mat4::from_translation(Vec3::new(40.0, 0.0, -10.0))
* Mat4::from_rotation_y(core::f32::consts::PI);
assert!(!cluster_survives_cull(
&frustum,
camera,
aside,
SINGLE_SIDED,
&bounds
));
}
#[test]
fn the_open_box_loses_the_clusters_each_of_the_three_test_cameras_hides() {
let clusters = crcbl_shaders::meshlet::open_box_clusters();
assert_eq!(
clusters.clusters.len(),
crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
"one cluster per face is what makes the counts below mean anything"
);
let at = Vec3::new(-2.0, 0.0, 0.0);
let transform = Mat4::from_translation(at);
let aspect = 256.0 / 192.0;
let kept = |eye: Vec3, target: Vec3| -> Vec<&'static str> {
let look = Camera {
eye,
target,
..Camera::default()
};
let frustum = Frustum::from_view_projection(look.view_projection(aspect));
clusters
.clusters
.iter()
.zip(crcbl_shaders::mesh::OPEN_BOX_FACES)
.filter(|(cluster, _)| {
cluster_survives_cull(&frustum, eye, transform, SINGLE_SIDED, &cluster.bounds)
})
.map(|(_, face)| face.name)
.collect()
};
assert_eq!(
kept(at + Vec3::new(0.2, 3.2, 0.3), at).len(),
crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
"from above and between the walls every face is front-facing, so a \
correct cull rejects none of them"
);
assert_eq!(
kept(Vec3::new(1.6, 1.2, 2.2) * 1.7, Vec3::ZERO),
vec!["floor", "-X wall", "-Z wall"],
"the two walls whose inward normals point away from the golden's \
camera are the ones the cone must reject, and no others"
);
assert_eq!(
kept(
at + Vec3::new(0.0, 0.4, -0.3),
at + Vec3::new(0.0, 0.4, -1.0)
),
vec!["-X wall", "+X wall", "-Z wall"],
"from inside, looking level, the floor is under the frame and the +Z \
wall is behind the eye"
);
}
#[test]
fn the_radius_term_keeps_two_clusters_the_point_form_drops() {
let clusters = crcbl_shaders::meshlet::open_box_clusters();
let at = Vec3::new(-2.0, 0.0, 0.0);
let transform = Mat4::from_translation(at);
let eye = at + Vec3::new(0.8, 3.0, 0.8);
let look = Camera {
eye,
target: at,
..Camera::default()
};
let frustum = Frustum::from_view_projection(look.view_projection(256.0 / 192.0));
let conservative = clusters
.clusters
.iter()
.filter(|cluster| {
cluster_survives_cull(&frustum, eye, transform, SINGLE_SIDED, &cluster.bounds)
})
.count();
assert_eq!(
conservative,
crcbl_shaders::mesh::OPEN_BOX_FACES.len(),
"the documented rule keeps every cluster from here"
);
let point_form = clusters
.clusters
.iter()
.filter(|cluster| {
let bounds = &cluster.bounds;
let center = transform.transform_point3(Vec3::from_array(bounds.center));
if !frustum.intersects_sphere(center, bounds.radius) {
return false;
}
let axis = Mat3::from_mat4(transform) * Vec3::from_array(bounds.cone_axis);
let to_center = center - eye;
let sine = (1.0 - bounds.cone_cutoff * bounds.cone_cutoff)
.max(0.0)
.sqrt();
!(bounds.cone_cutoff > 0.0 && axis.dot(to_center) > sine * to_center.length())
})
.count();
assert_eq!(
point_form, 3,
"the radius-free form drops the two walls whose planes this camera has \
crossed, which is the difference the term exists to make"
);
}
fn trough(offset: Vec3) -> Mat4 {
Mat4::from_translation(Vec3::new(0.0, 1.0, 0.0) + offset)
* Mat4::from_scale(Vec3::new(6.0, 2.0, 1.6))
}
fn trough_camera() -> Camera {
Camera {
eye: Vec3::new(0.0, 2.2, 0.0),
target: Vec3::ZERO,
up: Vec3::Z,
projection: Projection::Perspective {
fov_y: core::f32::consts::FRAC_PI_3,
near: 0.01,
},
}
}
#[test]
fn a_scaled_instance_keeps_a_cluster_whose_surface_faces_the_camera() {
let turn = glam::Quat::from_axis_angle(Vec3::new(0.3, 0.8, 0.5).normalize(), 0.7);
let cone_axis = Vec3::new(0.9, 0.8, 0.9).normalize();
let bounds = ClusterBounds {
center: [0.0, 0.0, 0.0],
radius: 0.5,
cone_axis: cone_axis.to_array(),
cone_cutoff: 20.0f32.to_radians().cos(),
};
for (case, scale, view_degrees, faces_camera, kept) in [
(
"a non-uniform scale",
Vec3::new(6.0, 2.0, 1.6),
100.0f32,
true,
true,
),
(
"the same shape uniformly scaled",
Vec3::splat(6.0),
0.0f32,
false,
false,
),
] {
let transform = Mat4::from_quat(turn) * Mat4::from_scale(scale);
let basis = Mat3::from_mat4(transform);
let cofactor = basis.inverse().transpose() * basis.determinant();
let facing = (cofactor * cone_axis).normalize();
let read = (basis * cone_axis).normalize();
assert_eq!(
facing.dot(read) < 0.9,
faces_camera,
"{case}: the two axes differ exactly where the scale is non-uniform",
);
let sideways = (read - facing * facing.dot(read)).normalize_or_zero();
let view = facing * view_degrees.to_radians().cos()
+ sideways * view_degrees.to_radians().sin();
let eye = Vec3::from_array(bounds.center) - view * 100.0;
let camera = Camera {
eye,
target: Vec3::from_array(bounds.center),
up: Vec3::Y,
projection: Projection::Perspective {
fov_y: core::f32::consts::FRAC_PI_3,
near: 0.01,
},
};
let frustum = Frustum::from_view_projection(camera.view_projection(1.0));
let to_center = Vec3::from_array(bounds.center) - eye;
assert_eq!(
facing.dot(to_center) < 0.0,
faces_camera,
"{case}: which side of the surface the camera is on",
);
let sine = (1.0 - bounds.cone_cutoff * bounds.cone_cutoff).sqrt();
let rejected_by_the_old_rule = read.dot(to_center)
> sine.mul_add(to_center.length(), bounds.radius * max_stretch(basis));
assert!(
rejected_by_the_old_rule,
"{case}: the old rule rejected both of these, which is the point",
);
assert_eq!(
cluster_cull_verdict(&frustum, eye, transform, SINGLE_SIDED, &bounds)
== ClusterVerdict::Kept,
kept,
"{case}: a cluster facing the camera must survive, and one facing away \
under a transform the cone can be trusted through must not",
);
}
}
#[test]
fn a_scaled_instances_cluster_sphere_still_contains_its_geometry() {
let clusters = crcbl_shaders::meshlet::open_box_clusters();
let vertices = crcbl_shaders::mesh::open_box_vertices();
let transform = trough(Vec3::ZERO);
let stretch = max_stretch(Mat3::from_mat4(transform));
assert_eq!(
stretch, 6.0,
"the trough's longest axis is its run, and the bound is exact for an \
axis-aligned scale"
);
let mut escaped_the_local_radius = 0usize;
for cluster in &clusters.clusters {
let bounds = &cluster.bounds;
let center = transform.transform_point3(Vec3::from_array(bounds.center));
let run = cluster.vertex_offset as usize;
let furthest = clusters.vertices[run..run + cluster.vertex_count as usize]
.iter()
.map(|&vertex| {
let position = vertices[vertex as usize].position;
let world = transform.transform_point3(Vec3::new(
position[0],
position[1],
position[2],
));
(world - center).length()
})
.fold(0.0f32, f32::max);
assert!(
furthest <= bounds.radius * stretch,
"the scaled radius must bound the transformed cluster: {furthest} \
reached against {}",
bounds.radius * stretch
);
if furthest > bounds.radius {
escaped_the_local_radius += 1;
}
}
assert_eq!(
escaped_the_local_radius,
clusters.clusters.len(),
"every cluster of a trough this size outgrows its mesh-space radius, so \
a cull carrying that radius across is testing a sphere that contains \
none of them"
);
}
#[test]
fn a_scaled_trough_slid_across_the_camera_keeps_the_floor_it_still_shows() {
let clusters = crcbl_shaders::meshlet::open_box_clusters();
let vertices = crcbl_shaders::mesh::open_box_vertices();
let camera = trough_camera();
let view_projection = camera.view_projection(256.0 / 192.0);
let frustum = Frustum::from_view_projection(view_projection);
let floor = &clusters.clusters[0];
assert_eq!(
crcbl_shaders::mesh::OPEN_BOX_FACES[0].name,
"floor",
"cluster zero is the face this test is about"
);
for offset in [2.6f32, 3.0, 4.0] {
let transform = trough(Vec3::X * offset);
let run = floor.vertex_offset as usize;
let on_screen = clusters.vertices[run..run + floor.vertex_count as usize]
.iter()
.filter(|&&vertex| {
let position = vertices[vertex as usize].position;
let clip = view_projection
* (transform
* Vec3::new(position[0], position[1], position[2]).extend(1.0));
clip.w > 0.0
&& (clip.x / clip.w).abs() <= 1.0
&& (clip.y / clip.w).abs() <= 1.0
&& clip.z / clip.w >= 0.0
})
.count();
assert!(
on_screen > 0,
"the trough {offset} units along its run must still show floor, or \
there is nothing here for a cull to wrongly reject"
);
assert!(
cluster_survives_cull(&frustum, camera.eye, transform, SINGLE_SIDED, &floor.bounds),
"the floor puts {on_screen} of its vertices in the frame from {offset} \
units out and the cull rejected it — that is the box that stops \
drawing"
);
}
let away = trough(Vec3::X * 40.0);
assert!(
!clusters
.clusters
.iter()
.any(|cluster| cluster_survives_cull(
&frustum,
camera.eye,
away,
SINGLE_SIDED,
&cluster.bounds
)),
"forty units out the whole trough is outside the frustum, radius and all"
);
}
}