use thiserror::Error;
use crate::math::{desaturate, saturate_throttle, saturate_unit};
use crate::{ActuatorCommand, ControlOutput, Mixer, Saturation, Vec3};
mod presets;
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Slot {
Motor(u8),
Servo(u8),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MixRow {
slot: Slot,
roll: f32,
pitch: f32,
yaw: f32,
pusher: bool,
}
impl MixRow {
pub const fn motor(index: u8, roll: f32, pitch: f32, yaw: f32) -> Self {
MixRow {
slot: Slot::Motor(index),
roll,
pitch,
yaw,
pusher: false,
}
}
pub const fn servo(index: u8, roll: f32, pitch: f32, yaw: f32) -> Self {
MixRow {
slot: Slot::Servo(index),
roll,
pitch,
yaw,
pusher: false,
}
}
pub const fn pusher(index: u8) -> Self {
MixRow {
slot: Slot::Motor(index),
roll: 0.0,
pitch: 0.0,
yaw: 0.0,
pusher: true,
}
}
pub const fn slot(&self) -> Slot {
self.slot
}
pub const fn roll(&self) -> f32 {
self.roll
}
pub const fn pitch(&self) -> f32 {
self.pitch
}
pub const fn yaw(&self) -> f32 {
self.yaw
}
pub const fn is_pusher(&self) -> bool {
self.pusher
}
pub const fn with_reversed_yaw(self) -> Self {
MixRow {
yaw: -self.yaw,
..self
}
}
fn moment(&self, moments: Vec3) -> f32 {
self.roll * moments.x + self.pitch * moments.y + self.yaw * moments.z
}
fn is_finite(&self) -> bool {
self.roll.is_finite() && self.pitch.is_finite() && self.yaw.is_finite()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MixerConfig {
pub thrust_factor: f32,
pub yaw_ratio: f32,
}
impl Default for MixerConfig {
fn default() -> Self {
MixerConfig {
thrust_factor: 0.9,
yaw_ratio: 2.5,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum MixerError {
#[error("mixer table is empty")]
Empty,
#[error("mixer slot {0:?} is out of range")]
SlotOutOfRange(Slot),
#[error("mixer slot {0:?} appears twice")]
DuplicateSlot(Slot),
#[error("mixer slot {0:?} leaves a gap in the motor slots")]
MotorGap(Slot),
#[error("mixer pusher slot {0:?} comes before a motor slot")]
PusherBeforeMotor(Slot),
#[error("mixer slot {0:?} has a non-finite factor")]
NonFiniteFactor(Slot),
#[error("mixer thrust factor must be in (0, 1)")]
ThrustFactor,
#[error("mixer yaw ratio must be finite and non-negative")]
YawRatio,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TableMixer<const N: usize> {
rows: [MixRow; N],
config: MixerConfig,
motor_count: usize,
saturation: Saturation,
}
impl<const N: usize> TableMixer<N> {
pub fn new(rows: [MixRow; N], config: MixerConfig) -> Result<Self, MixerError> {
validate_rows(&rows)?;
validate_config(&config)?;
Ok(Self::from_valid(rows, config))
}
pub fn config(&self) -> MixerConfig {
self.config
}
pub fn with_config(self, config: MixerConfig) -> Result<Self, MixerError> {
validate_config(&config)?;
Ok(Self { config, ..self })
}
pub fn with_reversed_yaw(self) -> Self {
Self {
rows: self.rows.map(|row| match row.slot {
Slot::Motor(_) => row.with_reversed_yaw(),
Slot::Servo(_) => row,
}),
..self
}
}
pub const fn rows(&self) -> &[MixRow; N] {
&self.rows
}
fn from_valid(rows: [MixRow; N], config: MixerConfig) -> Self {
let motor_count = motor_count(&rows, false);
TableMixer {
rows,
config,
motor_count,
saturation: Saturation::default(),
}
}
}
impl<const N: usize> Mixer for TableMixer<N> {
fn mix(&mut self, command: &ControlOutput) -> ActuatorCommand {
let thrust = saturate_throttle(command.thrust);
let moments = command.moments.map(saturate_unit);
let (cruise_thrust, surface_moments) = command.cruise.map_or((0.0, moments), |cruise| {
(
saturate_throttle(cruise.thrust),
cruise.moments.map(saturate_unit),
)
});
let MixerConfig {
thrust_factor,
yaw_ratio,
} = self.config;
let collective = thrust * thrust_factor;
let headroom = 1.0 - thrust_factor;
let motor_moments = Vec3::new(
moments.x * headroom,
moments.y * headroom,
moments.z * headroom * yaw_ratio,
);
let mut command = ActuatorCommand::default();
let mut servo_clamped = false;
for row in &self.rows {
match row.slot {
Slot::Motor(index) => {
if let Some(motor) = command.motors.get_mut(usize::from(index)) {
*motor = if row.pusher {
cruise_thrust
} else {
collective + row.moment(motor_moments)
};
}
}
Slot::Servo(index) => {
let value = row.moment(surface_moments);
servo_clamped |= value.abs() > 1.0;
if let Some(servo) = command.servos.get_mut(usize::from(index)) {
*servo = value.clamp(-1.0, 1.0);
}
}
}
}
let desaturation = command
.motors
.get_mut(..self.motor_count)
.map(|motors| desaturate(motors, collective))
.unwrap_or_default();
self.saturation = Saturation {
mixer_thrust: desaturation.lowered,
mixer_moments: desaturation.moments_lost || servo_clamped,
..Saturation::default()
};
command
}
fn saturation(&self) -> Saturation {
self.saturation
}
}
fn motor_count(rows: &[MixRow], pushers: bool) -> usize {
rows.iter()
.filter(|row| matches!(row.slot, Slot::Motor(_)) && (pushers || !row.pusher))
.count()
}
fn validate_rows(rows: &[MixRow]) -> Result<(), MixerError> {
if rows.is_empty() {
return Err(MixerError::Empty);
}
for (i, row) in rows.iter().enumerate() {
let (Slot::Motor(index) | Slot::Servo(index)) = row.slot;
if usize::from(index) >= ActuatorCommand::SLOTS {
return Err(MixerError::SlotOutOfRange(row.slot));
}
if rows[..i].iter().any(|earlier| earlier.slot == row.slot) {
return Err(MixerError::DuplicateSlot(row.slot));
}
if !row.is_finite() {
return Err(MixerError::NonFiniteFactor(row.slot));
}
}
let slot_count = motor_count(rows, true);
if let Some(row) = rows
.iter()
.find(|row| matches!(row.slot, Slot::Motor(index) if usize::from(index) >= slot_count))
{
return Err(MixerError::MotorGap(row.slot));
}
let lift_count = motor_count(rows, false);
if let Some(row) = rows.iter().find(
|row| matches!(row.slot, Slot::Motor(index) if row.pusher && usize::from(index) < lift_count),
) {
return Err(MixerError::PusherBeforeMotor(row.slot));
}
Ok(())
}
fn validate_config(config: &MixerConfig) -> Result<(), MixerError> {
if !(config.thrust_factor > 0.0 && config.thrust_factor < 1.0) {
return Err(MixerError::ThrustFactor);
}
if !(config.yaw_ratio >= 0.0 && config.yaw_ratio.is_finite()) {
return Err(MixerError::YawRatio);
}
Ok(())
}