Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Body/MotionProperties.h
9912 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Geometry/Sphere.h>7#include <Jolt/Physics/Body/AllowedDOFs.h>8#include <Jolt/Physics/Body/MotionQuality.h>9#include <Jolt/Physics/Body/BodyAccess.h>10#include <Jolt/Physics/Body/MotionType.h>11#include <Jolt/Physics/Body/BodyType.h>12#include <Jolt/Physics/Body/MassProperties.h>13#include <Jolt/Physics/DeterminismLog.h>1415JPH_NAMESPACE_BEGIN1617class StateRecorder;1819/// Enum that determines if an object can go to sleep20enum class ECanSleep21{22CannotSleep = 0, ///< Object cannot go to sleep23CanSleep = 1, ///< Object can go to sleep24};2526/// 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.27class JPH_EXPORT MotionProperties28{29public:30JPH_OVERRIDE_NEW_DELETE3132/// Motion quality, or how well it detects collisions when it has a high velocity33EMotionQuality GetMotionQuality() const { return mMotionQuality; }3435/// Get the allowed degrees of freedom that this body has (this can be changed by calling SetMassProperties)36inline EAllowedDOFs GetAllowedDOFs() const { return mAllowedDOFs; }3738/// If this body can go to sleep.39inline bool GetAllowSleeping() const { return mAllowSleeping; }4041/// Get world space linear velocity of the center of mass42inline Vec3 GetLinearVelocity() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::Read)); return mLinearVelocity; }4344/// Set world space linear velocity of the center of mass45void SetLinearVelocity(Vec3Arg inLinearVelocity) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); JPH_ASSERT(inLinearVelocity.Length() <= mMaxLinearVelocity); mLinearVelocity = LockTranslation(inLinearVelocity); }4647/// Set world space linear velocity of the center of mass, will make sure the value is clamped against the maximum linear velocity48void SetLinearVelocityClamped(Vec3Arg inLinearVelocity) { mLinearVelocity = LockTranslation(inLinearVelocity); ClampLinearVelocity(); }4950/// Get world space angular velocity of the center of mass51inline Vec3 GetAngularVelocity() const { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::Read)); return mAngularVelocity; }5253/// Set world space angular velocity of the center of mass54void SetAngularVelocity(Vec3Arg inAngularVelocity) { JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); JPH_ASSERT(inAngularVelocity.Length() <= mMaxAngularVelocity); mAngularVelocity = LockAngular(inAngularVelocity); }5556/// Set world space angular velocity of the center of mass, will make sure the value is clamped against the maximum angular velocity57void SetAngularVelocityClamped(Vec3Arg inAngularVelocity) { mAngularVelocity = LockAngular(inAngularVelocity); ClampAngularVelocity(); }5859/// Set velocity of body such that it will be rotate/translate by inDeltaPosition/Rotation in inDeltaTime seconds.60inline void MoveKinematic(Vec3Arg inDeltaPosition, QuatArg inDeltaRotation, float inDeltaTime);6162///@name Velocity limits63///@{6465/// Maximum linear velocity that a body can achieve. Used to prevent the system from exploding.66inline float GetMaxLinearVelocity() const { return mMaxLinearVelocity; }67inline void SetMaxLinearVelocity(float inLinearVelocity) { JPH_ASSERT(inLinearVelocity >= 0.0f); mMaxLinearVelocity = inLinearVelocity; }6869/// Maximum angular velocity that a body can achieve. Used to prevent the system from exploding.70inline float GetMaxAngularVelocity() const { return mMaxAngularVelocity; }71inline void SetMaxAngularVelocity(float inAngularVelocity) { JPH_ASSERT(inAngularVelocity >= 0.0f); mMaxAngularVelocity = inAngularVelocity; }72///@}7374/// Clamp velocity according to limit75inline void ClampLinearVelocity();76inline void ClampAngularVelocity();7778/// Get linear damping: dv/dt = -c * v. c must be between 0 and 1 but is usually close to 0.79inline float GetLinearDamping() const { return mLinearDamping; }80void SetLinearDamping(float inLinearDamping) { JPH_ASSERT(inLinearDamping >= 0.0f); mLinearDamping = inLinearDamping; }8182/// Get angular damping: dw/dt = -c * w. c must be between 0 and 1 but is usually close to 0.83inline float GetAngularDamping() const { return mAngularDamping; }84void SetAngularDamping(float inAngularDamping) { JPH_ASSERT(inAngularDamping >= 0.0f); mAngularDamping = inAngularDamping; }8586/// Get gravity factor (1 = normal gravity, 0 = no gravity)87inline float GetGravityFactor() const { return mGravityFactor; }88void SetGravityFactor(float inGravityFactor) { mGravityFactor = inGravityFactor; }8990/// Set the mass and inertia tensor91void SetMassProperties(EAllowedDOFs inAllowedDOFs, const MassProperties &inMassProperties);9293/// 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)94inline float GetInverseMass() const { JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic); return mInvMass; }95inline float GetInverseMassUnchecked() const { return mInvMass; }9697/// Set the inverse mass (1 / mass).98/// 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$).99/// If you change mass, inertia should probably change as well. You can use ScaleToMass to update mass and inertia at the same time.100/// If all your translation degrees of freedom are restricted, make sure this is zero (see EAllowedDOFs).101void SetInverseMass(float inInverseMass) { mInvMass = inInverseMass; }102103/// 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)104inline Vec3 GetInverseInertiaDiagonal() const { JPH_ASSERT(mCachedMotionType == EMotionType::Dynamic); return mInvInertiaDiagonal; }105106/// Rotation (R) that takes inverse inertia diagonal to local space: \f$I_{body}^{-1} = R \: D \: R^{-1}\f$107inline Quat GetInertiaRotation() const { return mInertiaRotation; }108109/// Set the inverse inertia tensor in local space by setting the diagonal and the rotation: \f$I_{body}^{-1} = R \: D \: R^{-1}\f$.110/// 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$).111/// If you change inertia, mass should probably change as well. You can use ScaleToMass to update mass and inertia at the same time.112/// If all your rotation degrees of freedom are restricted, make sure this is zero (see EAllowedDOFs).113void SetInverseInertia(Vec3Arg inDiagonal, QuatArg inRot) { mInvInertiaDiagonal = inDiagonal; mInertiaRotation = inRot; }114115/// Sets the mass to inMass and scale the inertia tensor based on the ratio between the old and new mass.116/// Note that this only works when the current mass is finite (i.e. the body is dynamic and translational degrees of freedom are not restricted).117void ScaleToMass(float inMass);118119/// Get inverse inertia matrix (\f$I_{body}^{-1}\f$). Will be a matrix of zeros for a static or kinematic object.120inline Mat44 GetLocalSpaceInverseInertia() const;121122/// Same as GetLocalSpaceInverseInertia() but doesn't check if the body is dynamic123inline Mat44 GetLocalSpaceInverseInertiaUnchecked() const;124125/// Get inverse inertia matrix (\f$I^{-1}\f$) for a given object rotation (translation will be ignored). Zero if object is static or kinematic.126inline Mat44 GetInverseInertiaForRotation(Mat44Arg inRotation) const;127128/// Multiply a vector with the inverse world space inertia tensor (\f$I_{world}^{-1}\f$). Zero if object is static or kinematic.129JPH_INLINE Vec3 MultiplyWorldSpaceInverseInertiaByVector(QuatArg inBodyRotation, Vec3Arg inV) const;130131/// Velocity of point inPoint (in center of mass space, e.g. on the surface of the body) of the body (unit: m/s)132JPH_INLINE Vec3 GetPointVelocityCOM(Vec3Arg inPointRelativeToCOM) const { return mLinearVelocity + mAngularVelocity.Cross(inPointRelativeToCOM); }133134// 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 PhysicsSystem::Update.135JPH_INLINE Vec3 GetAccumulatedForce() const { return Vec3::sLoadFloat3Unsafe(mForce); }136137// 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 PhysicsSystem::Update.138JPH_INLINE Vec3 GetAccumulatedTorque() const { return Vec3::sLoadFloat3Unsafe(mTorque); }139140// Reset the total accumulated force, note that this will be done automatically after every time step.141JPH_INLINE void ResetForce() { mForce = Float3(0, 0, 0); }142143// Reset the total accumulated torque, note that this will be done automatically after every time step.144JPH_INLINE void ResetTorque() { mTorque = Float3(0, 0, 0); }145146// Reset the current velocity and accumulated force and torque.147JPH_INLINE void ResetMotion()148{149JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite));150mLinearVelocity = mAngularVelocity = Vec3::sZero();151mForce = mTorque = Float3(0, 0, 0);152}153154/// Returns a vector where the linear components that are not allowed by mAllowedDOFs are set to 0 and the rest to 0xffffffff155JPH_INLINE UVec4 GetLinearDOFsMask() const156{157UVec4 mask(uint32(EAllowedDOFs::TranslationX), uint32(EAllowedDOFs::TranslationY), uint32(EAllowedDOFs::TranslationZ), 0);158return UVec4::sEquals(UVec4::sAnd(UVec4::sReplicate(uint32(mAllowedDOFs)), mask), mask);159}160161/// Takes a translation vector inV and returns a vector where the components that are not allowed by mAllowedDOFs are set to 0162JPH_INLINE Vec3 LockTranslation(Vec3Arg inV) const163{164return Vec3::sAnd(inV, Vec3(GetLinearDOFsMask().ReinterpretAsFloat()));165}166167/// Returns a vector where the angular components that are not allowed by mAllowedDOFs are set to 0 and the rest to 0xffffffff168JPH_INLINE UVec4 GetAngularDOFsMask() const169{170UVec4 mask(uint32(EAllowedDOFs::RotationX), uint32(EAllowedDOFs::RotationY), uint32(EAllowedDOFs::RotationZ), 0);171return UVec4::sEquals(UVec4::sAnd(UVec4::sReplicate(uint32(mAllowedDOFs)), mask), mask);172}173174/// Takes an angular velocity / torque vector inV and returns a vector where the components that are not allowed by mAllowedDOFs are set to 0175JPH_INLINE Vec3 LockAngular(Vec3Arg inV) const176{177return Vec3::sAnd(inV, Vec3(GetAngularDOFsMask().ReinterpretAsFloat()));178}179180/// Used only when this body is dynamic and colliding. Override for the number of solver velocity iterations to run, 0 means use the default in PhysicsSettings::mNumVelocitySteps. The number of iterations to use is the max of all contacts and constraints in the island.181void SetNumVelocityStepsOverride(uint inN) { JPH_ASSERT(inN < 256); mNumVelocityStepsOverride = uint8(inN); }182uint GetNumVelocityStepsOverride() const { return mNumVelocityStepsOverride; }183184/// Used only when this body is dynamic and colliding. Override for the number of solver position iterations to run, 0 means use the default in PhysicsSettings::mNumPositionSteps. The number of iterations to use is the max of all contacts and constraints in the island.185void SetNumPositionStepsOverride(uint inN) { JPH_ASSERT(inN < 256); mNumPositionStepsOverride = uint8(inN); }186uint GetNumPositionStepsOverride() const { return mNumPositionStepsOverride; }187188////////////////////////////////////////////////////////////189// FUNCTIONS BELOW THIS LINE ARE FOR INTERNAL USE ONLY190////////////////////////////////////////////////////////////191192///@name Update linear and angular velocity (used during constraint solving)193///@{194inline void AddLinearVelocityStep(Vec3Arg inLinearVelocityChange) { JPH_DET_LOG("AddLinearVelocityStep: " << inLinearVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mLinearVelocity = LockTranslation(mLinearVelocity + inLinearVelocityChange); JPH_ASSERT(!mLinearVelocity.IsNaN()); }195inline void SubLinearVelocityStep(Vec3Arg inLinearVelocityChange) { JPH_DET_LOG("SubLinearVelocityStep: " << inLinearVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mLinearVelocity = LockTranslation(mLinearVelocity - inLinearVelocityChange); JPH_ASSERT(!mLinearVelocity.IsNaN()); }196inline void AddAngularVelocityStep(Vec3Arg inAngularVelocityChange) { JPH_DET_LOG("AddAngularVelocityStep: " << inAngularVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mAngularVelocity += inAngularVelocityChange; JPH_ASSERT(!mAngularVelocity.IsNaN()); }197inline void SubAngularVelocityStep(Vec3Arg inAngularVelocityChange) { JPH_DET_LOG("SubAngularVelocityStep: " << inAngularVelocityChange); JPH_ASSERT(BodyAccess::sCheckRights(BodyAccess::sVelocityAccess(), BodyAccess::EAccess::ReadWrite)); mAngularVelocity -= inAngularVelocityChange; JPH_ASSERT(!mAngularVelocity.IsNaN()); }198///@}199200/// Apply the gyroscopic force (aka Dzhanibekov effect, see https://en.wikipedia.org/wiki/Tennis_racket_theorem)201inline void ApplyGyroscopicForceInternal(QuatArg inBodyRotation, float inDeltaTime);202203/// Apply all accumulated forces, torques and drag (should only be called by the PhysicsSystem)204inline void ApplyForceTorqueAndDragInternal(QuatArg inBodyRotation, Vec3Arg inGravity, float inDeltaTime);205206/// Access to the island index207uint32 GetIslandIndexInternal() const { return mIslandIndex; }208void SetIslandIndexInternal(uint32 inIndex) { mIslandIndex = inIndex; }209210/// Access to the index in the active bodies array211uint32 GetIndexInActiveBodiesInternal() const { return mIndexInActiveBodies; }212213#ifdef JPH_DOUBLE_PRECISION214inline DVec3 GetSleepTestOffset() const { return DVec3::sLoadDouble3Unsafe(mSleepTestOffset); }215#endif // JPH_DOUBLE_PRECISION216217/// Reset spheres to center around inPoints with radius 0218inline void ResetSleepTestSpheres(const RVec3 *inPoints);219220/// Reset the sleep test timer without resetting the sleep test spheres221inline void ResetSleepTestTimer() { mSleepTestTimer = 0.0f; }222223/// Accumulate sleep time and return if a body can go to sleep224inline ECanSleep AccumulateSleepTime(float inDeltaTime, float inTimeBeforeSleep);225226/// Saving state for replay227void SaveState(StateRecorder &inStream) const;228229/// Restoring state for replay230void RestoreState(StateRecorder &inStream);231232static constexpr uint32 cInactiveIndex = uint32(-1); ///< Constant indicating that body is not active233234private:235friend class BodyManager;236friend class Body;237238// 1st cache line239// 16 byte aligned240Vec3 mLinearVelocity { Vec3::sZero() }; ///< World space linear velocity of the center of mass (m/s)241Vec3 mAngularVelocity { Vec3::sZero() }; ///< World space angular velocity (rad/s)242Vec3 mInvInertiaDiagonal; ///< Diagonal of inverse inertia matrix: D243Quat mInertiaRotation; ///< Rotation (R) that takes inverse inertia diagonal to local space: Ibody^-1 = R * D * R^-1244245// 2nd cache line246// 4 byte aligned247Float3 mForce { 0, 0, 0 }; ///< Accumulated world space force (N). Note loaded through intrinsics so ensure that the 4 bytes after this are readable!248Float3 mTorque { 0, 0, 0 }; ///< Accumulated world space torque (N m). Note loaded through intrinsics so ensure that the 4 bytes after this are readable!249float mInvMass; ///< Inverse mass of the object (1/kg)250float mLinearDamping; ///< Linear damping: dv/dt = -c * v. c must be between 0 and 1 but is usually close to 0.251float mAngularDamping; ///< Angular damping: dw/dt = -c * w. c must be between 0 and 1 but is usually close to 0.252float mMaxLinearVelocity; ///< Maximum linear velocity that this body can reach (m/s)253float mMaxAngularVelocity; ///< Maximum angular velocity that this body can reach (rad/s)254float mGravityFactor; ///< Factor to multiply gravity with255uint32 mIndexInActiveBodies = cInactiveIndex; ///< If the body is active, this is the index in the active body list or cInactiveIndex if it is not active (note that there are 2 lists, one for rigid and one for soft bodies)256uint32 mIslandIndex = cInactiveIndex; ///< Index of the island that this body is part of, when the body has not yet been updated or is not active this is cInactiveIndex257258// 1 byte aligned259EMotionQuality mMotionQuality; ///< Motion quality, or how well it detects collisions when it has a high velocity260bool mAllowSleeping; ///< If this body can go to sleep261EAllowedDOFs mAllowedDOFs = EAllowedDOFs::All; ///< Allowed degrees of freedom for this body262uint8 mNumVelocityStepsOverride = 0; ///< Used only when this body is dynamic and colliding. Override for the number of solver velocity iterations to run, 0 means use the default in PhysicsSettings::mNumVelocitySteps. The number of iterations to use is the max of all contacts and constraints in the island.263uint8 mNumPositionStepsOverride = 0; ///< Used only when this body is dynamic and colliding. Override for the number of solver position iterations to run, 0 means use the default in PhysicsSettings::mNumPositionSteps. The number of iterations to use is the max of all contacts and constraints in the island.264265// 3rd cache line (least frequently used)266// 4 byte aligned (or 8 byte if running in double precision)267#ifdef JPH_DOUBLE_PRECISION268Double3 mSleepTestOffset; ///< mSleepTestSpheres are relative to this offset to prevent floating point inaccuracies. Warning: Loaded using sLoadDouble3Unsafe which will read 8 extra bytes.269#endif // JPH_DOUBLE_PRECISION270Sphere 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 axis271float mSleepTestTimer; ///< How long this body has been within the movement tolerance272273#ifdef JPH_ENABLE_ASSERTS274EBodyType mCachedBodyType; ///< Copied from Body::mBodyType and cached for asserting purposes275EMotionType mCachedMotionType; ///< Copied from Body::mMotionType and cached for asserting purposes276#endif277};278279JPH_NAMESPACE_END280281#include "MotionProperties.inl"282283284