use glam::DVec3;
use std::collections::VecDeque;
pub const MAX_GRID_CELL_COUNT: usize = 262_144;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GroundGridConfig {
pub origin: DVec3,
pub cell_size_m: f64,
pub width: usize,
pub height: usize,
}
impl GroundGridConfig {
#[must_use]
pub const fn new(origin: DVec3, cell_size_m: f64, width: usize, height: usize) -> Self {
Self {
origin,
cell_size_m,
width,
height,
}
}
fn cell_count(self) -> Result<usize, GroundGridConfigError> {
if !self.origin.is_finite() {
return Err(GroundGridConfigError::InvalidOrigin);
}
if !self.cell_size_m.is_finite() || self.cell_size_m <= 0.0 {
return Err(GroundGridConfigError::InvalidCellSize);
}
if self.width == 0 || self.height == 0 {
return Err(GroundGridConfigError::InvalidDimensions);
}
let count = self
.width
.checked_mul(self.height)
.ok_or(GroundGridConfigError::TooManyCells)?;
if count > MAX_GRID_CELL_COUNT {
return Err(GroundGridConfigError::TooManyCells);
}
Ok(count)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GridCell {
Walkable,
Blocked,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum GroundGridConfigError {
#[error("the grid origin is not a finite position")]
InvalidOrigin,
#[error("the cell size is not a finite positive length")]
InvalidCellSize,
#[error("the grid has a zero width or height")]
InvalidDimensions,
#[error("the grid has more cells than MAX_GRID_CELL_COUNT allows")]
TooManyCells,
#[error("the cell map's length is not the grid's width times its height")]
CellCountMismatch,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum GroundRouteError {
#[error("a position is not finite")]
InvalidWorldPosition,
#[error("a position is outside the grid")]
OutsideGrid,
#[error("no walkable route joins the start and the goal")]
NoRoute,
}
#[derive(Clone, Debug, PartialEq)]
pub struct GroundRoute {
pub waypoints: Vec<DVec3>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct GroundGrid {
config: GroundGridConfig,
cells: Vec<GridCell>,
}
impl GroundGrid {
pub fn new(
config: GroundGridConfig,
cells: Vec<GridCell>,
) -> Result<Self, GroundGridConfigError> {
let cell_count = config.cell_count()?;
if cells.len() != cell_count {
return Err(GroundGridConfigError::CellCountMismatch);
}
Ok(Self { config, cells })
}
pub fn plan(
&self,
start_world_position: DVec3,
goal_world_position: DVec3,
) -> Result<GroundRoute, GroundRouteError> {
let start = self.world_to_cell(start_world_position)?;
let goal = self.world_to_cell(goal_world_position)?;
if self.cells[start] == GridCell::Blocked || self.cells[goal] == GridCell::Blocked {
return Err(GroundRouteError::NoRoute);
}
if start == goal {
return Ok(GroundRoute {
waypoints: Vec::new(),
});
}
let mut predecessors = vec![None; self.cells.len()];
let mut frontier = VecDeque::new();
predecessors[start] = Some(start);
frontier.push_back(start);
while let Some(current) = frontier.pop_front() {
for neighbor in self.neighbors(current).into_iter().flatten() {
if self.cells[neighbor] == GridCell::Blocked || predecessors[neighbor].is_some() {
continue;
}
predecessors[neighbor] = Some(current);
if neighbor == goal {
return Ok(self.build_route(start, goal, &predecessors));
}
frontier.push_back(neighbor);
}
}
Err(GroundRouteError::NoRoute)
}
pub fn reachable_within(
&self,
start_world_position: DVec3,
max_steps: usize,
) -> Result<Vec<(DVec3, usize)>, GroundRouteError> {
let start = self.world_to_cell(start_world_position)?;
if self.cells[start] == GridCell::Blocked {
return Err(GroundRouteError::NoRoute);
}
let mut steps = vec![None; self.cells.len()];
let mut frontier = VecDeque::new();
let mut reached = Vec::new();
steps[start] = Some(0);
frontier.push_back(start);
while let Some(current) = frontier.pop_front() {
let current_steps = steps[current].expect("a queued cell has its step count");
reached.push((self.cell_center(current), current_steps));
if current_steps == max_steps {
continue;
}
for neighbor in self.neighbors(current).into_iter().flatten() {
if self.cells[neighbor] == GridCell::Walkable && steps[neighbor].is_none() {
steps[neighbor] = Some(current_steps + 1);
frontier.push_back(neighbor);
}
}
}
Ok(reached)
}
pub fn nearest_walkable(
&self,
world_position: DVec3,
max_rings: usize,
) -> Result<Option<DVec3>, GroundRouteError> {
let cell = self.world_to_cell(world_position)?;
if self.cells[cell] == GridCell::Walkable {
return Ok(Some(self.cell_center(cell)));
}
let (width, height) = (self.config.width, self.config.height);
let (x, z) = (cell % width, cell / width);
let mut nearest: Option<(f64, usize)> = None;
for row in z.saturating_sub(max_rings)..=z.saturating_add(max_rings).min(height - 1) {
for column in x.saturating_sub(max_rings)..=x.saturating_add(max_rings).min(width - 1) {
let index = row * width + column;
if self.cells[index] == GridCell::Blocked {
continue;
}
let center = self.cell_center(index);
let distance = (center.x - world_position.x).hypot(center.z - world_position.z);
if nearest.is_none_or(|(best, _)| distance < best) {
nearest = Some((distance, index));
}
}
}
Ok(nearest.map(|(_, index)| self.cell_center(index)))
}
#[must_use]
pub fn cell_size_m(&self) -> f64 {
self.config.cell_size_m
}
fn world_to_cell(&self, position: DVec3) -> Result<usize, GroundRouteError> {
if !position.is_finite() {
return Err(GroundRouteError::InvalidWorldPosition);
}
let relative_x = (position.x - self.config.origin.x) / self.config.cell_size_m;
let relative_z = (position.z - self.config.origin.z) / self.config.cell_size_m;
if !relative_x.is_finite() || !relative_z.is_finite() {
return Err(GroundRouteError::OutsideGrid);
}
let x = relative_x.floor();
let z = relative_z.floor();
if x < 0.0 || z < 0.0 || x >= self.config.width as f64 || z >= self.config.height as f64 {
return Err(GroundRouteError::OutsideGrid);
}
Ok(z as usize * self.config.width + x as usize)
}
fn neighbors(&self, cell: usize) -> [Option<usize>; 4] {
let x = cell % self.config.width;
let z = cell / self.config.width;
[
if z + 1 < self.config.height {
Some(cell + self.config.width)
} else {
None
},
if x + 1 < self.config.width {
Some(cell + 1)
} else {
None
},
if z > 0 {
Some(cell - self.config.width)
} else {
None
},
if x > 0 { Some(cell - 1) } else { None },
]
}
fn build_route(
&self,
start: usize,
goal: usize,
predecessors: &[Option<usize>],
) -> GroundRoute {
let mut cells = Vec::new();
let mut current = goal;
while current != start {
cells.push(current);
current = predecessors[current].expect("visited route cell has a predecessor");
}
cells.reverse();
GroundRoute {
waypoints: cells
.into_iter()
.map(|cell| self.cell_center(cell))
.collect(),
}
}
fn cell_center(&self, cell: usize) -> DVec3 {
let x = cell % self.config.width;
let z = cell / self.config.width;
DVec3::new(
self.config.origin.x + (x as f64 + 0.5) * self.config.cell_size_m,
self.config.origin.y,
self.config.origin.z + (z as f64 + 0.5) * self.config.cell_size_m,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn grid(width: usize, height: usize, cells: Vec<GridCell>) -> GroundGrid {
GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, 1.0, width, height),
cells,
)
.unwrap()
}
#[test]
fn straight_route_returns_cell_centres_after_the_start_cell() {
let grid = grid(4, 1, vec![GridCell::Walkable; 4]);
let route = grid
.plan(DVec3::new(0.1, 0.0, 0.1), DVec3::new(3.9, 0.0, 0.1))
.unwrap();
assert_eq!(route.waypoints.len(), 3);
assert_eq!(
route.waypoints,
vec![
DVec3::new(1.5, 0.0, 0.5),
DVec3::new(2.5, 0.0, 0.5),
DVec3::new(3.5, 0.0, 0.5),
]
);
}
#[test]
fn route_around_a_wall_uses_the_only_gap() {
let grid = grid(
5,
3,
vec![
GridCell::Walkable,
GridCell::Walkable,
GridCell::Blocked,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Blocked,
GridCell::Walkable,
GridCell::Walkable,
],
);
let route = grid
.plan(DVec3::new(0.1, 0.0, 0.1), DVec3::new(4.1, 0.0, 0.1))
.unwrap();
assert_eq!(route.waypoints.len(), 6);
assert!(route.waypoints.contains(&DVec3::new(2.5, 0.0, 1.5)));
assert_eq!(route.waypoints.last(), Some(&DVec3::new(4.5, 0.0, 0.5)));
}
#[test]
fn sealed_wall_has_no_route() {
let grid = grid(
3,
2,
vec![
GridCell::Walkable,
GridCell::Blocked,
GridCell::Walkable,
GridCell::Walkable,
GridCell::Blocked,
GridCell::Walkable,
],
);
assert_eq!(
grid.plan(DVec3::new(0.1, 0.0, 0.1), DVec3::new(2.1, 0.0, 0.1)),
Err(GroundRouteError::NoRoute)
);
}
#[test]
fn positions_outside_the_grid_are_rejected() {
let grid = grid(1, 1, vec![GridCell::Walkable]);
assert_eq!(
grid.plan(DVec3::new(-0.01, 0.0, 0.5), DVec3::new(0.5, 0.0, 0.5)),
Err(GroundRouteError::OutsideGrid)
);
assert_eq!(
grid.plan(DVec3::new(0.5, 0.0, 0.5), DVec3::new(1.0, 0.0, 0.5)),
Err(GroundRouteError::OutsideGrid)
);
}
#[test]
fn equal_cost_routes_use_the_stable_north_then_east_tie_break() {
let grid = grid(2, 2, vec![GridCell::Walkable; 4]);
let first = grid
.plan(DVec3::new(0.1, 0.0, 0.1), DVec3::new(1.1, 0.0, 1.1))
.unwrap();
let second = grid
.plan(DVec3::new(0.1, 0.0, 0.1), DVec3::new(1.1, 0.0, 1.1))
.unwrap();
assert_eq!(first, second);
assert_eq!(
first.waypoints,
vec![DVec3::new(0.5, 0.0, 1.5), DVec3::new(1.5, 0.0, 1.5)]
);
}
#[test]
fn invalid_and_overflow_dimensions_are_rejected() {
assert_eq!(
GroundGrid::new(
GroundGridConfig::new(DVec3::new(f64::NAN, 0.0, 0.0), 1.0, 1, 1),
vec![],
),
Err(GroundGridConfigError::InvalidOrigin)
);
assert_eq!(
GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, 0.0, 1, 1),
vec![GridCell::Walkable],
),
Err(GroundGridConfigError::InvalidCellSize)
);
assert_eq!(
GroundGrid::new(GroundGridConfig::new(DVec3::ZERO, 1.0, 0, 1), vec![]),
Err(GroundGridConfigError::InvalidDimensions)
);
assert_eq!(
GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, 1.0, usize::MAX, 2),
vec![],
),
Err(GroundGridConfigError::TooManyCells)
);
assert_eq!(
GroundGrid::new(GroundGridConfig::new(DVec3::ZERO, 1.0, 2, 2), vec![]),
Err(GroundGridConfigError::CellCountMismatch)
);
}
#[test]
fn reachable_cells_stop_at_walls_and_the_step_budget() {
use GridCell::{Blocked, Walkable};
let corridor = grid(4, 1, vec![Walkable, Walkable, Blocked, Walkable]);
let reached = corridor
.reachable_within(DVec3::new(0.5, 0.0, 0.5), 5)
.unwrap();
assert_eq!(
reached,
vec![
(DVec3::new(0.5, 0.0, 0.5), 0),
(DVec3::new(1.5, 0.0, 0.5), 1)
]
);
let open = grid(4, 1, vec![Walkable; 4]);
let reached = open.reachable_within(DVec3::new(0.5, 0.0, 0.5), 2).unwrap();
assert_eq!(reached.len(), 3, "the budget stops the fill at two steps");
}
#[test]
fn identical_grids_give_identical_routes_that_lean_plus_z_then_plus_x() {
let a = grid(3, 3, vec![GridCell::Walkable; 9]);
let b = grid(3, 3, vec![GridCell::Walkable; 9]);
let start = DVec3::new(0.5, 0.0, 0.5);
let goal = DVec3::new(2.5, 0.0, 2.5);
let from_a = a.plan(start, goal).unwrap();
let from_b = b.plan(start, goal).unwrap();
assert_eq!(from_a, from_b);
assert_eq!(
from_a.waypoints,
vec![
DVec3::new(0.5, 0.0, 1.5),
DVec3::new(0.5, 0.0, 2.5),
DVec3::new(1.5, 0.0, 2.5),
DVec3::new(2.5, 0.0, 2.5),
]
);
assert_eq!(
a.reachable_within(start, 4).unwrap(),
b.reachable_within(start, 4).unwrap()
);
}
#[test]
fn reachable_within_returns_exactly_the_cells_inside_the_budget() {
let open = grid(5, 5, vec![GridCell::Walkable; 25]);
let centre = DVec3::new(2.5, 0.0, 2.5);
let budget = 2;
let reached = open.reachable_within(centre, budget).unwrap();
let manhattan = |p: DVec3| ((p.x - centre.x).abs() + (p.z - centre.z).abs()) as usize;
let inside = (0..5)
.flat_map(|z: usize| (0..5_usize).map(move |x| (x, z)))
.filter(|&(x, z)| x.abs_diff(2) + z.abs_diff(2) <= budget)
.count();
assert_eq!(reached.len(), inside);
for &(cell, steps) in &reached {
assert!(
steps <= budget,
"{cell} at {steps} steps is past the budget"
);
assert_eq!(steps, manhattan(cell), "{cell} is not at its fewest steps");
}
let mut distinct: Vec<_> = reached
.iter()
.map(|(cell, _)| (cell.x.to_bits(), cell.z.to_bits()))
.collect();
distinct.sort_unstable();
distinct.dedup();
assert_eq!(distinct.len(), reached.len(), "a cell was reported twice");
assert_eq!(
open.reachable_within(centre, 0).unwrap(),
vec![(centre, 0)],
"a zero budget is the start alone"
);
}
#[test]
fn reachable_within_lists_the_start_first_in_breadth_first_order() {
use GridCell::{Blocked, Walkable};
#[rustfmt::skip]
let cells = vec![
Walkable, Walkable, Walkable, Walkable,
Walkable, Blocked, Blocked, Walkable,
Walkable, Walkable, Walkable, Walkable,
];
let grid = grid(4, 3, cells);
let start = DVec3::new(1.5, 0.0, 0.5);
let reached = grid.reachable_within(start, usize::MAX).unwrap();
assert_eq!(reached.first(), Some(&(start, 0)));
assert!(
reached.windows(2).all(|pair| pair[0].1 <= pair[1].1),
"step counts went down: {reached:?}"
);
assert_eq!(reached.len(), 10, "every walkable cell is reachable");
}
#[test]
fn a_start_and_goal_in_one_cell_is_an_empty_route() {
let grid = grid(2, 2, vec![GridCell::Walkable; 4]);
let route = grid
.plan(DVec3::new(1.1, 0.0, 1.1), DVec3::new(1.9, 7.0, 1.9))
.unwrap();
assert!(route.waypoints.is_empty());
}
#[test]
fn a_blocked_start_or_goal_has_no_route() {
use GridCell::{Blocked, Walkable};
let grid = grid(3, 1, vec![Blocked, Walkable, Blocked]);
let middle = DVec3::new(1.5, 0.0, 0.5);
assert_eq!(
grid.plan(DVec3::new(0.5, 0.0, 0.5), middle),
Err(GroundRouteError::NoRoute)
);
assert_eq!(
grid.plan(middle, DVec3::new(2.5, 0.0, 0.5)),
Err(GroundRouteError::NoRoute)
);
assert_eq!(
grid.reachable_within(DVec3::new(0.5, 0.0, 0.5), 3),
Err(GroundRouteError::NoRoute)
);
}
#[test]
fn an_enclosed_goal_is_unreachable() {
use GridCell::{Blocked, Walkable};
#[rustfmt::skip]
let cells = vec![
Walkable, Walkable, Walkable, Walkable, Walkable,
Walkable, Walkable, Walkable, Blocked, Walkable,
Walkable, Walkable, Blocked, Walkable, Blocked,
Walkable, Walkable, Walkable, Blocked, Walkable,
];
let grid = grid(5, 4, cells);
assert_eq!(
grid.plan(DVec3::new(0.5, 0.0, 0.5), DVec3::new(3.5, 0.0, 2.5)),
Err(GroundRouteError::NoRoute)
);
}
#[test]
fn non_finite_and_overflowing_positions_are_rejected() {
let grid = GroundGrid::new(
GroundGridConfig::new(DVec3::new(-1.0, 0.0, -1.0), 0.5, 4, 4),
vec![GridCell::Walkable; 16],
)
.unwrap();
let inside = DVec3::ZERO;
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
assert_eq!(
grid.plan(DVec3::new(bad, 0.0, 0.0), inside),
Err(GroundRouteError::InvalidWorldPosition)
);
assert_eq!(
grid.plan(inside, DVec3::new(0.0, bad, 0.0)),
Err(GroundRouteError::InvalidWorldPosition)
);
assert_eq!(
grid.reachable_within(DVec3::new(0.0, 0.0, bad), 1),
Err(GroundRouteError::InvalidWorldPosition)
);
}
assert_eq!(
grid.plan(DVec3::new(f64::MAX, 0.0, 0.0), inside),
Err(GroundRouteError::OutsideGrid)
);
}
#[test]
fn every_non_finite_or_non_positive_cell_size_is_rejected() {
for size in [f64::NAN, f64::INFINITY, -1.0, -0.0] {
assert_eq!(
GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, size, 1, 1),
vec![GridCell::Walkable],
),
Err(GroundGridConfigError::InvalidCellSize),
"{size}"
);
}
assert_eq!(
GroundGrid::new(
GroundGridConfig::new(DVec3::new(0.0, f64::INFINITY, 0.0), 1.0, 1, 1),
vec![GridCell::Walkable],
),
Err(GroundGridConfigError::InvalidOrigin)
);
}
#[test]
fn the_cell_cap_admits_its_own_size_and_nothing_past_it() {
let width = 1024;
let height = MAX_GRID_CELL_COUNT / width;
assert_eq!(width * height, MAX_GRID_CELL_COUNT);
let at_cap = GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, 1.0, width, height),
vec![GridCell::Walkable; MAX_GRID_CELL_COUNT],
);
assert!(at_cap.is_ok());
assert_eq!(
GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, 1.0, width, height + 1),
vec![GridCell::Walkable; MAX_GRID_CELL_COUNT + width],
),
Err(GroundGridConfigError::TooManyCells)
);
}
#[test]
fn cell_size_is_what_the_config_said() {
let grid = GroundGrid::new(
GroundGridConfig::new(DVec3::ZERO, 0.25, 2, 2),
vec![GridCell::Walkable; 4],
)
.unwrap();
assert_eq!(grid.cell_size_m(), 0.25);
}
#[test]
fn nearest_walkable_snaps_a_blocked_position_to_the_closest_walkable_centre() {
use GridCell::{Blocked as B, Walkable as W};
let grid = grid(4, 2, vec![W, B, B, W, B, B, B, W]);
let near_minus_x = DVec3::new(1.2, 0.0, 0.5);
assert_eq!(
grid.plan(near_minus_x, DVec3::new(3.5, 0.0, 0.5)),
Err(GroundRouteError::NoRoute)
);
let snapped = grid.nearest_walkable(near_minus_x, 1).unwrap();
assert_eq!(snapped, Some(DVec3::new(0.5, 0.0, 0.5)));
assert_eq!(
grid.nearest_walkable(DVec3::new(2.8, 0.0, 0.5), 1).unwrap(),
Some(DVec3::new(3.5, 0.0, 0.5)),
"the nearer side wins"
);
assert!(
grid.plan(snapped.unwrap(), DVec3::new(0.5, 0.0, 0.5))
.is_ok(),
"the answer is a start plan accepts"
);
let between = DVec3::new(3.5, 0.0, 1.0);
let grid_tied = self::grid(4, 2, vec![B, B, B, W, B, B, B, W]);
assert_eq!(
grid_tied
.nearest_walkable(DVec3::new(2.5, 0.0, 1.0), 1)
.unwrap(),
Some(DVec3::new(3.5, 0.0, 0.5)),
"a tie goes to the lower row"
);
assert_eq!(
grid_tied.nearest_walkable(between, 1).unwrap(),
Some(DVec3::new(3.5, 0.0, 1.5)),
"on the row boundary the position is in the upper row's walkable cell, which wins \
over the tie-break"
);
assert_eq!(
grid.nearest_walkable(DVec3::new(1.5, 0.0, 1.5), 0).unwrap(),
None,
"no rings is the position's own cell alone"
);
assert_eq!(
grid.nearest_walkable(DVec3::new(1.5, 0.0, 1.5), 1).unwrap(),
Some(DVec3::new(0.5, 0.0, 0.5)),
"one ring reaches the diagonal"
);
assert_eq!(
grid.nearest_walkable(DVec3::new(3.2, 0.0, 0.5), 0).unwrap(),
Some(DVec3::new(3.5, 0.0, 0.5)),
"a walkable cell answers its own centre"
);
assert_eq!(
grid.nearest_walkable(DVec3::new(f64::NAN, 0.0, 0.5), 1),
Err(GroundRouteError::InvalidWorldPosition)
);
assert_eq!(
grid.nearest_walkable(DVec3::new(9.0, 0.0, 0.5), 1),
Err(GroundRouteError::OutsideGrid)
);
}
}