ferravex_physics/
joints.rs

1//! Bounded, generational connections between two bodies. Anchors are relative to
2//! authored body origins, so compound center-of-mass edits do not move a pivot.
3use crate::PhysicsError;
4use crate::body::{RigidBodyHandle, Slot};
5use ferravex_math::{Quat, Vec3};
6use std::fmt;
7use std::ops::{Index, IndexMut};
8pub const MAX_JOINTS: usize = 4096;
9
10/// The first invalid field in a joint description or live configuration.
11///
12/// Field names follow [`JointDesc`], with paths such as `limits.lower` and
13/// `motor.max_speed`. Validation never clamps or normalizes authored values.
14#[derive(Clone, Copy, Debug, PartialEq)]
15#[non_exhaustive]
16pub enum JointValidationError {
17    /// The named scalar, vector or quaternion contains NaN or infinity.
18    NonFinite { field: &'static str },
19    /// A finite scalar or vector component is outside the inclusive bounds.
20    OutOfRange {
21        field: &'static str,
22        min: f32,
23        max: f32,
24    },
25    /// Spring stiffness must be strictly greater than zero.
26    MustBePositive { field: &'static str },
27    /// A rotation or hinge axis must have squared length within 0.001 of one.
28    NotUnit { field: &'static str },
29    /// A planar anchor must have zero Z; rotations and axes must preserve +Z.
30    NotPlanar { field: &'static str },
31    /// Only hinge joints accept angular limits and motors.
32    HingeRequired { field: &'static str },
33    /// The lower angular limit exceeds the upper angular limit.
34    InvertedLimits,
35}
36
37impl JointValidationError {
38    /// Returns the field to highlight in an editor or diagnostic.
39    ///
40    /// ```
41    /// use ferravex_physics::JointMotor;
42    /// let error = JointMotor::velocity(1., -1.).validate().unwrap_err();
43    /// assert_eq!(error.field(), "motor.max_torque");
44    /// assert!(error.to_string().contains("between 0 and 1000000000"));
45    /// ```
46    pub fn field(&self) -> &'static str {
47        match *self {
48            Self::NonFinite { field }
49            | Self::OutOfRange { field, .. }
50            | Self::MustBePositive { field }
51            | Self::NotUnit { field }
52            | Self::NotPlanar { field }
53            | Self::HingeRequired { field } => field,
54            Self::InvertedLimits => "limits",
55        }
56    }
57}
58
59impl fmt::Display for JointValidationError {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        write!(f, "joint {}: ", self.field())?;
62        match *self {
63            Self::NonFinite { .. } => write!(f, "must contain only finite values"),
64            Self::OutOfRange { min, max, .. } => {
65                write!(f, "must be between {min} and {max}, inclusive")
66            }
67            Self::MustBePositive { .. } => write!(f, "must be greater than zero"),
68            Self::NotUnit { .. } => {
69                write!(f, "squared length must differ from 1 by less than 0.001")
70            }
71            Self::NotPlanar { .. } => {
72                write!(
73                    f,
74                    "planar anchors require Z = 0; axes and rotations must preserve +Z"
75                )
76            }
77            Self::HingeRequired { .. } => write!(f, "requires a hinge joint"),
78            Self::InvertedLimits => write!(f, "lower limit must not exceed upper limit"),
79        }
80    }
81}
82
83impl std::error::Error for JointValidationError {}
84
85fn validate_range(
86    value: f32,
87    field: &'static str,
88    min: f32,
89    max: f32,
90) -> Result<(), JointValidationError> {
91    if !value.is_finite() {
92        Err(JointValidationError::NonFinite { field })
93    } else if !(min..=max).contains(&value) {
94        Err(JointValidationError::OutOfRange { field, min, max })
95    } else {
96        Ok(())
97    }
98}
99
100#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
101pub struct JointHandle {
102    pub(crate) index: usize,
103    pub(crate) generation: u32,
104}
105#[derive(Clone, Copy, Debug, PartialEq)]
106pub enum JointKind {
107    Fixed,
108    Hinge {
109        axis1: Vec3,
110        axis2: Vec3,
111    },
112    Distance {
113        length: f32,
114    },
115    /// Force = -stiffness * extension - damping * relative speed, solved implicitly.
116    Spring {
117        length: f32,
118        stiffness: f32,
119        damping: f32,
120    },
121}
122#[derive(Clone, Copy, Debug, PartialEq)]
123pub struct JointMotor {
124    pub target_velocity: f32,
125    pub target_position: Option<f32>,
126    pub stiffness: f32,
127    pub max_speed: f32,
128    pub max_torque: f32,
129}
130impl JointMotor {
131    pub fn velocity(speed: f32, max_torque: f32) -> Self {
132        Self {
133            target_velocity: speed,
134            target_position: None,
135            stiffness: 0.,
136            max_speed: speed.abs(),
137            max_torque,
138        }
139    }
140    pub fn position(angle: f32, stiffness: f32, max_speed: f32, max_torque: f32) -> Self {
141        Self {
142            target_velocity: 0.,
143            target_position: Some(angle),
144            stiffness,
145            max_speed,
146            max_torque,
147        }
148    }
149    /// Checks the existing motor bounds without changing any value.
150    ///
151    /// Velocity is in [-1000, 1000] rad/s, position in [-pi, pi] radians,
152    /// stiffness and maximum torque in [0, 1e9], and maximum speed in
153    /// [0, 1000] rad/s. Zero torque or speed is allowed. The solver clamps a
154    /// position target to the joint's limits; a target outside those limits is
155    /// therefore valid if it remains within [-pi, pi].
156    ///
157    /// ```
158    /// use ferravex_physics::JointMotor;
159    /// JointMotor::position(0.5, 20., 8., 80.).validate().unwrap();
160    /// let error = JointMotor::velocity(f32::NAN, 1.).validate().unwrap_err();
161    /// assert_eq!(error.field(), "motor.target_velocity");
162    /// ```
163    pub fn validate(self) -> Result<(), JointValidationError> {
164        validate_range(self.target_velocity, "motor.target_velocity", -1000., 1000.)?;
165        if let Some(position) = self.target_position {
166            validate_range(
167                position,
168                "motor.target_position",
169                -std::f32::consts::PI,
170                std::f32::consts::PI,
171            )?;
172        }
173        validate_range(self.stiffness, "motor.stiffness", 0., 1e9)?;
174        validate_range(self.max_speed, "motor.max_speed", 0., 1000.)?;
175        validate_range(self.max_torque, "motor.max_torque", 0., 1e9)
176    }
177}
178/// Conservative sums of absolute constraint row forces/torques, avoiding
179/// cancellation between opposing rows. Units are newtons and newton-meters.
180#[derive(Clone, Copy, Debug, Default, PartialEq)]
181pub struct JointLoad {
182    pub force: f32,
183    pub torque: f32,
184}
185#[derive(Clone, Copy, Debug, PartialEq)]
186pub struct BreakLimits {
187    pub force: f32,
188    pub torque: f32,
189}
190#[derive(Clone, Copy, Debug, PartialEq)]
191pub struct JointBreakEvent {
192    pub joint: JointHandle,
193    pub bodies: [RigidBodyHandle; 2],
194    pub load: JointLoad,
195}
196#[derive(Clone, Copy, Debug, PartialEq)]
197pub struct JointDesc {
198    pub kind: JointKind,
199    pub local_anchor1: Vec3,
200    pub local_anchor2: Vec3,
201    /// None captures the bodies' relative orientation at insertion.
202    pub reference_rotation: Option<Quat>,
203    pub contacts_enabled: bool,
204    pub enabled: bool,
205    /// Twist range relative to the captured orientation, in radians [-pi, pi].
206    pub limits: Option<[f32; 2]>,
207    pub motor: Option<JointMotor>,
208    pub break_limits: Option<BreakLimits>,
209}
210impl JointDesc {
211    pub fn new(kind: JointKind) -> Self {
212        Self {
213            kind,
214            local_anchor1: Vec3::ZERO,
215            local_anchor2: Vec3::ZERO,
216            reference_rotation: None,
217            contacts_enabled: false,
218            enabled: true,
219            limits: None,
220            motor: None,
221            break_limits: None,
222        }
223    }
224    pub(crate) fn valid(self, planar: bool) -> bool {
225        self.validate(planar).is_ok()
226    }
227
228    /// Checks authored fields, returning the first invalid field and its cause.
229    ///
230    /// Pass `true` for a 2D world and `false` for a 3D world. This uses the same
231    /// bounds as insertion, but does not check body handles, body types or world
232    /// capacity. Insertion still performs those checks. No values are changed.
233    ///
234    /// ```
235    /// use ferravex_math::Vec3;
236    /// use ferravex_physics::{JointDesc, JointKind};
237    /// let mut desc = JointDesc::new(JointKind::Hinge {
238    ///     axis1: Vec3::Z,
239    ///     axis2: Vec3::Z,
240    /// });
241    /// desc.limits = Some([-0.5, 0.5]);
242    /// desc.validate(true).unwrap();
243    /// desc.limits = Some([0.5, -0.5]);
244    /// assert_eq!(desc.validate(true).unwrap_err().field(), "limits");
245    /// ```
246    pub fn validate(self, planar: bool) -> Result<(), JointValidationError> {
247        use JointValidationError as Error;
248        for (p, field) in [
249            (self.local_anchor1, "local_anchor1"),
250            (self.local_anchor2, "local_anchor2"),
251        ] {
252            if !p.is_finite() {
253                return Err(Error::NonFinite { field });
254            }
255            if p.abs().max_element() > 1e6 {
256                return Err(Error::OutOfRange {
257                    field,
258                    min: -1e6,
259                    max: 1e6,
260                });
261            }
262            if planar && p.z != 0. {
263                return Err(Error::NotPlanar { field });
264            }
265        }
266        if let Some(q) = self.reference_rotation {
267            let field = "reference_rotation";
268            if !q.is_finite() {
269                return Err(Error::NonFinite { field });
270            }
271            if (q.length_squared() - 1.).abs() >= 0.001 {
272                return Err(Error::NotUnit { field });
273            }
274            if planar && (q * Vec3::Z - Vec3::Z).length_squared() >= 1e-6 {
275                return Err(Error::NotPlanar { field });
276            }
277        }
278        match self.kind {
279            JointKind::Fixed => {}
280            JointKind::Distance { length } => validate_range(length, "kind.length", 0., 1e6)?,
281            JointKind::Spring {
282                length,
283                stiffness,
284                damping,
285            } => {
286                validate_range(length, "kind.length", 0., 1e6)?;
287                validate_range(stiffness, "kind.stiffness", 0., 1e6)?;
288                if stiffness == 0. {
289                    return Err(Error::MustBePositive {
290                        field: "kind.stiffness",
291                    });
292                }
293                validate_range(damping, "kind.damping", 0., 1e6)?;
294            }
295            JointKind::Hinge { axis1, axis2 } => {
296                for (a, field) in [(axis1, "kind.axis1"), (axis2, "kind.axis2")] {
297                    if !a.is_finite() {
298                        return Err(Error::NonFinite { field });
299                    }
300                    if (a.length_squared() - 1.).abs() >= 0.001 {
301                        return Err(Error::NotUnit { field });
302                    }
303                    if planar && a.distance_squared(Vec3::Z) >= 1e-6 {
304                        return Err(Error::NotPlanar { field });
305                    }
306                }
307            }
308        }
309        let hinge = matches!(self.kind, JointKind::Hinge { .. });
310        if let Some([lower, upper]) = self.limits {
311            if !hinge {
312                return Err(Error::HingeRequired { field: "limits" });
313            }
314            let pi = std::f32::consts::PI;
315            validate_range(lower, "limits.lower", -pi, pi)?;
316            validate_range(upper, "limits.upper", -pi, pi)?;
317            if lower > upper {
318                return Err(Error::InvertedLimits);
319            }
320        }
321        if let Some(limits) = self.break_limits {
322            validate_range(limits.force, "break_limits.force", 0., 1e12)?;
323            validate_range(limits.torque, "break_limits.torque", 0., 1e12)?;
324        }
325        if let Some(motor) = self.motor {
326            if !hinge {
327                return Err(Error::HingeRequired { field: "motor" });
328            }
329            motor.validate()?;
330        }
331        Ok(())
332    }
333}
334#[derive(Clone, Copy, Debug, Default)]
335pub(crate) struct CachedRow {
336    pub impulse: f32,
337    pub axis: Vec3,
338}
339#[derive(Clone, Debug)]
340pub struct Joint {
341    pub(crate) a: RigidBodyHandle,
342    pub(crate) b: RigidBodyHandle,
343    pub(crate) desc: JointDesc,
344    pub(crate) dirty: bool,
345    pub(crate) revisions: [u64; 2],
346    pub(crate) dt: f32,
347    pub(crate) cache: [CachedRow; 8],
348    pub(crate) load: JointLoad,
349    pub(crate) peak: JointLoad,
350}
351impl Joint {
352    pub fn peak_load(&self) -> JointLoad {
353        self.peak
354    }
355    pub fn bodies(&self) -> [RigidBodyHandle; 2] {
356        [self.a, self.b]
357    }
358    pub fn description(&self) -> JointDesc {
359        self.desc
360    }
361    /// Replaces the motor transactionally, preserving the existing error type.
362    /// Use [`Self::set_limits_and_motor`] for field-specific errors.
363    pub fn set_motor(&mut self, motor: Option<JointMotor>) -> Result<(), PhysicsError> {
364        self.set_limits_and_motor(self.desc.limits, motor)
365            .map_err(|_| PhysicsError::InvalidJoint)
366    }
367    /// Replaces angular limits transactionally, preserving the existing error type.
368    /// Use [`Self::set_limits_and_motor`] for field-specific errors.
369    pub fn set_limits(&mut self, limits: Option<[f32; 2]>) -> Result<(), PhysicsError> {
370        self.set_limits_and_motor(limits, self.desc.motor)
371            .map_err(|_| PhysicsError::InvalidJoint)
372    }
373
374    /// Replaces angular limits and the motor together, or changes nothing.
375    ///
376    /// `None` removes the corresponding setting. Nonempty settings require a
377    /// hinge; finite limits must satisfy `-pi <= lower <= upper <= pi`. Equal
378    /// endpoints are allowed. Motor bounds are checked by [`JointMotor::validate`].
379    /// Position targets outside the limits retain the solver's target clamping.
380    ///
381    /// A rejected edit leaves the description and solver state intact. An
382    /// identical edit does not wake the bodies or invalidate cached impulses.
383    /// An accepted change uses the existing dirty flag so the next physics step
384    /// clears cached impulses and wakes connected bodies. Handles, anchors and
385    /// the captured reference rotation are preserved.
386    ///
387    /// ```
388    /// # #[cfg(feature = "dim2")] {
389    /// use ferravex_physics::{d2, JointMotor};
390    /// let mut world = d2::PhysicsWorld::default();
391    /// let anchor = world.insert_body(d2::RigidBodyBuilder::fixed()).unwrap();
392    /// let rotor = world.add_box([0.; 2], [0.5, 0.2], true);
393    /// let handle = world.insert_joint(anchor, rotor, d2::JointBuilder::hinge()).unwrap();
394    /// let joint = world.joints.get_mut(handle).unwrap();
395    /// joint.set_limits_and_motor(
396    ///     Some([-0.6, 0.8]), Some(JointMotor::position(0.5, 20., 8., 80.)),
397    /// ).unwrap();
398    /// let before = joint.description();
399    /// assert!(joint.set_limits_and_motor(Some([1., -1.]), None).is_err());
400    /// assert_eq!(joint.description(), before);
401    /// world.step(1. / 120.);
402    /// # }
403    /// ```
404    pub fn set_limits_and_motor(
405        &mut self,
406        limits: Option<[f32; 2]>,
407        motor: Option<JointMotor>,
408    ) -> Result<(), JointValidationError> {
409        let desc = JointDesc {
410            limits,
411            motor,
412            ..self.desc
413        };
414        // Dimension-specific validation was performed on insertion; these fields
415        // are dimension-independent. Validate the entire candidate before mutation.
416        desc.validate(false)?;
417        if self.desc != desc {
418            self.desc = desc;
419            self.dirty = true;
420        }
421        Ok(())
422    }
423    pub fn set_enabled(&mut self, enabled: bool) {
424        if self.desc.enabled != enabled {
425            self.desc.enabled = enabled;
426            self.dirty = true;
427        }
428    }
429    pub fn set_contacts_enabled(&mut self, enabled: bool) {
430        if self.desc.contacts_enabled != enabled {
431            self.desc.contacts_enabled = enabled;
432            self.dirty = true;
433        }
434    }
435}
436#[derive(Clone, Debug)]
437pub struct JointSet {
438    slots: Vec<Slot<Joint>>,
439    len: usize,
440}
441crate::body::arena!(JointSet, Joint, JointHandle);
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use JointValidationError as Error;
447    use std::f32::consts::PI;
448
449    fn hinge() -> JointDesc {
450        JointDesc::new(JointKind::Hinge {
451            axis1: Vec3::Z,
452            axis2: Vec3::Z,
453        })
454    }
455
456    #[test]
457    fn limit_errors_identify_the_endpoint_and_preserve_inclusive_bounds() {
458        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
459            for (limits, field) in [([value, 0.], "limits.lower"), ([0., value], "limits.upper")] {
460                let desc = JointDesc {
461                    limits: Some(limits),
462                    ..hinge()
463                };
464                assert_eq!(desc.validate(false), Err(Error::NonFinite { field }));
465            }
466        }
467        for (limits, field) in [([-4., 0.], "limits.lower"), ([0., 4.], "limits.upper")] {
468            assert_eq!(
469                JointDesc {
470                    limits: Some(limits),
471                    ..hinge()
472                }
473                .validate(false),
474                Err(Error::OutOfRange {
475                    field,
476                    min: -PI,
477                    max: PI
478                }),
479            );
480        }
481        assert_eq!(
482            JointDesc {
483                limits: Some([1., -1.]),
484                ..hinge()
485            }
486            .validate(false),
487            Err(Error::InvertedLimits),
488        );
489        for limits in [[-PI, PI], [-PI, -PI], [PI, PI], [0., 0.]] {
490            for planar in [false, true] {
491                assert!(
492                    JointDesc {
493                        limits: Some(limits),
494                        ..hinge()
495                    }
496                    .validate(planar)
497                    .is_ok()
498                );
499            }
500        }
501    }
502
503    #[test]
504    fn motor_validation_reports_each_field_without_clamping() {
505        let base = JointMotor::position(0.5, 20., 8., 80.);
506        for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, f32::MAX] {
507            for (motor, field) in [
508                (
509                    JointMotor {
510                        target_velocity: value,
511                        ..base
512                    },
513                    "motor.target_velocity",
514                ),
515                (
516                    JointMotor {
517                        target_position: Some(value),
518                        ..base
519                    },
520                    "motor.target_position",
521                ),
522                (
523                    JointMotor {
524                        stiffness: value,
525                        ..base
526                    },
527                    "motor.stiffness",
528                ),
529                (
530                    JointMotor {
531                        max_speed: value,
532                        ..base
533                    },
534                    "motor.max_speed",
535                ),
536                (
537                    JointMotor {
538                        max_torque: value,
539                        ..base
540                    },
541                    "motor.max_torque",
542                ),
543            ] {
544                let error = motor.validate().unwrap_err();
545                assert_eq!(error.field(), field);
546                if !value.is_finite() {
547                    assert_eq!(error, Error::NonFinite { field });
548                } else {
549                    assert!(matches!(error, Error::OutOfRange { .. }));
550                }
551                assert!(error.to_string().contains(field));
552            }
553        }
554        for (motor, field, min, max) in [
555            (
556                JointMotor {
557                    target_velocity: -1001.,
558                    ..base
559                },
560                "motor.target_velocity",
561                -1000.,
562                1000.,
563            ),
564            (
565                JointMotor {
566                    target_position: Some(-4.),
567                    ..base
568                },
569                "motor.target_position",
570                -PI,
571                PI,
572            ),
573            (
574                JointMotor {
575                    stiffness: -1.,
576                    ..base
577                },
578                "motor.stiffness",
579                0.,
580                1e9,
581            ),
582            (
583                JointMotor {
584                    max_speed: -1.,
585                    ..base
586                },
587                "motor.max_speed",
588                0.,
589                1000.,
590            ),
591            (
592                JointMotor {
593                    max_torque: -1.,
594                    ..base
595                },
596                "motor.max_torque",
597                0.,
598                1e9,
599            ),
600        ] {
601            assert_eq!(motor.validate(), Err(Error::OutOfRange { field, min, max }));
602        }
603        for motor in [
604            JointMotor::velocity(0., 0.),
605            JointMotor::velocity(-1000., 1e9),
606            JointMotor::velocity(1000., 1e9),
607            JointMotor::position(-PI, 0., 0., 0.),
608            JointMotor::position(PI, 1e9, 1000., 1e9),
609        ] {
610            assert!(motor.validate().is_ok());
611        }
612    }
613
614    #[test]
615    fn descriptor_validation_explains_geometry_and_planar_restrictions() {
616        for (desc, error) in [
617            (
618                JointDesc {
619                    local_anchor1: Vec3::splat(f32::NAN),
620                    ..hinge()
621                },
622                Error::NonFinite {
623                    field: "local_anchor1",
624                },
625            ),
626            (
627                JointDesc {
628                    local_anchor2: Vec3::splat(f32::INFINITY),
629                    ..hinge()
630                },
631                Error::NonFinite {
632                    field: "local_anchor2",
633                },
634            ),
635            (
636                JointDesc {
637                    local_anchor2: Vec3::splat(1e7),
638                    ..hinge()
639                },
640                Error::OutOfRange {
641                    field: "local_anchor2",
642                    min: -1e6,
643                    max: 1e6,
644                },
645            ),
646            (
647                JointDesc {
648                    reference_rotation: Some(Quat::from_xyzw(0., 0., 0., f32::NAN)),
649                    ..hinge()
650                },
651                Error::NonFinite {
652                    field: "reference_rotation",
653                },
654            ),
655            (
656                JointDesc {
657                    reference_rotation: Some(Quat::from_xyzw(0., 0., 0., 2.)),
658                    ..hinge()
659                },
660                Error::NotUnit {
661                    field: "reference_rotation",
662                },
663            ),
664            (
665                JointDesc::new(JointKind::Hinge {
666                    axis1: Vec3::ZERO,
667                    axis2: Vec3::Z,
668                }),
669                Error::NotUnit {
670                    field: "kind.axis1",
671                },
672            ),
673            (
674                JointDesc::new(JointKind::Hinge {
675                    axis1: Vec3::Z,
676                    axis2: Vec3::splat(f32::MAX),
677                }),
678                Error::NotUnit {
679                    field: "kind.axis2",
680                },
681            ),
682            (
683                JointDesc::new(JointKind::Hinge {
684                    axis1: Vec3::Z,
685                    axis2: Vec3::splat(f32::INFINITY),
686                }),
687                Error::NonFinite {
688                    field: "kind.axis2",
689                },
690            ),
691        ] {
692            assert_eq!(desc.validate(false), Err(error));
693        }
694        for (desc, field) in [
695            (
696                JointDesc {
697                    local_anchor1: Vec3::Z,
698                    ..hinge()
699                },
700                "local_anchor1",
701            ),
702            (
703                JointDesc {
704                    reference_rotation: Some(Quat::from_rotation_x(0.5)),
705                    ..hinge()
706                },
707                "reference_rotation",
708            ),
709            (
710                JointDesc::new(JointKind::Hinge {
711                    axis1: Vec3::Y,
712                    axis2: Vec3::Y,
713                }),
714                "kind.axis1",
715            ),
716            (
717                JointDesc::new(JointKind::Hinge {
718                    axis1: Vec3::Z,
719                    axis2: -Vec3::Z,
720                }),
721                "kind.axis2",
722            ),
723        ] {
724            assert_eq!(desc.validate(false), Ok(()));
725            assert_eq!(desc.validate(true), Err(Error::NotPlanar { field }));
726        }
727    }
728
729    #[test]
730    fn descriptor_validation_preserves_kind_and_break_threshold_rules() {
731        for kind in [
732            JointKind::Fixed,
733            JointKind::Distance { length: 0. },
734            JointKind::Spring {
735                length: 0.,
736                stiffness: 1.,
737                damping: 0.,
738            },
739        ] {
740            let desc = JointDesc::new(kind);
741            assert!(desc.validate(false).is_ok());
742            assert_eq!(
743                JointDesc {
744                    limits: Some([0., 0.]),
745                    ..desc
746                }
747                .validate(false),
748                Err(Error::HingeRequired { field: "limits" })
749            );
750            assert_eq!(
751                JointDesc {
752                    motor: Some(JointMotor::velocity(0., 0.)),
753                    ..desc
754                }
755                .validate(false),
756                Err(Error::HingeRequired { field: "motor" })
757            );
758        }
759        for (kind, error) in [
760            (
761                JointKind::Distance { length: -1. },
762                Error::OutOfRange {
763                    field: "kind.length",
764                    min: 0.,
765                    max: 1e6,
766                },
767            ),
768            (
769                JointKind::Spring {
770                    length: 1.,
771                    stiffness: 0.,
772                    damping: 0.,
773                },
774                Error::MustBePositive {
775                    field: "kind.stiffness",
776                },
777            ),
778            (
779                JointKind::Spring {
780                    length: 1.,
781                    stiffness: 1.,
782                    damping: f32::NAN,
783                },
784                Error::NonFinite {
785                    field: "kind.damping",
786                },
787            ),
788        ] {
789            assert_eq!(JointDesc::new(kind).validate(false), Err(error));
790        }
791        for (limits, error) in [
792            (
793                BreakLimits {
794                    force: f32::INFINITY,
795                    torque: 0.,
796                },
797                Error::NonFinite {
798                    field: "break_limits.force",
799                },
800            ),
801            (
802                BreakLimits {
803                    force: 0.,
804                    torque: -1.,
805                },
806                Error::OutOfRange {
807                    field: "break_limits.torque",
808                    min: 0.,
809                    max: 1e12,
810                },
811            ),
812        ] {
813            assert_eq!(
814                JointDesc {
815                    break_limits: Some(limits),
816                    ..hinge()
817                }
818                .validate(false),
819                Err(error)
820            );
821        }
822        assert!(
823            JointDesc {
824                local_anchor1: Vec3::splat(-1e6),
825                local_anchor2: Vec3::splat(1e6),
826                break_limits: Some(BreakLimits {
827                    force: 0.,
828                    torque: 1e12
829                }),
830                ..JointDesc::new(JointKind::Spring {
831                    length: 1e6,
832                    stiffness: 1e6,
833                    damping: 1e6
834                })
835            }
836            .validate(false)
837            .is_ok()
838        );
839    }
840
841    // Check all persistent state, including impulses and pending invalidation,
842    // rather than just the public description after a failed transaction.
843    #[cfg(feature = "dim3")]
844    fn assert_same_state(actual: &Joint, before: &Joint) {
845        assert_eq!(actual.bodies(), before.bodies());
846        assert_eq!(actual.desc, before.desc);
847        assert_eq!(actual.dirty, before.dirty);
848        assert_eq!(actual.revisions, before.revisions);
849        assert_eq!(actual.dt, before.dt);
850        assert_eq!(actual.load, before.load);
851        assert_eq!(actual.peak, before.peak);
852        for (actual, before) in actual.cache.iter().zip(&before.cache) {
853            assert_eq!(actual.impulse, before.impulse);
854            assert_eq!(actual.axis, before.axis);
855        }
856    }
857
858    #[cfg(feature = "dim3")]
859    #[test]
860    fn live_edits_are_atomic_and_noops_preserve_solver_state() {
861        use crate::d3;
862        let mut world = d3::PhysicsWorld::default();
863        let a = world.insert_body(d3::RigidBodyBuilder::fixed()).unwrap();
864        let b = world.add_box([0.; 3], [0.5; 3], true);
865        let id = world
866            .insert_joint(
867                a,
868                b,
869                d3::JointBuilder::hinge().motor(JointMotor::velocity(2., 10.)),
870            )
871            .unwrap();
872        world.step(1. / 120.);
873        assert!(world.joints[id].cache.iter().any(|row| row.impulse != 0.));
874        let joint = &mut world.joints[id];
875        let before = joint.clone();
876        joint
877            .set_limits_and_motor(before.desc.limits, before.desc.motor)
878            .unwrap();
879        joint.set_limits(before.desc.limits).unwrap();
880        joint.set_motor(before.desc.motor).unwrap();
881        assert_same_state(joint, &before);
882        for limits in [[1., -1.], [f32::NAN, 1.], [-1., f32::INFINITY], [-4., 0.]] {
883            assert!(joint.set_limits_and_motor(Some(limits), None).is_err());
884            assert_same_state(joint, &before);
885            assert_eq!(
886                joint.set_limits(Some(limits)),
887                Err(PhysicsError::InvalidJoint)
888            );
889            assert_same_state(joint, &before);
890        }
891        let bad_motor = Some(JointMotor::velocity(f32::NAN, 1.));
892        assert!(
893            joint
894                .set_limits_and_motor(Some([-1., 1.]), bad_motor)
895                .is_err()
896        );
897        assert_same_state(joint, &before);
898        assert_eq!(joint.set_motor(bad_motor), Err(PhysicsError::InvalidJoint));
899        assert_same_state(joint, &before);
900
901        joint.set_limits_and_motor(Some([-0.5, 0.5]), None).unwrap();
902        assert!(joint.dirty);
903        let mut expected = before.clone();
904        expected.desc.limits = Some([-0.5, 0.5]);
905        expected.desc.motor = None;
906        expected.dirty = true;
907        assert_same_state(joint, &expected);
908        // A failure or no-op must not discard an earlier pending accepted edit.
909        assert!(joint.set_limits_and_motor(Some([1., -1.]), None).is_err());
910        joint.set_limits_and_motor(Some([-0.5, 0.5]), None).unwrap();
911        assert_same_state(joint, &expected);
912        // Existing refresh owns cache invalidation and endpoint wake-up.
913        world.step(1. / 120.);
914        assert!(!world.joints[id].dirty);
915        assert!(world.joints[id].dt > 0.);
916        assert!(world.joints[id].cache.iter().all(|row| row.impulse == 0.));
917        assert_eq!(world.joints[id].bodies(), [a, b]);
918
919        assert!(world.remove_joint(id));
920        let replacement = world.insert_joint(a, b, d3::JointBuilder::fixed()).unwrap();
921        assert_ne!(replacement, id);
922        assert!(world.joints.get_mut(id).is_none());
923        let fixed = &mut world.joints[replacement];
924        let before = fixed.clone();
925        assert_eq!(
926            fixed.set_limits_and_motor(Some([0., 0.]), None),
927            Err(Error::HingeRequired { field: "limits" })
928        );
929        assert_eq!(
930            fixed.set_limits_and_motor(None, Some(JointMotor::velocity(1., 1.))),
931            Err(Error::HingeRequired { field: "motor" })
932        );
933        fixed.set_limits_and_motor(None, None).unwrap();
934        assert_same_state(fixed, &before);
935    }
936
937    #[cfg(feature = "dim2")]
938    #[test]
939    fn accepted_configuration_wakes_a_sleeping_hinge_and_drives_clamped_target() {
940        use crate::d2;
941        const DT: f32 = 1. / 120.;
942        let mut world = d2::PhysicsWorld::default();
943        let a = world.insert_body(d2::RigidBodyBuilder::fixed()).unwrap();
944        let b = world.add_box([0.; 2], [0.5, 0.2], true);
945        let id = world.insert_joint(a, b, d2::JointBuilder::hinge()).unwrap();
946        for _ in 0..240 {
947            world.step(DT);
948        }
949        assert!(world.bodies[b].is_sleeping());
950        world.joints[id].set_limits_and_motor(None, None).unwrap();
951        assert!(
952            world.joints[id]
953                .set_limits_and_motor(Some([1., -1.]), None)
954                .is_err()
955        );
956        world.step(DT);
957        assert!(world.bodies[b].is_sleeping());
958
959        world.joints[id]
960            .set_limits_and_motor(
961                Some([-0.4, 0.4]),
962                Some(JointMotor::position(0.9, 20., 8., 80.)),
963            )
964            .unwrap();
965        assert!(world.bodies[b].is_sleeping());
966        world.step(DT);
967        assert!(!world.bodies[b].is_sleeping());
968        for _ in 0..240 {
969            world.step(DT);
970            assert!((-0.405..=0.405).contains(&world.joint_angle(id).unwrap()));
971        }
972        assert!((world.joint_angle(id).unwrap() - 0.4).abs() < 0.005);
973        assert_eq!(
974            world.joints[id].desc.motor.unwrap().target_position,
975            Some(0.9)
976        );
977
978        // Both values disappear together; the now-unpowered rotor passes its old limit.
979        world.joints[id].set_limits_and_motor(None, None).unwrap();
980        world.bodies[b].set_angvel(2., true);
981        for _ in 0..30 {
982            world.step(DT);
983        }
984        assert!(world.joint_angle(id).unwrap() > 0.7);
985        assert_eq!(world.joints[id].description().limits, None);
986        assert_eq!(world.joints[id].description().motor, None);
987    }
988}