stable_flight/guidance/vtol/off_nose.rs
1//! [`OffNoseSpeed`]: a quadplane's copter-flight speed cut while its nose is off the way to its
2//! waypoint, so it doesn't fly fast sideways or tail first.
3
4use crate::controllers::{InvalidConfig, check_limit};
5use crate::math::{DEG, wrap_angle};
6use crate::{Configurable, VehicleState, WaypointCommand};
7
8mod params;
9#[cfg(test)]
10mod tests;
11
12/// Default [`OffNoseSpeedConfig::speed_mps`], in m/s: its 5 m/s tail first is ArduPilot's
13/// quadplane waypoint speed (`Q_WP_SPD`, `ArduPlane/quadplane.cpp:609`) and the speed the
14/// RealFlight Titan Cobra flies legs behind it cleanly (#433). On the sim quadplanes it holds
15/// an uncapped leg's turnaround within 1° of the tilt cap, where uncapped it overshoots by up
16/// to 12° (#437).
17pub const DEFAULT_OFF_NOSE_SPEED_MPS: f32 = 15.0;
18
19/// Heading error, from the nose to the bearing to the waypoint, up to which the speed isn't
20/// cut (ArduPilot, `ArduPlane/quadplane.cpp:3087-3105`).
21const FREE_RAD: f32 = 20.0 * DEG;
22
23/// Heading error at and past which the speed is cut the most (ArduPilot, as above).
24const FULL_RAD: f32 = 160.0 * DEG;
25
26/// What the speed is divided by at [`FULL_RAD`] (ArduPilot, as above).
27const FULL_DIVISOR: f32 = 3.0;
28
29/// [`OffNoseSpeed`] settings.
30#[derive(Debug, Clone, Copy, PartialEq)]
31pub struct OffNoseSpeedConfig {
32 /// Speed, in m/s, that the cut divides: the cap just past 20° off the nose, a third of it
33 /// from 160°; `0` is off. Non-negative and finite. Defaults to
34 /// [`DEFAULT_OFF_NOSE_SPEED_MPS`].
35 pub speed_mps: f32,
36}
37
38impl OffNoseSpeedConfig {
39 /// `Ok` when the speed is non-negative and finite.
40 ///
41 /// # Errors
42 ///
43 /// [`InvalidConfig`] naming `speed_mps`.
44 pub fn validate(&self) -> Result<(), InvalidConfig> {
45 check_limit("speed_mps", self.speed_mps)
46 }
47}
48
49impl Default for OffNoseSpeedConfig {
50 /// [`DEFAULT_OFF_NOSE_SPEED_MPS`].
51 fn default() -> Self {
52 OffNoseSpeedConfig {
53 speed_mps: DEFAULT_OFF_NOSE_SPEED_MPS,
54 }
55 }
56}
57
58/// Caps a quadplane's waypoint speed in copter flight by how far the nose is off the bearing to
59/// the waypoint, as ArduPilot's quadplane does (`get_scaled_wp_speed`,
60/// `ArduPlane/quadplane.cpp:3087-3105`): uncut within 20°, then
61/// [`speed_mps`](OffNoseSpeedConfig::speed_mps) divided by a factor rising linearly from 1 at
62/// 20° to 3 at 160° and past it. The waypoint's own cruise speed still applies when lower.
63///
64/// A quadplane's wing and tail push it around flying sideways or tail first: tail first at
65/// 15 m/s the RealFlight Titan Cobra pitched past what its lift rotors hold and flipped (#437).
66/// Turning the nose along the leg (copter guidance's
67/// [`waypoint_yaw_radps`](crate::guidance::copter::CopterGuidanceConfig::waypoint_yaw_radps))
68/// leaves the turnarounds, an overshoot flown back along the leg, and legs with the turn off.
69///
70/// # Examples
71///
72/// ```
73/// use stable_flight::guidance::vtol::{OffNoseSpeed, OffNoseSpeedConfig};
74/// use stable_flight::{Vec2, VehicleState, WaypointCommand};
75///
76/// let off_nose = OffNoseSpeed::new(OffNoseSpeedConfig { speed_mps: 15.0 });
77/// let behind = WaypointCommand { position_m: Vec2::new(-100.0, 0.0), ..Default::default() };
78/// let capped = off_nose.cap(&behind, &VehicleState::default()); // heading north
79/// assert_eq!(capped.cruise_speed_mps, 5.0);
80/// ```
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct OffNoseSpeed {
83 config: OffNoseSpeedConfig,
84}
85
86impl OffNoseSpeed {
87 /// The cut with `config`.
88 ///
89 /// # Panics
90 ///
91 /// If `config` is invalid ([`OffNoseSpeedConfig::validate`]).
92 pub fn new(config: OffNoseSpeedConfig) -> Self {
93 if let Err(error) = config.validate() {
94 panic!("invalid OffNoseSpeedConfig: {error}");
95 }
96 OffNoseSpeed { config }
97 }
98
99 /// `waypoint` with its cruise speed lowered to the cap for the vehicle's heading and
100 /// position; unchanged when off, within 20° of the nose, or below the cap already. A
101 /// non-finite position or heading leaves it unchanged (input policy).
102 pub fn cap(&self, waypoint: &WaypointCommand, state: &VehicleState) -> WaypointCommand {
103 let to_m = waypoint.position_m - state.position_m.xy();
104 let bearing_rad = libm::atan2f(to_m.y, to_m.x);
105 let cap_mps = self.cap_mps(wrap_angle(bearing_rad - state.heading_rad).abs());
106 // `>` is false for NaN: an unknown cap, or no cruise speed, takes the cap.
107 let cruise_mps = waypoint.cruise_speed_mps;
108 if !cap_mps.is_finite() || (cruise_mps > 0.0 && cruise_mps <= cap_mps) {
109 return *waypoint;
110 }
111 WaypointCommand {
112 cruise_speed_mps: cap_mps,
113 ..*waypoint
114 }
115 }
116
117 /// The speed cap, in m/s, `error_rad` off the nose: infinite when off, within 20°, or for
118 /// a NaN error.
119 fn cap_mps(&self, error_rad: f32) -> f32 {
120 let speed_mps = self.config.speed_mps;
121 // `>` is false for NaN.
122 if !(speed_mps > 0.0 && error_rad > FREE_RAD) {
123 return f32::INFINITY;
124 }
125 let share = ((error_rad - FREE_RAD) / (FULL_RAD - FREE_RAD)).min(1.0);
126 speed_mps / (1.0 + (FULL_DIVISOR - 1.0) * share)
127 }
128}
129
130impl Configurable for OffNoseSpeed {
131 type Config = OffNoseSpeedConfig;
132
133 fn config(&self) -> &OffNoseSpeedConfig {
134 &self.config
135 }
136
137 /// Validates with [`OffNoseSpeedConfig::validate`]; applies from the next tick.
138 fn set_config(&mut self, config: OffNoseSpeedConfig) -> Result<(), InvalidConfig> {
139 config.validate()?;
140 self.config = config;
141 Ok(())
142 }
143}