use sampling_planning::{
Euclidean, GoalRegion, Path, Problem, StateSpace, StraightLine, UniformBox, Validity,
ValidityChecker, discretized_motion,
};
pub type World2d = Problem<Euclidean<2>, UniformBox<2>, Boxes, StraightLine>;
pub type Rect = ([f64; 2], [f64; 2]);
#[derive(Debug, Clone, Default)]
pub struct Boxes {
pub obstacles: Vec<Rect>,
pub fog: Vec<Rect>,
}
fn inside(rect: &Rect, state: &[f64; 2]) -> bool {
(0..2).all(|i| (rect.0[i]..=rect.1[i]).contains(&state[i]))
}
impl ValidityChecker<Euclidean<2>> for Boxes {
fn check_state(&self, state: &[f64; 2]) -> Validity {
if self.obstacles.iter().any(|rect| inside(rect, state)) {
Validity::Invalid
} else if self.fog.iter().any(|rect| inside(rect, state)) {
Validity::Unknown
} else {
Validity::Valid
}
}
fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
discretized_motion(space, from, to, 0.02, |state| self.check_state(state))
}
}
pub fn slalom() -> World2d {
problem(Boxes {
obstacles: vec![([4.0, 0.0], [5.0, 7.0]), ([6.0, 3.0], [7.0, 10.0])],
fog: Vec::new(),
})
}
pub fn pole() -> World2d {
let mut world = problem(Boxes {
obstacles: vec![([4.5, 3.0], [5.5, 7.0])],
fog: Vec::new(),
});
world.start = [1.0, 5.0];
world.goal = GoalRegion::new([9.0, 5.0], 0.5);
world
}
pub const POLE_OPTIMUM: f64 = 8.562;
pub fn problem(checker: Boxes) -> World2d {
Problem {
space: Euclidean::<2>,
sampler: UniformBox::new([0.0, 0.0], [10.0, 10.0]),
checker,
steering: StraightLine::new(1.0),
start: [1.0, 1.0],
goal: GoalRegion::new([9.0, 9.0], 0.5),
}
}
pub fn assert_solves(world: &World2d, path: &Path<[f64; 2]>) {
assert_solves_with(world, path, world.steering.max_step());
}
pub fn assert_solves_with(world: &World2d, path: &Path<[f64; 2]>, max_edge: f64) {
let states = &path.states;
assert_eq!(states.first(), Some(&world.start));
assert!(
world
.goal
.contains(&world.space, states.last().expect("non-empty"))
);
for state in states {
assert!(world.sampler.contains(state), "{state:?} left the box");
}
let mut length = 0.0;
for pair in states.windows(2) {
let validity = world.checker.check_motion(&world.space, &pair[0], &pair[1]);
assert_eq!(validity, Validity::Valid, "segment {pair:?}");
assert!(world.space.distance(&pair[0], &pair[1]) <= max_edge + 1e-9);
length += world.space.distance(&pair[0], &pair[1]);
}
assert!(
(length - path.cost).abs() < 1e-9,
"cost {} vs length {length}",
path.cost
);
}