CharacterVirtual.h 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751
  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/Character/CharacterID.h>
  7. #include <Jolt/Physics/Body/MotionType.h>
  8. #include <Jolt/Physics/Body/BodyFilter.h>
  9. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>
  10. #include <Jolt/Physics/Collision/ObjectLayer.h>
  11. #include <Jolt/Physics/Collision/TransformedShape.h>
  12. #include <Jolt/Core/STLTempAllocator.h>
  13. JPH_NAMESPACE_BEGIN
  14. class CharacterVirtual;
  15. class CollideShapeSettings;
  16. /// Contains the configuration of a character
  17. class JPH_EXPORT CharacterVirtualSettings : public CharacterBaseSettings
  18. {
  19. public:
  20. JPH_OVERRIDE_NEW_DELETE
  21. /// Constructor
  22. CharacterVirtualSettings() = default;
  23. CharacterVirtualSettings(const CharacterVirtualSettings &) = default;
  24. CharacterVirtualSettings & operator = (const CharacterVirtualSettings &) = default;
  25. /// ID to give to this character. This is used for deterministically sorting and as an identifier to represent the character in the contact removal callback.
  26. CharacterID mID = CharacterID::sNextCharacterID();
  27. /// Character mass (kg). Used to push down objects with gravity when the character is standing on top.
  28. float mMass = 70.0f;
  29. /// Maximum force with which the character can push other bodies (N).
  30. float mMaxStrength = 100.0f;
  31. /// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
  32. Vec3 mShapeOffset = Vec3::sZero();
  33. ///@name Movement settings
  34. 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.
  35. 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.
  36. uint mMaxCollisionIterations = 5; ///< Max amount of collision loops
  37. uint mMaxConstraintIterations = 15; ///< How often to try stepping in the constraint solving
  38. float mMinTimeRemaining = 1.0e-4f; ///< Early out condition: If this much time is left to simulate we are done
  39. float mCollisionTolerance = 1.0e-3f; ///< How far we're willing to penetrate geometry
  40. 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
  41. uint mMaxNumHits = 256; ///< Max num hits to collect in order to avoid excess of contact points collection
  42. 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.
  43. float mPenetrationRecoverySpeed = 1.0f; ///< This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  44. /// This character can optionally have an inner rigid body. This rigid body can be used to give the character presence in the world. When set it means that:
  45. /// - Regular collision checks (e.g. NarrowPhaseQuery::CastRay) will collide with the rigid body (they cannot collide with CharacterVirtual since it is not added to the broad phase)
  46. /// - Regular contact callbacks will be called through the ContactListener (next to the ones that will be passed to the CharacterContactListener)
  47. /// - Fast moving objects of motion quality LinearCast will not be able to pass through the CharacterVirtual in 1 time step
  48. RefConst<Shape> mInnerBodyShape;
  49. /// For a deterministic simulation, it is important to have a deterministic body ID. When set and when mInnerBodyShape is specified,
  50. /// the inner body will be created with this specified ID instead of a generated ID.
  51. BodyID mInnerBodyIDOverride;
  52. /// Layer that the inner rigid body will be added to
  53. ObjectLayer mInnerBodyLayer = 0;
  54. };
  55. /// This class contains settings that allow you to override the behavior of a character's collision response
  56. class CharacterContactSettings
  57. {
  58. public:
  59. /// True when the object can push the virtual character.
  60. bool mCanPushCharacter = true;
  61. /// True when the virtual character can apply impulses (push) the body.
  62. /// Note that this only works against rigid bodies. Other CharacterVirtual objects can only be moved in their own update,
  63. /// so you must ensure that in their OnCharacterContactAdded mCanPushCharacter is true.
  64. bool mCanReceiveImpulses = true;
  65. };
  66. /// This class receives callbacks when a virtual character hits something.
  67. class JPH_EXPORT CharacterContactListener
  68. {
  69. public:
  70. /// Destructor
  71. virtual ~CharacterContactListener() = default;
  72. /// 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.
  73. /// Note that inBody2 is locked during the callback so you can read its properties freely.
  74. virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }
  75. /// Checks if a character can collide with specified body. Return true if the contact is valid.
  76. virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }
  77. /// Same as OnContactValidate but when colliding with a CharacterVirtual
  78. virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2) { return true; }
  79. /// Called whenever the character collides with a body for the first time.
  80. /// @param inCharacter Character that is being solved
  81. /// @param inBodyID2 Body ID of body that is being hit
  82. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  83. /// @param inContactPosition World space contact position
  84. /// @param inContactNormal World space contact normal
  85. /// @param ioSettings Settings returned by the contact callback to indicate how the character should behave
  86. virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  87. /// Called whenever the character persists colliding with a body.
  88. /// @param inCharacter Character that is being solved
  89. /// @param inBodyID2 Body ID of body that is being hit
  90. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  91. /// @param inContactPosition World space contact position
  92. /// @param inContactNormal World space contact normal
  93. /// @param ioSettings Settings returned by the contact callback to indicate how the character should behave
  94. virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  95. /// Called whenever the character loses contact with a body.
  96. /// Note that there is no guarantee that the body or its sub shape still exists at this point. The body may have been deleted since the last update.
  97. /// @param inCharacter Character that is being solved
  98. /// @param inBodyID2 Body ID of body that is being hit
  99. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  100. virtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }
  101. /// Same as OnContactAdded but when colliding with a CharacterVirtual
  102. virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  103. /// Same as OnContactPersisted but when colliding with a CharacterVirtual
  104. virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }
  105. /// Same as OnContactRemoved but when colliding with a CharacterVirtual
  106. /// Note that inOtherCharacterID can be the ID of a character that has been deleted. This happens if the character was in contact with this character during the last update, but has been deleted since.
  107. virtual void OnCharacterContactRemoved(const CharacterVirtual *inCharacter, const CharacterID &inOtherCharacterID, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }
  108. /// 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).
  109. /// @param inCharacter Character that is being solved
  110. /// @param inBodyID2 Body ID of body that is being hit
  111. /// @param inSubShapeID2 Sub shape ID of shape that is being hit
  112. /// @param inContactPosition World space contact position
  113. /// @param inContactNormal World space contact normal
  114. /// @param inContactVelocity World space velocity of contact point (e.g. for a moving platform)
  115. /// @param inContactMaterial Material of contact point
  116. /// @param inCharacterVelocity World space velocity of the character prior to hitting this contact
  117. /// @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.
  118. 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 */ }
  119. /// Same as OnContactSolve but when colliding with a CharacterVirtual
  120. virtual void OnCharacterContactSolve(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, Vec3Arg inContactVelocity, const PhysicsMaterial *inContactMaterial, Vec3Arg inCharacterVelocity, Vec3 &ioNewCharacterVelocity) { /* Default do nothing */ }
  121. };
  122. /// Interface class that allows a CharacterVirtual to check collision with other CharacterVirtual instances.
  123. /// Since CharacterVirtual instances are not registered anywhere, it is up to the application to test collision against relevant characters.
  124. /// The characters could be stored in a tree structure to make this more efficient.
  125. class JPH_EXPORT CharacterVsCharacterCollision : public NonCopyable
  126. {
  127. public:
  128. virtual ~CharacterVsCharacterCollision() = default;
  129. /// Collide a character against other CharacterVirtuals.
  130. /// @param inCharacter The character to collide.
  131. /// @param inCenterOfMassTransform Center of mass transform for this character.
  132. /// @param inCollideShapeSettings Settings for the collision check.
  133. /// @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
  134. /// @param ioCollector Collision collector that receives the collision results.
  135. virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const = 0;
  136. /// Cast a character against other CharacterVirtuals.
  137. /// @param inCharacter The character to cast.
  138. /// @param inCenterOfMassTransform Center of mass transform for this character.
  139. /// @param inDirection Direction and length to cast in.
  140. /// @param inShapeCastSettings Settings for the shape cast.
  141. /// @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
  142. /// @param ioCollector Collision collector that receives the collision results.
  143. virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const = 0;
  144. };
  145. /// Simple collision checker that loops over all registered characters.
  146. /// This is a brute force checking algorithm. If you have a lot of characters you may want to store your characters
  147. /// in a hierarchical structure to make this more efficient.
  148. /// Note that this is not thread safe, so make sure that only one CharacterVirtual is checking collision at a time.
  149. class JPH_EXPORT CharacterVsCharacterCollisionSimple : public CharacterVsCharacterCollision
  150. {
  151. public:
  152. /// Add a character to the list of characters to check collision against.
  153. void Add(CharacterVirtual *inCharacter) { mCharacters.push_back(inCharacter); }
  154. /// Remove a character from the list of characters to check collision against.
  155. void Remove(const CharacterVirtual *inCharacter);
  156. // See: CharacterVsCharacterCollision
  157. virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const override;
  158. virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const override;
  159. Array<CharacterVirtual *> mCharacters; ///< The list of characters to check collision against
  160. };
  161. /// Runtime character object.
  162. /// 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).
  163. /// 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)
  164. /// but the downside is that other objects don't see this virtual character. To make a CharacterVirtual visible to the simulation, you can optionally create an inner
  165. /// rigid body through CharacterVirtualSettings::mInnerBodyShape. A CharacterVirtual is not tracked by the PhysicsSystem so you need to update it yourself. This also means
  166. /// that a call to PhysicsSystem::SaveState will not save its state, you need to call CharacterVirtual::SaveState yourself.
  167. class JPH_EXPORT CharacterVirtual : public CharacterBase
  168. {
  169. public:
  170. JPH_OVERRIDE_NEW_DELETE
  171. /// Constructor
  172. /// @param inSettings The settings for the character
  173. /// @param inPosition Initial position for the character
  174. /// @param inRotation Initial rotation for the character (usually only around the up-axis)
  175. /// @param inUserData Application specific value
  176. /// @param inSystem Physics system that this character will be added to
  177. CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, uint64 inUserData, PhysicsSystem *inSystem);
  178. /// Constructor without user data
  179. CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem) : CharacterVirtual(inSettings, inPosition, inRotation, 0, inSystem) { }
  180. /// Destructor
  181. virtual ~CharacterVirtual() override;
  182. /// The ID of this character
  183. inline const CharacterID & GetID() const { return mID; }
  184. /// Set the contact listener
  185. void SetListener(CharacterContactListener *inListener) { mListener = inListener; }
  186. /// Get the current contact listener
  187. CharacterContactListener * GetListener() const { return mListener; }
  188. /// Set the character vs character collision interface
  189. void SetCharacterVsCharacterCollision(CharacterVsCharacterCollision *inCharacterVsCharacterCollision) { mCharacterVsCharacterCollision = inCharacterVsCharacterCollision; }
  190. /// Get the linear velocity of the character (m / s)
  191. Vec3 GetLinearVelocity() const { return mLinearVelocity; }
  192. /// Set the linear velocity of the character (m / s)
  193. void SetLinearVelocity(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; }
  194. /// Get the position of the character
  195. RVec3 GetPosition() const { return mPosition; }
  196. /// Set the position of the character
  197. void SetPosition(RVec3Arg inPosition) { mPosition = inPosition; UpdateInnerBodyTransform(); }
  198. /// Get the rotation of the character
  199. Quat GetRotation() const { return mRotation; }
  200. /// Set the rotation of the character
  201. void SetRotation(QuatArg inRotation) { mRotation = inRotation; UpdateInnerBodyTransform(); }
  202. // Get the center of mass position of the shape
  203. inline RVec3 GetCenterOfMassPosition() const { return mPosition + (mRotation * (mShapeOffset + mShape->GetCenterOfMass()) + mCharacterPadding * mUp); }
  204. /// Calculate the world transform of the character
  205. RMat44 GetWorldTransform() const { return RMat44::sRotationTranslation(mRotation, mPosition); }
  206. /// Calculates the transform for this character's center of mass
  207. RMat44 GetCenterOfMassTransform() const { return GetCenterOfMassTransform(mPosition, mRotation, mShape); }
  208. /// Character mass (kg)
  209. float GetMass() const { return mMass; }
  210. void SetMass(float inMass) { mMass = inMass; }
  211. /// Maximum force with which the character can push other bodies (N)
  212. float GetMaxStrength() const { return mMaxStrength; }
  213. void SetMaxStrength(float inMaxStrength) { mMaxStrength = inMaxStrength; }
  214. /// This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  215. float GetPenetrationRecoverySpeed() const { return mPenetrationRecoverySpeed; }
  216. void SetPenetrationRecoverySpeed(float inSpeed) { mPenetrationRecoverySpeed = inSpeed; }
  217. /// Set to indicate that extra effort should be made to try to remove ghost contacts (collisions with internal edges of a mesh). This is more expensive but makes bodies move smoother over a mesh with convex edges.
  218. bool GetEnhancedInternalEdgeRemoval() const { return mEnhancedInternalEdgeRemoval; }
  219. void SetEnhancedInternalEdgeRemoval(bool inApply) { mEnhancedInternalEdgeRemoval = inApply; }
  220. /// Character padding
  221. float GetCharacterPadding() const { return mCharacterPadding; }
  222. /// Max num hits to collect in order to avoid excess of contact points collection
  223. uint GetMaxNumHits() const { return mMaxNumHits; }
  224. void SetMaxNumHits(uint inMaxHits) { mMaxNumHits = inMaxHits; }
  225. /// 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.
  226. float GetHitReductionCosMaxAngle() const { return mHitReductionCosMaxAngle; }
  227. void SetHitReductionCosMaxAngle(float inCosMaxAngle) { mHitReductionCosMaxAngle = inCosMaxAngle; }
  228. /// Returns if we exceeded the maximum number of hits during the last collision check and had to discard hits based on distance.
  229. /// This can be used to find areas that have too complex geometry for the character to navigate properly.
  230. /// To solve you can either increase the max number of hits or simplify the geometry. Note that the character simulation will
  231. /// try to do its best to select the most relevant contacts to avoid the character from getting stuck.
  232. bool GetMaxHitsExceeded() const { return mMaxHitsExceeded; }
  233. /// 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.
  234. Vec3 GetShapeOffset() const { return mShapeOffset; }
  235. void SetShapeOffset(Vec3Arg inShapeOffset) { mShapeOffset = inShapeOffset; UpdateInnerBodyTransform(); }
  236. /// Access to the user data, can be used for anything by the application
  237. uint64 GetUserData() const { return mUserData; }
  238. void SetUserData(uint64 inUserData);
  239. /// Optional inner rigid body that proxies the character in the world. Can be used to update body properties.
  240. BodyID GetInnerBodyID() const { return mInnerBodyID; }
  241. /// 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.
  242. /// This velocity can then be set on the character using SetLinearVelocity()
  243. /// @param inDesiredVelocity Velocity to clamp against steep walls
  244. /// @return A new velocity vector that won't make the character move up steep slopes
  245. Vec3 CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const;
  246. /// This function is internally called by Update, WalkStairs, StickToFloor and ExtendedUpdate and is responsible for tracking if contacts are added, persisted or removed.
  247. /// If you want to do multiple operations on a character (e.g. first Update then WalkStairs), you can surround the code with a StartTrackingContactChanges and FinishTrackingContactChanges pair
  248. /// to only receive a single callback per contact on the CharacterContactListener. If you don't do this then you could for example receive a contact added callback during the Update and a
  249. /// contact persisted callback during WalkStairs.
  250. void StartTrackingContactChanges();
  251. /// This call triggers contact removal callbacks and is used in conjunction with StartTrackingContactChanges.
  252. void FinishTrackingContactChanges();
  253. /// 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
  254. /// 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!
  255. /// 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.
  256. /// @param inDeltaTime Time step to simulate.
  257. /// @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.
  258. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  259. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  260. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  261. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  262. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  263. void Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  264. /// This function will return true if the character has moved into a slope that is too steep (e.g. a vertical wall).
  265. /// You would call WalkStairs to attempt to step up stairs.
  266. /// @param inLinearVelocity The linear velocity that the player desired. This is used to determine if we're pushing into a step.
  267. bool CanWalkStairs(Vec3Arg inLinearVelocity) const;
  268. /// 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
  269. /// @param inDeltaTime Time step to simulate.
  270. /// @param inStepUp The direction and distance to step up (this corresponds to the max step height)
  271. /// @param inStepForward The direction and distance to step forward after the step up
  272. /// @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.
  273. /// @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.
  274. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  275. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  276. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  277. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  278. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  279. /// @return true if the stair walk was successful
  280. 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);
  281. /// 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
  282. /// 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,
  283. /// we do an additional collision check downwards and if we find the floor within a certain distance, we project the character onto the floor.
  284. /// @param inStepDown Max amount to project the character downwards (if no floor is found within this distance, the function will return false)
  285. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  286. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  287. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  288. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  289. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  290. /// @return True if the character was successfully projected onto the floor.
  291. bool StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  292. /// Settings struct with settings for ExtendedUpdate
  293. struct ExtendedUpdateSettings
  294. {
  295. Vec3 mStickToFloorStepDown { 0, -0.5f, 0 }; ///< See StickToFloor inStepDown parameter. Can be zero to turn off.
  296. Vec3 mWalkStairsStepUp { 0, 0.4f, 0 }; ///< See WalkStairs inStepUp parameter. Can be zero to turn off.
  297. float mWalkStairsMinStepForward { 0.02f }; ///< See WalkStairs inStepForward parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
  298. float mWalkStairsStepForwardTest { 0.15f }; ///< See WalkStairs inStepForwardTest parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.
  299. 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.
  300. Vec3 mWalkStairsStepDownExtra { Vec3::sZero() }; ///< See WalkStairs inStepDownExtra
  301. };
  302. /// This function combines Update, StickToFloor and WalkStairs. This function serves as an example of how these functions could be combined.
  303. /// Before calling, call SetLinearVelocity to update the horizontal/vertical speed of the character, typically this is:
  304. /// - When on OnGround and not moving away from ground: velocity = GetGroundVelocity() + horizontal speed as input by player + optional vertical jump velocity + delta time * gravity
  305. /// - Else: velocity = current vertical velocity + horizontal speed as input by player + delta time * gravity
  306. /// @param inDeltaTime Time step to simulate.
  307. /// @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.
  308. /// @param inSettings A structure containing settings for the algorithm.
  309. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  310. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  311. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  312. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  313. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  314. void ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  315. /// This function can be used after a character has teleported to determine the new contacts with the world.
  316. void RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  317. /// 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.
  318. /// It will not perform collision detection, so is less accurate than RefreshContacts but a lot faster.
  319. void UpdateGroundVelocity();
  320. /// Switch the shape of the character (e.g. for stance).
  321. /// @param inShape The shape to switch to.
  322. /// @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.
  323. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  324. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  325. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  326. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  327. /// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.
  328. /// @return Returns true if the switch succeeded.
  329. bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  330. /// Updates the shape of the inner rigid body. Should be called after a successful call to SetShape.
  331. void SetInnerBodyShape(const Shape *inShape);
  332. /// Get the transformed shape that represents the volume of the character, can be used for collision checks.
  333. TransformedShape GetTransformedShape() const { return TransformedShape(GetCenterOfMassPosition(), mRotation, mShape, mInnerBodyID); }
  334. /// @brief Get all contacts for the character at a particular location.
  335. /// When colliding with another character virtual, this pointer will be provided through CollideShapeCollector::SetUserContext before adding a hit.
  336. /// @param inPosition Position to test, note that this position will be corrected for the character padding.
  337. /// @param inRotation Rotation at which to test the shape.
  338. /// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.
  339. /// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).
  340. /// @param inShape Shape to test collision with.
  341. /// @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
  342. /// @param ioCollector Collision collector that receives the collision results.
  343. /// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.
  344. /// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.
  345. /// @param inBodyFilter Filter that is used to check if a character collides with a body.
  346. /// @param inShapeFilter Filter that is used to check if a character collides with a subshape.
  347. 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;
  348. /// Get the character settings that can recreate this character
  349. CharacterVirtualSettings GetCharacterVirtualSettings() const;
  350. // Saving / restoring state for replay
  351. virtual void SaveState(StateRecorder &inStream) const override;
  352. virtual void RestoreState(StateRecorder &inStream) override;
  353. #ifdef JPH_DEBUG_RENDERER
  354. static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating them
  355. static inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithm
  356. static inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm
  357. #endif
  358. /// Uniquely identifies a contact between a character and another body or character
  359. class ContactKey
  360. {
  361. public:
  362. /// Constructor
  363. ContactKey() = default;
  364. ContactKey(const ContactKey &inContact) = default;
  365. ContactKey(const BodyID &inBodyB, const SubShapeID &inSubShapeID) : mBodyB(inBodyB), mSubShapeIDB(inSubShapeID) { }
  366. ContactKey(const CharacterID &inCharacterIDB, const SubShapeID &inSubShapeID) : mCharacterIDB(inCharacterIDB), mSubShapeIDB(inSubShapeID) { }
  367. ContactKey & operator = (const ContactKey &inContact) = default;
  368. /// Checks if two contacts refer to the same body (or virtual character)
  369. inline bool IsSameBody(const ContactKey &inOther) const { return mBodyB == inOther.mBodyB && mCharacterIDB == inOther.mCharacterIDB; }
  370. /// Equality operator
  371. bool operator == (const ContactKey &inRHS) const
  372. {
  373. return mBodyB == inRHS.mBodyB && mCharacterIDB == inRHS.mCharacterIDB && mSubShapeIDB == inRHS.mSubShapeIDB;
  374. }
  375. bool operator != (const ContactKey &inRHS) const
  376. {
  377. return !(*this == inRHS);
  378. }
  379. /// Hash of this structure
  380. uint64 GetHash() const
  381. {
  382. static_assert(sizeof(BodyID) + sizeof(CharacterID) + sizeof(SubShapeID) == sizeof(ContactKey), "No padding expected");
  383. return HashBytes(this, sizeof(ContactKey));
  384. }
  385. // Saving / restoring state for replay
  386. void SaveState(StateRecorder &inStream) const;
  387. void RestoreState(StateRecorder &inStream);
  388. BodyID mBodyB; ///< ID of body we're colliding with (if not invalid)
  389. CharacterID mCharacterIDB; ///< Character we're colliding with (if not invalid)
  390. SubShapeID mSubShapeIDB; ///< Sub shape ID of body or character we're colliding with
  391. };
  392. /// Encapsulates a collision contact
  393. struct Contact : public ContactKey
  394. {
  395. // Saving / restoring state for replay
  396. void SaveState(StateRecorder &inStream) const;
  397. void RestoreState(StateRecorder &inStream);
  398. RVec3 mPosition; ///< Position where the character makes contact
  399. Vec3 mLinearVelocity; ///< Velocity of the contact point
  400. Vec3 mContactNormal; ///< Contact normal, pointing towards the character
  401. Vec3 mSurfaceNormal; ///< Surface normal of the contact
  402. float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive
  403. float mFraction; ///< Fraction along the path where this contact takes place
  404. EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact
  405. bool mIsSensorB; ///< If B is a sensor
  406. const CharacterVirtual * mCharacterB = nullptr; ///< Character we're colliding with (if not nullptr). Note that this may be a dangling pointer when accessed through GetActiveContacts(), use mCharacterIDB instead.
  407. uint64 mUserData; ///< User data of B
  408. const PhysicsMaterial * mMaterial; ///< Material of B
  409. bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)
  410. bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact or when the body is a sensor
  411. bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character
  412. };
  413. using TempContactList = Array<Contact, STLTempAllocator<Contact>>;
  414. using ContactList = Array<Contact>;
  415. /// Access to the internal list of contacts that the character has found.
  416. /// Note that only contacts that have their mHadCollision flag set are actual contacts.
  417. const ContactList & GetActiveContacts() const { return mActiveContacts; }
  418. /// Check if the character is currently in contact with or has collided with another body in the last operation (e.g. Update or WalkStairs)
  419. bool HasCollidedWith(const BodyID &inBody) const
  420. {
  421. for (const CharacterVirtual::Contact &c : mActiveContacts)
  422. if (c.mHadCollision && c.mBodyB == inBody)
  423. return true;
  424. return false;
  425. }
  426. /// Check if the character is currently in contact with or has collided with another character in the last time step (e.g. Update or WalkStairs)
  427. bool HasCollidedWith(const CharacterID &inCharacterID) const
  428. {
  429. for (const CharacterVirtual::Contact &c : mActiveContacts)
  430. if (c.mHadCollision && c.mCharacterIDB == inCharacterID)
  431. return true;
  432. return false;
  433. }
  434. /// Check if the character is currently in contact with or has collided with another character in the last time step (e.g. Update or WalkStairs)
  435. bool HasCollidedWith(const CharacterVirtual *inCharacter) const
  436. {
  437. return HasCollidedWith(inCharacter->GetID());
  438. }
  439. private:
  440. // Sorting predicate for making contact order deterministic
  441. struct ContactOrderingPredicate
  442. {
  443. inline bool operator () (const Contact &inLHS, const Contact &inRHS) const
  444. {
  445. if (inLHS.mBodyB != inRHS.mBodyB)
  446. return inLHS.mBodyB < inRHS.mBodyB;
  447. if (inLHS.mCharacterIDB != inRHS.mCharacterIDB)
  448. return inLHS.mCharacterIDB < inRHS.mCharacterIDB;
  449. return inLHS.mSubShapeIDB.GetValue() < inRHS.mSubShapeIDB.GetValue();
  450. }
  451. };
  452. using IgnoredContactList = Array<ContactKey, STLTempAllocator<ContactKey>>;
  453. // A constraint that limits the movement of the character
  454. struct Constraint
  455. {
  456. Contact * mContact; ///< Contact that this constraint was generated from
  457. float mTOI; ///< Calculated time of impact (can be negative if penetrating)
  458. float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)
  459. Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)
  460. Plane mPlane; ///< Plane around the origin that describes how far we can displace (from the origin)
  461. bool mIsSteepSlope = false; ///< If this constraint belongs to a steep slope
  462. };
  463. using ConstraintList = Array<Constraint, STLTempAllocator<Constraint>>;
  464. // Collision collector that collects hits for CollideShape
  465. class ContactCollector : public CollideShapeCollector
  466. {
  467. public:
  468. 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) { }
  469. virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }
  470. virtual void AddHit(const CollideShapeResult &inResult) override;
  471. RVec3 mBaseOffset;
  472. Vec3 mUp;
  473. PhysicsSystem * mSystem;
  474. const CharacterVirtual * mCharacter;
  475. CharacterVirtual * mOtherCharacter = nullptr;
  476. TempContactList & mContacts;
  477. uint mMaxHits;
  478. float mHitReductionCosMaxAngle;
  479. bool mMaxHitsExceeded = false;
  480. };
  481. // A collision collector that collects hits for CastShape
  482. class ContactCastCollector : public CastShapeCollector
  483. {
  484. public:
  485. 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) { }
  486. virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }
  487. virtual void AddHit(const ShapeCastResult &inResult) override;
  488. RVec3 mBaseOffset;
  489. Vec3 mDisplacement;
  490. Vec3 mUp;
  491. PhysicsSystem * mSystem;
  492. const CharacterVirtual * mCharacter;
  493. CharacterVirtual * mOtherCharacter = nullptr;
  494. const IgnoredContactList & mIgnoredContacts;
  495. Contact & mContact;
  496. };
  497. // Helper function to convert a Jolt collision result into a contact
  498. template <class taCollector>
  499. inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);
  500. inline static void sFillCharacterContactProperties(Contact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult);
  501. // Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometry
  502. void MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator
  503. #ifdef JPH_DEBUG_RENDERER
  504. , bool inDrawConstraints = false
  505. #endif // JPH_DEBUG_RENDERER
  506. );
  507. // Ask the callback if inContact is a valid contact point
  508. bool ValidateContact(const Contact &inContact) const;
  509. // Trigger the contact callback for inContact and get the contact settings
  510. void ContactAdded(const Contact &inContact, CharacterContactSettings &ioSettings);
  511. // Tests the shape for collision around inPosition
  512. void GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  513. // Remove penetrating contacts with the same body that have conflicting normals, leaving these will make the character mover get stuck
  514. void RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const;
  515. // 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.
  516. void DetermineConstraints(TempContactList &inContacts, float inDeltaTime, ConstraintList &outConstraints) const;
  517. // 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.
  518. void SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator
  519. #ifdef JPH_DEBUG_RENDERER
  520. , bool inDrawConstraints = false
  521. #endif // JPH_DEBUG_RENDERER
  522. );
  523. // Get the velocity of a body adjusted by the contact listener
  524. void GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const;
  525. // 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.
  526. // Note that we don't just take the point velocity because a point on an object with angular velocity traces an arc,
  527. // so if you just take point velocity * delta time you get an error that accumulates over time
  528. Vec3 CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass, Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, float inDeltaTime) const;
  529. // Handle contact with physics object that we're colliding against
  530. bool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime);
  531. // Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision
  532. bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;
  533. // Store contacts so that we have proper ground information
  534. void StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);
  535. // This function will determine which contacts are touching the character and will calculate the one that is supporting us
  536. void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);
  537. /// This function can be called after moving the character to a new colliding position
  538. void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);
  539. // This function returns the actual center of mass of the shape, not corrected for the character padding
  540. inline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const
  541. {
  542. return RMat44::sRotationTranslation(inRotation, inPosition).PreTranslated(mShapeOffset + inShape->GetCenterOfMass()).PostTranslated(mCharacterPadding * mUp);
  543. }
  544. // This function returns the position of the inner rigid body
  545. inline RVec3 GetInnerBodyPosition() const
  546. {
  547. return mPosition + (mRotation * mShapeOffset + mCharacterPadding * mUp);
  548. }
  549. // Move the inner rigid body to the current position
  550. void UpdateInnerBodyTransform();
  551. // ID
  552. CharacterID mID;
  553. // Our main listener for contacts
  554. CharacterContactListener * mListener = nullptr;
  555. // Interface to detect collision between characters
  556. CharacterVsCharacterCollision * mCharacterVsCharacterCollision = nullptr;
  557. // Movement settings
  558. 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.
  559. 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.
  560. uint mMaxCollisionIterations; // Max amount of collision loops
  561. uint mMaxConstraintIterations; // How often to try stepping in the constraint solving
  562. float mMinTimeRemaining; // Early out condition: If this much time is left to simulate we are done
  563. float mCollisionTolerance; // How far we're willing to penetrate geometry
  564. 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
  565. uint mMaxNumHits; // Max num hits to collect in order to avoid excess of contact points collection
  566. 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.
  567. float mPenetrationRecoverySpeed; // This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update
  568. bool mEnhancedInternalEdgeRemoval; // Set to indicate that extra effort should be made to try to remove ghost contacts (collisions with internal edges of a mesh). This is more expensive but makes bodies move smoother over a mesh with convex edges.
  569. // Character mass (kg)
  570. float mMass;
  571. // Maximum force with which the character can push other bodies (N)
  572. float mMaxStrength;
  573. // An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.
  574. Vec3 mShapeOffset = Vec3::sZero();
  575. // Current position (of the base, not the center of mass)
  576. RVec3 mPosition = RVec3::sZero();
  577. // Current rotation (of the base, not of the center of mass)
  578. Quat mRotation = Quat::sIdentity();
  579. // Current linear velocity
  580. Vec3 mLinearVelocity = Vec3::sZero();
  581. // List of contacts that were active in the last frame
  582. ContactList mActiveContacts;
  583. // Remembers how often we called StartTrackingContactChanges
  584. int mTrackingContactChanges = 0;
  585. // View from a contact listener perspective on which contacts have been added/removed
  586. struct ListenerContactValue
  587. {
  588. ListenerContactValue() = default;
  589. explicit ListenerContactValue(const CharacterContactSettings &inSettings) : mSettings(inSettings) { }
  590. CharacterContactSettings mSettings;
  591. int mCount = 0;
  592. };
  593. using ListenerContacts = UnorderedMap<ContactKey, ListenerContactValue>;
  594. ListenerContacts mListenerContacts;
  595. // Remembers the delta time of the last update
  596. float mLastDeltaTime = 1.0f / 60.0f;
  597. // Remember if we exceeded the maximum number of hits and had to remove similar contacts
  598. mutable bool mMaxHitsExceeded = false;
  599. // User data, can be used for anything by the application
  600. uint64 mUserData = 0;
  601. // The inner rigid body that proxies the character in the world
  602. BodyID mInnerBodyID;
  603. };
  604. JPH_NAMESPACE_END