GearConstraintPart.h 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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/StateRecorder.h>
  7. JPH_NAMESPACE_BEGIN
  8. /// Constraint that constrains two rotations using a gear (rotating in opposite direction)
  9. ///
  10. /// Constraint equation:
  11. ///
  12. /// C = Rotation1(t) + r Rotation2(t)
  13. ///
  14. /// Derivative:
  15. ///
  16. /// d/dt C = 0
  17. /// <=> w1 . a + r w2 . b = 0
  18. ///
  19. /// Jacobian:
  20. ///
  21. /// \f[J = \begin{bmatrix}0 & a^T & 0 & r b^T\end{bmatrix}\f]
  22. ///
  23. /// Used terms (here and below, everything in world space):\n
  24. /// a = axis around which body 1 rotates (normalized).\n
  25. /// b = axis along which body 2 slides (normalized).\n
  26. /// Rotation1(t) = rotation around a of body 1.\n
  27. /// Rotation2(t) = rotation around b of body 2.\n
  28. /// r = ratio between rotation for body 1 and 2.\n
  29. /// v = [v1, w1, v2, w2].\n
  30. /// v1, v2 = linear velocity of body 1 and 2.\n
  31. /// w1, w2 = angular velocity of body 1 and 2.\n
  32. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  33. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  34. /// \f$\beta\f$ = baumgarte constant.
  35. class GearConstraintPart
  36. {
  37. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  38. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, float inLambda) const
  39. {
  40. // Apply impulse if delta is not zero
  41. if (inLambda != 0.0f)
  42. {
  43. // Calculate velocity change due to constraint
  44. //
  45. // Impulse:
  46. // P = J^T lambda
  47. //
  48. // Euler velocity integration:
  49. // v' = v + M^-1 P
  50. ioBody1.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI1_A);
  51. ioBody2.GetMotionProperties()->AddAngularVelocityStep(inLambda * mInvI2_B);
  52. return true;
  53. }
  54. return false;
  55. }
  56. public:
  57. /// Calculate properties used during the functions below
  58. /// @param inBody1 The first body that this constraint is attached to
  59. /// @param inBody2 The second body that this constraint is attached to
  60. /// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates
  61. /// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates
  62. /// @param inRatio The ratio between rotation and translation
  63. inline void CalculateConstraintProperties(const Body &inBody1, Vec3Arg inWorldSpaceHingeAxis1, const Body &inBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)
  64. {
  65. JPH_ASSERT(inWorldSpaceHingeAxis1.IsNormalized(1.0e-4f));
  66. JPH_ASSERT(inWorldSpaceHingeAxis2.IsNormalized(1.0e-4f));
  67. // Calculate: I1^-1 a
  68. mInvI1_A = inBody1.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody1.GetRotation(), inWorldSpaceHingeAxis1);
  69. // Calculate: I2^-1 b
  70. mInvI2_B = inBody2.GetMotionProperties()->MultiplyWorldSpaceInverseInertiaByVector(inBody2.GetRotation(), inWorldSpaceHingeAxis2);
  71. // K^-1 = 1 / (J M^-1 J^T) = 1 / (a^T I1^-1 a + r^2 * b^T I2^-1 b)
  72. float inv_effective_mass = (inWorldSpaceHingeAxis1.Dot(mInvI1_A) + inWorldSpaceHingeAxis2.Dot(mInvI2_B) * Square(inRatio));
  73. if (inv_effective_mass == 0.0f)
  74. Deactivate();
  75. else
  76. mEffectiveMass = 1.0f / inv_effective_mass;
  77. }
  78. /// Deactivate this constraint
  79. inline void Deactivate()
  80. {
  81. mEffectiveMass = 0.0f;
  82. mTotalLambda = 0.0f;
  83. }
  84. /// Check if constraint is active
  85. inline bool IsActive() const
  86. {
  87. return mEffectiveMass != 0.0f;
  88. }
  89. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  90. /// @param ioBody1 The first body that this constraint is attached to
  91. /// @param ioBody2 The second body that this constraint is attached to
  92. /// @param inWarmStartImpulseRatio Ratio of new step to old time step (dt_new / dt_old) for scaling the lagrange multiplier of the previous frame
  93. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  94. {
  95. mTotalLambda *= inWarmStartImpulseRatio;
  96. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  97. }
  98. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  99. /// @param ioBody1 The first body that this constraint is attached to
  100. /// @param ioBody2 The second body that this constraint is attached to
  101. /// @param inWorldSpaceHingeAxis1 The axis around which body 1 rotates
  102. /// @param inWorldSpaceHingeAxis2 The axis around which body 2 rotates
  103. /// @param inRatio The ratio between rotation and translation
  104. inline bool SolveVelocityConstraint(Body &ioBody1, Vec3Arg inWorldSpaceHingeAxis1, Body &ioBody2, Vec3Arg inWorldSpaceHingeAxis2, float inRatio)
  105. {
  106. // Lagrange multiplier is:
  107. //
  108. // lambda = -K^-1 (J v + b)
  109. float lambda = -mEffectiveMass * (inWorldSpaceHingeAxis1.Dot(ioBody1.GetAngularVelocity()) + inRatio * inWorldSpaceHingeAxis2.Dot(ioBody2.GetAngularVelocity()));
  110. mTotalLambda += lambda; // Store accumulated impulse
  111. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  112. }
  113. /// Return lagrange multiplier
  114. float GetTotalLambda() const
  115. {
  116. return mTotalLambda;
  117. }
  118. /// Iteratively update the position constraint. Makes sure C(...) == 0.
  119. /// @param ioBody1 The first body that this constraint is attached to
  120. /// @param ioBody2 The second body that this constraint is attached to
  121. /// @param inC Value of the constraint equation (C)
  122. /// @param inBaumgarte Baumgarte constant (fraction of the error to correct)
  123. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, float inC, float inBaumgarte) const
  124. {
  125. // Only apply position constraint when the constraint is hard, otherwise the velocity bias will fix the constraint
  126. if (inC != 0.0f)
  127. {
  128. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  129. //
  130. // lambda = -K^-1 * beta / dt * C
  131. //
  132. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  133. float lambda = -mEffectiveMass * inBaumgarte * inC;
  134. // Directly integrate velocity change for one time step
  135. //
  136. // Euler velocity integration:
  137. // dv = M^-1 P
  138. //
  139. // Impulse:
  140. // P = J^T lambda
  141. //
  142. // Euler position integration:
  143. // x' = x + dv * dt
  144. //
  145. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  146. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  147. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  148. // integrate + a position integrate and then discard the velocity change.
  149. if (ioBody1.IsDynamic())
  150. ioBody1.AddRotationStep(lambda * mInvI1_A);
  151. if (ioBody2.IsDynamic())
  152. ioBody2.AddRotationStep(lambda * mInvI2_B);
  153. return true;
  154. }
  155. return false;
  156. }
  157. /// Save state of this constraint part
  158. void SaveState(StateRecorder &inStream) const
  159. {
  160. inStream.Write(mTotalLambda);
  161. }
  162. /// Restore state of this constraint part
  163. void RestoreState(StateRecorder &inStream)
  164. {
  165. inStream.Read(mTotalLambda);
  166. }
  167. private:
  168. Vec3 mInvI1_A;
  169. Vec3 mInvI2_B;
  170. float mEffectiveMass = 0.0f;
  171. float mTotalLambda = 0.0f;
  172. };
  173. JPH_NAMESPACE_END