Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/Vehicle/VehicleConstraint.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/Constraints/Constraint.h>7#include <Jolt/Physics/PhysicsStepListener.h>8#include <Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h>9#include <Jolt/Physics/Vehicle/VehicleCollisionTester.h>10#include <Jolt/Physics/Vehicle/VehicleAntiRollBar.h>11#include <Jolt/Physics/Vehicle/Wheel.h>12#include <Jolt/Physics/Vehicle/VehicleController.h>1314JPH_NAMESPACE_BEGIN1516class PhysicsSystem;1718/// Configuration for constraint that simulates a wheeled vehicle.19///20/// The properties in this constraint are largely based on "Car Physics for Games" by Marco Monster.21/// See: https://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html22class JPH_EXPORT VehicleConstraintSettings : public ConstraintSettings23{24JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, VehicleConstraintSettings)2526public:27/// Saves the contents of the constraint settings in binary form to inStream.28virtual void SaveBinaryState(StreamOut &inStream) const override;2930Vec3 mUp { 0, 1, 0 }; ///< Vector indicating the up direction of the vehicle (in local space to the body)31Vec3 mForward { 0, 0, 1 }; ///< Vector indicating forward direction of the vehicle (in local space to the body)32float mMaxPitchRollAngle = JPH_PI; ///< Defines the maximum pitch/roll angle (rad), can be used to avoid the car from getting upside down. The vehicle up direction will stay within a cone centered around the up axis with half top angle mMaxPitchRollAngle, set to pi to turn off.33Array<Ref<WheelSettings>> mWheels; ///< List of wheels and their properties34VehicleAntiRollBars mAntiRollBars; ///< List of anti rollbars and their properties35Ref<VehicleControllerSettings> mController; ///< Defines how the vehicle can accelerate / decelerate3637protected:38/// This function should not be called directly, it is used by sRestoreFromBinaryState.39virtual void RestoreBinaryState(StreamIn &inStream) override;40};4142/// Constraint that simulates a vehicle43/// Note: Don't forget to register the constraint as a StepListener with the PhysicsSystem!44///45/// When the vehicle drives over very light objects (rubble) you may see the car body dip down. This is a known issue and is an artifact of the iterative solver that Jolt is using.46/// Basically if a light object is sandwiched between two heavy objects (the static floor and the car body), the light object is not able to transfer enough force from the ground to47/// the car body to keep the car body up. You can see this effect in the HeavyOnLightTest sample, the boxes on the right have a lot of penetration because they're on top of light objects.48///49/// There are a couple of ways to improve this:50///51/// 1. You can increase the number of velocity steps (global settings PhysicsSettings::mNumVelocitySteps or if you only want to increase it on52/// the vehicle you can use VehicleConstraintSettings::mNumVelocityStepsOverride). E.g. going from 10 to 30 steps in the HeavyOnLightTest sample makes the penetration a lot less.53/// The number of position steps can also be increased (the first prevents the body from going down, the second corrects it if the problem did54/// occur which inevitably happens due to numerical drift). This solution costs CPU cycles.55///56/// 2. You can reduce the mass difference between the vehicle body and the rubble on the floor (by making the rubble heavier or the car lighter).57///58/// 3. You could filter out collisions between the vehicle collision test and the rubble completely. This would make the wheels ignore the rubble but would cause the vehicle to drive59/// through it as if nothing happened. You could create fake wheels (keyframed bodies) that move along with the vehicle and that only collide with rubble (and not the vehicle or the ground).60/// This would cause the vehicle to push away the rubble without the rubble being able to affect the vehicle (unless it hits the main body of course).61///62/// Note that when driving over rubble, you may see the wheel jump up and down quite quickly because one frame a collision is found and the next frame not.63/// To alleviate this, it may be needed to smooth the motion of the visual mesh for the wheel.64class JPH_EXPORT VehicleConstraint : public Constraint, public PhysicsStepListener65{66public:67/// Constructor / destructor68VehicleConstraint(Body &inVehicleBody, const VehicleConstraintSettings &inSettings);69virtual ~VehicleConstraint() override;7071/// Get the type of a constraint72virtual EConstraintSubType GetSubType() const override { return EConstraintSubType::Vehicle; }7374/// Defines the maximum pitch/roll angle (rad), can be used to avoid the car from getting upside down. The vehicle up direction will stay within a cone centered around the up axis with half top angle mMaxPitchRollAngle, set to pi to turn off.75void SetMaxPitchRollAngle(float inMaxPitchRollAngle) { mCosMaxPitchRollAngle = Cos(inMaxPitchRollAngle); }7677/// Set the interface that tests collision between wheel and ground78void SetVehicleCollisionTester(const VehicleCollisionTester *inTester) { mVehicleCollisionTester = inTester; }7980/// Callback function to combine the friction of a tire with the friction of the body it is colliding with.81/// On input ioLongitudinalFriction and ioLateralFriction contain the friction of the tire, on output they should contain the combined friction with inBody2.82using CombineFunction = function<void(uint inWheelIndex, float &ioLongitudinalFriction, float &ioLateralFriction, const Body &inBody2, const SubShapeID &inSubShapeID2)>;8384/// Set the function that combines the friction of two bodies and returns it85/// Default method is the geometric mean: sqrt(friction1 * friction2).86void SetCombineFriction(const CombineFunction &inCombineFriction) { mCombineFriction = inCombineFriction; }87const CombineFunction & GetCombineFriction() const { return mCombineFriction; }8889/// Callback function to notify of current stage in PhysicsStepListener::OnStep.90using StepCallback = function<void(VehicleConstraint &inVehicle, const PhysicsStepListenerContext &inContext)>;9192/// Callback function to notify that PhysicsStepListener::OnStep has started for this vehicle. Default is to do nothing.93/// Can be used to allow higher-level code to e.g. control steering. This is the last moment that the position/orientation of the vehicle can be changed.94/// Wheel collision checks have not been performed yet.95const StepCallback & GetPreStepCallback() const { return mPreStepCallback; }96void SetPreStepCallback(const StepCallback &inPreStepCallback) { mPreStepCallback = inPreStepCallback; }9798/// Callback function to notify that PhysicsStepListener::OnStep has just completed wheel collision checks. Default is to do nothing.99/// Can be used to allow higher-level code to e.g. detect tire contact or to modify the velocity of the vehicle based on the wheel contacts.100/// You should not change the position of the vehicle in this callback as the wheel collision checks have already been performed.101const StepCallback & GetPostCollideCallback() const { return mPostCollideCallback; }102void SetPostCollideCallback(const StepCallback &inPostCollideCallback) { mPostCollideCallback = inPostCollideCallback; }103104/// Callback function to notify that PhysicsStepListener::OnStep has completed for this vehicle. Default is to do nothing.105/// Can be used to allow higher-level code to e.g. control the vehicle in the air.106/// You should not change the position of the vehicle in this callback as the wheel collision checks have already been performed.107const StepCallback & GetPostStepCallback() const { return mPostStepCallback; }108void SetPostStepCallback(const StepCallback &inPostStepCallback) { mPostStepCallback = inPostStepCallback; }109110/// Override gravity for this vehicle. Note that overriding gravity will set the gravity factor of the vehicle body to 0 and apply gravity in the PhysicsStepListener instead.111void OverrideGravity(Vec3Arg inGravity) { mGravityOverride = inGravity; mIsGravityOverridden = true; }112bool IsGravityOverridden() const { return mIsGravityOverridden; }113Vec3 GetGravityOverride() const { return mGravityOverride; }114void ResetGravityOverride() { mIsGravityOverridden = false; mBody->GetMotionProperties()->SetGravityFactor(1.0f); } ///< Note that resetting the gravity override will restore the gravity factor of the vehicle body to 1.115116/// Get the local space forward vector of the vehicle117Vec3 GetLocalForward() const { return mForward; }118119/// Get the local space up vector of the vehicle120Vec3 GetLocalUp() const { return mUp; }121122/// Vector indicating the world space up direction (used to limit vehicle pitch/roll), calculated every frame by inverting gravity123Vec3 GetWorldUp() const { return mWorldUp; }124125/// Access to the vehicle body126Body * GetVehicleBody() const { return mBody; }127128/// Access to the vehicle controller interface (determines acceleration / deceleration)129const VehicleController * GetController() const { return mController; }130131/// Access to the vehicle controller interface (determines acceleration / deceleration)132VehicleController * GetController() { return mController; }133134/// Get the state of the wheels135const Wheels & GetWheels() const { return mWheels; }136137/// Get the state of a wheels (writable interface, allows you to make changes to the configuration which will take effect the next time step)138Wheels & GetWheels() { return mWheels; }139140/// Get the state of a wheel141Wheel * GetWheel(uint inIdx) { return mWheels[inIdx]; }142const Wheel * GetWheel(uint inIdx) const { return mWheels[inIdx]; }143144/// Get the basis vectors for the wheel in local space to the vehicle body (note: basis does not rotate when the wheel rotates around its axis)145/// @param inWheel Wheel to fetch basis for146/// @param outForward Forward vector for the wheel147/// @param outUp Up vector for the wheel148/// @param outRight Right vector for the wheel149void GetWheelLocalBasis(const Wheel *inWheel, Vec3 &outForward, Vec3 &outUp, Vec3 &outRight) const;150151/// Get the transform of a wheel in local space to the vehicle body, returns a matrix that transforms a cylinder aligned with the Y axis in body space (not COM space)152/// @param inWheelIndex Index of the wheel to fetch153/// @param inWheelRight Unit vector that indicates right in model space of the wheel (so if you only have 1 wheel model, you probably want to specify the opposite direction for the left and right wheels)154/// @param inWheelUp Unit vector that indicates up in model space of the wheel155Mat44 GetWheelLocalTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const;156157/// Get the transform of a wheel in world space, returns a matrix that transforms a cylinder aligned with the Y axis in world space158/// @param inWheelIndex Index of the wheel to fetch159/// @param inWheelRight Unit vector that indicates right in model space of the wheel (so if you only have 1 wheel model, you probably want to specify the opposite direction for the left and right wheels)160/// @param inWheelUp Unit vector that indicates up in model space of the wheel161RMat44 GetWheelWorldTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const;162163/// Access to the vehicle's anti roll bars164const VehicleAntiRollBars & GetAntiRollBars() const { return mAntiRollBars; }165VehicleAntiRollBars & GetAntiRollBars() { return mAntiRollBars; }166167/// Number of simulation steps between wheel collision tests when the vehicle is active. Default is 1. 0 = never, 1 = every step, 2 = every other step, etc.168/// Note that if a vehicle has multiple wheels and the number of steps > 1, the wheels will be tested in a round robin fashion.169/// If there are multiple vehicles, the tests will be spread out based on the BodyID of the vehicle.170/// If you set this to test less than every step, you may see simulation artifacts. This setting can be used to reduce the cost of simulating vehicles in the distance.171void SetNumStepsBetweenCollisionTestActive(uint inSteps) { mNumStepsBetweenCollisionTestActive = inSteps; }172uint GetNumStepsBetweenCollisionTestActive() const { return mNumStepsBetweenCollisionTestActive; }173174/// Number of simulation steps between wheel collision tests when the vehicle is inactive. Default is 1. 0 = never, 1 = every step, 2 = every other step, etc.175/// Note that if a vehicle has multiple wheels and the number of steps > 1, the wheels will be tested in a round robin fashion.176/// If there are multiple vehicles, the tests will be spread out based on the BodyID of the vehicle.177/// This number can be lower than the number of steps when the vehicle is active as the only purpose of this test is178/// to allow the vehicle to wake up in response to bodies moving into the wheels but not touching the body of the vehicle.179void SetNumStepsBetweenCollisionTestInactive(uint inSteps) { mNumStepsBetweenCollisionTestInactive = inSteps; }180uint GetNumStepsBetweenCollisionTestInactive() const { return mNumStepsBetweenCollisionTestInactive; }181182// Generic interface of a constraint183virtual bool IsActive() const override { return mIsActive && Constraint::IsActive(); }184virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) override { /* Do nothing */ }185virtual void SetupVelocityConstraint(float inDeltaTime) override;186virtual void ResetWarmStart() override;187virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) override;188virtual bool SolveVelocityConstraint(float inDeltaTime) override;189virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) override;190virtual void BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager) override;191virtual uint BuildIslandSplits(LargeIslandSplitter &ioSplitter) const override;192#ifdef JPH_DEBUG_RENDERER193virtual void DrawConstraint(DebugRenderer *inRenderer) const override;194virtual void DrawConstraintLimits(DebugRenderer *inRenderer) const override;195#endif // JPH_DEBUG_RENDERER196virtual void SaveState(StateRecorder &inStream) const override;197virtual void RestoreState(StateRecorder &inStream) override;198virtual Ref<ConstraintSettings> GetConstraintSettings() const override;199200private:201// See: PhysicsStepListener202virtual void OnStep(const PhysicsStepListenerContext &inContext) override;203204// Calculate the position where the suspension and traction forces should be applied in world space, relative to the center of mass of both bodies205void CalculateSuspensionForcePoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const;206207// Calculate the constraint properties for mPitchRollPart208void CalculatePitchRollConstraintProperties(RMat44Arg inBodyTransform);209210// Gravity override211bool mIsGravityOverridden = false; ///< If the gravity is currently overridden212Vec3 mGravityOverride = Vec3::sZero(); ///< Gravity override value, replaces PhysicsSystem::GetGravity() when mIsGravityOverridden is true213214// Simulation information215Body * mBody; ///< Body of the vehicle216Vec3 mForward; ///< Local space forward vector for the vehicle217Vec3 mUp; ///< Local space up vector for the vehicle218Vec3 mWorldUp; ///< Vector indicating the world space up direction (used to limit vehicle pitch/roll)219Wheels mWheels; ///< Wheel states of the vehicle220VehicleAntiRollBars mAntiRollBars; ///< Anti rollbars of the vehicle221VehicleController * mController; ///< Controls the acceleration / deceleration of the vehicle222bool mIsActive = false; ///< If this constraint is active223uint mNumStepsBetweenCollisionTestActive = 1; ///< Number of simulation steps between wheel collision tests when the vehicle is active224uint mNumStepsBetweenCollisionTestInactive = 1; ///< Number of simulation steps between wheel collision tests when the vehicle is inactive225uint mCurrentStep = 0; ///< Current step number, used to determine when to test a wheel226227// Prevent vehicle from toppling over228float mCosMaxPitchRollAngle; ///< Cos of the max pitch/roll angle229float mCosPitchRollAngle; ///< Cos of the current pitch/roll angle230Vec3 mPitchRollRotationAxis { 0, 1, 0 }; ///< Current axis along which to apply torque to prevent the car from toppling over231AngleConstraintPart mPitchRollPart; ///< Constraint part that prevents the car from toppling over232233// Interfaces234RefConst<VehicleCollisionTester> mVehicleCollisionTester; ///< Class that performs testing of collision for the wheels235CombineFunction mCombineFriction = [](uint, float &ioLongitudinalFriction, float &ioLateralFriction, const Body &inBody2, const SubShapeID &)236{237float body_friction = inBody2.GetFriction();238239ioLongitudinalFriction = sqrt(ioLongitudinalFriction * body_friction);240ioLateralFriction = sqrt(ioLateralFriction * body_friction);241};242243// Callbacks244StepCallback mPreStepCallback;245StepCallback mPostCollideCallback;246StepCallback mPostStepCallback;247};248249JPH_NAMESPACE_END250251252