use crate::controllers::{InvalidConfig, check, check_limit};
use crate::math::{DEG, wrap_angle};
use crate::{Configurable, VehicleState, WaypointCommand};
use core::f32::consts::PI;
mod params;
#[cfg(test)]
mod tests;
pub const DEFAULT_OFF_NOSE_SPEED_MPS: f32 = 15.0;
pub const DEFAULT_OFF_NOSE_FREE_RAD: f32 = 20.0 * DEG;
pub const DEFAULT_OFF_NOSE_FULL_RAD: f32 = 160.0 * DEG;
pub const DEFAULT_OFF_NOSE_TAIL_FIRST_DIVISOR: f32 = 3.0;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OffNoseSpeedConfig {
pub speed_mps: f32,
pub free_rad: f32,
pub full_rad: f32,
pub tail_first_divisor: f32,
}
impl OffNoseSpeedConfig {
pub fn validate(&self) -> Result<(), InvalidConfig> {
check_limit("speed_mps", self.speed_mps)?;
check(
"free_rad",
(0.0..PI).contains(&self.free_rad),
"in [0, π) rad",
)?;
check(
"full_rad",
self.full_rad > 0.0 && self.full_rad <= PI,
"in (0, π] rad",
)?;
check(
"tail_first_divisor",
self.tail_first_divisor >= 1.0 && self.tail_first_divisor.is_finite(),
"at least 1, finite",
)
}
}
impl Default for OffNoseSpeedConfig {
fn default() -> Self {
OffNoseSpeedConfig {
speed_mps: DEFAULT_OFF_NOSE_SPEED_MPS,
free_rad: DEFAULT_OFF_NOSE_FREE_RAD,
full_rad: DEFAULT_OFF_NOSE_FULL_RAD,
tail_first_divisor: DEFAULT_OFF_NOSE_TAIL_FIRST_DIVISOR,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct OffNoseSpeed {
config: OffNoseSpeedConfig,
}
impl OffNoseSpeed {
pub fn new(config: OffNoseSpeedConfig) -> Self {
if let Err(error) = config.validate() {
panic!("invalid OffNoseSpeedConfig: {error}");
}
OffNoseSpeed { config }
}
pub fn cap(&self, waypoint: &WaypointCommand, state: &VehicleState) -> WaypointCommand {
let to_m = waypoint.position_m - state.position_m.xy();
let bearing_rad = libm::atan2f(to_m.y, to_m.x);
let cap_mps = self.cap_mps(wrap_angle(bearing_rad - state.heading_rad).abs());
let cruise_mps = waypoint.cruise_speed_mps;
if !cap_mps.is_finite() || (cruise_mps > 0.0 && cruise_mps <= cap_mps) {
return *waypoint;
}
WaypointCommand {
cruise_speed_mps: cap_mps,
..*waypoint
}
}
fn cap_mps(&self, error_rad: f32) -> f32 {
let OffNoseSpeedConfig {
speed_mps,
free_rad,
full_rad,
tail_first_divisor,
} = self.config;
if !(speed_mps > 0.0 && error_rad > free_rad) {
return f32::INFINITY;
}
let span_rad = full_rad - free_rad;
let share = if span_rad > 0.0 {
((error_rad - free_rad) / span_rad).min(1.0)
} else {
1.0
};
speed_mps / (1.0 + (tail_first_divisor - 1.0) * share)
}
}
impl Configurable for OffNoseSpeed {
type Config = OffNoseSpeedConfig;
fn config(&self) -> &OffNoseSpeedConfig {
&self.config
}
fn set_config(&mut self, config: OffNoseSpeedConfig) -> Result<(), InvalidConfig> {
config.validate()?;
self.config = config;
Ok(())
}
}