1use alloc::vec::Vec;
12
13use rand_core::Rng;
14
15use crate::{Path, StateSpace, ValidityChecker, unit_f64};
16
17pub fn shortcut<Sp, C>(
52 space: &Sp,
53 checker: &C,
54 path: &Path<Sp::State>,
55 max_edge: f64,
56) -> Path<Sp::State>
57where
58 Sp: StateSpace,
59 C: ValidityChecker<Sp>,
60{
61 let states = &path.states;
62 let mut kept = Vec::new();
63 let mut current = 0;
64
65 while current + 1 < states.len() {
66 kept.push(states[current].clone());
67 current = furthest_reachable(space, checker, states, current, max_edge);
68 }
69
70 kept.extend(states.last().cloned());
71
72 cheaper(space, kept, path)
73}
74
75fn furthest_reachable<Sp, C>(
78 space: &Sp,
79 checker: &C,
80 states: &[Sp::State],
81 from: usize,
82 max_edge: f64,
83) -> usize
84where
85 Sp: StateSpace,
86 C: ValidityChecker<Sp>,
87{
88 (from + 2..states.len())
89 .rev()
90 .find(|&to| is_direct_motion_allowed(space, checker, &states[from], &states[to], max_edge))
91 .unwrap_or(from + 1)
92}
93
94fn is_direct_motion_allowed<Sp, C>(
96 space: &Sp,
97 checker: &C,
98 from: &Sp::State,
99 to: &Sp::State,
100 max_edge: f64,
101) -> bool
102where
103 Sp: StateSpace,
104 C: ValidityChecker<Sp>,
105{
106 space.distance(from, to) <= max_edge && checker.check_motion(space, from, to).is_valid()
107}
108
109pub fn shortcut_random<Sp, C, R>(
144 space: &Sp,
145 checker: &C,
146 path: &Path<Sp::State>,
147 max_edge: f64,
148 attempts: usize,
149 rng: &mut R,
150) -> Path<Sp::State>
151where
152 Sp: StateSpace,
153 C: ValidityChecker<Sp>,
154 R: Rng + ?Sized,
155{
156 let mut states = path.states.clone();
157
158 for _ in 0..attempts {
159 if states.len() < 3 {
160 break;
161 }
162
163 let cut = RandomCut::draw(space, &states, rng);
164 if let Some(spliced) = cut.splice(space, checker, &states, max_edge) {
165 states = spliced;
166 }
167 }
168
169 cheaper(space, states, path)
170}
171
172struct RandomCut {
174 first_segment: usize,
176 first_t: f64,
178 second_segment: usize,
180 second_t: f64,
182}
183
184impl RandomCut {
185 fn draw<Sp: StateSpace, R: Rng + ?Sized>(
187 space: &Sp,
188 states: &[Sp::State],
189 rng: &mut R,
190 ) -> Self {
191 let lengths: Vec<f64> = states
192 .windows(2)
193 .map(|pair| space.distance(&pair[0], &pair[1]))
194 .collect();
195 let total: f64 = lengths.iter().sum();
196 let (a, b) = (unit_f64(rng) * total, unit_f64(rng) * total);
197 let ((first_segment, first_t), (second_segment, second_t)) =
198 (locate(&lengths, a.min(b)), locate(&lengths, a.max(b)));
199
200 Self {
201 first_segment,
202 first_t,
203 second_segment,
204 second_t,
205 }
206 }
207
208 fn splice<Sp, C>(
211 &self,
212 space: &Sp,
213 checker: &C,
214 states: &[Sp::State],
215 max_edge: f64,
216 ) -> Option<Vec<Sp::State>>
217 where
218 Sp: StateSpace,
219 C: ValidityChecker<Sp>,
220 {
221 if self.first_segment >= self.second_segment {
222 return None;
223 }
224
225 let point =
226 |segment: usize, t: f64| space.interpolate(&states[segment], &states[segment + 1], t);
227 let from = point(self.first_segment, self.first_t);
228 let to = point(self.second_segment, self.second_t);
229
230 let old = space.distance(&from, &states[self.first_segment + 1])
231 + path_length(space, &states[self.first_segment + 1..=self.second_segment])
232 + space.distance(&states[self.second_segment], &to);
233 if space.distance(&from, &to) >= old {
234 return None;
235 }
236
237 let before = &states[self.first_segment];
240 let after = &states[self.second_segment + 1];
241 let allowed = checker.check_motion(space, before, &from).is_valid()
242 && is_direct_motion_allowed(space, checker, &from, &to, max_edge)
243 && checker.check_motion(space, &to, after).is_valid();
244
245 if !allowed {
246 return None;
247 }
248
249 let mut spliced = states[..=self.first_segment].to_vec();
250 spliced.extend([from, to]);
251 spliced.extend_from_slice(&states[self.second_segment + 1..]);
252
253 Some(spliced)
254 }
255}
256
257fn locate(lengths: &[f64], s: f64) -> (usize, f64) {
260 let mut remaining = s;
261
262 for (segment, &length) in lengths.iter().enumerate() {
263 if remaining < length {
264 return (segment, remaining / length);
265 }
266
267 remaining -= length;
268 }
269
270 (lengths.len() - 1, 1.0)
271}
272
273fn path_length<Sp: StateSpace>(space: &Sp, states: &[Sp::State]) -> f64 {
275 states
276 .windows(2)
277 .map(|pair| space.distance(&pair[0], &pair[1]))
278 .sum()
279}
280
281fn cheaper<Sp: StateSpace>(
283 space: &Sp,
284 states: Vec<Sp::State>,
285 original: &Path<Sp::State>,
286) -> Path<Sp::State> {
287 let cost = path_length(space, &states);
288
289 if cost <= original.cost {
290 Path { states, cost }
291 } else {
292 original.clone()
293 }
294}
295
296#[cfg(test)]
297mod tests {
298 use super::*;
299 use crate::{Euclidean, Validity, discretized_motion};
300 use rand_core::SeedableRng;
301
302 struct Wall;
304
305 impl ValidityChecker<Euclidean<2>> for Wall {
306 fn check_state(&self, s: &[f64; 2]) -> Validity {
307 if (1.4..=1.6).contains(&s[0]) && s[1] < 1.5 {
308 Validity::Invalid
309 } else {
310 Validity::Valid
311 }
312 }
313
314 fn check_motion(&self, space: &Euclidean<2>, from: &[f64; 2], to: &[f64; 2]) -> Validity {
315 discretized_motion(space, from, to, 0.01, |s| self.check_state(s))
316 }
317 }
318
319 fn detour() -> Path<[f64; 2]> {
321 let states = alloc::vec![
322 [0.0, 0.0],
323 [0.0, 1.0],
324 [0.0, 2.0],
325 [1.5, 2.0],
326 [3.0, 2.0],
327 [3.0, 0.0]
328 ];
329 let cost = path_length(&Euclidean::<2>, &states);
330
331 Path { states, cost }
332 }
333
334 fn assert_valid(path: &Path<[f64; 2]>, max_edge: f64) {
336 for pair in path.states.windows(2) {
337 assert_eq!(
338 Wall.check_motion(&Euclidean::<2>, &pair[0], &pair[1]),
339 Validity::Valid
340 );
341 assert!(Euclidean::<2>.distance(&pair[0], &pair[1]) <= max_edge);
342 }
343 }
344
345 #[test]
346 fn greedy_shortcut_keeps_endpoints_and_validity() {
347 let path = detour();
348 let short = shortcut(&Euclidean::<2>, &Wall, &path, f64::INFINITY);
349
350 assert_eq!(short.states.first(), path.states.first());
351 assert_eq!(short.states.last(), path.states.last());
352 assert!(short.cost < path.cost);
353 assert_valid(&short, f64::INFINITY);
354 assert_eq!(short.states, [[0.0, 0.0], [1.5, 2.0], [3.0, 0.0]]);
355 }
356
357 #[test]
358 fn greedy_shortcut_respects_max_edge() {
359 let path = detour();
360 let short = shortcut(&Euclidean::<2>, &Wall, &path, 2.0);
361
362 assert!(short.cost <= path.cost);
363 assert_eq!(short.states.len(), path.states.len() - 1);
364 assert_valid(&short, 2.0);
365 }
366
367 #[test]
368 fn random_shortcut_never_increases_cost() {
369 let path = detour();
370 let mut rng = rand_pcg::Pcg64Mcg::seed_from_u64(9);
371 let smoothed = shortcut_random(&Euclidean::<2>, &Wall, &path, f64::INFINITY, 200, &mut rng);
372
373 assert_eq!(smoothed.states.first(), path.states.first());
374 assert_eq!(smoothed.states.last(), path.states.last());
375 assert!(smoothed.cost < path.cost - 0.5, "{}", smoothed.cost);
376 assert!((smoothed.cost - path_length(&Euclidean::<2>, &smoothed.states)).abs() < 1e-12);
377 assert_valid(&smoothed, f64::INFINITY);
378 }
379}