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