AngleConstraintPart.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Body/Body.h>
  6. #include <Jolt/Physics/Constraints/ConstraintPart/SpringPart.h>
  7. #include <Jolt/Physics/Constraints/SpringSettings.h>
  8. #include <Jolt/Physics/StateRecorder.h>
  9. JPH_NAMESPACE_BEGIN
  10. /// Constraint that constrains rotation along 1 axis
  11. ///
  12. /// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, see section 2.4.5
  13. ///
  14. /// Constraint equation (eq 108):
  15. ///
  16. /// \f[C = \theta(t) - \theta_{min}\f]
  17. ///
  18. /// Jacobian (eq 109):
  19. ///
  20. /// \f[J = \begin{bmatrix}0 & -a^T & 0 & a^T\end{bmatrix}\f]
  21. ///
  22. /// Used terms (here and below, everything in world space):\n
  23. /// a = axis around which rotation is constrained (normalized).\n
  24. /// x1, x2 = center of mass for the bodies.\n
  25. /// v = [v1, w1, v2, w2].\n
  26. /// v1, v2 = linear velocity of body 1 and 2.\n
  27. /// w1, w2 = angular velocity of body 1 and 2.\n
  28. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  29. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  30. /// b = velocity bias.\n
  31. /// \f$\beta\f$ = baumgarte constant.
  32. class AngleConstraintPart
  33. {
  34. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  35. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
  36. {
  37. // Apply impulse if delta is not zero
  38. if (inLambda != 0.0f)
  39. {
  40. // Calculate velocity change due to constraint
  41. //
  42. // Impulse:
  43. // P = J^T lambda
  44. //
  45. // Euler velocity integration:
  46. // v' = v + M^-1 P
  47. if (ioBody1.IsDynamic())
  48. ioBody1.GetMotionProperties()->SubAngularVelocityStep(inLambda * mInvI1_Axis);
  49. if (ioBody2.IsDynamic())
  50. ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_Axis);
  51. return true;
  52. }
  53. return false;
  54. }
  55. /// Internal helper function to calculate the inverse effective mass
  56. JPH_INLINE float CalculateInverseEffectiveMass(const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis)
  57. {
  58. JPH_ASSERT(inWorldSpaceAxis.IsNormalized(1.0e-4f));
  59. // Calculate properties used below
  60. mInvI1_Axis = inBody1.IsDynamic()? inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceAxis) : Vec3::sZero();
  61. mInvI2_Axis = inBody2.IsDynamic()? inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceAxis) : Vec3::sZero();
  62. // Calculate inverse effective mass: K = J M^-1 J^T
  63. return inWorldSpaceAxis.Dot(mInvI1_Axis + mInvI2_Axis);
  64. }
  65. public:
  66. /// Calculate properties used during the functions below
  67. /// @param inBody1 The first body that this constraint is attached to
  68. /// @param inBody2 The second body that this constraint is attached to
  69. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  70. /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:
  71. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  72. inline void CalculateConstraintProperties(const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias = 0.0f)
  73. {
  74. mEffectiveMass = 1.0f / CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  75. mSpringPart.CalculateSpringPropertiesWithBias(inBias);
  76. }
  77. /// Calculate properties used during the functions below
  78. /// @param inDeltaTime Time step
  79. /// @param inBody1 The first body that this constraint is attached to
  80. /// @param inBody2 The second body that this constraint is attached to
  81. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  82. /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:
  83. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  84. /// @param inC Value of the constraint equation (C)
  85. /// @param inFrequency Oscillation frequency (Hz)
  86. /// @param inDamping Damping factor (0 = no damping, 1 = critical damping)
  87. inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping)
  88. {
  89. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  90. mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);
  91. }
  92. /// Calculate properties used during the functions below
  93. /// @param inDeltaTime Time step
  94. /// @param inBody1 The first body that this constraint is attached to
  95. /// @param inBody2 The second body that this constraint is attached to
  96. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  97. /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:
  98. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  99. /// @param inC Value of the constraint equation (C)
  100. /// @param inStiffness Spring stiffness k.
  101. /// @param inDamping Spring damping coefficient c.
  102. inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping)
  103. {
  104. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  105. mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);
  106. }
  107. /// Selects one of the above functions based on the spring settings
  108. inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)
  109. {
  110. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  111. if (inv_effective_mass == 0.0f)
  112. Deactivate();
  113. else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping)
  114. mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass);
  115. else
  116. mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass);
  117. }
  118. /// Deactivate this constraint
  119. inline void Deactivate()
  120. {
  121. mEffectiveMass = 0.0f;
  122. mTotalLambda = 0.0f;
  123. }
  124. /// Check if constraint is active
  125. inline bool IsActive() const
  126. {
  127. return mEffectiveMass != 0.0f;
  128. }
  129. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  130. /// @param ioBody1 The first body that this constraint is attached to
  131. /// @param ioBody2 The second body that this constraint is attached to
  132. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  133. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  134. {
  135. mTotalLambda *= inWarmStartImpulseRatio;
  136. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  137. }
  138. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  139. /// @param ioBody1 The first body that this constraint is attached to
  140. /// @param ioBody2 The second body that this constraint is attached to
  141. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  142. /// @param inMinLambda Minimum angular impulse to apply (N m s)
  143. /// @param inMaxLambda Maximum angular impulse to apply (N m s)
  144. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  145. {
  146. // Lagrange multiplier is:
  147. //
  148. // lambda = -K^-1 (J v + b)
  149. float lambda = mEffectiveMass * (inWorldSpaceAxis.Dot(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity()) - mSpringPart.GetBias(mTotalLambda));
  150. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  151. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  152. mTotalLambda = new_lambda; // Store accumulated impulse
  153. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  154. }
  155. /// Return lagrange multiplier
  156. float GetTotalLambda() const
  157. {
  158. return mTotalLambda;
  159. }
  160. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  161. /// @param ioBody1 The first body that this constraint is attached to
  162. /// @param ioBody2 The second body that this constraint is attached to
  163. /// @param inC Value of the constraint equation (C)
  164. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  165. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  166. {
  167. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  168. if (inC != 0.0f && !mSpringPart.IsActive())
  169. {
  170. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  171. //
  172. // lambda = -K^-1 * beta / dt * C
  173. //
  174. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  175. float lambda = -mEffectiveMass * inBaumgarte * inC;
  176. // Directly integrate velocity change for one time step
  177. //
  178. // Euler velocity integration:
  179. // dv = M^-1 P
  180. //
  181. // Impulse:
  182. // P = J^T lambda
  183. //
  184. // Euler position integration:
  185. // x' = x + dv * dt
  186. //
  187. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  188. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  189. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  190. // integrate + a position integrate and then discard the velocity change.
  191. if (ioBody1.IsDynamic())
  192. ioBody1.SubRotationStep(lambda * mInvI1_Axis);
  193. if (ioBody2.IsDynamic())
  194. ioBody2.AddRotationStep(lambda * mInvI2_Axis);
  195. return true;
  196. }
  197. return false;
  198. }
  199. /// Save state of this constraint part
  200. void SaveState(StateRecorder &inStream) const
  201. {
  202. inStream.Write(mTotalLambda);
  203. }
  204. /// Restore state of this constraint part
  205. void RestoreState(StateRecorder &inStream)
  206. {
  207. inStream.Read(mTotalLambda);
  208. }
  209. private:
  210. Vec3 mInvI1_Axis;
  211. Vec3 mInvI2_Axis;
  212. float mEffectiveMass = 0.0f;
  213. SpringPart mSpringPart;
  214. float mTotalLambda = 0.0f;
  215. };
  216. JPH_NAMESPACE_END