SixDOFConstraint.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Constraints/TwoBodyConstraint.h>
  5. #include <Jolt/Physics/Constraints/MotorSettings.h>
  6. #include <Jolt/Physics/Constraints/ConstraintPart/PointConstraintPart.h>
  7. #include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
  8. #include <Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h>
  9. #include <Jolt/Physics/Constraints/ConstraintPart/RotationEulerConstraintPart.h>
  10. #include <Jolt/Physics/Constraints/ConstraintPart/SwingTwistConstraintPart.h>
  11. JPH_NAMESPACE_BEGIN
  12. /// 6 Degree Of Freedom Constraint setup structure. Allows control over each of the 6 degrees of freedom.
  13. class SixDOFConstraintSettings final : public TwoBodyConstraintSettings
  14. {
  15. public:
  16. JPH_DECLARE_SERIALIZABLE_VIRTUAL(SixDOFConstraintSettings)
  17. /// Constraint is split up into translation/rotation around X, Y and Z axis.
  18. enum EAxis
  19. {
  20. TranslationX,
  21. TranslationY,
  22. TranslationZ,
  23. RotationX, ///< When limited: MinLimit needs to be [-PI, 0], MaxLimit needs to be [0, PI]
  24. RotationY, ///< When limited: MaxLimit between [0, PI]. MinLimit = -MaxLimit. Forms a cone shaped limit with Z.
  25. RotationZ, ///< When limited: MaxLimit between [0, PI]. MinLimit = -MaxLimit. Forms a cone shaped limit with Y.
  26. Num,
  27. };
  28. // See: ConstraintSettings::SaveBinaryState
  29. virtual void SaveBinaryState(StreamOut &inStream) const override;
  30. /// Create an an instance of this constraint
  31. virtual TwoBodyConstraint * Create(Body &inBody1, Body &inBody2) const override;
  32. /// This determines in which space the constraint is setup, all properties below should be in the specified space
  33. EConstraintSpace mSpace = EConstraintSpace::WorldSpace;
  34. /// Body 1 constraint reference frame (space determined by mSpace)
  35. Vec3 mPosition1 = Vec3::sZero();
  36. Vec3 mAxisX1 = Vec3::sAxisX();
  37. Vec3 mAxisY1 = Vec3::sAxisY();
  38. /// Body 2 constraint reference frame (space determined by mSpace)
  39. Vec3 mPosition2 = Vec3::sZero();
  40. Vec3 mAxisX2 = Vec3::sAxisX();
  41. Vec3 mAxisY2 = Vec3::sAxisY();
  42. /// Friction settings.
  43. /// For translation: Max friction force in N. 0 = no friction.
  44. /// For rotation: Max friction torque in Nm. 0 = no friction.
  45. float mMaxFriction[EAxis::Num] = { 0, 0, 0, 0, 0, 0 };
  46. /// Limits.
  47. /// For translation: Min and max linear limits in m (0 is frame of body 1 and 2 coincide).
  48. /// For rotation: Min and max angular limits in rad (0 is frame of body 1 and 2 coincide). See comments at Axis enum for limit ranges.
  49. ///
  50. /// Remove degree of freedom by setting min = FLT_MAX and max = -FLT_MAX. The constraint will be driven to 0 for this axis.
  51. ///
  52. /// Free movement over an axis is allowed when min = -FLT_MAX and max = FLT_MAX.
  53. float mLimitMin[EAxis::Num] = { -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX, -FLT_MAX };
  54. float mLimitMax[EAxis::Num] = { FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX, FLT_MAX };
  55. /// Make axis free (unconstrained)
  56. void MakeFreeAxis(EAxis inAxis) { mLimitMin[inAxis] = -FLT_MAX; mLimitMax[inAxis] = FLT_MAX; }
  57. bool IsFreeAxis(EAxis inAxis) const { return mLimitMin[inAxis] == -FLT_MAX && mLimitMax[inAxis] == FLT_MAX; }
  58. /// Make axis fixed (fixed at value 0)
  59. void MakeFixedAxis(EAxis inAxis) { mLimitMin[inAxis] = FLT_MAX; mLimitMax[inAxis] = -FLT_MAX; }
  60. bool IsFixedAxis(EAxis inAxis) const { return mLimitMin[inAxis] >= mLimitMax[inAxis]; }
  61. /// Set a valid range for the constraint
  62. void SetLimitedAxis(EAxis inAxis, float inMin, float inMax) { JPH_ASSERT(inMin < inMax); JPH_ASSERT(inMin <= 0.0f); JPH_ASSERT(inMax >= 0.0f); mLimitMin[inAxis] = inMin; mLimitMax[inAxis] = inMax; }
  63. /// Motor settings for each axis
  64. MotorSettings mMotorSettings[EAxis::Num];
  65. protected:
  66. // See: ConstraintSettings::RestoreBinaryState
  67. virtual void RestoreBinaryState(StreamIn &inStream) override;
  68. };
  69. /// 6 Degree Of Freedom Constraint. Allows control over each of the 6 degrees of freedom.
  70. class SixDOFConstraint final : public TwoBodyConstraint
  71. {
  72. public:
  73. /// Get Axis from settings class
  74. using EAxis = SixDOFConstraintSettings::EAxis;
  75. /// Construct six DOF constraint
  76. SixDOFConstraint(Body &inBody1, Body &inBody2, const SixDOFConstraintSettings &inSettings);
  77. /// Generic interface of a constraint
  78. virtual EConstraintSubType GetSubType() const override { return EConstraintSubType::SixDOF; }
  79. virtual void SetupVelocityConstraint(float inDeltaTime) override;
  80. virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) override;
  81. virtual bool SolveVelocityConstraint(float inDeltaTime) override;
  82. virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) override;
  83. #ifdef JPH_DEBUG_RENDERER
  84. virtual void DrawConstraint(DebugRenderer *inRenderer) const override;
  85. virtual void DrawConstraintLimits(DebugRenderer *inRenderer) const override;
  86. #endif // JPH_DEBUG_RENDERER
  87. virtual void SaveState(StateRecorder &inStream) const override;
  88. virtual void RestoreState(StateRecorder &inStream) override;
  89. virtual Ref<ConstraintSettings> GetConstraintSettings() const override;
  90. // See: TwoBodyConstraint
  91. virtual Mat44 GetConstraintToBody1Matrix() const override { return Mat44::sRotationTranslation(mConstraintToBody1, mLocalSpacePosition1); }
  92. virtual Mat44 GetConstraintToBody2Matrix() const override { return Mat44::sRotationTranslation(mConstraintToBody2, mLocalSpacePosition2); }
  93. /// Update the translation limits for this constraint, note that this won't change if axis are free or not.
  94. void SetTranslationLimits(Vec3Arg inLimitMin, Vec3Arg inLimitMax);
  95. /// Update the rotational limits for this constraint, note that this won't change if axis are free or not.
  96. void SetRotationLimits(Vec3Arg inLimitMin, Vec3Arg inLimitMax);
  97. /// Set the max friction for each axis
  98. void SetMaxFriction(EAxis inAxis, float inFriction);
  99. float GetMaxFriction(EAxis inAxis) const { return mMaxFriction[inAxis]; }
  100. /// Get rotation of constraint in constraint space
  101. inline Quat GetRotationInConstraintSpace() const;
  102. /// Motor settings
  103. MotorSettings & GetMotorSettings(EAxis inAxis) { return mMotorSettings[inAxis]; }
  104. const MotorSettings & GetMotorSettings(EAxis inAxis) const { return mMotorSettings[inAxis]; }
  105. /// Motor controls.
  106. /// Translation motors work in constraint space of body 1.
  107. /// Rotation motors work in constraint space of body 2 (!).
  108. void SetMotorState(EAxis inAxis, EMotorState inState);
  109. EMotorState GetMotorState(EAxis inAxis) const { return mMotorState[inAxis]; }
  110. /// Set the target velocity in body 1 constraint space
  111. Vec3 GetTargetVelocityCS() const { return mTargetVelocity; }
  112. void SetTargetVelocityCS(Vec3Arg inVelocity) { mTargetVelocity = inVelocity; }
  113. /// Set the target angular velocity in body 2 constraint space (!)
  114. void SetTargetAngularVelocityCS(Vec3Arg inAngularVelocity) { mTargetAngularVelocity = inAngularVelocity; }
  115. Vec3 GetTargetAngularVelocityCS() const { return mTargetAngularVelocity; }
  116. /// Set the target position in body 1 constraint space
  117. Vec3 GetTargetPositionCS() const { return mTargetPosition; }
  118. void SetTargetPositionCS(Vec3Arg inPosition) { mTargetPosition = inPosition; }
  119. /// Set the target orientation in body 1 constraint space
  120. void SetTargetOrientationCS(QuatArg inOrientation);
  121. Quat GetTargetOrientationCS() const { return mTargetOrientation; }
  122. /// Set the target orientation in body space (R2 = R1 * inOrientation, where R1 and R2 are the world space rotations for body 1 and 2).
  123. /// Solve: R2 * ConstraintToBody2 = R1 * ConstraintToBody1 * q (see SwingTwistConstraint::GetSwingTwist) and R2 = R1 * inOrientation for q.
  124. void SetTargetOrientationBS(QuatArg inOrientation) { SetTargetOrientationCS(mConstraintToBody1.Conjugated() * inOrientation * mConstraintToBody2); }
  125. ///@name Get Lagrange multiplier from last physics update (relates to how much force/torque was applied to satisfy the constraint)
  126. inline Vec3 GetTotalLambdaPosition() const { return IsTranslationFullyConstrained()? mPointConstraintPart.GetTotalLambda() : Vec3(mTranslationConstraintPart[0].GetTotalLambda(), mTranslationConstraintPart[1].GetTotalLambda(), mTranslationConstraintPart[2].GetTotalLambda()); }
  127. inline Vec3 GetTotalLambdaRotation() const { return IsRotationFullyConstrained()? mRotationConstraintPart.GetTotalLambda() : Vec3(mSwingTwistConstraintPart.GetTotalTwistLambda(), mSwingTwistConstraintPart.GetTotalSwingYLambda(), mSwingTwistConstraintPart.GetTotalSwingZLambda()); }
  128. inline Vec3 GetTotalLambdaMotorTranslation() const { return Vec3(mMotorTranslationConstraintPart[0].GetTotalLambda(), mMotorTranslationConstraintPart[1].GetTotalLambda(), mMotorTranslationConstraintPart[2].GetTotalLambda()); }
  129. inline Vec3 GetTotalLambdaMotorRotation() const { return Vec3(mMotorRotationConstraintPart[0].GetTotalLambda(), mMotorRotationConstraintPart[1].GetTotalLambda(), mMotorRotationConstraintPart[2].GetTotalLambda()); }
  130. private:
  131. // Calculate properties needed for the position constraint
  132. inline void GetPositionConstraintProperties(Vec3 &outR1PlusU, Vec3 &outR2, Vec3 &outU) const;
  133. // Propagate the rotation limits to the constraint part
  134. inline void UpdateRotationLimits();
  135. // Cache the state of mTranslationMotorActive
  136. void CacheTranslationMotorActive();
  137. // Cache the state of mRotationMotorActive
  138. void CacheRotationMotorActive();
  139. // Constraint settings helper functions
  140. inline bool IsAxisFixed(EAxis inAxis) const { return (mFixedAxis & (1 << inAxis)) != 0; }
  141. inline bool IsAxisFree(EAxis inAxis) const { return (mFreeAxis & (1 << inAxis)) != 0; }
  142. inline bool IsTranslationConstrained() const { return (mFreeAxis & 0b111) != 0b111; }
  143. inline bool IsTranslationFullyConstrained() const { return (mFixedAxis & 0b111) == 0b111; }
  144. inline bool IsRotationConstrained() const { return (mFreeAxis & 0b111000) != 0b111000; }
  145. inline bool IsRotationFullyConstrained() const { return (mFixedAxis & 0b111000) == 0b111000; }
  146. inline bool HasFriction(EAxis inAxis) const { return !IsAxisFixed(inAxis) && mMaxFriction[inAxis] > 0.0f; }
  147. // CONFIGURATION PROPERTIES FOLLOW
  148. // Local space constraint positions
  149. Vec3 mLocalSpacePosition1;
  150. Vec3 mLocalSpacePosition2;
  151. // Transforms from constraint space to body space
  152. Quat mConstraintToBody1;
  153. Quat mConstraintToBody2;
  154. // Limits
  155. uint8 mFreeAxis; // Bitmask of free axis (bit 0 = TranslationX)
  156. uint8 mFixedAxis; // Bitmask of fixed axis (bit 0 = TranslationX)
  157. bool mTranslationMotorActive = false; // If any of the translational frictions / motors are active
  158. bool mRotationMotorActive = false; // If any of the rotational frictions / motors are active
  159. uint8 mRotationPositionMotorActive = 0; // Bitmask of axis that have position motor active (bit 0 = RotationX)
  160. float mLimitMin[EAxis::Num];
  161. float mLimitMax[EAxis::Num];
  162. // Motor settings for each axis
  163. MotorSettings mMotorSettings[EAxis::Num];
  164. // Friction settings for each axis
  165. float mMaxFriction[EAxis::Num];
  166. // Motor controls
  167. EMotorState mMotorState[EAxis::Num] = { EMotorState::Off, EMotorState::Off, EMotorState::Off, EMotorState::Off, EMotorState::Off, EMotorState::Off };
  168. Vec3 mTargetVelocity = Vec3::sZero();
  169. Vec3 mTargetAngularVelocity = Vec3::sZero();
  170. Vec3 mTargetPosition = Vec3::sZero();
  171. Quat mTargetOrientation = Quat::sIdentity();
  172. // RUN TIME PROPERTIES FOLLOW
  173. // Constraint space axis in world space
  174. Vec3 mTranslationAxis[3];
  175. Vec3 mRotationAxis[3];
  176. // Translation displacement (valid when translation axis has a range limit)
  177. float mDisplacement[3];
  178. // Individual constraint parts for translation, or a combined point constraint part if all axis are fixed
  179. AxisConstraintPart mTranslationConstraintPart[3];
  180. PointConstraintPart mPointConstraintPart;
  181. // Individual constraint parts for rotation or a combined constraint part if rotation is fixed
  182. SwingTwistConstraintPart mSwingTwistConstraintPart;
  183. RotationEulerConstraintPart mRotationConstraintPart;
  184. // Motor or friction constraints
  185. AxisConstraintPart mMotorTranslationConstraintPart[3];
  186. AngleConstraintPart mMotorRotationConstraintPart[3];
  187. };
  188. JPH_NAMESPACE_END