use alloc::vec::Vec;
use search_core::{Budget, Cost, NonNegF64};
use crate::grid::{GridCell, LineOfSight, STEPS, can_move, is_open, offset, sqrt};
use crate::open_list::OpenList;
use crate::outcome::{Outcome, SearchResult, Solution, Stats};
pub type AnyAngleResult = SearchResult<GridCell, (), NonNegF64>;
pub fn theta_star<G: LineOfSight>(
grid: &G,
start: GridCell,
goal: GridCell,
budget: impl Budget<Stats>,
) -> AnyAngleResult {
theta_star_multi(grid, [start], goal, budget)
}
pub fn theta_star_multi<G: LineOfSight>(
grid: &G,
starts: impl IntoIterator<Item = GridCell>,
goal: GridCell,
budget: impl Budget<Stats>,
) -> AnyAngleResult {
AnyAngle::new(grid, goal, false).run(starts, budget)
}
pub fn lazy_theta_star<G: LineOfSight>(
grid: &G,
start: GridCell,
goal: GridCell,
budget: impl Budget<Stats>,
) -> AnyAngleResult {
lazy_theta_star_multi(grid, [start], goal, budget)
}
pub fn lazy_theta_star_multi<G: LineOfSight>(
grid: &G,
starts: impl IntoIterator<Item = GridCell>,
goal: GridCell,
budget: impl Budget<Stats>,
) -> AnyAngleResult {
AnyAngle::new(grid, goal, true).run(starts, budget)
}
const NO_PARENT: usize = usize::MAX;
struct AnyAngle<'a, G> {
grid: &'a G,
goal: GridCell,
lazy: bool,
g: Vec<NonNegF64>,
parent: Vec<usize>,
closed: Vec<bool>,
open: OpenList<NonNegF64>,
stats: Stats,
}
impl<'a, G: LineOfSight> AnyAngle<'a, G> {
fn new(grid: &'a G, goal: GridCell, lazy: bool) -> Self {
let cells = grid.width() * grid.height();
Self {
grid,
goal,
lazy,
g: alloc::vec![NonNegF64::INFINITY; cells],
parent: alloc::vec![NO_PARENT; cells],
closed: alloc::vec![false; cells],
open: OpenList::new(),
stats: Stats::default(),
}
}
fn run(
mut self,
starts: impl IntoIterator<Item = GridCell>,
mut budget: impl Budget<Stats>,
) -> AnyAngleResult {
if !is_open(self.grid, self.goal) {
return self.finish(Outcome::Unsolvable);
}
for start in starts.into_iter().filter(|&cell| is_open(self.grid, cell)) {
if start == self.goal {
let solution = Solution {
states: alloc::vec![start],
actions: Vec::new(),
cost: NonNegF64::ZERO,
};
return self.finish(Outcome::Found(solution));
}
let id = self.id(start);
if self.parent[id] == NO_PARENT {
self.parent[id] = id;
self.relax(id, NonNegF64::ZERO);
}
}
loop {
let (closed, g) = (&self.closed, &self.g);
let Some(id) = self
.open
.pop_where(|id, entry| !closed[id] && entry == g[id])
.map(|(id, _)| id)
else {
return self.finish(Outcome::Unsolvable);
};
if self.lazy {
self.repair_parent(id);
}
if id == self.id(self.goal) {
let solution = self.solution(id);
return self.finish(Outcome::Found(solution));
}
if budget.exhausted(&self.stats) {
return self.finish(Outcome::LimitReached);
}
self.expand(id);
}
}
fn expand(&mut self, id: usize) {
self.stats.expanded += 1;
self.closed[id] = true;
let cell = self.cell(id);
for step in STEPS {
if !can_move(self.grid, cell, step) {
continue;
}
self.stats.generated += 1;
let next =
self.id(offset(self.grid, cell, step).expect("a legal move stays on the grid"));
if !self.closed[next] {
self.update(id, next);
}
}
}
fn update(&mut self, id: usize, next: usize) {
let grandparent = self.parent[id];
let shortcut = self.lazy
|| self
.grid
.line_of_sight(self.cell(grandparent), self.cell(next));
let from = if shortcut { grandparent } else { id };
let g = self.g[from] + self.distance(from, next);
if g < self.g[next] {
self.parent[next] = from;
self.relax(next, g);
}
}
fn repair_parent(&mut self, id: usize) {
let parent = self.parent[id];
if parent == id || self.grid.line_of_sight(self.cell(parent), self.cell(id)) {
return;
}
let cell = self.cell(id);
let best = STEPS
.iter()
.filter(|&&step| can_move(self.grid, cell, step))
.filter_map(|&step| offset(self.grid, cell, step).map(|neighbour| self.id(neighbour)))
.filter(|&neighbour| self.closed[neighbour])
.map(|neighbour| (self.g[neighbour] + self.distance(neighbour, id), neighbour))
.min_by(|a, b| a.0.cmp(&b.0))
.expect("the cell was generated by an expanded neighbour");
self.g[id] = best.0;
self.parent[id] = best.1;
}
fn relax(&mut self, id: usize, g: NonNegF64) {
self.g[id] = g;
let f = g + euclidean(self.cell(id), self.goal);
self.open.push(id, f, g);
}
fn solution(&self, id: usize) -> Solution<GridCell, (), NonNegF64> {
let mut states = alloc::vec![self.cell(id)];
let mut at = id;
while self.parent[at] != at {
at = self.parent[at];
states.push(self.cell(at));
}
states.reverse();
Solution {
actions: alloc::vec![(); states.len() - 1],
states,
cost: self.g[id],
}
}
fn distance(&self, a: usize, b: usize) -> NonNegF64 {
euclidean(self.cell(a), self.cell(b))
}
fn id(&self, (x, y): GridCell) -> usize {
y * self.grid.width() + x
}
fn cell(&self, id: usize) -> GridCell {
(id % self.grid.width(), id / self.grid.width())
}
fn finish(self, outcome: Outcome<GridCell, (), NonNegF64>) -> AnyAngleResult {
SearchResult {
outcome,
stats: self.stats,
}
}
}
fn euclidean(a: GridCell, b: GridCell) -> NonNegF64 {
let (dx, dy) = (a.0.abs_diff(b.0) as u128, a.1.abs_diff(b.1) as u128);
#[expect(
clippy::cast_precision_loss,
reason = "squared grid distances; a rounded input is fine"
)]
let squared = (dx * dx + dy * dy) as f64;
NonNegF64::new(sqrt(squared)).expect("square roots are non-negative")
}