use glam::DVec3;
use crate::components::{RigidBody, Transform};
pub trait ForceProvider: std::fmt::Debug + Send {
fn apply(&self, body: &mut RigidBody, transform: &Transform, dt: f64);
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GravityForce {
pub acceleration: DVec3,
}
impl GravityForce {
#[inline]
#[must_use]
pub fn new(acceleration: DVec3) -> Self {
Self { acceleration }
}
pub const EARTH: Self = Self {
acceleration: DVec3::new(0.0, -9.81, 0.0),
};
}
impl ForceProvider for GravityForce {
fn apply(&self, body: &mut RigidBody, _transform: &Transform, _dt: f64) {
if body.is_dynamic() {
body.apply_force(self.acceleration * body.mass);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PointGravity {
pub mu: f64,
pub centre: DVec3,
}
impl PointGravity {
#[inline]
#[must_use]
pub fn new(mu: f64, centre: DVec3) -> Self {
debug_assert!(mu >= 0.0, "a gravitational parameter is not negative");
Self { mu, centre }
}
#[must_use]
pub fn acceleration_at(&self, position: DVec3) -> DVec3 {
let offset = position - self.centre;
let distance_squared = offset.length_squared();
if distance_squared.is_nan() || distance_squared <= 0.0 {
return DVec3::ZERO;
}
-offset * (self.mu / (distance_squared * distance_squared.sqrt()))
}
}
impl ForceProvider for PointGravity {
fn apply(&self, body: &mut RigidBody, transform: &Transform, _dt: f64) {
if body.is_dynamic() {
body.apply_force(self.acceleration_at(transform.position) * body.mass);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DragForce {
pub coefficient: f64,
}
impl DragForce {
#[inline]
#[must_use]
pub fn new(coefficient: f64) -> Self {
debug_assert!(coefficient >= 0.0, "drag coefficient must be non-negative");
Self { coefficient }
}
}
impl DragForce {
#[inline]
#[must_use]
pub fn world_force(&self, velocity: DVec3) -> DVec3 {
-velocity * self.coefficient
}
}
impl ForceProvider for DragForce {
fn apply(&self, body: &mut RigidBody, _transform: &Transform, _dt: f64) {
if body.is_dynamic() {
body.apply_force(self.world_force(body.velocity));
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DampingForce {
pub coefficient: f64,
}
impl DampingForce {
#[inline]
#[must_use]
pub fn new(coefficient: f64) -> Self {
debug_assert!(
coefficient >= 0.0,
"damping coefficient must be non-negative"
);
Self { coefficient }
}
}
impl DampingForce {
#[inline]
#[must_use]
pub fn world_force(&self, velocity: DVec3, mass: f64, dt: f64) -> DVec3 {
let critical = mass / dt;
let effective = if self.coefficient < critical {
self.coefficient
} else {
critical
};
-velocity * effective
}
}
impl ForceProvider for DampingForce {
fn apply(&self, body: &mut RigidBody, _transform: &Transform, dt: f64) {
if !body.is_dynamic() {
return;
}
body.apply_force(self.world_force(body.velocity, body.mass, dt));
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ThrustForce {
pub magnitude: f64,
pub local_direction: DVec3,
}
impl ThrustForce {
#[inline]
#[must_use]
pub fn new(magnitude: f64, local_direction: DVec3) -> Self {
Self {
magnitude,
local_direction: local_direction.normalize_or_zero(),
}
}
#[inline]
#[must_use]
pub fn forward(magnitude: f64) -> Self {
Self {
magnitude,
local_direction: DVec3::NEG_Z,
}
}
#[inline]
#[must_use]
pub fn world_force(&self, transform: &Transform) -> DVec3 {
(transform.rotation * self.local_direction) * self.magnitude
}
}
impl ForceProvider for ThrustForce {
fn apply(&self, body: &mut RigidBody, transform: &Transform, _dt: f64) {
if body.is_dynamic() {
body.apply_force(self.world_force(transform));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::integrator::{Integrator as _, SemiImplicitEuler};
#[test]
fn gravity_applies_mass_proportional_force() {
let g = GravityForce::EARTH;
let mut body = RigidBody::new_dynamic(2.0); g.apply(&mut body, &Transform::IDENTITY, 0.0);
assert_eq!(body.force_accum, DVec3::new(0.0, -19.62, 0.0));
}
#[test]
fn gravity_ignores_kinematic_bodies() {
let g = GravityForce::EARTH;
let mut body = RigidBody::new_kinematic();
g.apply(&mut body, &Transform::IDENTITY, 0.0);
assert_eq!(body.force_accum, DVec3::ZERO);
}
#[test]
fn drag_produces_a_force_opposite_the_velocity_and_proportional_to_it() {
let drag = DragForce::new(0.5);
let mut body = RigidBody::new_dynamic(1.0);
body.velocity = DVec3::new(10.0, 0.0, 0.0);
drag.apply(&mut body, &Transform::IDENTITY, 0.0);
assert_eq!(body.force_accum, DVec3::new(-5.0, 0.0, 0.0));
}
#[test]
fn drag_ignores_kinematic_bodies() {
let drag = DragForce::new(1.0);
let mut body = RigidBody::new_kinematic();
body.velocity = DVec3::new(5.0, 0.0, 0.0);
drag.apply(&mut body, &Transform::IDENTITY, 0.0);
assert_eq!(body.force_accum, DVec3::ZERO);
}
#[test]
fn damping_matches_drag_at_a_sane_timestep() {
let mut damped = RigidBody::new_dynamic(2.0);
let mut dragged = RigidBody::new_dynamic(2.0);
damped.velocity = DVec3::new(3.0, -4.0, 1.0);
dragged.velocity = damped.velocity;
let dt = 1.0 / 120.0;
DampingForce::new(0.5).apply(&mut damped, &Transform::IDENTITY, dt);
DragForce::new(0.5).apply(&mut dragged, &Transform::IDENTITY, dt);
assert_eq!(damped.force_accum, dragged.force_accum);
}
#[test]
fn damping_is_capped_at_the_force_that_stops_the_body() {
let dt = 0.5;
let mut body = RigidBody::new_dynamic(2.0);
body.velocity = DVec3::new(10.0, 0.0, 0.0);
DampingForce::new(1000.0).apply(&mut body, &Transform::IDENTITY, dt);
assert_eq!(body.force_accum, DVec3::new(-40.0, 0.0, 0.0));
let mut transform = Transform::IDENTITY;
SemiImplicitEuler.step(&mut body, &mut transform, dt);
assert_eq!(body.velocity, DVec3::ZERO);
}
#[test]
fn the_per_entity_damping_is_the_pipelines_own_including_the_cap() {
let provider = DampingForce::new(3.0);
let mass = 2.0;
let mut capped = 0;
for dt in [1.0 / 240.0, 1.0 / 60.0, 0.5, 1.0, 4.0] {
for velocity in [
DVec3::ZERO,
DVec3::new(3.0, -4.0, 0.0),
DVec3::new(-14.0, 0.0, 0.0),
] {
let mut body = RigidBody::new_dynamic(mass);
body.velocity = velocity;
provider.apply(&mut body, &Transform::IDENTITY, dt);
let effective = provider.coefficient.min(mass / dt);
let expected = -velocity * effective;
assert_eq!(
provider.world_force(velocity, mass, dt),
expected,
"the per-entity route at dt {dt}, {velocity:?}",
);
assert_eq!(
body.force_accum, expected,
"the pipeline at dt {dt}, {velocity:?}",
);
if provider.coefficient > mass / dt {
capped += 1;
let mut transform = Transform::IDENTITY;
SemiImplicitEuler.step(&mut body, &mut transform, dt);
assert_eq!(
body.velocity,
DVec3::ZERO,
"the capped force did not stop the body at dt {dt}",
);
}
}
}
assert!(
capped > 0,
"no `dt` in this grid reaches the cap, so the case that matters is untested",
);
}
#[test]
fn the_per_entity_drag_is_the_pipelines_own() {
let provider = DragForce::new(0.75);
let velocity = DVec3::new(3.0, -4.0, 12.0);
let mut body = RigidBody::new_dynamic(2.0);
body.velocity = velocity;
provider.apply(&mut body, &Transform::IDENTITY, 1.0 / 60.0);
assert_eq!(body.force_accum, provider.world_force(velocity));
}
#[test]
fn damping_ignores_kinematic_bodies() {
let mut body = RigidBody::new_kinematic();
body.velocity = DVec3::new(5.0, 0.0, 0.0);
DampingForce::new(1.0).apply(&mut body, &Transform::IDENTITY, 0.1);
assert_eq!(body.force_accum, DVec3::ZERO);
}
#[test]
fn thrust_points_along_the_body_facing() {
let thrust = ThrustForce::forward(50.0);
let mut body = RigidBody::new_dynamic(1.0);
thrust.apply(&mut body, &Transform::IDENTITY, 0.1);
assert_eq!(body.force_accum, DVec3::new(0.0, 0.0, -50.0));
let mut body = RigidBody::new_dynamic(1.0);
let transform = Transform::new(
DVec3::ZERO,
crate::rotation_from_scaled_axis(DVec3::Y * std::f64::consts::FRAC_PI_2),
);
thrust.apply(&mut body, &transform, 0.1);
assert!(
(body.force_accum - DVec3::new(-50.0, 0.0, 0.0)).length() < 1e-12,
"got {:?}",
body.force_accum
);
}
#[test]
fn thrust_along_a_chosen_local_axis_stays_in_the_plane() {
let thrust = ThrustForce::new(10.0, DVec3::Y);
let mut body = RigidBody::new_dynamic(1.0);
let transform = Transform::new(
DVec3::ZERO,
crate::rotation_from_scaled_axis(DVec3::Z * std::f64::consts::FRAC_PI_2),
);
thrust.apply(&mut body, &transform, 0.1);
assert!(
(body.force_accum - DVec3::new(-10.0, 0.0, 0.0)).length() < 1e-12,
"got {:?}",
body.force_accum
);
assert_eq!(body.force_accum.z, 0.0);
}
#[test]
fn thrust_normalises_its_direction() {
let thrust = ThrustForce::new(7.0, DVec3::new(0.0, 3.0, 0.0));
let mut body = RigidBody::new_dynamic(1.0);
thrust.apply(&mut body, &Transform::IDENTITY, 0.1);
assert_eq!(body.force_accum, DVec3::new(0.0, 7.0, 0.0));
}
#[test]
fn zero_thrust_direction_produces_no_force_rather_than_nan() {
let thrust = ThrustForce::new(7.0, DVec3::ZERO);
let mut body = RigidBody::new_dynamic(1.0);
thrust.apply(&mut body, &Transform::IDENTITY, 0.1);
assert_eq!(body.force_accum, DVec3::ZERO);
}
#[test]
fn thrust_ignores_kinematic_bodies() {
let mut body = RigidBody::new_kinematic();
ThrustForce::forward(100.0).apply(&mut body, &Transform::IDENTITY, 0.1);
assert_eq!(body.force_accum, DVec3::ZERO);
}
#[test]
fn two_force_providers_add_into_the_same_accumulator_rather_than_replacing_it() {
let g = GravityForce::EARTH;
let drag = DragForce::new(0.3);
let mut body = RigidBody::new_dynamic(1.0);
body.velocity = DVec3::new(0.0, -5.0, 0.0); g.apply(&mut body, &Transform::IDENTITY, 0.0);
drag.apply(&mut body, &Transform::IDENTITY, 0.0);
assert!(
(body.force_accum.y + 8.31).abs() < 1e-10,
"expected ~-8.31, got {}",
body.force_accum.y
);
}
#[test]
fn point_gravity_at_the_earths_surface_is_nine_point_eight() {
const EARTH_MU: f64 = 3.986_004_418e14;
const EQUATORIAL_RADIUS: f64 = 6_378_137.0;
let gravity = PointGravity::new(EARTH_MU, DVec3::ZERO);
let surface = DVec3::new(0.0, EQUATORIAL_RADIUS, 0.0);
let acceleration = gravity.acceleration_at(surface);
assert!(
acceleration.x == 0.0 && acceleration.z == 0.0 && acceleration.y < 0.0,
"gravity at the north of a sphere points straight down, got {acceleration:?}"
);
let magnitude = acceleration.length();
assert!(
(magnitude - 9.798).abs() < 0.001,
"surface gravity came out {magnitude} m/s², expected 9.798"
);
let twice_out = gravity.acceleration_at(surface * 2.0).length();
assert!(
(twice_out - magnitude / 4.0).abs() < magnitude * 1.0e-12,
"twice the distance must be a quarter the pull: {twice_out} against {}",
magnitude / 4.0
);
assert_eq!(gravity.acceleration_at(DVec3::ZERO), DVec3::ZERO);
assert_eq!(gravity.acceleration_at(DVec3::splat(f64::NAN)), DVec3::ZERO);
}
#[test]
fn point_gravity_pulls_a_dynamic_body_and_not_a_kinematic_one() {
const EARTH_MU: f64 = 3.986_004_418e14;
const MASS: f64 = 1_200.0;
let gravity = PointGravity::new(EARTH_MU, DVec3::ZERO);
let transform = Transform {
position: DVec3::new(0.0, 6_378_137.0, 0.0),
rotation: glam::DQuat::IDENTITY,
};
let mut body = RigidBody::new_dynamic(MASS);
gravity.apply(&mut body, &transform, 1.0 / 60.0);
let expected = gravity.acceleration_at(transform.position) * MASS;
assert!(
(body.force_accum - expected).length() < expected.length() * 1.0e-12,
"expected {expected:?}, got {:?}",
body.force_accum
);
let mut anchored = RigidBody::new_kinematic();
gravity.apply(&mut anchored, &transform, 1.0 / 60.0);
assert_eq!(
anchored.force_accum,
DVec3::ZERO,
"a kinematic body is moved by its own script, not by gravity"
);
}
}