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