VehicleConstraint.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Physics/Constraints/Constraint.h>
  6. #include <Jolt/Physics/PhysicsStepListener.h>
  7. #include <Jolt/Physics/Constraints/ConstraintPart/AngleConstraintPart.h>
  8. #include <Jolt/Physics/Vehicle/VehicleCollisionTester.h>
  9. #include <Jolt/Physics/Vehicle/VehicleAntiRollBar.h>
  10. #include <Jolt/Physics/Vehicle/Wheel.h>
  11. #include <Jolt/Physics/Vehicle/VehicleController.h>
  12. JPH_NAMESPACE_BEGIN
  13. class PhysicsSystem;
  14. /// Configuration for constraint that simulates a wheeled vehicle.
  15. ///
  16. /// The properties in this constraint are largely based on "Car Physics for Games" by Marco Monster.
  17. /// See: https://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html
  18. class JPH_EXPORT VehicleConstraintSettings : public ConstraintSettings
  19. {
  20. public:
  21. JPH_DECLARE_SERIALIZABLE_VIRTUAL(JPH_EXPORT, VehicleConstraintSettings)
  22. /// Saves the contents of the constraint settings in binary form to inStream.
  23. virtual void SaveBinaryState(StreamOut &inStream) const override;
  24. Vec3 mUp { 0, 1, 0 }; ///< Vector indicating the up direction of the vehicle (in local space to the body)
  25. Vec3 mForward { 0, 0, 1 }; ///< Vector indicating forward direction of the vehicle (in local space to the body)
  26. float 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.
  27. Array<Ref<WheelSettings>> mWheels; ///< List of wheels and their properties
  28. Array<VehicleAntiRollBar> mAntiRollBars; ///< List of anti rollbars and their properties
  29. Ref<VehicleControllerSettings> mController; ///< Defines how the vehicle can accelerate / decelerate
  30. protected:
  31. /// This function should not be called directly, it is used by sRestoreFromBinaryState.
  32. virtual void RestoreBinaryState(StreamIn &inStream) override;
  33. };
  34. /// Constraint that simulates a vehicle
  35. /// Note: Don't forget to register the constraint as a StepListener with the PhysicsSystem!
  36. ///
  37. /// 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.
  38. /// 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 to
  39. /// 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.
  40. ///
  41. /// There are a couple of ways to improve this:
  42. ///
  43. /// 1. You can increase the number of velocity steps (global settings PhysicsSettings::mNumVelocitySteps or if you only want to increase it on
  44. /// 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.
  45. /// The number of position steps can also be increased (the first prevents the body from going down, the second corrects it if the problem did
  46. /// occur which inevitably happens due to numerical drift). This solution costs CPU cycles.
  47. ///
  48. /// 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).
  49. ///
  50. /// 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 drive
  51. /// 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).
  52. /// 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).
  53. ///
  54. /// 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.
  55. /// To alleviate this, it may be needed to smooth the motion of the visual mesh for the wheel.
  56. class JPH_EXPORT VehicleConstraint : public Constraint, public PhysicsStepListener
  57. {
  58. public:
  59. /// Constructor / destructor
  60. VehicleConstraint(Body &inVehicleBody, const VehicleConstraintSettings &inSettings);
  61. virtual ~VehicleConstraint() override;
  62. /// Get the type of a constraint
  63. virtual EConstraintSubType GetSubType() const override { return EConstraintSubType::Vehicle; }
  64. /// 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.
  65. void SetMaxPitchRollAngle(float inMaxPitchRollAngle) { mCosMaxPitchRollAngle = Cos(inMaxPitchRollAngle); }
  66. /// Set the interface that tests collision between wheel and ground
  67. void SetVehicleCollisionTester(const VehicleCollisionTester *inTester) { mVehicleCollisionTester = inTester; }
  68. /// Callback function to combine the friction of a tire with the friction of the body it is colliding with.
  69. /// On input ioLongitudinalFriction and ioLateralFriction contain the friction of the tire, on output they should contain the combined friction with inBody2.
  70. using CombineFunction = function<void(uint inWheelIndex, float &ioLongitudinalFriction, float &ioLateralFriction, const Body &inBody2, const SubShapeID &inSubShapeID2)>;
  71. /// Set the function that combines the friction of two bodies and returns it
  72. /// Default method is the geometric mean: sqrt(friction1 * friction2).
  73. void SetCombineFriction(const CombineFunction &inCombineFriction) { mCombineFriction = inCombineFriction; }
  74. const CombineFunction & GetCombineFriction() const { return mCombineFriction; }
  75. /// Callback function to notify of current stage in PhysicsStepListener::OnStep.
  76. using StepCallback = function<void(VehicleConstraint &inVehicle, float inDeltaTime, PhysicsSystem &inPhysicsSystem)>;
  77. /// Callback function to notify that PhysicsStepListener::OnStep has started for this vehicle. Default is to do nothing.
  78. /// 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.
  79. /// Wheel collision checks have not been performed yet.
  80. const StepCallback & GetPreStepCallback() const { return mPreStepCallback; }
  81. void SetPreStepCallback(const StepCallback &inPreStepCallback) { mPreStepCallback = inPreStepCallback; }
  82. /// Callback function to notify that PhysicsStepListener::OnStep has just completed wheel collision checks. Default is to do nothing.
  83. /// 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.
  84. /// You should not change the position of the vehicle in this callback as the wheel collision checks have already been performed.
  85. const StepCallback & GetPostCollideCallback() const { return mPostCollideCallback; }
  86. void SetPostCollideCallback(const StepCallback &inPostCollideCallback) { mPostCollideCallback = inPostCollideCallback; }
  87. /// Callback function to notify that PhysicsStepListener::OnStep has completed for this vehicle. Default is to do nothing.
  88. /// Can be used to allow higher-level code to e.g. control the vehicle in the air.
  89. /// You should not change the position of the vehicle in this callback as the wheel collision checks have already been performed.
  90. const StepCallback & GetPostStepCallback() const { return mPostStepCallback; }
  91. void SetPostStepCallback(const StepCallback &inPostStepCallback) { mPostStepCallback = inPostStepCallback; }
  92. /// Get the local space forward vector of the vehicle
  93. Vec3 GetLocalForward() const { return mForward; }
  94. /// Get the local space up vector of the vehicle
  95. Vec3 GetLocalUp() const { return mUp; }
  96. /// Vector indicating the world space up direction (used to limit vehicle pitch/roll), calculated every frame by inverting gravity
  97. Vec3 GetWorldUp() const { return mWorldUp; }
  98. /// Access to the vehicle body
  99. Body * GetVehicleBody() const { return mBody; }
  100. /// Access to the vehicle controller interface (determines acceleration / deceleration)
  101. const VehicleController * GetController() const { return mController; }
  102. /// Access to the vehicle controller interface (determines acceleration / deceleration)
  103. VehicleController * GetController() { return mController; }
  104. /// Get the state of the wheels
  105. const Wheels & GetWheels() const { return mWheels; }
  106. /// Get the state of a wheels (writable interface, allows you to make changes to the configuration which will take effect the next time step)
  107. Wheels & GetWheels() { return mWheels; }
  108. /// Get the state of a wheel
  109. Wheel * GetWheel(uint inIdx) { return mWheels[inIdx]; }
  110. const Wheel * GetWheel(uint inIdx) const { return mWheels[inIdx]; }
  111. /// 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)
  112. /// @param inWheel Wheel to fetch basis for
  113. /// @param outForward Forward vector for the wheel
  114. /// @param outUp Up vector for the wheel
  115. /// @param outRight Right vector for the wheel
  116. void GetWheelLocalBasis(const Wheel *inWheel, Vec3 &outForward, Vec3 &outUp, Vec3 &outRight) const;
  117. /// 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)
  118. /// @param inWheelIndex Index of the wheel to fetch
  119. /// @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)
  120. /// @param inWheelUp Unit vector that indicates up in model space of the wheel
  121. Mat44 GetWheelLocalTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const;
  122. /// Get the transform of a wheel in world space, returns a matrix that transforms a cylinder aligned with the Y axis in world space
  123. /// @param inWheelIndex Index of the wheel to fetch
  124. /// @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)
  125. /// @param inWheelUp Unit vector that indicates up in model space of the wheel
  126. RMat44 GetWheelWorldTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const;
  127. /// 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.
  128. /// Note that if a vehicle has multiple wheels and the number of steps > 1, the wheels will be tested in a round robin fashion.
  129. /// If there are multiple vehicles, the tests will be spread out based on the BodyID of the vehicle.
  130. /// 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.
  131. void SetNumStepsBetweenCollisionTestActive(uint inSteps) { mNumStepsBetweenCollisionTestActive = inSteps; }
  132. uint GetNumStepsBetweenCollisionTestActive() const { return mNumStepsBetweenCollisionTestActive; }
  133. /// 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.
  134. /// Note that if a vehicle has multiple wheels and the number of steps > 1, the wheels will be tested in a round robin fashion.
  135. /// If there are multiple vehicles, the tests will be spread out based on the BodyID of the vehicle.
  136. /// This number can be lower than the number of steps when the vehicle is active as the only purpose of this test is
  137. /// to allow the vehicle to wake up in response to bodies moving into the wheels but not touching the body of the vehicle.
  138. void SetNumStepsBetweenCollisionTestInactive(uint inSteps) { mNumStepsBetweenCollisionTestInactive = inSteps; }
  139. uint GetNumStepsBetweenCollisionTestInactive() const { return mNumStepsBetweenCollisionTestInactive; }
  140. // Generic interface of a constraint
  141. virtual bool IsActive() const override { return mIsActive && Constraint::IsActive(); }
  142. virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) override { /* Do nothing */ }
  143. virtual void SetupVelocityConstraint(float inDeltaTime) override;
  144. virtual void ResetWarmStart() override;
  145. virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) override;
  146. virtual bool SolveVelocityConstraint(float inDeltaTime) override;
  147. virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) override;
  148. virtual void BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager) override;
  149. virtual uint BuildIslandSplits(LargeIslandSplitter &ioSplitter) const override;
  150. #ifdef JPH_DEBUG_RENDERER
  151. virtual void DrawConstraint(DebugRenderer *inRenderer) const override;
  152. virtual void DrawConstraintLimits(DebugRenderer *inRenderer) const override;
  153. #endif // JPH_DEBUG_RENDERER
  154. virtual void SaveState(StateRecorder &inStream) const override;
  155. virtual void RestoreState(StateRecorder &inStream) override;
  156. virtual Ref<ConstraintSettings> GetConstraintSettings() const override;
  157. private:
  158. // See: PhysicsStepListener
  159. virtual void OnStep(float inDeltaTime, PhysicsSystem &inPhysicsSystem) override;
  160. // Calculate the position where the suspension and traction forces should be applied in world space, relative to the center of mass of both bodies
  161. void CalculateSuspensionForcePoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const;
  162. // Calculate the constraint properties for mPitchRollPart
  163. void CalculatePitchRollConstraintProperties(RMat44Arg inBodyTransform);
  164. // Simulation information
  165. Body * mBody; ///< Body of the vehicle
  166. Vec3 mForward; ///< Local space forward vector for the vehicle
  167. Vec3 mUp; ///< Local space up vector for the vehicle
  168. Vec3 mWorldUp; ///< Vector indicating the world space up direction (used to limit vehicle pitch/roll)
  169. Wheels mWheels; ///< Wheel states of the vehicle
  170. Array<VehicleAntiRollBar> mAntiRollBars; ///< Anti rollbars of the vehicle
  171. VehicleController * mController; ///< Controls the acceleration / deceleration of the vehicle
  172. bool mIsActive = false; ///< If this constraint is active
  173. uint mNumStepsBetweenCollisionTestActive = 1; ///< Number of simulation steps between wheel collision tests when the vehicle is active
  174. uint mNumStepsBetweenCollisionTestInactive = 1; ///< Number of simulation steps between wheel collision tests when the vehicle is inactive
  175. uint mCurrentStep = 0; ///< Current step number, used to determine when to test a wheel
  176. // Prevent vehicle from toppling over
  177. float mCosMaxPitchRollAngle; ///< Cos of the max pitch/roll angle
  178. float mCosPitchRollAngle; ///< Cos of the current pitch/roll angle
  179. Vec3 mPitchRollRotationAxis { 0, 1, 0 }; ///< Current axis along which to apply torque to prevent the car from toppling over
  180. AngleConstraintPart mPitchRollPart; ///< Constraint part that prevents the car from toppling over
  181. // Interfaces
  182. RefConst<VehicleCollisionTester> mVehicleCollisionTester; ///< Class that performs testing of collision for the wheels
  183. CombineFunction mCombineFriction = [](uint, float &ioLongitudinalFriction, float &ioLateralFriction, const Body &inBody2, const SubShapeID &)
  184. {
  185. float body_friction = inBody2.GetFriction();
  186. ioLongitudinalFriction = sqrt(ioLongitudinalFriction * body_friction);
  187. ioLateralFriction = sqrt(ioLateralFriction * body_friction);
  188. };
  189. // Callbacks
  190. StepCallback mPreStepCallback;
  191. StepCallback mPostCollideCallback;
  192. StepCallback mPostStepCallback;
  193. };
  194. JPH_NAMESPACE_END