MotionProperties.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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/Geometry/Sphere.h>
  6. #include <Jolt/Physics/Body/MotionQuality.h>
  7. #include <Jolt/Physics/Body/BodyAccess.h>
  8. #include <Jolt/Physics/Body/MotionType.h>
  9. #include <Jolt/Physics/Body/MassProperties.h>
  10. #include <Jolt/Physics/DeterminismLog.h>
  11. JPH_NAMESPACE_BEGIN
  12. class StateRecorder;
  13. /// The Body class only keeps track of state for static bodies, the MotionProperties class keeps the additional state needed for a moving Body. It has a 1-on-1 relationship with the body.
  14. class MotionProperties
  15. {
  16. public:
  17. JPH_OVERRIDE_NEW_DELETE
  18. /// Motion quality, or how well it detects collisions when it has a high velocity
  19. EMotionQuality GetMotionQuality() const { return mMotionQuality; }
  20. /// Get world space linear velocity of the center of mass
  21. inline Vec3 GetLinearVelocity() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::Read)); return mLinearVelocity; }
  22. /// Set world space linear velocity of the center of mass
  23. void SetLinearVelocity(Vec3Arg inLinearVelocity) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::ReadWrite)); JPH_ASSERT(inLinearVelocity.Length() <= mMaxLinearVelocity); mLinearVelocity = inLinearVelocity; }
  24. /// Set world space linear velocity of the center of mass, will make sure the value is clamped against the maximum linear velocity
  25. void SetLinearVelocityClamped(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; ClampLinearVelocity(); }
  26. /// Get world space angular velocity of the center of mass
  27. inline Vec3 GetAngularVelocity() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::Read)); return mAngularVelocity; }
  28. /// Set world space angular velocity of the center of mass
  29. void SetAngularVelocity(Vec3Arg inAngularVelocity) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::ReadWrite)); JPH_ASSERT(inAngularVelocity.Length() <= mMaxAngularVelocity); mAngularVelocity = inAngularVelocity; }
  30. /// Set world space angular velocity of the center of mass, will make sure the value is clamped against the maximum angular velocity
  31. void SetAngularVelocityClamped(Vec3Arg inAngularVelocity) { mAngularVelocity = inAngularVelocity; ClampAngularVelocity(); }
  32. /// Set velocity of body such that it will be rotate/translate by inDeltaPosition/Rotation in inDeltaTime seconds.
  33. inline void MoveKinematic(Vec3Arg inDeltaPosition, QuatArg inDeltaRotation, float inDeltaTime);
  34. ///@name Velocity limits
  35. ///@{
  36. /// Maximum linear velocity that a body can achieve. Used to prevent the system from exploding.
  37. inline float GetMaxLinearVelocity() const { return mMaxLinearVelocity; }
  38. inline void SetMaxLinearVelocity(float inLinearVelocity) { JPH_ASSERT(inLinearVelocity >= 0.0f); mMaxLinearVelocity = inLinearVelocity; }
  39. /// Maximum angular velocity that a body can achieve. Used to prevent the system from exploding.
  40. inline float GetMaxAngularVelocity() const { return mMaxAngularVelocity; }
  41. inline void SetMaxAngularVelocity(float inAngularVelocity) { JPH_ASSERT(inAngularVelocity >= 0.0f); mMaxAngularVelocity = inAngularVelocity; }
  42. ///@}
  43. /// Clamp velocity according to limit
  44. inline void ClampLinearVelocity();
  45. inline void ClampAngularVelocity();
  46. /// Get linear damping: dv/dt = -c * v. c must be between 0 and 1 but is usually close to 0.
  47. inline float GetLinearDamping() const { return mLinearDamping; }
  48. void SetLinearDamping(float inLinearDamping) { JPH_ASSERT(inLinearDamping >= 0.0f); mLinearDamping = inLinearDamping; }
  49. /// Get angular damping: dw/dt = -c * w. c must be between 0 and 1 but is usually close to 0.
  50. inline float GetAngularDamping() const { return mAngularDamping; }
  51. void SetAngularDamping(float inAngularDamping) { JPH_ASSERT(inAngularDamping >= 0.0f); mAngularDamping = inAngularDamping; }
  52. /// Get gravity factor (1 = normal gravity, 0 = no gravity)
  53. inline float GetGravityFactor() const { return mGravityFactor; }
  54. void SetGravityFactor(float inGravityFactor) { mGravityFactor = inGravityFactor; }
  55. /// Set the mass and inertia tensor
  56. inline void SetMassProperties(const MassProperties &inMassProperties);
  57. /// Get inverse mass (1 / mass). Should only be called on a dynamic object (static or kinematic bodies have infinite mass so should be treated as 1 / mass = 0)
  58. inline float GetInverseMass() const { JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic); return mInvMass; }
  59. inline float GetInverseMassUnchecked() const { return mInvMass; }
  60. /// Set the inverse mass (1 / mass).
  61. /// Note that mass and inertia are linearly related (e.g. inertia of a sphere with mass m and radius r is \f$2/5 \: m \: r^2\f$).
  62. /// If you change mass, inertia should probably change as well. See MassProperties::ScaleToMass.
  63. void SetInverseMass(float inInverseMass) { mInvMass = inInverseMass; }
  64. /// Diagonal of inverse inertia matrix: D. Should only be called on a dynamic object (static or kinematic bodies have infinite mass so should be treated as D = 0)
  65. inline Vec3 GetInverseInertiaDiagonal() const { JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic); return mInvInertiaDiagonal; }
  66. /// Rotation (R) that takes inverse inertia diagonal to local space: \f$I_{body}^{-1} = R \: D \: R^{-1}\f$
  67. inline Quat GetInertiaRotation() const { return mInertiaRotation; }
  68. /// Set the inverse inertia tensor in local space by setting the diagonal and the rotation: \f$I_{body}^{-1} = R \: D \: R^{-1}\f$.
  69. /// Note that mass and inertia are linearly related (e.g. inertia of a sphere with mass m and radius r is \f$2/5 \: m \: r^2\f$).
  70. /// If you change inertia, mass should probably change as well. See MassProperties::ScaleToMass.
  71. void SetInverseInertia(Vec3Arg inDiagonal, QuatArg inRot) { mInvInertiaDiagonal = inDiagonal; mInertiaRotation = inRot; }
  72. /// Get inverse inertia matrix (\f$I_{body}^{-1}\f$). Will be a matrix of zeros for a static or kinematic object.
  73. inline Mat44 GetLocalSpaceInverseInertia() const;
  74. /// Same as GetLocalSpaceInverseInertia() but doesn't check if the body is dynamic
  75. inline Mat44 GetLocalSpaceInverseInertiaUnchecked() const;
  76. /// Get inverse inertia matrix (\f$I^{-1}\f$) for a given object rotation (translation will be ignored). Zero if object is static or kinematic.
  77. inline Mat44 GetInverseInertiaForRotation(Mat44Arg inRotation) const;
  78. /// Multiply a vector with the inverse world space inertia tensor (\f$I_{world}^{-1}\f$). Zero if object is static or kinematic.
  79. JPH_INLINE Vec3 MultiplyWorldSpaceInverseInertiaByVector(QuatArg inBodyRotation, Vec3Arg inV) const;
  80. /// Velocity of point inPoint (in center of mass space, e.g. on the surface of the body) of the body (unit: m/s)
  81. JPH_INLINE Vec3 GetPointVelocityCOM(Vec3Arg inPointRelativeToCOM) const { return mLinearVelocity + mAngularVelocity.Cross(inPointRelativeToCOM); }
  82. // Get the total amount of force applied to the center of mass this time step (through Body::AddForce calls). Note that it will reset to zero after PhysicsSimulation::Update.
  83. JPH_INLINE Vec3 GetAccumulatedForce() const { return Vec3::sLoadFloat3Unsafe(mForce); }
  84. // Get the total amount of torque applied to the center of mass this time step (through Body::AddForce/Body::AddTorque calls). Note that it will reset to zero after PhysicsSimulation::Update.
  85. JPH_INLINE Vec3 GetAccumulatedTorque() const { return Vec3::sLoadFloat3Unsafe(mTorque); }
  86. ////////////////////////////////////////////////////////////
  87. // FUNCTIONS BELOW THIS LINE ARE FOR INTERNAL USE ONLY
  88. ////////////////////////////////////////////////////////////
  89. ///@name Update linear and angular velocity (used during constraint solving)
  90. ///@{
  91. inline void AddLinearVelocityStep(Vec3Arg inLinearVelocityChange) { JPH_DET_LOG("AddLinearVelocityStep: " << inLinearVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::ReadWrite)); mLinearVelocity += inLinearVelocityChange; JPH_ASSERT(!mLinearVelocity.IsNaN()); }
  92. inline void SubLinearVelocityStep(Vec3Arg inLinearVelocityChange) { JPH_DET_LOG("SubLinearVelocityStep: " << inLinearVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::ReadWrite)); mLinearVelocity -= inLinearVelocityChange; JPH_ASSERT(!mLinearVelocity.IsNaN()); }
  93. inline void AddAngularVelocityStep(Vec3Arg inAngularVelocityChange) { JPH_DET_LOG("AddAngularVelocityStep: " << inAngularVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::ReadWrite)); mAngularVelocity += inAngularVelocityChange; JPH_ASSERT(!mAngularVelocity.IsNaN()); }
  94. inline void SubAngularVelocityStep(Vec3Arg inAngularVelocityChange) { JPH_DET_LOG("SubAngularVelocityStep: " << inAngularVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess, BodyAccess::EAccess::ReadWrite)); mAngularVelocity -= inAngularVelocityChange; JPH_ASSERT(!mAngularVelocity.IsNaN()); }
  95. ///@}
  96. /// Apply all accumulated forces, torques and drag (should only be called by the PhysicsSystem)
  97. inline void ApplyForceTorqueAndDragInternal(QuatArg inBodyRotation, Vec3Arg inGravity, float inDeltaTime);
  98. /// At the end of a simulation update the forces and torques need to be reset for the next frame
  99. inline void ResetForceAndTorqueInternal() { mForce = Float3(0, 0, 0); mTorque = Float3(0, 0, 0); }
  100. /// Access to the island index
  101. uint32 GetIslandIndexInternal() const { return mIslandIndex; }
  102. void SetIslandIndexInternal(uint32 inIndex) { mIslandIndex = inIndex; }
  103. /// Access to the index in the active bodies array
  104. uint32 GetIndexInActiveBodiesInternal() const { return mIndexInActiveBodies; }
  105. #ifdef JPH_DOUBLE_PRECISION
  106. inline DVec3 GetSleepTestOffset() const { return DVec3::sLoadDouble3Unsafe(mSleepTestOffset); }
  107. #endif // JPH_DOUBLE_PRECISION
  108. /// Reset spheres to center around inPoints with radius 0
  109. inline void ResetSleepTestSpheres(const RVec3 *inPoints);
  110. /// Saving state for replay
  111. void SaveState(StateRecorder &inStream) const;
  112. /// Restoring state for replay
  113. void RestoreState(StateRecorder &inStream);
  114. private:
  115. friend class BodyManager;
  116. friend class Body;
  117. // 1st cache line
  118. // 16 byte aligned
  119. Vec3 mLinearVelocity { Vec3::sZero() }; ///< World space linear velocity of the center of mass (m/s)
  120. Vec3 mAngularVelocity { Vec3::sZero() }; ///< World space angular velocity (rad/s)
  121. Vec3 mInvInertiaDiagonal; ///< Diagonal of inverse inertia matrix: D
  122. Quat mInertiaRotation; ///< Rotation (R) that takes inverse inertia diagonal to local space: Ibody^-1 = R * D * R^-1
  123. // 2nd cache line
  124. // 4 byte aligned
  125. Float3 mForce { 0, 0, 0 }; ///< Accumulated world space force (N). Note loaded through intrinsics so ensure that the 4 bytes after this are readable!
  126. Float3 mTorque { 0, 0, 0 }; ///< Accumulated world space torque (N m). Note loaded through intrinsics so ensure that the 4 bytes after this are readable!
  127. float mInvMass; ///< Inverse mass of the object (1/kg)
  128. float mLinearDamping; ///< Linear damping: dv/dt = -c * v. c must be between 0 and 1 but is usually close to 0.
  129. float mAngularDamping; ///< Angular damping: dw/dt = -c * w. c must be between 0 and 1 but is usually close to 0.
  130. float mMaxLinearVelocity; ///< Maximum linear velocity that this body can reach (m/s)
  131. float mMaxAngularVelocity; ///< Maximum angular velocity that this body can reach (rad/s)
  132. float mGravityFactor; ///< Factor to multiply gravity with
  133. uint32 mIndexInActiveBodies; ///< If the body is active, this is the index in the active body list or cInactiveIndex if it is not active
  134. uint32 mIslandIndex; ///< Index of the island that this body is part of, when the body has not yet been updated or is not active this is cInactiveIndex
  135. // 1 byte aligned
  136. EMotionQuality mMotionQuality; ///< Motion quality, or how well it detects collisions when it has a high velocity
  137. bool mAllowSleeping; ///< If this body can go to sleep
  138. // 3rd cache line (least frequently used)
  139. // 4 byte aligned (or 8 byte if running in double precision)
  140. #ifdef JPH_DOUBLE_PRECISION
  141. Double3 mSleepTestOffset; ///< mSleepTestSpheres are relative to this offset to prevent floating point inaccuracies. Warning: Loaded using sLoadDouble3Unsafe which will read 8 extra bytes.
  142. #endif // JPH_DOUBLE_PRECISION
  143. Sphere mSleepTestSpheres[3]; ///< Measure motion for 3 points on the body to see if it is resting: COM, COM + largest bounding box axis, COM + second largest bounding box axis
  144. float mSleepTestTimer; ///< How long this body has been within the movement tolerance
  145. #ifdef JPH_ENABLE_ASSERTS
  146. EMotionType mCachedMotionType; ///< Copied from Body::mMotionType and cached for asserting purposes
  147. #endif
  148. };
  149. JPH_NAMESPACE_END
  150. #include "MotionProperties.inl"