RotationQuatConstraintPart.h 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. /// Quaternion based constraint that constrains rotation around all axis so that only translation is allowed.
  9. ///
  10. /// NOTE: This constraint part is more expensive than the RotationEulerConstraintPart and slightly more correct since
  11. /// RotationEulerConstraintPart::SolvePositionConstraint contains an approximation. In practice the difference
  12. /// is small, so the RotationEulerConstraintPart is probably the better choice.
  13. ///
  14. /// Rotation is fixed between bodies like this:
  15. ///
  16. /// q2 = q1 r0
  17. ///
  18. /// Where:
  19. /// q1, q2 = world space quaternions representing rotation of body 1 and 2.
  20. /// r0 = initial rotation between bodies in local space of body 1, this can be calculated by:
  21. ///
  22. /// q20 = q10 r0
  23. /// <=> r0 = q10^* q20
  24. ///
  25. /// Where:
  26. /// q10, q20 = initial world space rotations of body 1 and 2.
  27. /// q10^* = conjugate of quaternion q10 (which is the same as the inverse for a unit quaternion)
  28. ///
  29. /// We exclusively use the conjugate below:
  30. ///
  31. /// r0^* = q20^* q10
  32. ///
  33. /// The error in the rotation is (in local space of body 1):
  34. ///
  35. /// q2 = q1 error r0
  36. /// <=> error = q1^* q2 r0^*
  37. ///
  38. /// The imaginary part of the quaternion represents the rotation axis * sin(angle / 2). The real part of the quaternion
  39. /// does not add any additional information (we know the quaternion in normalized) and we're removing 3 degrees of freedom
  40. /// so we want 3 parameters. Therefore we define the constraint equation like:
  41. ///
  42. /// C = A q1^* q2 r0^* = 0
  43. ///
  44. /// Where (if you write a quaternion as [real-part, i-part, j-part, k-part]):
  45. ///
  46. /// [0, 1, 0, 0]
  47. /// A = [0, 0, 1, 0]
  48. /// [0, 0, 0, 1]
  49. ///
  50. /// or in our case since we store a quaternion like [i-part, j-part, k-part, real-part]:
  51. ///
  52. /// [1, 0, 0, 0]
  53. /// A = [0, 1, 0, 0]
  54. /// [0, 0, 1, 0]
  55. ///
  56. /// Time derivative:
  57. ///
  58. /// d/dt C = A (q1^* d/dt(q2) + d/dt(q1^*) q2) r0^*
  59. /// = A (q1^* (1/2 W2 q2) + (1/2 W1 q1)^* q2) r0^*
  60. /// = 1/2 A (q1^* W2 q2 + q1^* W1^* q2) r0^*
  61. /// = 1/2 A (q1^* W2 q2 - q1^* W1 * q2) r0^*
  62. /// = 1/2 A ML(q1^*) MR(q2 r0^*) (W2 - W1)
  63. /// = 1/2 A ML(q1^*) MR(q2 r0^*) A^T (w2 - w1)
  64. ///
  65. /// Where:
  66. /// W1 = [0, w1], W2 = [0, w2] (converting angular velocity to imaginary part of quaternion).
  67. /// w1, w2 = angular velocity of body 1 and 2.
  68. /// d/dt(q) = 1/2 W q (time derivative of a quaternion).
  69. /// W^* = -W (conjugate negates angular velocity as quaternion).
  70. /// ML(q): 4x4 matrix so that q * p = ML(q) * p, where q and p are quaternions.
  71. /// MR(p): 4x4 matrix so that q * p = MR(p) * q, where q and p are quaternions.
  72. /// A^T: Transpose of A.
  73. ///
  74. /// Jacobian:
  75. ///
  76. /// J = [0, -1/2 A ML(q1^*) MR(q2 r0^*) A^T, 0, 1/2 A ML(q1^*) MR(q2 r0^*) A^T]
  77. /// = [0, -JP, 0, JP]
  78. ///
  79. /// Suggested reading:
  80. /// - 3D Constraint Derivations for Impulse Solvers - Marijn Tamis
  81. /// - Game Physics Pearls - Section 9 - Quaternion Based Constraints - Claude Lacoursiere
  82. class RotationQuatConstraintPart
  83. {
  84. private:
  85. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  86. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
  87. {
  88. // Apply impulse if delta is not zero
  89. if (inLambda != Vec3::sZero())
  90. {
  91. // Calculate velocity change due to constraint
  92. //
  93. // Impulse:
  94. // P = J^T lambda
  95. //
  96. // Euler velocity integration:
  97. // v' = v + M^-1 P
  98. if (ioBody1.IsDynamic())
  99. ioBody1.GetMotionProperties()->SubAngularVelocityStep(mInvI1_JPT.Multiply3x3(inLambda));
  100. if (ioBody2.IsDynamic())
  101. ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2_JPT.Multiply3x3(inLambda));
  102. return true;
  103. }
  104. return false;
  105. }
  106. public:
  107. /// Return inverse of initial rotation from body 1 to body 2 in body 1 space
  108. static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)
  109. {
  110. // q20 = q10 r0
  111. // <=> r0 = q10^-1 q20
  112. // <=> r0^-1 = q20^-1 q10
  113. //
  114. // where:
  115. //
  116. // q20 = initial orientation of body 2
  117. // q10 = initial orientation of body 1
  118. // r0 = initial rotation rotation from body 1 to body 2
  119. return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();
  120. }
  121. /// Calculate properties used during the functions below
  122. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2, QuatArg inInvInitialOrientation)
  123. {
  124. // Calculate: JP = 1/2 A ML(q1^*) MR(q2 r0^*) A^T
  125. Mat44 jp = (Mat44::sQuatLeftMultiply(0.5f * inBody1.GetRotation().Conjugated()) * Mat44::sQuatRightMultiply(inBody2.GetRotation() * inInvInitialOrientation)).GetRotationSafe();
  126. // Calculate properties used during constraint solving
  127. Mat44 invi1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  128. Mat44 invi2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  129. mInvI1_JPT = invi1.Multiply3x3RightTransposed(jp);
  130. mInvI2_JPT = invi2.Multiply3x3RightTransposed(jp);
  131. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  132. // = (JP * I1^-1 * JP^T + JP * I2^-1 * JP^T)^-1
  133. // = (JP * (I1^-1 + I2^-1) * JP^T)^-1
  134. if (!mEffectiveMass.SetInversed3x3(jp.Multiply3x3(invi1 + invi2).Multiply3x3RightTransposed(jp)))
  135. Deactivate();
  136. else
  137. mEffectiveMass_JP = mEffectiveMass.Multiply3x3(jp);
  138. }
  139. /// Deactivate this constraint
  140. inline void Deactivate()
  141. {
  142. mEffectiveMass = Mat44::sZero();
  143. mEffectiveMass_JP = Mat44::sZero();
  144. mTotalLambda = Vec3::sZero();
  145. }
  146. /// Check if constraint is active
  147. inline bool IsActive() const
  148. {
  149. return mEffectiveMass(3, 3) != 0.0f;
  150. }
  151. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  152. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  153. {
  154. mTotalLambda *= inWarmStartImpulseRatio;
  155. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  156. }
  157. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  158. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  159. {
  160. // Calculate lagrange multiplier:
  161. //
  162. // lambda = -K^-1 (J v + b)
  163. Vec3 lambda = mEffectiveMass_JP.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
  164. mTotalLambda += lambda;
  165. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  166. }
  167. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  168. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
  169. {
  170. // Calculate constraint equation
  171. Vec3 c = (ioBody1.GetRotation().Conjugated() * ioBody2.GetRotation() * inInvInitialOrientation).GetXYZ();
  172. if (c != Vec3::sZero())
  173. {
  174. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  175. //
  176. // lambda = -K^-1 * beta / dt * C
  177. //
  178. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  179. Vec3 lambda = -inBaumgarte * mEffectiveMass * c;
  180. // Directly integrate velocity change for one time step
  181. //
  182. // Euler velocity integration:
  183. // dv = M^-1 P
  184. //
  185. // Impulse:
  186. // P = J^T lambda
  187. //
  188. // Euler position integration:
  189. // x' = x + dv * dt
  190. //
  191. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  192. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  193. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  194. // integrate + a position integrate and then discard the velocity change.
  195. if (ioBody1.IsDynamic())
  196. ioBody1.SubRotationStep(mInvI1_JPT.Multiply3x3(lambda));
  197. if (ioBody2.IsDynamic())
  198. ioBody2.AddRotationStep(mInvI2_JPT.Multiply3x3(lambda));
  199. return true;
  200. }
  201. return false;
  202. }
  203. /// Return lagrange multiplier
  204. Vec3 GetTotalLambda() const
  205. {
  206. return mTotalLambda;
  207. }
  208. /// Save state of this constraint part
  209. void SaveState(StateRecorder &inStream) const
  210. {
  211. inStream.Write(mTotalLambda);
  212. }
  213. /// Restore state of this constraint part
  214. void RestoreState(StateRecorder &inStream)
  215. {
  216. inStream.Read(mTotalLambda);
  217. }
  218. private:
  219. Mat44 mInvI1_JPT;
  220. Mat44 mInvI2_JPT;
  221. Mat44 mEffectiveMass;
  222. Mat44 mEffectiveMass_JP;
  223. Vec3 mTotalLambda { Vec3::sZero() };
  224. };
  225. JPH_NAMESPACE_END