stable_flight/view.rs
1//! [`View`]: runs a [`Guidance`] or [`Stabilizer`] in a body frame rotated by a constant, so a
2//! tailsitter hovers nose up on the copter controllers.
3//!
4//! A tailsitter's body frame is the airplane's (x along the nose), so hover sits at pitch 90°,
5//! the Euler singularity, where roll and heading turn about the same axis. Like ArduPilot, the
6//! hover controllers run in a **view** rotated 90° in pitch, where nose-up hover reads level:
7//! ArduPilot builds its tailsitter's VTOL attitude, position, and navigation controllers on an
8//! AHRS view with `ROTATION_PITCH_90` (`ArduPlane/quadplane.cpp`, `create_view`), which rotates
9//! the attitude and gyro into the view (`libraries/AP_AHRS/AP_AHRS_View.cpp`). PX4 rotates the
10//! other way: its tailsitter's body frame is the hover frame, and its fixed-wing controllers
11//! take the rotated view (`_q_mc_to_fw` in `fw_att_control`); a `View` serves either.
12//!
13//! In the view the vehicle's belly is forward: tilting the nose toward the belly is how a
14//! tailsitter tips into forward flight, belly down. Its axes are the airplane's turned: view
15//! roll is airplane yaw, view pitch is pitch, and view yaw is airplane −roll. Gains for a viewed
16//! controller are in those view axes.
17//!
18//! The view's Euler angles are singular at view pitch ±90°, which is forward flight, not hover.
19//! The transition pitches toward it, so a viewed [`CopterStabilizer`] works from a quaternion
20//! attitude error, not Euler differences.
21//!
22//! [`CopterStabilizer`]: crate::stabilizers::copter::CopterStabilizer
23
24use nalgebra::UnitQuaternion;
25
26use crate::controllers::InvalidConfig;
27use crate::tuning::{ProbeConfig, ProbeStatus, Tunable};
28use crate::{
29 Configurable, ControlInput, ControlOutput, CruiseOutput, FlightModeReport, FlightRegime,
30 Guidance, Saturation, Setpoint, Stabilizer, VehicleState, WindEstimate,
31};
32
33#[cfg(test)]
34mod tests;
35
36/// The smallest share of a view axis in a body axis that carries a saturation flag across:
37/// above float noise (a 90° rotation leaves ~1e-7 off-axis).
38const AXIS_SHARE: f32 = 1e-3;
39
40/// A tailsitter's hover view rotation: the airplane body frame turned −90° in pitch, so
41/// nose-up hover reads level (ArduPilot's `ROTATION_PITCH_90` view). [`View::tailsitter`]
42/// flies in it, and a ground station shows hover attitude in it.
43///
44/// # Examples
45///
46/// ```
47/// use stable_flight::VehicleState;
48/// use stable_flight::nalgebra::UnitQuaternion;
49/// use stable_flight::view::tailsitter_rotation;
50///
51/// let nose_up = UnitQuaternion::from_euler_angles(0.0, core::f32::consts::FRAC_PI_2, 0.0);
52/// let hover = VehicleState { attitude: nose_up, ..Default::default() };
53/// assert!(hover.rotate_body(&tailsitter_rotation()).pitch_rad.abs() < 1e-6);
54/// ```
55pub fn tailsitter_rotation() -> UnitQuaternion<f32> {
56 UnitQuaternion::from_euler_angles(0.0, -core::f32::consts::FRAC_PI_2, 0.0)
57}
58
59/// A [`Guidance`] or [`Stabilizer`] run in a body frame rotated by a constant.
60///
61/// `rotation` is the view's frame expressed in the vehicle's body frame. Each tick the inner
62/// component sees the state in the view ([`VehicleState::rotate_body`]); a viewed stabilizer's
63/// moments are rotated back into the body frame for the mixer, and its per-axis saturation
64/// flags with them. Config ([`Configurable`], so params too) and autotune probes ([`Tunable`])
65/// pass through to the inner component, in view axes; the probes' frame
66/// ([`Tunable::probe_frame`]) is the view, so the autotune supervisor
67/// ([`Autotune`](crate::tuning::autotune::Autotune)) judges its envelope in view axes too.
68///
69/// Wrap guidance and the stabilizer each in the same view, as ArduPilot builds each tailsitter
70/// controller on its view (see the [module docs](self)).
71///
72/// # Examples
73///
74/// ```
75/// use core::f32::consts::FRAC_PI_2;
76/// use stable_flight::guidance::copter::{CopterGuidance, CopterGuidanceConfig};
77/// use stable_flight::nalgebra::UnitQuaternion;
78/// use stable_flight::stabilizers::copter::{CopterStabilizer, CopterStabilizerConfig};
79/// use stable_flight::{AttitudeSetpoint, Setpoint, Stabilizer, VehicleState, View};
80///
81/// let guidance = View::tailsitter(CopterGuidance::new(CopterGuidanceConfig::default()));
82/// let mut stabilizer = View::tailsitter(CopterStabilizer::new(CopterStabilizerConfig::default()));
83///
84/// // Hovering nose up is level in the view: no attitude error, so no moments.
85/// let hover = VehicleState {
86/// attitude: UnitQuaternion::from_euler_angles(0.0, FRAC_PI_2, 0.0),
87/// ..Default::default()
88/// };
89/// let setpoint = Setpoint::Attitude(AttitudeSetpoint { thrust: 0.5, ..Default::default() });
90/// let output = stabilizer.stabilize(0.004, &setpoint, &hover);
91/// assert!(output.moments.norm() < 1e-5);
92/// ```
93#[derive(Debug, Clone, PartialEq)]
94pub struct View<T> {
95 inner: T,
96 rotation: UnitQuaternion<f32>,
97}
98
99impl<T> View<T> {
100 /// `inner`, run in the view `rotation` (the view's frame expressed in the body frame).
101 pub fn new(inner: T, rotation: UnitQuaternion<f32>) -> Self {
102 View { inner, rotation }
103 }
104
105 /// `inner`, run in a tailsitter's hover view ([`tailsitter_rotation`]).
106 pub fn tailsitter(inner: T) -> Self {
107 Self::new(inner, tailsitter_rotation())
108 }
109
110 /// The view's frame expressed in the body frame.
111 pub fn rotation(&self) -> &UnitQuaternion<f32> {
112 &self.rotation
113 }
114
115 /// The wrapped component.
116 pub fn inner(&self) -> &T {
117 &self.inner
118 }
119
120 /// The wrapped component, mutably, for its owner's crate-internal calls.
121 pub(crate) fn inner_mut(&mut self) -> &mut T {
122 &mut self.inner
123 }
124
125 /// Unwraps the component.
126 pub fn into_inner(self) -> T {
127 self.inner
128 }
129
130 fn view_state(&self, state: &VehicleState) -> VehicleState {
131 state.rotate_body(&self.rotation)
132 }
133}
134
135impl<G: Guidance> Guidance for View<G> {
136 fn guide(
137 &mut self,
138 dt: f32,
139 regime: FlightRegime,
140 input: &ControlInput,
141 state: &VehicleState,
142 ) -> Setpoint {
143 let state = self.view_state(state);
144 self.inner.guide(dt, regime, input, &state)
145 }
146
147 fn prime(&mut self, state: &VehicleState) {
148 let state = self.view_state(state);
149 self.inner.prime(&state);
150 }
151
152 fn saturation(&self) -> Saturation {
153 self.inner.saturation()
154 }
155
156 fn flight_mode(&self) -> Option<FlightModeReport> {
157 self.inner.flight_mode()
158 }
159
160 /// The inner guidance's: wind is a world quantity, so the view doesn't rotate it.
161 fn wind(&self) -> Option<WindEstimate> {
162 self.inner.wind()
163 }
164}
165
166impl<S: Stabilizer> Stabilizer for View<S> {
167 /// Stabilizes in the view, then rotates the moments (and any cruise moments) back into the
168 /// body frame.
169 fn stabilize(&mut self, dt: f32, setpoint: &Setpoint, state: &VehicleState) -> ControlOutput {
170 let state = self.view_state(state);
171 let output = self.inner.stabilize(dt, setpoint, &state);
172 ControlOutput {
173 moments: self.rotation * output.moments,
174 cruise: output.cruise.map(|cruise| CruiseOutput {
175 moments: self.rotation * cruise.moments,
176 ..cruise
177 }),
178 ..output
179 }
180 }
181
182 fn prime(&mut self, state: &VehicleState) {
183 let state = self.view_state(state);
184 self.inner.prime(&state);
185 }
186
187 /// The inner stabilizer's report, its per-axis `moments` flags carried into body axes: a
188 /// body axis is flagged when a saturated view axis feeds it (for a 90° view, the flags are
189 /// relabeled).
190 fn saturation(&self) -> Saturation {
191 let inner = self.inner.saturation();
192 let to_body = self.rotation.to_rotation_matrix();
193 let moments = core::array::from_fn(|body| {
194 (0..3).any(|view| inner.moments[view] && to_body[(body, view)].abs() > AXIS_SHARE)
195 });
196 Saturation { moments, ..inner }
197 }
198}
199
200impl<T: Configurable> Configurable for View<T> {
201 type Config = T::Config;
202
203 fn config(&self) -> &T::Config {
204 self.inner.config()
205 }
206
207 fn set_config(&mut self, config: T::Config) -> Result<(), InvalidConfig> {
208 self.inner.set_config(config)
209 }
210}
211
212impl<S: Tunable> Tunable for View<S> {
213 type Target = S::Target;
214
215 fn start_probe(&mut self, target: S::Target, config: ProbeConfig) {
216 self.inner.start_probe(target, config);
217 }
218
219 fn probe(&self) -> Option<(S::Target, ProbeStatus)> {
220 self.inner.probe()
221 }
222
223 fn stop_probe(&mut self) -> Option<(S::Target, ProbeStatus)> {
224 self.inner.stop_probe()
225 }
226
227 /// The inner component's probe frame, in this view.
228 fn probe_frame(&self) -> UnitQuaternion<f32> {
229 self.rotation * self.inner.probe_frame()
230 }
231}