1use rand_core::Rng;
4
5use super::{Error, tree::Tree};
6use crate::{
7 LinearScan, NearestNeighbors, Path, Problem, Sampler, StateSpace, Steering, ValidityChecker,
8};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12enum Side {
13 Start,
15 Goal,
17}
18
19impl Side {
20 const fn other(self) -> Self {
22 match self {
23 Self::Start => Self::Goal,
24 Self::Goal => Self::Start,
25 }
26 }
27}
28
29#[derive(Clone)]
31struct Half<S, N> {
32 tree: Tree<S>,
34 nn: N,
36}
37
38#[derive(Clone)]
92pub struct RrtConnect<Sp: StateSpace, Sa, C, St, N = LinearScan<<Sp as StateSpace>::State>> {
93 problem: Problem<Sp, Sa, C, St>,
95 start: Half<Sp::State, N>,
97 goal: Half<Sp::State, N>,
99 active: Side,
101 solution: Option<Path<Sp::State>>,
103}
104
105impl<Sp, Sa, C, St> RrtConnect<Sp, Sa, C, St>
106where
107 Sp: StateSpace,
108 Sa: Sampler<Sp::State>,
109 C: ValidityChecker<Sp>,
110 St: Steering<Sp>,
111{
112 pub fn new(problem: Problem<Sp, Sa, C, St>) -> Result<Self, Error> {
119 Self::with_nearest_neighbors(problem, LinearScan::default())
120 }
121}
122
123impl<Sp, Sa, C, St, N> RrtConnect<Sp, Sa, C, St, N>
124where
125 Sp: StateSpace,
126 Sa: Sampler<Sp::State>,
127 C: ValidityChecker<Sp>,
128 St: Steering<Sp>,
129 N: NearestNeighbors<Sp> + Clone,
130{
131 pub fn with_nearest_neighbors(problem: Problem<Sp, Sa, C, St>, nn: N) -> Result<Self, Error> {
138 let start_validity = problem.checker.check_state(&problem.start);
139 if !start_validity.is_valid() {
140 return Err(Error::InvalidStart(start_validity));
141 }
142
143 let goal_validity = problem.checker.check_state(problem.goal.center());
144 if !goal_validity.is_valid() {
145 return Err(Error::InvalidGoal(goal_validity));
146 }
147
148 let solution = problem
149 .goal
150 .contains(&problem.space, &problem.start)
151 .then(|| Path {
152 states: alloc::vec![problem.start.clone()],
153 cost: 0.0,
154 });
155
156 Ok(Self {
157 start: Half::rooted(problem.start.clone(), nn.clone()),
158 goal: Half::rooted(problem.goal.center().clone(), nn),
159 problem,
160 active: Side::Start,
161 solution,
162 })
163 }
164
165 pub fn step<R: Rng + ?Sized>(&mut self, rng: &mut R) -> bool {
168 if self.solution.is_some() {
169 return true;
170 }
171
172 let side = self.active;
173 self.active = side.other();
174
175 let target = self.problem.sampler.sample(rng);
176 if let Some(new) = self.extend(side, &target) {
177 self.check_direct_goal(side, new);
178
179 if self.solution.is_none() {
180 self.connect(side.other(), new, side);
181 }
182 }
183
184 self.solution.is_some()
185 }
186
187 pub fn solve<R: Rng + ?Sized>(
191 &mut self,
192 max_iterations: usize,
193 rng: &mut R,
194 ) -> Option<Path<Sp::State>> {
195 for _ in 0..max_iterations {
196 if self.step(rng) {
197 break;
198 }
199 }
200
201 self.solution.clone()
202 }
203
204 #[must_use]
206 pub const fn path(&self) -> Option<&Path<Sp::State>> {
207 self.solution.as_ref()
208 }
209
210 #[must_use]
212 pub fn node_count(&self) -> usize {
213 self.start.tree.len() + self.goal.tree.len()
214 }
215
216 const fn half(&self, side: Side) -> &Half<Sp::State, N> {
218 match side {
219 Side::Start => &self.start,
220 Side::Goal => &self.goal,
221 }
222 }
223
224 fn extend(&mut self, side: Side, target: &Sp::State) -> Option<usize> {
228 let nearest = self.nearest(side, target);
229
230 self.step_from(side, nearest, target)
231 }
232
233 fn step_from(&mut self, side: Side, from: usize, target: &Sp::State) -> Option<usize> {
236 let space = &self.problem.space;
237 let tree = &self.half(side).tree;
238 let new = self.problem.steering.steer(space, tree.state(from), target);
239
240 if !self.is_edge_valid(side, from, &new) {
241 return None;
242 }
243
244 let cost = tree.cost(from) + space.distance(tree.state(from), &new);
245 let half = match side {
246 Side::Start => &mut self.start,
247 Side::Goal => &mut self.goal,
248 };
249 let id = half.tree.add(new.clone(), from, cost);
250 half.nn.insert(id, new);
251
252 Some(id)
253 }
254
255 fn connect(&mut self, side: Side, target: usize, target_side: Side) {
258 let goal = self.half(target_side).tree.state(target).clone();
259 let mut current = self.nearest(side, &goal);
260
261 while let Some(next) = self.step_from(side, current, &goal) {
262 let reached = self.half(side).tree.state(next);
263
264 if self.problem.space.distance(reached, &goal) <= 0.0 {
265 self.record_meeting(side, next, target);
266 return;
267 }
268
269 current = next;
270 }
271 }
272
273 fn check_direct_goal(&mut self, side: Side, id: usize) {
276 let tree = &self.start.tree;
277
278 if side == Side::Start
279 && self
280 .problem
281 .goal
282 .contains(&self.problem.space, tree.state(id))
283 {
284 self.solution = Some(Path {
285 states: tree.path_to(id),
286 cost: tree.cost(id),
287 });
288 }
289 }
290
291 fn record_meeting(&mut self, side: Side, id: usize, other: usize) {
294 let (start_id, goal_id) = match side {
295 Side::Start => (id, other),
296 Side::Goal => (other, id),
297 };
298
299 let mut states = self.start.tree.path_to(start_id);
300 let mut to_goal = self.goal.tree.path_to(goal_id);
301 to_goal.reverse();
302 states.extend(to_goal.into_iter().skip(1));
303
304 self.solution = Some(Path {
305 states,
306 cost: self.start.tree.cost(start_id) + self.goal.tree.cost(goal_id),
307 });
308 }
309
310 fn nearest(&self, side: Side, target: &Sp::State) -> usize {
312 self.half(side)
313 .nn
314 .nearest(&self.problem.space, target)
315 .expect("each tree always holds its root")
316 }
317
318 fn is_edge_valid(&self, side: Side, parent: usize, new: &Sp::State) -> bool {
321 let checker = &self.problem.checker;
322 let space = &self.problem.space;
323 let parent_state = self.half(side).tree.state(parent);
324
325 match side {
326 Side::Start => checker.check_motion(space, parent_state, new).is_valid(),
327 Side::Goal => {
328 checker.check_state(new).is_valid()
329 && checker.check_motion(space, new, parent_state).is_valid()
330 }
331 }
332 }
333}
334
335impl<S: Clone, N> Half<S, N> {
336 fn rooted<Sp>(root: S, mut nn: N) -> Self
338 where
339 Sp: StateSpace<State = S>,
340 N: NearestNeighbors<Sp>,
341 {
342 nn.insert(0, root.clone());
343
344 Self {
345 tree: Tree::new(root),
346 nn,
347 }
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354 use crate::{Euclidean, GoalRegion, StraightLine, UniformBox, Validity, discretized_motion};
355 use rand_core::SeedableRng;
356
357 struct OneWay;
360
361 impl ValidityChecker<Euclidean<1>> for OneWay {
362 fn check_state(&self, _: &[f64; 1]) -> Validity {
363 Validity::Valid
364 }
365
366 fn check_motion(&self, space: &Euclidean<1>, from: &[f64; 1], to: &[f64; 1]) -> Validity {
367 let crosses = (from[0] < 5.0) != (to[0] < 5.0);
368
369 if crosses && to[0] < from[0] {
370 Validity::Invalid
371 } else {
372 discretized_motion(space, from, to, 0.1, |_| Validity::Valid)
373 }
374 }
375 }
376
377 #[test]
378 fn paths_are_valid_in_travel_direction() {
379 let problem = Problem {
380 space: Euclidean::<1>,
381 sampler: UniformBox::new([0.0], [10.0]),
382 checker: OneWay,
383 steering: StraightLine::new(0.7),
384 start: [1.0],
385 goal: GoalRegion::new([9.0], 0.1),
386 };
387 let mut planner = RrtConnect::new(problem).expect("valid");
388 let path = planner
389 .solve(10_000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(4))
390 .expect("the gate is passable left to right");
391 for pair in path.states.windows(2) {
392 assert_eq!(
393 OneWay.check_motion(&Euclidean::<1>, &pair[0], &pair[1]),
394 Validity::Valid
395 );
396 }
397
398 assert!((path.cost - 8.0).abs() < 1e-9, "{}", path.cost);
399 }
400
401 #[test]
402 fn one_way_gate_blocks_the_reverse_direction() {
403 let problem = Problem {
406 space: Euclidean::<1>,
407 sampler: UniformBox::new([0.0], [10.0]),
408 checker: OneWay,
409 steering: StraightLine::new(0.7),
410 start: [9.0],
411 goal: GoalRegion::new([1.0], 0.1),
412 };
413 let mut planner = RrtConnect::new(problem).expect("valid");
414
415 assert_eq!(
416 planner.solve(3000, &mut rand_pcg::Pcg64Mcg::seed_from_u64(4)),
417 None
418 );
419 }
420}