CharacterVirtual.h 36 KB

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