use polyzonotope::{Containment, Interval, IntervalBox, Polytope, SparsePolyZonotope, Zonotope};
use sampling_planning::{Euclidean, Validity, ValidityChecker};
use crate::{Obstacles, Reach, SafetyVerdict, Steer, check_edge};
#[derive(Debug, Clone)]
pub struct ReachChecker<R, const N: usize> {
obstacles: Obstacles,
reach: R,
half_widths: [f64; N],
}
impl<R: Reach<N>, const N: usize> ReachChecker<R, N> {
#[must_use]
pub fn new(obstacles: Obstacles, reach: R, half_widths: [f64; N]) -> Self {
assert!(
half_widths.iter().all(|r| r.is_finite() && *r >= 0.0),
"half widths must be non-negative and finite"
);
Self {
obstacles,
reach,
half_widths,
}
}
#[must_use]
pub const fn obstacles(&self) -> &Obstacles {
&self.obstacles
}
#[must_use]
pub const fn reach(&self) -> &R {
&self.reach
}
#[must_use]
pub fn tube(&self, state: &[f64; N]) -> IntervalBox {
IntervalBox(
state
.iter()
.zip(&self.half_widths)
.map(|(x, r)| Interval::new(x - r, x + r))
.collect(),
)
}
fn returns_into_tube(&self, end: &SparsePolyZonotope, to: &[f64; N]) -> Validity {
let tube = Polytope::from_box(&self.tube(to));
match end.containment(&tube, self.obstacles.max_splits()) {
Containment::Inside => Validity::Valid,
Containment::NotInside | Containment::Unknown => Validity::Unknown,
}
}
}
impl<R: Reach<N> + Steer<N, R::Control>, const N: usize> ValidityChecker<Euclidean<N>>
for ReachChecker<R, N>
{
fn check_state(&self, state: &[f64; N]) -> Validity {
let tube = SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&self.tube(state)));
self.obstacles.check_set(&tube).into()
}
fn check_motion(&self, _: &Euclidean<N>, from: &[f64; N], to: &[f64; N]) -> Validity {
let (control, end) = self.reach.steer(from, to);
#[expect(
clippy::float_cmp,
reason = "the motion must end exactly at `to`, where the next tube is centered"
)]
let misses_target = end != *to;
if misses_target {
return Validity::Unknown;
}
let initial = SparsePolyZonotope::from_zonotope(&Zonotope::from_box(&self.tube(from)));
let mut cover = Vec::new();
let (verdict, end_set) =
check_edge(&self.reach, &self.obstacles, &initial, &control, &mut cover);
let Some(end_set) = end_set.filter(|_| verdict == SafetyVerdict::Safe) else {
return verdict.into();
};
self.returns_into_tube(&end_set, to)
}
}