VehicleConstraint.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. JPH_NAMESPACE_BEGIN
  12. class PhysicsSystem;
  13. class VehicleController;
  14. class VehicleControllerSettings;
  15. /// Configuration for constraint that simulates a wheeled vehicle.
  16. ///
  17. /// The properties in this constraint are largely based on "Car Physics for Games" by Marco Monster.
  18. /// See: https://www.asawicki.info/Mirror/Car%20Physics%20for%20Games/Car%20Physics%20for%20Games.html
  19. class VehicleConstraintSettings : public ConstraintSettings
  20. {
  21. public:
  22. JPH_DECLARE_SERIALIZABLE_VIRTUAL(VehicleConstraintSettings)
  23. /// Saves the contents of the constraint settings in binary form to inStream.
  24. virtual void SaveBinaryState(StreamOut &inStream) const override;
  25. Vec3 mUp { 0, 1, 0 }; ///< Vector indicating the up direction of the vehicle (in local space to the body)
  26. Vec3 mForward { 0, 0, 1 }; ///< Vector indicating forward direction of the vehicle (in local space to the body)
  27. 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.
  28. Array<Ref<WheelSettings>> mWheels; ///< List of wheels and their properties
  29. Array<VehicleAntiRollBar> mAntiRollBars; ///< List of anti rollbars and their properties
  30. Ref<VehicleControllerSettings> mController; ///< Defines how the vehicle can accelerate / decellerate
  31. protected:
  32. /// This function should not be called directly, it is used by sRestoreFromBinaryState.
  33. virtual void RestoreBinaryState(StreamIn &inStream) override;
  34. };
  35. /// Constraint that simulates a vehicle
  36. /// Note: Don't forget to register the constraint as a StepListener with the PhysicsSystem!
  37. ///
  38. /// 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.
  39. /// 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
  40. /// 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.
  41. ///
  42. /// There are a couple of ways to improve this:
  43. ///
  44. /// 1. You can increase the number of velocity steps (global settings PhysicsSettings::mNumVelocitySteps or if you only want to increase it on
  45. /// 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.
  46. /// 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
  47. /// occur which inevitably happens due to numerical drift). This solution costs CPU cycles.
  48. ///
  49. /// 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).
  50. ///
  51. /// 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
  52. /// 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).
  53. /// 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).
  54. ///
  55. /// 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.
  56. /// To alleviate this, it may be needed to smooth the motion of the visual mesh for the wheel.
  57. class VehicleConstraint : public Constraint, public PhysicsStepListener
  58. {
  59. public:
  60. /// Constructor / destructor
  61. VehicleConstraint(Body &inVehicleBody, const VehicleConstraintSettings &inSettings);
  62. virtual ~VehicleConstraint() override;
  63. /// Get the type of a constraint
  64. virtual EConstraintSubType GetSubType() const override { return EConstraintSubType::Vehicle; }
  65. /// 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.
  66. void SetMaxPitchRollAngle(float inMaxPitchRollAngle) { mCosMaxPitchRollAngle = Cos(inMaxPitchRollAngle); }
  67. /// Set the interface that tests collision between wheel and ground
  68. void SetVehicleCollisionTester(const VehicleCollisionTester *inTester) { mVehicleCollisionTester = inTester; }
  69. /// Get the local space forward vector of the vehicle
  70. Vec3 GetLocalForward() const { return mForward; }
  71. /// Get the local space up vector of the vehicle
  72. Vec3 GetLocalUp() const { return mUp; }
  73. /// Access to the vehicle body
  74. Body * GetVehicleBody() const { return mBody; }
  75. /// Access to the vehicle controller interface (determines acceleration / decelleration)
  76. const VehicleController * GetController() const { return mController; }
  77. /// Access to the vehicle controller interface (determines acceleration / decelleration)
  78. VehicleController * GetController() { return mController; }
  79. /// Get the state of the wheels
  80. const Wheels & GetWheels() const { return mWheels; }
  81. /// Get the state of a wheels (writable interface, allows you to make changes to the configuration which will take effect the next time step)
  82. Wheels & GetWheels() { return mWheels; }
  83. /// Get the state of a wheel
  84. Wheel * GetWheel(uint inIdx) { return mWheels[inIdx]; }
  85. const Wheel * GetWheel(uint inIdx) const { return mWheels[inIdx]; }
  86. /// Get the basis vectors for the wheel in local space to the vehicle body (note: basis does not rotate when the wheel rotates arounds its axis)
  87. /// @param inWheel Wheel to fetch basis for
  88. /// @param outForward Forward vector for the wheel
  89. /// @param outUp Up vector for the wheel
  90. /// @param outRight Right vector for the wheel
  91. void GetWheelLocalBasis(const Wheel *inWheel, Vec3 &outForward, Vec3 &outUp, Vec3 &outRight) const;
  92. /// 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)
  93. /// @param inWheelIndex Index of the wheel to fetch
  94. /// @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)
  95. /// @param inWheelUp Unit vector that indicates up in model space of the wheel
  96. Mat44 GetWheelLocalTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const;
  97. /// Get the transform of a wheel in world space, returns a matrix that transforms a cylinder aligned with the Y axis in world space
  98. /// @param inWheelIndex Index of the wheel to fetch
  99. /// @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)
  100. /// @param inWheelUp Unit vector that indicates up in model space of the wheel
  101. RMat44 GetWheelWorldTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const;
  102. // Generic interface of a constraint
  103. virtual bool IsActive() const override { return mIsActive && Constraint::IsActive(); }
  104. virtual void NotifyShapeChanged(const BodyID &inBodyID, Vec3Arg inDeltaCOM) override { /* Do nothing */ }
  105. virtual void SetupVelocityConstraint(float inDeltaTime) override;
  106. virtual void WarmStartVelocityConstraint(float inWarmStartImpulseRatio) override;
  107. virtual bool SolveVelocityConstraint(float inDeltaTime) override;
  108. virtual bool SolvePositionConstraint(float inDeltaTime, float inBaumgarte) override;
  109. virtual void BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager) override;
  110. virtual uint BuildIslandSplits(LargeIslandSplitter &ioSplitter) const override;
  111. #ifdef JPH_DEBUG_RENDERER
  112. virtual void DrawConstraint(DebugRenderer *inRenderer) const override;
  113. virtual void DrawConstraintLimits(DebugRenderer *inRenderer) const override;
  114. #endif // JPH_DEBUG_RENDERER
  115. virtual void SaveState(StateRecorder &inStream) const override;
  116. virtual void RestoreState(StateRecorder &inStream) override;
  117. virtual Ref<ConstraintSettings> GetConstraintSettings() const override;
  118. private:
  119. // See: PhysicsStepListener
  120. virtual void OnStep(float inDeltaTime, PhysicsSystem &inPhysicsSystem) override;
  121. // Calculate the contact positions of the wheel in world space, relative to the center of mass of both bodies
  122. void CalculateWheelContactPoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const;
  123. // Calculate the constraint properties for mPitchRollPart
  124. void CalculatePitchRollConstraintProperties(float inDeltaTime, RMat44Arg inBodyTransform);
  125. // Simluation information
  126. Body * mBody; ///< Body of the vehicle
  127. Vec3 mForward; ///< Local space forward vector for the vehicle
  128. Vec3 mUp; ///< Local space up vector for the vehicle
  129. Wheels mWheels; ///< Wheel states of the vehicle
  130. Array<VehicleAntiRollBar> mAntiRollBars; ///< Anti rollbars of the vehicle
  131. VehicleController * mController; ///< Controls the acceleration / declerration of the vehicle
  132. bool mIsActive = false; ///< If this constraint is active
  133. // Prevent vehicle from toppling over
  134. float mCosMaxPitchRollAngle; ///< Cos of the max pitch/roll angle
  135. float mCosPitchRollAngle; ///< Cos of the current pitch/roll angle
  136. Vec3 mPitchRollRotationAxis { 0, 1, 0 }; ///< Current axis along which to apply torque to prevent the car from toppling over
  137. AngleConstraintPart mPitchRollPart; ///< Constraint part that prevents the car from toppling over
  138. // Interfaces
  139. RefConst<VehicleCollisionTester> mVehicleCollisionTester; ///< Class that performs testing of collision for the wheels
  140. };
  141. JPH_NAMESPACE_END