use core::fmt;
use crate::commanders::TouchdownDetector;
use crate::math::all_finite;
use crate::{Command, Commander, ControlInput, LandCommand, Vec2, VehicleState, WaypointCommand};
#[cfg(test)]
mod tests;
pub const DEFAULT_ACCEPTANCE_RADIUS_M: f32 = 3.0;
pub const DEFAULT_ALTITUDE_ACCEPTANCE_M: f32 = 0.8;
pub const PLANE_ALTITUDE_ACCEPTANCE_M: f32 = 10.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EmptyWaypoints;
impl fmt::Display for EmptyWaypoints {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("waypoint list is empty")
}
}
impl core::error::Error for EmptyWaypoints {}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum RouteEnd {
#[default]
Loop,
Hold,
Land,
}
#[derive(Debug, Clone)]
pub struct WaypointFollower<W> {
waypoints: W,
current: usize,
acceptance_radius_squared: f32,
altitude_acceptance_m: f32,
route_end: RouteEnd,
leg_direction: Option<Vec2>,
leg_velocity_mps: Option<Vec2>,
reached_end: bool,
wait_for_altitude: bool,
waiting_for_altitude: bool,
touchdown: TouchdownDetector,
}
impl<W: AsRef<[WaypointCommand]>> WaypointFollower<W> {
pub fn new(waypoints: W) -> Result<Self, EmptyWaypoints> {
if waypoints.as_ref().is_empty() {
return Err(EmptyWaypoints);
}
Ok(WaypointFollower {
waypoints,
current: 0,
acceptance_radius_squared: DEFAULT_ACCEPTANCE_RADIUS_M * DEFAULT_ACCEPTANCE_RADIUS_M,
altitude_acceptance_m: DEFAULT_ALTITUDE_ACCEPTANCE_M,
route_end: RouteEnd::default(),
leg_direction: None,
leg_velocity_mps: None,
reached_end: false,
wait_for_altitude: false,
waiting_for_altitude: false,
touchdown: TouchdownDetector::default(),
})
}
pub fn with_route_end(mut self, route_end: RouteEnd) -> Self {
self.route_end = route_end;
self
}
pub fn with_acceptance_radius(mut self, radius_m: f32) -> Self {
debug_assert!(
radius_m >= 0.0,
"acceptance radius must be non-negative, got {radius_m}"
);
self.acceptance_radius_squared = radius_m * radius_m;
self
}
pub fn with_altitude_acceptance(mut self, altitude_m: f32) -> Self {
self.set_altitude_acceptance(altitude_m);
self
}
pub fn set_altitude_acceptance(&mut self, altitude_m: f32) {
debug_assert!(
altitude_m >= 0.0,
"altitude acceptance must be non-negative, got {altitude_m}"
);
self.altitude_acceptance_m = altitude_m;
}
pub fn with_wait_for_altitude(mut self, wait: bool) -> Self {
self.set_wait_for_altitude(wait);
self
}
pub fn set_wait_for_altitude(&mut self, wait: bool) {
self.wait_for_altitude = wait;
self.waiting_for_altitude &= wait;
}
pub fn route_end(&self) -> RouteEnd {
self.route_end
}
pub fn waypoints(&self) -> &[WaypointCommand] {
self.waypoints.as_ref()
}
pub fn current_index(&self) -> usize {
self.current
}
pub fn is_complete(&self) -> bool {
match self.route_end {
RouteEnd::Loop => false,
RouteEnd::Hold => self.reached_end,
RouteEnd::Land => self.touchdown.touched_down(),
}
}
fn advance(&mut self, previous: usize, next: usize) {
self.current = next;
self.waiting_for_altitude = false;
let waypoints = self.waypoints.as_ref();
let to = &waypoints[next];
self.leg_direction = (to.position_m - waypoints[previous].position_m)
.try_normalize(0.0)
.filter(all_finite);
let holds_here = self.route_end != RouteEnd::Loop && next == waypoints.len() - 1;
self.leg_velocity_mps = if !holds_here && to.cruise_speed_mps > 0.0 {
self.leg_direction
.map(|direction| direction * to.cruise_speed_mps)
.filter(all_finite)
} else {
None
};
}
}
impl<W: AsRef<[WaypointCommand]>> Commander for WaypointFollower<W> {
fn next_command(&mut self, dt: f32, current_state: &VehicleState) -> Command {
let waypoints = self.waypoints.as_ref();
let target = &waypoints[self.current];
let dx = target.position_m.x - current_state.position_m.x;
let dy = target.position_m.y - current_state.position_m.y;
let within_radius = dx * dx + dy * dy <= self.acceptance_radius_squared;
let passed = self
.leg_direction
.is_some_and(|direction| direction.x * dx + direction.y * dy <= 0.0);
let at_altitude =
(target.altitude_m - current_state.position_m.z).abs() <= self.altitude_acceptance_m;
if self.wait_for_altitude && (within_radius || passed) && !at_altitude {
self.waiting_for_altitude = true;
}
let arrived = within_radius || passed || self.waiting_for_altitude;
if !self.reached_end && arrived && at_altitude {
let previous = self.current;
let last = waypoints.len() - 1;
match self.route_end {
RouteEnd::Hold | RouteEnd::Land if previous == last => self.reached_end = true,
_ => self.advance(previous, (previous + 1) % waypoints.len()),
}
}
if self.route_end == RouteEnd::Land && self.reached_end {
let land = ControlInput::Land(LandCommand {
position_m: self.waypoints.as_ref()[self.current].position_m,
});
let down = self.touchdown.update(dt, current_state.velocity_mps.z);
return Command::new(!down, land);
}
let mut target = self.waypoints.as_ref()[self.current];
if self.waiting_for_altitude {
target.velocity_mps = None;
} else if target.velocity_mps.is_none() {
target.velocity_mps = self.leg_velocity_mps;
}
Command::armed(ControlInput::Waypoint(target))
}
}