Skip to main content

stable_flight/commanders/
waypoint.rs

1//! Follows a fixed list of waypoints, looping, holding, or landing at the end.
2
3use core::fmt;
4
5use crate::commanders::{TouchdownConfig, TouchdownDetector};
6use crate::controllers::InvalidConfig;
7use crate::math::all_finite;
8use crate::{Command, Commander, ControlInput, LandCommand, Vec2, VehicleState, WaypointCommand};
9
10#[cfg(test)]
11mod tests;
12
13/// Default horizontal distance (meters) within which the active waypoint is considered
14/// reached and the follower advances to the next one.
15pub const DEFAULT_ACCEPTANCE_RADIUS_M: f32 = 3.0;
16
17/// Default altitude error (meters, either way) within which a waypoint can be reached: PX4's
18/// multicopter `NAV_MC_ALT_RAD` (`src/modules/navigator/navigator_params.yaml`).
19pub const DEFAULT_ALTITUDE_ACCEPTANCE_M: f32 = 0.8;
20
21/// Default altitude acceptance (meters, either way) for a wing-borne leg, which holds altitude
22/// loosely while it flies: PX4's fixed-wing `NAV_FW_ALT_RAD`
23/// (`src/modules/navigator/navigator_params.yaml`).
24pub const DEFAULT_PLANE_ALTITUDE_ACCEPTANCE_M: f32 = 10.0;
25
26/// Returned by [`WaypointFollower::new`] when given no waypoints; there is nothing to fly.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct EmptyWaypoints;
29
30impl fmt::Display for EmptyWaypoints {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        f.write_str("waypoint list is empty")
33    }
34}
35
36impl core::error::Error for EmptyWaypoints {}
37
38/// What a [`WaypointFollower`] does after reaching the last waypoint.
39#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
40pub enum RouteEnd {
41    /// Wrap to the first waypoint and fly the route again, forever.
42    #[default]
43    Loop,
44    /// Stop on the last waypoint and hover there;
45    /// [`is_complete`](WaypointFollower::is_complete) turns true on reaching it.
46    Hold,
47    /// Land on the last waypoint: on reaching it, descend there
48    /// ([`ControlInput::Land`]) until a [`TouchdownDetector`] reports touchdown, then disarm
49    /// for good. [`is_complete`](WaypointFollower::is_complete) turns true on touchdown.
50    Land,
51}
52
53/// A [`Commander`] that flies a sequence of waypoints.
54///
55/// Each tick it emits the active waypoint as an armed [`ControlInput::Waypoint`]. When the
56/// vehicle is within the acceptance radius of it (horizontal distance), or has passed it along
57/// the leg that leads to it (missed it wide), *and* is within the altitude acceptance of its
58/// altitude, it advances to the next: an acceptance cylinder, as in PX4
59/// (`MissionBlock::is_mission_item_reached_or_completed`). So a waypoint straight above the
60/// vehicle is reached at the end of the climb, not on the ground.
61///
62/// With [`with_wait_for_altitude`](Self::with_wait_for_altitude) on, for wing-borne legs,
63/// the follower waits on a waypoint it reaches or passes outside the altitude acceptance: it
64/// emits the waypoint without a velocity until within the acceptance, wherever the vehicle
65/// is by then, and only then advances. Plane guidance loiters around it, where a velocity
66/// would fly the line through it on and away (#451). PX4's fixed-wing mode manager loiters
67/// the same way (`FixedWingModeManager::handle_setpoint_type`). It is off
68/// by default: copter guidance flies *to* the waypoint, so it can't run away, and waiting
69/// would stop it on every waypoint of a descending route its altitude loop trails (the
70/// figure eight slowed below 2 m/s on 6 of its legs).
71///
72/// After the last it follows its [`RouteEnd`]: wrap to the first ([`RouteEnd::Loop`], the
73/// default), hold the last ([`RouteEnd::Hold`]), or land on the last and disarm
74/// ([`RouteEnd::Land`]). It knows nothing about where the waypoints came from or what shape
75/// they trace.
76///
77/// So the vehicle flies each leg at cruise speed instead of slowing at every waypoint, a
78/// waypoint without its own `velocity_mps` is emitted with one along the leg that leads to it:
79/// from the previous waypoint, at the waypoint's `cruise_speed_mps`. The first waypoint
80/// flown, a waypoint with no positive cruise speed, and the waypoint held at the route's end
81/// get none, so the vehicle stops on them.
82///
83/// Generic over the storage: anything that is `AsRef<[WaypointCommand]>`. Firmware can use a
84/// `[WaypointCommand; N]` or `&'static [WaypointCommand]`; a host can use a `Vec`. It never
85/// allocates.
86///
87/// # Examples
88///
89/// ```
90/// use stable_flight::{Vec2, Vec3};
91/// use stable_flight::commanders::{RouteEnd, WaypointFollower};
92/// use stable_flight::{Commander, ControlInput, VehicleState, WaypointCommand};
93///
94/// let square = [
95///     WaypointCommand { position_m: Vec2::zeros(), altitude_m: 10.0, ..Default::default() },
96///     WaypointCommand { position_m: Vec2::new(20.0, 0.0), altitude_m: 10.0, ..Default::default() },
97///     WaypointCommand { position_m: Vec2::new(20.0, 20.0), altitude_m: 10.0, ..Default::default() },
98///     WaypointCommand { position_m: Vec2::new(0.0, 20.0), altitude_m: 10.0, ..Default::default() },
99/// ];
100/// let mut follower = WaypointFollower::new(square)
101///     .expect("non-empty")
102///     .with_acceptance_radius(2.0)
103///     .with_route_end(RouteEnd::Hold);
104///
105/// // Starting on the first waypoint, at its altitude, the follower advances to the second.
106/// let on_first = VehicleState {
107///     position_m: Vec3::new(0.0, 0.0, 10.0),
108///     ..Default::default()
109/// };
110/// let command = follower.next_command(0.004, &on_first);
111/// let ControlInput::Waypoint(target) = command.input else {
112///     unreachable!("WaypointFollower only emits waypoint commands");
113/// };
114/// assert_eq!(target.position_m.x, 20.0);
115/// assert!(!follower.is_complete());
116/// ```
117#[derive(Debug, Clone)]
118pub struct WaypointFollower<W> {
119    waypoints: W,
120    current: usize,
121    acceptance_radius_squared: f32,
122    altitude_acceptance_m: f32,
123    route_end: RouteEnd,
124    /// Unit direction of the leg into the active waypoint, from the previous one; `None` for
125    /// the first waypoint flown or a zero-length leg. Set on each advance, so the per-tick
126    /// path does no sqrt.
127    leg_direction: Option<Vec2>,
128    /// Velocity emitted with the active waypoint when it has none of its own.
129    leg_velocity_mps: Option<Vec2>,
130    /// The last waypoint has been reached under [`RouteEnd::Hold`] or [`RouteEnd::Land`].
131    reached_end: bool,
132    /// Wait on a waypoint reached off its altitude, for wing-borne legs.
133    wait_for_altitude: bool,
134    /// The vehicle came near or past the active waypoint outside its altitude acceptance,
135    /// with `wait_for_altitude` on: it is emitted without a velocity until within it.
136    /// Latched, since circling the waypoint takes the vehicle back out of the radius and
137    /// before it along the leg.
138    waiting_for_altitude: bool,
139    /// Watches the land under [`RouteEnd::Land`].
140    touchdown: TouchdownDetector,
141}
142
143impl<W: AsRef<[WaypointCommand]>> WaypointFollower<W> {
144    /// Starts at the first waypoint with [`DEFAULT_ACCEPTANCE_RADIUS_M`] and
145    /// [`DEFAULT_ALTITUDE_ACCEPTANCE_M`].
146    ///
147    /// # Errors
148    ///
149    /// Returns [`EmptyWaypoints`] if `waypoints` is empty.
150    pub fn new(waypoints: W) -> Result<Self, EmptyWaypoints> {
151        if waypoints.as_ref().is_empty() {
152            return Err(EmptyWaypoints);
153        }
154        Ok(WaypointFollower {
155            waypoints,
156            current: 0,
157            acceptance_radius_squared: DEFAULT_ACCEPTANCE_RADIUS_M * DEFAULT_ACCEPTANCE_RADIUS_M,
158            altitude_acceptance_m: DEFAULT_ALTITUDE_ACCEPTANCE_M,
159            route_end: RouteEnd::default(),
160            leg_direction: None,
161            leg_velocity_mps: None,
162            reached_end: false,
163            wait_for_altitude: false,
164            waiting_for_altitude: false,
165            touchdown: TouchdownDetector::default(),
166        })
167    }
168
169    /// Sets what happens after the last waypoint (default [`RouteEnd::Loop`]).
170    pub fn with_route_end(mut self, route_end: RouteEnd) -> Self {
171        self.route_end = route_end;
172        self
173    }
174
175    /// Overrides the horizontal acceptance radius (meters). `radius_m` must be non-negative.
176    pub fn with_acceptance_radius(mut self, radius_m: f32) -> Self {
177        debug_assert!(
178            radius_m >= 0.0,
179            "acceptance radius must be non-negative, got {radius_m}"
180        );
181        self.acceptance_radius_squared = radius_m * radius_m;
182        self
183    }
184
185    /// Overrides the altitude acceptance (meters, either way; default
186    /// [`DEFAULT_ALTITUDE_ACCEPTANCE_M`]). A wing-borne leg wants a looser band
187    /// ([`DEFAULT_PLANE_ALTITUDE_ACCEPTANCE_M`]). `altitude_m` must be non-negative.
188    pub fn with_altitude_acceptance(mut self, altitude_m: f32) -> Self {
189        self.set_altitude_acceptance(altitude_m);
190        self
191    }
192
193    /// Sets the altitude acceptance (meters, either way) from the next tick, e.g. per leg as
194    /// the regime flown changes. `altitude_m` must be non-negative.
195    pub fn set_altitude_acceptance(&mut self, altitude_m: f32) {
196        debug_assert!(
197            altitude_m >= 0.0,
198            "altitude acceptance must be non-negative, got {altitude_m}"
199        );
200        self.altitude_acceptance_m = altitude_m;
201    }
202
203    /// Sets when a land under [`RouteEnd::Land`] has touched down (default
204    /// [`TouchdownConfig::default`]).
205    ///
206    /// # Errors
207    ///
208    /// [`InvalidConfig`] if `config` fails [`TouchdownConfig::validate`].
209    pub fn with_touchdown(mut self, config: TouchdownConfig) -> Result<Self, InvalidConfig> {
210        self.touchdown = TouchdownDetector::new(config)?;
211        Ok(self)
212    }
213
214    /// Turns on waiting on a waypoint reached or passed off its altitude, for wing-borne legs
215    /// (default off): see [`WaypointFollower`].
216    pub fn with_wait_for_altitude(mut self, wait: bool) -> Self {
217        self.set_wait_for_altitude(wait);
218        self
219    }
220
221    /// Turns waiting for a waypoint's altitude on or off from the next tick, e.g. per leg as
222    /// the regime flown changes. Turning it off ends a wait.
223    pub fn set_wait_for_altitude(&mut self, wait: bool) {
224        self.wait_for_altitude = wait;
225        self.waiting_for_altitude &= wait;
226    }
227
228    /// What the follower does after the last waypoint.
229    pub fn route_end(&self) -> RouteEnd {
230        self.route_end
231    }
232
233    /// The waypoints being followed.
234    pub fn waypoints(&self) -> &[WaypointCommand] {
235        self.waypoints.as_ref()
236    }
237
238    /// Index of the active waypoint.
239    pub fn current_index(&self) -> usize {
240        self.current
241    }
242
243    /// True once the last waypoint has been reached under [`RouteEnd::Hold`] (the follower
244    /// keeps holding it), or once landed on it under [`RouteEnd::Land`] (the follower stays
245    /// disarmed). Always false under [`RouteEnd::Loop`].
246    pub fn is_complete(&self) -> bool {
247        match self.route_end {
248            RouteEnd::Loop => false,
249            RouteEnd::Hold => self.reached_end,
250            RouteEnd::Land => self.touchdown.touched_down(),
251        }
252    }
253
254    /// Makes `next` the active waypoint, arriving from `previous`.
255    fn advance(&mut self, previous: usize, next: usize) {
256        self.current = next;
257        self.waiting_for_altitude = false;
258        let waypoints = self.waypoints.as_ref();
259        let to = &waypoints[next];
260        // A zero-length or non-finite leg has no direction.
261        self.leg_direction = (to.position_m - waypoints[previous].position_m)
262            .try_normalize(0.0)
263            .filter(all_finite);
264        let holds_here = self.route_end != RouteEnd::Loop && next == waypoints.len() - 1;
265        // `>` is false for NaN: no positive cruise speed, no leg velocity.
266        self.leg_velocity_mps = if !holds_here && to.cruise_speed_mps > 0.0 {
267            self.leg_direction
268                .map(|direction| direction * to.cruise_speed_mps)
269                .filter(all_finite)
270        } else {
271            None
272        };
273    }
274}
275
276impl<W: AsRef<[WaypointCommand]>> Commander for WaypointFollower<W> {
277    fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
278        let waypoints = self.waypoints.as_ref();
279
280        // Compare squared horizontal distance to avoid a per-tick sqrt.
281        let target = &waypoints[self.current];
282        let dx = target.position_m.x - current_state.position_m.x;
283        let dy = target.position_m.y - current_state.position_m.y;
284        let within_radius = dx * dx + dy * dy <= self.acceptance_radius_squared;
285        // Past the waypoint along its leg: the vehicle missed it wide. Without this, the leg
286        // velocity fed forward would park it past the waypoint, outside the radius, where the
287        // position loop's pull back balances it.
288        let passed = self
289            .leg_direction
290            .is_some_and(|direction| direction.x * dx + direction.y * dy <= 0.0);
291        // `<=` is false for NaN: a non-finite altitude never reaches a waypoint.
292        let at_altitude =
293            (target.altitude_m - current_state.position_m.z).abs() <= self.altitude_acceptance_m;
294        if self.wait_for_altitude && (within_radius || passed) && !at_altitude {
295            self.waiting_for_altitude = true;
296        }
297        let arrived = within_radius || passed || self.waiting_for_altitude;
298        if !self.reached_end && arrived && at_altitude {
299            let previous = self.current;
300            let last = waypoints.len() - 1;
301            match self.route_end {
302                RouteEnd::Hold | RouteEnd::Land if previous == last => self.reached_end = true,
303                _ => self.advance(previous, (previous + 1) % waypoints.len()),
304            }
305        }
306
307        if self.route_end == RouteEnd::Land && self.reached_end {
308            let land = ControlInput::Land(LandCommand {
309                position_m: self.waypoints.as_ref()[self.current].position_m,
310            });
311            let down = self.touchdown.update(dt, current_state.velocity_mps.z);
312            return Command::new(!down, land);
313        }
314
315        let mut target = self.waypoints.as_ref()[self.current];
316        if self.waiting_for_altitude {
317            target.velocity_mps = None;
318        } else if target.velocity_mps.is_none() {
319            target.velocity_mps = self.leg_velocity_mps;
320        }
321        Command::armed(ControlInput::Waypoint(target))
322    }
323}