Skip to main content

rapier2d/dynamics/joint/
generic_joint.rs

1#![allow(clippy::bad_bit_mask)] // Clippy will complain about the bitmasks due to JointAxesMask::FREE_FIXED_AXES being 0.
2#![allow(clippy::unnecessary_cast)] // Casts are needed for switching between f32/f64.
3
4#[cfg(feature = "alloc")]
5use crate::dynamics::RigidBody;
6use crate::dynamics::integration_parameters::SpringCoefficients;
7#[cfg(feature = "alloc")]
8use crate::dynamics::solver::MotorParameters;
9use crate::dynamics::{FixedJoint, MotorModel, PrismaticJoint, RevoluteJoint, RopeJoint};
10use crate::math::{Pose, Real, Rotation, SPATIAL_DIM, Vector};
11#[cfg(feature = "dim2")]
12use crate::utils::OrthonormalBasis;
13use crate::utils::SimdRealCopy;
14#[cfg(feature = "dim2")]
15use parry::math::Matrix;
16
17#[cfg(feature = "dim3")]
18use crate::dynamics::SphericalJoint;
19
20#[cfg(feature = "dim3")]
21bitflags::bitflags! {
22    /// A bit mask identifying multiple degrees of freedom of a joint.
23    #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
24    #[derive(Copy, Clone, PartialEq, Eq, Debug)]
25    pub struct JointAxesMask: u8 {
26        /// The linear (translational) degree of freedom along the local X axis of a joint.
27        const LIN_X = 1 << 0;
28        /// The linear (translational) degree of freedom along the local Y axis of a joint.
29        const LIN_Y = 1 << 1;
30        /// The linear (translational) degree of freedom along the local Z axis of a joint.
31        const LIN_Z = 1 << 2;
32        /// The angular degree of freedom along the local X axis of a joint.
33        const ANG_X = 1 << 3;
34        /// The angular degree of freedom along the local Y axis of a joint.
35        const ANG_Y = 1 << 4;
36        /// The angular degree of freedom along the local Z axis of a joint.
37        const ANG_Z = 1 << 5;
38        /// The set of degrees of freedom locked by a revolute joint.
39        const LOCKED_REVOLUTE_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits() | Self::LIN_Z.bits() | Self::ANG_Y.bits() | Self::ANG_Z.bits();
40        /// The set of degrees of freedom locked by a prismatic joint.
41        const LOCKED_PRISMATIC_AXES = Self::LIN_Y.bits() | Self::LIN_Z.bits() | Self::ANG_X.bits() | Self::ANG_Y.bits() | Self::ANG_Z.bits();
42        /// The set of degrees of freedom locked by a fixed joint.
43        const LOCKED_FIXED_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits() | Self::LIN_Z.bits() | Self::ANG_X.bits() | Self::ANG_Y.bits() | Self::ANG_Z.bits();
44        /// The set of degrees of freedom locked by a spherical joint.
45        const LOCKED_SPHERICAL_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits() | Self::LIN_Z.bits();
46        /// The set of degrees of freedom left free by a revolute joint.
47        const FREE_REVOLUTE_AXES = Self::ANG_X.bits();
48        /// The set of degrees of freedom left free by a prismatic joint.
49        const FREE_PRISMATIC_AXES = Self::LIN_X.bits();
50        /// The set of degrees of freedom left free by a fixed joint.
51        const FREE_FIXED_AXES = 0;
52        /// The set of degrees of freedom left free by a spherical joint.
53        const FREE_SPHERICAL_AXES = Self::ANG_X.bits() | Self::ANG_Y.bits() | Self::ANG_Z.bits();
54        /// The set of all translational degrees of freedom.
55        const LIN_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits() | Self::LIN_Z.bits();
56        /// The set of all angular degrees of freedom.
57        const ANG_AXES = Self::ANG_X.bits() | Self::ANG_Y.bits() | Self::ANG_Z.bits();
58    }
59}
60
61#[cfg(feature = "dim2")]
62bitflags::bitflags! {
63    /// A bit mask identifying multiple degrees of freedom of a joint.
64    #[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
65    #[derive(Copy, Clone, PartialEq, Eq, Debug)]
66    pub struct JointAxesMask: u8 {
67        /// The linear (translational) degree of freedom along the local X axis of a joint.
68        const LIN_X = 1 << 0;
69        /// The linear (translational) degree of freedom along the local Y axis of a joint.
70        const LIN_Y = 1 << 1;
71        /// The angular degree of freedom of a joint.
72        const ANG_X = 1 << 2;
73        /// The set of degrees of freedom locked by a revolute joint.
74        const LOCKED_REVOLUTE_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits();
75        /// The set of degrees of freedom locked by a prismatic joint.
76        const LOCKED_PRISMATIC_AXES = Self::LIN_Y.bits() | Self::ANG_X.bits();
77        /// The set of degrees of freedom locked by a pin slot joint.
78        const LOCKED_PIN_SLOT_AXES = Self::LIN_Y.bits();
79        /// The set of degrees of freedom locked by a fixed joint.
80        const LOCKED_FIXED_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits() | Self::ANG_X.bits();
81        /// The set of degrees of freedom left free by a revolute joint.
82        const FREE_REVOLUTE_AXES = Self::ANG_X.bits();
83        /// The set of degrees of freedom left free by a prismatic joint.
84        const FREE_PRISMATIC_AXES = Self::LIN_X.bits();
85        /// The set of degrees of freedom left free by a fixed joint.
86        const FREE_FIXED_AXES = 0;
87        /// The set of all translational degrees of freedom.
88        const LIN_AXES = Self::LIN_X.bits() | Self::LIN_Y.bits();
89        /// The set of all angular degrees of freedom.
90        const ANG_AXES = Self::ANG_X.bits();
91    }
92}
93
94impl Default for JointAxesMask {
95    fn default() -> Self {
96        Self::empty()
97    }
98}
99
100/// Identifiers of degrees of freedoms of a joint.
101#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
102#[derive(Copy, Clone, Debug, PartialEq)]
103pub enum JointAxis {
104    /// The linear (translational) degree of freedom along the joint’s local X axis.
105    LinX = 0,
106    /// The linear (translational) degree of freedom along the joint’s local Y axis.
107    LinY,
108    /// The linear (translational) degree of freedom along the joint’s local Z axis.
109    #[cfg(feature = "dim3")]
110    LinZ,
111    /// The rotational degree of freedom along the joint’s local X axis.
112    AngX,
113    /// The rotational degree of freedom along the joint’s local Y axis.
114    #[cfg(feature = "dim3")]
115    AngY,
116    /// The rotational degree of freedom along the joint’s local Z axis.
117    #[cfg(feature = "dim3")]
118    AngZ,
119}
120
121impl From<JointAxis> for JointAxesMask {
122    fn from(axis: JointAxis) -> Self {
123        JointAxesMask::from_bits(1 << axis as usize).unwrap()
124    }
125}
126
127/// Limits that restrict a joint's range of motion along one axis.
128///
129/// Use to constrain how far a joint can move/rotate. Examples:
130/// - Door that only opens 90°: revolute joint with limits `[0.0, PI/2.0]`
131/// - Piston with 2-unit stroke: prismatic joint with limits `[0.0, 2.0]`
132/// - Elbow that bends 0-150°: revolute joint with limits `[0.0, 5*PI/6]`
133///
134/// When a joint hits its limit, forces are applied to prevent further movement in that direction.
135///
136/// An angular range may sit anywhere on the circle (`[0, 3π/2]` and `[π, 3π/2]` both work), but
137/// it can't be wider than a full turn: the joint's angle is derived from the bodies' relative
138/// rotation, which doesn't count revolutions, so a wider range is indistinguishable from no
139/// limit at all and leaves the axis free.
140#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
141#[derive(Copy, Clone, Debug, PartialEq)]
142pub struct JointLimits<N> {
143    /// Minimum allowed value (angle for revolute, distance for prismatic).
144    pub min: N,
145    /// Maximum allowed value (angle for revolute, distance for prismatic).
146    pub max: N,
147    /// Internal: impulse being applied to enforce the limit.
148    pub impulse: N,
149}
150
151impl<N: SimdRealCopy> Default for JointLimits<N> {
152    fn default() -> Self {
153        Self {
154            min: -N::splat(Real::MAX),
155            max: N::splat(Real::MAX),
156            impulse: N::splat(0.0),
157        }
158    }
159}
160
161impl<N: SimdRealCopy> From<[N; 2]> for JointLimits<N> {
162    fn from(value: [N; 2]) -> Self {
163        Self {
164            min: value[0],
165            max: value[1],
166            impulse: N::splat(0.0),
167        }
168    }
169}
170
171/// A powered motor that drives a joint toward a target position/velocity.
172///
173/// Motors add actuation to joints - they apply forces to make the joint move toward
174/// a desired state. Think of them as servos, electric motors, or hydraulic actuators.
175///
176/// ## Two control modes
177///
178/// 1. **Velocity control**: Set `target_vel` to make the motor spin/slide at constant speed
179/// 2. **Position control**: Set `target_pos` with `stiffness`/`damping` to reach a target angle/position
180///
181/// You can combine both for precise control.
182///
183/// ## Parameters
184///
185/// - `stiffness`: How strongly to pull toward target (spring constant)
186/// - `damping`: Resistance to motion (prevents oscillation)
187/// - `max_force`: Maximum force/torque the motor can apply
188///
189/// # Example
190/// ```
191/// # use rapier3d::prelude::*;
192/// # use rapier3d::dynamics::{RevoluteJoint, PrismaticJoint};
193/// # let mut revolute_joint = RevoluteJoint::new(Vector::X);
194/// # let mut prismatic_joint = PrismaticJoint::new(Vector::X);
195/// // Motor that spins a wheel at 10 rad/s
196/// revolute_joint.set_motor_velocity(10.0, 0.8);
197///
198/// // Motor that moves to position 5.0
199/// prismatic_joint.set_motor_position(5.0, 100.0, 10.0);  // stiffness=100, damping=10
200/// ```
201#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
202#[derive(Copy, Clone, Debug, PartialEq)]
203pub struct JointMotor {
204    /// Target velocity (units/sec for prismatic, rad/sec for revolute).
205    pub target_vel: Real,
206    /// Target position (units for prismatic, radians for revolute).
207    pub target_pos: Real,
208    /// Spring constant - how strongly to pull toward target position.
209    pub stiffness: Real,
210    /// Damping coefficient - resistance to motion (prevents oscillation).
211    pub damping: Real,
212    /// Maximum force the motor can apply (Newtons for prismatic, Nm for revolute).
213    pub max_force: Real,
214    /// Internal: current impulse being applied.
215    pub impulse: Real,
216    /// Force-based or acceleration-based motor model.
217    pub model: MotorModel,
218}
219
220impl Default for JointMotor {
221    fn default() -> Self {
222        Self {
223            target_pos: 0.0,
224            target_vel: 0.0,
225            stiffness: 0.0,
226            damping: 0.0,
227            max_force: Real::MAX,
228            impulse: 0.0,
229            model: MotorModel::AccelerationBased,
230        }
231    }
232}
233
234#[cfg(feature = "alloc")]
235impl JointMotor {
236    pub(crate) fn motor_params(&self, dt: Real) -> MotorParameters<Real> {
237        let (erp_inv_dt, cfm_coeff, cfm_gain) =
238            self.model
239                .combine_coefficients(dt, self.stiffness, self.damping);
240        MotorParameters {
241            erp_inv_dt,
242            cfm_coeff,
243            cfm_gain,
244            // keep_lhs,
245            target_pos: self.target_pos,
246            target_vel: self.target_vel,
247            max_impulse: self.max_force * dt,
248        }
249    }
250}
251
252#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
253#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
254/// Enum indicating whether or not a joint is enabled.
255pub enum JointEnabled {
256    /// The joint is enabled.
257    Enabled,
258    /// The joint wasn’t disabled by the user explicitly but it is attached to
259    /// a disabled rigid-body.
260    DisabledByAttachedBody,
261    /// The joint is disabled by the user explicitly.
262    Disabled,
263}
264
265#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
266#[derive(Copy, Clone, Debug, PartialEq)]
267/// A generic joint.
268pub struct GenericJoint {
269    /// The joint’s frame, expressed in the first rigid-body’s local-space.
270    pub local_frame1: Pose,
271    /// The joint’s frame, expressed in the second rigid-body’s local-space.
272    pub local_frame2: Pose,
273    /// The degrees-of-freedoms locked by this joint.
274    pub locked_axes: JointAxesMask,
275    /// The degrees-of-freedoms limited by this joint.
276    pub limit_axes: JointAxesMask,
277    /// The degrees-of-freedoms motorised by this joint.
278    pub motor_axes: JointAxesMask,
279    /// The coupled degrees of freedom of this joint.
280    ///
281    /// Note that coupling degrees of freedoms (DoF) changes the interpretation of the coupled joint’s limits and motors.
282    /// If multiple linear DoF are limited/motorized, only the limits/motor configuration for the first
283    /// coupled linear DoF is applied to all coupled linear DoF. Similarly, if multiple angular DoF are limited/motorized
284    /// only the limits/motor configuration for the first coupled angular DoF is applied to all coupled angular DoF.
285    pub coupled_axes: JointAxesMask,
286    /// The limits, along each degree of freedoms of this joint.
287    ///
288    /// Note that the limit must also be explicitly enabled by the `limit_axes` bitmask.
289    /// For coupled degrees of freedoms (DoF), only the first linear (resp. angular) coupled DoF limit and `limit_axis`
290    /// bitmask is applied to the coupled linear (resp. angular) axes.
291    pub limits: [JointLimits<Real>; SPATIAL_DIM],
292    /// The motors, along each degree of freedoms of this joint.
293    ///
294    /// Note that the motor must also be explicitly enabled by the `motor_axes` bitmask.
295    /// For coupled degrees of freedoms (DoF), only the first linear (resp. angular) coupled DoF motor and `motor_axes`
296    /// bitmask is applied to the coupled linear (resp. angular) axes.
297    pub motors: [JointMotor; SPATIAL_DIM],
298    /// The coefficients controlling the joint constraints’ softness.
299    pub softness: SpringCoefficients<Real>,
300    /// Are contacts between the attached rigid-bodies enabled?
301    pub contacts_enabled: bool,
302    /// Whether the joint is enabled.
303    pub enabled: JointEnabled,
304    /// User-defined data associated to this joint.
305    pub user_data: u128,
306}
307
308impl Default for GenericJoint {
309    fn default() -> Self {
310        Self {
311            local_frame1: Pose::IDENTITY,
312            local_frame2: Pose::IDENTITY,
313            locked_axes: JointAxesMask::empty(),
314            limit_axes: JointAxesMask::empty(),
315            motor_axes: JointAxesMask::empty(),
316            coupled_axes: JointAxesMask::empty(),
317            limits: [JointLimits::default(); SPATIAL_DIM],
318            motors: [JointMotor::default(); SPATIAL_DIM],
319            softness: SpringCoefficients::joint_defaults(),
320            contacts_enabled: true,
321            enabled: JointEnabled::Enabled,
322            user_data: 0,
323        }
324    }
325}
326
327impl GenericJoint {
328    /// Creates a new generic joint that locks the specified degrees of freedom.
329    #[must_use]
330    pub fn new(locked_axes: JointAxesMask) -> Self {
331        *Self::default().lock_axes(locked_axes)
332    }
333
334    /// Can this joint use SIMD-accelerated constraint formulations?
335    ///
336    /// Locked axes and uncoupled limits have wide row formulations, as does the
337    /// 2D angular motor (the workhorse of ragdoll joints); linear motors, 3D
338    /// motors and coupled limit rows don't (yet) and fall back to the scalar
339    /// path.
340    #[cfg(feature = "alloc")]
341    pub(crate) fn supports_simd_constraints(&self) -> bool {
342        #[cfg(feature = "dim2")]
343        let motors_ok =
344            (self.motor_axes.bits() & !self.locked_axes.bits() & JointAxesMask::LIN_AXES.bits())
345                == 0;
346        #[cfg(feature = "dim3")]
347        let motors_ok = (self.motor_axes.bits() & !self.locked_axes.bits()) == 0;
348        motors_ok && (self.limit_axes & self.coupled_axes).is_empty()
349    }
350
351    /// The constraint-row layout signature of this joint: joints sharing it emit
352    /// the same row sequence (kinds, axes and count), so they can share the
353    /// lanes of one SIMD constraint group.
354    #[cfg(feature = "alloc")]
355    pub(crate) fn simd_row_signature(&self) -> u32 {
356        let locked = self.locked_axes.bits() as u32;
357        let limits = (self.limit_axes.bits() & !self.locked_axes.bits()) as u32;
358        #[cfg(feature = "dim2")]
359        {
360            // The angular motor row's coefficient formula depends on the motor
361            // model, so lanes must also share it.
362            let motors = (self.motor_axes.bits() & !self.locked_axes.bits()) as u32;
363            let model = (self.motors[crate::math::DIM].model
364                == crate::dynamics::MotorModel::ForceBased) as u32;
365            locked | (limits << 8) | (motors << 16) | (model << 24)
366        }
367        #[cfg(feature = "dim3")]
368        {
369            locked | (limits << 8)
370        }
371    }
372
373    #[doc(hidden)]
374    pub fn complete_ang_frame(axis: Vector) -> Rotation {
375        #[cfg(feature = "dim2")]
376        {
377            let basis = axis.orthonormal_basis();
378            let mat = Matrix::from_cols(axis, basis[0]);
379            Rotation::from_matrix_unchecked(mat)
380        }
381
382        #[cfg(feature = "dim3")]
383        {
384            // Minimal rotation taking +X to `axis`, NOT an arbitrary orthonormal basis:
385            // frames completed from two independently-set axes must not disagree by a twist,
386            // which fights a prismatic-like joint's angular locks and can diverge.
387            Rotation::from_rotation_arc(Vector::X, axis)
388        }
389    }
390
391    /// Is this joint enabled?
392    pub fn is_enabled(&self) -> bool {
393        self.enabled == JointEnabled::Enabled
394    }
395
396    /// Set whether this joint is enabled or not.
397    pub fn set_enabled(&mut self, enabled: bool) {
398        match self.enabled {
399            JointEnabled::Enabled | JointEnabled::DisabledByAttachedBody => {
400                if !enabled {
401                    self.enabled = JointEnabled::Disabled;
402                }
403            }
404            JointEnabled::Disabled => {
405                if enabled {
406                    self.enabled = JointEnabled::Enabled;
407                }
408            }
409        }
410    }
411
412    /// Add the specified axes to the set of axes locked by this joint.
413    pub fn lock_axes(&mut self, axes: JointAxesMask) -> &mut Self {
414        self.locked_axes |= axes;
415        self
416    }
417
418    /// Sets the joint’s frame, expressed in the first rigid-body’s local-space.
419    pub fn set_local_frame1(&mut self, local_frame: Pose) -> &mut Self {
420        self.local_frame1 = local_frame;
421        self
422    }
423
424    /// Sets the joint’s frame, expressed in the second rigid-body’s local-space.
425    pub fn set_local_frame2(&mut self, local_frame: Pose) -> &mut Self {
426        self.local_frame2 = local_frame;
427        self
428    }
429
430    /// The principal (local X) axis of this joint, expressed in the first rigid-body’s local-space.
431    #[must_use]
432    pub fn local_axis1(&self) -> Vector {
433        self.local_frame1 * Vector::X
434    }
435
436    /// Sets the principal (local X) axis of this joint, expressed in the first rigid-body’s local-space.
437    ///
438    /// The tangent axes of the joint frame are completed deterministically with the minimal
439    /// rotation taking +X to `local_axis`, so frames set from two rotated-but-matching axes
440    /// remain twist-consistent. For exact control over the tangent axes, set the full frame
441    /// with [`Self::set_local_frame1`] instead.
442    pub fn set_local_axis1(&mut self, local_axis: Vector) -> &mut Self {
443        self.local_frame1.rotation = Self::complete_ang_frame(local_axis);
444        self
445    }
446
447    /// The principal (local X) axis of this joint, expressed in the second rigid-body’s local-space.
448    #[must_use]
449    pub fn local_axis2(&self) -> Vector {
450        self.local_frame2 * Vector::X
451    }
452
453    /// Sets the principal (local X) axis of this joint, expressed in the second rigid-body’s local-space.
454    ///
455    /// The tangent axes of the joint frame are completed deterministically with the minimal
456    /// rotation taking +X to `local_axis`, so frames set from two rotated-but-matching axes
457    /// remain twist-consistent. For exact control over the tangent axes, set the full frame
458    /// with [`Self::set_local_frame2`] instead.
459    pub fn set_local_axis2(&mut self, local_axis: Vector) -> &mut Self {
460        self.local_frame2.rotation = Self::complete_ang_frame(local_axis);
461        self
462    }
463
464    /// The anchor of this joint, expressed in the first rigid-body’s local-space.
465    #[must_use]
466    pub fn local_anchor1(&self) -> Vector {
467        self.local_frame1.translation
468    }
469
470    /// Sets anchor of this joint, expressed in the first rigid-body's local-space.
471    pub fn set_local_anchor1(&mut self, anchor1: Vector) -> &mut Self {
472        self.local_frame1.translation = anchor1;
473        self
474    }
475
476    /// The anchor of this joint, expressed in the second rigid-body's local-space.
477    #[must_use]
478    pub fn local_anchor2(&self) -> Vector {
479        self.local_frame2.translation
480    }
481
482    /// Sets anchor of this joint, expressed in the second rigid-body's local-space.
483    pub fn set_local_anchor2(&mut self, anchor2: Vector) -> &mut Self {
484        self.local_frame2.translation = anchor2;
485        self
486    }
487
488    /// Are contacts between the attached rigid-bodies enabled?
489    pub fn contacts_enabled(&self) -> bool {
490        self.contacts_enabled
491    }
492
493    /// Sets whether contacts between the attached rigid-bodies are enabled.
494    pub fn set_contacts_enabled(&mut self, enabled: bool) -> &mut Self {
495        self.contacts_enabled = enabled;
496        self
497    }
498
499    /// Sets the spring coefficients controlling this joint constraint’s softness.
500    #[must_use]
501    pub fn set_softness(&mut self, softness: SpringCoefficients<Real>) -> &mut Self {
502        self.softness = softness;
503        self
504    }
505
506    /// The joint limits along the specified axis.
507    #[must_use]
508    pub fn limits(&self, axis: JointAxis) -> Option<&JointLimits<Real>> {
509        let i = axis as usize;
510        if self.limit_axes.contains(axis.into()) {
511            Some(&self.limits[i])
512        } else {
513            None
514        }
515    }
516
517    /// Sets the joint limits along the specified axis.
518    pub fn set_limits(&mut self, axis: JointAxis, limits: [Real; 2]) -> &mut Self {
519        let i = axis as usize;
520        self.limit_axes |= axis.into();
521        self.limits[i].min = limits[0];
522        self.limits[i].max = limits[1];
523        self
524    }
525
526    /// The spring-like motor model along the specified axis of this joint.
527    #[must_use]
528    pub fn motor_model(&self, axis: JointAxis) -> Option<MotorModel> {
529        let i = axis as usize;
530        if self.motor_axes.contains(axis.into()) {
531            Some(self.motors[i].model)
532        } else {
533            None
534        }
535    }
536
537    /// Set the spring-like model used by the motor to reach the desired target velocity and position.
538    pub fn set_motor_model(&mut self, axis: JointAxis, model: MotorModel) -> &mut Self {
539        self.motors[axis as usize].model = model;
540        self
541    }
542
543    /// Sets the target velocity this motor needs to reach.
544    pub fn set_motor_velocity(
545        &mut self,
546        axis: JointAxis,
547        target_vel: Real,
548        factor: Real,
549    ) -> &mut Self {
550        self.set_motor(
551            axis,
552            self.motors[axis as usize].target_pos,
553            target_vel,
554            0.0,
555            factor,
556        )
557    }
558
559    /// Sets the target angle this motor needs to reach.
560    pub fn set_motor_position(
561        &mut self,
562        axis: JointAxis,
563        target_pos: Real,
564        stiffness: Real,
565        damping: Real,
566    ) -> &mut Self {
567        self.set_motor(axis, target_pos, 0.0, stiffness, damping)
568    }
569
570    /// Sets the maximum force the motor can deliver along the specified axis.
571    pub fn set_motor_max_force(&mut self, axis: JointAxis, max_force: Real) -> &mut Self {
572        self.motors[axis as usize].max_force = max_force;
573        self
574    }
575
576    /// The motor affecting the joint’s degree of freedom along the specified axis.
577    #[must_use]
578    pub fn motor(&self, axis: JointAxis) -> Option<&JointMotor> {
579        let i = axis as usize;
580        if self.motor_axes.contains(axis.into()) {
581            Some(&self.motors[i])
582        } else {
583            None
584        }
585    }
586
587    /// Configure both the target angle and target velocity of the motor.
588    pub fn set_motor(
589        &mut self,
590        axis: JointAxis,
591        target_pos: Real,
592        target_vel: Real,
593        stiffness: Real,
594        damping: Real,
595    ) -> &mut Self {
596        self.motor_axes |= axis.into();
597        let i = axis as usize;
598        self.motors[i].target_vel = target_vel;
599        self.motors[i].target_pos = target_pos;
600        self.motors[i].stiffness = stiffness;
601        self.motors[i].damping = damping;
602        self
603    }
604
605    /// Flips the orientation of the joint, including limits and motors.
606    pub fn flip(&mut self) {
607        core::mem::swap(&mut self.local_frame1, &mut self.local_frame2);
608
609        let coupled_bits = self.coupled_axes.bits();
610
611        for dim in 0..SPATIAL_DIM {
612            if coupled_bits & (1 << dim) == 0 {
613                let limit = self.limits[dim];
614                self.limits[dim].min = -limit.max;
615                self.limits[dim].max = -limit.min;
616            }
617
618            self.motors[dim].target_vel = -self.motors[dim].target_vel;
619            self.motors[dim].target_pos = -self.motors[dim].target_pos;
620        }
621    }
622
623    #[cfg(feature = "alloc")]
624    pub(crate) fn transform_to_solver_body_space(&mut self, rb1: &RigidBody, rb2: &RigidBody) {
625        if rb1.is_fixed() {
626            self.local_frame1 = rb1.pos.position * self.local_frame1;
627        } else {
628            self.local_frame1.translation -= rb1.mprops.local_mprops.local_com;
629        }
630
631        if rb2.is_fixed() {
632            self.local_frame2 = rb2.pos.position * self.local_frame2;
633        } else {
634            self.local_frame2.translation -= rb2.mprops.local_mprops.local_com;
635        }
636    }
637}
638
639macro_rules! joint_conversion_methods(
640    ($as_joint: ident, $as_joint_mut: ident, $Joint: ty, $axes: expr) => {
641        /// Converts the joint to its specific variant, if it is one.
642        #[must_use]
643        pub fn $as_joint(&self) -> Option<&$Joint> {
644            if self.locked_axes == $axes {
645                // SAFETY: this is OK because the target joint type is
646                //         a `repr(transparent)` newtype of `Joint`.
647                Some(unsafe { core::mem::transmute::<&Self, &$Joint>(self) })
648            } else {
649                None
650            }
651        }
652
653        /// Converts the joint to its specific mutable variant, if it is one.
654        #[must_use]
655        pub fn $as_joint_mut(&mut self) -> Option<&mut $Joint> {
656            if self.locked_axes == $axes {
657                // SAFETY: this is OK because the target joint type is
658                //         a `repr(transparent)` newtype of `Joint`.
659                Some(unsafe { core::mem::transmute::<&mut Self, &mut $Joint>(self) })
660            } else {
661                None
662            }
663        }
664    }
665);
666
667impl GenericJoint {
668    joint_conversion_methods!(
669        as_revolute,
670        as_revolute_mut,
671        RevoluteJoint,
672        JointAxesMask::LOCKED_REVOLUTE_AXES
673    );
674    joint_conversion_methods!(
675        as_fixed,
676        as_fixed_mut,
677        FixedJoint,
678        JointAxesMask::LOCKED_FIXED_AXES
679    );
680    joint_conversion_methods!(
681        as_prismatic,
682        as_prismatic_mut,
683        PrismaticJoint,
684        JointAxesMask::LOCKED_PRISMATIC_AXES
685    );
686    joint_conversion_methods!(
687        as_rope,
688        as_rope_mut,
689        RopeJoint,
690        JointAxesMask::FREE_FIXED_AXES
691    );
692
693    #[cfg(feature = "dim3")]
694    joint_conversion_methods!(
695        as_spherical,
696        as_spherical_mut,
697        SphericalJoint,
698        JointAxesMask::LOCKED_SPHERICAL_AXES
699    );
700}
701
702/// Create generic joints using the builder pattern.
703#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
704#[derive(Copy, Clone, Debug, PartialEq)]
705pub struct GenericJointBuilder(pub GenericJoint);
706
707impl GenericJointBuilder {
708    /// Creates a new generic joint builder.
709    #[must_use]
710    pub fn new(locked_axes: JointAxesMask) -> Self {
711        Self(GenericJoint::new(locked_axes))
712    }
713
714    /// Sets the degrees of freedom locked by the joint.
715    #[must_use]
716    pub fn locked_axes(mut self, axes: JointAxesMask) -> Self {
717        self.0.locked_axes = axes;
718        self
719    }
720
721    /// Sets whether contacts between the attached rigid-bodies are enabled.
722    #[must_use]
723    pub fn contacts_enabled(mut self, enabled: bool) -> Self {
724        self.0.contacts_enabled = enabled;
725        self
726    }
727
728    /// Sets the joint’s frame, expressed in the first rigid-body’s local-space.
729    #[must_use]
730    pub fn local_frame1(mut self, local_frame: Pose) -> Self {
731        self.0.set_local_frame1(local_frame);
732        self
733    }
734
735    /// Sets the joint’s frame, expressed in the second rigid-body’s local-space.
736    #[must_use]
737    pub fn local_frame2(mut self, local_frame: Pose) -> Self {
738        self.0.set_local_frame2(local_frame);
739        self
740    }
741
742    /// Sets the principal (local X) axis of this joint, expressed in the first rigid-body’s local-space.
743    #[must_use]
744    pub fn local_axis1(mut self, local_axis: Vector) -> Self {
745        self.0.set_local_axis1(local_axis);
746        self
747    }
748
749    /// Sets the principal (local X) axis of this joint, expressed in the second rigid-body’s local-space.
750    #[must_use]
751    pub fn local_axis2(mut self, local_axis: Vector) -> Self {
752        self.0.set_local_axis2(local_axis);
753        self
754    }
755
756    /// Sets the anchor of this joint, expressed in the first rigid-body’s local-space.
757    #[must_use]
758    pub fn local_anchor1(mut self, anchor1: Vector) -> Self {
759        self.0.set_local_anchor1(anchor1);
760        self
761    }
762
763    /// Sets the anchor of this joint, expressed in the second rigid-body’s local-space.
764    #[must_use]
765    pub fn local_anchor2(mut self, anchor2: Vector) -> Self {
766        self.0.set_local_anchor2(anchor2);
767        self
768    }
769
770    /// Sets the joint limits along the specified axis.
771    #[must_use]
772    pub fn limits(mut self, axis: JointAxis, limits: [Real; 2]) -> Self {
773        self.0.set_limits(axis, limits);
774        self
775    }
776
777    /// Sets the coupled degrees of freedom for this joint’s limits and motor.
778    #[must_use]
779    pub fn coupled_axes(mut self, axes: JointAxesMask) -> Self {
780        self.0.coupled_axes = axes;
781        self
782    }
783
784    /// Set the spring-like model used by the motor to reach the desired target velocity and position.
785    #[must_use]
786    pub fn motor_model(mut self, axis: JointAxis, model: MotorModel) -> Self {
787        self.0.set_motor_model(axis, model);
788        self
789    }
790
791    /// Sets the target velocity this motor needs to reach.
792    #[must_use]
793    pub fn motor_velocity(mut self, axis: JointAxis, target_vel: Real, factor: Real) -> Self {
794        self.0.set_motor_velocity(axis, target_vel, factor);
795        self
796    }
797
798    /// Sets the target angle this motor needs to reach.
799    #[must_use]
800    pub fn motor_position(
801        mut self,
802        axis: JointAxis,
803        target_pos: Real,
804        stiffness: Real,
805        damping: Real,
806    ) -> Self {
807        self.0
808            .set_motor_position(axis, target_pos, stiffness, damping);
809        self
810    }
811
812    /// Configure both the target angle and target velocity of the motor.
813    #[must_use]
814    pub fn set_motor(
815        mut self,
816        axis: JointAxis,
817        target_pos: Real,
818        target_vel: Real,
819        stiffness: Real,
820        damping: Real,
821    ) -> Self {
822        self.0
823            .set_motor(axis, target_pos, target_vel, stiffness, damping);
824        self
825    }
826
827    /// Sets the maximum force the motor can deliver along the specified axis.
828    #[must_use]
829    pub fn motor_max_force(mut self, axis: JointAxis, max_force: Real) -> Self {
830        self.0.set_motor_max_force(axis, max_force);
831        self
832    }
833
834    /// Sets the softness of this joint’s locked degrees of freedom.
835    #[must_use]
836    pub fn softness(mut self, softness: SpringCoefficients<Real>) -> Self {
837        self.0.softness = softness;
838        self
839    }
840
841    /// An arbitrary user-defined 128-bit integer associated to the joints built by this builder.
842    pub fn user_data(mut self, data: u128) -> Self {
843        self.0.user_data = data;
844        self
845    }
846
847    /// Builds the generic joint.
848    #[must_use]
849    pub fn build(self) -> GenericJoint {
850        self.0
851    }
852}
853
854impl From<GenericJointBuilder> for GenericJoint {
855    fn from(val: GenericJointBuilder) -> GenericJoint {
856        val.0
857    }
858}