use glam::DVec3;
use crate::components::{RigidBody, Transform};
use crate::forces::ForceProvider;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Atmosphere {
pub sea_level_density: f64,
pub scale_height: f64,
pub ceiling: f64,
}
impl Atmosphere {
pub const EARTH: Self = Self {
sea_level_density: 1.225,
scale_height: 8_500.0,
ceiling: 100_000.0,
};
#[must_use]
pub fn new(sea_level_density: f64, scale_height: f64, ceiling: f64) -> Self {
assert!(
sea_level_density >= 0.0,
"sea-level density must not be negative, got {sea_level_density}"
);
assert!(
scale_height > 0.0,
"scale height must be positive, got {scale_height}"
);
Self {
sea_level_density,
scale_height,
ceiling,
}
}
#[must_use]
pub fn density_at(&self, altitude: f64) -> f64 {
if altitude.is_nan() || altitude >= self.ceiling {
return 0.0;
}
if altitude <= 0.0 {
return self.sea_level_density;
}
self.sea_level_density * exp_neg(altitude / self.scale_height)
}
}
#[expect(
clippy::disallowed_methods,
reason = "no constructed exponential exists yet; see the doc comment"
)]
fn exp_neg(x: f64) -> f64 {
(-x).exp()
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AtmosphericDrag {
pub atmosphere: Atmosphere,
pub centre: DVec3,
pub radius: f64,
pub drag_coefficient: f64,
pub reference_area: f64,
}
impl AtmosphericDrag {
#[must_use]
pub fn altitude_of(&self, position: DVec3) -> f64 {
(position - self.centre).length() - self.radius
}
#[must_use]
pub fn world_force(&self, position: DVec3, velocity: DVec3) -> DVec3 {
let speed_squared = velocity.length_squared();
if speed_squared <= f64::MIN_POSITIVE {
return DVec3::ZERO;
}
let density = self.atmosphere.density_at(self.altitude_of(position));
if density <= 0.0 {
return DVec3::ZERO;
}
let magnitude = 0.5 * density * self.drag_coefficient * self.reference_area;
-velocity * (magnitude * speed_squared.sqrt())
}
}
impl ForceProvider for AtmosphericDrag {
fn apply(&self, body: &mut RigidBody, transform: &Transform, _dt: f64) {
if body.is_dynamic() {
let force = self.world_force(transform.position, body.velocity);
body.apply_force(force);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::forces::GravityForce;
use crate::integrator::{Integrator, SemiImplicitEuler};
use glam::DQuat;
const RADIUS: f64 = 6_371_000.0;
fn at_altitude(altitude: f64) -> DVec3 {
DVec3::new(0.0, RADIUS + altitude, 0.0)
}
fn drag_with(
atmosphere: Atmosphere,
drag_coefficient: f64,
reference_area: f64,
) -> AtmosphericDrag {
AtmosphericDrag {
atmosphere,
centre: DVec3::ZERO,
radius: RADIUS,
drag_coefficient,
reference_area,
}
}
#[test]
fn density_falls_off_exponentially_with_altitude() {
let air = Atmosphere::EARTH;
assert_eq!(
air.density_at(0.0),
air.sea_level_density,
"the surface is the sea-level value by definition"
);
let one_up = air.density_at(air.scale_height);
let expected = air.sea_level_density / std::f64::consts::E;
assert!(
(one_up - expected).abs() < expected * 1e-12,
"one scale height up must divide density by e: got {one_up}, expected {expected}"
);
let two_up = air.density_at(2.0 * air.scale_height);
let expected_two = air.sea_level_density / (std::f64::consts::E * std::f64::consts::E);
assert!(
(two_up - expected_two).abs() < expected_two * 1e-12,
"two scale heights up must divide it by e twice: got {two_up}, expected {expected_two}"
);
}
#[test]
fn there_is_no_air_above_the_ceiling_and_none_at_a_nan_altitude() {
let air = Atmosphere::EARTH;
assert_eq!(
air.density_at(air.ceiling),
0.0,
"the ceiling itself is vacuum"
);
assert_eq!(air.density_at(air.ceiling * 2.0), 0.0);
assert_eq!(
air.density_at(f64::NAN),
0.0,
"a NaN altitude must land in vacuum rather than being multiplied into a force"
);
assert_eq!(
air.density_at(-1_000.0),
air.sea_level_density,
"below the surface must clamp to sea level, not run the exponential away"
);
}
#[test]
fn drag_opposes_motion_and_a_still_body_feels_none() {
let drag = drag_with(Atmosphere::EARTH, 0.5, 1.0);
let position = at_altitude(0.0);
let velocity = DVec3::new(30.0, -40.0, 0.0);
let force = drag.world_force(position, velocity);
assert!(
force.dot(velocity) < 0.0,
"drag must oppose the direction of travel: {force:?} against {velocity:?}"
);
assert!(force.is_finite(), "{force:?}");
assert_eq!(
drag.world_force(position, DVec3::ZERO),
DVec3::ZERO,
"a body at rest has no direction to be slowed along"
);
}
#[test]
fn terminal_velocity_emerges_within_one_percent_of_the_closed_form() {
const MASS: f64 = 100.0;
const CD: f64 = 0.5;
const AREA: f64 = 1.0;
const G: f64 = 9.81;
const DT: f64 = 1.0 / 240.0;
let uniform = Atmosphere::new(1.225, 1.0e12, f64::INFINITY);
let drag = drag_with(uniform, CD, AREA);
let gravity = GravityForce::new(DVec3::new(0.0, -G, 0.0));
let integrator = SemiImplicitEuler;
let mut body = RigidBody::new_dynamic(MASS);
let mut transform = Transform {
position: at_altitude(10_000.0),
rotation: DQuat::IDENTITY,
};
for _ in 0..(60.0 / DT) as u32 {
gravity.apply(&mut body, &transform, DT);
drag.apply(&mut body, &transform, DT);
integrator.step(&mut body, &mut transform, DT);
}
let settled = body.velocity.length();
let density = uniform.density_at(drag.altitude_of(transform.position));
let expected = (2.0 * MASS * G / (density * CD * AREA)).sqrt();
assert!(
(settled - expected).abs() <= expected * 0.01,
"terminal velocity {settled} m/s is not within 1% of the closed form \
{expected} m/s for m={MASS} g={G} rho={density} Cd={CD} A={AREA}"
);
}
#[test]
fn the_same_body_falls_faster_where_the_air_is_thinner() {
let drag = drag_with(Atmosphere::EARTH, 0.5, 1.0);
let velocity = DVec3::new(0.0, -100.0, 0.0);
let low = drag.world_force(at_altitude(1_000.0), velocity).length();
let high = drag.world_force(at_altitude(30_000.0), velocity).length();
assert!(
high < low,
"drag at 30 km ({high} N) must be less than at 1 km ({low} N)"
);
assert!(low > 0.0, "there must be drag at 1 km at all");
}
}