Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.h
9912 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#pragma once56#include <Jolt/Physics/Character/CharacterBase.h>7#include <Jolt/Physics/Character/CharacterID.h>8#include <Jolt/Physics/Body/MotionType.h>9#include <Jolt/Physics/Body/BodyFilter.h>10#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseLayer.h>11#include <Jolt/Physics/Collision/ObjectLayer.h>12#include <Jolt/Physics/Collision/TransformedShape.h>13#include <Jolt/Core/STLTempAllocator.h>1415JPH_NAMESPACE_BEGIN1617class CharacterVirtual;18class CollideShapeSettings;1920/// Contains the configuration of a character21class JPH_EXPORT CharacterVirtualSettings : public CharacterBaseSettings22{23public:24JPH_OVERRIDE_NEW_DELETE2526/// 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.27CharacterID mID = CharacterID::sNextCharacterID();2829/// Character mass (kg). Used to push down objects with gravity when the character is standing on top.30float mMass = 70.0f;3132/// Maximum force with which the character can push other bodies (N).33float mMaxStrength = 100.0f;3435/// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.36Vec3 mShapeOffset = Vec3::sZero();3738///@name Movement settings39EBackFaceMode 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.40float 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.41uint mMaxCollisionIterations = 5; ///< Max amount of collision loops42uint mMaxConstraintIterations = 15; ///< How often to try stepping in the constraint solving43float mMinTimeRemaining = 1.0e-4f; ///< Early out condition: If this much time is left to simulate we are done44float mCollisionTolerance = 1.0e-3f; ///< How far we're willing to penetrate geometry45float 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 stuck46uint mMaxNumHits = 256; ///< Max num hits to collect in order to avoid excess of contact points collection47float 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.48float mPenetrationRecoverySpeed = 1.0f; ///< This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update4950/// 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:51/// - 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)52/// - Regular contact callbacks will be called through the ContactListener (next to the ones that will be passed to the CharacterContactListener)53/// - Fast moving objects of motion quality LinearCast will not be able to pass through the CharacterVirtual in 1 time step54RefConst<Shape> mInnerBodyShape;5556/// For a deterministic simulation, it is important to have a deterministic body ID. When set and when mInnerBodyShape is specified,57/// the inner body will be created with this specified ID instead of a generated ID.58BodyID mInnerBodyIDOverride;5960/// Layer that the inner rigid body will be added to61ObjectLayer mInnerBodyLayer = 0;62};6364/// This class contains settings that allow you to override the behavior of a character's collision response65class CharacterContactSettings66{67public:68/// True when the object can push the virtual character.69bool mCanPushCharacter = true;7071/// True when the virtual character can apply impulses (push) the body.72/// Note that this only works against rigid bodies. Other CharacterVirtual objects can only be moved in their own update,73/// so you must ensure that in their OnCharacterContactAdded mCanPushCharacter is true.74bool mCanReceiveImpulses = true;75};7677/// This class receives callbacks when a virtual character hits something.78class JPH_EXPORT CharacterContactListener79{80public:81/// Destructor82virtual ~CharacterContactListener() = default;8384/// 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.85/// Note that inBody2 is locked during the callback so you can read its properties freely.86virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }8788/// Checks if a character can collide with specified body. Return true if the contact is valid.89virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }9091/// Same as OnContactValidate but when colliding with a CharacterVirtual92virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2) { return true; }9394/// Called whenever the character collides with a body for the first time.95/// @param inCharacter Character that is being solved96/// @param inBodyID2 Body ID of body that is being hit97/// @param inSubShapeID2 Sub shape ID of shape that is being hit98/// @param inContactPosition World space contact position99/// @param inContactNormal World space contact normal100/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave101virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }102103/// Called whenever the character persists colliding with a body.104/// @param inCharacter Character that is being solved105/// @param inBodyID2 Body ID of body that is being hit106/// @param inSubShapeID2 Sub shape ID of shape that is being hit107/// @param inContactPosition World space contact position108/// @param inContactNormal World space contact normal109/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave110virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }111112/// Called whenever the character loses contact with a body.113/// 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.114/// @param inCharacter Character that is being solved115/// @param inBodyID2 Body ID of body that is being hit116/// @param inSubShapeID2 Sub shape ID of shape that is being hit117virtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }118119/// Same as OnContactAdded but when colliding with a CharacterVirtual120virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }121122/// Same as OnContactPersisted but when colliding with a CharacterVirtual123virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }124125/// Same as OnContactRemoved but when colliding with a CharacterVirtual126/// 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.127virtual void OnCharacterContactRemoved(const CharacterVirtual *inCharacter, const CharacterID &inOtherCharacterID, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }128129/// 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).130/// @param inCharacter Character that is being solved131/// @param inBodyID2 Body ID of body that is being hit132/// @param inSubShapeID2 Sub shape ID of shape that is being hit133/// @param inContactPosition World space contact position134/// @param inContactNormal World space contact normal135/// @param inContactVelocity World space velocity of contact point (e.g. for a moving platform)136/// @param inContactMaterial Material of contact point137/// @param inCharacterVelocity World space velocity of the character prior to hitting this contact138/// @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.139virtual 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 */ }140141/// Same as OnContactSolve but when colliding with a CharacterVirtual142virtual 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 */ }143};144145/// Interface class that allows a CharacterVirtual to check collision with other CharacterVirtual instances.146/// Since CharacterVirtual instances are not registered anywhere, it is up to the application to test collision against relevant characters.147/// The characters could be stored in a tree structure to make this more efficient.148class JPH_EXPORT CharacterVsCharacterCollision : public NonCopyable149{150public:151virtual ~CharacterVsCharacterCollision() = default;152153/// Collide a character against other CharacterVirtuals.154/// @param inCharacter The character to collide.155/// @param inCenterOfMassTransform Center of mass transform for this character.156/// @param inCollideShapeSettings Settings for the collision check.157/// @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 origin158/// @param ioCollector Collision collector that receives the collision results.159virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const = 0;160161/// Cast a character against other CharacterVirtuals.162/// @param inCharacter The character to cast.163/// @param inCenterOfMassTransform Center of mass transform for this character.164/// @param inDirection Direction and length to cast in.165/// @param inShapeCastSettings Settings for the shape cast.166/// @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 origin167/// @param ioCollector Collision collector that receives the collision results.168virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const = 0;169};170171/// Simple collision checker that loops over all registered characters.172/// This is a brute force checking algorithm. If you have a lot of characters you may want to store your characters173/// in a hierarchical structure to make this more efficient.174/// Note that this is not thread safe, so make sure that only one CharacterVirtual is checking collision at a time.175class JPH_EXPORT CharacterVsCharacterCollisionSimple : public CharacterVsCharacterCollision176{177public:178/// Add a character to the list of characters to check collision against.179void Add(CharacterVirtual *inCharacter) { mCharacters.push_back(inCharacter); }180181/// Remove a character from the list of characters to check collision against.182void Remove(const CharacterVirtual *inCharacter);183184// See: CharacterVsCharacterCollision185virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const override;186virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const override;187188Array<CharacterVirtual *> mCharacters; ///< The list of characters to check collision against189};190191/// Runtime character object.192/// 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).193/// 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)194/// 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 inner195/// rigid body through CharacterVirtualSettings::mInnerBodyShape. A CharacterVirtual is not tracked by the PhysicsSystem so you need to update it yourself. This also means196/// that a call to PhysicsSystem::SaveState will not save its state, you need to call CharacterVirtual::SaveState yourself.197class JPH_EXPORT CharacterVirtual : public CharacterBase198{199public:200JPH_OVERRIDE_NEW_DELETE201202/// Constructor203/// @param inSettings The settings for the character204/// @param inPosition Initial position for the character205/// @param inRotation Initial rotation for the character (usually only around the up-axis)206/// @param inUserData Application specific value207/// @param inSystem Physics system that this character will be added to208CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, uint64 inUserData, PhysicsSystem *inSystem);209210/// Constructor without user data211CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem) : CharacterVirtual(inSettings, inPosition, inRotation, 0, inSystem) { }212213/// Destructor214virtual ~CharacterVirtual() override;215216/// The ID of this character217inline const CharacterID & GetID() const { return mID; }218219/// Set the contact listener220void SetListener(CharacterContactListener *inListener) { mListener = inListener; }221222/// Get the current contact listener223CharacterContactListener * GetListener() const { return mListener; }224225/// Set the character vs character collision interface226void SetCharacterVsCharacterCollision(CharacterVsCharacterCollision *inCharacterVsCharacterCollision) { mCharacterVsCharacterCollision = inCharacterVsCharacterCollision; }227228/// Get the linear velocity of the character (m / s)229Vec3 GetLinearVelocity() const { return mLinearVelocity; }230231/// Set the linear velocity of the character (m / s)232void SetLinearVelocity(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; }233234/// Get the position of the character235RVec3 GetPosition() const { return mPosition; }236237/// Set the position of the character238void SetPosition(RVec3Arg inPosition) { mPosition = inPosition; UpdateInnerBodyTransform(); }239240/// Get the rotation of the character241Quat GetRotation() const { return mRotation; }242243/// Set the rotation of the character244void SetRotation(QuatArg inRotation) { mRotation = inRotation; UpdateInnerBodyTransform(); }245246// Get the center of mass position of the shape247inline RVec3 GetCenterOfMassPosition() const { return mPosition + (mRotation * (mShapeOffset + mShape->GetCenterOfMass()) + mCharacterPadding * mUp); }248249/// Calculate the world transform of the character250RMat44 GetWorldTransform() const { return RMat44::sRotationTranslation(mRotation, mPosition); }251252/// Calculates the transform for this character's center of mass253RMat44 GetCenterOfMassTransform() const { return GetCenterOfMassTransform(mPosition, mRotation, mShape); }254255/// Character mass (kg)256float GetMass() const { return mMass; }257void SetMass(float inMass) { mMass = inMass; }258259/// Maximum force with which the character can push other bodies (N)260float GetMaxStrength() const { return mMaxStrength; }261void SetMaxStrength(float inMaxStrength) { mMaxStrength = inMaxStrength; }262263/// This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update264float GetPenetrationRecoverySpeed() const { return mPenetrationRecoverySpeed; }265void SetPenetrationRecoverySpeed(float inSpeed) { mPenetrationRecoverySpeed = inSpeed; }266267/// 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.268bool GetEnhancedInternalEdgeRemoval() const { return mEnhancedInternalEdgeRemoval; }269void SetEnhancedInternalEdgeRemoval(bool inApply) { mEnhancedInternalEdgeRemoval = inApply; }270271/// Character padding272float GetCharacterPadding() const { return mCharacterPadding; }273274/// Max num hits to collect in order to avoid excess of contact points collection275uint GetMaxNumHits() const { return mMaxNumHits; }276void SetMaxNumHits(uint inMaxHits) { mMaxNumHits = inMaxHits; }277278/// 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.279float GetHitReductionCosMaxAngle() const { return mHitReductionCosMaxAngle; }280void SetHitReductionCosMaxAngle(float inCosMaxAngle) { mHitReductionCosMaxAngle = inCosMaxAngle; }281282/// Returns if we exceeded the maximum number of hits during the last collision check and had to discard hits based on distance.283/// This can be used to find areas that have too complex geometry for the character to navigate properly.284/// To solve you can either increase the max number of hits or simplify the geometry. Note that the character simulation will285/// try to do its best to select the most relevant contacts to avoid the character from getting stuck.286bool GetMaxHitsExceeded() const { return mMaxHitsExceeded; }287288/// 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.289Vec3 GetShapeOffset() const { return mShapeOffset; }290void SetShapeOffset(Vec3Arg inShapeOffset) { mShapeOffset = inShapeOffset; UpdateInnerBodyTransform(); }291292/// Access to the user data, can be used for anything by the application293uint64 GetUserData() const { return mUserData; }294void SetUserData(uint64 inUserData);295296/// Optional inner rigid body that proxies the character in the world. Can be used to update body properties.297BodyID GetInnerBodyID() const { return mInnerBodyID; }298299/// 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.300/// This velocity can then be set on the character using SetLinearVelocity()301/// @param inDesiredVelocity Velocity to clamp against steep walls302/// @return A new velocity vector that won't make the character move up steep slopes303Vec3 CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const;304305/// This function is internally called by Update, WalkStairs, StickToFloor and ExtendedUpdate and is responsible for tracking if contacts are added, persisted or removed.306/// 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 pair307/// 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 a308/// contact persisted callback during WalkStairs.309void StartTrackingContactChanges();310311/// This call triggers contact removal callbacks and is used in conjunction with StartTrackingContactChanges.312void FinishTrackingContactChanges();313314/// 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 sense315/// 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!316/// 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.317/// @param inDeltaTime Time step to simulate.318/// @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.319/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.320/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.321/// @param inBodyFilter Filter that is used to check if a character collides with a body.322/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.323/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.324void Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);325326/// This function will return true if the character has moved into a slope that is too steep (e.g. a vertical wall).327/// You would call WalkStairs to attempt to step up stairs.328/// @param inLinearVelocity The linear velocity that the player desired. This is used to determine if we're pushing into a step.329bool CanWalkStairs(Vec3Arg inLinearVelocity) const;330331/// When stair walking is needed, you can call the WalkStairs function to cast up, forward and down again to try to find a valid position332/// @param inDeltaTime Time step to simulate.333/// @param inStepUp The direction and distance to step up (this corresponds to the max step height)334/// @param inStepForward The direction and distance to step forward after the step up335/// @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.336/// @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.337/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.338/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.339/// @param inBodyFilter Filter that is used to check if a character collides with a body.340/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.341/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.342/// @return true if the stair walk was successful343bool 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);344345/// 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 will346/// 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,347/// we do an additional collision check downwards and if we find the floor within a certain distance, we project the character onto the floor.348/// @param inStepDown Max amount to project the character downwards (if no floor is found within this distance, the function will return false)349/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.350/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.351/// @param inBodyFilter Filter that is used to check if a character collides with a body.352/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.353/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.354/// @return True if the character was successfully projected onto the floor.355bool StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);356357/// Settings struct with settings for ExtendedUpdate358struct ExtendedUpdateSettings359{360Vec3 mStickToFloorStepDown { 0, -0.5f, 0 }; ///< See StickToFloor inStepDown parameter. Can be zero to turn off.361Vec3 mWalkStairsStepUp { 0, 0.4f, 0 }; ///< See WalkStairs inStepUp parameter. Can be zero to turn off.362float mWalkStairsMinStepForward { 0.02f }; ///< See WalkStairs inStepForward parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.363float mWalkStairsStepForwardTest { 0.15f }; ///< See WalkStairs inStepForwardTest parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.364float 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.365Vec3 mWalkStairsStepDownExtra { Vec3::sZero() }; ///< See WalkStairs inStepDownExtra366};367368/// This function combines Update, StickToFloor and WalkStairs. This function serves as an example of how these functions could be combined.369/// Before calling, call SetLinearVelocity to update the horizontal/vertical speed of the character, typically this is:370/// - When on OnGround and not moving away from ground: velocity = GetGroundVelocity() + horizontal speed as input by player + optional vertical jump velocity + delta time * gravity371/// - Else: velocity = current vertical velocity + horizontal speed as input by player + delta time * gravity372/// @param inDeltaTime Time step to simulate.373/// @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.374/// @param inSettings A structure containing settings for the algorithm.375/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.376/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.377/// @param inBodyFilter Filter that is used to check if a character collides with a body.378/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.379/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.380void ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);381382/// This function can be used after a character has teleported to determine the new contacts with the world.383void RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);384385/// 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.386/// It will not perform collision detection, so is less accurate than RefreshContacts but a lot faster.387void UpdateGroundVelocity();388389/// Switch the shape of the character (e.g. for stance).390/// @param inShape The shape to switch to.391/// @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.392/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.393/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.394/// @param inBodyFilter Filter that is used to check if a character collides with a body.395/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.396/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.397/// @return Returns true if the switch succeeded.398bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);399400/// Updates the shape of the inner rigid body. Should be called after a successful call to SetShape.401void SetInnerBodyShape(const Shape *inShape);402403/// Get the transformed shape that represents the volume of the character, can be used for collision checks.404TransformedShape GetTransformedShape() const { return TransformedShape(GetCenterOfMassPosition(), mRotation, mShape, mInnerBodyID); }405406/// @brief Get all contacts for the character at a particular location.407/// When colliding with another character virtual, this pointer will be provided through CollideShapeCollector::SetUserContext before adding a hit.408/// @param inPosition Position to test, note that this position will be corrected for the character padding.409/// @param inRotation Rotation at which to test the shape.410/// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.411/// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).412/// @param inShape Shape to test collision with.413/// @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 origin414/// @param ioCollector Collision collector that receives the collision results.415/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.416/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.417/// @param inBodyFilter Filter that is used to check if a character collides with a body.418/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.419void 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;420421// Saving / restoring state for replay422virtual void SaveState(StateRecorder &inStream) const override;423virtual void RestoreState(StateRecorder &inStream) override;424425#ifdef JPH_DEBUG_RENDERER426static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating them427static inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithm428static inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm429#endif430431/// Uniquely identifies a contact between a character and another body or character432class ContactKey433{434public:435/// Constructor436ContactKey() = default;437ContactKey(const ContactKey &inContact) = default;438ContactKey(const BodyID &inBodyB, const SubShapeID &inSubShapeID) : mBodyB(inBodyB), mSubShapeIDB(inSubShapeID) { }439ContactKey(const CharacterID &inCharacterIDB, const SubShapeID &inSubShapeID) : mCharacterIDB(inCharacterIDB), mSubShapeIDB(inSubShapeID) { }440ContactKey & operator = (const ContactKey &inContact) = default;441442/// Checks if two contacts refer to the same body (or virtual character)443inline bool IsSameBody(const ContactKey &inOther) const { return mBodyB == inOther.mBodyB && mCharacterIDB == inOther.mCharacterIDB; }444445/// Equality operator446bool operator == (const ContactKey &inRHS) const447{448return mBodyB == inRHS.mBodyB && mCharacterIDB == inRHS.mCharacterIDB && mSubShapeIDB == inRHS.mSubShapeIDB;449}450451bool operator != (const ContactKey &inRHS) const452{453return !(*this == inRHS);454}455456/// Hash of this structure457uint64 GetHash() const458{459static_assert(sizeof(BodyID) + sizeof(CharacterID) + sizeof(SubShapeID) == sizeof(ContactKey), "No padding expected");460return HashBytes(this, sizeof(ContactKey));461}462463// Saving / restoring state for replay464void SaveState(StateRecorder &inStream) const;465void RestoreState(StateRecorder &inStream);466467BodyID mBodyB; ///< ID of body we're colliding with (if not invalid)468CharacterID mCharacterIDB; ///< Character we're colliding with (if not invalid)469SubShapeID mSubShapeIDB; ///< Sub shape ID of body or character we're colliding with470};471472/// Encapsulates a collision contact473struct Contact : public ContactKey474{475// Saving / restoring state for replay476void SaveState(StateRecorder &inStream) const;477void RestoreState(StateRecorder &inStream);478479RVec3 mPosition; ///< Position where the character makes contact480Vec3 mLinearVelocity; ///< Velocity of the contact point481Vec3 mContactNormal; ///< Contact normal, pointing towards the character482Vec3 mSurfaceNormal; ///< Surface normal of the contact483float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive484float mFraction; ///< Fraction along the path where this contact takes place485EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact486bool mIsSensorB; ///< If B is a sensor487const 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.488uint64 mUserData; ///< User data of B489const PhysicsMaterial * mMaterial; ///< Material of B490bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)491bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact or when the body is a sensor492bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character493};494495using TempContactList = Array<Contact, STLTempAllocator<Contact>>;496using ContactList = Array<Contact>;497498/// Access to the internal list of contacts that the character has found.499/// Note that only contacts that have their mHadCollision flag set are actual contacts.500const ContactList & GetActiveContacts() const { return mActiveContacts; }501502/// Check if the character is currently in contact with or has collided with another body in the last operation (e.g. Update or WalkStairs)503bool HasCollidedWith(const BodyID &inBody) const504{505for (const CharacterVirtual::Contact &c : mActiveContacts)506if (c.mHadCollision && c.mBodyB == inBody)507return true;508return false;509}510511/// 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)512bool HasCollidedWith(const CharacterID &inCharacterID) const513{514for (const CharacterVirtual::Contact &c : mActiveContacts)515if (c.mHadCollision && c.mCharacterIDB == inCharacterID)516return true;517return false;518}519520/// 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)521bool HasCollidedWith(const CharacterVirtual *inCharacter) const522{523return HasCollidedWith(inCharacter->GetID());524}525526private:527// Sorting predicate for making contact order deterministic528struct ContactOrderingPredicate529{530inline bool operator () (const Contact &inLHS, const Contact &inRHS) const531{532if (inLHS.mBodyB != inRHS.mBodyB)533return inLHS.mBodyB < inRHS.mBodyB;534535if (inLHS.mCharacterIDB != inRHS.mCharacterIDB)536return inLHS.mCharacterIDB < inRHS.mCharacterIDB;537538return inLHS.mSubShapeIDB.GetValue() < inRHS.mSubShapeIDB.GetValue();539}540};541542using IgnoredContactList = Array<ContactKey, STLTempAllocator<ContactKey>>;543544// A constraint that limits the movement of the character545struct Constraint546{547Contact * mContact; ///< Contact that this constraint was generated from548float mTOI; ///< Calculated time of impact (can be negative if penetrating)549float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)550Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)551Plane mPlane; ///< Plane around the origin that describes how far we can displace (from the origin)552bool mIsSteepSlope = false; ///< If this constraint belongs to a steep slope553};554555using ConstraintList = Array<Constraint, STLTempAllocator<Constraint>>;556557// Collision collector that collects hits for CollideShape558class ContactCollector : public CollideShapeCollector559{560public:561ContactCollector(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) { }562563virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }564565virtual void AddHit(const CollideShapeResult &inResult) override;566567RVec3 mBaseOffset;568Vec3 mUp;569PhysicsSystem * mSystem;570const CharacterVirtual * mCharacter;571CharacterVirtual * mOtherCharacter = nullptr;572TempContactList & mContacts;573uint mMaxHits;574float mHitReductionCosMaxAngle;575bool mMaxHitsExceeded = false;576};577578// A collision collector that collects hits for CastShape579class ContactCastCollector : public CastShapeCollector580{581public:582ContactCastCollector(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) { }583584virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }585586virtual void AddHit(const ShapeCastResult &inResult) override;587588RVec3 mBaseOffset;589Vec3 mDisplacement;590Vec3 mUp;591PhysicsSystem * mSystem;592const CharacterVirtual * mCharacter;593CharacterVirtual * mOtherCharacter = nullptr;594const IgnoredContactList & mIgnoredContacts;595Contact & mContact;596};597598// Helper function to convert a Jolt collision result into a contact599template <class taCollector>600inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);601inline static void sFillCharacterContactProperties(Contact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult);602603// Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometry604void MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator605#ifdef JPH_DEBUG_RENDERER606, bool inDrawConstraints = false607#endif // JPH_DEBUG_RENDERER608);609610// Ask the callback if inContact is a valid contact point611bool ValidateContact(const Contact &inContact) const;612613// Trigger the contact callback for inContact and get the contact settings614void ContactAdded(const Contact &inContact, CharacterContactSettings &ioSettings);615616// Tests the shape for collision around inPosition617void GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;618619// Remove penetrating contacts with the same body that have conflicting normals, leaving these will make the character mover get stuck620void RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const;621622// 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.623void DetermineConstraints(TempContactList &inContacts, float inDeltaTime, ConstraintList &outConstraints) const;624625// 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.626void SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator627#ifdef JPH_DEBUG_RENDERER628, bool inDrawConstraints = false629#endif // JPH_DEBUG_RENDERER630);631632// Get the velocity of a body adjusted by the contact listener633void GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const;634635// 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.636// Note that we don't just take the point velocity because a point on an object with angular velocity traces an arc,637// so if you just take point velocity * delta time you get an error that accumulates over time638Vec3 CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass, Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, float inDeltaTime) const;639640// Handle contact with physics object that we're colliding against641bool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime);642643// Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision644bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;645646// Store contacts so that we have proper ground information647void StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);648649// This function will determine which contacts are touching the character and will calculate the one that is supporting us650void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);651652/// This function can be called after moving the character to a new colliding position653void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);654655// This function returns the actual center of mass of the shape, not corrected for the character padding656inline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const657{658return RMat44::sRotationTranslation(inRotation, inPosition).PreTranslated(mShapeOffset + inShape->GetCenterOfMass()).PostTranslated(mCharacterPadding * mUp);659}660661// This function returns the position of the inner rigid body662inline RVec3 GetInnerBodyPosition() const663{664return mPosition + (mRotation * mShapeOffset + mCharacterPadding * mUp);665}666667// Move the inner rigid body to the current position668void UpdateInnerBodyTransform();669670// ID671CharacterID mID;672673// Our main listener for contacts674CharacterContactListener * mListener = nullptr;675676// Interface to detect collision between characters677CharacterVsCharacterCollision * mCharacterVsCharacterCollision = nullptr;678679// Movement settings680EBackFaceMode 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.681float 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.682uint mMaxCollisionIterations; // Max amount of collision loops683uint mMaxConstraintIterations; // How often to try stepping in the constraint solving684float mMinTimeRemaining; // Early out condition: If this much time is left to simulate we are done685float mCollisionTolerance; // How far we're willing to penetrate geometry686float 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 stuck687uint mMaxNumHits; // Max num hits to collect in order to avoid excess of contact points collection688float 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.689float mPenetrationRecoverySpeed; // This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update690bool 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.691692// Character mass (kg)693float mMass;694695// Maximum force with which the character can push other bodies (N)696float mMaxStrength;697698// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.699Vec3 mShapeOffset = Vec3::sZero();700701// Current position (of the base, not the center of mass)702RVec3 mPosition = RVec3::sZero();703704// Current rotation (of the base, not of the center of mass)705Quat mRotation = Quat::sIdentity();706707// Current linear velocity708Vec3 mLinearVelocity = Vec3::sZero();709710// List of contacts that were active in the last frame711ContactList mActiveContacts;712713// Remembers how often we called StartTrackingContactChanges714int mTrackingContactChanges = 0;715716// View from a contact listener perspective on which contacts have been added/removed717struct ListenerContactValue718{719ListenerContactValue() = default;720explicit ListenerContactValue(const CharacterContactSettings &inSettings) : mSettings(inSettings) { }721722CharacterContactSettings mSettings;723int mCount = 0;724};725726using ListenerContacts = UnorderedMap<ContactKey, ListenerContactValue>;727ListenerContacts mListenerContacts;728729// Remembers the delta time of the last update730float mLastDeltaTime = 1.0f / 60.0f;731732// Remember if we exceeded the maximum number of hits and had to remove similar contacts733mutable bool mMaxHitsExceeded = false;734735// User data, can be used for anything by the application736uint64 mUserData = 0;737738// The inner rigid body that proxies the character in the world739BodyID mInnerBodyID;740};741742JPH_NAMESPACE_END743744745