CharacterVirtual.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #pragma once
  4. #include <Jolt/Physics/Character/CharacterBase.h>
  5. #include <Jolt/Physics/Body/MotionType.h>
  6. #include <Jolt/Physics/Body/BodyFilter.h>
  7. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
  8. #include <Jolt/Physics/Collision/ObjectLayer.h>
  9. #include <Jolt/Core/STLTempAllocator.h>
  10. JPH_NAMESPACE_BEGIN
  11. class CharacterVirtual;
  12. /// Contains the configuration of a character
  13. class CharacterVirtualSettings : public CharacterBaseSettings
  14. {
  15. public:
  16. JPH_OVERRIDE_NEW_DELETE
  17. /// Character mass (kg). Used to push down objects with gravity when the character is standing on top.
  18. float mMass = 70.0f;
  19. /// Maximum force with which the character can push other bodies (N).
  20. float mMaxStrength = 100.0f;
  21. /// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
  22. Vec3 mShapeOffset = Vec3::sZero();
  23. ///@name Movement settings
  24. float mPredictiveContactDistance = 0.1f; ///< How far to scan outside of the shape for predictive contacts
  25. uint mMaxCollisionIterations = 5; ///< Max amount of collision loops
  26. uint mMaxConstraintIterations = 15; ///< How often to try stepping in the constraint solving
  27. float mMinTimeRemaining = 1.0e-4f; ///< Early out condition: If this much time is left to simulate we are done
  28. float mCollisionTolerance = 1.0e-3f; ///< How far we're willing to penetrate geometry
  29. float mCharacterPadding = 0.02f; ///< How far we try to stay away from the geometry, this ensures that the sweep will hit as little as possible lowering the collision cost and reducing the risk of getting stuck
  30. uint mMaxNumHits = 256; ///< Max num hits to collect in order to avoid excess of contact points collection
  31. float mHitReductionCosMaxAngle = 0.999f; ///< Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
  32. float mPenetrationRecoverySpeed = 1.0f; ///< This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  33. };
  34. /// This class contains settings that allow you to override the behavior of a character's collision response
  35. class CharacterContactSettings
  36. {
  37. public:
  38. bool mCanPushCharacter = true; ///< True when the object can push the virtual character
  39. bool mCanReceiveImpulses = true; ///< True when the virtual character can apply impulses (push) the body
  40. };
  41. /// This class receives callbacks when a virtual character hits something.
  42. class CharacterContactListener
  43. {
  44. public:
  45. /// Destructor
  46. virtual ~CharacterContactListener() = default;
  47. /// Callback to adjust the velocity of a body as seen by the character. Can be adjusted to e.g. implement a conveyor belt or an inertial dampener system of a sci-fi space ship.
  48. /// Note that inBody2 is locked during the callback so you can read its properties freely.
  49. virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }
  50. /// Checks if a character can collide with specified body. Return true if the contact is valid.
  51. virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }
  52. /// Called whenever the character collides with a body. Returns true if the contact can push the character.
  53. /// @param inCharacter Character that is being solved
  54. /// @param inBodyID2 Body ID of body that is being hit
  55. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  56. /// @param inContactPosition World space contact position
  57. /// @param inContactNormal World space contact normal
  58. /// @param ioSettings Settings returned by the contact callback to indicate how the character should behave
  59. virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  60. /// Called whenever a contact is being used by the solver. Allows the listener to override the resulting character velocity (e.g. by preventing sliding along certain surfaces).
  61. /// @param inCharacter Character that is being solved
  62. /// @param inBodyID2 Body ID of body that is being hit
  63. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  64. /// @param inContactPosition World space contact position
  65. /// @param inContactNormal World space contact normal
  66. /// @param inContactVelocity World space velocity of contact point (e.g. for a moving platform)
  67. /// @param inContactMaterial Material of contact point
  68. /// @param inCharacterVelocity World space velocity of the character prior to hitting this contact
  69. /// @param ioNewCharacterVelocity Contains the calculated world space velocity of the character after hitting this contact, this velocity slides along the surface of the contact. Can be modified by the listener to provide an alternative velocity.
  70. virtual void OnContactSolve(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) { /* Default do nothing */ }
  71. };
  72. /// Runtime character object.
  73. /// This object usually represents the player. Contrary to the Character class it doesn't use a rigid body but moves doing collision checks only (hence the name virtual).
  74. /// The advantage of this is that you can determine when the character moves in the frame (usually this has to happen at a very particular point in the frame)
  75. /// but the downside is that other objects don't see this virtual character. In order to make this work it is recommended to pair a CharacterVirtual with a Character that
  76. /// moves along. This Character should be keyframed (or at least have no gravity) and move along with the CharacterVirtual so that other rigid bodies can collide with it.
  77. class CharacterVirtual : public CharacterBase
  78. {
  79. public:
  80. JPH_OVERRIDE_NEW_DELETE
  81. /// Constructor
  82. /// @param inSettings The settings for the character
  83. /// @param inPosition Initial position for the character
  84. /// @param inRotation Initial rotation for the character (usually only around the up-axis)
  85. /// @param inSystem Physics system that this character will be added to later
  86. CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem);
  87. /// Set the contact listener
  88. void SetListener(CharacterContactListener *inListener) { mListener = inListener; }
  89. /// Get the current contact listener
  90. CharacterContactListener * GetListener() const { return mListener; }
  91. /// Get the linear velocity of the character (m / s)
  92. Vec3 GetLinearVelocity() const { return mLinearVelocity; }
  93. /// Set the linear velocity of the character (m / s)
  94. void SetLinearVelocity(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; }
  95. /// Get the position of the character
  96. RVec3 GetPosition() const { return mPosition; }
  97. /// Set the position of the character
  98. void SetPosition(RVec3Arg inPosition) { mPosition = inPosition; }
  99. /// Get the rotation of the character
  100. Quat GetRotation() const { return mRotation; }
  101. /// Set the rotation of the character
  102. void SetRotation(QuatArg inRotation) { mRotation = inRotation; }
  103. /// Calculate the world transform of the character
  104. RMat44 GetWorldTransform() const { return RMat44::sRotationTranslation(mRotation, mPosition); }
  105. /// Calculates the transform for this character's center of mass
  106. RMat44 GetCenterOfMassTransform() const { return GetCenterOfMassTransform(mPosition, mRotation, mShape); }
  107. /// Character mass (kg)
  108. float GetMass() const { return mMass; }
  109. void SetMass(float inMass) { mMass = inMass; }
  110. /// Maximum force with which the character can push other bodies (N)
  111. float GetMaxStrength() const { return mMaxStrength; }
  112. void SetMaxStrength(float inMaxStrength) { mMaxStrength = inMaxStrength; }
  113. /// This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  114. float GetPenetrationRecoverySpeed() const { return mPenetrationRecoverySpeed; }
  115. void SetPenetrationRecoverySpeed(float inSpeed) { mPenetrationRecoverySpeed = inSpeed; }
  116. /// Character padding
  117. float GetCharacterPadding() const { return mCharacterPadding; }
  118. /// Max num hits to collect in order to avoid excess of contact points collection
  119. uint GetMaxNumHits() const { return mMaxNumHits; }
  120. void SetMaxNumHits(uint inMaxHits) { mMaxNumHits = inMaxHits; }
  121. /// Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
  122. float GetHitReductionCosMaxAngle() const { return mHitReductionCosMaxAngle; }
  123. void SetHitReductionCosMaxAngle(float inCosMaxAngle) { mHitReductionCosMaxAngle = inCosMaxAngle; }
  124. /// Returns if we exceeded the maximum number of hits during the last collision check and had to discard hits based on distance.
  125. /// This can be used to find areas that have too complex geometry for the character to navigate properly.
  126. /// To solve you can either increase the max number of hits or simplify the geometry. Note that the character simulation will
  127. /// try to do its best to select the most relevant contacts to avoid the character from getting stuck.
  128. bool GetMaxHitsExceeded() const { return mMaxHitsExceeded; }
  129. /// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space. Note that setting it on the fly can cause the shape to teleport into collision.
  130. Vec3 GetShapeOffset() const { return mShapeOffset; }
  131. void SetShapeOffset(Vec3Arg inShapeOffset) { mShapeOffset = inShapeOffset; }
  132. /// This function can be called prior to calling Update() to convert a desired velocity into a velocity that won't make the character move further onto steep slopes.
  133. /// This velocity can then be set on the character using SetLinearVelocity()
  134. /// @param inDesiredVelocity Velocity to clamp against steep walls
  135. /// @return A new velocity vector that won't make the character move up steep slopes
  136. Vec3 CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const;
  137. /// This is the main update function. It moves the character according to its current velocity (the character is similar to a kinematic body in the sense
  138. /// that you set the velocity and the character will follow unless collision is blocking the way). Note it's your own responsibility to apply gravity to the character velocity!
  139. /// Different surface materials (like ice) can be emulated by getting the ground material and adjusting the velocity and/or the max slope angle accordingly every frame.
  140. /// @param inDeltaTime Time step to simulate.
  141. /// @param inGravity Gravity vector (m/s^2). This gravity vector is only used when the character is standing on top of another object to apply downward force.
  142. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  143. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  144. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  145. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  146. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  147. void Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  148. /// This function will return true if the character has moved into a slope that is too steep (e.g. a vertical wall).
  149. /// You would call WalkStairs to attempt to step up stairs.
  150. /// @param inLinearVelocity The linear velocity that the player desired. This is used to determine if we're pusing into a step.
  151. bool CanWalkStairs(Vec3Arg inLinearVelocity) const;
  152. /// When stair walking is needed, you can call the WalkStairs function to cast up, forward and down again to try to find a valid position
  153. /// @param inDeltaTime Time step to simulate.
  154. /// @param inStepUp The direction and distance to step up (this corresponds to the max step height)
  155. /// @param inStepForward The direction and distance to step forward after the step up
  156. /// @param inStepForwardTest When running at a high frequency, inStepForward can be very small and it's likely that you hit the side of the stairs on the way down. This could produce a normal that violates the max slope angle. If this happens, we test again using this distance from the up position to see if we find a valid slope.
  157. /// @param inStepDownExtra An additional translation that is added when stepping down at the end. Allows you to step further down than up. Set to zero if you don't want this. Should be in the opposite direction of up.
  158. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  159. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  160. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  161. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  162. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  163. /// @return true if the stair walk was successful
  164. bool WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg inStepForward, Vec3Arg inStepForwardTest, Vec3Arg inStepDownExtra, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  165. /// This function can be used to artificially keep the character to the floor. Normally when a character is on a small step and starts moving horizontally, the character will
  166. /// lose contact with the floor because the initial vertical velocity is zero while the horizontal velocity is quite high. To prevent the character from losing contact with the floor,
  167. /// we do an additional collision check downwards and if we find the floor within a certain distance, we project the character onto the floor.
  168. /// @param inStepDown Max amount to project the character downwards (if no floor is found within this distance, the function will return false)
  169. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  170. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  171. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  172. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  173. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  174. /// @return True if the character was successfully projected onto the floor.
  175. bool StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  176. /// Settings struct with settings for ExtendedUpdate
  177. struct ExtendedUpdateSettings
  178. {
  179. Vec3 mStickToFloorStepDown { 0, -0.5f, 0 }; ///< See StickToFloor inStepDown parameter. Can be zero to turn off.
  180. Vec3 mWalkStairsStepUp { 0, 0.4f, 0 }; ///< See WalkStairs inStepUp parameter. Can be zero to turn off.
  181. float mWalkStairsMinStepForward { 0.02f }; ///< See WalkStairs inStepForward parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
  182. float mWalkStairsStepForwardTest { 0.15f }; ///< See WalkStairs inStepForwardTest parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
  183. float mWalkStairsCosAngleForwardContact { Cos(DegreesToRadians(75.0f)) }; ///< Cos(angle) where angle is the maximum angle between the ground normal in the horizontal plane and the character forward vector where we're willing to adjust the step forward test towards the contact normal.
  184. Vec3 mWalkStairsStepDownExtra { Vec3::sZero() }; ///< See WalkStairs inStepDownExtra
  185. };
  186. /// This function combines Update, StickToFloor and WalkStairs. This function serves as an example of how these functions could be combined.
  187. /// Before calling, call SetLinearVelocity to update the horizontal/vertical speed of the character, typically this is:
  188. /// - When on OnGround and not moving away from ground: velocity = GetGroundVelocity() + horizontal speed as input by player + optional vertical jump velocity + delta time * gravity
  189. /// - Else: velocity = current vertical velocity + horizontal speed as input by player + delta time * gravity
  190. /// @param inDeltaTime Time step to simulate.
  191. /// @param inGravity Gravity vector (m/s^2). This gravity vector is only used when the character is standing on top of another object to apply downward force.
  192. /// @param inSettings A structure containing settings for the algorithm.
  193. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  194. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  195. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  196. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  197. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  198. void ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  199. /// This function can be used after a character has teleported to determine the new contacts with the world.
  200. void RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  201. /// Switch the shape of the character (e.g. for stance).
  202. /// @param inShape The shape to switch to.
  203. /// @param inMaxPenetrationDepth When inMaxPenetrationDepth is not FLT_MAX, it checks if the new shape collides before switching shape. This is the max penetration we're willing to accept after the switch.
  204. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  205. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  206. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  207. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  208. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  209. /// @return Returns true if the switch succeeded.
  210. bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  211. /// @brief Get all contacts for the character at a particular location
  212. /// @param inPosition Position to test, note that this position will be corrected for the character padding.
  213. /// @param inRotation Rotation at which to test the shape.
  214. /// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.
  215. /// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).
  216. /// @param inShape Shape to test collision with.
  217. /// @param inBaseOffset All hit results will be returned relative to this offset, can be zero to get results in world position, but when you're testing far from the origin you get better precision by picking a position that's closer e.g. GetPosition() since floats are most accurate near the origin
  218. /// @param ioCollector Collision collector that receives the collision results.
  219. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  220. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  221. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  222. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  223. void CheckCollision(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inMovementDirection, float inMaxSeparationDistance, const Shape *inShape, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  224. // Saving / restoring state for replay
  225. virtual void SaveState(StateRecorder &inStream) const override;
  226. virtual void RestoreState(StateRecorder &inStream) override;
  227. #ifdef JPH_DEBUG_RENDERER
  228. static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating them
  229. static inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithm
  230. static inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm
  231. #endif
  232. // Encapsulates a collision contact
  233. struct Contact
  234. {
  235. // Saving / restoring state for replay
  236. void SaveState(StateRecorder &inStream) const;
  237. void RestoreState(StateRecorder &inStream);
  238. RVec3 mPosition; ///< Position where the character makes contact
  239. Vec3 mLinearVelocity; ///< Velocity of the contact point
  240. Vec3 mContactNormal; ///< Contact normal, pointing towards the character
  241. Vec3 mSurfaceNormal; ///< Surface normal of the contact
  242. float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive
  243. float mFraction; ///< Fraction along the path where this contact takes place
  244. BodyID mBodyB; ///< ID of body we're colliding with
  245. SubShapeID mSubShapeIDB; ///< Sub shape ID of body we're colliding with
  246. EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact
  247. uint64 mUserData; ///< User data of B
  248. const PhysicsMaterial * mMaterial; ///< Material of B
  249. bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)
  250. bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact
  251. bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character
  252. };
  253. using TempContactList = std::vector<Contact, STLTempAllocator<Contact>>;
  254. using ContactList = Array<Contact>;
  255. /// Access to the internal list of contacts that the character has found.
  256. const ContactList & GetActiveContacts() const { return mActiveContacts; }
  257. private:
  258. // A contact that needs to be ignored
  259. struct IgnoredContact
  260. {
  261. IgnoredContact() = default;
  262. IgnoredContact(const BodyID &inBodyID, const SubShapeID &inSubShapeID) : mBodyID(inBodyID), mSubShapeID(inSubShapeID) { }
  263. BodyID mBodyID; ///< ID of body we're colliding with
  264. SubShapeID mSubShapeID; ///< Sub shape of body we're colliding with
  265. };
  266. using IgnoredContactList = std::vector<IgnoredContact, STLTempAllocator<IgnoredContact>>;
  267. // A constraint that limits the movement of the character
  268. struct Constraint
  269. {
  270. Contact * mContact; ///< Contact that this constraint was generated from
  271. float mTOI; ///< Calculated time of impact (can be negative if penetrating)
  272. float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)
  273. Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)
  274. Plane mPlane; ///< Plane around the origin that describes how far we can displace (from the origin)
  275. };
  276. using ConstraintList = std::vector<Constraint, STLTempAllocator<Constraint>>;
  277. // Collision collector that collects hits for CollideShape
  278. class ContactCollector : public CollideShapeCollector
  279. {
  280. public:
  281. ContactCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, uint inMaxHits, float inHitReductionCosMaxAngle, Vec3Arg inUp, RVec3Arg inBaseOffset, TempContactList &outContacts) : mBaseOffset(inBaseOffset), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mContacts(outContacts), mMaxHits(inMaxHits), mHitReductionCosMaxAngle(inHitReductionCosMaxAngle) { }
  282. virtual void AddHit(const CollideShapeResult &inResult) override;
  283. RVec3 mBaseOffset;
  284. Vec3 mUp;
  285. PhysicsSystem * mSystem;
  286. const CharacterVirtual * mCharacter;
  287. TempContactList & mContacts;
  288. uint mMaxHits;
  289. float mHitReductionCosMaxAngle;
  290. bool mMaxHitsExceeded = false;
  291. };
  292. // A collision collector that collects hits for CastShape
  293. class ContactCastCollector : public CastShapeCollector
  294. {
  295. public:
  296. ContactCastCollector(PhysicsSystem *inSystem, const CharacterVirtual *inCharacter, Vec3Arg inDisplacement, Vec3Arg inUp, const IgnoredContactList &inIgnoredContacts, RVec3Arg inBaseOffset, Contact &outContact) : mBaseOffset(inBaseOffset), mDisplacement(inDisplacement), mUp(inUp), mSystem(inSystem), mCharacter(inCharacter), mIgnoredContacts(inIgnoredContacts), mContact(outContact) { }
  297. virtual void AddHit(const ShapeCastResult &inResult) override;
  298. RVec3 mBaseOffset;
  299. Vec3 mDisplacement;
  300. Vec3 mUp;
  301. PhysicsSystem * mSystem;
  302. const CharacterVirtual * mCharacter;
  303. const IgnoredContactList & mIgnoredContacts;
  304. Contact & mContact;
  305. };
  306. // Helper function to convert a Jolt collision result into a contact
  307. template <class taCollector>
  308. inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);
  309. // Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometry
  310. void MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator
  311. #ifdef JPH_DEBUG_RENDERER
  312. , bool inDrawConstraints = false
  313. #endif // JPH_DEBUG_RENDERER
  314. ) const;
  315. // Ask the callback if inContact is a valid contact point
  316. bool ValidateContact(const Contact &inContact) const;
  317. // Tests the shape for collision around inPosition
  318. void GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  319. // Remove penetrating contacts with the same body that have conflicting normals, leaving these will make the character mover get stuck
  320. void RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const;
  321. // Convert contacts into constraints. The character is assumed to start at the origin and the constraints are planes around the origin that confine the movement of the character.
  322. void DetermineConstraints(TempContactList &inContacts, ConstraintList &outConstraints) const;
  323. // Use the constraints to solve the displacement of the character. This will slide the character on the planes around the origin for as far as possible.
  324. void SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator
  325. #ifdef JPH_DEBUG_RENDERER
  326. , bool inDrawConstraints = false
  327. #endif // JPH_DEBUG_RENDERER
  328. ) const;
  329. // Get the velocity of a body adjusted by the contact listener
  330. void GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const;
  331. // Handle contact with physics object that we're colliding against
  332. bool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime) const;
  333. // Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision
  334. bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  335. // Store contacts so that we have proper ground information
  336. void StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);
  337. // This function will determine which contacts are touching the character and will calculate the one that is supporting us
  338. void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);
  339. /// This function can be called after moving the character to a new colliding position
  340. void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  341. // This function returns the actual center of mass of the shape, not corrected for the character padding
  342. inline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const
  343. {
  344. return RMat44::sRotationTranslation(inRotation, inPosition).PreTranslated(mShapeOffset + inShape->GetCenterOfMass()).PostTranslated(mCharacterPadding * mUp);
  345. }
  346. // Our main listener for contacts
  347. CharacterContactListener * mListener = nullptr;
  348. // Movement settings
  349. float mPredictiveContactDistance; // How far to scan outside of the shape for predictive contacts
  350. uint mMaxCollisionIterations; // Max amount of collision loops
  351. uint mMaxConstraintIterations; // How often to try stepping in the constraint solving
  352. float mMinTimeRemaining; // Early out condition: If this much time is left to simulate we are done
  353. float mCollisionTolerance; // How far we're willing to penetrate geometry
  354. float mCharacterPadding; // How far we try to stay away from the geometry, this ensures that the sweep will hit as little as possible lowering the collision cost and reducing the risk of getting stuck
  355. uint mMaxNumHits; // Max num hits to collect in order to avoid excess of contact points collection
  356. float mHitReductionCosMaxAngle; // Cos(angle) where angle is the maximum angle between two hits contact normals that are allowed to be merged during hit reduction. Default is around 2.5 degrees. Set to -1 to turn off.
  357. float mPenetrationRecoverySpeed; // This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  358. // Character mass (kg)
  359. float mMass;
  360. // Maximum force with which the character can push other bodies (N)
  361. float mMaxStrength;
  362. // An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
  363. Vec3 mShapeOffset = Vec3::sZero();
  364. // Current position (of the base, not the center of mass)
  365. RVec3 mPosition = RVec3::sZero();
  366. // Current rotation (of the base, not of the center of mass)
  367. Quat mRotation = Quat::sIdentity();
  368. // Current linear velocity
  369. Vec3 mLinearVelocity = Vec3::sZero();
  370. // List of contacts that were active in the last frame
  371. ContactList mActiveContacts;
  372. // Remembers the delta time of the last update
  373. float mLastDeltaTime = 1.0f / 60.0f;
  374. // Remember if we exceeded the maximum number of hits and had to remove similar contacts
  375. mutable bool mMaxHitsExceeded = false;
  376. };
  377. JPH_NAMESPACE_END