crcbl_phys/components.rs
1//! ECS-ready component types for physics simulation.
2//!
3//! These are plain data structs designed to be stored in
4//! [`crcbl_ecs::System<T>`] arrays. They carry no storage or scheduling logic —
5//! that belongs to the physics system (see [`crate::system`]).
6
7use crcbl_ecs::quantize::{self, Codec, Field, Fixed, Quantized, SmallestThree};
8use glam::{DMat3, DQuat, DVec3};
9
10use crate::compound_shape::CompoundShape;
11use crate::mesh::TriangleMesh;
12
13// ---------------------------------------------------------------------------
14// RigidBody
15// ---------------------------------------------------------------------------
16
17/// Dynamics data for a physics entity.
18///
19/// Mass and velocity are in SI units (kg, m/s); angular velocity is in rad/s
20/// and inertia in kg·m². The force and torque accumulators are cleared every
21/// substep after integration.
22///
23/// # Rotation
24///
25/// A body rotates at [`angular_velocity`](Self::angular_velocity) whatever its
26/// inertia, so a kinematic body spun by a game turns just as it moves. What the
27/// inertia decides is how the spin *changes*: a torque turns into angular
28/// acceleration through [`inverse_local_inertia`](Self::inverse_local_inertia),
29/// and a body whose inertia is not isotropic precesses and tumbles under the
30/// gyroscopic term — see [`crate::integrator::SemiImplicitEuler`].
31///
32/// A body starts with **no rotational inertia at all**: both tensors are zero,
33/// which this crate reads as "torque does nothing and the spin never changes".
34/// That keeps every body built before rotation existed exactly as it was, and a
35/// body that should tumble says so with [`with_inertia`](Self::with_inertia) —
36/// [`crate::mass::MassProperties`] computes the tensor from collider shapes.
37///
38/// The inertia is about the body's origin, which is taken to be its centre of
39/// mass: a centre of mass away from the origin is not modelled yet, so a
40/// compound body places its parts about the centre
41/// [`MassProperties::combine`](crate::mass::MassProperties::combine) reports.
42///
43/// An entity with a [`RigidBody`] but no [`Transform`] component is a bug
44/// (detected at system registration time).
45#[derive(Debug, Clone, Copy, PartialEq)]
46pub struct RigidBody {
47 /// Mass in kilograms. Must be > 0; `inverse_mass` is `1.0 / mass`.
48 pub mass: f64,
49 /// Pre-computed inverse mass (`0.0` for kinematic / infinite-mass bodies).
50 pub inverse_mass: f64,
51 /// Linear velocity in m/s (world-space).
52 pub velocity: DVec3,
53 /// Net force accumulated this substep, in newtons. Cleared after
54 /// integration.
55 pub force_accum: DVec3,
56 /// Angular velocity in rad/s (world-space): the axis is the direction and
57 /// the rate is the length.
58 pub angular_velocity: DVec3,
59 /// Net torque accumulated this substep, in newton-metres (world-space).
60 /// Cleared after integration.
61 pub torque_accum: DVec3,
62 /// The inertia tensor about the centre of mass, in the body's own frame,
63 /// in kg·m². Zero for a body with no rotational inertia; see the type docs.
64 pub local_inertia: DMat3,
65 /// The inverse of [`local_inertia`](Self::local_inertia), or zero where
66 /// that is zero.
67 pub inverse_local_inertia: DMat3,
68 /// Whether this body is a **bullet**: in a system with contacts, a
69 /// dynamic bullet is swept every tick it moves, however slowly, and
70 /// against every other body as well as the static ones. See
71 /// [`crate::contact`]'s continuous collision. Off by default, and ignored
72 /// for a kinematic body, which nothing sweeps.
73 pub bullet: bool,
74}
75
76impl RigidBody {
77 /// Create a dynamic rigid body with no rotational inertia; see
78 /// [`with_inertia`](Self::with_inertia).
79 ///
80 /// # Panics
81 ///
82 /// Panics if `mass <= 0`.
83 #[inline]
84 #[must_use]
85 pub fn new_dynamic(mass: f64) -> Self {
86 assert!(mass > 0.0, "dynamic mass must be positive");
87 Self {
88 mass,
89 inverse_mass: 1.0 / mass,
90 ..Self::new_kinematic()
91 }
92 }
93
94 /// Create a kinematic body (infinite mass, not affected by forces).
95 #[inline]
96 #[must_use]
97 pub fn new_kinematic() -> Self {
98 Self {
99 mass: f64::INFINITY,
100 inverse_mass: 0.0,
101 velocity: DVec3::ZERO,
102 force_accum: DVec3::ZERO,
103 angular_velocity: DVec3::ZERO,
104 torque_accum: DVec3::ZERO,
105 local_inertia: DMat3::ZERO,
106 inverse_local_inertia: DMat3::ZERO,
107 bullet: false,
108 }
109 }
110
111 /// This body with its [`bullet`](Self::bullet) flag set to `bullet`.
112 #[must_use]
113 pub const fn with_bullet(self, bullet: bool) -> Self {
114 Self { bullet, ..self }
115 }
116
117 /// This body with `local_inertia` as its inertia tensor, about its centre
118 /// of mass in its own frame.
119 ///
120 /// # Panics
121 ///
122 /// Panics if the body is kinematic — its inertia is infinite, and a finite
123 /// tensor would make torque turn it — or if the tensor is not symmetric
124 /// positive definite, which no physical body's is.
125 #[must_use]
126 pub fn with_inertia(self, local_inertia: DMat3) -> Self {
127 assert!(self.is_dynamic(), "a kinematic body has no finite inertia");
128 let m = local_inertia;
129 assert!(
130 m.x_axis.y == m.y_axis.x && m.x_axis.z == m.z_axis.x && m.y_axis.z == m.z_axis.y,
131 "an inertia tensor is symmetric: {m:?}"
132 );
133 assert!(
134 is_positive_definite(m),
135 "an inertia tensor is positive definite: {m:?}"
136 );
137 Self {
138 local_inertia,
139 inverse_local_inertia: local_inertia.inverse(),
140 ..self
141 }
142 }
143
144 /// Whether this body responds to forces (inverse mass > 0).
145 #[inline]
146 #[must_use]
147 pub fn is_dynamic(&self) -> bool {
148 self.inverse_mass > 0.0
149 }
150
151 /// Whether this body responds to torque: it is dynamic and has been given
152 /// an inertia tensor.
153 #[inline]
154 #[must_use]
155 pub fn has_rotational_inertia(&self) -> bool {
156 self.is_dynamic() && self.inverse_local_inertia != DMat3::ZERO
157 }
158
159 /// Clear the force and torque accumulators (called after integration).
160 #[inline]
161 pub fn clear_forces(&mut self) {
162 self.force_accum = DVec3::ZERO;
163 self.torque_accum = DVec3::ZERO;
164 }
165
166 /// Apply a world-space force for this substep.
167 #[inline]
168 pub fn apply_force(&mut self, force: DVec3) {
169 self.force_accum += force;
170 }
171
172 /// Apply a world-space torque for this substep. A body with no rotational
173 /// inertia ignores it when it integrates.
174 #[inline]
175 pub fn apply_torque(&mut self, torque: DVec3) {
176 self.torque_accum += torque;
177 }
178
179 /// Apply an impulse (instantaneous velocity change).
180 #[inline]
181 pub fn apply_impulse(&mut self, impulse: DVec3) {
182 self.velocity += impulse * self.inverse_mass;
183 }
184
185 /// The angular momentum about the centre of mass, world-space, for a body
186 /// oriented at `rotation`: `R · I · Rᵀ · ω`.
187 #[must_use]
188 pub fn angular_momentum(&self, rotation: DQuat) -> DVec3 {
189 let local = rotation.inverse() * self.angular_velocity;
190 rotation * (self.local_inertia * local)
191 }
192
193 /// Kinetic energy in joules: `½ m v²` plus `½ ωᵀ I ω`.
194 ///
195 /// Zero for a kinematic body, whose mass is infinite — what it carries is
196 /// not energy the simulation can exchange. The rotational half is zero for
197 /// a body with no rotational inertia, for the same reason.
198 #[must_use]
199 pub fn kinetic_energy(&self, rotation: DQuat) -> f64 {
200 if !self.is_dynamic() {
201 return 0.0;
202 }
203 let local = rotation.inverse() * self.angular_velocity;
204 0.5 * self.mass * self.velocity.length_squared()
205 + 0.5 * local.dot(self.local_inertia * local)
206 }
207}
208
209impl Default for RigidBody {
210 fn default() -> Self {
211 Self::new_kinematic()
212 }
213}
214
215/// Whether `m` is positive definite, as [`RigidBody::with_inertia`] requires,
216/// by Sylvester's criterion: every leading principal minor is positive. A
217/// minor that underflows to zero or is `NaN` fails it.
218pub(crate) fn is_positive_definite(m: DMat3) -> bool {
219 let minor2 = m.x_axis.x * m.y_axis.y - m.y_axis.x * m.x_axis.y;
220 m.x_axis.x > 0.0 && minor2 > 0.0 && m.determinant() > 0.0
221}
222
223// ---------------------------------------------------------------------------
224// Transform
225// ---------------------------------------------------------------------------
226
227/// World-space transform for a physics entity.
228///
229/// This is the authoritative position used by the server simulation.
230/// The renderer receives a camera-relative transform derived from this.
231#[derive(Debug, Clone, Copy, PartialEq)]
232pub struct Transform {
233 /// World-space position in metres.
234 pub position: DVec3,
235 /// World-space orientation (unit quaternion).
236 pub rotation: DQuat,
237}
238
239impl Transform {
240 /// Identity transform at the origin.
241 pub const IDENTITY: Self = Self {
242 position: DVec3::ZERO,
243 rotation: DQuat::IDENTITY,
244 };
245
246 /// Create a transform at `position` with the given `rotation`.
247 #[inline]
248 #[must_use]
249 pub fn new(position: DVec3, rotation: DQuat) -> Self {
250 Self { position, rotation }
251 }
252
253 /// Create a transform at `position` with identity rotation.
254 #[inline]
255 #[must_use]
256 pub fn from_position(position: DVec3) -> Self {
257 Self {
258 position,
259 rotation: DQuat::IDENTITY,
260 }
261 }
262
263 /// The forward direction (local -Z in right-handed coordinates, or
264 /// local +Z depending on convention; matches glam's default).
265 #[inline]
266 #[must_use]
267 pub fn forward(&self) -> DVec3 {
268 self.rotation * DVec3::NEG_Z
269 }
270
271 /// The right direction (local +X).
272 #[inline]
273 #[must_use]
274 pub fn right(&self) -> DVec3 {
275 self.rotation * DVec3::X
276 }
277
278 /// The up direction (local +Y).
279 #[inline]
280 #[must_use]
281 pub fn up(&self) -> DVec3 {
282 self.rotation * DVec3::Y
283 }
284
285 /// Byte length of the replication encoding written by [`Self::encode`].
286 ///
287 /// The encoding is position (3 × f64 LE) followed by rotation
288 /// quaternion (4 × f64 LE, x/y/z/w) — 56 bytes.
289 pub const ENCODED_LEN: usize = 7 * 8;
290
291 /// How far a decoded quaternion's length² may sit from 1 before
292 /// [`Self::decode`] rejects it.
293 ///
294 /// Wide enough to absorb the round-trip error of an `f64` quaternion built
295 /// from Euler angles; far too tight to admit a degenerate or zero one.
296 const ROTATION_TOLERANCE: f64 = 1e-6;
297
298 /// Half the width of the range a replicated position axis is quantized
299 /// over, in metres, centred on the sector's origin.
300 ///
301 /// Wire positions are sector-local, and today every snapshot is
302 /// `crcbl_net::SectorId::ZERO` with physics never rebasing, so sector-local
303 /// is world space. The range is bounded by the scenes that replicate, not
304 /// by `crcbl_core::SECTOR_SIZE`: a whole sector at
305 /// [`Self::WIRE_POSITION_BITS`] would be a sixteenth of a metre per step,
306 /// too coarse to watch a crate settle. A body outside it replicates
307 /// exactly (see [`Self::encode_wire`]).
308 pub const WIRE_POSITION_EXTENT: f64 = 4096.0;
309
310 /// Bits per replicated position axis.
311 pub const WIRE_POSITION_BITS: u32 = 24;
312
313 /// A replicated position axis: [`Self::WIRE_POSITION_BITS`] of fixed point
314 /// over `±`[`Self::WIRE_POSITION_EXTENT`]. The width is a power of two, so
315 /// the quantum is too (asserted in the tests) and a position on that grid
316 /// replicates exactly.
317 pub const WIRE_POSITION: Fixed = Fixed::new(
318 -Self::WIRE_POSITION_EXTENT,
319 Self::WIRE_POSITION_EXTENT,
320 Self::WIRE_POSITION_BITS,
321 );
322
323 /// Bits per sent component of a replicated rotation. With the index bits
324 /// and the three position axes it fills [`Self::QUANTIZED_LEN`] with no
325 /// padding (asserted below the impl), so the precision costs nothing the
326 /// payload's last byte was not already spending.
327 pub const WIRE_ROTATION_BITS: u32 = 18;
328
329 /// A replicated rotation: smallest-three at [`Self::WIRE_ROTATION_BITS`].
330 pub const WIRE_ROTATION: SmallestThree = SmallestThree::new(Self::WIRE_ROTATION_BITS);
331
332 /// The quantized replication schema: each position axis as
333 /// [`Self::WIRE_POSITION`] fixed point, the rotation as
334 /// [`Self::WIRE_ROTATION`].
335 pub const WIRE_SCHEMA: &'static [Field] = &[
336 Field {
337 name: "position.x",
338 codec: Codec::Fixed(Self::WIRE_POSITION),
339 },
340 Field {
341 name: "position.y",
342 codec: Codec::Fixed(Self::WIRE_POSITION),
343 },
344 Field {
345 name: "position.z",
346 codec: Codec::Fixed(Self::WIRE_POSITION),
347 },
348 Field {
349 name: "rotation",
350 codec: Codec::Rotation(Self::WIRE_ROTATION),
351 },
352 ];
353
354 /// Byte length of the quantized form [`Self::encode_wire`] writes.
355 pub const QUANTIZED_LEN: usize = quantize::encoded_len(Self::WIRE_SCHEMA);
356
357 /// Byte length of the replication encoding written by [`Self::encode`].
358 ///
359 /// Always [`Self::ENCODED_LEN`] — the encoding is fixed-width, so this
360 /// does not depend on `self`. It takes a receiver only so call sites can
361 /// write `transform.encoded_len()` next to `transform.encode(..)`.
362 #[inline]
363 #[must_use]
364 pub const fn encoded_len(&self) -> usize {
365 Self::ENCODED_LEN
366 }
367
368 /// Append the replication encoding to `out` (little-endian, platform-
369 /// and run-deterministic).
370 pub fn encode(&self, out: &mut Vec<u8>) {
371 for value in [
372 self.position.x,
373 self.position.y,
374 self.position.z,
375 self.rotation.x,
376 self.rotation.y,
377 self.rotation.z,
378 self.rotation.w,
379 ] {
380 out.extend_from_slice(&value.to_le_bytes());
381 }
382 }
383
384 /// Decode a transform from the encoding written by [`Self::encode`].
385 ///
386 /// Returns `None` if `data` is not exactly [`Self::ENCODED_LEN`] bytes, if
387 /// any component is not finite, or if the rotation is not (near enough) a
388 /// unit quaternion.
389 ///
390 /// This runs on bytes a peer sent us. A NaN or infinite position poisons
391 /// every AABB it reaches and, through them, the whole BVH; a degenerate
392 /// quaternion turns [`Self::forward`] / [`Self::right`] / [`Self::up`]
393 /// into garbage. Neither is representable by [`Self::encode`], so
394 /// rejecting them here costs a well-behaved peer nothing.
395 #[must_use]
396 pub fn decode(data: &[u8]) -> Option<Self> {
397 if data.len() != Self::ENCODED_LEN {
398 return None;
399 }
400 let mut values = [0.0f64; 7];
401 for (i, value) in values.iter_mut().enumerate() {
402 let bytes: [u8; 8] = data[i * 8..(i + 1) * 8].try_into().ok()?;
403 *value = f64::from_le_bytes(bytes);
404 }
405 Self::from_parts(&values)
406 }
407
408 /// A transform from position then rotation `x, y, z, w`, or `None` if any
409 /// is not finite or the rotation is not (near enough) a unit quaternion.
410 fn from_parts(values: &[f64; 7]) -> Option<Self> {
411 if values.iter().any(|value| !value.is_finite()) {
412 return None;
413 }
414 let rotation = DQuat::from_xyzw(values[3], values[4], values[5], values[6]);
415 if (rotation.length_squared() - 1.0).abs() > Self::ROTATION_TOLERANCE {
416 return None;
417 }
418 Some(Self {
419 position: DVec3::new(values[0], values[1], values[2]),
420 rotation,
421 })
422 }
423
424 /// Append the replicated form to `out`: [`Self::WIRE_SCHEMA`]'s
425 /// [`Self::QUANTIZED_LEN`] bytes when the position is inside
426 /// [`Self::WIRE_POSITION`], otherwise the exact [`Self::encode`] form.
427 ///
428 /// The fallback is what keeps an entity outside the declared range where
429 /// it is: clamping it to the range's edge would move it on every client
430 /// and say nothing. The two lengths differ, which is how
431 /// [`Self::decode_wire`] tells them apart.
432 pub fn encode_wire(&self, out: &mut Vec<u8>) {
433 // A refusal writes nothing, so the exact form lands in its place.
434 if quantize::encode(self, out).is_err() {
435 self.encode(out);
436 }
437 }
438
439 /// Decode either form [`Self::encode_wire`] writes, telling them apart by
440 /// length.
441 ///
442 /// Returns `None` for any other length, and for what [`Self::decode`]
443 /// refuses. A quantized payload always holds a unit quaternion and a
444 /// finite position; one with a padding bit or a code the encoder never
445 /// writes is refused.
446 #[must_use]
447 pub fn decode_wire(data: &[u8]) -> Option<Self> {
448 match data.len() {
449 Self::QUANTIZED_LEN => quantize::decode(data).ok(),
450 Self::ENCODED_LEN => Self::decode(data),
451 _ => None,
452 }
453 }
454
455 /// Linearly interpolate between `self` and `other` at `alpha ∈ [0, 1]`.
456 ///
457 /// Position is lerped; rotation is glam's nlerp (shortest-path
458 /// corrected, renormalised). This is presentation-only smoothing for
459 /// the client render path — simulation state is never interpolated.
460 #[must_use]
461 pub fn lerp(&self, other: &Self, alpha: f64) -> Self {
462 Self {
463 position: self.position.lerp(other.position, alpha),
464 rotation: self.rotation.lerp(other.rotation, alpha),
465 }
466 }
467}
468
469/// The quantized wire form [`Transform::encode_wire`] prefers.
470impl Quantized for Transform {
471 const SCHEMA: &'static [Field] = Self::WIRE_SCHEMA;
472 type Values = [f64; 7];
473
474 fn to_values(&self) -> [f64; 7] {
475 [
476 self.position.x,
477 self.position.y,
478 self.position.z,
479 self.rotation.x,
480 self.rotation.y,
481 self.rotation.z,
482 self.rotation.w,
483 ]
484 }
485
486 fn from_values(values: &[f64; 7]) -> Option<Self> {
487 Self::from_parts(values)
488 }
489}
490
491// The quantized form must not be mistaken for the exact one, and the schema
492// must consume exactly the seven values `to_values` supplies.
493const _: () = assert!(Transform::QUANTIZED_LEN != Transform::ENCODED_LEN);
494const _: () = assert!(quantize::value_count(Transform::WIRE_SCHEMA) == 7);
495const _: () = assert!(
496 3 * Transform::WIRE_POSITION_BITS + Transform::WIRE_ROTATION.encoded_bits()
497 == 8 * Transform::QUANTIZED_LEN as u32
498);
499
500impl Default for Transform {
501 fn default() -> Self {
502 Self::IDENTITY
503 }
504}
505
506// ---------------------------------------------------------------------------
507// ColliderComponent
508// ---------------------------------------------------------------------------
509
510/// A shape attached to an entity for physics queries.
511///
512/// This bundles a collider shape with a trigger flag. The shape is stored
513/// by-value; there is no indirection to the `crate::PhysicsWorld` — the
514/// physics system is responsible for syncing colliders into the world.
515#[derive(Debug, Clone, PartialEq)]
516pub enum ColliderComponent {
517 /// A sphere collider, its offset turned with its body in the contact
518 /// pipeline and the query world ([`crate::PhysicsSystem::world`]) alike.
519 Sphere {
520 /// Offset from the entity's [`Transform::position`] in the body's
521 /// frame.
522 offset: DVec3,
523 /// Radius in metres.
524 radius: f64,
525 /// Whether this collider is a trigger (non-solid, overlap-only).
526 is_trigger: bool,
527 },
528 /// A box collider, turned with its body: the offset and the faces are
529 /// turned by the body's rotation, in the contact pipeline and the query
530 /// world ([`crate::PhysicsSystem::world`]) alike.
531 Box {
532 /// Offset from the entity's [`Transform::position`] in the body's
533 /// frame.
534 offset: DVec3,
535 /// Half-extents along the body's own axes, in metres.
536 half_extents: DVec3,
537 /// Whether this collider is a trigger.
538 is_trigger: bool,
539 },
540 /// A capsule collider along the body's `Y`, turned with its body: the
541 /// offset and the core are turned by the body's rotation, in the contact
542 /// pipeline and the query world ([`crate::PhysicsSystem::world`]) alike.
543 Capsule {
544 /// Offset from the entity's [`Transform::position`] in the body's
545 /// frame.
546 offset: DVec3,
547 /// Radius in metres.
548 radius: f64,
549 /// Half the length of the cylindrical section.
550 half_height: f64,
551 /// Whether this collider is a trigger.
552 is_trigger: bool,
553 },
554 /// Several boxes fixed in the body's frame, turning with it: see
555 /// [`CompoundShape`].
556 ///
557 /// The offset and every part are turned by the body's rotation wherever
558 /// they are placed. In a system with contacts each part collides on its
559 /// own; in the query world ([`crate::PhysicsSystem::world`]) the compound
560 /// is one collider whose rays, sweeps and overlaps answer for the parts
561 /// themselves, each hit naming its part in
562 /// [`ShapeHit::part`](crate::ShapeHit::part)
563 /// ([`crate::PhysicsWorld::add_compound`]).
564 Compound {
565 /// Offset of the shape's frame from the entity's
566 /// [`Transform::position`], in the body's frame: minus the centre of
567 /// mass for a body [`CompoundShape::dynamic_body`] builds.
568 offset: DVec3,
569 /// The parts.
570 shape: CompoundShape,
571 /// Whether this collider is a trigger.
572 is_trigger: bool,
573 },
574 /// A static triangle mesh, its vertices in the body's frame, turning with
575 /// it: see [`TriangleMesh`].
576 ///
577 /// **For static and kinematic bodies only**: a mesh has no volume to
578 /// weigh, so [`crate::PhysicsSystem::set_collider`] and
579 /// [`crate::PhysicsSystem::set_body`] refuse to put one on a dynamic body.
580 /// In a system with contacts each triangle collides on its own, one-sided;
581 /// the query world ([`crate::PhysicsSystem::world`]) holds the mesh
582 /// itself, and its rays, sweeps and overlaps hit the triangles exactly.
583 Mesh {
584 /// The mesh.
585 mesh: TriangleMesh,
586 /// Whether this collider is a trigger.
587 is_trigger: bool,
588 },
589}
590
591impl ColliderComponent {
592 /// How far its farthest point is from the body's origin, which the body
593 /// turns about, in metres: what an angular speed is multiplied by to give
594 /// the fastest a point of the body moves.
595 ///
596 /// Exact for a sphere, a box and a compound (their farthest corners), and
597 /// for a capsule (the farther cap). A mesh answers the farthest vertex;
598 /// it is never on a dynamic body, which is the only kind that sleeps.
599 #[must_use]
600 pub fn max_extent(&self) -> f64 {
601 let farthest_corner = |centre: DVec3, rotation: DQuat, half: DVec3| {
602 let mut farthest: f64 = 0.0;
603 for x in [-half.x, half.x] {
604 for y in [-half.y, half.y] {
605 for z in [-half.z, half.z] {
606 farthest = farthest.max((centre + rotation * DVec3::new(x, y, z)).length());
607 }
608 }
609 }
610 farthest
611 };
612 match self {
613 Self::Sphere { offset, radius, .. } => offset.length() + radius,
614 Self::Box {
615 offset,
616 half_extents,
617 ..
618 } => farthest_corner(*offset, DQuat::IDENTITY, *half_extents),
619 Self::Capsule {
620 offset,
621 radius,
622 half_height,
623 ..
624 } => {
625 let cap = DVec3::new(0.0, *half_height, 0.0);
626 (*offset + cap).length().max((*offset - cap).length()) + radius
627 }
628 Self::Compound { offset, shape, .. } => shape
629 .parts()
630 .iter()
631 .map(|part| {
632 farthest_corner(*offset + part.centre, part.rotation, part.half_extents)
633 })
634 .fold(0.0, f64::max),
635 Self::Mesh { mesh, .. } => mesh
636 .vertices()
637 .iter()
638 .map(|vertex| vertex.length())
639 .fold(0.0, f64::max),
640 }
641 }
642
643 /// How many shapes it is to the contact pipeline: its parts for a
644 /// compound, its triangles for a mesh, one for anything else.
645 #[must_use]
646 pub fn part_count(&self) -> usize {
647 match self {
648 Self::Compound { shape, .. } => shape.parts().len(),
649 Self::Mesh { mesh, .. } => mesh.triangle_count(),
650 Self::Sphere { .. } | Self::Box { .. } | Self::Capsule { .. } => 1,
651 }
652 }
653}
654
655// ---------------------------------------------------------------------------
656// Tests
657// ---------------------------------------------------------------------------
658
659#[cfg(test)]
660mod tests {
661 use super::*;
662
663 #[test]
664 fn dynamic_body_has_inverse_mass() {
665 let body = RigidBody::new_dynamic(2.0);
666 assert!((body.inverse_mass - 0.5).abs() < 1e-12);
667 assert!(body.is_dynamic());
668 }
669
670 #[test]
671 fn kinematic_body_is_not_dynamic() {
672 let body = RigidBody::new_kinematic();
673 assert_eq!(body.inverse_mass, 0.0);
674 assert!(!body.is_dynamic());
675 }
676
677 #[test]
678 #[should_panic(expected = "dynamic mass must be positive")]
679 fn new_dynamic_rejects_zero_mass() {
680 let _ = RigidBody::new_dynamic(0.0);
681 }
682
683 #[test]
684 #[should_panic(expected = "a kinematic body has no finite inertia")]
685 fn a_kinematic_body_refuses_an_inertia() {
686 let _ = RigidBody::new_kinematic().with_inertia(DMat3::IDENTITY);
687 }
688
689 #[test]
690 #[should_panic(expected = "positive definite")]
691 fn an_inertia_that_is_not_positive_definite_is_refused() {
692 let _ = RigidBody::new_dynamic(1.0)
693 .with_inertia(DMat3::from_diagonal(DVec3::new(1.0, -1.0, 1.0)));
694 }
695
696 #[test]
697 #[should_panic(expected = "symmetric")]
698 fn an_asymmetric_inertia_is_refused() {
699 let mut inertia = DMat3::IDENTITY;
700 inertia.x_axis.y = 0.1;
701 let _ = RigidBody::new_dynamic(1.0).with_inertia(inertia);
702 }
703
704 /// A body spinning at `ω` about a principal axis of moment `I`: momentum
705 /// `I ω` along the axis, whichever way the body is turned, and energy
706 /// `½ m v² + ½ I ω²`.
707 #[test]
708 fn momentum_and_energy_read_the_inertia_in_the_bodys_own_frame() {
709 let mut body = RigidBody::new_dynamic(2.0)
710 .with_inertia(DMat3::from_diagonal(DVec3::new(1.0, 2.0, 3.0)));
711 body.velocity = DVec3::new(3.0, 0.0, 0.0);
712 // Turned a quarter about Z, the body's X lies along world Y; spinning
713 // about world Y is spinning about the body's X, moment 1.
714 let quarter = DQuat::from_xyzw(
715 0.0,
716 0.0,
717 core::f64::consts::FRAC_1_SQRT_2,
718 core::f64::consts::FRAC_1_SQRT_2,
719 );
720 body.angular_velocity = DVec3::new(0.0, 4.0, 0.0);
721 let momentum = body.angular_momentum(quarter);
722 assert!(
723 (momentum - DVec3::new(0.0, 4.0, 0.0)).length() < 1e-12,
724 "{momentum:?}"
725 );
726 let energy = body.kinetic_energy(quarter);
727 assert!((energy - (9.0 + 8.0)).abs() < 1e-12, "{energy}");
728 assert_eq!(RigidBody::new_kinematic().kinetic_energy(quarter), 0.0);
729 }
730
731 #[test]
732 fn applied_forces_sum_into_the_accumulator_and_clearing_zeroes_it() {
733 let mut body = RigidBody::new_dynamic(1.0);
734 body.apply_force(DVec3::new(1.0, 0.0, 0.0));
735 body.apply_force(DVec3::new(0.0, 2.0, 0.0));
736 assert_eq!(body.force_accum, DVec3::new(1.0, 2.0, 0.0));
737 body.clear_forces();
738 assert_eq!(body.force_accum, DVec3::ZERO);
739 }
740
741 #[test]
742 fn apply_impulse_changes_velocity() {
743 let mut body = RigidBody::new_dynamic(2.0);
744 body.apply_impulse(DVec3::new(4.0, 0.0, 0.0));
745 assert_eq!(body.velocity, DVec3::new(2.0, 0.0, 0.0));
746 }
747
748 #[test]
749 fn kinematic_body_ignores_impulse() {
750 let mut body = RigidBody::new_kinematic();
751 body.apply_impulse(DVec3::new(10.0, 0.0, 0.0));
752 assert_eq!(body.velocity, DVec3::ZERO);
753 }
754
755 #[test]
756 fn transform_directions_are_orthogonal() {
757 let t = Transform::IDENTITY;
758 assert_eq!(t.forward(), DVec3::NEG_Z);
759 assert_eq!(t.right(), DVec3::X);
760 assert_eq!(t.up(), DVec3::Y);
761 }
762
763 /// **The exact form is unchanged**: seven `f64`s, little-endian, position
764 /// then rotation `x, y, z, w` — what every replicated transform was before
765 /// quantization, and what one outside the quantized range still is.
766 #[test]
767 fn the_exact_encoding_is_the_seven_values_little_endian() {
768 let t = Transform::new(
769 DVec3::new(1.25, -2.5, 1e6),
770 crate::rotation_from_scaled_axis(DVec3::X * 0.5),
771 );
772 let mut buf = Vec::new();
773 t.encode(&mut buf);
774 let raw: Vec<u8> = [
775 t.position.x,
776 t.position.y,
777 t.position.z,
778 t.rotation.x,
779 t.rotation.y,
780 t.rotation.z,
781 t.rotation.w,
782 ]
783 .iter()
784 .flat_map(|v| v.to_le_bytes())
785 .collect();
786 assert_eq!(buf, raw);
787 }
788
789 #[test]
790 fn the_wire_position_quantum_is_a_power_of_two() {
791 assert_eq!(Transform::WIRE_POSITION.quantum(), 1.0 / 2048.0);
792 assert_eq!(Transform::QUANTIZED_LEN, 16);
793 }
794
795 /// A transform drawn from `i`: a position anywhere inside the quantized
796 /// range and an arbitrary rotation.
797 fn drawn(i: u64) -> Transform {
798 use crcbl_core::rand::hash_unit;
799 let extent = Transform::WIRE_POSITION_EXTENT;
800 let unit = |k: u64| hash_unit(0x7157, 8 * i + k) * 2.0 - 1.0;
801 let axis = DVec3::new(unit(3), unit(4), unit(5));
802 Transform::new(
803 DVec3::new(unit(0), unit(1), unit(2)) * extent * (1.0 - 1e-9),
804 crate::rotation_from_scaled_axis(axis * std::f64::consts::PI),
805 )
806 }
807
808 /// **A quantized transform decodes within its bounds**: half a quantum per
809 /// position axis, and the rotation within smallest-three's four half-quanta
810 /// per component (derived beside `crcbl_ecs::quantize`'s own test), after
811 /// lining `q` and `-q` up.
812 #[test]
813 fn a_quantized_transform_round_trips_within_its_bounds() {
814 let half = Transform::WIRE_POSITION.quantum() / 2.0;
815 let rotation_bound = 2.0 * Transform::WIRE_ROTATION.quantum();
816 for i in 0..5_000 {
817 let t = drawn(i);
818 let mut buf = Vec::new();
819 t.encode_wire(&mut buf);
820 assert_eq!(buf.len(), Transform::QUANTIZED_LEN, "{t:?} is in range");
821 let back = Transform::decode_wire(&buf).expect("a quantized payload decodes");
822 assert!((back.position - t.position).abs().max_element() <= half);
823 let aligned = if back.rotation.dot(t.rotation) < 0.0 {
824 -back.rotation
825 } else {
826 back.rotation
827 };
828 let error = (aligned - t.rotation).to_array();
829 assert!(
830 error.iter().all(|e| e.abs() <= rotation_bound),
831 "{error:?} past {rotation_bound:e}"
832 );
833 }
834 // The range's own edges: its bottom corner and its last code.
835 let top = Transform::WIRE_POSITION_EXTENT - Transform::WIRE_POSITION.quantum();
836 for corner in [
837 DVec3::splat(-Transform::WIRE_POSITION_EXTENT),
838 DVec3::splat(top),
839 ] {
840 let mut buf = Vec::new();
841 Transform::from_position(corner).encode_wire(&mut buf);
842 assert_eq!(buf.len(), Transform::QUANTIZED_LEN);
843 assert_eq!(Transform::decode_wire(&buf).unwrap().position, corner);
844 }
845 }
846
847 /// **Outside the quantized range a transform replicates exactly**, rather
848 /// than being clamped to the edge, and the decoder reads that form too.
849 #[test]
850 fn a_transform_outside_the_range_falls_back_to_the_exact_form() {
851 let far = Transform::new(
852 DVec3::new(Transform::WIRE_POSITION_EXTENT, -3.0, 0.125),
853 crate::rotation_from_scaled_axis(DVec3::Z * 1.1),
854 );
855 let mut buf = Vec::new();
856 far.encode_wire(&mut buf);
857 assert_eq!(buf.len(), Transform::ENCODED_LEN);
858 assert_eq!(Transform::decode_wire(&buf), Some(far), "bit for bit");
859
860 for len in [
861 0,
862 4,
863 Transform::QUANTIZED_LEN - 1,
864 Transform::QUANTIZED_LEN + 1,
865 ] {
866 assert_eq!(Transform::decode_wire(&vec![0; len]), None, "{len} bytes");
867 }
868 }
869
870 #[test]
871 fn decode_rejects_non_finite_and_degenerate_payloads() {
872 let good = Transform::new(
873 DVec3::new(1.0, 2.0, 3.0),
874 crate::rotation_from_scaled_axis(DVec3::Y * 0.75),
875 );
876 let mut buf = Vec::new();
877 good.encode(&mut buf);
878 assert!(Transform::decode(&buf).is_some());
879
880 // Field 0 is position.x, field 3 the first quaternion component.
881 let poison = |field: usize, value: f64| {
882 let mut data = buf.clone();
883 data[field * 8..(field + 1) * 8].copy_from_slice(&value.to_le_bytes());
884 Transform::decode(&data)
885 };
886
887 assert!(poison(0, f64::NAN).is_none(), "NaN position");
888 assert!(poison(1, f64::INFINITY).is_none(), "infinite position");
889 assert!(poison(2, f64::NEG_INFINITY).is_none(), "-inf position");
890 assert!(poison(6, f64::NAN).is_none(), "NaN quaternion component");
891
892 // A zero quaternion has length 0: `forward()` on it is meaningless.
893 let mut zero_rot = buf.clone();
894 for field in 3..7 {
895 zero_rot[field * 8..(field + 1) * 8].copy_from_slice(&0.0f64.to_le_bytes());
896 }
897 assert!(Transform::decode(&zero_rot).is_none(), "zero quaternion");
898
899 // So is a scaled one.
900 let scaled = Transform::new(good.position, DQuat::from_xyzw(0.0, 0.0, 0.0, 4.0));
901 let mut data = Vec::new();
902 scaled.encode(&mut data);
903 assert!(Transform::decode(&data).is_none(), "non-unit quaternion");
904 }
905
906 #[test]
907 fn collider_component_is_clone() {
908 let c = ColliderComponent::Sphere {
909 offset: DVec3::ZERO,
910 radius: 1.0,
911 is_trigger: false,
912 };
913 let c2 = c.clone();
914 assert_eq!(c, c2);
915 }
916
917 /// **Each shape's farthest point from the body's origin**, checked
918 /// against values worked by hand.
919 #[test]
920 fn max_extent_is_the_farthest_point_of_each_shape() {
921 let close = |a: f64, b: f64| (a - b).abs() < 1e-12;
922 let sphere = ColliderComponent::Sphere {
923 offset: DVec3::new(3.0, 4.0, 0.0),
924 radius: 1.0,
925 is_trigger: false,
926 };
927 assert!(close(sphere.max_extent(), 6.0));
928 let cuboid = ColliderComponent::Box {
929 offset: DVec3::ZERO,
930 half_extents: DVec3::new(1.0, 2.0, 2.0),
931 is_trigger: false,
932 };
933 assert!(close(cuboid.max_extent(), 3.0));
934 let capsule = ColliderComponent::Capsule {
935 offset: DVec3::new(0.0, 1.0, 0.0),
936 radius: 0.5,
937 half_height: 1.0,
938 is_trigger: false,
939 };
940 assert!(close(capsule.max_extent(), 2.5), "the upper cap");
941 let shape = CompoundShape::from_aabbs(&[crate::collider::Aabb::from_centre_half(
942 DVec3::new(2.0, 0.0, 0.0),
943 DVec3::new(1.0, 2.0, 2.0),
944 )])
945 .expect("one part");
946 let compound = ColliderComponent::Compound {
947 offset: DVec3::new(1.0, 0.0, 0.0),
948 shape,
949 is_trigger: false,
950 };
951 // The corner at (1 + 2 + 1, 2, 2).
952 assert!(close(compound.max_extent(), 24.0_f64.sqrt()));
953 }
954}