use rand_core::Rng;
use super::{Error, growth::Growth};
use crate::{
LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
};
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RrtConfig {
pub goal_bias: f64,
}
impl Default for RrtConfig {
fn default() -> Self {
Self { goal_bias: 0.05 }
}
}
#[derive(Clone)]
pub struct Rrt<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
growth: Growth<Sp, Sa, C, St, N>,
}
impl<Sp, Sa, C, St> Rrt<Sp, Sa, C, St>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
St: Steering<Sp>,
{
pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtConfig) -> Result<Self, Error> {
Self::with_nearest_neighbors(problem, config, LinearScan::default())
}
}
impl<Sp, Sa, C, St, N> Rrt<Sp, Sa, C, St, N>
where
Sp: StateSpace,
Sa: Sampler<Sp::State>,
C: ValidityChecker<Sp>,
St: Steering<Sp>,
N: NearestNeighbors<Sp>,
{
pub fn with_nearest_neighbors(
problem: Problem<Sp, Sa, C, St>,
config: RrtConfig,
nn: N,
) -> Result<Self, Error> {
Ok(Self {
growth: Growth::new(problem, config.goal_bias, nn)?,
})
}
pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
let (nearest, new) = self.growth.propose(rng);
if !self.growth.is_motion_valid(nearest, &new) {
return false;
}
let cost = self.growth.cost_via(nearest, &new);
self.growth.add(new, nearest, cost);
true
}
pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
for _ in 0..iterations {
self.step(rng);
}
}
pub fn solve<R: Rng + ?Sized>(
&mut self,
max_iterations: usize,
rng: &mut R,
) -> Option<Path<Sp::State>> {
for _ in 0..max_iterations {
if self.growth.has_solution() {
break;
}
self.step(rng);
}
self.growth.best_path()
}
#[must_use]
pub fn best_path(&self) -> Option<Path<Sp::State>> {
self.growth.best_path()
}
#[must_use]
pub fn node_count(&self) -> usize {
self.growth.tree.len()
}
}