Skip to main content

sampling_planning/
steering.rs

1//! Steering: how a planner extends a node toward a sample.
2
3use crate::StateSpace;
4
5/// Extends a state toward a target state.
6pub trait Steering<Sp: StateSpace> {
7    /// The state reached when moving from `from` toward `toward`.
8    ///
9    /// May stop short of `toward`; the result must be connectable from `from` by
10    /// [`StateSpace::interpolate`], since that segment is what gets validity-checked.
11    fn steer(&self, space: &Sp, from: &Sp::State, toward: &Sp::State) -> Sp::State;
12}
13
14/// Moves along the geodesic toward the target, at most `max_step` far.
15#[derive(Debug, Clone, Copy, PartialEq)]
16pub struct StraightLine {
17    /// The longest step, in units of [`StateSpace::distance`]. Positive and finite.
18    max_step: f64,
19}
20
21impl StraightLine {
22    /// Creates a straight-line steering function with the given maximum step length.
23    ///
24    /// # Panics
25    ///
26    /// Panics if `max_step` is not positive and finite.
27    #[must_use]
28    pub fn new(max_step: f64) -> Self {
29        assert!(
30            max_step.is_finite() && max_step > 0.0,
31            "max_step must be positive and finite"
32        );
33
34        Self { max_step }
35    }
36
37    /// The longest step, in units of [`StateSpace::distance`].
38    #[must_use]
39    pub const fn max_step(&self) -> f64 {
40        self.max_step
41    }
42}
43
44impl<Sp: StateSpace> Steering<Sp> for StraightLine {
45    fn steer(&self, space: &Sp, from: &Sp::State, toward: &Sp::State) -> Sp::State {
46        let distance = space.distance(from, toward);
47
48        if distance <= self.max_step {
49            toward.clone()
50        } else {
51            space.interpolate(from, toward, self.max_step / distance)
52        }
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59    use crate::Euclidean;
60
61    #[test]
62    fn reaches_near_targets_and_clamps_far_ones() {
63        let steering = StraightLine::new(1.0);
64        let space = Euclidean::<2>;
65
66        assert_eq!(steering.steer(&space, &[0.0, 0.0], &[0.6, 0.8]), [0.6, 0.8]);
67
68        let far = steering.steer(&space, &[0.0, 0.0], &[30.0, 40.0]);
69        assert!((space.distance(&[0.0, 0.0], &far) - 1.0).abs() < 1e-12);
70        assert!((far[0] - 0.6).abs() < 1e-12 && (far[1] - 0.8).abs() < 1e-12);
71    }
72}