ferravex_physics/
body.rs

1use crate::Rotation2;
2use ferravex_math::{Quat, Vec3};
3use std::ops::{Index, IndexMut};
4
5/// Linear and angular velocity handling during a checked teleport.
6/// See `d2::RigidBody::try_teleport` or `d3::RigidBody::try_teleport`.
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum VelocityPolicy {
9    /// Retain the stored world-space center-of-mass and angular velocities.
10    /// This does not preserve angular momentum when the orientation changes.
11    Preserve,
12    /// Set both stored velocities to zero.
13    Clear,
14}
15
16/// Independent motion-reset choices for a checked teleport.
17/// Construction requires an explicit velocity policy. Fields may be edited to
18/// retain forces or pending targets; see the dimensional teleport methods.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20#[must_use]
21pub struct TeleportOptions {
22    pub velocity: VelocityPolicy,
23    /// Clear both accumulated force and torque. Gravity/damping are unchanged.
24    pub clear_forces: bool,
25    /// Clear both next-position and next-rotation kinematic targets.
26    pub clear_kinematic_targets: bool,
27}
28impl TeleportOptions {
29    /// Select a velocity policy and clear forces/torque and kinematic targets.
30    /// To retain either independently, set the corresponding field to `false`.
31    /// See `d2::RigidBody::try_teleport` for a runnable reset recipe.
32    pub const fn new(velocity: VelocityPolicy) -> Self {
33        Self {
34            velocity,
35            clear_forces: true,
36            clear_kinematic_targets: true,
37        }
38    }
39}
40
41/// Checked teleport failure. The entire request is rejected before any edit.
42/// The world method checks the handle first, then translation, rotation and
43/// revision capacity. Handles must come from the same world; they contain no
44/// world identity. See the dimensional `PhysicsWorld::try_teleport_body` recipe.
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum TeleportError {
47    /// The requested body handle is stale or absent.
48    InvalidHandle,
49    /// The authored body-origin translation contains a non-finite component.
50    Translation,
51    /// Rotation cannot be normalized to a finite, dimension-valid quaternion.
52    Rotation,
53    /// The body's contact revision cannot advance without reusing an identity.
54    RevisionExhausted,
55}
56impl std::fmt::Display for TeleportError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58        f.write_str(match self {
59            Self::InvalidHandle => "teleport body handle is stale or absent",
60            Self::Translation => "teleport translation must be finite",
61            Self::Rotation => "teleport rotation must be finite, nonzero and dimension-valid",
62            Self::RevisionExhausted => "teleport body revision exhausted",
63        })
64    }
65}
66impl std::error::Error for TeleportError {}
67
68/// Transactional shape replacement failure. See the dimensional
69/// `PhysicsWorld::replace_collider_shape` method for a runnable editing recipe.
70/// Existing `PhysicsError` variants remain unchanged.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum ColliderShapeError {
73    /// The collider or its parent is stale or absent in this world.
74    InvalidHandle,
75    /// Candidate geometry or retained collider settings are invalid for this world.
76    InvalidCollider,
77    /// The resulting dynamic compound has zero or unrepresentable mass/inertia.
78    InvalidMass,
79    /// The collider or body contact revision cannot advance without identity reuse.
80    RevisionExhausted,
81}
82impl std::fmt::Display for ColliderShapeError {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        f.write_str(match self {
85            Self::InvalidHandle => "shape replacement handle is stale or absent",
86            Self::InvalidCollider => "shape replacement collider is invalid for this world",
87            Self::InvalidMass => "shape replacement compound mass/inertia is invalid",
88            Self::RevisionExhausted => "shape replacement contact revision exhausted",
89        })
90    }
91}
92impl std::error::Error for ColliderShapeError {}
93
94/// The first invalid field encountered by checked rigid-body authoring.
95///
96/// Mass is derived from collider densities and dimensions, not supplied on a
97/// rigid-body builder. `Mass` therefore describes the combined mass/inertia;
98/// `Density` describes an invalid individual density. Checks never insert into
99/// a world or change a previously built body/collider.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum BodyValidationError {
102    /// Body translation must be finite.
103    Translation,
104    /// Body rotation must represent a finite unit quaternion.
105    Rotation,
106    /// Linear velocity must be finite.
107    LinearVelocity,
108    /// Angular velocity must be finite.
109    AngularVelocity,
110    /// Linear damping must be finite and nonnegative.
111    LinearDamping,
112    /// Angular damping must be finite and nonnegative.
113    AngularDamping,
114    /// Gravity scale must be finite.
115    GravityScale,
116    /// Collider translation must be finite and within +/-1e6 on each axis.
117    ColliderTranslation,
118    /// Collider rotation must be valid and preserve the plane for 2D bodies.
119    ColliderRotation,
120    /// Density must be finite and in 0..=1e6; zero-density children are allowed.
121    Density,
122    /// Radius must be finite and positive.
123    Radius,
124    /// Every half-extent must be finite and positive.
125    HalfExtents,
126    /// Cylinder half-height must be finite and positive.
127    HalfHeight,
128    /// The first capsule endpoint must be finite and planar in 2D.
129    CapsuleStart,
130    /// The second capsule endpoint must be finite and planar in 2D.
131    CapsuleEnd,
132    /// A cylinder cannot be used in a 2D body definition.
133    ShapeDimension,
134    /// The contact material must satisfy `PhysicsMaterial::valid`.
135    Material,
136    /// Dynamic bodies need positive finite mass and representable inverse mass/inertia.
137    Mass,
138    /// A body definition may contain at most `MAX_CHILDREN` colliders.
139    ChildCapacity,
140}
141
142impl std::fmt::Display for BodyValidationError {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        f.write_str(match self {
145            Self::Translation => "body translation must be finite",
146            Self::Rotation => "body rotation must represent a finite unit quaternion",
147            Self::LinearVelocity => "linear velocity must be finite",
148            Self::AngularVelocity => "angular velocity must be finite",
149            Self::LinearDamping => "linear damping must be finite and nonnegative",
150            Self::AngularDamping => "angular damping must be finite and nonnegative",
151            Self::GravityScale => "gravity scale must be finite",
152            Self::ColliderTranslation => {
153                "collider translation must be finite, within +/-1e6, and planar in 2D"
154            }
155            Self::ColliderRotation => {
156                "collider rotation must be a finite unit quaternion and preserve the plane in 2D"
157            }
158            Self::Density => "density must be finite and in 0..=1e6",
159            Self::Radius => "radius must be finite and positive",
160            Self::HalfExtents => "half-extents must be finite and positive",
161            Self::HalfHeight => "half-height must be finite and positive",
162            Self::CapsuleStart => "capsule start must be finite and planar in 2D",
163            Self::CapsuleEnd => "capsule end must be finite and planar in 2D",
164            Self::ShapeDimension => "cylinders require a 3D body",
165            Self::Material => "contact material is invalid",
166            Self::Mass => "dynamic body mass/inertia must be positive, finite and invertible",
167            Self::ChildCapacity => "body definition exceeds MAX_CHILDREN",
168        })
169    }
170}
171impl std::error::Error for BodyValidationError {}
172
173fn require(valid: bool, error: BodyValidationError) -> Result<(), BodyValidationError> {
174    if valid { Ok(()) } else { Err(error) }
175}
176
177fn unit_rotation(q: Quat, planar: bool) -> bool {
178    q.is_finite()
179        && (q.length_squared() - 1.).abs() < 0.001
180        && (!planar || (q * Vec3::Z - Vec3::Z).length_squared() < 1e-6)
181}
182
183fn valid_density(density: f32) -> bool {
184    density.is_finite() && (0. ..=1e6).contains(&density)
185}
186
187fn valid_local_translation(p: Vec3, planar: bool) -> bool {
188    p.is_finite() && p.abs().max_element() <= 1e6 && (!planar || p.z == 0.)
189}
190
191#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
192pub struct RigidBodyHandle {
193    pub(crate) index: usize,
194    pub(crate) generation: u32,
195}
196#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
197pub struct ColliderHandle {
198    pub(crate) index: usize,
199    pub(crate) generation: u32,
200}
201#[derive(Clone, Debug)]
202pub(crate) struct Slot<T> {
203    pub(crate) generation: u32,
204    pub(crate) value: Option<T>,
205}
206#[derive(Clone, Debug)]
207pub struct BodySet<B> {
208    slots: Vec<Slot<B>>,
209    len: usize,
210}
211#[derive(Clone, Debug)]
212pub struct ColliderSet {
213    slots: Vec<Slot<Collider>>,
214    len: usize,
215}
216macro_rules! arena {
217    ($set:ident $(<$generic:ident>)?,$item:ty,$handle:ident) => {
218        impl$(<$generic>)? Default for $set$(<$generic>)? {fn default()->Self {Self{slots:Vec::new(),len:0}}}
219        impl$(<$generic>)? $set$(<$generic>)? {
220            pub fn len(&self)->usize {self.len}
221            pub fn is_empty(&self)->bool {self.len==0}
222            pub fn get(&self,h:$handle)->Option<&$item> {let s=self.slots.get(h.index)?; (s.generation==h.generation).then_some(s.value.as_ref()).flatten()}
223            pub fn get_mut(&mut self,h:$handle)->Option<&mut $item> {let s=self.slots.get_mut(h.index)?; (s.generation==h.generation).then_some(s.value.as_mut()).flatten()}
224            pub fn iter(&self)->impl Iterator<Item=($handle,&$item)> {self.slots.iter().enumerate().filter_map(|(index,s)|s.value.as_ref().map(|v|($handle{index,generation:s.generation},v)))}
225            pub fn iter_mut(&mut self)->impl Iterator<Item=($handle,&mut $item)> {self.slots.iter_mut().enumerate().filter_map(|(index,s)|s.value.as_mut().map(|v|($handle{index,generation:s.generation},v)))}
226            pub(crate) fn insert(&mut self,value:$item)->$handle {
227                self.len+=1;
228                for(index,s) in self.slots.iter_mut().enumerate() {if s.value.is_none()&&s.generation<u32::MAX {s.value=Some(value);return $handle{index,generation:s.generation};}}
229                let index=self.slots.len();self.slots.push(Slot{generation:0,value:Some(value)});$handle{index,generation:0}
230            }
231            pub(crate) fn remove(&mut self,h:$handle)->Option<$item> {let s=self.slots.get_mut(h.index)?;if s.generation!=h.generation {return None;} let v=s.value.take()?;s.generation=s.generation.saturating_add(1);self.len-=1;Some(v)}
232        }
233        impl$(<$generic>)? Index<$handle> for $set$(<$generic>)? {type Output=$item;fn index(&self,h:$handle)->&$item {self.get(h).expect("stale physics handle")}}
234        impl$(<$generic>)? IndexMut<$handle> for $set$(<$generic>)? {fn index_mut(&mut self,h:$handle)->&mut $item {self.get_mut(h).expect("stale physics handle")}}
235    }
236}
237pub(crate) use arena;
238arena!(BodySet<B>, B, RigidBodyHandle);
239arena!(ColliderSet, Collider, ColliderHandle);
240#[derive(Clone, Copy, Debug)]
241pub(crate) enum Shape {
242    Ball(f32),
243    Box(Vec3),
244    #[cfg(feature = "dim2")]
245    Capsule {
246        a: Vec3,
247        b: Vec3,
248        radius: f32,
249    },
250    #[cfg(feature = "dim3")]
251    Cylinder {
252        half_height: f32,
253        radius: f32,
254    },
255}
256impl Shape {
257    pub(crate) fn check_dimensions(self, planar: bool) -> Result<(), BodyValidationError> {
258        use BodyValidationError as E;
259        // Used even in builds without dimension-specific primitives.
260        let _ = planar;
261        match self {
262            Self::Ball(radius) => require(radius.is_finite() && radius > 0., E::Radius),
263            Self::Box(half) => require(
264                half.is_finite() && half.x > 0. && half.y > 0. && half.z > 0.,
265                E::HalfExtents,
266            ),
267            #[cfg(feature = "dim2")]
268            Self::Capsule { a, b, radius } => {
269                require(a.is_finite() && (!planar || a.z == 0.), E::CapsuleStart)?;
270                require(b.is_finite() && (!planar || b.z == 0.), E::CapsuleEnd)?;
271                require(radius.is_finite() && radius > 0., E::Radius)
272            }
273            #[cfg(feature = "dim3")]
274            Self::Cylinder {
275                half_height,
276                radius,
277            } => {
278                require(!planar, E::ShapeDimension)?;
279                require(half_height.is_finite() && half_height > 0., E::HalfHeight)?;
280                require(radius.is_finite() && radius > 0., E::Radius)
281            }
282        }
283    }
284
285    pub fn validate(self) {
286        match self {
287            Self::Ball(r) => assert!(r.is_finite() && r > 0.),
288            Self::Box(h) => assert!(h.is_finite() && h.x > 0. && h.y > 0. && h.z > 0.),
289            #[cfg(feature = "dim2")]
290            Self::Capsule { a, b, radius } => {
291                assert!(a.is_finite() && b.is_finite() && radius.is_finite() && radius > 0.)
292            }
293            #[cfg(feature = "dim3")]
294            Self::Cylinder {
295                half_height,
296                radius,
297            } => assert!(
298                half_height.is_finite() && half_height > 0. && radius.is_finite() && radius > 0.
299            ),
300        }
301    }
302}
303#[derive(Clone, Debug)]
304pub struct Collider {
305    pub(crate) shape: Shape,
306    pub(crate) local_translation: Vec3,
307    pub(crate) local_rotation: Quat,
308    pub(crate) mass_dirty: bool,
309    pub(crate) parent: Option<RigidBodyHandle>,
310    pub(crate) density: f32,
311    pub(crate) material: crate::PhysicsMaterial,
312    pub(crate) sensor: bool,
313    pub(crate) membership: u32,
314    pub(crate) filter: u32,
315    pub(crate) revision: u64,
316    pub(crate) dirty: bool,
317}
318impl Collider {
319    fn validate_authoring(&self, planar: bool) -> Result<(), BodyValidationError> {
320        use BodyValidationError as E;
321        self.shape.check_dimensions(planar)?;
322        require(
323            valid_local_translation(self.local_translation, planar),
324            E::ColliderTranslation,
325        )?;
326        require(
327            unit_rotation(self.local_rotation, planar),
328            E::ColliderRotation,
329        )?;
330        require(valid_density(self.density), E::Density)?;
331        require(self.material.valid(), E::Material)
332    }
333
334    pub(crate) fn new(shape: Shape) -> Self {
335        Self {
336            shape,
337            local_translation: Vec3::ZERO,
338            local_rotation: Quat::IDENTITY,
339            mass_dirty: false,
340            parent: None,
341            density: 1.,
342            material: crate::PhysicsMaterial::default(),
343            sensor: false,
344            membership: u32::MAX,
345            filter: u32::MAX,
346            revision: 0,
347            dirty: false,
348        }
349    }
350    pub(crate) fn valid(&self, planar: bool) -> bool {
351        self.material.valid()
352            && self.local_translation.is_finite()
353            && self.local_translation.abs().max_element() <= 1e6
354            && self.local_rotation.is_finite()
355            && (self.local_rotation.length_squared() - 1.).abs() < 0.001
356            && self.density.is_finite()
357            && (0. ..=1e6).contains(&self.density)
358            && (!planar
359                || self.local_translation.z == 0.
360                    && (self.local_rotation * Vec3::Z - Vec3::Z).length_squared() < 1e-6)
361    }
362    pub fn local_translation(&self) -> Vec3 {
363        self.local_translation
364    }
365    pub fn local_rotation(&self) -> Quat {
366        self.local_rotation
367    }
368    pub fn density(&self) -> f32 {
369        self.density
370    }
371    pub fn set_density(&mut self, density: f32) {
372        assert!(density.is_finite() && (0. ..=1e6).contains(&density));
373        if self.density != density {
374            self.density = density;
375            self.touch_mass();
376        }
377    }
378    pub(crate) fn touch_mass(&mut self) {
379        self.revision = self
380            .revision
381            .checked_add(1)
382            .expect("collider revision exhausted");
383        self.dirty = true;
384        self.mass_dirty = true;
385    }
386    pub(crate) fn pose(&self, body: &Core) -> crate::geometry::Pose {
387        crate::geometry::Pose {
388            position: body.position + body.rotation * self.local_translation,
389            rotation: body.rotation * self.local_rotation,
390            planar: body.planar,
391        }
392    }
393    pub fn set_sensor(&mut self, sensor: bool) {
394        if self.sensor != sensor {
395            self.revision = self
396                .revision
397                .checked_add(1)
398                .expect("collider revision exhausted");
399            self.dirty = true;
400            self.sensor = sensor;
401        }
402    }
403    pub fn set_collision_layers(&mut self, membership: u32, filter: u32) {
404        if (self.membership, self.filter) != (membership, filter) {
405            self.revision = self
406                .revision
407                .checked_add(1)
408                .expect("collider revision exhausted");
409            self.dirty = true;
410            self.membership = membership;
411            self.filter = filter;
412        }
413    }
414    pub fn parent(&self) -> Option<RigidBodyHandle> {
415        self.parent
416    }
417    pub fn is_sensor(&self) -> bool {
418        self.sensor
419    }
420    pub fn material(&self) -> crate::PhysicsMaterial {
421        self.material
422    }
423    pub fn set_material(
424        &mut self,
425        material: crate::PhysicsMaterial,
426    ) -> Result<(), crate::PhysicsError> {
427        if !material.valid() {
428            return Err(crate::PhysicsError::InvalidCollider);
429        }
430        if self.material != material {
431            self.revision = self
432                .revision
433                .checked_add(1)
434                .expect("collider revision exhausted");
435            self.dirty = true;
436            self.material = material;
437        }
438        Ok(())
439    }
440    pub fn set_restitution(&mut self, v: f32) {
441        self.set_material(crate::PhysicsMaterial {
442            restitution: v,
443            ..self.material
444        })
445        .expect("valid restitution");
446    }
447    pub fn set_friction(&mut self, v: f32) {
448        self.set_material(crate::PhysicsMaterial {
449            static_friction: v,
450            sliding_friction: v,
451            ..self.material
452        })
453        .expect("valid friction");
454    }
455}
456#[derive(Clone, Copy, Debug, PartialEq, Eq)]
457pub(crate) enum Kind {
458    Fixed,
459    Dynamic,
460    Kinematic,
461}
462#[derive(Clone, Debug)]
463#[doc(hidden)]
464pub struct Core {
465    pub(crate) kind: Kind,
466    pub(crate) planar: bool,
467    pub(crate) position: Vec3,
468    pub(crate) rotation: Quat,
469    pub(crate) rotation2: Rotation2,
470    pub(crate) velocity: Vec3,
471    pub(crate) angular_velocity: Vec3,
472    pub(crate) mass: f32,
473    pub(crate) inv_mass: f32,
474    pub(crate) inv_inertia: crate::mass::Tensor,
475    pub(crate) local_com: Vec3,
476    pub(crate) force: Vec3,
477    pub(crate) torque: Vec3,
478    pub(crate) gravity_scale: f32,
479    pub(crate) linear_damping: f32,
480    pub(crate) angular_damping: f32,
481    pub(crate) ccd: bool,
482    pub(crate) sleeping: bool,
483    pub(crate) quiet: f32,
484    pub(crate) revision: u64,
485    pub(crate) solver_dirty: bool,
486    pub(crate) wake_requested: bool,
487    pub(crate) next_position: Option<Vec3>,
488    pub(crate) next_rotation: Option<Quat>,
489    pub(crate) colliders: Vec<ColliderHandle>,
490}
491#[doc(hidden)]
492pub trait Access {
493    fn core(&self) -> &Core;
494    fn core_mut(&mut self) -> &mut Core;
495}
496impl Core {
497    fn validate_authoring(&self) -> Result<(), BodyValidationError> {
498        use BodyValidationError as E;
499        require(self.position.is_finite(), E::Translation)?;
500        require(unit_rotation(self.rotation, self.planar), E::Rotation)?;
501        require(self.velocity.is_finite(), E::LinearVelocity)?;
502        require(self.angular_velocity.is_finite(), E::AngularVelocity)?;
503        require(
504            self.linear_damping.is_finite() && self.linear_damping >= 0.,
505            E::LinearDamping,
506        )?;
507        require(
508            self.angular_damping.is_finite() && self.angular_damping >= 0.,
509            E::AngularDamping,
510        )?;
511        require(self.gravity_scale.is_finite(), E::GravityScale)
512    }
513
514    fn validate_definition(&self, children: &[Collider]) -> Result<(), BodyValidationError> {
515        self.validate_authoring()?;
516        require(
517            children.len() <= crate::MAX_CHILDREN,
518            BodyValidationError::ChildCapacity,
519        )?;
520        for child in children {
521            child.validate_authoring(self.planar)?;
522        }
523        if self.kind == Kind::Dynamic {
524            let properties = crate::mass::compound(children.iter(), self.planar)
525                .map_err(|_| BodyValidationError::Mass)?;
526            let inverse = properties.mass.recip();
527            require(
528                inverse.is_finite() && inverse > 0.,
529                BodyValidationError::Mass,
530            )?;
531        }
532        Ok(())
533    }
534
535    pub(crate) fn new(kind: Kind, planar: bool) -> Self {
536        Self {
537            kind,
538            planar,
539            position: Vec3::ZERO,
540            rotation: Quat::IDENTITY,
541            rotation2: Rotation2::default(),
542            velocity: Vec3::ZERO,
543            angular_velocity: Vec3::ZERO,
544            mass: 0.,
545            inv_mass: 0.,
546            inv_inertia: crate::mass::Tensor::ZERO,
547            local_com: Vec3::ZERO,
548            force: Vec3::ZERO,
549            torque: Vec3::ZERO,
550            gravity_scale: 1.,
551            linear_damping: 0.,
552            angular_damping: 0.,
553            ccd: false,
554            sleeping: false,
555            quiet: 0.,
556            revision: 0,
557            solver_dirty: false,
558            wake_requested: false,
559            next_position: None,
560            next_rotation: None,
561            colliders: Vec::with_capacity(1),
562        }
563    }
564    // Prepare every fallible value before changing live state. Unlike the
565    // legacy setters, a revision-capacity failure is returned, not asserted.
566    pub(crate) fn try_teleport(
567        &mut self,
568        position: Vec3,
569        rotation: Quat,
570        options: TeleportOptions,
571    ) -> Result<(), TeleportError> {
572        if !position.is_finite() {
573            return Err(TeleportError::Translation);
574        }
575        let rotation = rotation.try_normalize().ok_or(TeleportError::Rotation)?;
576        if !unit_rotation(rotation, self.planar) {
577            return Err(TeleportError::Rotation);
578        }
579        let revision = self
580            .revision
581            .checked_add(1)
582            .ok_or(TeleportError::RevisionExhausted)?;
583        self.position = position;
584        self.rotation = rotation;
585        if self.planar {
586            let axis = rotation * Vec3::X;
587            self.rotation2 = Rotation2::from_angle(axis.y.atan2(axis.x));
588        }
589        if options.velocity == VelocityPolicy::Clear {
590            self.velocity = Vec3::ZERO;
591            self.angular_velocity = Vec3::ZERO;
592        }
593        if options.clear_forces {
594            self.force = Vec3::ZERO;
595            self.torque = Vec3::ZERO;
596        }
597        if options.clear_kinematic_targets {
598            self.next_position = None;
599            self.next_rotation = None;
600        }
601        // Even an identical-pose reset must not reuse pre-reset impulses.
602        self.revision = revision;
603        self.solver_dirty = true;
604        self.wake();
605        Ok(())
606    }
607    pub(crate) fn invalidate_contacts(&mut self) {
608        self.revision = self
609            .revision
610            .checked_add(1)
611            .expect("body revision exhausted");
612        self.solver_dirty = true;
613    }
614    pub(crate) fn wake(&mut self) {
615        self.wake_requested = true;
616        self.wake_internal();
617    }
618    pub(crate) fn wake_internal(&mut self) {
619        self.sleeping = false;
620        self.quiet = 0.;
621    }
622    pub(crate) fn set_rotation(&mut self, q: Quat) {
623        assert!(q.is_finite());
624        self.rotation = q.normalize();
625        if self.planar {
626            let axis = self.rotation * Vec3::X;
627            self.rotation2 = Rotation2::from_angle(axis.y.atan2(axis.x));
628        }
629    }
630    pub(crate) fn inverse_inertia(&self, v: Vec3) -> Vec3 {
631        // Fixed and kinematic bodies have zero inverse inertia. Contacts with
632        // floors/walls need no quaternion transforms for that half of the pair.
633        if self.kind != Kind::Dynamic {
634            Vec3::ZERO
635        } else {
636            self.rotation * self.inv_inertia.apply(self.rotation.conjugate() * v)
637        }
638    }
639    pub(crate) fn contact_inverse_inertia(&self, v: Vec3) -> Vec3 {
640        if self.sleeping {
641            Vec3::ZERO
642        } else {
643            self.inverse_inertia(v)
644        }
645    }
646    pub(crate) fn contact_inv_mass(&self) -> f32 {
647        if self.sleeping { 0. } else { self.inv_mass }
648    }
649    pub(crate) fn point_velocity(&self, p: Vec3) -> Vec3 {
650        self.offset_velocity(p - self.world_com())
651    }
652    /// Velocity at offset `r` from the world center of mass.
653    pub(crate) fn offset_velocity(&self, r: Vec3) -> Vec3 {
654        self.velocity + self.angular_velocity.cross(r)
655    }
656    pub(crate) fn impulse(&mut self, j: Vec3, p: Vec3) {
657        self.offset_impulse(j, p - self.world_com());
658    }
659    /// [`Self::impulse`] at offset `r` from the world center of mass.
660    pub(crate) fn offset_impulse(&mut self, j: Vec3, r: Vec3) {
661        if self.kind == Kind::Dynamic && !self.sleeping {
662            self.velocity += j * self.inv_mass;
663            self.angular_velocity += self.inverse_inertia(r.cross(j));
664        }
665    }
666    pub(crate) fn world_com(&self) -> Vec3 {
667        self.position + self.rotation * self.local_com
668    }
669    pub(crate) fn set_mass_properties(&mut self, properties: crate::mass::Mass) {
670        let old = self.world_com();
671        self.local_com = properties.center;
672        self.mass = properties.mass;
673        self.inv_mass = 1. / properties.mass;
674        self.inv_inertia = properties.inverse;
675        self.velocity += self.angular_velocity.cross(self.world_com() - old);
676        self.invalidate_contacts();
677        self.wake();
678    }
679    pub(crate) fn integrate(&mut self, dt: f32) {
680        let center = self.world_com() + self.velocity * dt;
681        self.set_rotation(Quat::from_scaled_axis(self.angular_velocity * dt) * self.rotation);
682        self.position = center - self.rotation * self.local_com;
683    }
684    pub(crate) fn position_impulse(&mut self, linear: Vec3, angular: Vec3) {
685        if self.kind != Kind::Dynamic || self.sleeping {
686            return;
687        }
688        let center = self.world_com() + linear * self.inv_mass;
689        let delta = self.inverse_inertia(angular).clamp_length_max(0.2);
690        if delta.length_squared() > 1e-20 {
691            self.set_rotation(Quat::from_scaled_axis(delta) * self.rotation);
692        }
693        self.position = center - self.rotation * self.local_com;
694    }
695}
696impl<B> BodySet<B> {
697    pub(crate) fn two_mut(&mut self, a: RigidBodyHandle, b: RigidBodyHandle) -> (&mut B, &mut B) {
698        assert!(a.index != b.index);
699        let (sa, sb) = if a.index < b.index {
700            let (l, r) = self.slots.split_at_mut(b.index);
701            (&mut l[a.index], &mut r[0])
702        } else {
703            let (l, r) = self.slots.split_at_mut(a.index);
704            (&mut r[0], &mut l[b.index])
705        };
706        assert_eq!(sa.generation, a.generation);
707        assert_eq!(sb.generation, b.generation);
708        (sa.value.as_mut().unwrap(), sb.value.as_mut().unwrap())
709    }
710}
711
712// Inherent extensions live here to keep authoring checks together without
713// changing the existing dimension-specific types or their constructors.
714macro_rules! checked_builders {
715    ($planar:expr) => {
716        impl RigidBodyBuilder {
717            /// Checked translation in world units. Rejects non-finite components.
718            pub fn try_translation(self, p: Vector) -> Result<Self, BodyValidationError> {
719                require(p.is_finite(), BodyValidationError::Translation)?;
720                Ok(self.translation(p))
721            }
722
723            /// Checked rotation in radians (a scaled axis in 3D).
724            /// Rejects non-finite input or an unrepresentable quaternion conversion.
725            pub fn try_rotation(self, r: Angular) -> Result<Self, BodyValidationError> {
726                let axis = angular3(r);
727                require(axis.is_finite(), BodyValidationError::Rotation)?;
728                require(
729                    unit_rotation(Quat::from_scaled_axis(axis), $planar),
730                    BodyValidationError::Rotation,
731                )?;
732                Ok(self.rotation(r))
733            }
734
735            /// Checked linear velocity in world units per second.
736            pub fn try_linvel(self, v: Vector) -> Result<Self, BodyValidationError> {
737                require(v.is_finite(), BodyValidationError::LinearVelocity)?;
738                Ok(self.linvel(v))
739            }
740
741            /// Checked angular velocity in radians per second.
742            pub fn try_angvel(self, v: Angular) -> Result<Self, BodyValidationError> {
743                require(
744                    angular3(v).is_finite(),
745                    BodyValidationError::AngularVelocity,
746                )?;
747                Ok(self.angvel(v))
748            }
749
750            /// Checked finite, nonnegative linear damping.
751            pub fn try_linear_damping(self, v: f32) -> Result<Self, BodyValidationError> {
752                require(v.is_finite() && v >= 0., BodyValidationError::LinearDamping)?;
753                Ok(self.linear_damping(v))
754            }
755
756            /// Checked finite, nonnegative angular damping.
757            pub fn try_angular_damping(self, v: f32) -> Result<Self, BodyValidationError> {
758                require(
759                    v.is_finite() && v >= 0.,
760                    BodyValidationError::AngularDamping,
761                )?;
762                Ok(self.angular_damping(v))
763            }
764
765            /// Checked finite gravity scale; negative scales are allowed.
766            pub fn try_gravity_scale(self, v: f32) -> Result<Self, BodyValidationError> {
767                require(v.is_finite(), BodyValidationError::GravityScale)?;
768                Ok(self.gravity_scale(v))
769            }
770
771            /// Builds after checking pose, velocities, damping and gravity scale.
772            ///
773            /// Mass is assigned by world insertion. To also check the proposed
774            /// colliders and dynamic mass, use [`Self::try_build_with_colliders`].
775            /// Legacy setters can still panic before this method is reached;
776            /// use the `try_*` setters for untrusted numeric input.
777            ///
778            /// ```
779            /// # #[cfg(feature = "dim2")] {
780            /// use ferravex_math::Vec2;
781            /// use ferravex_physics::d2::RigidBodyBuilder;
782            /// let body = RigidBodyBuilder::dynamic()
783            ///     .try_translation(Vec2::new(2., 3.)).unwrap()
784            ///     .try_rotation(0.5).unwrap()
785            ///     .try_linvel(Vec2::X).unwrap()
786            ///     .try_angvel(1.).unwrap()
787            ///     .try_linear_damping(0.1).unwrap()
788            ///     .try_angular_damping(0.2).unwrap()
789            ///     .try_gravity_scale(-1.).unwrap()
790            ///     .try_build().unwrap();
791            /// assert_eq!(body.linvel(), Vec2::X);
792            /// assert_eq!(body.mass(), 0.); // Mass is assigned on insertion.
793            /// let error = RigidBodyBuilder::fixed().try_linvel(Vec2::NAN).unwrap_err();
794            /// assert_eq!(error.to_string(), "linear velocity must be finite");
795            /// # }
796            /// ```
797            pub fn try_build(self) -> Result<RigidBody, BodyValidationError> {
798                let body = self.build();
799                body.core().validate_authoring()?;
800                Ok(body)
801            }
802
803            /// Builds and validates the proposed complete collider definition.
804            ///
805            /// This borrows the colliders without cloning, attaching or inserting
806            /// them. Mass remains unassigned until world insertion. Validation
807            /// does not reserve world capacity or guarantee stability for future
808            /// forces, time steps or extreme finite coordinates/velocities.
809            ///
810            /// ```
811            /// # #[cfg(feature = "dim3")] {
812            /// use ferravex_math::{Quat, Vec3};
813            /// use ferravex_physics::d3::{ColliderBuilder, PhysicsWorld, RigidBodyBuilder};
814            /// let children = [ColliderBuilder::try_cuboid(1., 0.5, 0.25).unwrap()
815            ///     .try_density(2.).unwrap()
816            ///     .try_translation(Vec3::X).unwrap()
817            ///     .try_rotation(Quat::IDENTITY).unwrap()
818            ///     .try_build().unwrap()];
819            /// let body = RigidBodyBuilder::dynamic()
820            ///     .try_rotation(Vec3::Z * 0.3).unwrap()
821            ///     .try_angvel(Vec3::Z).unwrap()
822            ///     .try_build_with_colliders(&children).unwrap();
823            /// body.validate_definition(&children).unwrap();
824            /// let mut world = PhysicsWorld::new([0.; 3]);
825            /// let handle = world.insert_compound(body, children).unwrap();
826            /// assert_eq!(world.bodies[handle].mass(), 2.);
827            /// # }
828            /// ```
829            pub fn try_build_with_colliders(
830                self,
831                colliders: &[Collider],
832            ) -> Result<RigidBody, BodyValidationError> {
833                let body = self.build();
834                body.validate_definition(colliders)?;
835                Ok(body)
836            }
837        }
838
839        impl RigidBody {
840            /// Checks this body's authored state against a proposed collider slice.
841            ///
842            /// Checks body fields first, then the child limit and each collider in
843            /// slice order, then derived mass/inertia. The first failing field is
844            /// returned. Fixed/kinematic bodies permit empty or massless geometry;
845            /// dynamic bodies need positive combined mass and invertible inertia.
846            /// Zero-density children are valid when the combined mass is valid.
847            ///
848            /// This allocation-free check does not mutate the body or colliders,
849            /// inspect attached handles, or alter cached mass. See
850            /// [`RigidBodyBuilder::try_build_with_colliders`] for an insertion example.
851            pub fn validate_definition(
852                &self,
853                colliders: &[Collider],
854            ) -> Result<(), BodyValidationError> {
855                self.core().validate_definition(colliders)
856            }
857        }
858
859        impl ColliderBuilder {
860            /// Checked circle/sphere constructor with a finite positive radius.
861            pub fn try_ball(radius: f32) -> Result<Self, BodyValidationError> {
862                Shape::Ball(radius).check_dimensions($planar)?;
863                Ok(Self::ball(radius))
864            }
865
866            /// Checked density in 0..=1e6. Zero is allowed; validate the complete
867            /// dynamic definition to ensure its combined mass remains positive.
868            pub fn try_density(self, density: f32) -> Result<Self, BodyValidationError> {
869                require(valid_density(density), BodyValidationError::Density)?;
870                Ok(self.density(density))
871            }
872
873            /// Checked body-local offset, within +/-1e6 on each axis.
874            pub fn try_translation(self, p: Vector) -> Result<Self, BodyValidationError> {
875                require(
876                    valid_local_translation(vector3(p), $planar),
877                    BodyValidationError::ColliderTranslation,
878                )?;
879                Ok(self.translation(p))
880            }
881
882            /// Checked local rotation, normalized as by the existing setter.
883            /// A 3D quaternion must be finite with squared length greater than
884            /// 1e-12 and yield a finite unit quaternion on normalization.
885            pub fn try_rotation(self, rotation: Rotation) -> Result<Self, BodyValidationError> {
886                let q = rotation3(rotation);
887                require(
888                    q.is_finite()
889                        && q.length_squared() > 1e-12
890                        && unit_rotation(q.normalize(), $planar),
891                    BodyValidationError::ColliderRotation,
892                )?;
893                Ok(self.rotation(rotation))
894            }
895
896            /// Builds after checking dimensions, local pose, density and material.
897            ///
898            /// Does not require positive mass: massless children and fixed bodies
899            /// are supported. Use `RigidBodyBuilder::try_build_with_colliders` to
900            /// also validate dynamic mass/inertia. No world state is changed.
901            ///
902            /// ```
903            /// # #[cfg(feature = "dim2")] {
904            /// use ferravex_physics::d2::{ColliderBuilder, RigidBodyBuilder};
905            /// let child = ColliderBuilder::try_ball(0.5).unwrap()
906            ///     .try_density(0.).unwrap().try_build().unwrap();
907            /// assert!(RigidBodyBuilder::dynamic()
908            ///     .try_build_with_colliders(&[child]).is_err());
909            /// assert!(ColliderBuilder::try_ball(f32::NAN).is_err());
910            /// # }
911            /// ```
912            pub fn try_build(self) -> Result<Collider, BodyValidationError> {
913                let collider = self.build();
914                collider.validate_authoring($planar)?;
915                Ok(collider)
916            }
917        }
918    };
919}
920
921#[cfg(feature = "dim2")]
922mod checked_d2 {
923    use super::*;
924    use crate::d2::{Angular, ColliderBuilder, RigidBody, RigidBodyBuilder, Rotation, Vector};
925
926    fn vector3(v: Vector) -> Vec3 {
927        Vec3::new(v.x, v.y, 0.)
928    }
929    fn angular3(v: Angular) -> Vec3 {
930        Vec3::new(0., 0., v)
931    }
932    fn rotation3(r: Rotation) -> Quat {
933        Quat::from_rotation_z(r.angle())
934    }
935
936    checked_builders!(true);
937
938    impl ColliderBuilder {
939        /// Checked rectangle constructor. Both half-extents must be finite and positive.
940        ///
941        /// ```
942        /// # #[cfg(feature = "dim2")] {
943        /// use ferravex_physics::d2::ColliderBuilder;
944        /// assert!(ColliderBuilder::try_cuboid(1., 0.5).unwrap().try_build().is_ok());
945        /// assert!(ColliderBuilder::try_cuboid(1., 0.).is_err());
946        /// # }
947        /// ```
948        pub fn try_cuboid(x: f32, y: f32) -> Result<Self, BodyValidationError> {
949            Shape::Box(Vec3::new(x, y, 0.5)).check_dimensions(true)?;
950            Ok(Self::cuboid(x, y))
951        }
952
953        /// Checked capsule constructor. Coincident finite endpoints are allowed;
954        /// the radius must be finite and positive.
955        ///
956        /// ```
957        /// # #[cfg(feature = "dim2")] {
958        /// use ferravex_math::Vec2;
959        /// use ferravex_physics::d2::ColliderBuilder;
960        /// let capsule = ColliderBuilder::try_capsule_from_endpoints(Vec2::ZERO, Vec2::Y, 0.2)
961        ///     .unwrap().try_build().unwrap();
962        /// assert_eq!(capsule.density(), 1.);
963        /// # }
964        /// ```
965        pub fn try_capsule_from_endpoints(
966            a: Vector,
967            b: Vector,
968            radius: f32,
969        ) -> Result<Self, BodyValidationError> {
970            Shape::Capsule {
971                a: vector3(a),
972                b: vector3(b),
973                radius,
974            }
975            .check_dimensions(true)?;
976            Ok(Self::capsule_from_endpoints(a, b, radius))
977        }
978    }
979}
980
981#[cfg(feature = "dim3")]
982mod checked_d3 {
983    use super::*;
984    use crate::d3::{Angular, ColliderBuilder, RigidBody, RigidBodyBuilder, Rotation, Vector};
985
986    fn vector3(v: Vector) -> Vec3 {
987        v
988    }
989    fn angular3(v: Angular) -> Vec3 {
990        v
991    }
992    fn rotation3(r: Rotation) -> Quat {
993        r
994    }
995
996    checked_builders!(false);
997
998    impl ColliderBuilder {
999        /// Checked box constructor. All three half-extents must be finite and positive.
1000        /// See `RigidBodyBuilder::try_build_with_colliders` for a complete example.
1001        pub fn try_cuboid(x: f32, y: f32, z: f32) -> Result<Self, BodyValidationError> {
1002            Shape::Box(Vec3::new(x, y, z)).check_dimensions(false)?;
1003            Ok(Self::cuboid(x, y, z))
1004        }
1005
1006        /// Checked cylinder constructor with finite positive half-height and radius.
1007        ///
1008        /// ```
1009        /// # #[cfg(feature = "dim3")] {
1010        /// use ferravex_physics::d3::{ColliderBuilder, RigidBodyBuilder};
1011        /// let cylinder = ColliderBuilder::try_cylinder(0.5, 0.25).unwrap().try_build().unwrap();
1012        /// assert!(RigidBodyBuilder::dynamic().try_build_with_colliders(&[cylinder]).is_ok());
1013        /// # }
1014        /// ```
1015        pub fn try_cylinder(half_height: f32, radius: f32) -> Result<Self, BodyValidationError> {
1016            Shape::Cylinder {
1017                half_height,
1018                radius,
1019            }
1020            .check_dimensions(false)?;
1021            Ok(Self::cylinder(half_height, radius))
1022        }
1023    }
1024}
1025
1026#[cfg(test)]
1027mod journey200_031 {
1028    use super::*;
1029    use BodyValidationError as E;
1030
1031    macro_rules! authoring_tests {
1032        ($dimension:ident, $vector:ty, $angular:expr) => {
1033            mod $dimension {
1034                use super::*;
1035                use crate::$dimension::{ColliderBuilder, PhysicsWorld, RigidBodyBuilder};
1036                type Vector = $vector;
1037
1038                #[test]
1039                fn checked_body_fields_reject_bad_inputs_and_preserve_valid_values() {
1040                    for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1041                        for axis in 0..Vector::ZERO.to_array().len() {
1042                            let mut components = Vector::ZERO.to_array();
1043                            components[axis] = invalid;
1044                            let v = Vector::from_array(components);
1045                            assert_eq!(RigidBodyBuilder::dynamic().try_translation(v).unwrap_err(), E::Translation);
1046                            assert_eq!(RigidBodyBuilder::dynamic().try_linvel(v).unwrap_err(), E::LinearVelocity);
1047                        }
1048                        assert_eq!(RigidBodyBuilder::dynamic().try_rotation($angular(invalid)).unwrap_err(), E::Rotation);
1049                        assert_eq!(RigidBodyBuilder::dynamic().try_angvel($angular(invalid)).unwrap_err(), E::AngularVelocity);
1050                        assert_eq!(RigidBodyBuilder::dynamic().try_gravity_scale(invalid).unwrap_err(), E::GravityScale);
1051                    }
1052                    for invalid in [-1., f32::NAN, f32::INFINITY] {
1053                        assert_eq!(RigidBodyBuilder::dynamic().try_linear_damping(invalid).unwrap_err(), E::LinearDamping);
1054                        assert_eq!(RigidBodyBuilder::dynamic().try_angular_damping(invalid).unwrap_err(), E::AngularDamping);
1055                    }
1056                    assert!(RigidBodyBuilder::dynamic().try_rotation($angular(f32::MAX)).unwrap().try_build().is_ok());
1057                    let body = RigidBodyBuilder::dynamic()
1058                        .try_translation(Vector::X * 2.).unwrap()
1059                        .try_rotation($angular(0.3)).unwrap()
1060                        .try_linvel(Vector::Y * 3.).unwrap()
1061                        .try_angvel($angular(0.4)).unwrap()
1062                        .try_linear_damping(0.1).unwrap()
1063                        .try_angular_damping(0.2).unwrap()
1064                        .try_gravity_scale(-1.).unwrap()
1065                        .ccd_enabled(true)
1066                        .try_build().unwrap();
1067                    assert_eq!(body.translation(), Vector::X * 2.);
1068                    assert_eq!(body.linvel(), Vector::Y * 3.);
1069                    assert_eq!(body.angvel(), $angular(0.4));
1070                    assert!(body.is_ccd_enabled());
1071                    assert_eq!(body.core().linear_damping, 0.1);
1072                    assert_eq!(body.core().angular_damping, 0.2);
1073                    assert_eq!(body.core().gravity_scale, -1.);
1074                    assert!(RigidBodyBuilder::fixed().try_rotation($angular(0.)).unwrap().try_build().is_ok());
1075                }
1076
1077                #[test]
1078                fn collider_checks_dimensions_density_and_local_pose() {
1079                    for invalid in [0., -0., -1., f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
1080                        assert_eq!(ColliderBuilder::try_ball(invalid).unwrap_err(), E::Radius);
1081                    }
1082                    for invalid in [-1., 1_000_001., f32::NAN, f32::INFINITY] {
1083                        assert_eq!(ColliderBuilder::ball(1.).try_density(invalid).unwrap_err(), E::Density);
1084                    }
1085                    for valid in [0., -0., 1e6] {
1086                        let collider = ColliderBuilder::ball(1.).try_density(valid).unwrap().try_build().unwrap();
1087                        assert_eq!(collider.density(), valid);
1088                    }
1089                    for invalid in [Vector::NAN, Vector::X * 1_000_001.] {
1090                        assert_eq!(ColliderBuilder::ball(1.).try_translation(invalid).unwrap_err(), E::ColliderTranslation);
1091                        // The legacy setter accepts the out-of-range finite offset.
1092                        if invalid.is_finite() {
1093                            assert_eq!(ColliderBuilder::ball(1.).translation(invalid).try_build().unwrap_err(), E::ColliderTranslation);
1094                        }
1095                    }
1096                    assert!(ColliderBuilder::ball(1.).try_translation(Vector::X * 1e6).unwrap().try_build().is_ok());
1097                }
1098
1099                #[test]
1100                fn definition_revalidates_fields_without_mutating_them() {
1101                    let base = RigidBodyBuilder::dynamic().build();
1102                    let colliders = [ColliderBuilder::ball(1.).build()];
1103                    let changes: [(fn(&mut Core), E); 8] = [
1104                        (|c| c.position.x = f32::NAN, E::Translation),
1105                        (|c| c.rotation = Quat::from_xyzw(0., 0., 0., 0.), E::Rotation),
1106                        (|c| c.velocity.y = f32::INFINITY, E::LinearVelocity),
1107                        (|c| c.angular_velocity.z = f32::NAN, E::AngularVelocity),
1108                        (|c| c.linear_damping = -1., E::LinearDamping),
1109                        (|c| c.angular_damping = -1., E::AngularDamping),
1110                        (|c| c.gravity_scale = f32::NAN, E::GravityScale),
1111                        (|c| { c.position.x = f32::NAN; c.velocity.y = f32::NAN; }, E::Translation),
1112                    ];
1113                    for (change, error) in changes {
1114                        let mut body = base.clone();
1115                        change(body.core_mut());
1116                        let before = format!("{body:?}");
1117                        assert_eq!(body.validate_definition(&colliders), Err(error));
1118                        assert_eq!(format!("{body:?}"), before);
1119                    }
1120                    let changes: [(fn(&mut Collider), E); 5] = [
1121                        (|c| c.shape = Shape::Ball(-1.), E::Radius),
1122                        (|c| c.local_translation = Vec3::NAN, E::ColliderTranslation),
1123                        (|c| c.local_rotation = Quat::from_xyzw(0., 0., 0., 0.), E::ColliderRotation),
1124                        (|c| c.density = f32::NAN, E::Density),
1125                        (|c| c.material.restitution = 2., E::Material),
1126                    ];
1127                    for (change, error) in changes {
1128                        let mut child = colliders[0].clone();
1129                        change(&mut child);
1130                        let before = format!("{child:?}");
1131                        assert_eq!(base.validate_definition(std::slice::from_ref(&child)), Err(error));
1132                        assert_eq!(format!("{child:?}"), before);
1133                    }
1134                }
1135
1136                #[test]
1137                fn complete_definition_checks_combined_mass_and_child_bound() {
1138                    let dynamic = RigidBodyBuilder::dynamic().build();
1139                    let fixed = RigidBodyBuilder::fixed().build();
1140                    let kinematic = RigidBodyBuilder::kinematic_position_based().build();
1141                    assert_eq!(dynamic.validate_definition(&[]), Err(E::Mass));
1142                    assert_eq!(fixed.validate_definition(&[]), Ok(()));
1143                    assert_eq!(kinematic.validate_definition(&[]), Ok(()));
1144                    let massless = ColliderBuilder::ball(1.).density(0.).try_build().unwrap();
1145                    assert_eq!(dynamic.validate_definition(std::slice::from_ref(&massless)), Err(E::Mass));
1146                    assert_eq!(fixed.validate_definition(std::slice::from_ref(&massless)), Ok(()));
1147                    let children = [massless, ColliderBuilder::ball(1.).build()];
1148                    assert_eq!(dynamic.validate_definition(&children), Ok(()));
1149                    assert_eq!(children[0].density(), 0.);
1150                    assert_eq!(dynamic.mass(), 0.);
1151                    for radius in [1e-30, 1e30] {
1152                        let extreme = ColliderBuilder::try_ball(radius).unwrap().try_build().unwrap();
1153                        assert_eq!(dynamic.validate_definition(std::slice::from_ref(&extreme)), Err(E::Mass));
1154                        assert_eq!(fixed.validate_definition(&[extreme]), Ok(()));
1155                    }
1156                    let mut children = vec![ColliderBuilder::ball(1.).build(); crate::MAX_CHILDREN];
1157                    assert_eq!(dynamic.validate_definition(&children), Ok(()));
1158                    children.push(ColliderBuilder::ball(1.).build());
1159                    assert_eq!(dynamic.validate_definition(&children), Err(E::ChildCapacity));
1160                    assert_eq!(fixed.validate_definition(&children), Err(E::ChildCapacity));
1161                }
1162
1163                #[test]
1164                fn checked_builds_insert_and_step_like_existing_builders() {
1165                    let children = [ColliderBuilder::try_ball(0.5).unwrap()
1166                        .try_density(2.).unwrap().try_build().unwrap()];
1167                    let body = RigidBodyBuilder::dynamic()
1168                        .try_translation(Vector::Y).unwrap()
1169                        .try_linvel(Vector::X * 3.).unwrap()
1170                        .try_angvel($angular(0.2)).unwrap()
1171                        .try_build_with_colliders(&children).unwrap();
1172                    let mut checked = PhysicsWorld::new(Vector::ZERO.to_array());
1173                    let a = checked.insert_compound(body, children).unwrap();
1174                    let mut legacy = PhysicsWorld::new(Vector::ZERO.to_array());
1175                    let b = legacy.insert(
1176                        RigidBodyBuilder::dynamic().translation(Vector::Y)
1177                            .linvel(Vector::X * 3.).angvel($angular(0.2)),
1178                        ColliderBuilder::ball(0.5).density(2.),
1179                    ).0;
1180                    assert_eq!(checked.bodies[a].mass(), legacy.bodies[b].mass());
1181                    checked.step(1. / 60.);
1182                    legacy.step(1. / 60.);
1183                    assert_eq!(checked.bodies[a].translation(), legacy.bodies[b].translation());
1184                    assert_eq!(checked.bodies[a].rotation(), legacy.bodies[b].rotation());
1185                    assert_eq!(checked.bodies[a].linvel(), legacy.bodies[b].linvel());
1186                    assert_eq!(checked.bodies[a].angvel(), legacy.bodies[b].angvel());
1187                }
1188
1189                #[test]
1190                fn legacy_constructors_keep_their_panics() {
1191                    assert!(std::panic::catch_unwind(|| ColliderBuilder::ball(0.)).is_err());
1192                    assert!(std::panic::catch_unwind(|| RigidBodyBuilder::dynamic().linvel(Vector::NAN)).is_err());
1193                }
1194            }
1195        };
1196    }
1197
1198    #[cfg(feature = "dim2")]
1199    authoring_tests!(d2, ferravex_math::Vec2, |v: f32| v);
1200    #[cfg(feature = "dim3")]
1201    authoring_tests!(d3, Vec3, |v: f32| Vec3::new(0., 0., v));
1202
1203    #[cfg(feature = "dim2")]
1204    #[test]
1205    fn planar_dimensions_endpoints_and_rotations() {
1206        use crate::d2::{ColliderBuilder, RigidBodyBuilder};
1207        use ferravex_math::Vec2;
1208        for invalid in [0., -1., f32::NAN, f32::INFINITY] {
1209            assert_eq!(
1210                ColliderBuilder::try_cuboid(invalid, 1.).unwrap_err(),
1211                E::HalfExtents
1212            );
1213            assert_eq!(
1214                ColliderBuilder::try_cuboid(1., invalid).unwrap_err(),
1215                E::HalfExtents
1216            );
1217        }
1218        assert_eq!(
1219            ColliderBuilder::try_capsule_from_endpoints(Vec2::NAN, Vec2::ZERO, 1.).unwrap_err(),
1220            E::CapsuleStart
1221        );
1222        assert_eq!(
1223            ColliderBuilder::try_capsule_from_endpoints(Vec2::ZERO, Vec2::NAN, 1.).unwrap_err(),
1224            E::CapsuleEnd
1225        );
1226        assert_eq!(
1227            ColliderBuilder::try_capsule_from_endpoints(Vec2::ZERO, Vec2::ZERO, 0.).unwrap_err(),
1228            E::Radius
1229        );
1230        let body = RigidBodyBuilder::dynamic().build();
1231        let point_capsule = ColliderBuilder::try_capsule_from_endpoints(Vec2::ZERO, Vec2::ZERO, 1.)
1232            .unwrap()
1233            .try_rotation(Rotation2::from_angle(0.3))
1234            .unwrap()
1235            .try_build()
1236            .unwrap();
1237        assert_eq!(body.validate_definition(&[point_capsule]), Ok(()));
1238        let mut child = ColliderBuilder::ball(1.).build();
1239        child.local_rotation = Quat::from_rotation_x(0.5);
1240        assert_eq!(
1241            body.validate_definition(std::slice::from_ref(&child)),
1242            Err(E::ColliderRotation)
1243        );
1244        child.local_rotation = Quat::IDENTITY;
1245        child.local_translation.z = 1.;
1246        assert_eq!(
1247            body.validate_definition(&[child]),
1248            Err(E::ColliderTranslation)
1249        );
1250    }
1251
1252    #[cfg(feature = "dim3")]
1253    #[test]
1254    fn spatial_dimensions_and_zero_quaternion_are_checked() {
1255        use crate::d3::{ColliderBuilder, RigidBodyBuilder};
1256        assert_eq!(
1257            RigidBodyBuilder::dynamic()
1258                .try_rotation(Vec3::splat(f32::MAX))
1259                .unwrap_err(),
1260            E::Rotation
1261        );
1262        for invalid in [0., -1., f32::NAN, f32::INFINITY] {
1263            assert_eq!(
1264                ColliderBuilder::try_cuboid(invalid, 1., 1.).unwrap_err(),
1265                E::HalfExtents
1266            );
1267            assert_eq!(
1268                ColliderBuilder::try_cuboid(1., invalid, 1.).unwrap_err(),
1269                E::HalfExtents
1270            );
1271            assert_eq!(
1272                ColliderBuilder::try_cuboid(1., 1., invalid).unwrap_err(),
1273                E::HalfExtents
1274            );
1275            assert_eq!(
1276                ColliderBuilder::try_cylinder(invalid, 1.).unwrap_err(),
1277                E::HalfHeight
1278            );
1279            assert_eq!(
1280                ColliderBuilder::try_cylinder(1., invalid).unwrap_err(),
1281                E::Radius
1282            );
1283        }
1284        for invalid in [
1285            Quat::from_xyzw(0., 0., 0., 0.),
1286            Quat::NAN,
1287            Quat::from_xyzw(0., 0., 0., 1e-7),
1288        ] {
1289            assert_eq!(
1290                ColliderBuilder::ball(1.).try_rotation(invalid).unwrap_err(),
1291                E::ColliderRotation
1292            );
1293        }
1294        let child = ColliderBuilder::try_cylinder(0.5, 1.)
1295            .unwrap()
1296            .try_rotation(Quat::from_xyzw(0., 0., 0., 2.))
1297            .unwrap()
1298            .try_build()
1299            .unwrap();
1300        assert_eq!(child.local_rotation(), Quat::IDENTITY);
1301        assert_eq!(
1302            RigidBodyBuilder::dynamic()
1303                .build()
1304                .validate_definition(&[child]),
1305            Ok(())
1306        );
1307    }
1308
1309    #[cfg(all(feature = "dim2", feature = "dim3"))]
1310    #[test]
1311    fn spatial_cylinder_is_rejected_in_planar_definition() {
1312        let child = crate::d3::ColliderBuilder::cylinder(1., 1.).build();
1313        assert_eq!(
1314            crate::d2::RigidBodyBuilder::fixed()
1315                .build()
1316                .validate_definition(&[child]),
1317            Err(E::ShapeDimension)
1318        );
1319    }
1320
1321    #[test]
1322    fn errors_are_field_specific_and_implement_std_error() {
1323        fn message(error: &dyn std::error::Error) -> String {
1324            error.to_string()
1325        }
1326        assert_eq!(
1327            message(&E::Density),
1328            "density must be finite and in 0..=1e6"
1329        );
1330        assert_ne!(message(&E::Mass), message(&E::Density));
1331        assert_ne!(message(&E::Translation), message(&E::ColliderTranslation));
1332    }
1333}
1334
1335#[cfg(test)]
1336mod journey400_221 {
1337    use super::*;
1338
1339    fn prepared(kind: Kind, planar: bool) -> Core {
1340        let mut core = Core::new(kind, planar);
1341        core.velocity = Vec3::X;
1342        core.angular_velocity = Vec3::Z;
1343        core.force = Vec3::Y;
1344        core.torque = Vec3::Z * 2.;
1345        core.next_position = Some(Vec3::X * 5.);
1346        core.next_rotation = Some(Quat::from_rotation_z(0.5));
1347        core.sleeping = true;
1348        core.quiet = 0.8;
1349        core
1350    }
1351
1352    #[test]
1353    fn revision_capacity_failure_preserves_every_field_for_every_body_kind() {
1354        let options = TeleportOptions::new(VelocityPolicy::Clear);
1355        for planar in [false, true] {
1356            for kind in [Kind::Fixed, Kind::Dynamic, Kind::Kinematic] {
1357                let mut core = prepared(kind, planar);
1358                core.revision = u64::MAX - 1;
1359                core.try_teleport(Vec3::Y, Quat::from_rotation_z(0.7), options)
1360                    .unwrap();
1361                assert_eq!(core.revision, u64::MAX);
1362                assert!(core.solver_dirty && core.wake_requested);
1363                assert!(!core.sleeping);
1364                assert_eq!(core.quiet, 0.);
1365                // Restage state that a failed reset must not consume.
1366                core.force = Vec3::X;
1367                core.torque = Vec3::Y;
1368                core.next_position = Some(Vec3::X * 3.);
1369                core.next_rotation = Some(Quat::IDENTITY);
1370                core.velocity = Vec3::Y;
1371                core.angular_velocity = Vec3::Z;
1372                let before = format!("{core:?}");
1373                assert_eq!(
1374                    core.try_teleport(Vec3::X, Quat::IDENTITY, options),
1375                    Err(TeleportError::RevisionExhausted),
1376                );
1377                assert_eq!(format!("{core:?}"), before);
1378                assert_eq!(
1379                    core.try_teleport(Vec3::X, Quat::NAN, options),
1380                    Err(TeleportError::Rotation),
1381                );
1382                assert_eq!(
1383                    core.try_teleport(Vec3::NAN, Quat::NAN, options),
1384                    Err(TeleportError::Translation),
1385                );
1386                assert_eq!(format!("{core:?}"), before);
1387            }
1388        }
1389    }
1390
1391    #[test]
1392    fn planar_invalid_rotation_leaves_sleep_forces_targets_and_pose_unchanged() {
1393        let mut core = prepared(Kind::Kinematic, true);
1394        let before = format!("{core:?}");
1395        for rotation in [
1396            Quat::NAN,
1397            Quat::from_array([0.; 4]),
1398            Quat::from_rotation_x(0.5),
1399            Quat::from_rotation_y(0.5),
1400        ] {
1401            assert_eq!(
1402                core.try_teleport(
1403                    Vec3::X,
1404                    rotation,
1405                    TeleportOptions::new(VelocityPolicy::Clear)
1406                ),
1407                Err(TeleportError::Rotation),
1408            );
1409            assert_eq!(format!("{core:?}"), before);
1410        }
1411    }
1412
1413    #[test]
1414    fn reset_options_control_only_the_requested_motion_fields() {
1415        for velocity in [VelocityPolicy::Clear, VelocityPolicy::Preserve] {
1416            for clear_forces in [false, true] {
1417                for clear_kinematic_targets in [false, true] {
1418                    let mut core = prepared(Kind::Dynamic, false);
1419                    let before = core.clone();
1420                    core.try_teleport(
1421                        Vec3::X * 2.,
1422                        Quat::IDENTITY,
1423                        TeleportOptions {
1424                            velocity,
1425                            clear_forces,
1426                            clear_kinematic_targets,
1427                        },
1428                    )
1429                    .unwrap();
1430                    assert_eq!(
1431                        core.force,
1432                        if clear_forces {
1433                            Vec3::ZERO
1434                        } else {
1435                            before.force
1436                        }
1437                    );
1438                    assert_eq!(
1439                        core.torque,
1440                        if clear_forces {
1441                            Vec3::ZERO
1442                        } else {
1443                            before.torque
1444                        }
1445                    );
1446                    assert_eq!(
1447                        core.next_position,
1448                        if clear_kinematic_targets {
1449                            None
1450                        } else {
1451                            before.next_position
1452                        }
1453                    );
1454                    assert_eq!(
1455                        core.next_rotation,
1456                        if clear_kinematic_targets {
1457                            None
1458                        } else {
1459                            before.next_rotation
1460                        }
1461                    );
1462                    assert_eq!(
1463                        core.velocity,
1464                        if velocity == VelocityPolicy::Clear {
1465                            Vec3::ZERO
1466                        } else {
1467                            before.velocity
1468                        }
1469                    );
1470                    assert_eq!(
1471                        core.angular_velocity,
1472                        if velocity == VelocityPolicy::Clear {
1473                            Vec3::ZERO
1474                        } else {
1475                            before.angular_velocity
1476                        }
1477                    );
1478                    assert_eq!(core.revision, before.revision + 1);
1479                }
1480            }
1481        }
1482    }
1483}