AngleConstraintPart.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  75. if (inv_effective_mass == 0.0f)
  76. Deactivate();
  77. else
  78. {
  79. mEffectiveMass = 1.0f / inv_effective_mass;
  80. mSpringPart.CalculateSpringPropertiesWithBias(inBias);
  81. }
  82. }
  83. /// Calculate properties used during the functions below
  84. /// @param inDeltaTime Time step
  85. /// @param inBody1 The first body that this constraint is attached to
  86. /// @param inBody2 The second body that this constraint is attached to
  87. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  88. /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:
  89. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  90. /// @param inC Value of the constraint equation (C)
  91. /// @param inFrequency Oscillation frequency (Hz)
  92. /// @param inDamping Damping factor (0 = no damping, 1 = critical damping)
  93. inline void CalculateConstraintPropertiesWithFrequencyAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inFrequency, float inDamping)
  94. {
  95. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  96. if (inv_effective_mass == 0.0f)
  97. Deactivate();
  98. else
  99. mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inFrequency, inDamping, mEffectiveMass);
  100. }
  101. /// Calculate properties used during the functions below
  102. /// @param inDeltaTime Time step
  103. /// @param inBody1 The first body that this constraint is attached to
  104. /// @param inBody2 The second body that this constraint is attached to
  105. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  106. /// Set the following terms to zero if you don't want to drive the constraint to zero with a spring:
  107. /// @param inBias Bias term (b) for the constraint impulse: lambda = J v + b
  108. /// @param inC Value of the constraint equation (C)
  109. /// @param inStiffness Spring stiffness k.
  110. /// @param inDamping Spring damping coefficient c.
  111. inline void CalculateConstraintPropertiesWithStiffnessAndDamping(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, float inStiffness, float inDamping)
  112. {
  113. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  114. if (inv_effective_mass == 0.0f)
  115. Deactivate();
  116. else
  117. mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inStiffness, inDamping, mEffectiveMass);
  118. }
  119. /// Selects one of the above functions based on the spring settings
  120. inline void CalculateConstraintPropertiesWithSettings(float inDeltaTime, const Body &inBody1, const Body &inBody2, Vec3Arg inWorldSpaceAxis, float inBias, float inC, const SpringSettings &inSpringSettings)
  121. {
  122. float inv_effective_mass = CalculateInverseEffectiveMass(inBody1, inBody2, inWorldSpaceAxis);
  123. if (inv_effective_mass == 0.0f)
  124. Deactivate();
  125. else if (inSpringSettings.mMode == ESpringMode::FrequencyAndDamping)
  126. mSpringPart.CalculateSpringPropertiesWithFrequencyAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mFrequency, inSpringSettings.mDamping, mEffectiveMass);
  127. else
  128. mSpringPart.CalculateSpringPropertiesWithStiffnessAndDamping(inDeltaTime, inv_effective_mass, inBias, inC, inSpringSettings.mStiffness, inSpringSettings.mDamping, mEffectiveMass);
  129. }
  130. /// Deactivate this constraint
  131. inline void Deactivate()
  132. {
  133. mEffectiveMass = 0.0f;
  134. mTotalLambda = 0.0f;
  135. }
  136. /// Check if constraint is active
  137. inline bool IsActive() const
  138. {
  139. return mEffectiveMass != 0.0f;
  140. }
  141. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  142. /// @param ioBody1 The first body that this constraint is attached to
  143. /// @param ioBody2 The second body that this constraint is attached to
  144. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  145. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  146. {
  147. mTotalLambda *= inWarmStartImpulseRatio;
  148. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  149. }
  150. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  151. /// @param ioBody1 The first body that this constraint is attached to
  152. /// @param ioBody2 The second body that this constraint is attached to
  153. /// @param inWorldSpaceAxis The axis of rotation along which the constraint acts (normalized)
  154. /// @param inMinLambda Minimum angular impulse to apply (N m s)
  155. /// @param inMaxLambda Maximum angular impulse to apply (N m s)
  156. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2, Vec3Arg inWorldSpaceAxis, float inMinLambda, float inMaxLambda)
  157. {
  158. // Lagrange multiplier is:
  159. //
  160. // lambda = -K^-1 (J v + b)
  161. float lambda = mEffectiveMass * (inWorldSpaceAxis.Dot(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity()) - mSpringPart.GetBias(mTotalLambda));
  162. float new_lambda = Clamp(mTotalLambda + lambda, inMinLambda, inMaxLambda); // Clamp impulse
  163. lambda = new_lambda - mTotalLambda; // Lambda potentially got clamped, calculate the new impulse to apply
  164. mTotalLambda = new_lambda; // Store accumulated impulse
  165. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  166. }
  167. /// Return lagrange multiplier
  168. float GetTotalLambda() const
  169. {
  170. return mTotalLambda;
  171. }
  172. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  173. /// @param ioBody1 The first body that this constraint is attached to
  174. /// @param ioBody2 The second body that this constraint is attached to
  175. /// @param inC Value of the constraint equation (C)
  176. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  177. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  178. {
  179. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  180. if (inC != 0.0f && !mSpringPart.IsActive())
  181. {
  182. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  183. //
  184. // lambda = -K^-1 * beta / dt * C
  185. //
  186. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  187. float lambda = -mEffectiveMass * inBaumgarte * inC;
  188. // Directly integrate velocity change for one time step
  189. //
  190. // Euler velocity integration:
  191. // dv = M^-1 P
  192. //
  193. // Impulse:
  194. // P = J^T lambda
  195. //
  196. // Euler position integration:
  197. // x' = x + dv * dt
  198. //
  199. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  200. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  201. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  202. // integrate + a position integrate and then discard the velocity change.
  203. if (ioBody1.IsDynamic())
  204. ioBody1.SubRotationStep(lambda * mInvI1_Axis);
  205. if (ioBody2.IsDynamic())
  206. ioBody2.AddRotationStep(lambda * mInvI2_Axis);
  207. return true;
  208. }
  209. return false;
  210. }
  211. /// Save state of this constraint part
  212. void SaveState(StateRecorder &inStream) const
  213. {
  214. inStream.Write(mTotalLambda);
  215. }
  216. /// Restore state of this constraint part
  217. void RestoreState(StateRecorder &inStream)
  218. {
  219. inStream.Read(mTotalLambda);
  220. }
  221. private:
  222. Vec3 mInvI1_Axis;
  223. Vec3 mInvI2_Axis;
  224. float mEffectiveMass = 0.0f;
  225. SpringPart mSpringPart;
  226. float mTotalLambda = 0.0f;
  227. };
  228. JPH_NAMESPACE_END