use crcbl_ecs::quantize::{self, Codec, Field, Fixed, Quantized, SmallestThree};
use glam::{DMat3, DQuat, DVec3};
use crate::compound_shape::CompoundShape;
use crate::mesh::TriangleMesh;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RigidBody {
pub mass: f64,
pub inverse_mass: f64,
pub velocity: DVec3,
pub force_accum: DVec3,
pub angular_velocity: DVec3,
pub torque_accum: DVec3,
pub local_inertia: DMat3,
pub inverse_local_inertia: DMat3,
pub bullet: bool,
}
impl RigidBody {
#[inline]
#[must_use]
pub fn new_dynamic(mass: f64) -> Self {
assert!(mass > 0.0, "dynamic mass must be positive");
Self {
mass,
inverse_mass: 1.0 / mass,
..Self::new_kinematic()
}
}
#[inline]
#[must_use]
pub fn new_kinematic() -> Self {
Self {
mass: f64::INFINITY,
inverse_mass: 0.0,
velocity: DVec3::ZERO,
force_accum: DVec3::ZERO,
angular_velocity: DVec3::ZERO,
torque_accum: DVec3::ZERO,
local_inertia: DMat3::ZERO,
inverse_local_inertia: DMat3::ZERO,
bullet: false,
}
}
#[must_use]
pub const fn with_bullet(self, bullet: bool) -> Self {
Self { bullet, ..self }
}
#[must_use]
pub fn with_inertia(self, local_inertia: DMat3) -> Self {
assert!(self.is_dynamic(), "a kinematic body has no finite inertia");
let m = local_inertia;
assert!(
m.x_axis.y == m.y_axis.x && m.x_axis.z == m.z_axis.x && m.y_axis.z == m.z_axis.y,
"an inertia tensor is symmetric: {m:?}"
);
assert!(
is_positive_definite(m),
"an inertia tensor is positive definite: {m:?}"
);
Self {
local_inertia,
inverse_local_inertia: local_inertia.inverse(),
..self
}
}
#[inline]
#[must_use]
pub fn is_dynamic(&self) -> bool {
self.inverse_mass > 0.0
}
#[inline]
#[must_use]
pub fn has_rotational_inertia(&self) -> bool {
self.is_dynamic() && self.inverse_local_inertia != DMat3::ZERO
}
#[inline]
pub fn clear_forces(&mut self) {
self.force_accum = DVec3::ZERO;
self.torque_accum = DVec3::ZERO;
}
#[inline]
pub fn apply_force(&mut self, force: DVec3) {
self.force_accum += force;
}
#[inline]
pub fn apply_torque(&mut self, torque: DVec3) {
self.torque_accum += torque;
}
#[inline]
pub fn apply_impulse(&mut self, impulse: DVec3) {
self.velocity += impulse * self.inverse_mass;
}
#[must_use]
pub fn angular_momentum(&self, rotation: DQuat) -> DVec3 {
let local = rotation.inverse() * self.angular_velocity;
rotation * (self.local_inertia * local)
}
#[must_use]
pub fn kinetic_energy(&self, rotation: DQuat) -> f64 {
if !self.is_dynamic() {
return 0.0;
}
let local = rotation.inverse() * self.angular_velocity;
0.5 * self.mass * self.velocity.length_squared()
+ 0.5 * local.dot(self.local_inertia * local)
}
}
impl Default for RigidBody {
fn default() -> Self {
Self::new_kinematic()
}
}
pub(crate) fn is_positive_definite(m: DMat3) -> bool {
let minor2 = m.x_axis.x * m.y_axis.y - m.y_axis.x * m.x_axis.y;
m.x_axis.x > 0.0 && minor2 > 0.0 && m.determinant() > 0.0
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transform {
pub position: DVec3,
pub rotation: DQuat,
}
impl Transform {
pub const IDENTITY: Self = Self {
position: DVec3::ZERO,
rotation: DQuat::IDENTITY,
};
#[inline]
#[must_use]
pub fn new(position: DVec3, rotation: DQuat) -> Self {
Self { position, rotation }
}
#[inline]
#[must_use]
pub fn from_position(position: DVec3) -> Self {
Self {
position,
rotation: DQuat::IDENTITY,
}
}
#[inline]
#[must_use]
pub fn forward(&self) -> DVec3 {
self.rotation * DVec3::NEG_Z
}
#[inline]
#[must_use]
pub fn right(&self) -> DVec3 {
self.rotation * DVec3::X
}
#[inline]
#[must_use]
pub fn up(&self) -> DVec3 {
self.rotation * DVec3::Y
}
pub const ENCODED_LEN: usize = 7 * 8;
const ROTATION_TOLERANCE: f64 = 1e-6;
pub const WIRE_POSITION_EXTENT: f64 = 4096.0;
pub const WIRE_POSITION_BITS: u32 = 24;
pub const WIRE_POSITION: Fixed = Fixed::new(
-Self::WIRE_POSITION_EXTENT,
Self::WIRE_POSITION_EXTENT,
Self::WIRE_POSITION_BITS,
);
pub const WIRE_ROTATION_BITS: u32 = 18;
pub const WIRE_ROTATION: SmallestThree = SmallestThree::new(Self::WIRE_ROTATION_BITS);
pub const WIRE_SCHEMA: &'static [Field] = &[
Field {
name: "position.x",
codec: Codec::Fixed(Self::WIRE_POSITION),
},
Field {
name: "position.y",
codec: Codec::Fixed(Self::WIRE_POSITION),
},
Field {
name: "position.z",
codec: Codec::Fixed(Self::WIRE_POSITION),
},
Field {
name: "rotation",
codec: Codec::Rotation(Self::WIRE_ROTATION),
},
];
pub const QUANTIZED_LEN: usize = quantize::encoded_len(Self::WIRE_SCHEMA);
#[inline]
#[must_use]
pub const fn encoded_len(&self) -> usize {
Self::ENCODED_LEN
}
pub fn encode(&self, out: &mut Vec<u8>) {
for value in [
self.position.x,
self.position.y,
self.position.z,
self.rotation.x,
self.rotation.y,
self.rotation.z,
self.rotation.w,
] {
out.extend_from_slice(&value.to_le_bytes());
}
}
#[must_use]
pub fn decode(data: &[u8]) -> Option<Self> {
if data.len() != Self::ENCODED_LEN {
return None;
}
let mut values = [0.0f64; 7];
for (i, value) in values.iter_mut().enumerate() {
let bytes: [u8; 8] = data[i * 8..(i + 1) * 8].try_into().ok()?;
*value = f64::from_le_bytes(bytes);
}
Self::from_parts(&values)
}
fn from_parts(values: &[f64; 7]) -> Option<Self> {
if values.iter().any(|value| !value.is_finite()) {
return None;
}
let rotation = DQuat::from_xyzw(values[3], values[4], values[5], values[6]);
if (rotation.length_squared() - 1.0).abs() > Self::ROTATION_TOLERANCE {
return None;
}
Some(Self {
position: DVec3::new(values[0], values[1], values[2]),
rotation,
})
}
pub fn encode_wire(&self, out: &mut Vec<u8>) {
if quantize::encode(self, out).is_err() {
self.encode(out);
}
}
#[must_use]
pub fn decode_wire(data: &[u8]) -> Option<Self> {
match data.len() {
Self::QUANTIZED_LEN => quantize::decode(data).ok(),
Self::ENCODED_LEN => Self::decode(data),
_ => None,
}
}
#[must_use]
pub fn lerp(&self, other: &Self, alpha: f64) -> Self {
Self {
position: self.position.lerp(other.position, alpha),
rotation: self.rotation.lerp(other.rotation, alpha),
}
}
}
impl Quantized for Transform {
const SCHEMA: &'static [Field] = Self::WIRE_SCHEMA;
type Values = [f64; 7];
fn to_values(&self) -> [f64; 7] {
[
self.position.x,
self.position.y,
self.position.z,
self.rotation.x,
self.rotation.y,
self.rotation.z,
self.rotation.w,
]
}
fn from_values(values: &[f64; 7]) -> Option<Self> {
Self::from_parts(values)
}
}
const _: () = assert!(Transform::QUANTIZED_LEN != Transform::ENCODED_LEN);
const _: () = assert!(quantize::value_count(Transform::WIRE_SCHEMA) == 7);
const _: () = assert!(
3 * Transform::WIRE_POSITION_BITS + Transform::WIRE_ROTATION.encoded_bits()
== 8 * Transform::QUANTIZED_LEN as u32
);
impl Default for Transform {
fn default() -> Self {
Self::IDENTITY
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum ColliderComponent {
Sphere {
offset: DVec3,
radius: f64,
is_trigger: bool,
},
Box {
offset: DVec3,
half_extents: DVec3,
is_trigger: bool,
},
Capsule {
offset: DVec3,
radius: f64,
half_height: f64,
is_trigger: bool,
},
Compound {
offset: DVec3,
shape: CompoundShape,
is_trigger: bool,
},
Mesh {
mesh: TriangleMesh,
is_trigger: bool,
},
}
impl ColliderComponent {
#[must_use]
pub fn max_extent(&self) -> f64 {
let farthest_corner = |centre: DVec3, rotation: DQuat, half: DVec3| {
let mut farthest: f64 = 0.0;
for x in [-half.x, half.x] {
for y in [-half.y, half.y] {
for z in [-half.z, half.z] {
farthest = farthest.max((centre + rotation * DVec3::new(x, y, z)).length());
}
}
}
farthest
};
match self {
Self::Sphere { offset, radius, .. } => offset.length() + radius,
Self::Box {
offset,
half_extents,
..
} => farthest_corner(*offset, DQuat::IDENTITY, *half_extents),
Self::Capsule {
offset,
radius,
half_height,
..
} => {
let cap = DVec3::new(0.0, *half_height, 0.0);
(*offset + cap).length().max((*offset - cap).length()) + radius
}
Self::Compound { offset, shape, .. } => shape
.parts()
.iter()
.map(|part| {
farthest_corner(*offset + part.centre, part.rotation, part.half_extents)
})
.fold(0.0, f64::max),
Self::Mesh { mesh, .. } => mesh
.vertices()
.iter()
.map(|vertex| vertex.length())
.fold(0.0, f64::max),
}
}
#[must_use]
pub fn part_count(&self) -> usize {
match self {
Self::Compound { shape, .. } => shape.parts().len(),
Self::Mesh { mesh, .. } => mesh.triangle_count(),
Self::Sphere { .. } | Self::Box { .. } | Self::Capsule { .. } => 1,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dynamic_body_has_inverse_mass() {
let body = RigidBody::new_dynamic(2.0);
assert!((body.inverse_mass - 0.5).abs() < 1e-12);
assert!(body.is_dynamic());
}
#[test]
fn kinematic_body_is_not_dynamic() {
let body = RigidBody::new_kinematic();
assert_eq!(body.inverse_mass, 0.0);
assert!(!body.is_dynamic());
}
#[test]
#[should_panic(expected = "dynamic mass must be positive")]
fn new_dynamic_rejects_zero_mass() {
let _ = RigidBody::new_dynamic(0.0);
}
#[test]
#[should_panic(expected = "a kinematic body has no finite inertia")]
fn a_kinematic_body_refuses_an_inertia() {
let _ = RigidBody::new_kinematic().with_inertia(DMat3::IDENTITY);
}
#[test]
#[should_panic(expected = "positive definite")]
fn an_inertia_that_is_not_positive_definite_is_refused() {
let _ = RigidBody::new_dynamic(1.0)
.with_inertia(DMat3::from_diagonal(DVec3::new(1.0, -1.0, 1.0)));
}
#[test]
#[should_panic(expected = "symmetric")]
fn an_asymmetric_inertia_is_refused() {
let mut inertia = DMat3::IDENTITY;
inertia.x_axis.y = 0.1;
let _ = RigidBody::new_dynamic(1.0).with_inertia(inertia);
}
#[test]
fn momentum_and_energy_read_the_inertia_in_the_bodys_own_frame() {
let mut body = RigidBody::new_dynamic(2.0)
.with_inertia(DMat3::from_diagonal(DVec3::new(1.0, 2.0, 3.0)));
body.velocity = DVec3::new(3.0, 0.0, 0.0);
let quarter = DQuat::from_xyzw(
0.0,
0.0,
core::f64::consts::FRAC_1_SQRT_2,
core::f64::consts::FRAC_1_SQRT_2,
);
body.angular_velocity = DVec3::new(0.0, 4.0, 0.0);
let momentum = body.angular_momentum(quarter);
assert!(
(momentum - DVec3::new(0.0, 4.0, 0.0)).length() < 1e-12,
"{momentum:?}"
);
let energy = body.kinetic_energy(quarter);
assert!((energy - (9.0 + 8.0)).abs() < 1e-12, "{energy}");
assert_eq!(RigidBody::new_kinematic().kinetic_energy(quarter), 0.0);
}
#[test]
fn applied_forces_sum_into_the_accumulator_and_clearing_zeroes_it() {
let mut body = RigidBody::new_dynamic(1.0);
body.apply_force(DVec3::new(1.0, 0.0, 0.0));
body.apply_force(DVec3::new(0.0, 2.0, 0.0));
assert_eq!(body.force_accum, DVec3::new(1.0, 2.0, 0.0));
body.clear_forces();
assert_eq!(body.force_accum, DVec3::ZERO);
}
#[test]
fn apply_impulse_changes_velocity() {
let mut body = RigidBody::new_dynamic(2.0);
body.apply_impulse(DVec3::new(4.0, 0.0, 0.0));
assert_eq!(body.velocity, DVec3::new(2.0, 0.0, 0.0));
}
#[test]
fn kinematic_body_ignores_impulse() {
let mut body = RigidBody::new_kinematic();
body.apply_impulse(DVec3::new(10.0, 0.0, 0.0));
assert_eq!(body.velocity, DVec3::ZERO);
}
#[test]
fn transform_directions_are_orthogonal() {
let t = Transform::IDENTITY;
assert_eq!(t.forward(), DVec3::NEG_Z);
assert_eq!(t.right(), DVec3::X);
assert_eq!(t.up(), DVec3::Y);
}
#[test]
fn the_exact_encoding_is_the_seven_values_little_endian() {
let t = Transform::new(
DVec3::new(1.25, -2.5, 1e6),
crate::rotation_from_scaled_axis(DVec3::X * 0.5),
);
let mut buf = Vec::new();
t.encode(&mut buf);
let raw: Vec<u8> = [
t.position.x,
t.position.y,
t.position.z,
t.rotation.x,
t.rotation.y,
t.rotation.z,
t.rotation.w,
]
.iter()
.flat_map(|v| v.to_le_bytes())
.collect();
assert_eq!(buf, raw);
}
#[test]
fn the_wire_position_quantum_is_a_power_of_two() {
assert_eq!(Transform::WIRE_POSITION.quantum(), 1.0 / 2048.0);
assert_eq!(Transform::QUANTIZED_LEN, 16);
}
fn drawn(i: u64) -> Transform {
use crcbl_core::rand::hash_unit;
let extent = Transform::WIRE_POSITION_EXTENT;
let unit = |k: u64| hash_unit(0x7157, 8 * i + k) * 2.0 - 1.0;
let axis = DVec3::new(unit(3), unit(4), unit(5));
Transform::new(
DVec3::new(unit(0), unit(1), unit(2)) * extent * (1.0 - 1e-9),
crate::rotation_from_scaled_axis(axis * std::f64::consts::PI),
)
}
#[test]
fn a_quantized_transform_round_trips_within_its_bounds() {
let half = Transform::WIRE_POSITION.quantum() / 2.0;
let rotation_bound = 2.0 * Transform::WIRE_ROTATION.quantum();
for i in 0..5_000 {
let t = drawn(i);
let mut buf = Vec::new();
t.encode_wire(&mut buf);
assert_eq!(buf.len(), Transform::QUANTIZED_LEN, "{t:?} is in range");
let back = Transform::decode_wire(&buf).expect("a quantized payload decodes");
assert!((back.position - t.position).abs().max_element() <= half);
let aligned = if back.rotation.dot(t.rotation) < 0.0 {
-back.rotation
} else {
back.rotation
};
let error = (aligned - t.rotation).to_array();
assert!(
error.iter().all(|e| e.abs() <= rotation_bound),
"{error:?} past {rotation_bound:e}"
);
}
let top = Transform::WIRE_POSITION_EXTENT - Transform::WIRE_POSITION.quantum();
for corner in [
DVec3::splat(-Transform::WIRE_POSITION_EXTENT),
DVec3::splat(top),
] {
let mut buf = Vec::new();
Transform::from_position(corner).encode_wire(&mut buf);
assert_eq!(buf.len(), Transform::QUANTIZED_LEN);
assert_eq!(Transform::decode_wire(&buf).unwrap().position, corner);
}
}
#[test]
fn a_transform_outside_the_range_falls_back_to_the_exact_form() {
let far = Transform::new(
DVec3::new(Transform::WIRE_POSITION_EXTENT, -3.0, 0.125),
crate::rotation_from_scaled_axis(DVec3::Z * 1.1),
);
let mut buf = Vec::new();
far.encode_wire(&mut buf);
assert_eq!(buf.len(), Transform::ENCODED_LEN);
assert_eq!(Transform::decode_wire(&buf), Some(far), "bit for bit");
for len in [
0,
4,
Transform::QUANTIZED_LEN - 1,
Transform::QUANTIZED_LEN + 1,
] {
assert_eq!(Transform::decode_wire(&vec![0; len]), None, "{len} bytes");
}
}
#[test]
fn decode_rejects_non_finite_and_degenerate_payloads() {
let good = Transform::new(
DVec3::new(1.0, 2.0, 3.0),
crate::rotation_from_scaled_axis(DVec3::Y * 0.75),
);
let mut buf = Vec::new();
good.encode(&mut buf);
assert!(Transform::decode(&buf).is_some());
let poison = |field: usize, value: f64| {
let mut data = buf.clone();
data[field * 8..(field + 1) * 8].copy_from_slice(&value.to_le_bytes());
Transform::decode(&data)
};
assert!(poison(0, f64::NAN).is_none(), "NaN position");
assert!(poison(1, f64::INFINITY).is_none(), "infinite position");
assert!(poison(2, f64::NEG_INFINITY).is_none(), "-inf position");
assert!(poison(6, f64::NAN).is_none(), "NaN quaternion component");
let mut zero_rot = buf.clone();
for field in 3..7 {
zero_rot[field * 8..(field + 1) * 8].copy_from_slice(&0.0f64.to_le_bytes());
}
assert!(Transform::decode(&zero_rot).is_none(), "zero quaternion");
let scaled = Transform::new(good.position, DQuat::from_xyzw(0.0, 0.0, 0.0, 4.0));
let mut data = Vec::new();
scaled.encode(&mut data);
assert!(Transform::decode(&data).is_none(), "non-unit quaternion");
}
#[test]
fn collider_component_is_clone() {
let c = ColliderComponent::Sphere {
offset: DVec3::ZERO,
radius: 1.0,
is_trigger: false,
};
let c2 = c.clone();
assert_eq!(c, c2);
}
#[test]
fn max_extent_is_the_farthest_point_of_each_shape() {
let close = |a: f64, b: f64| (a - b).abs() < 1e-12;
let sphere = ColliderComponent::Sphere {
offset: DVec3::new(3.0, 4.0, 0.0),
radius: 1.0,
is_trigger: false,
};
assert!(close(sphere.max_extent(), 6.0));
let cuboid = ColliderComponent::Box {
offset: DVec3::ZERO,
half_extents: DVec3::new(1.0, 2.0, 2.0),
is_trigger: false,
};
assert!(close(cuboid.max_extent(), 3.0));
let capsule = ColliderComponent::Capsule {
offset: DVec3::new(0.0, 1.0, 0.0),
radius: 0.5,
half_height: 1.0,
is_trigger: false,
};
assert!(close(capsule.max_extent(), 2.5), "the upper cap");
let shape = CompoundShape::from_aabbs(&[crate::collider::Aabb::from_centre_half(
DVec3::new(2.0, 0.0, 0.0),
DVec3::new(1.0, 2.0, 2.0),
)])
.expect("one part");
let compound = ColliderComponent::Compound {
offset: DVec3::new(1.0, 0.0, 0.0),
shape,
is_trigger: false,
};
assert!(close(compound.max_extent(), 24.0_f64.sqrt()));
}
}