Skip to main content

stable_flight/guidance/vtol/
lift.rs

1//! [`LiftTransition`]: the copter ⇄ plane transition of a lift+cruise VTOL (quadplane), which
2//! stays level and flies its lift rotors and its wing at once, trading lift between them.
3
4use crate::controllers::{InvalidConfig, check, check_limit, check_positive};
5use crate::math::{DEG, assert_dt};
6use crate::{
7    Configurable, FlightMode, FlightModeReport, FlightRegime, ModeRefusal, Vec3, VehicleState,
8};
9use core::f32::consts::FRAC_PI_2;
10
11use super::ForwardGate;
12
13mod params;
14#[cfg(test)]
15mod tests;
16
17/// Default [`LiftTransitionConfig::forward_pitch_max_rad`], in rad: ArduPilot's
18/// `Q_TRAN_PIT_MAX` default.
19pub const DEFAULT_FORWARD_PITCH_MAX_RAD: f32 = 3.0 * DEG;
20
21/// [`LiftTransition`] settings, and the pusher, handoff, pitch, and roll limits a quadplane
22/// guidance flies the transitions with ([`QuadPlaneGuidance`](super::QuadPlaneGuidance)).
23#[derive(Debug, Clone, Copy, PartialEq)]
24pub struct LiftTransitionConfig {
25    /// The airspeed that starts the forward lift ramp, in m/s.
26    pub min_airspeed_mps: f32,
27    /// How long the forward ramp takes the lift share from 1 to 0, in seconds.
28    pub lift_ramp_s: f32,
29    /// The longest a forward transition waits on airspeed before it falls back to copter, in
30    /// seconds. A started lift ramp always runs to its end.
31    pub timeout_s: f32,
32    /// The height above the arming altitude a forward transition needs to start, in meters.
33    pub min_height_m: f32,
34    /// The height above the arming altitude plane flight falls back to copter below, in
35    /// meters; a forward transition also needs it to start. Higher: falls back sooner, with
36    /// more height to lose in the back transition (0.7 m at a 3.5 m/s sink on the sim
37    /// quadplane, 2.4 m at 6.2 m/s and 53 m/s on the sim Alia). `0` turns it off.
38    pub plane_min_height_m: f32,
39    /// How long the back ramp takes the lift share from 0 to 1, in seconds; a fallback skips it.
40    pub back_ramp_s: f32,
41    /// The forward speed below which the back transition completes, in m/s.
42    pub back_speed_mps: f32,
43    /// The longest a back transition runs before it completes, in seconds.
44    pub back_timeout_s: f32,
45    /// The deceleration along the ground track a quadplane's back transition pitches the nose
46    /// up to hold, in m/s². Higher: slows sooner, the wing climbing more on the way. Finite,
47    /// non-negative.
48    pub back_decel_mps2: f32,
49    /// How fast the back transition's nose-up grows while it slows short of
50    /// `back_decel_mps2`, in rad/s per m/s² (rad·s/m); `0` turns the nose-up off, leaving
51    /// drag alone to slow it. Higher: reaches the pitch sooner, overshoots it more. Finite,
52    /// non-negative.
53    pub back_decel_i: f32,
54    /// The most linear thrust the pusher gets through the forward transition, `[0, 1]`.
55    pub forward_thrust: f32,
56    /// How fast the pusher's thrust may rise through the forward transition, in thrust per
57    /// second. Positive.
58    pub pusher_slew_per_s: f32,
59    /// Most pitch, up or down, in rad, in `(0, π/2)`, while the forward transition waits on
60    /// airspeed at 3 m/s of ground speed or more (0 below); twice it plus 2° on the lift ramp,
61    /// as ArduPilot's `Q_TRAN_PIT_MAX` (`SLT_Transition::set_FW_roll_pitch`); always within
62    /// the plane guidance's own pitch limits. Higher: the wing's altitude and airspeed loops
63    /// get more pitch to work with while the lift rotors still carry it.
64    pub forward_pitch_max_rad: f32,
65    /// How long the pusher's thrust blends to the plane guidance's at the handoff into plane
66    /// flight, in seconds ([`ThrustHandoff`](super::ThrustHandoff)); 0 switches at once.
67    pub handoff_s: f32,
68    /// Bank past which a transition is cut short, in radians, in `(0, π]`: forward aborts to
69    /// copter, back completes ([`LiftTransition::cut_short`]).
70    pub roll_limit_rad: f32,
71}
72
73impl LiftTransitionConfig {
74    /// `Ok` when every field is in range: times, ramps, and the slew positive, airspeed, speed,
75    /// height, deceleration and its gain, and handoff non-negative, all finite; the thrust in
76    /// `[0, 1]`, the forward pitch limit in `(0, π/2)`, and the roll limit in `(0, π]`.
77    ///
78    /// # Errors
79    ///
80    /// [`InvalidConfig`] naming the first field out of range.
81    pub fn validate(&self) -> Result<(), InvalidConfig> {
82        check_limit("min_airspeed_mps", self.min_airspeed_mps)?;
83        check_positive("lift_ramp_s", self.lift_ramp_s)?;
84        check_positive("timeout_s", self.timeout_s)?;
85        check_limit("min_height_m", self.min_height_m)?;
86        check_limit("plane_min_height_m", self.plane_min_height_m)?;
87        check_positive("back_ramp_s", self.back_ramp_s)?;
88        check_limit("back_speed_mps", self.back_speed_mps)?;
89        check_positive("back_timeout_s", self.back_timeout_s)?;
90        check_limit("back_decel_mps2", self.back_decel_mps2)?;
91        check_limit("back_decel_i", self.back_decel_i)?;
92        check(
93            "forward_thrust",
94            (0.0..=1.0).contains(&self.forward_thrust),
95            "in [0, 1]",
96        )?;
97        check_positive("pusher_slew_per_s", self.pusher_slew_per_s)?;
98        check(
99            "forward_pitch_max_rad",
100            self.forward_pitch_max_rad > 0.0 && self.forward_pitch_max_rad < FRAC_PI_2,
101            "in (0, π/2) rad",
102        )?;
103        check_limit("handoff_s", self.handoff_s)?;
104        check(
105            "roll_limit_rad",
106            self.roll_limit_rad > 0.0 && self.roll_limit_rad <= core::f32::consts::PI,
107            "in (0, π] rad",
108        )
109    }
110}
111
112impl Default for LiftTransitionConfig {
113    /// ArduPilot's 9 m/s airspeed gate and 5 s lift ramp, PX4's 15 s forward timeout, 3 s back
114    /// ramp, 5 m/s back speed, 10 s back timeout, 2 m/s² back deceleration at gain 0.1, and
115    /// pusher thrust up to full rising at 0.33/s, and 5 m of height, no plane minimum height
116    /// (PX4's `VT_FW_MIN_ALT`), a 0.5 s handoff, ArduPilot's 3° forward pitch limit, and a 45°
117    /// roll limit (as
118    /// [`TransitionConfig`](super::TransitionConfig)); see [`LiftTransition`]'s
119    /// [sources](LiftTransition#sources).
120    fn default() -> Self {
121        LiftTransitionConfig {
122            min_airspeed_mps: 9.0,
123            lift_ramp_s: 5.0,
124            timeout_s: 15.0,
125            min_height_m: 5.0,
126            plane_min_height_m: 0.0,
127            back_ramp_s: 3.0,
128            back_speed_mps: 5.0,
129            back_timeout_s: 10.0,
130            back_decel_mps2: 2.0,
131            back_decel_i: 0.1,
132            forward_thrust: 1.0,
133            pusher_slew_per_s: 0.33,
134            forward_pitch_max_rad: DEFAULT_FORWARD_PITCH_MAX_RAD,
135            handoff_s: 0.5,
136            roll_limit_rad: 45.0_f32.to_radians(),
137        }
138    }
139}
140
141/// What [`LiftTransition::update`] decided this tick.
142#[derive(Debug, Clone, Copy, PartialEq)]
143pub struct LiftTransitionStep {
144    /// The mode to fly this tick.
145    pub mode: FlightMode,
146    /// The share of hover lift the lift rotors carry, in `[0, 1]`: 1 in `Copter`, 0 in `Plane`,
147    /// ramping between them in the transitions (see [`LiftTransition`]).
148    pub lift_share: f32,
149    /// Control passed between hover and plane flight this tick (`ToPlane` → `Plane`,
150    /// `ToCopter` → `Copter`): prime the guidance taking over.
151    pub handoff: bool,
152}
153
154/// The copter ⇄ plane transition state machine of a lift+cruise VTOL: owns the
155/// [`FlightMode`] and the lift rotors' share of the lift, by the rows under [Modes](#modes).
156///
157/// Call [`prime`](Self::prime) when the vehicle arms, then [`update`](Self::update) every
158/// armed tick. Allocation-free and trig-free per tick.
159///
160/// # Modes
161///
162/// The request is a level, as for [`Transition`](super::Transition). First matching row wins:
163///
164/// | Mode | Condition | Next | Lift share | Handoff | Refusal reported |
165/// |---|---|---|---|---|---|
166/// | `Copter` | `Copter` requested | `Copter` | 1 | | none; clears a timeout |
167/// | `Copter` | `Plane` requested after a fallback | `Copter` | 1 | | why: `TransitionTimeout`, `RollError`, `BelowPlaneMinAltitude` |
168/// | `Copter` | `Plane` requested below `min_height_m` or `plane_min_height_m` (or NaN altitude) | `Copter` | 1 | | `BelowMinAltitude` |
169/// | `Copter` | `Plane` requested | `ToPlane`, waiting on airspeed | 1 | | |
170/// | `ToPlane` | `Copter` requested | `Copter` | 1 | | |
171/// | `ToPlane` | the lift ramp has run `lift_ramp_s` | `Plane` | 0 | yes | |
172/// | `ToPlane` | waiting longer than `timeout_s` | `Copter` | 1 | | `TransitionTimeout` |
173/// | `ToPlane` | waiting, and a valid airspeed ≥ `min_airspeed_mps` | `ToPlane`, the lift ramp starts | 1 | | |
174/// | `ToPlane` | otherwise | `ToPlane` | 1 waiting, then `1 − t / lift_ramp_s` | | |
175/// | `Plane` | `Copter` requested | `ToCopter` | 0 | | |
176/// | `Plane` | below `plane_min_height_m` | `ToCopter`, a fallback | 1 | | `BelowPlaneMinAltitude` |
177/// | `ToCopter` | `Plane` requested, and no fallback | `Plane` | 0 | | |
178/// | `ToCopter` | forward speed below `back_speed_mps`, or longer than `back_timeout_s` | `Copter` | 1 | yes | |
179/// | `ToCopter` | otherwise | `ToCopter` | 1 after a fallback, else `t / back_ramp_s`, at most 1 | | |
180///
181/// The lift share is the share of hover lift the lift rotors carry: the guidance flying this
182/// weights the lift rotors' thrust and moments by it. Without a valid airspeed the forward
183/// transition never starts its lift ramp and times out to `Copter`: the wing's speed is unknown,
184/// so handing it the weight could stall it. Once started, the ramp isn't timed out: the wing
185/// has its speed, and abandoning mid-ramp would throw the weight back onto the rotors at once.
186/// The forward speed is the ground velocity along the body `x` axis; when it isn't known (NaN
187/// velocity or attitude), a valid airspeed stands in, and without either the back transition
188/// completes on its timeout.
189///
190/// [`cut_short`](Self::cut_short) ends a transition early as
191/// [`Transition::cut_short`](super::Transition::cut_short) does. Height and abandonment follow
192/// [`Transition`](super::Transition): above the altitude at [`prime`](Self::prime),
193/// refused until then, and after a fallback (a forward transition abandoned, or plane flight
194/// below `plane_min_height_m`) `Plane` held refused until `Copter` is requested: `ToCopter`
195/// completes as if `Copter` were requested, reporting the fallback. A fallback's back
196/// transition gives the lift rotors all the lift from its first tick: the sink that set it off
197/// keeps going while they ramp in (10 m below the floor at 50 m/s on the X-Plane Alia's 10 s
198/// ramp, #493).
199///
200/// # Sources
201///
202/// ArduPilot (`368dc0c428`) and PX4 (`c4e4ef98e9`), described, not copied:
203///
204/// - Forward: ArduPilot holds hover on the lift rotors until airspeed passes `AIRSPEED_MIN`
205///   (9 m/s, `config.h`'s `AIRSPEED_FBW_MIN`), then ramps their throttle down linearly over
206///   `Q_TRANSITION_MS` (5 s, `SLT_Transition::update`); it needs an airspeed sensor
207///   to leave the wait. Its optional timeout (`Q_TRANS_FAIL`, off by default) covers only the
208///   wait (`SLT_Transition::update`); the 15 s is PX4's `VT_TRANS_TIMEOUT`
209///   (`VtolType::isFrontTransitionTimeout`), which also covers the ramp.
210/// - Back: PX4 ramps the lift rotors' weight up over `VT_B_TRANS_RAMP` (3 s,
211///   `Standard::update_transition_state`) and completes once the body-`x` ground speed
212///   is below `MPC_XY_CRUISE` (5 m/s; airspeed without a ground velocity) or after
213///   `VT_B_TRANS_DUR` (10 s, `Standard::update_vtol_state`).
214/// - Fallback: PX4's quad-chute switches to the lift rotors at once and cuts the pusher
215///   (`Standard::update_vtol_state`); ArduPilot entering a VTOL mode from forward flight runs
216///   its vertical controller with the throttle unlimited at once (`QuadPlane::hold_hover`,
217///   `QuadPlane::run_z_controller`).
218/// - Pusher: PX4 slews it to `VT_F_TRANS_THR` (1.0) at `VT_PSHER_SLEW` (0.33/s) going forward
219///   and cuts it going back (`Standard::update_transition_state`); ArduPilot flies it on the
220///   plane controller's throttle going forward, at least `TKOFF_THR_MIN` (cruise throttle when
221///   0) and at most `TKOFF_THR_MAX` (`Plane::apply_throttle_limits`).
222///
223/// # Examples
224///
225/// ```
226/// use stable_flight::guidance::vtol::{LiftTransition, LiftTransitionConfig};
227/// use stable_flight::{FlightMode, FlightRegime, Vec3, VehicleState};
228///
229/// let mut transition = LiftTransition::new(LiftTransitionConfig::default());
230/// transition.prime(&VehicleState::default());
231///
232/// // 10 m up and still slow: the lift rotors hold it while the pusher builds speed.
233/// let slow = VehicleState { position_m: Vec3::new(0.0, 0.0, 10.0), airspeed_mps: Some(4.0), ..Default::default() };
234/// let step = transition.update(0.01, FlightRegime::Plane, &slow);
235/// assert_eq!((step.mode, step.lift_share), (FlightMode::ToPlane, 1.0));
236///
237/// // Past the airspeed gate the lift ramps down.
238/// let fast = VehicleState { airspeed_mps: Some(10.0), ..slow };
239/// transition.update(0.01, FlightRegime::Plane, &fast);
240/// assert!(transition.update(0.01, FlightRegime::Plane, &fast).lift_share < 1.0);
241/// ```
242#[derive(Debug, Clone, PartialEq)]
243pub struct LiftTransition {
244    config: LiftTransitionConfig,
245    gate: ForwardGate,
246    mode: FlightMode,
247    refusal: Option<ModeRefusal>,
248    /// Time in the current transition, in seconds.
249    elapsed_s: f32,
250    /// When the forward lift ramp started, as `elapsed_s`; `None` while waiting on airspeed.
251    ramp_start_s: Option<f32>,
252}
253
254impl LiftTransition {
255    /// A transition in `Copter` with `config`. Until [`prime`](Self::prime) sets the arming
256    /// altitude it has no height reference, so it refuses `Plane` as `BelowMinAltitude`.
257    ///
258    /// # Panics
259    ///
260    /// If `config` is invalid ([`LiftTransitionConfig::validate`]).
261    pub fn new(config: LiftTransitionConfig) -> Self {
262        if let Err(error) = config.validate() {
263            panic!("invalid LiftTransitionConfig: {error}");
264        }
265        LiftTransition {
266            config,
267            gate: ForwardGate::new(),
268            mode: FlightMode::Copter,
269            refusal: None,
270            elapsed_s: 0.0,
271            ramp_start_s: None,
272        }
273    }
274
275    /// Back to `Copter` with no refusal or timeout, and `state`'s altitude as the height
276    /// reference. Call when the vehicle arms.
277    pub fn prime(&mut self, state: &VehicleState) {
278        self.mode = FlightMode::Copter;
279        self.refusal = None;
280        self.elapsed_s = 0.0;
281        self.ramp_start_s = None;
282        self.gate.prime(state);
283    }
284
285    /// Moves toward `requested` and returns this tick's mode and lift share.
286    ///
287    /// # Panics
288    ///
289    /// If `dt` isn't positive and finite.
290    pub fn update(
291        &mut self,
292        dt: f32,
293        requested: FlightRegime,
294        state: &VehicleState,
295    ) -> LiftTransitionStep {
296        assert_dt(dt);
297        self.refusal = None;
298        let mut handoff = false;
299
300        match self.mode {
301            FlightMode::Copter => match requested {
302                FlightRegime::Plane => {
303                    let needed_m = self.config.min_height_m.max(self.config.plane_min_height_m);
304                    self.refusal = self.gate.refusal(state, needed_m);
305                    if self.refusal.is_none() {
306                        self.start(FlightMode::ToPlane);
307                    }
308                }
309                FlightRegime::Copter => self.gate.clear(),
310            },
311            FlightMode::ToPlane => {
312                self.elapsed_s += dt;
313                if requested != FlightRegime::Plane {
314                    self.mode = FlightMode::Copter;
315                } else if self.lift_ramp_done() {
316                    self.mode = FlightMode::Plane;
317                    handoff = true;
318                } else if self.ramp_start_s.is_none() {
319                    if self.elapsed_s > self.config.timeout_s {
320                        self.abandon(ModeRefusal::TransitionTimeout);
321                    } else if self.fast_enough(state) {
322                        self.ramp_start_s = Some(self.elapsed_s);
323                    }
324                }
325            }
326            FlightMode::Plane => {
327                if requested != FlightRegime::Plane {
328                    self.start(FlightMode::ToCopter);
329                } else if self.gate.below(state, self.config.plane_min_height_m) {
330                    self.start(FlightMode::ToCopter);
331                    self.gate.abandon(ModeRefusal::BelowPlaneMinAltitude);
332                    self.refusal = Some(ModeRefusal::BelowPlaneMinAltitude);
333                }
334            }
335            FlightMode::ToCopter => {
336                self.elapsed_s += dt;
337                let plane_requested = requested == FlightRegime::Plane;
338                if plane_requested && !self.gate.fallen_back() {
339                    self.mode = FlightMode::Plane;
340                } else if self.slowed(state) || self.elapsed_s > self.config.back_timeout_s {
341                    self.mode = FlightMode::Copter;
342                    handoff = true;
343                }
344                if plane_requested {
345                    self.refusal = self.gate.fallback();
346                }
347            }
348        }
349
350        LiftTransitionStep {
351            mode: self.mode,
352            lift_share: self.lift_share(),
353            handoff,
354        }
355    }
356
357    /// Cuts a transition short for `refusal` (e.g. [`ModeRefusal::RollError`], from a check the
358    /// caller makes), returning the step to fly this tick instead of the one
359    /// [`update`](Self::update) gave: a forward transition is abandoned to `Copter`, held
360    /// refused until `Copter` is requested; a back transition completes to `Copter` with a
361    /// handoff. Outside a transition it returns the current mode, unchanged.
362    pub fn cut_short(&mut self, refusal: ModeRefusal) -> LiftTransitionStep {
363        let handoff = match self.mode {
364            FlightMode::ToPlane => {
365                self.abandon(refusal);
366                false
367            }
368            FlightMode::ToCopter => {
369                self.mode = FlightMode::Copter;
370                true
371            }
372            _ => false,
373        };
374        LiftTransitionStep {
375            mode: self.mode,
376            lift_share: self.lift_share(),
377            handoff,
378        }
379    }
380
381    /// The mode the last [`update`](Self::update) flew, and why it isn't the requested regime
382    /// when it can't be: what a VTOL guidance reports as its
383    /// [`flight_mode`](crate::Guidance::flight_mode).
384    pub fn report(&self) -> FlightModeReport {
385        FlightModeReport {
386            mode: self.mode,
387            refusal: self.refusal,
388        }
389    }
390
391    /// Whether a fallback holds `Plane` refused until `Copter` is requested.
392    pub(super) fn fallen_back(&self) -> bool {
393        self.gate.fallen_back()
394    }
395
396    /// Enters a transition `mode` from its start.
397    fn start(&mut self, mode: FlightMode) {
398        self.mode = mode;
399        self.elapsed_s = 0.0;
400        self.ramp_start_s = None;
401    }
402
403    /// Gives up a forward transition: back to `Copter`, refused for `refusal` until `Copter`
404    /// is requested.
405    fn abandon(&mut self, refusal: ModeRefusal) {
406        self.mode = FlightMode::Copter;
407        self.gate.abandon(refusal);
408        self.refusal = Some(refusal);
409    }
410
411    /// Whether the forward lift ramp has run its full time.
412    fn lift_ramp_done(&self) -> bool {
413        self.ramp_start_s
414            .is_some_and(|start_s| self.elapsed_s - start_s >= self.config.lift_ramp_s)
415    }
416
417    /// Whether a valid airspeed has reached the forward gate.
418    fn fast_enough(&self, state: &VehicleState) -> bool {
419        state
420            .valid_airspeed_mps()
421            .is_some_and(|airspeed_mps| airspeed_mps >= self.config.min_airspeed_mps)
422    }
423
424    /// Whether the back transition has slowed below its speed, by forward ground speed or,
425    /// without it, a valid airspeed. Unknown speed never has.
426    fn slowed(&self, state: &VehicleState) -> bool {
427        let speed_mps = Some(forward_speed_mps(state))
428            .filter(|speed_mps| speed_mps.is_finite())
429            .or_else(|| state.valid_airspeed_mps());
430        speed_mps.is_some_and(|speed_mps| speed_mps < self.config.back_speed_mps)
431    }
432
433    /// The lift rotors' share of the lift this tick.
434    fn lift_share(&self) -> f32 {
435        match self.mode {
436            FlightMode::Plane => 0.0,
437            FlightMode::ToPlane => self.ramp_start_s.map_or(1.0, |start_s| {
438                (1.0 - (self.elapsed_s - start_s) / self.config.lift_ramp_s).clamp(0.0, 1.0)
439            }),
440            FlightMode::ToCopter if self.gate.fallen_back() => 1.0,
441            FlightMode::ToCopter => (self.elapsed_s / self.config.back_ramp_s).min(1.0),
442            _ => 1.0,
443        }
444    }
445}
446
447impl Configurable for LiftTransition {
448    type Config = LiftTransitionConfig;
449
450    fn config(&self) -> &LiftTransitionConfig {
451        &self.config
452    }
453
454    /// Validates with [`LiftTransitionConfig::validate`]. A running transition keeps its mode
455    /// and times, and follows the new ramps, gates, and timeouts from the next tick.
456    fn set_config(&mut self, config: LiftTransitionConfig) -> Result<(), InvalidConfig> {
457        config.validate()?;
458        self.config = config;
459        Ok(())
460    }
461}
462
463/// The ground velocity along the body `x` axis, in m/s; NaN when the velocity or attitude is.
464fn forward_speed_mps(state: &VehicleState) -> f32 {
465    let nose = state.attitude * Vec3::x();
466    let velocity_mps = state.velocity_mps;
467    // `nose` is NED, the velocity `z` up: the `z` term flips.
468    nose.x * velocity_mps.x + nose.y * velocity_mps.y - nose.z * velocity_mps.z
469}