MotorcycleController.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2023 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Vehicle/MotorcycleController.h>
  6. #include <Jolt/Physics/PhysicsSystem.h>
  7. #include <Jolt/ObjectStream/TypeDeclarations.h>
  8. #include <Jolt/Core/StreamIn.h>
  9. #include <Jolt/Core/StreamOut.h>
  10. #ifdef JPH_DEBUG_RENDERER
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif // JPH_DEBUG_RENDERER
  13. JPH_NAMESPACE_BEGIN
  14. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(MotorcycleControllerSettings)
  15. {
  16. JPH_ADD_BASE_CLASS(MotorcycleControllerSettings, VehicleControllerSettings)
  17. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mMaxLeanAngle)
  18. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSpringConstant)
  19. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSpringDamping)
  20. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSmoothingFactor)
  21. }
  22. VehicleController *MotorcycleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  23. {
  24. return new MotorcycleController(*this, inConstraint);
  25. }
  26. void MotorcycleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  27. {
  28. WheeledVehicleControllerSettings::SaveBinaryState(inStream);
  29. inStream.Write(mMaxLeanAngle);
  30. inStream.Write(mLeanSpringConstant);
  31. inStream.Write(mLeanSpringDamping);
  32. inStream.Write(mLeanSmoothingFactor);
  33. }
  34. void MotorcycleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  35. {
  36. WheeledVehicleControllerSettings::RestoreBinaryState(inStream);
  37. inStream.Read(mMaxLeanAngle);
  38. inStream.Read(mLeanSpringConstant);
  39. inStream.Read(mLeanSpringDamping);
  40. inStream.Read(mLeanSmoothingFactor);
  41. }
  42. MotorcycleController::MotorcycleController(const MotorcycleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  43. WheeledVehicleController(inSettings, inConstraint),
  44. mMaxLeanAngle(inSettings.mMaxLeanAngle),
  45. mLeanSpringConstant(inSettings.mLeanSpringConstant),
  46. mLeanSpringDamping(inSettings.mLeanSpringDamping),
  47. mLeanSmoothingFactor(inSettings.mLeanSmoothingFactor)
  48. {
  49. }
  50. float MotorcycleController::GetWheelBase() const
  51. {
  52. float low = FLT_MAX, high = -FLT_MAX;
  53. for (const Wheel *w : mConstraint.GetWheels())
  54. {
  55. const WheelSettings *s = w->GetSettings();
  56. // Measure distance along the forward axis by looking at the fully extended suspension
  57. float value = (s->mPosition + s->mSuspensionDirection * s->mSuspensionMaxLength).Dot(mConstraint.GetLocalForward());
  58. // Update min and max
  59. low = min(low, value);
  60. high = max(high, value);
  61. }
  62. return high - low;
  63. }
  64. void MotorcycleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  65. {
  66. WheeledVehicleController::PreCollide(inDeltaTime, inPhysicsSystem);
  67. Vec3 gravity = inPhysicsSystem.GetGravity();
  68. float gravity_len = gravity.Length();
  69. Vec3 world_up = gravity_len > 0.0f? -gravity / gravity_len : mConstraint.GetLocalUp();
  70. const Body *body = mConstraint.GetVehicleBody();
  71. Vec3 forward = body->GetRotation() * mConstraint.GetLocalForward();
  72. float wheel_base = GetWheelBase();
  73. float velocity = body->GetLinearVelocity().Dot(forward);
  74. float velocity_sq = Square(velocity);
  75. // Calculate the target lean vector, this is in the direction of the total applied impulse by the ground on the wheels
  76. Vec3 target_lean = Vec3::sZero();
  77. for (const Wheel *w : mConstraint.GetWheels())
  78. if (w->HasContact())
  79. target_lean += w->GetContactNormal() * w->GetSuspensionLambda() + w->GetContactLateral() * w->GetLateralLambda();
  80. // Normalize the impulse
  81. target_lean = target_lean.NormalizedOr(world_up);
  82. // Smooth the impulse to avoid jittery behavior
  83. mTargetLean = mLeanSmoothingFactor * mTargetLean + (1.0f - mLeanSmoothingFactor) * target_lean;
  84. // Remove forward component, we can only lean sideways
  85. mTargetLean -= mTargetLean * mTargetLean.Dot(forward);
  86. mTargetLean = mTargetLean.NormalizedOr(world_up);
  87. JPH_DET_LOG("WheeledVehicleController::PreCollide: target_lean: " << target_lean << " mTargetLean: " << mTargetLean);
  88. // Calculate max steering angle based on the max lean angle we're willing to take
  89. // See: https://en.wikipedia.org/wiki/Bicycle_and_motorcycle_dynamics#Leaning
  90. // LeanAngle = Atan(Velocity^2 / (Gravity * TurnRadius))
  91. // And: https://en.wikipedia.org/wiki/Turning_radius (we're ignoring the tire width)
  92. // The CasterAngle is the added according to https://en.wikipedia.org/wiki/Bicycle_and_motorcycle_dynamics#Turning (this is the same formula but without small angle approximation)
  93. // TurnRadius = WheelBase / (Sin(SteerAngle) * Cos(CasterAngle))
  94. // => SteerAngle = ASin(WheelBase * Tan(LeanAngle) * Gravity / (Velocity^2 * Cos(CasterAngle))
  95. // The caster angle is different for each wheel so we can only calculate part of the equation here
  96. float max_steer_angle_factor = wheel_base * Tan(mMaxLeanAngle) * gravity_len;
  97. // Decompose steering into sign and direction
  98. float steer_strength = abs(mRightInput);
  99. float steer_sign = -Sign(mRightInput);
  100. for (Wheel *w_base : mConstraint.GetWheels())
  101. {
  102. WheelWV *w = static_cast<WheelWV *>(w_base);
  103. const WheelSettingsWV *s = w->GetSettings();
  104. // Check if this wheel can steer
  105. if (s->mMaxSteerAngle != 0.0f)
  106. {
  107. // Calculate cos(caster angle), the angle between the steering axis and the up vector
  108. float cos_caster_angle = s->mSteeringAxis.Dot(mConstraint.GetLocalUp());
  109. // Calculate steer angle
  110. float steer_angle = steer_strength * w->GetSettings()->mMaxSteerAngle;
  111. // Clamp to max steering angle
  112. if (velocity_sq > 1.0e-6f)
  113. {
  114. float max_steer_angle = ASin(max_steer_angle_factor / (velocity_sq * cos_caster_angle));
  115. steer_angle = min(steer_angle, max_steer_angle);
  116. }
  117. // Set steering angle
  118. w->SetSteerAngle(steer_sign * steer_angle);
  119. }
  120. }
  121. // Reset applied impulse
  122. mAppliedImpulse = 0;
  123. }
  124. bool MotorcycleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  125. {
  126. bool impulse = WheeledVehicleController::SolveLongitudinalAndLateralConstraints(inDeltaTime);
  127. // Only apply a lean impulse if all wheels are in contact, otherwise we can easily spin out
  128. bool all_in_contact = true;
  129. for (const Wheel *w : mConstraint.GetWheels())
  130. if (!w->HasContact() || w->GetSuspensionLambda() <= 0.0f)
  131. {
  132. all_in_contact = false;
  133. break;
  134. }
  135. if (all_in_contact)
  136. {
  137. Body *body = mConstraint.GetVehicleBody();
  138. const MotionProperties *mp = body->GetMotionProperties();
  139. Vec3 forward = body->GetRotation() * mConstraint.GetLocalForward();
  140. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  141. // Calculate delta to target angle and derivative
  142. float d_angle = -Sign(mTargetLean.Cross(up).Dot(forward)) * ACos(mTargetLean.Dot(up));
  143. float ddt_angle = body->GetAngularVelocity().Dot(forward);
  144. // Calculate impulse to apply to get to target lean angle
  145. float total_impulse = (mLeanSpringConstant * d_angle - mLeanSpringDamping * ddt_angle) * inDeltaTime;
  146. // Remember angular velocity pre angular impulse
  147. Vec3 old_w = mp->GetAngularVelocity();
  148. // Apply impulse taking into account the impulse we've applied earlier
  149. float delta_impulse = total_impulse - mAppliedImpulse;
  150. body->AddAngularImpulse(delta_impulse * forward);
  151. mAppliedImpulse = total_impulse;
  152. // Calculate delta angular velocity due to angular impulse
  153. Vec3 dw = mp->GetAngularVelocity() - old_w;
  154. Vec3 linear_acceleration = Vec3::sZero();
  155. float total_lambda = 0.0f;
  156. for (Wheel *w_base : mConstraint.GetWheels())
  157. {
  158. const WheelWV *w = static_cast<WheelWV *>(w_base);
  159. // We weigh the importance of each contact point according to the contact force
  160. float lambda = w->GetSuspensionLambda();
  161. total_lambda += lambda;
  162. // Linear acceleration of contact point is dw x com_to_contact
  163. Vec3 r = Vec3(w->GetContactPosition() - body->GetCenterOfMassPosition());
  164. linear_acceleration += lambda * dw.Cross(r);
  165. }
  166. // Apply linear impulse to COM to cancel the average velocity change on the wheels due to the angular impulse
  167. Vec3 linear_impulse = -linear_acceleration / (total_lambda * mp->GetInverseMass());
  168. body->AddImpulse(linear_impulse);
  169. // Return true if we applied an impulse
  170. impulse |= delta_impulse != 0.0f;
  171. }
  172. return impulse;
  173. }
  174. void MotorcycleController::SaveState(StateRecorder& inStream) const
  175. {
  176. WheeledVehicleController::SaveState(inStream);
  177. inStream.Write(mTargetLean);
  178. }
  179. void MotorcycleController::RestoreState(StateRecorder& inStream)
  180. {
  181. WheeledVehicleController::RestoreState(inStream);
  182. inStream.Read(mTargetLean);
  183. }
  184. #ifdef JPH_DEBUG_RENDERER
  185. void MotorcycleController::Draw(DebugRenderer *inRenderer) const
  186. {
  187. WheeledVehicleController::Draw(inRenderer);
  188. // Draw current and desired lean angle
  189. Body *body = mConstraint.GetVehicleBody();
  190. RVec3 center_of_mass = body->GetCenterOfMassPosition();
  191. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  192. inRenderer->DrawArrow(center_of_mass, center_of_mass + up, Color::sYellow, 0.1f);
  193. inRenderer->DrawArrow(center_of_mass, center_of_mass + mTargetLean, Color::sRed, 0.1f);
  194. }
  195. #endif // JPH_DEBUG_RENDERER
  196. JPH_NAMESPACE_END