sampling_planning/trees/
rrt.rs1use rand_core::Rng;
4
5use super::{Error, growth::Growth};
6use crate::{
7 LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
8};
9
10#[derive(Debug, Clone, Copy, PartialEq)]
12pub struct RrtConfig {
13 pub goal_bias: f64,
15}
16
17impl Default for RrtConfig {
18 fn default() -> Self {
20 Self { goal_bias: 0.05 }
21 }
22}
23
24#[derive(Clone)]
30pub struct Rrt<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
31 growth: Growth<Sp, Sa, C, St, N>,
33}
34
35impl<Sp, Sa, C, St> Rrt<Sp, Sa, C, St>
36where
37 Sp: StateSpace,
38 Sa: Sampler<Sp::State>,
39 C: ValidityChecker<Sp>,
40 St: Steering<Sp>,
41{
42 pub fn new(problem: Problem<Sp, Sa, C, St>, config: RrtConfig) -> Result<Self, Error> {
49 Self::with_nearest_neighbors(problem, config, LinearScan::default())
50 }
51}
52
53impl<Sp, Sa, C, St, N> Rrt<Sp, Sa, C, St, N>
54where
55 Sp: StateSpace,
56 Sa: Sampler<Sp::State>,
57 C: ValidityChecker<Sp>,
58 St: Steering<Sp>,
59 N: NearestNeighbors<Sp>,
60{
61 pub fn with_nearest_neighbors(
68 problem: Problem<Sp, Sa, C, St>,
69 config: RrtConfig,
70 nn: N,
71 ) -> Result<Self, Error> {
72 Ok(Self {
73 growth: Growth::new(problem, config.goal_bias, nn)?,
74 })
75 }
76
77 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
79 let (nearest, new) = self.growth.propose(rng);
80 if !self.growth.is_motion_valid(nearest, &new) {
81 return false;
82 }
83
84 let cost = self.growth.cost_via(nearest, &new);
85 self.growth.add(new, nearest, cost);
86
87 true
88 }
89
90 pub fn run<R: Rng + ?Sized>(&mut self, iterations: usize, rng: &mut R) {
92 for _ in 0..iterations {
93 self.step(rng);
94 }
95 }
96
97 pub fn solve<R: Rng + ?Sized>(
101 &mut self,
102 max_iterations: usize,
103 rng: &mut R,
104 ) -> Option<Path<Sp::State>> {
105 for _ in 0..max_iterations {
106 if self.growth.has_solution() {
107 break;
108 }
109
110 self.step(rng);
111 }
112
113 self.growth.best_path()
114 }
115
116 #[must_use]
118 pub fn best_path(&self) -> Option<Path<Sp::State>> {
119 self.growth.best_path()
120 }
121
122 #[must_use]
124 pub fn node_count(&self) -> usize {
125 self.growth.tree.len()
126 }
127}