mod path;
use search_core::{Budget, Cost, NonNegF64};
use crate::dynamic::incremental::{Estimate, Incremental, Searched};
use crate::grid::{CostGrid, GridCell, sqrt};
use crate::outcome::{Outcome, SearchResult, Stats};
pub type FieldResult = SearchResult<(f64, f64), (), NonNegF64>;
pub struct FieldDStar {
core: Incremental<GridCell, NonNegF64, Scaled>,
start: GridCell,
goal: GridCell,
}
impl FieldDStar {
pub fn new<G: CostGrid>(
_grid: &G,
start: GridCell,
goal: GridCell,
min_cost: NonNegF64,
) -> Self {
assert!(
min_cost.get().is_finite(),
"Field D* needs a finite lower bound on cell costs"
);
let heuristic = Scaled(min_cost.get() / core::f64::consts::SQRT_2);
Self {
core: Incremental::new(false, goal, start, heuristic, None),
start,
goal,
}
}
pub fn compute<G: CostGrid>(&mut self, grid: &G, budget: impl Budget<Stats>) -> FieldResult {
let (settled, stats) = self.core.repair(&Corners(grid), budget);
let outcome = if settled {
let core = &self.core;
let g = |corner: GridCell| core.consistent_g(&corner).map_or(f64::INFINITY, f64::from);
match path::extract(grid, g, self.start, self.goal) {
Some(solution) => Outcome::Found(solution),
None => Outcome::Unsolvable,
}
} else {
Outcome::LimitReached
};
SearchResult { outcome, stats }
}
#[must_use]
pub fn interpolated_cost(&self) -> Option<NonNegF64> {
self.core.consistent_g(&self.start)
}
pub fn move_start(&mut self, start: GridCell) {
self.core.move_target(start);
self.start = start;
}
pub fn cell_changed<G: CostGrid>(&mut self, grid: &G, x: usize, y: usize) {
let corners = Corners(grid);
for corner in [(x, y), (x + 1, y), (x, y + 1), (x + 1, y + 1)] {
if corners.on_lattice(corner) {
self.core.edge_changed(&corners, &corner, &corner);
}
}
}
#[must_use]
pub fn goal(&self) -> GridCell {
self.goal
}
#[must_use]
pub fn start(&self) -> GridCell {
self.start
}
#[must_use]
pub fn stats(&self) -> Stats {
self.core.total
}
}
struct Scaled(f64);
impl Estimate<GridCell, NonNegF64> for Scaled {
fn estimate(&mut self, from: &GridCell, to: &GridCell) -> NonNegF64 {
if self.0 == 0.0 {
return NonNegF64::ZERO;
}
let (dx, dy) = (
coordinate(from.0.abs_diff(to.0)),
coordinate(from.1.abs_diff(to.1)),
);
NonNegF64::new(self.0 * sqrt(dx * dx + dy * dy)).expect("distances are non-negative")
}
}
struct Corners<'g, G>(&'g G);
impl<G: CostGrid> Corners<'_, G> {
fn on_lattice(&self, (x, y): GridCell) -> bool {
x <= self.0.width() && y <= self.0.height()
}
fn offset(&self, (x, y): GridCell, (dx, dy): (i8, i8)) -> Option<GridCell> {
let corner = (
x.checked_add_signed(isize::from(dx))?,
y.checked_add_signed(isize::from(dy))?,
);
self.on_lattice(corner).then_some(corner)
}
fn cell_towards(&self, (x, y): GridCell, (dx, dy): (i8, i8)) -> f64 {
let x = if dx < 0 { x.checked_sub(1) } else { Some(x) };
let y = if dy < 0 { y.checked_sub(1) } else { Some(y) };
match (x, y) {
(Some(x), Some(y)) => cell_cost(self.0, x, y),
_ => f64::INFINITY,
}
}
fn around(&self, corner: GridCell) -> ([Option<GridCell>; 8], [f64; 4]) {
let neighbours = RING.map(|step| self.offset(corner, step));
let cells = [1, 3, 5, 7].map(|k| self.cell_towards(corner, RING[k]));
(neighbours, cells)
}
fn pairs(&self, corner: GridCell) -> impl Iterator<Item = Pair> {
let (neighbours, cells) = self.around(corner);
(0..RING.len()).filter_map(move |i| {
let (straight, diagonal, other) = pair_indices(i);
Some(Pair {
straight: neighbours[straight]?,
diagonal: neighbours[diagonal],
c: cells[diagonal / 2],
b: cells[other / 2],
})
})
}
fn rhs(&self, corner: GridCell, g: impl Fn(GridCell) -> f64) -> f64 {
let (neighbours, cells) = self.around(corner);
let values = neighbours.map(|neighbour| neighbour.map_or(f64::INFINITY, &g));
(0..RING.len())
.map(|i| {
let (straight, diagonal, other) = pair_indices(i);
let (c, b) = (cells[diagonal / 2], cells[other / 2]);
interpolate(values[straight], values[diagonal], c, b).0
})
.fold(f64::INFINITY, f64::min)
}
}
fn pair_indices(i: usize) -> (usize, usize, usize) {
let next = (i + 1) % RING.len();
let (straight, diagonal) = if i % 2 == 0 { (i, next) } else { (next, i) };
let other = (2 * straight + RING.len() - diagonal) % RING.len();
(straight, diagonal, other)
}
impl<G: CostGrid> Searched for Corners<'_, G> {
type Vertex = GridCell;
type Cost = NonNegF64;
const LOOKAHEAD: bool = true;
fn successors(&self, corner: &GridCell, mut emit: impl FnMut(GridCell, NonNegF64)) {
for step in RING {
if let Some(next) = self.offset(*corner, step) {
emit(next, NonNegF64::ZERO);
}
}
}
fn predecessors(&self, corner: &GridCell, emit: impl FnMut(GridCell, NonNegF64)) {
self.successors(corner, emit);
}
fn lookahead(
&self,
corner: &GridCell,
g: impl Fn(&GridCell) -> Option<NonNegF64>,
) -> Option<NonNegF64> {
let rhs = self.rhs(*corner, |other| g(&other).map_or(f64::INFINITY, f64::from));
rhs.is_finite()
.then(|| NonNegF64::new(rhs).expect("interpolated costs are non-negative"))
}
}
const RING: [(i8, i8); 8] = [
(1, 0),
(1, 1),
(0, 1),
(-1, 1),
(-1, 0),
(-1, -1),
(0, -1),
(1, -1),
];
#[derive(Debug, Clone, Copy)]
struct Pair {
straight: GridCell,
diagonal: Option<GridCell>,
c: f64,
b: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum Via {
Straight,
Diagonal,
Across(f64),
Bend(f64),
}
fn interpolate(g1: f64, g2: f64, c: f64, b: f64) -> (f64, Via) {
let edge = c.min(b);
if edge == f64::INFINITY {
return (f64::INFINITY, Via::Straight);
}
if g1 <= g2 || c == f64::INFINITY {
return (edge + g1, Via::Straight);
}
let f = g1 - g2;
let diagonal = (c * core::f64::consts::SQRT_2 + g2, Via::Diagonal);
if f <= b {
if c <= f {
return diagonal;
}
let y = (f / sqrt(c * c - f * f)).min(1.0);
if y >= 1.0 {
return diagonal;
}
return (c * sqrt(1.0 + y * y) + f * (1.0 - y) + g2, Via::Across(y));
}
if c <= b {
return diagonal;
}
let x = 1.0 - (b / sqrt(c * c - b * b)).min(1.0);
if x <= 0.0 {
return diagonal;
}
let rest = 1.0 - x;
(c * sqrt(1.0 + rest * rest) + b * x + g2, Via::Bend(x))
}
fn cell_cost<G: CostGrid>(grid: &G, x: usize, y: usize) -> f64 {
if x >= grid.width() || y >= grid.height() || !grid.is_passable(x, y) {
return f64::INFINITY;
}
let cost = grid.cell_cost(x, y).get();
debug_assert!(
cost > 0.0 && cost.is_finite(),
"cell costs must be finite and positive, got {cost} at ({x}, {y})"
);
cost
}
#[expect(
clippy::cast_precision_loss,
reason = "grid coordinates are far below 2^52"
)]
fn coordinate(value: usize) -> f64 {
value as f64
}