MotorcycleController.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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, mLeanSpringIntegrationCoefficient)
  21. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSpringIntegrationCoefficientDecay)
  22. JPH_ADD_ATTRIBUTE(MotorcycleControllerSettings, mLeanSmoothingFactor)
  23. }
  24. VehicleController *MotorcycleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  25. {
  26. return new MotorcycleController(*this, inConstraint);
  27. }
  28. void MotorcycleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  29. {
  30. WheeledVehicleControllerSettings::SaveBinaryState(inStream);
  31. inStream.Write(mMaxLeanAngle);
  32. inStream.Write(mLeanSpringConstant);
  33. inStream.Write(mLeanSpringDamping);
  34. inStream.Write(mLeanSpringIntegrationCoefficient);
  35. inStream.Write(mLeanSpringIntegrationCoefficientDecay);
  36. inStream.Write(mLeanSmoothingFactor);
  37. }
  38. void MotorcycleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  39. {
  40. WheeledVehicleControllerSettings::RestoreBinaryState(inStream);
  41. inStream.Read(mMaxLeanAngle);
  42. inStream.Read(mLeanSpringConstant);
  43. inStream.Read(mLeanSpringDamping);
  44. inStream.Read(mLeanSpringIntegrationCoefficient);
  45. inStream.Read(mLeanSpringIntegrationCoefficientDecay);
  46. inStream.Read(mLeanSmoothingFactor);
  47. }
  48. MotorcycleController::MotorcycleController(const MotorcycleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  49. WheeledVehicleController(inSettings, inConstraint),
  50. mMaxLeanAngle(inSettings.mMaxLeanAngle),
  51. mLeanSpringConstant(inSettings.mLeanSpringConstant),
  52. mLeanSpringDamping(inSettings.mLeanSpringDamping),
  53. mLeanSpringIntegrationCoefficient(inSettings.mLeanSpringIntegrationCoefficient),
  54. mLeanSpringIntegrationCoefficientDecay(inSettings.mLeanSpringIntegrationCoefficientDecay),
  55. mLeanSmoothingFactor(inSettings.mLeanSmoothingFactor)
  56. {
  57. }
  58. float MotorcycleController::GetWheelBase() const
  59. {
  60. float low = FLT_MAX, high = -FLT_MAX;
  61. for (const Wheel *w : mConstraint.GetWheels())
  62. {
  63. const WheelSettings *s = w->GetSettings();
  64. // Measure distance along the forward axis by looking at the fully extended suspension.
  65. // If the suspension force point is active, use that instead.
  66. Vec3 force_point = s->mEnableSuspensionForcePoint? s->mSuspensionForcePoint : s->mPosition + s->mSuspensionDirection * s->mSuspensionMaxLength;
  67. float value = force_point.Dot(mConstraint.GetLocalForward());
  68. // Update min and max
  69. low = min(low, value);
  70. high = max(high, value);
  71. }
  72. return high - low;
  73. }
  74. void MotorcycleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  75. {
  76. WheeledVehicleController::PreCollide(inDeltaTime, inPhysicsSystem);
  77. const Body *body = mConstraint.GetVehicleBody();
  78. Vec3 forward = body->GetRotation() * mConstraint.GetLocalForward();
  79. float wheel_base = GetWheelBase();
  80. Vec3 world_up = mConstraint.GetWorldUp();
  81. if (mEnableLeanController)
  82. {
  83. // Calculate the target lean vector, this is in the direction of the total applied impulse by the ground on the wheels
  84. Vec3 target_lean = Vec3::sZero();
  85. for (const Wheel *w : mConstraint.GetWheels())
  86. if (w->HasContact())
  87. target_lean += w->GetContactNormal() * w->GetSuspensionLambda() + w->GetContactLateral() * w->GetLateralLambda();
  88. // Normalize the impulse
  89. target_lean = target_lean.NormalizedOr(world_up);
  90. // Smooth the impulse to avoid jittery behavior
  91. mTargetLean = mLeanSmoothingFactor * mTargetLean + (1.0f - mLeanSmoothingFactor) * target_lean;
  92. // Remove forward component, we can only lean sideways
  93. mTargetLean -= forward * mTargetLean.Dot(forward);
  94. mTargetLean = mTargetLean.NormalizedOr(world_up);
  95. // Clamp the target lean against the max lean angle
  96. Vec3 adjusted_world_up = world_up - forward * world_up.Dot(forward);
  97. adjusted_world_up = adjusted_world_up.NormalizedOr(world_up);
  98. float w_angle = -Sign(mTargetLean.Cross(adjusted_world_up).Dot(forward)) * ACos(mTargetLean.Dot(adjusted_world_up));
  99. if (abs(w_angle) > mMaxLeanAngle)
  100. mTargetLean = Quat::sRotation(forward, Sign(w_angle) * mMaxLeanAngle) * adjusted_world_up;
  101. // Integrate the delta angle
  102. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  103. float d_angle = -Sign(mTargetLean.Cross(up).Dot(forward)) * ACos(mTargetLean.Dot(up));
  104. mLeanSpringIntegratedDeltaAngle += d_angle * inDeltaTime;
  105. }
  106. else
  107. {
  108. // Controller not enabled, reset target lean
  109. mTargetLean = world_up;
  110. // Reset integrated delta angle
  111. mLeanSpringIntegratedDeltaAngle = 0;
  112. }
  113. JPH_DET_LOG("WheeledVehicleController::PreCollide: mTargetLean: " << mTargetLean);
  114. // Calculate max steering angle based on the max lean angle we're willing to take
  115. // See: https://en.wikipedia.org/wiki/Bicycle_and_motorcycle_dynamics#Leaning
  116. // LeanAngle = Atan(Velocity^2 / (Gravity * TurnRadius))
  117. // And: https://en.wikipedia.org/wiki/Turning_radius (we're ignoring the tire width)
  118. // 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)
  119. // TurnRadius = WheelBase / (Sin(SteerAngle) * Cos(CasterAngle))
  120. // => SteerAngle = ASin(WheelBase * Tan(LeanAngle) * Gravity / (Velocity^2 * Cos(CasterAngle))
  121. // The caster angle is different for each wheel so we can only calculate part of the equation here
  122. float max_steer_angle_factor = wheel_base * Tan(mMaxLeanAngle) * inPhysicsSystem.GetGravity().Length();
  123. // Calculate forward velocity
  124. float velocity = body->GetLinearVelocity().Dot(forward);
  125. float velocity_sq = Square(velocity);
  126. // Decompose steering into sign and direction
  127. float steer_strength = abs(mRightInput);
  128. float steer_sign = -Sign(mRightInput);
  129. for (Wheel *w_base : mConstraint.GetWheels())
  130. {
  131. WheelWV *w = static_cast<WheelWV *>(w_base);
  132. const WheelSettingsWV *s = w->GetSettings();
  133. // Check if this wheel can steer
  134. if (s->mMaxSteerAngle != 0.0f)
  135. {
  136. // Calculate cos(caster angle), the angle between the steering axis and the up vector
  137. float cos_caster_angle = s->mSteeringAxis.Dot(mConstraint.GetLocalUp());
  138. // Calculate steer angle
  139. float steer_angle = steer_strength * w->GetSettings()->mMaxSteerAngle;
  140. // Clamp to max steering angle
  141. if (velocity_sq > 1.0e-6f && cos_caster_angle > 1.0e-6f)
  142. {
  143. float max_steer_angle = ASin(max_steer_angle_factor / (velocity_sq * cos_caster_angle));
  144. steer_angle = min(steer_angle, max_steer_angle);
  145. }
  146. // Set steering angle
  147. w->SetSteerAngle(steer_sign * steer_angle);
  148. }
  149. }
  150. // Reset applied impulse
  151. mAppliedImpulse = 0;
  152. }
  153. bool MotorcycleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  154. {
  155. bool impulse = WheeledVehicleController::SolveLongitudinalAndLateralConstraints(inDeltaTime);
  156. if (mEnableLeanController)
  157. {
  158. // Only apply a lean impulse if all wheels are in contact, otherwise we can easily spin out
  159. bool all_in_contact = true;
  160. for (const Wheel *w : mConstraint.GetWheels())
  161. if (!w->HasContact() || w->GetSuspensionLambda() <= 0.0f)
  162. {
  163. all_in_contact = false;
  164. break;
  165. }
  166. if (all_in_contact)
  167. {
  168. Body *body = mConstraint.GetVehicleBody();
  169. const MotionProperties *mp = body->GetMotionProperties();
  170. Vec3 forward = body->GetRotation() * mConstraint.GetLocalForward();
  171. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  172. // Calculate delta to target angle and derivative
  173. float d_angle = -Sign(mTargetLean.Cross(up).Dot(forward)) * ACos(mTargetLean.Dot(up));
  174. float ddt_angle = body->GetAngularVelocity().Dot(forward);
  175. // Calculate impulse to apply to get to target lean angle
  176. float total_impulse = (mLeanSpringConstant * d_angle - mLeanSpringDamping * ddt_angle + mLeanSpringIntegrationCoefficient * mLeanSpringIntegratedDeltaAngle) * inDeltaTime;
  177. // Remember angular velocity pre angular impulse
  178. Vec3 old_w = mp->GetAngularVelocity();
  179. // Apply impulse taking into account the impulse we've applied earlier
  180. float delta_impulse = total_impulse - mAppliedImpulse;
  181. body->AddAngularImpulse(delta_impulse * forward);
  182. mAppliedImpulse = total_impulse;
  183. // Calculate delta angular velocity due to angular impulse
  184. Vec3 dw = mp->GetAngularVelocity() - old_w;
  185. Vec3 linear_acceleration = Vec3::sZero();
  186. float total_lambda = 0.0f;
  187. for (Wheel *w_base : mConstraint.GetWheels())
  188. {
  189. const WheelWV *w = static_cast<WheelWV *>(w_base);
  190. // We weigh the importance of each contact point according to the contact force
  191. float lambda = w->GetSuspensionLambda();
  192. total_lambda += lambda;
  193. // Linear acceleration of contact point is dw x com_to_contact
  194. Vec3 r = Vec3(w->GetContactPosition() - body->GetCenterOfMassPosition());
  195. linear_acceleration += lambda * dw.Cross(r);
  196. }
  197. // Apply linear impulse to COM to cancel the average velocity change on the wheels due to the angular impulse
  198. Vec3 linear_impulse = -linear_acceleration / (total_lambda * mp->GetInverseMass());
  199. body->AddImpulse(linear_impulse);
  200. // Return true if we applied an impulse
  201. impulse |= delta_impulse != 0.0f;
  202. }
  203. else
  204. {
  205. // Decay the integrated angle because we won't be applying a torque this frame
  206. // Uses 1st order Taylor approximation of e^(-decay * dt) = 1 - decay * dt
  207. mLeanSpringIntegratedDeltaAngle *= max(0.0f, 1.0f - mLeanSpringIntegrationCoefficientDecay * inDeltaTime);
  208. }
  209. }
  210. return impulse;
  211. }
  212. void MotorcycleController::SaveState(StateRecorder& inStream) const
  213. {
  214. WheeledVehicleController::SaveState(inStream);
  215. inStream.Write(mTargetLean);
  216. }
  217. void MotorcycleController::RestoreState(StateRecorder& inStream)
  218. {
  219. WheeledVehicleController::RestoreState(inStream);
  220. inStream.Read(mTargetLean);
  221. }
  222. #ifdef JPH_DEBUG_RENDERER
  223. void MotorcycleController::Draw(DebugRenderer *inRenderer) const
  224. {
  225. WheeledVehicleController::Draw(inRenderer);
  226. // Draw current and desired lean angle
  227. Body *body = mConstraint.GetVehicleBody();
  228. RVec3 center_of_mass = body->GetCenterOfMassPosition();
  229. Vec3 up = body->GetRotation() * mConstraint.GetLocalUp();
  230. inRenderer->DrawArrow(center_of_mass, center_of_mass + up, Color::sYellow, 0.1f);
  231. inRenderer->DrawArrow(center_of_mass, center_of_mass + mTargetLean, Color::sRed, 0.1f);
  232. }
  233. #endif // JPH_DEBUG_RENDERER
  234. JPH_NAMESPACE_END