mod jps;
mod sight;
#[cfg(feature = "float")]
mod theta;
use core::cmp::Ordering;
use core::fmt;
use core::ops::Add;
use search_core::{Cost, Heuristic};
pub use jps::{jps, jps_multi};
pub use sight::LineOfSight;
#[cfg(feature = "float")]
pub use theta::{
AnyAngleResult, lazy_theta_star, lazy_theta_star_multi, theta_star, theta_star_multi,
};
use crate::problem::Successors;
#[cfg(feature = "float")]
use search_core::NonNegF64;
pub type GridCell = (usize, usize);
pub type GridStep = (i8, i8);
pub trait UniformGrid {
fn width(&self) -> usize;
fn height(&self) -> usize;
fn is_passable(&self, x: usize, y: usize) -> bool;
}
impl<G: UniformGrid + ?Sized> UniformGrid for &G {
fn width(&self) -> usize {
(**self).width()
}
fn height(&self) -> usize {
(**self).height()
}
fn is_passable(&self, x: usize, y: usize) -> bool {
(**self).is_passable(x, y)
}
}
#[cfg(feature = "float")]
pub trait CostGrid: UniformGrid {
fn cell_cost(&self, x: usize, y: usize) -> NonNegF64 {
let _ = (x, y);
NonNegF64::new(1.0).expect("one is a valid cost")
}
}
#[cfg(feature = "float")]
impl<G: CostGrid + ?Sized> CostGrid for &G {
fn cell_cost(&self, x: usize, y: usize) -> NonNegF64 {
(**self).cell_cost(x, y)
}
}
pub(crate) fn passable<G: UniformGrid + ?Sized>(
grid: &G,
cell: GridCell,
(dx, dy): GridStep,
) -> bool {
offset(grid, cell, (dx, dy)).is_some_and(|(x, y)| grid.is_passable(x, y))
}
pub(crate) fn offset<G: UniformGrid + ?Sized>(
grid: &G,
(x, y): GridCell,
(dx, dy): GridStep,
) -> Option<GridCell> {
let x = x.checked_add_signed(isize::from(dx))?;
let y = y.checked_add_signed(isize::from(dy))?;
(x < grid.width() && y < grid.height()).then_some((x, y))
}
pub(crate) fn is_open<G: UniformGrid + ?Sized>(grid: &G, cell: GridCell) -> bool {
passable(grid, cell, (0, 0))
}
pub(crate) fn can_move<G: UniformGrid + ?Sized>(
grid: &G,
cell: GridCell,
(dx, dy): GridStep,
) -> bool {
passable(grid, cell, (dx, dy))
&& (dx == 0 || dy == 0 || (passable(grid, cell, (dx, 0)) && passable(grid, cell, (0, dy))))
}
pub(crate) const STEPS: [GridStep; 8] = [
(1, 0),
(-1, 0),
(0, 1),
(0, -1),
(1, 1),
(1, -1),
(-1, 1),
(-1, -1),
];
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Octile {
straight: u32,
diagonal: u32,
}
impl Octile {
pub const STRAIGHT: Self = Self::new(1, 0);
pub const DIAGONAL: Self = Self::new(0, 1);
#[must_use]
pub const fn new(straight: u32, diagonal: u32) -> Self {
Self { straight, diagonal }
}
#[must_use]
pub const fn straight(self) -> u32 {
self.straight
}
#[must_use]
pub const fn diagonal(self) -> u32 {
self.diagonal
}
#[must_use]
pub fn between((x0, y0): GridCell, (x1, y1): GridCell) -> Self {
let (dx, dy) = (x0.abs_diff(x1), y0.abs_diff(y1));
let count = |n: usize| u32::try_from(n).expect("grid distances fit in u32");
Self::new(count(dx.max(dy) - dx.min(dy)), count(dx.min(dy)))
}
#[must_use]
pub fn to_f64(self) -> f64 {
f64::from(self.straight) + f64::from(self.diagonal) * core::f64::consts::SQRT_2
}
}
impl Ord for Octile {
fn cmp(&self, other: &Self) -> Ordering {
let x = i128::from(self.straight) - i128::from(other.straight);
let y = i128::from(self.diagonal) - i128::from(other.diagonal);
match (x.cmp(&0), y.cmp(&0)) {
(Ordering::Equal, sign) | (sign, Ordering::Equal) => sign,
(Ordering::Greater, Ordering::Greater) => Ordering::Greater,
(Ordering::Less, Ordering::Less) => Ordering::Less,
(Ordering::Greater, Ordering::Less) => (x * x).cmp(&(2 * y * y)),
(Ordering::Less, Ordering::Greater) => (2 * y * y).cmp(&(x * x)),
}
}
}
impl PartialOrd for Octile {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Add for Octile {
type Output = Self;
fn add(self, other: Self) -> Self {
Self::new(
self.straight + other.straight,
self.diagonal + other.diagonal,
)
}
}
impl Cost for Octile {
const ZERO: Self = Self::new(0, 0);
fn saturating_add(self, other: Self) -> Self {
Self::new(
self.straight.saturating_add(other.straight),
self.diagonal.saturating_add(other.diagonal),
)
}
fn saturating_times(self, factor: u32) -> Self {
Self::new(
self.straight.saturating_mul(factor),
self.diagonal.saturating_mul(factor),
)
}
}
impl fmt::Display for Octile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} + {}√2", self.straight, self.diagonal)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct OctileDistance(pub GridCell);
impl Heuristic<GridCell, Octile> for OctileDistance {
fn estimate(&mut self, cell: &GridCell) -> Option<Octile> {
Some(Octile::between(*cell, self.0))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EightConnected<G>(pub G);
impl<G: UniformGrid> Successors for EightConnected<G> {
type State = GridCell;
type Action = GridStep;
type Cost = Octile;
fn successors(&self, cell: &GridCell, mut emit: impl FnMut(GridStep, GridCell, Octile)) {
let grid = &self.0;
if !is_open(grid, *cell) {
return;
}
for step in STEPS {
if !can_move(grid, *cell, step) {
continue;
}
let target = offset(grid, *cell, step).expect("a passable target is on the grid");
let cost = if step.0 == 0 || step.1 == 0 {
Octile::STRAIGHT
} else {
Octile::DIAGONAL
};
emit(step, target, cost);
}
}
}
#[cfg(feature = "float")]
pub(crate) fn sqrt(x: f64) -> f64 {
if x.is_nan() || x == 0.0 || x == f64::INFINITY {
return x;
}
if x < 0.0 {
return f64::NAN;
}
let guess = f64::from_bits((x.to_bits() >> 1) + (1023_u64 << 51));
let mut root = guess.midpoint(x / guess);
loop {
let next = root.midpoint(x / root);
if next >= root {
return root;
}
root = next;
}
}
#[cfg(all(test, feature = "float"))]
mod tests {
use proptest::prelude::*;
use super::sqrt;
proptest! {
#[test]
fn exact_on_squares(n in 0_u32..1_000_000) {
let n = f64::from(n);
prop_assert_eq!(sqrt(n * n).to_bits(), n.to_bits());
}
#[test]
fn root_squared_is_the_input(bits in 1_u64..0x7FEF_FFFF_FFFF_FFFF) {
let x = f64::from_bits(bits);
let root = sqrt(x);
prop_assert!(root > 0.0);
let relative = (root * root - x).abs() / x;
let tolerance = if root * root < f64::MIN_POSITIVE { 1e-3 } else { 1e-15 };
prop_assert!(relative <= tolerance, "sqrt({x}) = {root}");
}
}
#[test]
fn special_values() {
assert_eq!(sqrt(0.0).to_bits(), 0.0_f64.to_bits());
assert_eq!(sqrt(f64::INFINITY).to_bits(), f64::INFINITY.to_bits());
assert!(sqrt(f64::NAN).is_nan());
assert!(sqrt(-1.0).is_nan());
}
}