use std::sync::Arc;
use glam::{DMat3, DQuat, DVec3};
use crate::collider::{Aabb, BoxCollider};
use crate::components::{ColliderComponent, RigidBody, Transform};
use crate::compound::{AabbCompound, CompoundError};
use crate::contact::shape::ContactShape;
use crate::mass::MassProperties;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CompoundPart {
pub centre: DVec3,
pub rotation: DQuat,
pub half_extents: DVec3,
}
impl CompoundPart {
#[inline]
#[must_use]
pub const fn new(centre: DVec3, rotation: DQuat, half_extents: DVec3) -> Self {
Self {
centre,
rotation,
half_extents,
}
}
#[inline]
#[must_use]
pub fn from_aabb(aabb: &Aabb) -> Self {
Self {
centre: aabb.centre(),
rotation: DQuat::IDENTITY,
half_extents: aabb.extents() * 0.5,
}
}
#[inline]
#[must_use]
pub fn volume(&self) -> f64 {
let h = self.half_extents;
8.0 * h.x * h.y * h.z
}
#[must_use]
pub(crate) fn placed(&self, offset: DVec3, transform: &Transform) -> BoxCollider {
BoxCollider::new(
transform.position + transform.rotation * (offset + self.centre),
self.half_extents,
)
.with_rotation(transform.rotation * self.rotation)
}
fn mass_properties(&self, density: f64) -> MassProperties {
let mass = density * self.volume();
let own = MassProperties::cuboid(mass, self.half_extents, self.centre);
let i = own.inertia;
MassProperties {
inertia: turned_inertia(
DMat3::from_quat(self.rotation),
DVec3::new(i.x_axis.x, i.y_axis.y, i.z_axis.z),
),
..own
}
}
}
fn turned_inertia(r: DMat3, d: DVec3) -> DMat3 {
let row = |i: usize| DVec3::new(r.col(0)[i], r.col(1)[i], r.col(2)[i]);
let rows = [row(0), row(1), row(2)];
let mut m = [[0.0; 3]; 3];
for i in 0..3 {
for j in i..3 {
let value = (rows[i] * d).dot(rows[j]);
m[i][j] = value;
m[j][i] = value;
}
}
DMat3::from_cols_array_2d(&m)
}
#[derive(Debug, Clone, PartialEq)]
pub struct CompoundShape {
parts: Arc<[CompoundPart]>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CompoundBody {
pub body: RigidBody,
pub collider: ColliderComponent,
pub centre_of_mass: DVec3,
}
impl CompoundShape {
pub const MAX_PARTS: usize = 32;
pub const DEFAULT_DENSITY: f64 = 1000.0;
pub fn new(parts: impl Into<Arc<[CompoundPart]>>) -> Result<Self, CompoundError> {
let parts: Arc<[CompoundPart]> = parts.into();
if parts.is_empty() {
return Err(CompoundError::NoParts);
}
if parts.len() > Self::MAX_PARTS {
return Err(CompoundError::TooManyParts { count: parts.len() });
}
for (index, part) in parts.iter().enumerate() {
if !part.centre.is_finite()
|| !part.half_extents.is_finite()
|| !part.rotation.is_finite()
{
return Err(CompoundError::NonFinitePart { index });
}
if part.half_extents.min_element() < 0.0 {
return Err(CompoundError::InvertedPart { index });
}
if !part.rotation.is_normalized() {
return Err(CompoundError::NonUnitRotation { index });
}
}
if parts.iter().all(|part| part.volume() == 0.0) {
return Err(CompoundError::NoVolume);
}
let parts = parts
.iter()
.map(|part| CompoundPart {
rotation: part.rotation.normalize(),
..*part
})
.collect();
Ok(Self { parts })
}
pub fn from_aabbs(parts: &[Aabb]) -> Result<Self, CompoundError> {
let parts = AabbCompound::new(parts)?.parts();
Self::new(
parts
.iter()
.map(CompoundPart::from_aabb)
.collect::<Vec<_>>(),
)
}
#[inline]
#[must_use]
pub fn parts(&self) -> &[CompoundPart] {
&self.parts
}
#[must_use]
pub fn volume(&self) -> f64 {
self.parts.iter().map(CompoundPart::volume).sum()
}
#[must_use]
pub fn mass_properties(&self, density: f64) -> MassProperties {
assert!(
density.is_finite() && density > 0.0,
"a density is positive and finite: {density}"
);
let parts: Vec<MassProperties> = self
.parts
.iter()
.map(|part| part.mass_properties(density))
.collect();
MassProperties::combine(&parts)
}
#[must_use]
pub fn dynamic_body(&self, density: f64) -> CompoundBody {
let props = self.mass_properties(density);
CompoundBody {
body: RigidBody::new_dynamic(props.mass).with_inertia(props.inertia),
collider: ColliderComponent::Compound {
offset: -props.centre_of_mass,
shape: self.clone(),
is_trigger: false,
},
centre_of_mass: props.centre_of_mass,
}
}
#[must_use]
pub fn world_bounds(&self, offset: DVec3, transform: &Transform) -> Aabb {
self.parts.iter().fold(Aabb::EMPTY, |bounds, part| {
let placed = ContactShape::compound_part(part, offset, transform);
bounds.union(placed.aabb().expect("a box is bounded"))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use core::f64::consts::FRAC_1_SQRT_2;
fn assert_close(got: DMat3, want: DMat3, what: &str) {
let error = (got - want)
.to_cols_array()
.iter()
.fold(0.0f64, |worst, e| worst.max(e.abs()));
assert!(error < 1e-12, "{what}: {got:?}, want {want:?}");
}
#[test]
fn two_cubes_side_by_side_weigh_and_turn_as_computed_by_hand() {
let shape = CompoundShape::from_aabbs(&[
Aabb::new(DVec3::ZERO, DVec3::ONE),
Aabb::new(DVec3::new(1.0, 0.0, 0.0), DVec3::new(2.0, 1.0, 1.0)),
])
.unwrap();
let props = shape.mass_properties(1.0);
assert_eq!(props.mass, 2.0);
assert_eq!(props.centre_of_mass, DVec3::new(1.0, 0.5, 0.5));
assert_close(
props.inertia,
DMat3::from_diagonal(DVec3::new(1.0 / 3.0, 5.0 / 6.0, 5.0 / 6.0)),
"two cubes",
);
}
#[test]
fn a_given_mass_is_shared_among_the_parts() {
let shape = CompoundShape::from_aabbs(&[
Aabb::new(DVec3::ZERO, DVec3::ONE),
Aabb::new(DVec3::new(1.0, 0.0, 0.0), DVec3::new(2.0, 1.0, 1.0)),
])
.unwrap();
let collider = ColliderComponent::Compound {
offset: DVec3::new(0.0, -1.0, 0.0),
shape,
is_trigger: false,
};
let props = MassProperties::of_collider(&collider, 6.0);
assert_eq!(props.mass, 6.0);
assert_eq!(props.centre_of_mass, DVec3::new(1.0, -0.5, 0.5));
assert_close(
props.inertia,
DMat3::from_diagonal(DVec3::new(1.0, 2.5, 2.5)),
"two cubes at 6 kg",
);
}
#[test]
fn an_l_shaped_compound_has_the_hand_computed_tensor() {
let shape = CompoundShape::from_aabbs(&[
Aabb::new(DVec3::ZERO, DVec3::new(2.0, 1.0, 1.0)),
Aabb::new(DVec3::new(0.0, 1.0, 0.0), DVec3::new(1.0, 2.0, 1.0)),
])
.unwrap();
let props = shape.mass_properties(1.0);
assert_eq!(props.mass, 3.0);
assert!(
(props.centre_of_mass - DVec3::new(5.0 / 6.0, 5.0 / 6.0, 0.5)).length() < 1e-15,
"{:?}",
props.centre_of_mass
);
let third = 1.0 / 3.0;
assert_close(
props.inertia,
DMat3::from_cols(
DVec3::new(7.0 / 6.0, third, 0.0),
DVec3::new(third, 7.0 / 6.0, 0.0),
DVec3::new(0.0, 0.0, 11.0 / 6.0),
),
"L",
);
}
#[test]
fn an_overlap_is_counted_once_for_each_part_it_is_in() {
let cube = Aabb::new(DVec3::ZERO, DVec3::ONE);
let props = CompoundShape::from_aabbs(&[cube, cube])
.unwrap()
.mass_properties(1.0);
assert_eq!(props.mass, 2.0);
assert_close(
props.inertia,
DMat3::from_diagonal(DVec3::splat(2.0 / 6.0)),
"doubled cube",
);
}
#[test]
fn a_turned_part_swaps_its_moments() {
let quarter = DQuat::from_xyzw(0.0, 0.0, FRAC_1_SQRT_2, FRAC_1_SQRT_2);
let part = CompoundPart::new(DVec3::ZERO, quarter, DVec3::new(0.5, 1.0, 1.5));
let shape = CompoundShape::new(vec![part]).unwrap();
let props = shape.mass_properties(2.0);
assert_eq!(props.mass, 12.0);
assert_close(
props.inertia,
DMat3::from_diagonal(DVec3::new(10.0, 13.0, 5.0)),
"turned box",
);
let m = props.inertia;
assert_eq!(m.x_axis.y, m.y_axis.x);
assert_eq!(m.x_axis.z, m.z_axis.x);
assert_eq!(m.y_axis.z, m.z_axis.y);
let skew = crate::rotation_from_scaled_axis(DVec3::new(0.3, 0.7, -0.2));
let turned = CompoundShape::new(vec![CompoundPart::new(
DVec3::ZERO,
skew,
DVec3::new(0.5, 1.0, 1.5),
)])
.unwrap()
.dynamic_body(2.0);
assert!(turned.body.has_rotational_inertia());
}
#[test]
fn a_dynamic_body_is_offset_to_its_centre_of_mass() {
let shape = CompoundShape::from_aabbs(&[
Aabb::new(DVec3::ZERO, DVec3::ONE),
Aabb::new(DVec3::new(1.0, 0.0, 0.0), DVec3::new(2.0, 1.0, 1.0)),
])
.unwrap();
let built = shape.dynamic_body(500.0);
assert_eq!(built.body.mass, 1000.0);
assert_eq!(built.centre_of_mass, DVec3::new(1.0, 0.5, 0.5));
let ColliderComponent::Compound { offset, .. } = built.collider else {
panic!("{:?}", built.collider);
};
assert_eq!(offset, -built.centre_of_mass);
let bounds = shape.world_bounds(offset, &Transform::from_position(built.centre_of_mass));
assert_eq!(bounds, Aabb::new(DVec3::ZERO, DVec3::new(2.0, 1.0, 1.0)));
}
#[test]
fn a_shape_refuses_what_cannot_be_a_body() {
let unit = CompoundPart::from_aabb(&Aabb::new(DVec3::ZERO, DVec3::ONE));
let flat = CompoundPart::from_aabb(&Aabb::new(DVec3::ZERO, DVec3::new(1.0, 0.0, 1.0)));
assert_eq!(CompoundShape::new(Vec::new()), Err(CompoundError::NoParts));
assert_eq!(
CompoundShape::new(vec![unit; CompoundShape::MAX_PARTS + 1]),
Err(CompoundError::TooManyParts {
count: CompoundShape::MAX_PARTS + 1
})
);
assert!(CompoundShape::new(vec![unit; CompoundShape::MAX_PARTS]).is_ok());
assert_eq!(
CompoundShape::new(vec![
unit,
CompoundPart {
centre: DVec3::new(0.0, f64::NAN, 0.0),
..unit
}
]),
Err(CompoundError::NonFinitePart { index: 1 })
);
assert_eq!(
CompoundShape::new(vec![CompoundPart {
half_extents: DVec3::new(1.0, -0.5, 1.0),
..unit
}]),
Err(CompoundError::InvertedPart { index: 0 })
);
assert_eq!(
CompoundShape::new(vec![
unit,
CompoundPart {
rotation: DQuat::from_xyzw(0.0, 0.0, 0.0, 2.0),
..unit
}
]),
Err(CompoundError::NonUnitRotation { index: 1 })
);
assert_eq!(
CompoundShape::new(vec![flat, flat]),
Err(CompoundError::NoVolume)
);
assert!(
CompoundShape::new(vec![flat, unit]).is_ok(),
"one flat part is fine"
);
assert_eq!(
CompoundShape::from_aabbs(&[Aabb::new(DVec3::ONE, DVec3::ZERO)]),
Err(CompoundError::InvertedPart { index: 0 }),
"AabbCompound's own refusals come first"
);
}
}