RotationEulerConstraintPart.h 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. /// Constrains rotation around all axis so that only translation is allowed
  9. ///
  10. /// Based on: "Constraints Derivation for Rigid Body Simulation in 3D" - Daniel Chappuis, section 2.5.1
  11. ///
  12. /// Constraint equation (eq 129):
  13. ///
  14. /// \f[C = \begin{bmatrix}\Delta\theta_x, \Delta\theta_y, \Delta\theta_z\end{bmatrix}\f]
  15. ///
  16. /// Jacobian (eq 131):
  17. ///
  18. /// \f[J = \begin{bmatrix}0 & -E & 0 & E\end{bmatrix}\f]
  19. ///
  20. /// Used terms (here and below, everything in world space):\n
  21. /// delta_theta_* = difference in rotation between initial rotation of bodyies 1 and 2.\n
  22. /// x1, x2 = center of mass for the bodies.\n
  23. /// v = [v1, w1, v2, w2].\n
  24. /// v1, v2 = linear velocity of body 1 and 2.\n
  25. /// w1, w2 = angular velocity of body 1 and 2.\n
  26. /// M = mass matrix, a diagonal matrix of the mass and inertia with diagonal [m1, I1, m2, I2].\n
  27. /// \f$K^{-1} = \left( J M^{-1} J^T \right)^{-1}\f$ = effective mass.\n
  28. /// b = velocity bias.\n
  29. /// \f$\beta\f$ = baumgarte constant.\n
  30. /// E = identity matrix.\n
  31. class RotationEulerConstraintPart
  32. {
  33. private:
  34. /// Internal helper function to update velocities of bodies after Lagrange multiplier is calculated
  35. JPH_INLINE bool ApplyVelocityStep(Body &ioBody1, Body &ioBody2, Vec3Arg inLambda) const
  36. {
  37. // Apply impulse if delta is not zero
  38. if (inLambda != Vec3::sZero())
  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(mInvI1.Multiply3x3(inLambda));
  49. if (ioBody2.IsDynamic())
  50. ioBody2.GetMotionProperties()->AddAngularVelocityStep(mInvI2.Multiply3x3(inLambda));
  51. return true;
  52. }
  53. return false;
  54. }
  55. public:
  56. /// Return inverse of initial rotation from body 1 to body 2 in body 1 space
  57. static Quat sGetInvInitialOrientation(const Body &inBody1, const Body &inBody2)
  58. {
  59. // q20 = q10 r0
  60. // <=> r0 = q10^-1 q20
  61. // <=> r0^-1 = q20^-1 q10
  62. //
  63. // where:
  64. //
  65. // q20 = initial orientation of body 2
  66. // q10 = initial orientation of body 1
  67. // r0 = initial rotation rotation from body 1 to body 2
  68. return inBody2.GetRotation().Conjugated() * inBody1.GetRotation();
  69. }
  70. /// @brief Return inverse of initial rotation from body 1 to body 2 in body 1 space
  71. /// @param inAxisX1 Reference axis X for body 1
  72. /// @param inAxisY1 Reference axis Y for body 1
  73. /// @param inAxisX2 Reference axis X for body 2
  74. /// @param inAxisY2 Reference axis Y for body 2
  75. static Quat sGetInvInitialOrientationXY(Vec3Arg inAxisX1, Vec3Arg inAxisY1, Vec3Arg inAxisX2, Vec3Arg inAxisY2)
  76. {
  77. // Store inverse of initial rotation from body 1 to body 2 in body 1 space:
  78. //
  79. // q20 = q10 r0
  80. // <=> r0 = q10^-1 q20
  81. // <=> r0^-1 = q20^-1 q10
  82. //
  83. // where:
  84. //
  85. // q10, q20 = world space initial orientation of body 1 and 2
  86. // r0 = initial rotation rotation from body 1 to body 2 in local space of body 1
  87. //
  88. // We can also write this in terms of the constraint matrices:
  89. //
  90. // q20 c2 = q10 c1
  91. // <=> q20 = q10 c1 c2^-1
  92. // => r0 = c1 c2^-1
  93. // <=> r0^-1 = c2 c1^-1
  94. //
  95. // where:
  96. //
  97. // c1, c2 = matrix that takes us from body 1 and 2 COM to constraint space 1 and 2
  98. if (inAxisX1 == inAxisX2 && inAxisY1 == inAxisY2)
  99. {
  100. // Axis are the same -> identity transform
  101. return Quat::sIdentity();
  102. }
  103. else
  104. {
  105. Mat44 constraint1(Vec4(inAxisX1, 0), Vec4(inAxisY1, 0), Vec4(inAxisX1.Cross(inAxisY1), 0), Vec4(0, 0, 0, 1));
  106. Mat44 constraint2(Vec4(inAxisX2, 0), Vec4(inAxisY2, 0), Vec4(inAxisX2.Cross(inAxisY2), 0), Vec4(0, 0, 0, 1));
  107. return constraint2.GetQuaternion() * constraint1.GetQuaternion().Conjugated();
  108. }
  109. }
  110. /// @brief Return inverse of initial rotation from body 1 to body 2 in body 1 space
  111. /// @param inAxisX1 Reference axis X for body 1
  112. /// @param inAxisZ1 Reference axis Z for body 1
  113. /// @param inAxisX2 Reference axis X for body 2
  114. /// @param inAxisZ2 Reference axis Z for body 2
  115. static Quat sGetInvInitialOrientationXZ(Vec3Arg inAxisX1, Vec3Arg inAxisZ1, Vec3Arg inAxisX2, Vec3Arg inAxisZ2)
  116. {
  117. // See comment at sGetInvInitialOrientationXY
  118. if (inAxisX1 == inAxisX2 && inAxisZ1 == inAxisZ2)
  119. {
  120. return Quat::sIdentity();
  121. }
  122. else
  123. {
  124. Mat44 constraint1(Vec4(inAxisX1, 0), Vec4(inAxisZ1.Cross(inAxisX1), 0), Vec4(inAxisZ1, 0), Vec4(0, 0, 0, 1));
  125. Mat44 constraint2(Vec4(inAxisX2, 0), Vec4(inAxisZ2.Cross(inAxisX2), 0), Vec4(inAxisZ2, 0), Vec4(0, 0, 0, 1));
  126. return constraint2.GetQuaternion() * constraint1.GetQuaternion().Conjugated();
  127. }
  128. }
  129. /// Calculate properties used during the functions below
  130. inline void CalculateConstraintProperties(const Body &inBody1, Mat44Arg inRotation1, const Body &inBody2, Mat44Arg inRotation2)
  131. {
  132. // Calculate properties used during constraint solving
  133. mInvI1 = inBody1.IsDynamic()? inBody1.GetMotionProperties()->GetInverseInertiaForRotation(inRotation1) : Mat44::sZero();
  134. mInvI2 = inBody2.IsDynamic()? inBody2.GetMotionProperties()->GetInverseInertiaForRotation(inRotation2) : Mat44::sZero();
  135. // Calculate effective mass: K^-1 = (J M^-1 J^T)^-1
  136. if (!mEffectiveMass.SetInversed3x3(mInvI1 + mInvI2))
  137. Deactivate();
  138. }
  139. /// Deactivate this constraint
  140. inline void Deactivate()
  141. {
  142. mEffectiveMass = Mat44::sZero();
  143. mTotalLambda = Vec3::sZero();
  144. }
  145. /// Check if constraint is active
  146. inline bool IsActive() const
  147. {
  148. return mEffectiveMass(3, 3) != 0.0f;
  149. }
  150. /// Must be called from the WarmStartVelocityConstraint call to apply the previous frame's impulses
  151. inline void WarmStart(Body &ioBody1, Body &ioBody2, float inWarmStartImpulseRatio)
  152. {
  153. mTotalLambda *= inWarmStartImpulseRatio;
  154. ApplyVelocityStep(ioBody1, ioBody2, mTotalLambda);
  155. }
  156. /// Iteratively update the velocity constraint. Makes sure d/dt C(...) = 0, where C is the constraint equation.
  157. inline bool SolveVelocityConstraint(Body &ioBody1, Body &ioBody2)
  158. {
  159. // Calculate lagrange multiplier:
  160. //
  161. // lambda = -K^-1 (J v + b)
  162. Vec3 lambda = mEffectiveMass.Multiply3x3(ioBody1.GetAngularVelocity() - ioBody2.GetAngularVelocity());
  163. mTotalLambda += lambda;
  164. return ApplyVelocityStep(ioBody1, ioBody2, lambda);
  165. }
  166. /// Iteratively update the position constraint. Makes sure C(...) = 0.
  167. inline bool SolvePositionConstraint(Body &ioBody1, Body &ioBody2, QuatArg inInvInitialOrientation, float inBaumgarte) const
  168. {
  169. // Calculate difference in rotation
  170. //
  171. // The rotation should be:
  172. //
  173. // q2 = q1 r0
  174. //
  175. // But because of drift the actual rotation is
  176. //
  177. // q2 = diff q1 r0
  178. // <=> diff = q2 r0^-1 q1^-1
  179. //
  180. // Where:
  181. // q1 = current rotation of body 1
  182. // q2 = current rotation of body 2
  183. // diff = error that needs to be reduced to zero
  184. Quat diff = ioBody2.GetRotation() * inInvInitialOrientation * ioBody1.GetRotation().Conjugated();
  185. // A quaternion can be seen as:
  186. //
  187. // q = [sin(theta / 2) * v, cos(theta/2)]
  188. //
  189. // Where:
  190. // v = rotation vector
  191. // theta = rotation angle
  192. //
  193. // If we assume theta is small (error is small) then sin(x) = x so an approximation of the error angles is:
  194. Vec3 error = 2.0f * diff.EnsureWPositive().GetXYZ();
  195. if (error != Vec3::sZero())
  196. {
  197. // Calculate lagrange multiplier (lambda) for Baumgarte stabilization:
  198. //
  199. // lambda = -K^-1 * beta / dt * C
  200. //
  201. // We should divide by inDeltaTime, but we should multiply by inDeltaTime in the Euler step below so they're cancelled out
  202. Vec3 lambda = -inBaumgarte * mEffectiveMass * error;
  203. // Directly integrate velocity change for one time step
  204. //
  205. // Euler velocity integration:
  206. // dv = M^-1 P
  207. //
  208. // Impulse:
  209. // P = J^T lambda
  210. //
  211. // Euler position integration:
  212. // x' = x + dv * dt
  213. //
  214. // Note we don't accumulate velocities for the stabilization. This is using the approach described in 'Modeling and
  215. // Solving Constraints' by Erin Catto presented at GDC 2007. On slide 78 it is suggested to split up the Baumgarte
  216. // stabilization for positional drift so that it does not actually add to the momentum. We combine an Euler velocity
  217. // integrate + a position integrate and then discard the velocity change.
  218. if (ioBody1.IsDynamic())
  219. ioBody1.SubRotationStep(mInvI1.Multiply3x3(lambda));
  220. if (ioBody2.IsDynamic())
  221. ioBody2.AddRotationStep(mInvI2.Multiply3x3(lambda));
  222. return true;
  223. }
  224. return false;
  225. }
  226. /// Return lagrange multiplier
  227. Vec3 GetTotalLambda() const
  228. {
  229. return mTotalLambda;
  230. }
  231. /// Save state of this constraint part
  232. void SaveState(StateRecorder &inStream) const
  233. {
  234. inStream.Write(mTotalLambda);
  235. }
  236. /// Restore state of this constraint part
  237. void RestoreState(StateRecorder &inStream)
  238. {
  239. inStream.Read(mTotalLambda);
  240. }
  241. private:
  242. Mat44 mInvI1;
  243. Mat44 mInvI2;
  244. Mat44 mEffectiveMass;
  245. Vec3 mTotalLambda { Vec3::sZero() };
  246. };
  247. JPH_NAMESPACE_END