Constraint.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/Core/Reference.h>
  6. #include <Jolt/Core/NonCopyable.h>
  7. #include <Jolt/Core/Result.h>
  8. #include <Jolt/ObjectStream/SerializableObject.h>
  9. JPH_NAMESPACE_BEGIN
  10. class BodyID;
  11. class IslandBuilder;
  12. class LargeIslandSplitter;
  13. class BodyManager;
  14. class StateRecorder;
  15. class StreamIn;
  16. class StreamOut;
  17. #ifdef JPH_DEBUG_RENDERER
  18. class DebugRenderer;
  19. #endif // JPH_DEBUG_RENDERER
  20. /// Enum to identify constraint type
  21. enum class EConstraintType
  22. {
  23. Constraint,
  24. TwoBodyConstraint,
  25. };
  26. /// Enum to identify constraint sub type
  27. enum class EConstraintSubType
  28. {
  29. Fixed,
  30. Point,
  31. Hinge,
  32. Slider,
  33. Distance,
  34. Cone,
  35. SwingTwist,
  36. SixDOF,
  37. Path,
  38. Vehicle,
  39. RackAndPinion,
  40. Gear,
  41. Pulley,
  42. /// User defined constraint types start here
  43. User1,
  44. User2,
  45. User3,
  46. User4
  47. };
  48. /// Certain constraints support setting them up in local or world space. This governs what is used.
  49. enum class EConstraintSpace
  50. {
  51. LocalToBodyCOM, ///< All constraint properties are specified in local space to center of mass of the bodies that are being constrained (so e.g. 'constraint position 1' will be local to body 1 COM, 'constraint position 2' will be local to body 2 COM). Note that this means you need to subtract Shape::GetCenterOfMass() from positions!
  52. WorldSpace, ///< All constraint properties are specified in world space
  53. };
  54. /// Class used to store the configuration of a constraint. Allows run-time creation of constraints.
  55. class JPH_EXPORT ConstraintSettings : public SerializableObject, public RefTarget<ConstraintSettings>
  56. {
  57. public:
  58. JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, ConstraintSettings)
  59. using ConstraintResult = Result<Ref<ConstraintSettings>>;
  60. /// Saves the contents of the constraint settings in binary form to inStream.
  61. virtual void SaveBinaryState(StreamOut &inStream) const;
  62. /// Creates a constraint of the correct type and restores its contents from the binary stream inStream.
  63. static ConstraintResult sRestoreFromBinaryState(StreamIn &inStream);
  64. /// If this constraint is enabled initially. Use Constraint::SetEnabled to toggle after creation.
  65. bool mEnabled = true;
  66. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  67. /// Note that if you want a deterministic simulation and you cannot guarantee the order in which constraints are added/removed, you can make the priority for all constraints unique to get a deterministic ordering.
  68. uint32 mConstraintPriority = 0;
  69. /// Used only when the constraint is active. 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.
  70. uint mNumVelocityStepsOverride = 0;
  71. /// Used only when the constraint is active. 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.
  72. uint mNumPositionStepsOverride = 0;
  73. /// Size of constraint when drawing it through the debug renderer
  74. float mDrawConstraintSize = 1.0f;
  75. /// User data value (can be used by application)
  76. uint64 mUserData = 0;
  77. protected:
  78. /// This function should not be called directly, it is used by sRestoreFromBinaryState.
  79. virtual void RestoreBinaryState(StreamIn &inStream);
  80. };
  81. /// Base class for all physics constraints. A constraint removes one or more degrees of freedom for a rigid body.
  82. class JPH_EXPORT Constraint : public RefTarget<Constraint>, public NonCopyable
  83. {
  84. public:
  85. JPH_OVERRIDE_NEW_DELETE
  86. /// Constructor
  87. explicit Constraint(const ConstraintSettings &inSettings) :
  88. #ifdef JPH_DEBUG_RENDERER
  89. mDrawConstraintSize(inSettings.mDrawConstraintSize),
  90. #endif // JPH_DEBUG_RENDERER
  91. mConstraintPriority(inSettings.mConstraintPriority),
  92. mNumVelocityStepsOverride(uint8(inSettings.mNumVelocityStepsOverride)),
  93. mNumPositionStepsOverride(uint8(inSettings.mNumPositionStepsOverride)),
  94. mEnabled(inSettings.mEnabled),
  95. mUserData(inSettings.mUserData)
  96. {
  97. JPH_ASSERT(inSettings.mNumVelocityStepsOverride < 256);
  98. JPH_ASSERT(inSettings.mNumPositionStepsOverride < 256);
  99. }
  100. /// Virtual destructor
  101. virtual ~Constraint() = default;
  102. /// Get the type of a constraint
  103. virtual EConstraintType GetType() const { return EConstraintType::Constraint; }
  104. /// Get the sub type of a constraint
  105. virtual EConstraintSubType GetSubType() const = 0;
  106. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  107. /// Note that if you want a deterministic simulation and you cannot guarantee the order in which constraints are added/removed, you can make the priority for all constraints unique to get a deterministic ordering.
  108. uint32 GetConstraintPriority() const { return mConstraintPriority; }
  109. void SetConstraintPriority(uint32 inPriority) { mConstraintPriority = inPriority; }
  110. /// Used only when the constraint is active. 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.
  111. void SetNumVelocityStepsOverride(uint inN) { JPH_ASSERT(inN < 256); mNumVelocityStepsOverride = uint8(inN); }
  112. uint GetNumVelocityStepsOverride() const { return mNumVelocityStepsOverride; }
  113. /// Used only when the constraint is active. 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.
  114. void SetNumPositionStepsOverride(uint inN) { JPH_ASSERT(inN < 256); mNumPositionStepsOverride = uint8(inN); }
  115. uint GetNumPositionStepsOverride() const { return mNumPositionStepsOverride; }
  116. /// Enable / disable this constraint. This can e.g. be used to implement a breakable constraint by detecting that the constraint impulse
  117. /// (see e.g. PointConstraint::GetTotalLambdaPosition) went over a certain limit and then disabling the constraint.
  118. /// Note that although a disabled constraint will not affect the simulation in any way anymore, it does incur some processing overhead.
  119. /// Alternatively you can remove a constraint from the constraint manager (which may be more costly if you want to disable the constraint for a short while).
  120. void SetEnabled(bool inEnabled) { mEnabled = inEnabled; }
  121. /// Test if a constraint is enabled.
  122. bool GetEnabled() const { return mEnabled; }
  123. /// Access to the user data, can be used for anything by the application
  124. uint64 GetUserData() const { return mUserData; }
  125. void SetUserData(uint64 inUserData) { mUserData = inUserData; }
  126. /// Notify the constraint that the shape of a body has changed and that its center of mass has moved by inDeltaCOM.
  127. /// Bodies don't know which constraints are connected to them so the user is responsible for notifying the relevant constraints when a body changes.
  128. /// @param inBodyID ID of the body that has changed
  129. /// @param inDeltaCOM The delta of the center of mass of the body (shape->GetCenterOfMass() - shape_before_change->GetCenterOfMass())
  130. virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) = 0;
  131. /// Notify the system that the configuration of the bodies and/or constraint has changed enough so that the warm start impulses should not be applied the next frame.
  132. /// You can use this function for example when repositioning a ragdoll through Ragdoll::SetPose in such a way that the orientation of the bodies completely changes so that
  133. /// the previous frame impulses are no longer a good approximation of what the impulses will be in the next frame. Calling this function when there are no big changes
  134. /// will result in the constraints being much 'softer' than usual so they are more easily violated (e.g. a long chain of bodies might sag a bit if you call this every frame).
  135. virtual void ResetWarmStart() = 0;
  136. ///@name Solver interface
  137. ///@{
  138. virtual bool IsActive() const { return mEnabled; }
  139. virtual void SetupVelocityConstraint(float inDeltaTime) = 0;
  140. virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) = 0;
  141. virtual bool SolveVelocityConstraint(float inDeltaTime) = 0;
  142. virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) = 0;
  143. ///@}
  144. /// Link bodies that are connected by this constraint in the island builder
  145. virtual void BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager) = 0;
  146. /// Link bodies that are connected by this constraint in the same split. Returns the split index.
  147. virtual uint BuildIslandSplits(LargeIslandSplitter &ioSplitter) const = 0;
  148. #ifdef JPH_DEBUG_RENDERER
  149. // Drawing interface
  150. virtual void DrawConstraint(DebugRenderer *inRenderer) const = 0;
  151. virtual void DrawConstraintLimits([[maybe_unused]] DebugRenderer *inRenderer) const { }
  152. virtual void DrawConstraintReferenceFrame([[maybe_unused]] DebugRenderer *inRenderer) const { }
  153. /// Size of constraint when drawing it through the debug renderer
  154. float GetDrawConstraintSize() const { return mDrawConstraintSize; }
  155. void SetDrawConstraintSize(float inSize) { mDrawConstraintSize = inSize; }
  156. #endif // JPH_DEBUG_RENDERER
  157. /// Saving state for replay
  158. virtual void SaveState(StateRecorder &inStream) const;
  159. /// Restoring state for replay
  160. virtual void RestoreState(StateRecorder &inStream);
  161. /// Debug function to convert a constraint to its settings, note that this will not save to which bodies the constraint is connected to
  162. virtual Ref<ConstraintSettings> GetConstraintSettings() const = 0;
  163. protected:
  164. /// Helper function to copy settings back to constraint settings for this base class
  165. void ToConstraintSettings(ConstraintSettings &outSettings) const;
  166. #ifdef JPH_DEBUG_RENDERER
  167. /// Size of constraint when drawing it through the debug renderer
  168. float mDrawConstraintSize;
  169. #endif // JPH_DEBUG_RENDERER
  170. private:
  171. friend class ConstraintManager;
  172. /// Index that indicates this constraint is not in the constraint manager
  173. static constexpr uint32 cInvalidConstraintIndex = 0xffffffff;
  174. /// Index in the mConstraints list of the ConstraintManager for easy finding
  175. uint32 mConstraintIndex = cInvalidConstraintIndex;
  176. /// Priority of the constraint when solving. Higher numbers have are more likely to be solved correctly.
  177. uint32 mConstraintPriority = 0;
  178. /// Used only when the constraint is active. 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.
  179. uint8 mNumVelocityStepsOverride = 0;
  180. /// Used only when the constraint is active. 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.
  181. uint8 mNumPositionStepsOverride = 0;
  182. /// If this constraint is currently enabled
  183. bool mEnabled = true;
  184. /// User data value (can be used by application)
  185. uint64 mUserData;
  186. };
  187. JPH_NAMESPACE_END