Skip to main content

crcbl_phys/
impulse.rs

1//! Instantaneous impulses applied at world-space points.
2
3use std::fmt;
4
5use crcbl_ecs::Entity;
6use glam::{DMat3, DQuat, DVec3};
7
8use crate::{PhysicsSystem, RigidBody, Transform};
9
10/// Why a point impulse was refused without changing the body.
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum ImpulseError {
13    /// The entity has no rigid body or transform.
14    UnknownBody,
15    /// The impulse contains a NaN or infinity.
16    NonFiniteImpulse,
17    /// The application point contains a NaN or infinity.
18    NonFinitePoint,
19    /// The body's position is non-finite or its rotation is not a unit quaternion.
20    InvalidTransform,
21    /// Applying the impulse would produce a non-finite velocity.
22    NonFiniteVelocity,
23}
24
25impl fmt::Display for ImpulseError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(match self {
28            Self::UnknownBody => "point impulse target has no body or transform",
29            Self::NonFiniteImpulse => "point impulse is not finite",
30            Self::NonFinitePoint => "impulse application point is not finite",
31            Self::InvalidTransform => "point impulse target transform is invalid",
32            Self::NonFiniteVelocity => "point impulse would produce non-finite velocity",
33        })
34    }
35}
36
37impl std::error::Error for ImpulseError {}
38
39impl RigidBody {
40    pub(crate) fn inverse_world_inertia(&self, rotation: DQuat) -> DMat3 {
41        if self.has_rotational_inertia() {
42            let turn = DMat3::from_quat(rotation);
43            turn * self.inverse_local_inertia * turn.transpose()
44        } else {
45            DMat3::ZERO
46        }
47    }
48
49    /// Applies a world-space impulse at `point`, in N·s.
50    ///
51    /// Linear momentum changes as in [`Self::apply_impulse`]; angular momentum
52    /// changes by the lever arm crossed with the impulse, using the body's
53    /// oriented inertia. Kinematic bodies retain their velocities. A dynamic
54    /// body without rotational inertia receives only the linear change.
55    ///
56    /// Returns [`ImpulseError`] for invalid inputs or non-finite results,
57    /// leaving all body fields unchanged. Force accumulators are not involved.
58    pub fn apply_impulse_at(
59        &mut self,
60        impulse: DVec3,
61        point: DVec3,
62        transform: &Transform,
63    ) -> Result<(), ImpulseError> {
64        if !impulse.is_finite() {
65            return Err(ImpulseError::NonFiniteImpulse);
66        }
67        if !point.is_finite() {
68            return Err(ImpulseError::NonFinitePoint);
69        }
70        if !transform.position.is_finite()
71            || !transform.rotation.is_finite()
72            || !transform.rotation.is_normalized()
73        {
74            return Err(ImpulseError::InvalidTransform);
75        }
76        let mut candidate = *self;
77        candidate.apply_impulse(impulse);
78        if self.has_rotational_inertia() {
79            let angular_impulse = (point - transform.position).cross(impulse);
80            candidate.angular_velocity +=
81                self.inverse_world_inertia(transform.rotation) * angular_impulse;
82        }
83        if !candidate.velocity.is_finite() || !candidate.angular_velocity.is_finite() {
84            return Err(ImpulseError::NonFiniteVelocity);
85        }
86        self.velocity = candidate.velocity;
87        self.angular_velocity = candidate.angular_velocity;
88        Ok(())
89    }
90}
91
92impl PhysicsSystem {
93    /// Applies an impulse immediately and wakes the target body's island.
94    ///
95    /// `impulse` and `point` are world-space, on
96    /// [`RigidBody::apply_impulse_at`]'s terms. Invalid input and missing bodies
97    /// return [`ImpulseError`] without changing velocities or waking an island.
98    /// A recorded [`crate::KineticContact`] has already affected its struck
99    /// body; transferring it to a newly created ragdoll body is the caller's
100    /// explicit action, not an automatic replay onto the original target.
101    pub fn apply_impulse_at(
102        &mut self,
103        entity: Entity,
104        impulse: DVec3,
105        point: DVec3,
106    ) -> Result<(), ImpulseError> {
107        let mut candidate = *self.body(entity).ok_or(ImpulseError::UnknownBody)?;
108        let transform = self.transform(entity).ok_or(ImpulseError::UnknownBody)?;
109        candidate.apply_impulse_at(impulse, point, transform)?;
110        let body = self
111            .body_mut(entity)
112            .expect("the validated body still exists");
113        body.velocity = candidate.velocity;
114        body.angular_velocity = candidate.angular_velocity;
115        Ok(())
116    }
117}