mod atlas;
mod cadence;
use glam::{Mat4, Vec3, Vec4Swizzles};
pub use atlas::{AtlasAllocator, MIN_TILE, TILE_LEVELS, Tile, TileRect};
pub use cadence::{Cadence, GROUPS, Group, r_shadow_cadence, r_shadow_faces};
use crate::camera::Camera;
use crate::cull::Frustum;
use crate::light::{Light, PointLight, SpotLight};
crcbl_console::convar! {
pub static r_shadow_filter: &'static str one_of ["pcss", "disc", "box"] = "pcss";
}
crcbl_console::convar! {
pub static r_shadow_split: f32 in 0.0 ..= 1.0 = 0.0;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Filter {
Pcss,
Disc,
Box,
}
impl Filter {
pub const ALL: [Self; 3] = [Self::Box, Self::Disc, Self::Pcss];
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::Pcss => "pcss",
Self::Disc => "disc",
Self::Box => "box",
}
}
#[must_use]
pub fn mode(self) -> u32 {
let at = crcbl_shaders::mesh::SHADOW_FILTERS
.iter()
.position(|label| *label == self.label())
.unwrap_or(0);
u32::try_from(at).unwrap_or(0)
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
FILTERS.into_iter().find(|filter| filter.label() == name)
}
}
const FILTERS: [Filter; 3] = [Filter::Pcss, Filter::Disc, Filter::Box];
#[must_use]
pub fn filter() -> Filter {
Filter::from_name(r_shadow_filter.get_enum()).unwrap_or(Filter::Pcss)
}
#[must_use]
pub fn shipped_filter() -> Filter {
match r_shadow_filter.default() {
crcbl_console::Value::Enum(name) => Filter::from_name(name).unwrap_or(Filter::Pcss),
_ => Filter::Pcss,
}
}
#[must_use]
pub fn split_at() -> Option<f32> {
let at = r_shadow_split.get_f32();
(at > 0.0 && at < 1.0).then_some(at)
}
#[cfg(test)]
pub(crate) static FILTER_SWITCH: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub const CASCADES: usize = crcbl_shaders::mesh::SHADOW_CASCADES;
pub const LIGHT_TILES: usize = crcbl_shaders::mesh::SHADOW_LIGHT_TILES;
pub const POINT_FACES: usize = crcbl_shaders::mesh::SHADOW_POINT_FACES;
pub const LIGHT_SLOTS: usize = 4;
pub const TILE: u32 = crcbl_shaders::mesh::SHADOW_TILE;
pub const ATLAS_COLUMNS: u32 = crcbl_shaders::mesh::SHADOW_ATLAS_COLUMNS;
pub const ATLAS_ROWS: u32 = crcbl_shaders::mesh::SHADOW_ATLAS_ROWS;
pub const TILES: usize = (ATLAS_COLUMNS * ATLAS_ROWS) as usize;
const _: () = assert!(
TILES == CASCADES + LIGHT_TILES,
"every tile of the grid is either a cascade's or a light's; a grid with a \
tile nothing owns is atlas nothing writes and nothing samples"
);
const _: () = assert!(
LIGHT_SLOTS <= LIGHT_TILES,
"a slot with no tile to render into is a cull dispatch whose result nothing \
can sample"
);
pub const MAX_SPOT_HALF_ANGLE: f32 = 80.0 * std::f32::consts::PI / 180.0;
const PUNCTUAL_NEAR: f32 = 0.05;
pub const DISTANCE: f32 = 24.0;
const SPLIT_LAMBDA: f32 = 0.7;
const CASTER_REACH: f32 = crcbl_shaders::mesh::SHADOW_CASTER_REACH;
const DEPTH_BIAS_TEXELS: f32 = 1.5;
const NORMAL_OFFSET_TEXELS: f32 = 2.0;
crcbl_console::convar! {
pub static r_shadow_bias: f32 in 0.0 ..= 128.0 = DEPTH_BIAS_TEXELS;
}
crcbl_console::convar! {
pub static r_shadow_normal_offset: f32 in 0.0 ..= 64.0 = NORMAL_OFFSET_TEXELS;
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Cascades {
pub view_proj: [Mat4; CASCADES],
pub far: [f32; 4],
}
impl Cascades {
fn splits(near: f32) -> [f32; CASCADES] {
let mut out = [DISTANCE; CASCADES];
for (index, far) in out.iter_mut().enumerate() {
#[expect(
clippy::cast_precision_loss,
reason = "a cascade index is at most four"
)]
let ratio = (index + 1) as f32 / CASCADES as f32;
let logarithmic = near * (DISTANCE / near).powf(ratio);
let uniform = near.mul_add(1.0 - ratio, DISTANCE * ratio);
*far = SPLIT_LAMBDA.mul_add(logarithmic, (1.0 - SPLIT_LAMBDA) * uniform);
}
out
}
#[must_use]
pub fn new(camera: &Camera, to_light: Vec3) -> Self {
let to_light = to_light.normalize_or_zero();
assert!(
to_light.length_squared() > 0.0,
"the sun must point somewhere: {to_light:?} has no direction"
);
let eye = camera.eye;
assert!(eye.is_finite(), "the camera's eye is not finite: {eye:?}");
let near = match camera.projection {
crate::camera::Projection::Perspective { near, .. }
| crate::camera::Projection::Orthographic { near, .. } => near.max(f32::MIN_POSITIVE),
};
let splits = Self::splits(near);
let mut view_proj = [Mat4::IDENTITY; CASCADES];
for (index, matrix) in view_proj.iter_mut().enumerate() {
*matrix = cascade_matrix(eye, to_light, splits[index]);
}
let mut far = [splits[CASCADES - 1]; 4];
far[..CASCADES].copy_from_slice(&splits);
Self { view_proj, far }
}
#[must_use]
pub fn params() -> [f32; 4] {
let (width, height) = atlas_extent();
#[expect(
clippy::cast_precision_loss,
reason = "an atlas extent is a few thousand texels"
)]
let inverse = [1.0 / width as f32, 1.0 / height as f32];
[
inverse[0],
inverse[1],
r_shadow_bias.get_f32(),
r_shadow_normal_offset.get_f32(),
]
}
}
#[must_use]
pub const fn atlas_extent() -> (u32, u32) {
(TILE * ATLAS_COLUMNS, TILE * ATLAS_ROWS)
}
#[must_use]
pub const fn tile_origin(index: usize) -> (u32, u32) {
let index = index as u32;
(
TILE * (index % ATLAS_COLUMNS),
TILE * (index / ATLAS_COLUMNS),
)
}
#[must_use]
pub const fn light_tile(tile: usize) -> usize {
CASCADES + tile
}
#[must_use]
pub const fn tile_span(light: &Light) -> usize {
match light {
Light::Point(_) => POINT_FACES,
Light::Spot(_) => 1,
Light::Rect(_) => 0,
}
}
fn cascade_matrix(eye: Vec3, to_light: Vec3, radius: f32) -> Mat4 {
let up = if to_light.dot(Vec3::Y).abs() > 0.99 {
Vec3::Z
} else {
Vec3::Y
};
let view = glam::camera::rh::view::look_at_mat4(Vec3::ZERO, -to_light, up);
#[expect(
clippy::cast_precision_loss,
reason = "a tile is a few thousand texels"
)]
let texel = 2.0 * radius / TILE as f32;
let centre = snap_to_texel((view * eye.extend(1.0)).xyz(), texel);
let farthest = radius - centre.z;
let nearest = -centre.z - radius - CASTER_REACH;
glam::camera::rh::proj::directx::orthographic(
centre.x - radius,
centre.x + radius,
centre.y - radius,
centre.y + radius,
farthest,
nearest,
) * view
}
#[must_use]
pub fn spot_matrix(spot: &SpotLight) -> Mat4 {
let axis = spot.direction.normalize_or_zero();
assert!(
axis.length_squared() > 0.0,
"a spot must point somewhere: {:?} has no direction",
spot.direction
);
assert!(
spot.position.is_finite(),
"the spot's position is not finite: {:?}",
spot.position
);
let up = if axis.dot(Vec3::Y).abs() > 0.99 {
Vec3::Z
} else {
Vec3::Y
};
let view = glam::camera::rh::view::look_at_mat4(spot.position, spot.position + axis, up);
let outer = spot.outer_angle.max(spot.inner_angle);
let far = spot.radius.max(PUNCTUAL_NEAR * 2.0);
glam::camera::rh::proj::directx::perspective(
2.0 * outer,
1.0,
far,
PUNCTUAL_NEAR,
) * view
}
#[must_use]
pub fn face_axis(face: usize) -> Vec3 {
match face {
0 => Vec3::X,
1 => Vec3::NEG_X,
2 => Vec3::Y,
3 => Vec3::NEG_Y,
4 => Vec3::Z,
5 => Vec3::NEG_Z,
_ => panic!("a point light has {POINT_FACES} faces, not a face {face}"),
}
}
#[must_use]
pub fn point_matrix(point: &PointLight, face: usize) -> Mat4 {
assert!(
point.position.is_finite(),
"the point light's position is not finite: {:?}",
point.position
);
let axis = face_axis(face);
let up = if axis.y == 0.0 { Vec3::Y } else { Vec3::Z };
let view = glam::camera::rh::view::look_at_mat4(point.position, point.position + axis, up);
let far = point.radius.max(PUNCTUAL_NEAR * 2.0);
glam::camera::rh::proj::directx::perspective(
std::f32::consts::FRAC_PI_2,
1.0,
far,
PUNCTUAL_NEAR,
) * view
}
#[must_use]
pub fn point_frustum(point: &PointLight) -> Frustum {
let (centre, radius) = (point.position, point.radius);
Frustum {
planes: [
glam::Vec4::new(1.0, 0.0, 0.0, radius - centre.x),
glam::Vec4::new(-1.0, 0.0, 0.0, radius + centre.x),
glam::Vec4::new(0.0, 1.0, 0.0, radius - centre.y),
glam::Vec4::new(0.0, -1.0, 0.0, radius + centre.y),
glam::Vec4::new(0.0, 0.0, 1.0, radius - centre.z),
glam::Vec4::new(0.0, 0.0, -1.0, radius + centre.z),
],
}
}
fn can_be_shadowed(light: &Light) -> bool {
if light.is_fill() {
return false;
}
match light {
Light::Point(point) => point.radius > 0.0 && point.position.is_finite(),
Light::Spot(spot) => {
spot.radius > 0.0
&& spot.direction.normalize_or_zero().length_squared() > 0.0
&& spot.position.is_finite()
&& spot.outer_angle.max(spot.inner_angle) < MAX_SPOT_HALF_ANGLE
}
Light::Rect(_) => false,
}
}
fn map_extent(light: &Light) -> f32 {
match light {
Light::Point(point) => 2.0 * point.radius,
Light::Spot(spot) => {
let outer = spot.outer_angle.max(spot.inner_angle);
2.0 * spot.radius * outer.tan()
}
Light::Rect(_) => 0.0,
}
}
fn coverage(light: &Light, camera: &Camera) -> f32 {
let scale = camera.projection.pixels_per_unit(1.0);
let extent = map_extent(light);
if camera.projection.is_orthographic() {
return extent * scale;
}
let (position, _) = light.sphere();
extent * scale / camera.eye.distance(position).max(1e-4)
}
const HOLD_RATIO: f32 = 1.25;
const WHOLE_CELL_COVERAGE: f32 = 0.25;
const LEVEL_HOLD_RATIO: f32 = 0.8;
fn level_threshold(level: usize) -> f32 {
if level + 1 >= TILE_LEVELS {
return 0.0;
}
#[expect(
clippy::cast_precision_loss,
reason = "the guard above bounds the shift by TILE_LEVELS"
)]
let halvings = (1u32 << level) as f32;
WHOLE_CELL_COVERAGE / halvings
}
fn tile_level(coverage: f32, previous: Option<usize>) -> usize {
let mut level = previous.unwrap_or(TILE_LEVELS - 1).min(TILE_LEVELS - 1);
while level > 0 && coverage >= level_threshold(level - 1) {
level -= 1;
}
while level + 1 < TILE_LEVELS && coverage < level_threshold(level) * LEVEL_HOLD_RATIO {
level += 1;
}
level
}
fn run_is_free(used: &[bool; LIGHT_TILES], base: usize, span: usize) -> bool {
base + span <= LIGHT_TILES && used[base..base + span].iter().all(|tile| !*tile)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Assignment {
pub light: usize,
pub base: usize,
pub level: usize,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Selection {
slots: [Option<Assignment>; LIGHT_SLOTS],
allocator: AtlasAllocator,
tiles: [Option<Tile>; TILES],
rects: [TileRect; TILES],
}
impl Selection {
pub fn update(&mut self, lights: &[Light], camera: &Camera) {
let previous = self.slots;
let held_by = |index: usize| {
previous
.iter()
.flatten()
.find(|assignment| assignment.light == index)
};
let mut ranked: Vec<(usize, f32, f32)> = lights
.iter()
.enumerate()
.filter(|(_, light)| can_be_shadowed(light))
.map(|(index, light)| {
let coverage = coverage(light, camera);
let score = coverage
* if held_by(index).is_some() {
HOLD_RATIO
} else {
1.0
};
(index, score, coverage)
})
.collect();
ranked.sort_by(|left, right| right.1.total_cmp(&left.1).then(left.0.cmp(&right.0)));
let mut used = [false; LIGHT_TILES];
let mut chosen: Vec<Assignment> = Vec::with_capacity(LIGHT_SLOTS);
for (index, _, coverage) in ranked {
if chosen.len() == LIGHT_SLOTS {
break;
}
let span = tile_span(&lights[index]);
let Some(base) = held_by(index)
.map(|assignment| assignment.base)
.filter(|base| run_is_free(&used, *base, span))
.or_else(|| (0..LIGHT_TILES).find(|base| run_is_free(&used, *base, span)))
else {
continue;
};
for tile in &mut used[base..base + span] {
*tile = true;
}
let level = tile_level(coverage, held_by(index).map(|held| held.level));
chosen.push(Assignment {
light: index,
base,
level,
});
}
let mut slots = [None; LIGHT_SLOTS];
for assignment in &chosen {
if let Some(slot) = previous
.iter()
.position(|held| held.is_some_and(|held| held.light == assignment.light))
{
slots[slot] = Some(*assignment);
}
}
for assignment in &chosen {
if slots.contains(&Some(*assignment)) {
continue;
}
if let Some(free) = slots.iter_mut().find(|slot| slot.is_none()) {
*free = Some(*assignment);
}
}
self.slots = slots;
self.lay_out(lights);
}
fn lay_out(&mut self, lights: &[Light]) {
let mut wanted: [Option<usize>; TILES] = [None; TILES];
for want in &mut wanted[..CASCADES] {
*want = Some(0);
}
for assignment in self.slots.iter().flatten() {
let Some(light) = lights.get(assignment.light) else {
continue;
};
let span = tile_span(light);
for tile in assignment.base..assignment.base + span {
wanted[light_tile(tile)] = Some(assignment.level);
}
}
for (slot, want) in wanted.iter().enumerate() {
let Some(held) = self.tiles[slot] else {
continue;
};
if *want == Some(held.level()) {
continue;
}
self.allocator.release(held);
self.tiles[slot] = None;
self.rects[slot] = TileRect::EMPTY;
}
let mut requests = [(0usize, 0usize); TILES];
let mut count = 0;
for (slot, want) in wanted.iter().enumerate() {
let Some(level) = *want else {
continue;
};
if self.tiles[slot].is_some() {
continue;
}
requests[count] = (slot, level);
count += 1;
}
requests[..count].sort_by_key(|(_, level)| *level);
for &(slot, level) in &requests[..count] {
let tile = self.allocator.allocate(level).unwrap_or_else(|| {
unreachable!("a whole root cell per atlas slot, coarsest first")
});
self.tiles[slot] = Some(tile);
self.rects[slot] = tile.rect();
}
}
#[must_use]
pub const fn slots(&self) -> &[Option<Assignment>; LIGHT_SLOTS] {
&self.slots
}
#[must_use]
pub fn atlas_rect(&self, slot: usize) -> TileRect {
self.rects.get(slot).copied().unwrap_or(TileRect::EMPTY)
}
#[must_use]
pub fn atlas_rects(&self) -> [[f32; 4]; TILES] {
self.rects.map(TileRect::to_uv)
}
#[must_use]
pub fn base_of(&self, index: usize) -> Option<usize> {
self.slots
.iter()
.flatten()
.find(|assignment| assignment.light == index)
.map(|assignment| assignment.base)
}
}
fn snap_to_texel(position: Vec3, texel: f32) -> Vec3 {
if texel <= 0.0 || !texel.is_finite() {
return position;
}
(position / texel).floor() * texel
}
#[cfg(test)]
mod tests {
use super::*;
use crate::camera::Projection;
fn camera_at(eye: Vec3) -> Camera {
Camera {
eye,
target: eye + Vec3::NEG_Z,
..Camera::default()
}
}
const SUN: Vec3 = Vec3::new(0.4, 0.8, 0.6);
#[test]
fn the_splits_increase_and_end_at_the_shadow_distance() {
let splits = Cascades::splits(0.1);
assert!(
(splits[CASCADES - 1] - DISTANCE).abs() < 1e-4,
"the last split is the shadow distance: {splits:?}"
);
for window in splits.windows(2) {
assert!(
window[1] > window[0],
"the splits must increase: {splits:?}"
);
}
assert!(splits[0] > 0.0, "a cascade with no reach: {splits:?}");
}
#[test]
fn every_point_within_a_cascades_reach_lands_inside_its_box() {
let camera = camera_at(Vec3::new(3.0, 1.0, -2.0));
let cascades = Cascades::new(&camera, SUN);
for (index, matrix) in cascades.view_proj.iter().enumerate() {
let radius = cascades.far[index];
for direction in [
Vec3::X,
Vec3::NEG_X,
Vec3::Y,
Vec3::NEG_Y,
Vec3::Z,
Vec3::NEG_Z,
Vec3::ONE.normalize(),
] {
let point = camera.eye + direction * (radius * 0.98);
let clip = *matrix * point.extend(1.0);
let ndc = clip.xyz() / clip.w;
assert!(
ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0,
"cascade {index} does not cover {direction:?}: ndc {ndc:?}"
);
assert!(
(0.0..=1.0).contains(&ndc.z),
"cascade {index} puts {direction:?} outside its depth range: ndc {ndc:?}"
);
}
}
}
#[test]
fn a_caster_nearer_the_light_gets_the_larger_depth() {
let camera = camera_at(Vec3::ZERO);
let cascades = Cascades::new(&camera, SUN);
let to_light = SUN.normalize();
let matrix = cascades.view_proj[0];
let near_light = (matrix * (to_light * 2.0).extend(1.0)).z;
let far_light = (matrix * (to_light * -2.0).extend(1.0)).z;
assert!(
near_light > far_light,
"reversed-Z: {near_light} must exceed {far_light}"
);
}
#[test]
fn turning_on_the_spot_leaves_every_cascade_alone() {
let eye = Vec3::new(-2.0, 3.0, 5.0);
let looking_north = Cascades::new(&camera_at(eye), SUN);
let looking_east = Cascades::new(
&Camera {
eye,
target: eye + Vec3::X,
..Camera::default()
},
SUN,
);
assert_eq!(
looking_north, looking_east,
"a cascade must not depend on where the camera looks"
);
let orthographic = Cascades::new(
&camera_at(eye).with_projection(Projection::Orthographic {
half_height: 4.0,
near: 0.1,
far: 50.0,
}),
SUN,
);
assert_eq!(looking_north, orthographic);
}
#[test]
fn moving_less_than_one_texel_changes_nothing() {
let eye = Vec3::new(1.0, 2.0, 3.0);
let splits = Cascades::splits(0.1);
#[expect(
clippy::cast_precision_loss,
reason = "a tile is a few thousand texels"
)]
let texel = 2.0 * splits[0] / TILE as f32;
let still = Cascades::new(&camera_at(eye), SUN);
let nudged = Cascades::new(&camera_at(eye + Vec3::X * texel * 0.1), SUN);
assert_eq!(
still.view_proj[0], nudged.view_proj[0],
"a sub-texel move must snap to the same origin"
);
let moved = Cascades::new(&camera_at(eye + Vec3::X * texel * 40.0), SUN);
assert_ne!(
still.view_proj[0], moved.view_proj[0],
"the cascade must follow the camera at all"
);
}
#[test]
fn a_light_straight_overhead_still_produces_a_basis() {
let cascades = Cascades::new(&camera_at(Vec3::ZERO), Vec3::Y);
for (index, matrix) in cascades.view_proj.iter().enumerate() {
assert!(
matrix.to_cols_array().iter().all(|value| value.is_finite()),
"cascade {index} is not finite under an overhead sun: {matrix:?}"
);
}
let clip = cascades.view_proj[0] * Vec3::ZERO.extend(1.0);
let ndc = clip.xyz() / clip.w;
assert!(ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0 && (0.0..=1.0).contains(&ndc.z));
}
#[test]
fn every_tile_of_the_grid_has_an_origin_of_its_own() {
let (width, height) = atlas_extent();
assert_eq!(width, TILE * ATLAS_COLUMNS);
assert_eq!(height, TILE * ATLAS_ROWS);
let params = Cascades::params();
#[expect(clippy::cast_precision_loss, reason = "an extent is a few thousand")]
let expected = [1.0 / width as f32, 1.0 / height as f32];
assert!((params[0] - expected[0]).abs() < f32::EPSILON);
assert!((params[1] - expected[1]).abs() < f32::EPSILON);
assert!(params[2] > 0.0 && params[3] > 0.0, "the bias must bias");
let origins: Vec<(u32, u32)> = (0..TILES).map(tile_origin).collect();
for (index, origin) in origins.iter().enumerate() {
assert!(
origin.0 + TILE <= width && origin.1 + TILE <= height,
"tile {index} at {origin:?} runs off a {width}x{height} atlas"
);
assert_eq!(
origins.iter().filter(|other| *other == origin).count(),
1,
"tile {index}'s origin {origin:?} is shared with another tile"
);
}
for cascade in 0..CASCADES {
assert_eq!(tile_origin(cascade), (TILE * cascade as u32, 0));
}
for tile in 0..LIGHT_TILES {
assert!(light_tile(tile) >= CASCADES && light_tile(tile) < TILES);
}
}
fn spot_at(position: Vec3, direction: Vec3) -> SpotLight {
SpotLight {
position,
radius: 4.0,
color: Vec3::ONE,
direction,
inner_angle: 0.2,
outer_angle: 0.5,
fill: false,
}
}
#[test]
fn a_caster_nearer_a_spot_gets_the_larger_depth() {
let spot = spot_at(Vec3::new(0.0, 2.0, 0.0), Vec3::NEG_Y);
let matrix = spot_matrix(&spot);
let depth_at = |distance: f32| {
let point = spot.position + Vec3::NEG_Y * distance;
let clip = matrix * point.extend(1.0);
(clip.xyz() / clip.w).z
};
let near = depth_at(0.5);
let far = depth_at(3.0);
assert!(
near > far,
"reversed-Z: a caster at 0.5 stores {near} and one at 3.0 stores {far}"
);
assert!(
(depth_at(PUNCTUAL_NEAR) - 1.0).abs() < 1e-4,
"the near plane must store 1.0, got {}",
depth_at(PUNCTUAL_NEAR)
);
assert!(
depth_at(spot.radius).abs() < 1e-4,
"the radius must store 0.0, got {}",
depth_at(spot.radius)
);
for step in 1..40u8 {
let depth =
depth_at(PUNCTUAL_NEAR + (spot.radius - PUNCTUAL_NEAR) * f32::from(step) / 40.0);
assert!(
(0.0..=1.0).contains(&depth),
"a caster inside the cone stored {depth}, outside 0..1"
);
}
}
#[test]
fn a_spots_map_covers_its_cone_and_no_more() {
let spot = spot_at(Vec3::new(1.0, 2.0, -1.0), Vec3::new(0.0, -1.0, 0.0));
let matrix = spot_matrix(&spot);
let ndc_of = |point: Vec3| {
let clip = matrix * point.extend(1.0);
clip.xyz() / clip.w
};
let drop = 1.0;
let edge = spot.outer_angle.tan() * drop;
let on_edge = ndc_of(spot.position + Vec3::new(edge, -drop, 0.0));
assert!(
(on_edge.x.abs() - 1.0).abs() < 1e-3,
"the cone's edge must land on the frustum's, got {on_edge:?}"
);
let inside = ndc_of(spot.position + Vec3::new(edge * 0.5, -drop, 0.0));
assert!(inside.x.abs() < 1.0 && inside.y.abs() < 1.0, "{inside:?}");
let outside = ndc_of(spot.position + Vec3::new(edge * 1.5, -drop, 0.0));
assert!(outside.x.abs() > 1.0, "{outside:?}");
let behind = matrix * (spot.position + Vec3::Y).extend(1.0);
assert!(
behind.w <= 0.0,
"a point behind the spot has w {}",
behind.w
);
}
#[test]
fn a_spot_pointing_straight_down_still_produces_a_basis() {
let matrix = spot_matrix(&spot_at(Vec3::new(0.0, 3.0, 0.0), Vec3::NEG_Y));
assert!(
matrix.to_cols_array().iter().all(|value| value.is_finite()),
"a spot pointing down produced {matrix:?}"
);
let clip = matrix * Vec3::ZERO.extend(1.0);
let ndc = clip.xyz() / clip.w;
assert!(ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0 && (0.0..=1.0).contains(&ndc.z));
}
#[test]
fn a_still_spot_produces_the_same_matrix() {
let spot = spot_at(Vec3::new(0.5, 2.0, -1.5), Vec3::new(0.2, -1.0, 0.1));
assert_eq!(spot_matrix(&spot), spot_matrix(&spot));
let mut moved = spot;
moved.position.x += 0.5;
assert_ne!(spot_matrix(&spot), spot_matrix(&moved));
}
fn point_at(position: Vec3, radius: f32) -> PointLight {
PointLight {
position,
radius,
color: Vec3::ONE,
fill: false,
}
}
fn inside(matrix: Mat4, point: Vec3) -> bool {
let clip = matrix * point.extend(1.0);
if clip.w <= 0.0 {
return false;
}
let ndc = clip.xyz() / clip.w;
ndc.x.abs() <= 1.0 && ndc.y.abs() <= 1.0 && (0.0..=1.0).contains(&ndc.z)
}
#[test]
fn every_face_of_a_point_light_covers_its_own_direction_and_no_other() {
let light = point_at(Vec3::new(0.5, -1.0, 2.0), 4.0);
let convention = [
(0, Vec3::X),
(1, Vec3::NEG_X),
(2, Vec3::Y),
(3, Vec3::NEG_Y),
(4, Vec3::Z),
(5, Vec3::NEG_Z),
];
assert_eq!(
convention.len(),
POINT_FACES,
"the convention below has to name every face there is"
);
for (face, axis) in convention {
let towards = light.position + axis * 2.0;
for other in 0..POINT_FACES {
let matrix = point_matrix(&light, other);
assert_eq!(
inside(matrix, towards),
other == face,
"a caster at {towards:?} is {axis:?} of the light, which is face {face}, \
and face {other}'s matrix {} it",
if other == face {
"does not cover"
} else {
"covers"
}
);
}
}
}
#[test]
fn the_six_faces_between_them_cover_every_direction() {
let light = point_at(Vec3::new(-2.0, 0.5, 1.0), 6.0);
let matrices: Vec<Mat4> = (0..POINT_FACES)
.map(|face| point_matrix(&light, face))
.collect();
for step in 0..512u32 {
let fraction = (f64::from(step) + 0.5) / 512.0;
let z = 1.0 - 2.0 * fraction;
let radius = (1.0 - z * z).max(0.0).sqrt();
let angle = std::f64::consts::PI * (3.0 - 5.0f64.sqrt()) * f64::from(step);
#[expect(clippy::cast_possible_truncation, reason = "a direction is an f32")]
let direction = Vec3::new(
(radius * angle.cos()) as f32,
(radius * angle.sin()) as f32,
z as f32,
);
let caster = light.position + direction * 3.0;
let covered = matrices
.iter()
.filter(|matrix| inside(**matrix, caster))
.count();
assert!(
covered >= 1,
"no face covers a caster {direction:?} from the light, so a shadow cast that \
way would be missing"
);
}
}
#[test]
fn a_caster_nearer_a_point_lights_face_gets_the_larger_depth() {
let light = point_at(Vec3::new(0.0, 2.0, 0.0), 4.0);
for face in 0..POINT_FACES {
let matrix = point_matrix(&light, face);
let depth_at = |distance: f32| {
let clip = matrix * (light.position + face_axis(face) * distance).extend(1.0);
(clip.xyz() / clip.w).z
};
let near = depth_at(0.5);
let far = depth_at(3.0);
assert!(
near > far,
"reversed-Z on face {face}: a caster at 0.5 stores {near} and one at 3.0 \
stores {far}"
);
assert!(
(depth_at(PUNCTUAL_NEAR) - 1.0).abs() < 1e-4,
"face {face}'s near plane must store 1.0, got {}",
depth_at(PUNCTUAL_NEAR)
);
assert!(
depth_at(light.radius).abs() < 1e-4,
"face {face}'s radius must store 0.0, got {}",
depth_at(light.radius)
);
}
}
#[test]
fn the_faces_that_look_along_y_still_produce_a_basis() {
let light = point_at(Vec3::new(0.0, 3.0, 0.0), 5.0);
for face in 0..POINT_FACES {
let matrix = point_matrix(&light, face);
assert!(
matrix.to_cols_array().iter().all(|value| value.is_finite()),
"face {face} produced {matrix:?}"
);
}
assert!(inside(point_matrix(&light, 3), Vec3::ZERO));
}
#[test]
fn a_still_point_light_produces_the_same_matrices() {
let light = point_at(Vec3::new(0.5, 2.0, -1.5), 4.0);
for face in 0..POINT_FACES {
assert_eq!(point_matrix(&light, face), point_matrix(&light, face));
}
let mut moved = light;
moved.position.x += 0.5;
assert_ne!(point_matrix(&light, 0), point_matrix(&moved, 0));
}
#[test]
fn a_point_lights_cull_keeps_what_is_inside_its_radius() {
let light = point_at(Vec3::new(1.0, 2.0, -3.0), 4.0);
let frustum = point_frustum(&light);
for face in 0..POINT_FACES {
let axis = face_axis(face);
let near = crate::cull::Aabb {
min: light.position + axis - Vec3::splat(0.1),
max: light.position + axis + Vec3::splat(0.1),
};
assert!(
frustum.intersects(&near),
"a caster a unit along face {face} is inside the light's reach"
);
let beyond = crate::cull::Aabb {
min: light.position + axis * 12.0 - Vec3::splat(0.1),
max: light.position + axis * 12.0 + Vec3::splat(0.1),
};
assert!(
!frustum.intersects(&beyond),
"a caster three radii along face {face} cannot shadow anything this light lights"
);
}
}
fn spot_light_at(position: Vec3, radius: f32) -> Light {
Light::Spot(SpotLight {
position,
radius,
color: Vec3::ONE,
direction: Vec3::NEG_Y,
inner_angle: 0.2,
outer_angle: 0.5,
fill: false,
})
}
const fn held(light: usize, base: usize) -> Option<Assignment> {
Some(Assignment {
light,
base,
level: 0,
})
}
#[test]
fn the_tiles_go_to_the_largest_projected_influence() {
let eye = Vec3::ZERO;
let lights = [
spot_light_at(Vec3::new(0.0, 0.0, -1.0), 0.5),
spot_light_at(Vec3::new(0.0, 0.0, -4.0), 8.0),
spot_light_at(Vec3::new(0.0, 0.0, -2.0), 3.0),
spot_light_at(Vec3::new(0.0, 0.0, -5.0), 5.0),
spot_light_at(Vec3::new(0.0, 0.0, -3.0), 2.25),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(eye));
assert_eq!(
selection.slots(),
&[held(1, 0), held(2, 1), held(3, 2), held(4, 3)],
"the largest influences take the slots and the first tiles, in rank order"
);
assert_eq!(selection.base_of(1), Some(0));
assert_eq!(selection.base_of(2), Some(1));
assert_eq!(selection.base_of(3), Some(2));
assert_eq!(selection.base_of(4), Some(3));
assert_eq!(
selection.base_of(0),
None,
"the light past the budget gets no tile — it still lights, it just \
does not occlude"
);
}
#[test]
fn an_exact_tie_breaks_by_index() {
let lights = [
spot_light_at(Vec3::new(3.0, 0.0, 0.0), 1.0),
spot_light_at(Vec3::new(-3.0, 0.0, 0.0), 1.0),
spot_light_at(Vec3::new(0.0, 3.0, 0.0), 1.0),
spot_light_at(Vec3::new(0.0, -3.0, 0.0), 1.0),
spot_light_at(Vec3::new(0.0, 0.0, 3.0), 1.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(0, 0), held(1, 1), held(2, 2), held(3, 3)]
);
assert_eq!(
selection.base_of(4),
None,
"the last light of an all-way tie is the one that loses it"
);
}
#[test]
fn an_incumbent_keeps_its_tile_until_a_challenger_clearly_beats_it() {
let contender = |influence: f32| spot_light_at(Vec3::new(0.0, 0.0, -1.0), influence);
let mut lights = [
contender(5.0),
contender(4.0),
contender(3.0),
contender(2.0),
contender(1.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(0, 0), held(1, 1), held(2, 2), held(3, 3)]
);
lights[4] = contender(2.1);
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(0, 0), held(1, 1), held(2, 2), held(3, 3)],
"a challenger 5% ahead must not take a held tile"
);
lights[4] = contender(2.0 * HOLD_RATIO + 0.1);
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(0, 0), held(1, 1), held(2, 2), held(4, 3)],
"a challenger past the hold ratio must take the tile"
);
}
#[test]
fn a_light_with_no_map_is_refused_a_tile_and_the_next_one_takes_it() {
let mut wide = spot_light_at(Vec3::new(0.0, 0.0, -1.0), 10.0);
if let Light::Spot(spot) = &mut wide {
spot.outer_angle = MAX_SPOT_HALF_ANGLE + 0.01;
}
let lights = [
Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 0.0)),
wide,
spot_light_at(Vec3::new(0.0, 0.0, -2.0), 1.0),
spot_light_at(Vec3::new(0.0, 0.0, -3.0), 1.0),
spot_light_at(Vec3::new(0.0, 0.0, -4.0), 1.0),
spot_light_at(Vec3::new(0.0, 0.0, -5.0), 1.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(2, 0), held(3, 1), held(4, 2), held(5, 3)],
"the two brightest are ineligible, so the tiles go to the ones that are"
);
}
#[test]
fn a_fill_light_is_refused_a_tile_where_the_same_light_takes_one() {
let point = point_at(Vec3::new(0.0, 0.0, -2.0), 4.0);
let spot = spot_at(Vec3::new(0.0, 0.0, -2.0), Vec3::NEG_Y);
let pairs = [
(
"point",
Light::Point(point),
Light::Point(PointLight {
fill: true,
..point
}),
),
(
"spot",
Light::Spot(spot),
Light::Spot(SpotLight { fill: true, ..spot }),
),
];
for (kind, casting, filling) in pairs {
let mut selection = Selection::default();
selection.update(&[casting], &camera_at(Vec3::ZERO));
assert_eq!(
selection.base_of(0),
Some(0),
"a {kind} light that is not fill must take the first tile, or \
the refusal below would pass against a build that shadows \
nothing"
);
let mut selection = Selection::default();
selection.update(&[filling], &camera_at(Vec3::ZERO));
assert_eq!(
selection.base_of(0),
None,
"a fill {kind} light lights without occluding, so it is handed \
no tile at all"
);
}
}
#[test]
fn a_point_light_and_a_spot_behind_it_are_both_shadowed() {
let lights = [
Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0)),
spot_light_at(Vec3::new(0.0, 0.0, -2.0), 1.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(0, 0), held(1, POINT_FACES), None, None],
"the point light's cube is the first {POINT_FACES} tiles and the spot's map is \
the one after it"
);
assert_eq!(selection.base_of(0), Some(0));
assert_eq!(selection.base_of(1), Some(POINT_FACES));
}
#[test]
fn two_point_lights_are_both_shadowed() {
let lights = [
Light::Point(point_at(Vec3::new(-2.0, 0.0, -1.0), 4.0)),
Light::Point(point_at(Vec3::new(2.0, 0.0, -1.0), 4.0)),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[held(0, 0), held(1, POINT_FACES), None, None],
"the first cube takes the first {POINT_FACES} tiles and the second the \
{POINT_FACES} after it"
);
for light in 0..lights.len() {
let base = selection
.base_of(light)
.unwrap_or_else(|| panic!("point light {light} was given no run"));
assert!(
base + POINT_FACES <= LIGHT_TILES,
"point light {light}'s run starts at {base}, which `mesh.slang` refuses: \
its faces run off the end of a {LIGHT_TILES}-tile region"
);
}
}
#[test]
fn a_point_light_that_cannot_fit_leaves_the_lights_around_it_alone() {
let lights = [
Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0)),
Light::Point(point_at(Vec3::new(0.0, 0.0, -2.0), 6.0)),
Light::Point(point_at(Vec3::new(0.0, 0.0, -4.0), 2.0)),
spot_light_at(Vec3::new(0.0, 0.0, -3.0), 1.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(
selection.slots(),
&[
held(0, 0),
held(1, POINT_FACES),
held(3, 2 * POINT_FACES),
None
],
"two cubes fill the region but for what is left of it, the third point light \
does not fit in that, and the spot ranked behind it still takes a tile of it"
);
assert_eq!(
selection.base_of(2),
None,
"the third cube has nowhere to go"
);
}
#[test]
fn no_two_lights_are_ever_given_the_same_tile() {
let spot = spot_light_at(Vec3::new(0.0, 0.0, -1.0), 4.0);
let other = spot_light_at(Vec3::new(0.0, 0.0, -2.0), 2.0);
let point = Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0));
let mut selection = Selection::default();
for lights in [
vec![spot, other],
vec![point, other],
vec![other, point],
vec![point],
vec![spot, other, point],
vec![point, point, point],
vec![point, spot, point, other, point],
] {
selection.update(&lights, &camera_at(Vec3::ZERO));
let mut used = [false; LIGHT_TILES];
for assignment in selection.slots().iter().flatten() {
let span = tile_span(&lights[assignment.light]);
assert!(
assignment.base + span <= LIGHT_TILES,
"light {} runs off the end of the region from {}",
assignment.light,
assignment.base
);
for tile in &mut used[assignment.base..assignment.base + span] {
assert!(!*tile, "two lights hold one tile: {:?}", selection.slots());
*tile = true;
}
}
}
}
fn distance_for(wanted: f32, light: &Light, camera: &Camera) -> f32 {
map_extent(light) * camera.projection.pixels_per_unit(1.0) / wanted
}
fn spot_covering(wanted: f32, camera: &Camera) -> Light {
let template = spot_light_at(Vec3::ZERO, 1.0);
let distance = distance_for(wanted, &template, camera);
spot_light_at(Vec3::new(0.0, 0.0, -distance), 1.0)
}
#[test]
fn a_light_with_no_history_lands_where_the_sharp_ladder_puts_it() {
for numerator in 1..=512u32 {
let coverage = f32::from(u16::try_from(numerator).expect("a small count")) / 512.0;
let sharp = (0..TILE_LEVELS)
.find(|level| coverage >= level_threshold(*level))
.unwrap_or(TILE_LEVELS - 1);
assert_eq!(
tile_level(coverage, None),
sharp,
"a coverage of {coverage} with no history"
);
}
}
#[test]
fn a_light_on_a_threshold_holds_its_tile_size_until_it_clearly_crosses() {
let inside_band = WHOLE_CELL_COVERAGE * (1.0 + LEVEL_HOLD_RATIO) / 2.0;
let past_band = WHOLE_CELL_COVERAGE * LEVEL_HOLD_RATIO * 0.95;
assert!(
past_band < WHOLE_CELL_COVERAGE * LEVEL_HOLD_RATIO && inside_band < WHOLE_CELL_COVERAGE,
"both excursions must be below the threshold, or the test is about the grow walk"
);
assert_eq!(tile_level(inside_band, Some(0)), 0);
assert_eq!(tile_level(past_band, Some(0)), 1);
assert_eq!(tile_level(inside_band, Some(1)), 1);
assert_eq!(tile_level(WHOLE_CELL_COVERAGE, Some(1)), 0);
}
#[test]
fn the_tile_size_falls_with_the_coverage() {
let camera = camera_at(Vec3::ZERO);
let lights: Vec<Light> = (0..TILE_LEVELS)
.map(|level| {
let wanted = if level + 1 == TILE_LEVELS {
level_threshold(level - 1) * 0.5
} else {
level_threshold(level) * 1.5
};
spot_covering(wanted, &camera)
})
.collect();
let mut selection = Selection::default();
selection.update(&lights, &camera);
for (level, _) in lights.iter().enumerate() {
let base = selection
.base_of(level)
.unwrap_or_else(|| panic!("light {level} was given no tile"));
let rect = selection.atlas_rect(light_tile(base));
assert_eq!(
rect.side,
TILE >> level,
"light {level} was laid out at {rect:?}, not the level-{level} tile its \
coverage earned"
);
}
let (width, height) = atlas_extent();
let mut covered = vec![false; (width * height) as usize];
for slot in 0..TILES {
let rect = selection.atlas_rect(slot);
for row in rect.y..rect.y + rect.side {
for column in rect.x..rect.x + rect.side {
let texel = (row * width + column) as usize;
assert!(
!covered[texel],
"texel ({column}, {row}) is in slot {slot}'s {rect:?} and in a \
slot laid out before it"
);
covered[texel] = true;
}
}
}
}
#[test]
fn a_moving_light_keeps_its_tile_size_across_a_small_excursion() {
let camera = camera_at(Vec3::ZERO);
let inside_band = WHOLE_CELL_COVERAGE * (1.0 + LEVEL_HOLD_RATIO) / 2.0;
let past_band = WHOLE_CELL_COVERAGE * LEVEL_HOLD_RATIO * 0.95;
let mut selection = Selection::default();
let side = |selection: &Selection| {
selection
.atlas_rect(light_tile(selection.base_of(0).expect("a tile")))
.side
};
selection.update(
&[spot_covering(WHOLE_CELL_COVERAGE * 2.0, &camera)],
&camera,
);
assert_eq!(
side(&selection),
TILE,
"a light well over the anchor is a whole cell"
);
selection.update(&[spot_covering(inside_band, &camera)], &camera);
assert_eq!(
side(&selection),
TILE,
"a light that drifted under the threshold but not out of the band must keep \
the tile it had"
);
selection.update(&[spot_covering(past_band, &camera)], &camera);
assert_eq!(
side(&selection),
TILE >> 1,
"a light clearly under the threshold must take the halving"
);
selection.update(&[spot_covering(inside_band, &camera)], &camera);
assert_eq!(
side(&selection),
TILE >> 1,
"coming back inside the band is not reaching the threshold, so the tile stays \
halved — the half of the band a one-sided test would miss"
);
selection.update(&[spot_covering(WHOLE_CELL_COVERAGE, &camera)], &camera);
assert_eq!(
side(&selection),
TILE,
"reaching the threshold outright takes the whole cell back"
);
}
#[test]
fn a_narrow_cone_outscores_a_wide_one_of_the_same_reach() {
let camera = camera_at(Vec3::ZERO);
let at = Vec3::new(0.0, 0.0, -4.0);
let mut narrow = spot_light_at(at, 1.0);
if let Light::Spot(spot) = &mut narrow {
spot.inner_angle = 0.05;
spot.outer_angle = 0.1;
}
let wide = spot_light_at(at, 1.0);
assert!(
coverage(&narrow, &camera) < coverage(&wide, &camera),
"a cone covering less of the frame must score below a wider one at the same reach"
);
assert_eq!(narrow.sphere().1, wide.sphere().1);
}
#[test]
fn a_slot_with_no_map_hands_the_shader_a_rectangle_of_zeros() {
assert_eq!(
TileRect::EMPTY.to_uv(),
[0.0; 4],
"an empty slot's rectangle is what `mesh.slang`'s `atlas_rect_is_empty` tests, and \
it tests `x` against zero"
);
let mut selection = Selection::default();
selection.update(&[], &camera_at(Vec3::ZERO));
for tile in 0..LIGHT_TILES {
assert_eq!(
selection.atlas_rect(light_tile(tile)).to_uv(),
[0.0; 4],
"light tile {tile} of a frame with no shadowed light must read as empty"
);
}
for level in 0..TILE_LEVELS {
let mut allocator = AtlasAllocator::new();
let tile = allocator
.allocate(level)
.unwrap_or_else(|| panic!("an empty atlas has room for a level-{level} tile"));
assert!(
tile.rect().to_uv()[0] > 0.0,
"a level-{level} tile reads as an empty slot, so `mesh.slang` would answer lit \
through a map that was rendered"
);
}
}
#[test]
fn a_still_frame_keeps_the_texels_the_last_one_drew_into() {
let camera = camera_at(Vec3::ZERO);
let lights = [
Light::Point(point_at(Vec3::new(0.0, 0.0, -3.0), 4.0)),
spot_light_at(Vec3::new(0.0, 0.0, -2.0), 2.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera);
let first: Vec<TileRect> = (0..TILES).map(|slot| selection.atlas_rect(slot)).collect();
assert!(
first[..CASCADES].iter().all(|rect| rect.side == TILE),
"the cascades must hold whole cells for this to be about the lights: {first:?}"
);
for round in 0..4 {
selection.update(&lights, &camera);
let again: Vec<TileRect> = (0..TILES).map(|slot| selection.atlas_rect(slot)).collect();
assert_eq!(
again, first,
"round {round} moved a map that nothing asked to move"
);
}
let mut fresh = Selection::default();
fresh.update(&lights, &camera);
assert_eq!(
selection, fresh,
"a selection that has held its tiles for five frames must hold exactly what one \
that has just laid them out holds — allocator included, or the atlas is drifting \
towards a layout no golden was blessed under"
);
}
#[test]
fn a_light_that_leaves_hands_every_tile_it_held_back() {
let camera = camera_at(Vec3::ZERO);
let spot = spot_light_at(Vec3::new(0.0, 0.0, -1.0), 4.0);
let other = spot_light_at(Vec3::new(0.0, 0.0, -2.0), 2.0);
let point = Light::Point(point_at(Vec3::new(0.0, 0.0, -1.0), 4.0));
let mut selection = Selection::default();
for lights in [
vec![spot, other],
vec![point, other],
vec![point],
vec![],
vec![spot, other, point],
vec![point, point, point],
vec![spot_covering(WHOLE_CELL_COVERAGE / 8.0, &camera)],
vec![point, spot, point, other, point],
] {
selection.update(&lights, &camera);
}
selection.update(&[], &camera);
let mut fresh = Selection::default();
fresh.update(&[], &camera);
assert_eq!(
selection, fresh,
"the atlas is not back where it started after every light left it"
);
}
#[test]
fn demoting_one_light_leaves_the_maps_around_it_where_they_were() {
let camera = camera_at(Vec3::ZERO);
let near = spot_covering(WHOLE_CELL_COVERAGE * 4.0, &camera);
let steady = spot_covering(WHOLE_CELL_COVERAGE * 2.0, &camera);
let mut selection = Selection::default();
selection.update(&[near, steady], &camera);
assert_eq!(
selection.base_of(0),
Some(0),
"the brighter light must hold the first run for this to be about the reordering"
);
let before = selection.atlas_rect(light_tile(1));
assert_eq!(
before.side, TILE,
"the steady light must start on a whole cell"
);
selection.update(
&[spot_covering(WHOLE_CELL_COVERAGE / 8.0, &camera), steady],
&camera,
);
assert!(
selection.atlas_rect(light_tile(0)).side < TILE,
"the first light did not demote, so nothing reordered"
);
assert_eq!(
selection.atlas_rect(light_tile(1)),
before,
"the steady light\'s map moved because its neighbour demoted"
);
}
#[test]
fn a_demoted_light_gives_its_cell_back_and_can_take_it_again() {
let camera = camera_at(Vec3::ZERO);
let near = [spot_covering(WHOLE_CELL_COVERAGE * 2.0, &camera)];
let far = [spot_covering(WHOLE_CELL_COVERAGE / 8.0, &camera)];
let tile = |selection: &Selection| selection.atlas_rect(light_tile(0)).side;
let mut selection = Selection::default();
selection.update(&near, &camera);
assert_eq!(
tile(&selection),
TILE,
"a near light must earn a whole cell"
);
selection.update(&far, &camera);
let demoted = tile(&selection);
assert!(
demoted < TILE,
"the far light kept a whole cell, so this test is not about a demotion"
);
selection.update(&near, &camera);
assert_eq!(
tile(&selection),
TILE,
"the cell the demotion released did not come back whole"
);
let mut fresh = Selection::default();
fresh.update(&near, &camera);
assert_eq!(
selection, fresh,
"a round trip down the ladder and back left the atlas fragmented"
);
}
#[test]
fn an_incumbent_that_leaves_the_list_frees_its_tile() {
let lights = [
spot_light_at(Vec3::new(0.0, 0.0, -1.0), 1.0),
spot_light_at(Vec3::new(0.0, 0.0, -2.0), 1.0),
];
let mut selection = Selection::default();
selection.update(&lights, &camera_at(Vec3::ZERO));
assert_eq!(selection.slots(), &[held(0, 0), held(1, 1), None, None]);
selection.update(&lights[..1], &camera_at(Vec3::ZERO));
assert_eq!(selection.slots(), &[held(0, 0), None, None, None]);
selection.update(&[], &camera_at(Vec3::ZERO));
assert_eq!(selection.slots(), &[None; LIGHT_SLOTS]);
}
#[test]
fn the_variable_names_are_the_filters_labels() {
let crcbl_console::Kind::Enum(names) = r_shadow_filter.kind() else {
panic!("`r_shadow_filter` is an enum variable");
};
let labels: Vec<&str> = FILTERS.into_iter().map(Filter::label).collect();
assert_eq!(names, labels.as_slice());
assert_eq!(
labels.as_slice(),
crcbl_shaders::mesh::SHADOW_FILTERS.as_slice(),
"the shader numbers its `SHADOW_FILTER_*` constants by position in its own list, \
so a set that differs here is a mode the fragment reads as another filter"
);
for filter in Filter::ALL {
assert_eq!(Filter::from_name(filter.label()), Some(filter));
}
assert_eq!(Filter::from_name("soft"), None);
for (mode, filter) in FILTERS.into_iter().enumerate() {
assert_eq!(
filter.mode() as usize,
mode,
"`{}` is the shader's mode {}, not {mode}",
filter.label(),
filter.mode()
);
}
}
#[test]
fn the_seams_other_side_is_the_filter_that_ships() {
use crcbl_console::Value;
let _guard = FILTER_SWITCH
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let before = r_shadow_filter.get_enum();
assert_eq!(
filter(),
Filter::Pcss,
"a frame nobody has touched the console on must sample through the filter every \
golden in this workspace was blessed under"
);
let shipped_before = shipped_filter();
r_shadow_filter
.set(&Value::Enum(Filter::Box.label()))
.expect("a writable enum in the set");
assert_eq!(
filter(),
Filter::Box,
"the getter did not follow the console"
);
assert_eq!(
shipped_filter(),
shipped_before,
"the shipped filter moved when the console did, so the seam compares a filter \
against itself"
);
assert_ne!(
shipped_filter(),
filter(),
"the shipped filter is what the console holds, so both sides of the seam run one \
kernel"
);
r_shadow_filter
.set(&Value::Enum(before))
.expect("putting the filter back");
}
#[test]
fn a_seam_at_either_edge_is_no_comparison() {
use crcbl_console::Value;
let _guard = FILTER_SWITCH
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let before = r_shadow_split.get_f32();
assert_eq!(
split_at(),
None,
"a frame nobody has touched the console on must draw one filter over the whole \
target, which is what every golden in this workspace was blessed as"
);
for (at, wanted) in [
(0.0, None),
(1.0, None),
(0.5, Some(0.5)),
(0.25, Some(0.25)),
] {
r_shadow_split
.set(&Value::Float(at))
.expect("a writable float in range");
assert_eq!(split_at(), wanted, "a seam asked for at {at}");
}
r_shadow_split
.set(&Value::Float(before))
.expect("putting the seam back");
}
}