Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Character/CharacterVirtual.h
21798 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/// Constructor27CharacterVirtualSettings() = default;28CharacterVirtualSettings(const CharacterVirtualSettings &) = default;29CharacterVirtualSettings & operator = (const CharacterVirtualSettings &) = default;3031/// 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.32CharacterID mID = CharacterID::sNextCharacterID();3334/// Character mass (kg). Used to push down objects with gravity when the character is standing on top.35float mMass = 70.0f;3637/// Maximum force with which the character can push other bodies (N).38float mMaxStrength = 100.0f;3940/// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.41Vec3 mShapeOffset = Vec3::sZero();4243///@name Movement settings44EBackFaceMode 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.45float 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.46uint mMaxCollisionIterations = 5; ///< Max amount of collision loops47uint mMaxConstraintIterations = 15; ///< How often to try stepping in the constraint solving48float mMinTimeRemaining = 1.0e-4f; ///< Early out condition: If this much time is left to simulate we are done49float mCollisionTolerance = 1.0e-3f; ///< How far we're willing to penetrate geometry50float 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 stuck51uint mMaxNumHits = 256; ///< Max num hits to collect in order to avoid excess of contact points collection52float 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.53float mPenetrationRecoverySpeed = 1.0f; ///< This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update5455/// 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:56/// - 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)57/// - Regular contact callbacks will be called through the ContactListener (next to the ones that will be passed to the CharacterContactListener)58/// - Fast moving objects of motion quality LinearCast will not be able to pass through the CharacterVirtual in 1 time step59RefConst<Shape> mInnerBodyShape;6061/// For a deterministic simulation, it is important to have a deterministic body ID. When set and when mInnerBodyShape is specified,62/// the inner body will be created with this specified ID instead of a generated ID.63BodyID mInnerBodyIDOverride;6465/// Layer that the inner rigid body will be added to66ObjectLayer mInnerBodyLayer = 0;67};6869/// This class contains settings that allow you to override the behavior of a character's collision response70class CharacterContactSettings71{72public:73/// True when the object can push the virtual character.74bool mCanPushCharacter = true;7576/// True when the virtual character can apply impulses (push) the body.77/// Note that this only works against rigid bodies. Other CharacterVirtual objects can only be moved in their own update,78/// so you must ensure that in their OnCharacterContactAdded mCanPushCharacter is true.79bool mCanReceiveImpulses = true;80};8182/// This class receives callbacks when a virtual character hits something.83class JPH_EXPORT CharacterContactListener84{85public:86/// Destructor87virtual ~CharacterContactListener() = default;8889/// 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.90/// Note that inBody2 is locked during the callback so you can read its properties freely.91virtual void OnAdjustBodyVelocity(const CharacterVirtual *inCharacter, const Body &inBody2, Vec3 &ioLinearVelocity, Vec3 &ioAngularVelocity) { /* Do nothing, the linear and angular velocity are already filled in */ }9293/// Checks if a character can collide with specified body. Return true if the contact is valid.94virtual bool OnContactValidate(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { return true; }9596/// Same as OnContactValidate but when colliding with a CharacterVirtual97virtual bool OnCharacterContactValidate(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2) { return true; }9899/// Called whenever the character collides with a body for the first time.100/// @param inCharacter Character that is being solved101/// @param inBodyID2 Body ID of body that is being hit102/// @param inSubShapeID2 Sub shape ID of shape that is being hit103/// @param inContactPosition World space contact position104/// @param inContactNormal World space contact normal105/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave106virtual void OnContactAdded(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }107108/// Called whenever the character persists colliding with a body.109/// @param inCharacter Character that is being solved110/// @param inBodyID2 Body ID of body that is being hit111/// @param inSubShapeID2 Sub shape ID of shape that is being hit112/// @param inContactPosition World space contact position113/// @param inContactNormal World space contact normal114/// @param ioSettings Settings returned by the contact callback to indicate how the character should behave115virtual void OnContactPersisted(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }116117/// Called whenever the character loses contact with a body.118/// 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.119/// @param inCharacter Character that is being solved120/// @param inBodyID2 Body ID of body that is being hit121/// @param inSubShapeID2 Sub shape ID of shape that is being hit122virtual void OnContactRemoved(const CharacterVirtual *inCharacter, const BodyID &inBodyID2, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }123124/// Same as OnContactAdded but when colliding with a CharacterVirtual125virtual void OnCharacterContactAdded(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }126127/// Same as OnContactPersisted but when colliding with a CharacterVirtual128virtual void OnCharacterContactPersisted(const CharacterVirtual *inCharacter, const CharacterVirtual *inOtherCharacter, const SubShapeID &inSubShapeID2, RVec3Arg inContactPosition, Vec3Arg inContactNormal, CharacterContactSettings &ioSettings) { /* Default do nothing */ }129130/// Same as OnContactRemoved but when colliding with a CharacterVirtual131/// 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.132virtual void OnCharacterContactRemoved(const CharacterVirtual *inCharacter, const CharacterID &inOtherCharacterID, const SubShapeID &inSubShapeID2) { /* Default do nothing */ }133134/// 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).135/// @param inCharacter Character that is being solved136/// @param inBodyID2 Body ID of body that is being hit137/// @param inSubShapeID2 Sub shape ID of shape that is being hit138/// @param inContactPosition World space contact position139/// @param inContactNormal World space contact normal140/// @param inContactVelocity World space velocity of contact point (e.g. for a moving platform)141/// @param inContactMaterial Material of contact point142/// @param inCharacterVelocity World space velocity of the character prior to hitting this contact143/// @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.144virtual 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 */ }145146/// Same as OnContactSolve but when colliding with a CharacterVirtual147virtual 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 */ }148};149150/// Interface class that allows a CharacterVirtual to check collision with other CharacterVirtual instances.151/// Since CharacterVirtual instances are not registered anywhere, it is up to the application to test collision against relevant characters.152/// The characters could be stored in a tree structure to make this more efficient.153class JPH_EXPORT CharacterVsCharacterCollision : public NonCopyable154{155public:156virtual ~CharacterVsCharacterCollision() = default;157158/// Collide a character against other CharacterVirtuals.159/// @param inCharacter The character to collide.160/// @param inCenterOfMassTransform Center of mass transform for this character.161/// @param inCollideShapeSettings Settings for the collision check.162/// @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 origin163/// @param ioCollector Collision collector that receives the collision results.164virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const = 0;165166/// Cast a character against other CharacterVirtuals.167/// @param inCharacter The character to cast.168/// @param inCenterOfMassTransform Center of mass transform for this character.169/// @param inDirection Direction and length to cast in.170/// @param inShapeCastSettings Settings for the shape cast.171/// @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 origin172/// @param ioCollector Collision collector that receives the collision results.173virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const = 0;174};175176/// Simple collision checker that loops over all registered characters.177/// This is a brute force checking algorithm. If you have a lot of characters you may want to store your characters178/// in a hierarchical structure to make this more efficient.179/// Note that this is not thread safe, so make sure that only one CharacterVirtual is checking collision at a time.180class JPH_EXPORT CharacterVsCharacterCollisionSimple : public CharacterVsCharacterCollision181{182public:183/// Add a character to the list of characters to check collision against.184void Add(CharacterVirtual *inCharacter) { mCharacters.push_back(inCharacter); }185186/// Remove a character from the list of characters to check collision against.187void Remove(const CharacterVirtual *inCharacter);188189// See: CharacterVsCharacterCollision190virtual void CollideCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, const CollideShapeSettings &inCollideShapeSettings, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector) const override;191virtual void CastCharacter(const CharacterVirtual *inCharacter, RMat44Arg inCenterOfMassTransform, Vec3Arg inDirection, const ShapeCastSettings &inShapeCastSettings, RVec3Arg inBaseOffset, CastShapeCollector &ioCollector) const override;192193Array<CharacterVirtual *> mCharacters; ///< The list of characters to check collision against194};195196/// Runtime character object.197/// 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).198/// 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)199/// 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 inner200/// rigid body through CharacterVirtualSettings::mInnerBodyShape. A CharacterVirtual is not tracked by the PhysicsSystem so you need to update it yourself. This also means201/// that a call to PhysicsSystem::SaveState will not save its state, you need to call CharacterVirtual::SaveState yourself.202class JPH_EXPORT CharacterVirtual : public CharacterBase203{204public:205JPH_OVERRIDE_NEW_DELETE206207/// Constructor208/// @param inSettings The settings for the character209/// @param inPosition Initial position for the character210/// @param inRotation Initial rotation for the character (usually only around the up-axis)211/// @param inUserData Application specific value212/// @param inSystem Physics system that this character will be added to213CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, uint64 inUserData, PhysicsSystem *inSystem);214215/// Constructor without user data216CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem) : CharacterVirtual(inSettings, inPosition, inRotation, 0, inSystem) { }217218/// Destructor219virtual ~CharacterVirtual() override;220221/// The ID of this character222inline const CharacterID & GetID() const { return mID; }223224/// Set the contact listener225void SetListener(CharacterContactListener *inListener) { mListener = inListener; }226227/// Get the current contact listener228CharacterContactListener * GetListener() const { return mListener; }229230/// Set the character vs character collision interface231void SetCharacterVsCharacterCollision(CharacterVsCharacterCollision *inCharacterVsCharacterCollision) { mCharacterVsCharacterCollision = inCharacterVsCharacterCollision; }232233/// Get the linear velocity of the character (m / s)234Vec3 GetLinearVelocity() const { return mLinearVelocity; }235236/// Set the linear velocity of the character (m / s)237void SetLinearVelocity(Vec3Arg inLinearVelocity) { mLinearVelocity = inLinearVelocity; }238239/// Get the position of the character240RVec3 GetPosition() const { return mPosition; }241242/// Set the position of the character243void SetPosition(RVec3Arg inPosition) { mPosition = inPosition; UpdateInnerBodyTransform(); }244245/// Get the rotation of the character246Quat GetRotation() const { return mRotation; }247248/// Set the rotation of the character249void SetRotation(QuatArg inRotation) { mRotation = inRotation; UpdateInnerBodyTransform(); }250251// Get the center of mass position of the shape252inline RVec3 GetCenterOfMassPosition() const { return mPosition + (mRotation * (mShapeOffset + mShape->GetCenterOfMass()) + mCharacterPadding * mUp); }253254/// Calculate the world transform of the character255RMat44 GetWorldTransform() const { return RMat44::sRotationTranslation(mRotation, mPosition); }256257/// Calculates the transform for this character's center of mass258RMat44 GetCenterOfMassTransform() const { return GetCenterOfMassTransform(mPosition, mRotation, mShape); }259260/// Character mass (kg)261float GetMass() const { return mMass; }262void SetMass(float inMass) { mMass = inMass; }263264/// Maximum force with which the character can push other bodies (N)265float GetMaxStrength() const { return mMaxStrength; }266void SetMaxStrength(float inMaxStrength) { mMaxStrength = inMaxStrength; }267268/// This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update269float GetPenetrationRecoverySpeed() const { return mPenetrationRecoverySpeed; }270void SetPenetrationRecoverySpeed(float inSpeed) { mPenetrationRecoverySpeed = inSpeed; }271272/// 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.273bool GetEnhancedInternalEdgeRemoval() const { return mEnhancedInternalEdgeRemoval; }274void SetEnhancedInternalEdgeRemoval(bool inApply) { mEnhancedInternalEdgeRemoval = inApply; }275276/// Character padding277float GetCharacterPadding() const { return mCharacterPadding; }278279/// Max num hits to collect in order to avoid excess of contact points collection280uint GetMaxNumHits() const { return mMaxNumHits; }281void SetMaxNumHits(uint inMaxHits) { mMaxNumHits = inMaxHits; }282283/// 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.284float GetHitReductionCosMaxAngle() const { return mHitReductionCosMaxAngle; }285void SetHitReductionCosMaxAngle(float inCosMaxAngle) { mHitReductionCosMaxAngle = inCosMaxAngle; }286287/// Returns if we exceeded the maximum number of hits during the last collision check and had to discard hits based on distance.288/// This can be used to find areas that have too complex geometry for the character to navigate properly.289/// To solve you can either increase the max number of hits or simplify the geometry. Note that the character simulation will290/// try to do its best to select the most relevant contacts to avoid the character from getting stuck.291bool GetMaxHitsExceeded() const { return mMaxHitsExceeded; }292293/// 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.294Vec3 GetShapeOffset() const { return mShapeOffset; }295void SetShapeOffset(Vec3Arg inShapeOffset) { mShapeOffset = inShapeOffset; UpdateInnerBodyTransform(); }296297/// Access to the user data, can be used for anything by the application298uint64 GetUserData() const { return mUserData; }299void SetUserData(uint64 inUserData);300301/// Optional inner rigid body that proxies the character in the world. Can be used to update body properties.302BodyID GetInnerBodyID() const { return mInnerBodyID; }303304/// 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.305/// This velocity can then be set on the character using SetLinearVelocity()306/// @param inDesiredVelocity Velocity to clamp against steep walls307/// @return A new velocity vector that won't make the character move up steep slopes308Vec3 CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const;309310/// This function is internally called by Update, WalkStairs, StickToFloor and ExtendedUpdate and is responsible for tracking if contacts are added, persisted or removed.311/// 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 pair312/// 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 a313/// contact persisted callback during WalkStairs.314void StartTrackingContactChanges();315316/// This call triggers contact removal callbacks and is used in conjunction with StartTrackingContactChanges.317void FinishTrackingContactChanges();318319/// 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 sense320/// 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!321/// 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.322/// @param inDeltaTime Time step to simulate.323/// @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.324/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.325/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.326/// @param inBodyFilter Filter that is used to check if a character collides with a body.327/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.328/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.329void Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);330331/// This function will return true if the character has moved into a slope that is too steep (e.g. a vertical wall).332/// You would call WalkStairs to attempt to step up stairs.333/// @param inLinearVelocity The linear velocity that the player desired. This is used to determine if we're pushing into a step.334bool CanWalkStairs(Vec3Arg inLinearVelocity) const;335336/// When stair walking is needed, you can call the WalkStairs function to cast up, forward and down again to try to find a valid position337/// @param inDeltaTime Time step to simulate.338/// @param inStepUp The direction and distance to step up (this corresponds to the max step height)339/// @param inStepForward The direction and distance to step forward after the step up340/// @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.341/// @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.342/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.343/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.344/// @param inBodyFilter Filter that is used to check if a character collides with a body.345/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.346/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.347/// @return true if the stair walk was successful348bool 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);349350/// 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 will351/// 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,352/// we do an additional collision check downwards and if we find the floor within a certain distance, we project the character onto the floor.353/// @param inStepDown Max amount to project the character downwards (if no floor is found within this distance, the function will return false)354/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.355/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.356/// @param inBodyFilter Filter that is used to check if a character collides with a body.357/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.358/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.359/// @return True if the character was successfully projected onto the floor.360bool StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);361362/// Settings struct with settings for ExtendedUpdate363struct ExtendedUpdateSettings364{365Vec3 mStickToFloorStepDown { 0, -0.5f, 0 }; ///< See StickToFloor inStepDown parameter. Can be zero to turn off.366Vec3 mWalkStairsStepUp { 0, 0.4f, 0 }; ///< See WalkStairs inStepUp parameter. Can be zero to turn off.367float mWalkStairsMinStepForward { 0.02f }; ///< See WalkStairs inStepForward parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.368float mWalkStairsStepForwardTest { 0.15f }; ///< See WalkStairs inStepForwardTest parameter. Note that the parameter only indicates a magnitude, direction is taken from current velocity.369float 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.370Vec3 mWalkStairsStepDownExtra { Vec3::sZero() }; ///< See WalkStairs inStepDownExtra371};372373/// This function combines Update, StickToFloor and WalkStairs. This function serves as an example of how these functions could be combined.374/// Before calling, call SetLinearVelocity to update the horizontal/vertical speed of the character, typically this is:375/// - When on OnGround and not moving away from ground: velocity = GetGroundVelocity() + horizontal speed as input by player + optional vertical jump velocity + delta time * gravity376/// - Else: velocity = current vertical velocity + horizontal speed as input by player + delta time * gravity377/// @param inDeltaTime Time step to simulate.378/// @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.379/// @param inSettings A structure containing settings for the algorithm.380/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.381/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.382/// @param inBodyFilter Filter that is used to check if a character collides with a body.383/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.384/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.385void ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);386387/// This function can be used after a character has teleported to determine the new contacts with the world.388void RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);389390/// 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.391/// It will not perform collision detection, so is less accurate than RefreshContacts but a lot faster.392void UpdateGroundVelocity();393394/// Switch the shape of the character (e.g. for stance).395/// @param inShape The shape to switch to.396/// @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.397/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.398/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.399/// @param inBodyFilter Filter that is used to check if a character collides with a body.400/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.401/// @param inAllocator An allocator for temporary allocations. All memory will be freed by the time this function returns.402/// @return Returns true if the switch succeeded.403bool SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);404405/// Updates the shape of the inner rigid body. Should be called after a successful call to SetShape.406void SetInnerBodyShape(const Shape *inShape);407408/// Get the transformed shape that represents the volume of the character, can be used for collision checks.409TransformedShape GetTransformedShape() const { return TransformedShape(GetCenterOfMassPosition(), mRotation, mShape, mInnerBodyID); }410411/// @brief Get all contacts for the character at a particular location.412/// When colliding with another character virtual, this pointer will be provided through CollideShapeCollector::SetUserContext before adding a hit.413/// @param inPosition Position to test, note that this position will be corrected for the character padding.414/// @param inRotation Rotation at which to test the shape.415/// @param inMovementDirection A hint in which direction the character is moving, will be used to calculate a proper normal.416/// @param inMaxSeparationDistance How much distance around the character you want to report contacts in (can be 0 to match the character exactly).417/// @param inShape Shape to test collision with.418/// @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 origin419/// @param ioCollector Collision collector that receives the collision results.420/// @param inBroadPhaseLayerFilter Filter that is used to check if the character collides with something in the broadphase.421/// @param inObjectLayerFilter Filter that is used to check if a character collides with a layer.422/// @param inBodyFilter Filter that is used to check if a character collides with a body.423/// @param inShapeFilter Filter that is used to check if a character collides with a subshape.424void 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;425426/// Get the character settings that can recreate this character427CharacterVirtualSettings GetCharacterVirtualSettings() const;428429// Saving / restoring state for replay430virtual void SaveState(StateRecorder &inStream) const override;431virtual void RestoreState(StateRecorder &inStream) override;432433#ifdef JPH_DEBUG_RENDERER434static inline bool sDrawConstraints = false; ///< Draw the current state of the constraints for iteration 0 when creating them435static inline bool sDrawWalkStairs = false; ///< Draw the state of the walk stairs algorithm436static inline bool sDrawStickToFloor = false; ///< Draw the state of the stick to floor algorithm437#endif438439/// Uniquely identifies a contact between a character and another body or character440class ContactKey441{442public:443/// Constructor444ContactKey() = default;445ContactKey(const ContactKey &inContact) = default;446ContactKey(const BodyID &inBodyB, const SubShapeID &inSubShapeID) : mBodyB(inBodyB), mSubShapeIDB(inSubShapeID) { }447ContactKey(const CharacterID &inCharacterIDB, const SubShapeID &inSubShapeID) : mCharacterIDB(inCharacterIDB), mSubShapeIDB(inSubShapeID) { }448ContactKey & operator = (const ContactKey &inContact) = default;449450/// Checks if two contacts refer to the same body (or virtual character)451inline bool IsSameBody(const ContactKey &inOther) const { return mBodyB == inOther.mBodyB && mCharacterIDB == inOther.mCharacterIDB; }452453/// Equality operator454bool operator == (const ContactKey &inRHS) const455{456return mBodyB == inRHS.mBodyB && mCharacterIDB == inRHS.mCharacterIDB && mSubShapeIDB == inRHS.mSubShapeIDB;457}458459bool operator != (const ContactKey &inRHS) const460{461return !(*this == inRHS);462}463464/// Hash of this structure465uint64 GetHash() const466{467static_assert(sizeof(BodyID) + sizeof(CharacterID) + sizeof(SubShapeID) == sizeof(ContactKey), "No padding expected");468return HashBytes(this, sizeof(ContactKey));469}470471// Saving / restoring state for replay472void SaveState(StateRecorder &inStream) const;473void RestoreState(StateRecorder &inStream);474475BodyID mBodyB; ///< ID of body we're colliding with (if not invalid)476CharacterID mCharacterIDB; ///< Character we're colliding with (if not invalid)477SubShapeID mSubShapeIDB; ///< Sub shape ID of body or character we're colliding with478};479480/// Encapsulates a collision contact481struct Contact : public ContactKey482{483// Saving / restoring state for replay484void SaveState(StateRecorder &inStream) const;485void RestoreState(StateRecorder &inStream);486487RVec3 mPosition; ///< Position where the character makes contact488Vec3 mLinearVelocity; ///< Velocity of the contact point489Vec3 mContactNormal; ///< Contact normal, pointing towards the character490Vec3 mSurfaceNormal; ///< Surface normal of the contact491float mDistance; ///< Distance to the contact <= 0 means that it is an actual contact, > 0 means predictive492float mFraction; ///< Fraction along the path where this contact takes place493EMotionType mMotionTypeB; ///< Motion type of B, used to determine the priority of the contact494bool mIsSensorB; ///< If B is a sensor495const 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.496uint64 mUserData; ///< User data of B497const PhysicsMaterial * mMaterial; ///< Material of B498bool mHadCollision = false; ///< If the character actually collided with the contact (can be false if a predictive contact never becomes a real one)499bool mWasDiscarded = false; ///< If the contact validate callback chose to discard this contact or when the body is a sensor500bool mCanPushCharacter = true; ///< When true, the velocity of the contact point can push the character501};502503using TempContactList = Array<Contact, STLTempAllocator<Contact>>;504using ContactList = Array<Contact>;505506/// Access to the internal list of contacts that the character has found.507/// Note that only contacts that have their mHadCollision flag set are actual contacts.508const ContactList & GetActiveContacts() const { return mActiveContacts; }509510/// Check if the character is currently in contact with or has collided with another body in the last operation (e.g. Update or WalkStairs)511bool HasCollidedWith(const BodyID &inBody) const512{513for (const CharacterVirtual::Contact &c : mActiveContacts)514if (c.mHadCollision && c.mBodyB == inBody)515return true;516return false;517}518519/// 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)520bool HasCollidedWith(const CharacterID &inCharacterID) const521{522for (const CharacterVirtual::Contact &c : mActiveContacts)523if (c.mHadCollision && c.mCharacterIDB == inCharacterID)524return true;525return false;526}527528/// 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)529bool HasCollidedWith(const CharacterVirtual *inCharacter) const530{531return HasCollidedWith(inCharacter->GetID());532}533534private:535// Sorting predicate for making contact order deterministic536struct ContactOrderingPredicate537{538inline bool operator () (const Contact &inLHS, const Contact &inRHS) const539{540if (inLHS.mBodyB != inRHS.mBodyB)541return inLHS.mBodyB < inRHS.mBodyB;542543if (inLHS.mCharacterIDB != inRHS.mCharacterIDB)544return inLHS.mCharacterIDB < inRHS.mCharacterIDB;545546return inLHS.mSubShapeIDB.GetValue() < inRHS.mSubShapeIDB.GetValue();547}548};549550using IgnoredContactList = Array<ContactKey, STLTempAllocator<ContactKey>>;551552// A constraint that limits the movement of the character553struct Constraint554{555Contact * mContact; ///< Contact that this constraint was generated from556float mTOI; ///< Calculated time of impact (can be negative if penetrating)557float mProjectedVelocity; ///< Velocity of the contact projected on the contact normal (negative if separating)558Vec3 mLinearVelocity; ///< Velocity of the contact (can contain a corrective velocity to resolve penetration)559Plane mPlane; ///< Plane around the origin that describes how far we can displace (from the origin)560bool mIsSteepSlope = false; ///< If this constraint belongs to a steep slope561};562563using ConstraintList = Array<Constraint, STLTempAllocator<Constraint>>;564565// Collision collector that collects hits for CollideShape566class ContactCollector : public CollideShapeCollector567{568public:569ContactCollector(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) { }570571virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }572573virtual void AddHit(const CollideShapeResult &inResult) override;574575RVec3 mBaseOffset;576Vec3 mUp;577PhysicsSystem * mSystem;578const CharacterVirtual * mCharacter;579CharacterVirtual * mOtherCharacter = nullptr;580TempContactList & mContacts;581uint mMaxHits;582float mHitReductionCosMaxAngle;583bool mMaxHitsExceeded = false;584};585586// A collision collector that collects hits for CastShape587class ContactCastCollector : public CastShapeCollector588{589public:590ContactCastCollector(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) { }591592virtual void SetUserData(uint64 inUserData) override { mOtherCharacter = reinterpret_cast<CharacterVirtual *>(inUserData); }593594virtual void AddHit(const ShapeCastResult &inResult) override;595596RVec3 mBaseOffset;597Vec3 mDisplacement;598Vec3 mUp;599PhysicsSystem * mSystem;600const CharacterVirtual * mCharacter;601CharacterVirtual * mOtherCharacter = nullptr;602const IgnoredContactList & mIgnoredContacts;603Contact & mContact;604};605606// Helper function to convert a Jolt collision result into a contact607template <class taCollector>608inline static void sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult);609inline static void sFillCharacterContactProperties(Contact &outContact, const CharacterVirtual *inOtherCharacter, RVec3Arg inBaseOffset, const CollideShapeResult &inResult);610611// Move the shape from ioPosition and try to displace it by inVelocity * inDeltaTime, this will try to slide the shape along the world geometry612void MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator613#ifdef JPH_DEBUG_RENDERER614, bool inDrawConstraints = false615#endif // JPH_DEBUG_RENDERER616);617618// Ask the callback if inContact is a valid contact point619bool ValidateContact(const Contact &inContact) const;620621// Trigger the contact callback for inContact and get the contact settings622void ContactAdded(const Contact &inContact, CharacterContactSettings &ioSettings);623624// Tests the shape for collision around inPosition625void GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;626627// Remove penetrating contacts with the same body that have conflicting normals, leaving these will make the character mover get stuck628void RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const;629630// 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.631void DetermineConstraints(TempContactList &inContacts, float inDeltaTime, ConstraintList &outConstraints) const;632633// 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.634void SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator635#ifdef JPH_DEBUG_RENDERER636, bool inDrawConstraints = false637#endif // JPH_DEBUG_RENDERER638);639640// Get the velocity of a body adjusted by the contact listener641void GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const;642643// 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.644// Note that we don't just take the point velocity because a point on an object with angular velocity traces an arc,645// so if you just take point velocity * delta time you get an error that accumulates over time646Vec3 CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass, Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, float inDeltaTime) const;647648// Handle contact with physics object that we're colliding against649bool HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime);650651// Does a swept test of the shape from inPosition with displacement inDisplacement, returns true if there was a collision652bool GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const;653654// Store contacts so that we have proper ground information655void StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator);656657// This function will determine which contacts are touching the character and will calculate the one that is supporting us658void UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator);659660/// This function can be called after moving the character to a new colliding position661void MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator);662663// This function returns the actual center of mass of the shape, not corrected for the character padding664inline RMat44 GetCenterOfMassTransform(RVec3Arg inPosition, QuatArg inRotation, const Shape *inShape) const665{666return RMat44::sRotationTranslation(inRotation, inPosition).PreTranslated(mShapeOffset + inShape->GetCenterOfMass()).PostTranslated(mCharacterPadding * mUp);667}668669// This function returns the position of the inner rigid body670inline RVec3 GetInnerBodyPosition() const671{672return mPosition + (mRotation * mShapeOffset + mCharacterPadding * mUp);673}674675// Move the inner rigid body to the current position676void UpdateInnerBodyTransform();677678// ID679CharacterID mID;680681// Our main listener for contacts682CharacterContactListener * mListener = nullptr;683684// Interface to detect collision between characters685CharacterVsCharacterCollision * mCharacterVsCharacterCollision = nullptr;686687// Movement settings688EBackFaceMode 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.689float 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.690uint mMaxCollisionIterations; // Max amount of collision loops691uint mMaxConstraintIterations; // How often to try stepping in the constraint solving692float mMinTimeRemaining; // Early out condition: If this much time is left to simulate we are done693float mCollisionTolerance; // How far we're willing to penetrate geometry694float 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 stuck695uint mMaxNumHits; // Max num hits to collect in order to avoid excess of contact points collection696float 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.697float mPenetrationRecoverySpeed; // This value governs how fast a penetration will be resolved, 0 = nothing is resolved, 1 = everything in one update698bool 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.699700// Character mass (kg)701float mMass;702703// Maximum force with which the character can push other bodies (N)704float mMaxStrength;705706// An extra offset applied to the shape in local space. This allows applying an extra offset to the shape in local space.707Vec3 mShapeOffset = Vec3::sZero();708709// Current position (of the base, not the center of mass)710RVec3 mPosition = RVec3::sZero();711712// Current rotation (of the base, not of the center of mass)713Quat mRotation = Quat::sIdentity();714715// Current linear velocity716Vec3 mLinearVelocity = Vec3::sZero();717718// List of contacts that were active in the last frame719ContactList mActiveContacts;720721// Remembers how often we called StartTrackingContactChanges722int mTrackingContactChanges = 0;723724// View from a contact listener perspective on which contacts have been added/removed725struct ListenerContactValue726{727ListenerContactValue() = default;728explicit ListenerContactValue(const CharacterContactSettings &inSettings) : mSettings(inSettings) { }729730CharacterContactSettings mSettings;731int mCount = 0;732};733734using ListenerContacts = UnorderedMap<ContactKey, ListenerContactValue>;735ListenerContacts mListenerContacts;736737// Remembers the delta time of the last update738float mLastDeltaTime = 1.0f / 60.0f;739740// Remember if we exceeded the maximum number of hits and had to remove similar contacts741mutable bool mMaxHitsExceeded = false;742743// User data, can be used for anything by the application744uint64 mUserData = 0;745746// The inner rigid body that proxies the character in the world747BodyID mInnerBodyID;748};749750JPH_NAMESPACE_END751752753