use std::cell::RefCell;
use std::cmp::Ordering;
use std::collections::{BTreeMap, BinaryHeap, VecDeque};
use glam::{DVec2, DVec3};
use crate::grid::{GroundRoute, GroundRouteError};
pub const MAX_SPAN_COLUMN_COUNT: usize = 1 << 22;
pub const MAX_EROSION_REACH_CELLS: usize = 64;
pub const PLAN_TOWARD_STEPS: u32 = 8;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NavAgent {
pub radius_m: f64,
pub height_m: f64,
pub max_climb_m: f64,
pub min_floor_normal_y: f64,
}
#[cfg(feature = "phys")]
impl NavAgent {
#[must_use]
pub fn from_character(config: &crcbl_phys::character::CharacterConfig) -> Self {
Self {
radius_m: config.radius,
height_m: 2.0 * (config.half_height + config.radius),
max_climb_m: config.step_offset,
min_floor_normal_y: config.min_ground_normal_y,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpanGridConfig {
pub origin: DVec2,
pub cell_size_m: f64,
pub width: usize,
pub height: usize,
}
impl SpanGridConfig {
#[must_use]
pub fn cell_center(&self, column: usize, row: usize) -> DVec2 {
self.origin + (DVec2::new(column as f64, row as f64) + 0.5) * self.cell_size_m
}
fn column_count(self) -> Result<usize, SpanGridError> {
if !self.origin.is_finite() {
return Err(SpanGridError::InvalidOrigin);
}
if !self.cell_size_m.is_finite() || self.cell_size_m <= 0.0 {
return Err(SpanGridError::InvalidCellSize);
}
if self.width == 0 || self.height == 0 {
return Err(SpanGridError::InvalidDimensions);
}
self.width
.checked_mul(self.height)
.filter(|&count| count <= MAX_SPAN_COLUMN_COUNT)
.ok_or(SpanGridError::TooManyColumns)
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ProbedFloor {
pub y: f64,
pub normal_y: f64,
pub headroom_clear: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
pub enum SpanGridError {
#[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 columns than MAX_SPAN_COLUMN_COUNT allows")]
TooManyColumns,
#[error("the agent's limits are not finite lengths and a normal's Y")]
InvalidAgent,
#[error("the agent's radius spans more cells than MAX_EROSION_REACH_CELLS")]
RadiusTooWide,
#[error("the probe reported a floor that is not finite")]
InvalidFloor,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TowardRoute {
pub route: GroundRoute,
pub end: DVec3,
pub reaches_goal: bool,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpanGrid {
config: SpanGridConfig,
agent: NavAgent,
column_start: Vec<usize>,
floors: Vec<f64>,
}
type SpanId = usize;
impl SpanGrid {
pub fn build(
config: SpanGridConfig,
agent: NavAgent,
mut probe: impl FnMut(DVec2) -> Vec<ProbedFloor>,
) -> Result<Self, SpanGridError> {
let column_count = config.column_count()?;
let finite = [
agent.radius_m,
agent.height_m,
agent.max_climb_m,
agent.min_floor_normal_y,
]
.iter()
.all(|value| value.is_finite());
if !finite
|| agent.radius_m < 0.0
|| agent.height_m <= 0.0
|| agent.max_climb_m < 0.0
|| !(-1.0..=1.0).contains(&agent.min_floor_normal_y)
{
return Err(SpanGridError::InvalidAgent);
}
let reach = agent.radius_m / config.cell_size_m;
if reach > MAX_EROSION_REACH_CELLS as f64 {
return Err(SpanGridError::RadiusTooWide);
}
#[allow(clippy::cast_possible_truncation)]
let steps = (reach + 0.5).ceil() as isize;
let offsets: Vec<(isize, isize)> = (-steps..=steps)
.flat_map(|dz| (-steps..=steps).map(move |dx| (dx, dz)))
.filter(|&(dx, dz)| {
let gap = DVec2::new(dx.unsigned_abs() as f64, dz.unsigned_abs() as f64) - 0.5;
gap.max(DVec2::ZERO).length() < reach
})
.collect();
let mut probed: Vec<Vec<f64>> = Vec::with_capacity(column_count);
for row in 0..config.height {
for column in 0..config.width {
let mut floors = Vec::new();
for floor in probe(config.cell_center(column, row)) {
if !floor.y.is_finite() || !floor.normal_y.is_finite() {
return Err(SpanGridError::InvalidFloor);
}
if floor.headroom_clear && floor.normal_y >= agent.min_floor_normal_y {
floors.push(floor.y);
}
}
floors.sort_by(f64::total_cmp);
probed.push(floors);
}
}
let mut column_start = Vec::with_capacity(column_count + 1);
let mut floors = Vec::new();
for row in 0..config.height {
for column in 0..config.width {
column_start.push(floors.len());
for &y in &probed[row * config.width + column] {
let clear = offsets.iter().all(|&(dx, dz)| {
let (Some(x), Some(z)) = (
column.checked_add_signed(dx).filter(|&x| x < config.width),
row.checked_add_signed(dz).filter(|&z| z < config.height),
) else {
return false;
};
probed[z * config.width + x]
.iter()
.any(|&other| (other - y).abs() <= agent.max_climb_m)
});
if clear {
floors.push(y);
}
}
}
}
column_start.push(floors.len());
Ok(Self {
config,
agent,
column_start,
floors,
})
}
#[must_use]
pub fn config(&self) -> SpanGridConfig {
self.config
}
#[must_use]
pub fn agent(&self) -> NavAgent {
self.agent
}
#[must_use]
pub fn cell_size_m(&self) -> f64 {
self.config.cell_size_m
}
#[must_use]
pub fn span_count(&self) -> usize {
self.floors.len()
}
#[must_use]
pub fn floors_at(&self, position: DVec3) -> &[f64] {
self.column_at(position)
.map_or(&[], |column| &self.floors[self.spans_of(column)])
}
pub fn plan(
&self,
start_world_position: DVec3,
goal_world_position: DVec3,
) -> Result<GroundRoute, GroundRouteError> {
let from = self.span_at(start_world_position)?;
let to = self.span_at(goal_world_position)?;
let (Some(from), Some(to)) = (from, to) else {
return Err(GroundRouteError::NoRoute);
};
self.route(from, to, |_, _, _| {})
.ok_or(GroundRouteError::NoRoute)
}
fn route(
&self,
from: SpanId,
to: SpanId,
mut popped: impl FnMut(SpanId, f64, f64),
) -> Option<GroundRoute> {
SCRATCH.with(|scratch| match scratch.try_borrow_mut() {
Ok(mut scratch) => self.route_in(&mut scratch, from, to, &mut popped),
Err(_) => self.route_in(&mut Scratch::default(), from, to, &mut popped),
})
}
fn route_in(
&self,
scratch: &mut Scratch,
from: SpanId,
to: SpanId,
popped: &mut impl FnMut(SpanId, f64, f64),
) -> Option<GroundRoute> {
let target = self.feet_of(to);
scratch.begin(self.floors.len());
scratch.reach(from, 0.0, from);
let from_column = self.column_of(from);
let mut open = BinaryHeap::from([Open {
estimate: self.feet_at(from, from_column).distance(target),
span: from,
column: from_column,
cost: 0.0,
}]);
while let Some(Open {
span, column, cost, ..
}) = open.pop()
{
if span == to {
let mut waypoints = Vec::new();
let mut at = to;
while at != from {
waypoints.push(self.feet_of(at));
at = scratch.slots[at].before;
}
waypoints.reverse();
return Some(GroundRoute { waypoints });
}
let so_far = scratch.slots[span].cost;
popped(span, cost, so_far);
if cost > so_far {
continue;
}
let here = self.feet_at(span, column);
self.each_neighbour(span, column, |next, next_column| {
let there = self.feet_at(next, next_column);
let through = so_far + here.distance(there);
if scratch.cost_of(next).is_none_or(|cost| through < cost) {
scratch.reach(next, through, span);
open.push(Open {
estimate: through + there.distance(target),
span: next,
column: next_column,
cost: through,
});
}
});
}
None
}
pub fn reachable_within(
&self,
start_world_position: DVec3,
max_steps: usize,
) -> Result<Vec<(DVec3, usize)>, GroundRouteError> {
let from = self
.span_at(start_world_position)?
.ok_or(GroundRouteError::NoRoute)?;
let mut steps = BTreeMap::from([(from, 0)]);
let mut frontier = VecDeque::from([(from, self.column_of(from))]);
let mut reached = Vec::new();
while let Some((span, column)) = frontier.pop_front() {
let here = steps[&span];
reached.push((self.feet_at(span, column), here));
if here == max_steps {
continue;
}
self.each_neighbour(span, column, |next, next_column| {
steps.entry(next).or_insert_with(|| {
frontier.push_back((next, next_column));
here + 1
});
});
}
Ok(reached)
}
pub fn nearest_walkable(
&self,
world_position: DVec3,
max_rings: usize,
) -> Result<Option<DVec3>, GroundRouteError> {
let column = self.column_of_position(world_position)?;
if let Some(span) = self.floor_in(column, world_position.y) {
return Ok(Some(self.feet_of(span)));
}
let (width, height) = (self.config.width, self.config.height);
let (x, z) = (column % width, column / width);
let mut nearest: Option<(f64, SpanId)> = 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) {
for span in self.spans_of(row * width + column) {
let distance = self.feet_of(span).distance(world_position);
if nearest.is_none_or(|(best, _)| distance < best) {
nearest = Some((distance, span));
}
}
}
}
Ok(nearest.map(|(_, span)| self.feet_of(span)))
}
pub fn plan_toward(
&self,
start_world_position: DVec3,
goal_world_position: DVec3,
max_rings: usize,
) -> Result<TowardRoute, GroundRouteError> {
let from = self
.span_at(start_world_position)?
.ok_or(GroundRouteError::NoRoute)?;
if !goal_world_position.is_finite() {
return Err(GroundRouteError::InvalidWorldPosition);
}
if let (Ok(Some(to)), Ok(route)) = (
self.span_at(goal_world_position),
self.plan(start_world_position, goal_world_position),
) {
return Ok(TowardRoute {
route,
end: self.feet_of(to),
reaches_goal: true,
});
}
let (width, height) = (self.config.width, self.config.height);
let clamped = DVec2::new(goal_world_position.x, goal_world_position.z).clamp(
self.config.cell_center(0, 0),
self.config.cell_center(width - 1, height - 1),
);
let toward = DVec3::new(clamped.x, goal_world_position.y, clamped.y);
let mut tried = None;
for step in 0..PLAN_TOWARD_STEPS {
let point = toward.lerp(
start_world_position,
f64::from(step) / f64::from(PLAN_TOWARD_STEPS),
);
let Some(floor) = self.nearest_walkable(point, max_rings)? else {
continue;
};
if tried == Some(floor) {
continue;
}
tried = Some(floor);
if let Ok(route) = self.plan(start_world_position, floor) {
return Ok(TowardRoute {
route,
end: floor,
reaches_goal: false,
});
}
}
Ok(TowardRoute {
route: GroundRoute {
waypoints: Vec::new(),
},
end: self.feet_of(from),
reaches_goal: false,
})
}
fn column_at(&self, position: DVec3) -> Option<usize> {
let local =
(DVec2::new(position.x, position.z) - self.config.origin) / self.config.cell_size_m;
if !local.is_finite() || local.x < 0.0 || local.y < 0.0 {
return None;
}
let (column, row) = (local.x.floor(), local.y.floor());
if column >= self.config.width as f64 || row >= self.config.height as f64 {
return None;
}
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
Some(row as usize * self.config.width + column as usize)
}
fn span_at(&self, position: DVec3) -> Result<Option<SpanId>, GroundRouteError> {
let column = self.column_of_position(position)?;
Ok(self.floor_in(column, position.y))
}
fn column_of_position(&self, position: DVec3) -> Result<usize, GroundRouteError> {
if !position.is_finite() {
return Err(GroundRouteError::InvalidWorldPosition);
}
self.column_at(position)
.ok_or(GroundRouteError::OutsideGrid)
}
fn floor_in(&self, column: usize, y: f64) -> Option<SpanId> {
self.spans_of(column)
.rev()
.find(|&span| (y - self.floors[span]).abs() <= self.agent.max_climb_m)
}
fn spans_of(&self, column: usize) -> std::ops::Range<SpanId> {
self.column_start[column]..self.column_start[column + 1]
}
fn column_of(&self, span: SpanId) -> usize {
self.column_start.partition_point(|&start| start <= span) - 1
}
fn feet_of(&self, span: SpanId) -> DVec3 {
self.feet_at(span, self.column_of(span))
}
fn feet_at(&self, span: SpanId, column: usize) -> DVec3 {
let at = self
.config
.cell_center(column % self.config.width, column / self.config.width);
DVec3::new(at.x, self.floors[span], at.y)
}
fn each_neighbour(&self, span: SpanId, column: usize, mut visit: impl FnMut(SpanId, usize)) {
let (width, height) = (self.config.width, self.config.height);
let (x, z) = (column % width, column / width);
let y = self.floors[span];
let toward = |dx: isize, dz: isize| -> Option<usize> {
let nx = x.checked_add_signed(dx).filter(|&v| v < width)?;
let nz = z.checked_add_signed(dz).filter(|&v| v < height)?;
Some(nz * width + nx)
};
let mut step = |dx: isize, dz: isize| -> bool {
let Some(next_column) = toward(dx, dz) else {
return false;
};
let mut any = false;
for other in self.spans_of(next_column) {
if (self.floors[other] - y).abs() <= self.agent.max_climb_m {
any = true;
visit(other, next_column);
}
}
any
};
let linked = [step(0, 1), step(1, 0), step(0, -1), step(-1, 0)];
let (plus_z, plus_x, minus_z, minus_x) = (linked[0], linked[1], linked[2], linked[3]);
for (dx, dz, past_x, past_z) in [
(1, 1, plus_x, plus_z),
(1, -1, plus_x, minus_z),
(-1, -1, minus_x, minus_z),
(-1, 1, minus_x, plus_z),
] {
if past_x && past_z {
step(dx, dz);
}
}
}
}
thread_local! {
static SCRATCH: RefCell<Scratch> = RefCell::default();
}
#[derive(Default)]
struct Scratch {
generation: u32,
slots: Vec<Slot>,
}
#[derive(Clone, Copy, Default)]
struct Slot {
stamp: u32,
cost: f64,
before: SpanId,
}
impl Scratch {
fn begin(&mut self, spans: usize) {
if self.slots.len() < spans {
self.slots.resize(spans, Slot::default());
}
if self.generation == u32::MAX {
for slot in &mut self.slots {
slot.stamp = 0;
}
self.generation = 0;
}
self.generation += 1;
}
fn cost_of(&self, span: SpanId) -> Option<f64> {
let slot = self.slots[span];
(slot.stamp == self.generation).then_some(slot.cost)
}
fn reach(&mut self, span: SpanId, cost: f64, before: SpanId) {
self.slots[span] = Slot {
stamp: self.generation,
cost,
before,
};
}
}
#[derive(Clone, Copy, Debug)]
struct Open {
estimate: f64,
span: SpanId,
column: usize,
cost: f64,
}
impl PartialEq for Open {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Open {}
impl Ord for Open {
fn cmp(&self, other: &Self) -> Ordering {
other
.estimate
.total_cmp(&self.estimate)
.then_with(|| other.span.cmp(&self.span))
}
}
impl PartialOrd for Open {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[cfg(test)]
#[path = "spans/tests.rs"]
mod tests;
#[cfg(test)]
#[path = "spans/route_equivalence_tests.rs"]
mod route_equivalence_tests;