use super::{TILE, TILES, atlas_extent, tile_origin};
pub const TILE_LEVELS: usize = 4;
pub const MIN_TILE: u32 = TILE >> (TILE_LEVELS - 1);
const _: () = assert!(
MIN_TILE > 0,
"a tile of no texels is a shadow map with nothing in it; the atlas has \
fewer halvings in it than TILE_LEVELS asks for"
);
const _: () = assert!(
TILE.is_multiple_of(1u32 << (TILE_LEVELS - 1)),
"every halving of a tile has to be a whole number of texels, or the \
rectangles the allocator hands out do not tile the cell they came from"
);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct TileRect {
pub x: u32,
pub y: u32,
pub side: u32,
}
impl TileRect {
pub const EMPTY: Self = Self {
x: 0,
y: 0,
side: 0,
};
#[must_use]
pub fn to_uv(self) -> [f32; 4] {
let (width, height) = atlas_extent();
#[expect(
clippy::cast_precision_loss,
reason = "an atlas extent is a few thousand texels"
)]
let (width, height) = (width as f32, height as f32);
#[expect(
clippy::cast_precision_loss,
reason = "a tile's origin and side are inside that extent"
)]
let (x, y, side) = (self.x as f32, self.y as f32, self.side as f32);
[side / width, side / height, x / width, y / height]
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Tile {
level: usize,
node: usize,
}
impl Tile {
#[must_use]
pub const fn level(self) -> usize {
self.level
}
#[must_use]
pub const fn side(self) -> u32 {
TILE >> self.level
}
#[must_use]
pub fn rect(self) -> TileRect {
let (root, column, row) = decompose(self.level, self.node);
let (origin_x, origin_y) = tile_origin(root);
let side = self.side();
TileRect {
x: origin_x + column * side,
y: origin_y + row * side,
side,
}
}
}
const fn nodes_at(level: usize) -> usize {
TILES << (2 * level)
}
fn decompose(level: usize, node: usize) -> (usize, u32, u32) {
let across = 1usize << level;
let root = node / (across * across);
let inside = node % (across * across);
#[expect(
clippy::cast_possible_truncation,
reason = "a column or row inside a root is at most 2^(TILE_LEVELS - 1)"
)]
let (column, row) = ((inside % across) as u32, (inside / across) as u32);
(root, column, row)
}
fn compose(level: usize, root: usize, column: u32, row: u32) -> usize {
let across = 1usize << level;
root * across * across + row as usize * across + column as usize
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum Node {
#[default]
Absent,
Free,
Taken,
Split,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AtlasAllocator {
nodes: Vec<Vec<Node>>,
}
impl Default for AtlasAllocator {
fn default() -> Self {
Self::new()
}
}
impl AtlasAllocator {
#[must_use]
pub fn new() -> Self {
Self {
nodes: (0..TILE_LEVELS)
.map(|level| {
let state = if level == 0 { Node::Free } else { Node::Absent };
vec![state; nodes_at(level)]
})
.collect(),
}
}
pub fn allocate(&mut self, level: usize) -> Option<Tile> {
let node = self.free_node(level)?;
self.nodes[level][node] = Node::Taken;
Some(Tile { level, node })
}
pub fn release(&mut self, tile: Tile) {
let mut level = tile.level;
let mut node = tile.node;
self.nodes[level][node] = Node::Free;
while level > 0 {
let (root, column, row) = decompose(level, node);
let (parent_column, parent_row) = (column / 2, row / 2);
let siblings = [
(parent_column * 2, parent_row * 2),
(parent_column * 2 + 1, parent_row * 2),
(parent_column * 2, parent_row * 2 + 1),
(parent_column * 2 + 1, parent_row * 2 + 1),
];
if !siblings.iter().all(|&(column, row)| {
self.nodes[level][compose(level, root, column, row)] == Node::Free
}) {
break;
}
for &(column, row) in &siblings {
let sibling = compose(level, root, column, row);
self.nodes[level][sibling] = Node::Absent;
}
let parent = compose(level - 1, root, parent_column, parent_row);
self.nodes[level - 1][parent] = Node::Free;
level -= 1;
node = parent;
}
}
fn free_node(&mut self, level: usize) -> Option<usize> {
if level >= TILE_LEVELS {
return None;
}
if let Some(node) = self.nodes[level]
.iter()
.position(|node| *node == Node::Free)
{
return Some(node);
}
if level == 0 {
return None;
}
let parent = self.free_node(level - 1)?;
let (root, column, row) = decompose(level - 1, parent);
self.nodes[level - 1][parent] = Node::Split;
for (across, down) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let child = compose(level, root, column * 2 + across, row * 2 + down);
self.nodes[level][child] = Node::Free;
}
Some(compose(level, root, column * 2, row * 2))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::shadow::{ATLAS_COLUMNS, ATLAS_ROWS};
#[test]
fn a_quadtree_hands_out_four_sizes_that_do_not_overlap() {
let mut allocator = AtlasAllocator::new();
let (width, height) = atlas_extent();
let mut covered = vec![false; (width * height) as usize];
let mut handed_out = 0usize;
let mut area = 0u64;
for _ in 0..2 {
for level in 0..TILE_LEVELS {
let tile = allocator
.allocate(level)
.unwrap_or_else(|| panic!("an empty atlas has room for a level-{level} tile"));
let rect = tile.rect();
assert_eq!(rect.side, TILE >> level, "a level-{level} tile's side");
assert!(
rect.x + rect.side <= width && rect.y + rect.side <= height,
"{rect:?} runs off an atlas of {width}x{height}"
);
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 {rect:?} and in a tile handed out \
before it"
);
covered[texel] = true;
}
}
handed_out += 1;
area += u64::from(rect.side) * u64::from(rect.side);
}
}
assert_eq!(
handed_out,
2 * TILE_LEVELS,
"the loop above stopped handing out tiles"
);
assert_eq!(
area,
covered.iter().filter(|texel| **texel).count() as u64,
"the tiles' areas and the texels they covered disagree, so two of them \
overlapped or one was counted twice"
);
}
#[test]
fn a_released_tile_s_space_is_reusable_at_its_own_size() {
let mut allocator = AtlasAllocator::new();
let quarters: Vec<Tile> = (0..4)
.map(|index| {
allocator
.allocate(1)
.unwrap_or_else(|| panic!("an empty atlas has room for quarter {index}"))
})
.collect();
let root = quarters[0].rect();
for quarter in &quarters {
let rect = quarter.rect();
assert_eq!(rect.side, TILE / 2, "a level-1 tile's side");
assert!(
rect.x / TILE == root.x / TILE && rect.y / TILE == root.y / TILE,
"{rect:?} is not in the cell the first quarter came from"
);
}
for quarter in quarters {
allocator.release(quarter);
}
let whole: Vec<TileRect> = (0..TILES)
.map(|index| {
allocator
.allocate(0)
.unwrap_or_else(|| {
panic!("cell {index} of {TILES} is not free after every quarter came back")
})
.rect()
})
.collect();
assert_eq!(whole.len(), TILES, "the loop above stopped allocating");
assert_eq!(
allocator.allocate(0),
None,
"the atlas handed out more whole cells than it has"
);
}
#[test]
fn whole_tiles_come_out_where_the_fixed_grid_put_them() {
let mut allocator = AtlasAllocator::new();
for index in 0..TILES {
let rect = allocator
.allocate(0)
.unwrap_or_else(|| panic!("cell {index} of {TILES}"))
.rect();
let (x, y) = tile_origin(index);
assert_eq!(
rect,
TileRect { x, y, side: TILE },
"cell {index} is not where `tile_origin` puts it"
);
}
}
#[test]
fn the_roots_tile_the_atlas_and_a_finer_request_is_refused() {
assert_eq!(
atlas_extent(),
(TILE * ATLAS_COLUMNS, TILE * ATLAS_ROWS),
"the allocator's roots do not cover the image they are cut from"
);
assert_eq!(nodes_at(0), TILES, "level 0 is one node per root cell");
let mut allocator = AtlasAllocator::new();
assert_eq!(
allocator.allocate(TILE_LEVELS),
None,
"a request past the finest level was answered with a tile larger than it \
asked for"
);
}
#[test]
fn a_rectangle_s_uv_puts_a_tile_s_corners_on_its_own_texels() {
let (width, height) = atlas_extent();
#[expect(
clippy::cast_precision_loss,
reason = "an atlas extent is a few thousand texels"
)]
let extent = [width as f32, height as f32];
let mut allocator = AtlasAllocator::new();
for level in 0..TILE_LEVELS {
let rect = allocator
.allocate(level)
.unwrap_or_else(|| panic!("a level-{level} tile"))
.rect();
let uv = rect.to_uv();
for (axis, extent) in extent.iter().enumerate() {
let origin = if axis == 0 { rect.x } else { rect.y };
#[expect(
clippy::cast_precision_loss,
reason = "an origin and a side are inside that extent"
)]
let (origin, side) = (origin as f32, rect.side as f32);
assert_eq!(
uv[2 + axis] * extent,
origin,
"a level-{level} tile's offset on axis {axis}"
);
assert_eq!(
(uv[2 + axis] + uv[axis]) * extent,
origin + side,
"a level-{level} tile's far edge on axis {axis}"
);
}
}
}
}