WheeledVehicleController.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include <Jolt/Jolt.h>
  5. #include <Jolt/Physics/Vehicle/WheeledVehicleController.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. #include <Jolt/Math/DynMatrix.h>
  11. #include <Jolt/Math/GaussianElimination.h>
  12. #ifdef JPH_DEBUG_RENDERER
  13. #include <Jolt/Renderer/DebugRenderer.h>
  14. #endif // JPH_DEBUG_RENDERER
  15. //#define JPH_TRACE_VEHICLE_STATS
  16. JPH_NAMESPACE_BEGIN
  17. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheeledVehicleControllerSettings)
  18. {
  19. JPH_ADD_BASE_CLASS(WheeledVehicleControllerSettings, VehicleControllerSettings)
  20. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mEngine)
  21. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mTransmission)
  22. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mDifferentials)
  23. JPH_ADD_ATTRIBUTE(WheeledVehicleControllerSettings, mDifferentialLimitedSlipRatio)
  24. }
  25. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheelSettingsWV)
  26. {
  27. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mInertia)
  28. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mAngularDamping)
  29. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxSteerAngle)
  30. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mLongitudinalFriction)
  31. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mLateralFriction)
  32. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxBrakeTorque)
  33. JPH_ADD_ATTRIBUTE(WheelSettingsWV, mMaxHandBrakeTorque)
  34. }
  35. WheelSettingsWV::WheelSettingsWV()
  36. {
  37. mLongitudinalFriction.Reserve(3);
  38. mLongitudinalFriction.AddPoint(0.0f, 0.0f);
  39. mLongitudinalFriction.AddPoint(0.06f, 1.2f);
  40. mLongitudinalFriction.AddPoint(0.2f, 1.0f);
  41. mLateralFriction.Reserve(3);
  42. mLateralFriction.AddPoint(0.0f, 0.0f);
  43. mLateralFriction.AddPoint(3.0f, 1.2f);
  44. mLateralFriction.AddPoint(20.0f, 1.0f);
  45. }
  46. void WheelSettingsWV::SaveBinaryState(StreamOut &inStream) const
  47. {
  48. inStream.Write(mInertia);
  49. inStream.Write(mAngularDamping);
  50. inStream.Write(mMaxSteerAngle);
  51. mLongitudinalFriction.SaveBinaryState(inStream);
  52. mLateralFriction.SaveBinaryState(inStream);
  53. inStream.Write(mMaxBrakeTorque);
  54. inStream.Write(mMaxHandBrakeTorque);
  55. }
  56. void WheelSettingsWV::RestoreBinaryState(StreamIn &inStream)
  57. {
  58. inStream.Read(mInertia);
  59. inStream.Read(mAngularDamping);
  60. inStream.Read(mMaxSteerAngle);
  61. mLongitudinalFriction.RestoreBinaryState(inStream);
  62. mLateralFriction.RestoreBinaryState(inStream);
  63. inStream.Read(mMaxBrakeTorque);
  64. inStream.Read(mMaxHandBrakeTorque);
  65. }
  66. WheelWV::WheelWV(const WheelSettingsWV &inSettings) :
  67. Wheel(inSettings)
  68. {
  69. JPH_ASSERT(inSettings.mInertia >= 0.0f);
  70. JPH_ASSERT(inSettings.mAngularDamping >= 0.0f);
  71. JPH_ASSERT(abs(inSettings.mMaxSteerAngle) <= 0.5f * JPH_PI);
  72. JPH_ASSERT(inSettings.mMaxBrakeTorque >= 0.0f);
  73. JPH_ASSERT(inSettings.mMaxHandBrakeTorque >= 0.0f);
  74. }
  75. void WheelWV::Update(uint inWheelIndex, float inDeltaTime, const VehicleConstraint &inConstraint)
  76. {
  77. const WheelSettingsWV *settings = GetSettings();
  78. // Angular damping: dw/dt = -c * w
  79. // Solution: w(t) = w(0) * e^(-c * t) or w2 = w1 * e^(-c * dt)
  80. // Taylor expansion of e^(-c * dt) = 1 - c * dt + ...
  81. // Since dt is usually in the order of 1/60 and c is a low number too this approximation is good enough
  82. mAngularVelocity *= max(0.0f, 1.0f - settings->mAngularDamping * inDeltaTime);
  83. // Update rotation of wheel
  84. mAngle = fmod(mAngle + mAngularVelocity * inDeltaTime, 2.0f * JPH_PI);
  85. if (mContactBody != nullptr)
  86. {
  87. const Body *body = inConstraint.GetVehicleBody();
  88. // Calculate relative velocity between wheel contact point and floor
  89. Vec3 relative_velocity = body->GetPointVelocity(mContactPosition) - mContactPointVelocity;
  90. // Cancel relative velocity in the normal plane
  91. relative_velocity -= mContactNormal.Dot(relative_velocity) * mContactNormal;
  92. float relative_longitudinal_velocity = relative_velocity.Dot(mContactLongitudinal);
  93. // Calculate longitudinal friction based on difference between velocity of rolling wheel and drive surface
  94. float relative_longitudinal_velocity_denom = Sign(relative_longitudinal_velocity) * max(1.0e-3f, abs(relative_longitudinal_velocity)); // Ensure we don't divide by zero
  95. mLongitudinalSlip = abs((mAngularVelocity * settings->mRadius - relative_longitudinal_velocity) / relative_longitudinal_velocity_denom);
  96. float longitudinal_slip_friction = settings->mLongitudinalFriction.GetValue(mLongitudinalSlip);
  97. // Calculate lateral friction based on slip angle
  98. float relative_velocity_len = relative_velocity.Length();
  99. mLateralSlip = relative_velocity_len < 1.0e-3f ? 0.0f : ACos(abs(relative_longitudinal_velocity) / relative_velocity_len);
  100. float lateral_slip_angle = RadiansToDegrees(mLateralSlip);
  101. float lateral_slip_friction = settings->mLateralFriction.GetValue(lateral_slip_angle);
  102. // Tire friction
  103. VehicleConstraint::CombineFunction combine_friction = inConstraint.GetCombineFriction();
  104. mCombinedLongitudinalFriction = longitudinal_slip_friction;
  105. mCombinedLateralFriction = lateral_slip_friction;
  106. combine_friction(inWheelIndex, mCombinedLongitudinalFriction, mCombinedLateralFriction, *mContactBody, mContactSubShapeID);
  107. }
  108. else
  109. {
  110. // No collision
  111. mLongitudinalSlip = 0.0f;
  112. mLateralSlip = 0.0f;
  113. mCombinedLongitudinalFriction = mCombinedLateralFriction = 0.0f;
  114. }
  115. }
  116. VehicleController *WheeledVehicleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  117. {
  118. return new WheeledVehicleController(*this, inConstraint);
  119. }
  120. void WheeledVehicleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  121. {
  122. mEngine.SaveBinaryState(inStream);
  123. mTransmission.SaveBinaryState(inStream);
  124. uint32 num_differentials = (uint32)mDifferentials.size();
  125. inStream.Write(num_differentials);
  126. for (const VehicleDifferentialSettings &d : mDifferentials)
  127. d.SaveBinaryState(inStream);
  128. inStream.Write(mDifferentialLimitedSlipRatio);
  129. }
  130. void WheeledVehicleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  131. {
  132. mEngine.RestoreBinaryState(inStream);
  133. mTransmission.RestoreBinaryState(inStream);
  134. uint32 num_differentials = 0;
  135. inStream.Read(num_differentials);
  136. mDifferentials.resize(num_differentials);
  137. for (VehicleDifferentialSettings &d : mDifferentials)
  138. d.RestoreBinaryState(inStream);
  139. inStream.Read(mDifferentialLimitedSlipRatio);
  140. }
  141. WheeledVehicleController::WheeledVehicleController(const WheeledVehicleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  142. VehicleController(inConstraint)
  143. {
  144. // Copy engine settings
  145. static_cast<VehicleEngineSettings &>(mEngine) = inSettings.mEngine;
  146. JPH_ASSERT(inSettings.mEngine.mMinRPM >= 0.0f);
  147. JPH_ASSERT(inSettings.mEngine.mMinRPM <= inSettings.mEngine.mMaxRPM);
  148. mEngine.SetCurrentRPM(mEngine.mMinRPM);
  149. // Copy transmission settings
  150. static_cast<VehicleTransmissionSettings &>(mTransmission) = inSettings.mTransmission;
  151. #ifdef JPH_ENABLE_ASSERTS
  152. for (float r : inSettings.mTransmission.mGearRatios)
  153. JPH_ASSERT(r > 0.0f);
  154. for (float r : inSettings.mTransmission.mReverseGearRatios)
  155. JPH_ASSERT(r < 0.0f);
  156. #endif // JPH_ENABLE_ASSERTS
  157. JPH_ASSERT(inSettings.mTransmission.mSwitchTime >= 0.0f);
  158. JPH_ASSERT(inSettings.mTransmission.mShiftDownRPM > 0.0f);
  159. JPH_ASSERT(inSettings.mTransmission.mMode != ETransmissionMode::Auto || inSettings.mTransmission.mShiftUpRPM < inSettings.mEngine.mMaxRPM);
  160. JPH_ASSERT(inSettings.mTransmission.mShiftUpRPM > inSettings.mTransmission.mShiftDownRPM);
  161. JPH_ASSERT(inSettings.mTransmission.mClutchStrength > 0.0f);
  162. // Copy differential settings
  163. mDifferentials.resize(inSettings.mDifferentials.size());
  164. for (uint i = 0; i < mDifferentials.size(); ++i)
  165. {
  166. const VehicleDifferentialSettings &d = inSettings.mDifferentials[i];
  167. mDifferentials[i] = d;
  168. JPH_ASSERT(d.mDifferentialRatio > 0.0f);
  169. JPH_ASSERT(d.mLeftRightSplit >= 0.0f && d.mLeftRightSplit <= 1.0f);
  170. JPH_ASSERT(d.mEngineTorqueRatio >= 0.0f);
  171. JPH_ASSERT(d.mLimitedSlipRatio > 1.0f);
  172. }
  173. mDifferentialLimitedSlipRatio = inSettings.mDifferentialLimitedSlipRatio;
  174. JPH_ASSERT(mDifferentialLimitedSlipRatio > 1.0f);
  175. }
  176. float WheeledVehicleController::GetWheelSpeedAtClutch() const
  177. {
  178. float wheel_speed_at_clutch = 0.0f;
  179. int num_driven_wheels = 0;
  180. for (const VehicleDifferentialSettings &d : mDifferentials)
  181. {
  182. int wheels[] = { d.mLeftWheel, d.mRightWheel };
  183. for (int w : wheels)
  184. if (w >= 0)
  185. {
  186. wheel_speed_at_clutch += mConstraint.GetWheel(w)->GetAngularVelocity() * d.mDifferentialRatio;
  187. num_driven_wheels++;
  188. }
  189. }
  190. return wheel_speed_at_clutch / float(num_driven_wheels) * VehicleEngine::cAngularVelocityToRPM * mTransmission.GetCurrentRatio();
  191. }
  192. bool WheeledVehicleController::AllowSleep() const
  193. {
  194. return mForwardInput == 0.0f // No user input
  195. && mTransmission.AllowSleep() // Transmission is not shifting
  196. && mEngine.AllowSleep(); // Engine is idling
  197. }
  198. void WheeledVehicleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  199. {
  200. JPH_PROFILE_FUNCTION();
  201. #ifdef JPH_TRACE_VEHICLE_STATS
  202. static bool sTracedHeader = false;
  203. if (!sTracedHeader)
  204. {
  205. Trace("Time, ForwardInput, Gear, ClutchFriction, EngineRPM, WheelRPM, Velocity (km/h)");
  206. sTracedHeader = true;
  207. }
  208. static float sTime = 0.0f;
  209. sTime += inDeltaTime;
  210. Trace("%.3f, %.1f, %d, %.1f, %.1f, %.1f, %.1f", sTime, mForwardInput, mTransmission.GetCurrentGear(), mTransmission.GetClutchFriction(), mEngine.GetCurrentRPM(), GetWheelSpeedAtClutch(), mConstraint.GetVehicleBody()->GetLinearVelocity().Length() * 3.6f);
  211. #endif // JPH_TRACE_VEHICLE_STATS
  212. for (Wheel *w_base : mConstraint.GetWheels())
  213. {
  214. WheelWV *w = static_cast<WheelWV *>(w_base);
  215. // Set steering angle
  216. w->SetSteerAngle(-mRightInput * w->GetSettings()->mMaxSteerAngle);
  217. }
  218. }
  219. void WheeledVehicleController::PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  220. {
  221. JPH_PROFILE_FUNCTION();
  222. // Remember old RPM so we can detect if we're increasing or decreasing
  223. float old_engine_rpm = mEngine.GetCurrentRPM();
  224. Wheels &wheels = mConstraint.GetWheels();
  225. // Update wheel angle, do this before applying torque to the wheels (as friction will slow them down again)
  226. for (uint wheel_index = 0, num_wheels = (uint)wheels.size(); wheel_index < num_wheels; ++wheel_index)
  227. {
  228. WheelWV *w = static_cast<WheelWV *>(wheels[wheel_index]);
  229. w->Update(wheel_index, inDeltaTime, mConstraint);
  230. }
  231. // In auto transmission mode, don't accelerate the engine when switching gears
  232. float forward_input = abs(mForwardInput);
  233. if (mTransmission.mMode == ETransmissionMode::Auto)
  234. forward_input *= mTransmission.GetClutchFriction();
  235. // Apply engine damping
  236. mEngine.ApplyDamping(inDeltaTime);
  237. // Calculate engine torque
  238. float engine_torque = mEngine.GetTorque(forward_input);
  239. // Define a struct that contains information about driven differentials (i.e. that have wheels connected)
  240. struct DrivenDifferential
  241. {
  242. const VehicleDifferentialSettings * mDifferential;
  243. float mAngularVelocity;
  244. float mClutchToDifferentialTorqueRatio;
  245. float mTempTorqueFactor;
  246. };
  247. // Collect driven differentials and their speeds
  248. Array<DrivenDifferential> driven_differentials;
  249. driven_differentials.reserve(mDifferentials.size());
  250. float differential_omega_min = FLT_MAX, differential_omega_max = 0.0f;
  251. for (const VehicleDifferentialSettings &d : mDifferentials)
  252. {
  253. float avg_omega = 0.0f;
  254. int avg_omega_denom = 0;
  255. int indices[] = { d.mLeftWheel, d.mRightWheel };
  256. for (int idx : indices)
  257. if (idx != -1)
  258. {
  259. avg_omega += wheels[idx]->GetAngularVelocity();
  260. avg_omega_denom++;
  261. }
  262. if (avg_omega_denom > 0)
  263. {
  264. avg_omega = abs(avg_omega * d.mDifferentialRatio / float(avg_omega_denom)); // ignoring that the differentials may be rotating in different directions
  265. driven_differentials.push_back({ &d, avg_omega, d.mEngineTorqueRatio, 0 });
  266. // Remember min and max velocity
  267. differential_omega_min = min(differential_omega_min, avg_omega);
  268. differential_omega_max = max(differential_omega_max, avg_omega);
  269. }
  270. }
  271. if (mDifferentialLimitedSlipRatio < FLT_MAX // Limited slip differential needs to be turned on
  272. && differential_omega_max > differential_omega_min) // There needs to be a velocity difference
  273. {
  274. // Calculate factor based on relative speed of a differential
  275. float sum_factor = 0.0f;
  276. for (DrivenDifferential &d : driven_differentials)
  277. {
  278. // Differential with max velocity gets factor 0, differential with min velocity 1
  279. d.mTempTorqueFactor = (differential_omega_max - d.mAngularVelocity) / (differential_omega_max - differential_omega_min);
  280. sum_factor += d.mTempTorqueFactor;
  281. }
  282. // Normalize the result
  283. for (DrivenDifferential &d : driven_differentials)
  284. d.mTempTorqueFactor /= sum_factor;
  285. // Prevent div by zero
  286. differential_omega_min = max(1.0e-3f, differential_omega_min);
  287. differential_omega_max = max(1.0e-3f, differential_omega_max);
  288. // Map into a value that is 0 when the wheels are turning at an equal rate and 1 when the wheels are turning at mDifferentialLimitedSlipRatio
  289. float alpha = min((differential_omega_max / differential_omega_min - 1.0f) / (mDifferentialLimitedSlipRatio - 1.0f), 1.0f);
  290. JPH_ASSERT(alpha >= 0.0f);
  291. float one_min_alpha = 1.0f - alpha;
  292. // Update torque ratio for all differentials
  293. for (DrivenDifferential &d : driven_differentials)
  294. d.mClutchToDifferentialTorqueRatio = one_min_alpha * d.mClutchToDifferentialTorqueRatio + alpha * d.mTempTorqueFactor;
  295. }
  296. #ifdef JPH_ENABLE_ASSERTS
  297. // Assert the values add up to 1
  298. float sum_torque_factors = 0.0f;
  299. for (DrivenDifferential &d : driven_differentials)
  300. sum_torque_factors += d.mClutchToDifferentialTorqueRatio;
  301. JPH_ASSERT(abs(sum_torque_factors - 1.0f) < 1.0e-6f);
  302. #endif // JPH_ENABLE_ASSERTS
  303. // Define a struct that collects information about the wheels that connect to the engine
  304. struct DrivenWheel
  305. {
  306. WheelWV * mWheel;
  307. float mClutchToWheelRatio;
  308. float mClutchToWheelTorqueRatio;
  309. float mEstimatedAngularImpulse;
  310. };
  311. Array<DrivenWheel> driven_wheels;
  312. driven_wheels.reserve(wheels.size());
  313. // Collect driven wheels
  314. float transmission_ratio = mTransmission.GetCurrentRatio();
  315. for (const DrivenDifferential &dd : driven_differentials)
  316. {
  317. VehicleDifferentialSettings d = *dd.mDifferential;
  318. WheelWV *wl = d.mLeftWheel != -1? static_cast<WheelWV *>(wheels[d.mLeftWheel]) : nullptr;
  319. WheelWV *wr = d.mRightWheel != -1? static_cast<WheelWV *>(wheels[d.mRightWheel]) : nullptr;
  320. float clutch_to_wheel_ratio = transmission_ratio * d.mDifferentialRatio;
  321. if (wl != nullptr && wr != nullptr)
  322. {
  323. // Calculate torque ratio
  324. float ratio_l, ratio_r;
  325. d.CalculateTorqueRatio(wl->GetAngularVelocity(), wr->GetAngularVelocity(), ratio_l, ratio_r);
  326. // Add both wheels
  327. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_l, 0.0f });
  328. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_r, 0.0f });
  329. }
  330. else if (wl != nullptr)
  331. {
  332. // Only left wheel, all power to left
  333. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio, 0.0f });
  334. }
  335. else if (wr != nullptr)
  336. {
  337. // Only right wheel, all power to right
  338. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio, 0.0f });
  339. }
  340. }
  341. bool solved = false;
  342. if (!driven_wheels.empty())
  343. {
  344. // Define the torque at the clutch at time t as:
  345. //
  346. // tc(t):=S*(we(t)-sum(R(j)*ww(j,t),j,1,N)/N)
  347. //
  348. // Where:
  349. // S is the total strength of clutch (= friction * strength)
  350. // we(t) is the engine angular velocity at time t
  351. // R(j) is the total gear ratio of clutch to wheel for wheel j
  352. // ww(j,t) is the angular velocity of wheel j at time t
  353. // N is the amount of wheels
  354. //
  355. // The torque that increases the engine angular velocity at time t is:
  356. //
  357. // te(t):=TE-tc(t)
  358. //
  359. // Where:
  360. // TE is the torque delivered by the engine
  361. //
  362. // The torque that increases the wheel angular velocity for wheel i at time t is:
  363. //
  364. // tw(i,t):=TW(i)+R(i)*F(i)*tc(t)
  365. //
  366. // Where:
  367. // TW(i) is the torque applied to the wheel outside of the engine (brake + torque due to friction with the ground)
  368. // F(i) is the fraction of the engine torque applied from engine to wheel i
  369. //
  370. // Because the angular acceleration and torque are connected through: Torque = I * dw/dt
  371. //
  372. // We have the angular acceleration of the engine at time t:
  373. //
  374. // ddt_we(t):=te(t)/Ie
  375. //
  376. // Where:
  377. // Ie is the inertia of the engine
  378. //
  379. // We have the angular acceleration of wheel i at time t:
  380. //
  381. // ddt_ww(i,t):=tw(i,t)/Iw(i)
  382. //
  383. // Where:
  384. // Iw(i) is the inertia of wheel i
  385. //
  386. // We could take a simple Euler step to calculate the resulting accelerations but because the system is very stiff this turns out to be unstable, so we need to use implicit Euler instead:
  387. //
  388. // we(t+dt)=we(t)+dt*ddt_we(t+dt)
  389. //
  390. // and:
  391. //
  392. // ww(i,t+dt)=ww(i,t)+dt*ddt_ww(i,t+dt)
  393. //
  394. // Expanding both equations (the equations above are in wxMaxima format and this can easily be done by expand(%)):
  395. //
  396. // For wheel:
  397. //
  398. // ww(i,t+dt) + (S*dt*F(i)*R(i)*sum(R(j)*ww(j,t+dt),j,1,N))/(N*Iw(i)) - (S*dt*F(i)*R(i)*we(t+dt))/Iw(i) = ww(i,t)+(dt*TW(i))/Iw(i)
  399. //
  400. // For engine:
  401. //
  402. // we(t+dt) + (S*dt*we(t+dt))/Ie - (S*dt*sum(R(j)*ww(j,t+dt),j,1,N))/(Ie*N) = we(t)+(TE*dt)/Ie
  403. //
  404. // Defining a vector w(t) = (ww(1, t), ww(2, t), ..., ww(N, t), we(t)) we can write both equations as a matrix multiplication:
  405. //
  406. // a * w(t + dt) = b
  407. //
  408. // We then invert the matrix to get the new angular velocities.
  409. // Dimension of matrix is N + 1
  410. int n = (int)driven_wheels.size() + 1;
  411. // Last column of w is for the engine angular velocity
  412. int engine = n - 1;
  413. // Define a and b
  414. DynMatrix a(n, n);
  415. DynMatrix b(n, 1);
  416. // Get number of driven wheels as a float
  417. float num_driven_wheels_float = float(driven_wheels.size());
  418. // Angular velocity of engine
  419. float w_engine = mEngine.GetAngularVelocity();
  420. // Calculate the total strength of the clutch
  421. float clutch_strength = transmission_ratio != 0.0f? mTransmission.GetClutchFriction() * mTransmission.mClutchStrength : 0.0f;
  422. // dt / Ie
  423. float dt_div_ie = inDeltaTime / mEngine.mInertia;
  424. // Calculate scale factor for impulses based on previous delta time
  425. float impulse_scale = mPreviousDeltaTime > 0.0f? inDeltaTime / mPreviousDeltaTime : 0.0f;
  426. // Iterate the rows for the wheels
  427. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  428. {
  429. DrivenWheel &w_i = driven_wheels[i];
  430. const WheelSettingsWV *settings = w_i.mWheel->GetSettings();
  431. // Get wheel inertia
  432. float inertia = settings->mInertia;
  433. // S * R(i)
  434. float s_r = clutch_strength * w_i.mClutchToWheelRatio;
  435. // dt * S * R(i) * F(i) / Iw
  436. float dt_s_r_f_div_iw = inDeltaTime * s_r * w_i.mClutchToWheelTorqueRatio / inertia;
  437. // Fill in the columns of a for wheel j
  438. for (int j = 0; j < (int)driven_wheels.size(); ++j)
  439. {
  440. const DrivenWheel &w_j = driven_wheels[j];
  441. a(i, j) = dt_s_r_f_div_iw * w_j.mClutchToWheelRatio / num_driven_wheels_float;
  442. }
  443. // Add ww(i, t+dt)
  444. a(i, i) += 1.0f;
  445. // Add the column for the engine
  446. a(i, engine) = -dt_s_r_f_div_iw;
  447. // Calculate external angular impulse operating on the wheel: TW(i) * dt
  448. float dt_tw = 0.0f;
  449. // Combine brake with hand brake torque
  450. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  451. if (brake_torque > 0.0f)
  452. {
  453. // We're braking
  454. // Calculate brake angular impulse
  455. float sign;
  456. if (w_i.mWheel->GetAngularVelocity() != 0.0f)
  457. sign = Sign(w_i.mWheel->GetAngularVelocity());
  458. else
  459. sign = Sign(mTransmission.GetCurrentRatio()); // When wheels have locked up use the transmission ratio to determine the sign
  460. dt_tw = sign * inDeltaTime * brake_torque;
  461. }
  462. if (w_i.mWheel->HasContact())
  463. {
  464. // We have wheel contact with the floor
  465. // Note that we don't know the torque due to the ground contact yet, so we use the impulse applied from the last frame to estimate it
  466. // Wheel torque TW = force * radius = lambda / dt * radius
  467. dt_tw += impulse_scale * w_i.mWheel->GetLongitudinalLambda() * settings->mRadius;
  468. }
  469. w_i.mEstimatedAngularImpulse = dt_tw;
  470. // Fill in the constant b = ww(i,t)+(dt*TW(i))/Iw(i)
  471. b(i, 0) = w_i.mWheel->GetAngularVelocity() - dt_tw / inertia;
  472. // To avoid looping over the wheels again, we also fill in the wheel columns of the engine row here
  473. a(engine, i) = -dt_div_ie * s_r / num_driven_wheels_float;
  474. }
  475. // Finalize the engine row
  476. a(engine, engine) = (1.0f + dt_div_ie * clutch_strength);
  477. b(engine, 0) = w_engine + dt_div_ie * engine_torque;
  478. // Solve the linear equation
  479. if (GaussianElimination(a, b))
  480. {
  481. // Update the angular velocities for the wheels
  482. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  483. {
  484. DrivenWheel &w_i = driven_wheels[i];
  485. const WheelSettingsWV *settings = w_i.mWheel->GetSettings();
  486. // Get solved wheel angular velocity
  487. float angular_velocity = b(i, 0);
  488. // We estimated TW and applied it in the equation above, but we haven't actually applied this torque yet so we undo it here.
  489. // It will be applied when we solve the actual braking / the constraints with the floor.
  490. angular_velocity += w_i.mEstimatedAngularImpulse / settings->mInertia;
  491. // Update angular velocity
  492. w_i.mWheel->SetAngularVelocity(angular_velocity);
  493. }
  494. // Update the engine RPM
  495. mEngine.SetCurrentRPM(b(engine, 0) * VehicleEngine::cAngularVelocityToRPM);
  496. // The speeds have been solved
  497. solved = true;
  498. }
  499. else
  500. {
  501. JPH_ASSERT(false, "New engine/wheel speeds could not be calculated!");
  502. }
  503. }
  504. if (!solved)
  505. {
  506. // Engine not connected to wheels, apply all torque to engine rotation
  507. mEngine.ApplyTorque(engine_torque, inDeltaTime);
  508. }
  509. // Calculate if any of the wheels are slipping, this is used to prevent gear switching
  510. bool wheels_slipping = false;
  511. for (const DrivenWheel &w : driven_wheels)
  512. wheels_slipping |= w.mClutchToWheelTorqueRatio > 0.0f && (!w.mWheel->HasContact() || w.mWheel->mLongitudinalSlip > 0.1f);
  513. // Only allow shifting up when we're not slipping and we're increasing our RPM.
  514. // After a jump, we have a very high engine RPM but once we hit the ground the RPM should be decreasing and we don't want to shift up
  515. // during that time.
  516. bool can_shift_up = !wheels_slipping && mEngine.GetCurrentRPM() >= old_engine_rpm;
  517. // Update transmission
  518. mTransmission.Update(inDeltaTime, mEngine.GetCurrentRPM(), mForwardInput, can_shift_up);
  519. // Braking
  520. for (Wheel *w_base : wheels)
  521. {
  522. WheelWV *w = static_cast<WheelWV *>(w_base);
  523. const WheelSettingsWV *settings = w->GetSettings();
  524. // Combine brake with hand brake torque
  525. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  526. if (brake_torque > 0.0f)
  527. {
  528. // Calculate how much torque is needed to stop the wheels from rotating in this time step
  529. float brake_torque_to_lock_wheels = abs(w->GetAngularVelocity()) * settings->mInertia / inDeltaTime;
  530. if (brake_torque > brake_torque_to_lock_wheels)
  531. {
  532. // Wheels are locked
  533. w->SetAngularVelocity(0.0f);
  534. w->mBrakeImpulse = (brake_torque - brake_torque_to_lock_wheels) * inDeltaTime / settings->mRadius;
  535. }
  536. else
  537. {
  538. // Slow down the wheels
  539. w->ApplyTorque(-Sign(w->GetAngularVelocity()) * brake_torque, inDeltaTime);
  540. w->mBrakeImpulse = 0.0f;
  541. }
  542. }
  543. else
  544. {
  545. // Not braking
  546. w->mBrakeImpulse = 0.0f;
  547. }
  548. }
  549. // Remember previous delta time so we can scale the impulses correctly
  550. mPreviousDeltaTime = inDeltaTime;
  551. }
  552. bool WheeledVehicleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  553. {
  554. bool impulse = false;
  555. float *max_lateral_friction_impulse = (float *)JPH_STACK_ALLOC(mConstraint.GetWheels().size() * sizeof(float));
  556. uint wheel_index = 0;
  557. for (Wheel *w_base : mConstraint.GetWheels())
  558. {
  559. if (w_base->HasContact())
  560. {
  561. WheelWV *w = static_cast<WheelWV *>(w_base);
  562. const WheelSettingsWV *settings = w->GetSettings();
  563. // Calculate max impulse that we can apply on the ground
  564. float max_longitudinal_friction_impulse;
  565. mTireMaxImpulseCallback(wheel_index,
  566. max_longitudinal_friction_impulse, max_lateral_friction_impulse[wheel_index], w->GetSuspensionLambda(),
  567. w->mCombinedLongitudinalFriction, w->mCombinedLateralFriction, w->mLongitudinalSlip, w->mLateralSlip, inDeltaTime);
  568. // Calculate relative velocity between wheel contact point and floor in longitudinal direction
  569. Vec3 relative_velocity = mConstraint.GetVehicleBody()->GetPointVelocity(w->GetContactPosition()) - w->GetContactPointVelocity();
  570. float relative_longitudinal_velocity = relative_velocity.Dot(w->GetContactLongitudinal());
  571. // Calculate brake force to apply
  572. float min_longitudinal_impulse, max_longitudinal_impulse;
  573. if (w->mBrakeImpulse != 0.0f)
  574. {
  575. // Limit brake force by max tire friction
  576. float brake_impulse = min(w->mBrakeImpulse, max_longitudinal_friction_impulse);
  577. // Check which direction the brakes should be applied (we don't want to apply an impulse that would accelerate the vehicle)
  578. if (relative_longitudinal_velocity >= 0.0f)
  579. {
  580. min_longitudinal_impulse = -brake_impulse;
  581. max_longitudinal_impulse = 0.0f;
  582. }
  583. else
  584. {
  585. min_longitudinal_impulse = 0.0f;
  586. max_longitudinal_impulse = brake_impulse;
  587. }
  588. // Longitudinal impulse, note that we assume that once the wheels are locked that the brakes have more than enough torque to keep the wheels locked so we exclude any rotation deltas
  589. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  590. }
  591. else
  592. {
  593. // Assume we want to apply an angular impulse that makes the delta velocity between wheel and ground zero in one time step, calculate the amount of linear impulse needed to do that
  594. float desired_angular_velocity = relative_longitudinal_velocity / settings->mRadius;
  595. float linear_impulse = (w->GetAngularVelocity() - desired_angular_velocity) * settings->mInertia / settings->mRadius;
  596. // Limit the impulse by max tire friction
  597. float prev_lambda = w->GetLongitudinalLambda();
  598. min_longitudinal_impulse = max_longitudinal_impulse = Clamp(prev_lambda + linear_impulse, -max_longitudinal_friction_impulse, max_longitudinal_friction_impulse);
  599. // Longitudinal impulse
  600. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  601. // Update the angular velocity of the wheels according to the lambda that was applied
  602. w->SetAngularVelocity(w->GetAngularVelocity() - (w->GetLongitudinalLambda() - prev_lambda) * settings->mRadius / settings->mInertia);
  603. }
  604. }
  605. ++wheel_index;
  606. }
  607. wheel_index = 0;
  608. for (Wheel *w_base : mConstraint.GetWheels())
  609. {
  610. if (w_base->HasContact())
  611. {
  612. WheelWV *w = static_cast<WheelWV *>(w_base);
  613. // Lateral friction
  614. float max_lateral_impulse = max_lateral_friction_impulse[wheel_index];
  615. impulse |= w->SolveLateralConstraintPart(mConstraint, -max_lateral_impulse, max_lateral_impulse);
  616. }
  617. ++wheel_index;
  618. }
  619. return impulse;
  620. }
  621. #ifdef JPH_DEBUG_RENDERER
  622. void WheeledVehicleController::Draw(DebugRenderer *inRenderer) const
  623. {
  624. float constraint_size = mConstraint.GetDrawConstraintSize();
  625. // Draw RPM
  626. Body *body = mConstraint.GetVehicleBody();
  627. Vec3 rpm_meter_up = body->GetRotation() * mConstraint.GetLocalUp();
  628. RVec3 rpm_meter_pos = body->GetPosition() + body->GetRotation() * mRPMMeterPosition;
  629. Vec3 rpm_meter_fwd = body->GetRotation() * mConstraint.GetLocalForward();
  630. mEngine.DrawRPM(inRenderer, rpm_meter_pos, rpm_meter_fwd, rpm_meter_up, mRPMMeterSize, mTransmission.mShiftDownRPM, mTransmission.mShiftUpRPM);
  631. if (mTransmission.GetCurrentRatio() != 0.0f)
  632. {
  633. // Calculate average wheel speed at clutch
  634. float wheel_speed_at_clutch = GetWheelSpeedAtClutch();
  635. // Draw the average wheel speed measured at clutch to compare engine RPM with wheel RPM
  636. inRenderer->DrawLine(rpm_meter_pos, rpm_meter_pos + Quat::sRotation(rpm_meter_fwd, mEngine.ConvertRPMToAngle(wheel_speed_at_clutch)) * (rpm_meter_up * 1.1f * mRPMMeterSize), Color::sYellow);
  637. }
  638. // Draw current vehicle state
  639. String status = StringFormat("Forward: %.1f, Right: %.1f\nBrake: %.1f, HandBrake: %.1f\n"
  640. "Gear: %d, Clutch: %.1f\nEngineRPM: %.0f, V: %.1f km/h",
  641. (double)mForwardInput, (double)mRightInput, (double)mBrakeInput, (double)mHandBrakeInput,
  642. mTransmission.GetCurrentGear(), (double)mTransmission.GetClutchFriction(), (double)mEngine.GetCurrentRPM(), (double)body->GetLinearVelocity().Length() * 3.6);
  643. inRenderer->DrawText3D(body->GetPosition(), status, Color::sWhite, constraint_size);
  644. RMat44 body_transform = body->GetWorldTransform();
  645. for (const Wheel *w_base : mConstraint.GetWheels())
  646. {
  647. const WheelWV *w = static_cast<const WheelWV *>(w_base);
  648. const WheelSettings *settings = w->GetSettings();
  649. // Calculate where the suspension attaches to the body in world space
  650. RVec3 ws_position = body_transform * settings->mPosition;
  651. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  652. // Draw suspension
  653. RVec3 min_suspension_pos = ws_position + ws_direction * settings->mSuspensionMinLength;
  654. RVec3 max_suspension_pos = ws_position + ws_direction * settings->mSuspensionMaxLength;
  655. inRenderer->DrawLine(ws_position, min_suspension_pos, Color::sRed);
  656. inRenderer->DrawLine(min_suspension_pos, max_suspension_pos, Color::sGreen);
  657. // Draw current length
  658. RVec3 wheel_pos = ws_position + ws_direction * w->GetSuspensionLength();
  659. inRenderer->DrawMarker(wheel_pos, w->GetSuspensionLength() < settings->mSuspensionMinLength? Color::sRed : Color::sGreen, constraint_size);
  660. // Draw wheel basis
  661. Vec3 wheel_forward, wheel_up, wheel_right;
  662. mConstraint.GetWheelLocalBasis(w, wheel_forward, wheel_up, wheel_right);
  663. wheel_forward = body_transform.Multiply3x3(wheel_forward);
  664. wheel_up = body_transform.Multiply3x3(wheel_up);
  665. wheel_right = body_transform.Multiply3x3(wheel_right);
  666. Vec3 steering_axis = body_transform.Multiply3x3(settings->mSteeringAxis);
  667. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_forward, Color::sRed);
  668. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_up, Color::sGreen);
  669. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_right, Color::sBlue);
  670. inRenderer->DrawLine(wheel_pos, wheel_pos + steering_axis, Color::sYellow);
  671. // Draw wheel
  672. RMat44 wheel_transform(Vec4(wheel_up, 0.0f), Vec4(wheel_right, 0.0f), Vec4(wheel_forward, 0.0f), wheel_pos);
  673. wheel_transform.SetRotation(wheel_transform.GetRotation() * Mat44::sRotationY(-w->GetRotationAngle()));
  674. inRenderer->DrawCylinder(wheel_transform, settings->mWidth * 0.5f, settings->mRadius, w->GetSuspensionLength() <= settings->mSuspensionMinLength? Color::sRed : Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  675. if (w->HasContact())
  676. {
  677. // Draw contact
  678. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactNormal(), Color::sYellow);
  679. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLongitudinal(), Color::sRed);
  680. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLateral(), Color::sBlue);
  681. DebugRenderer::sInstance->DrawText3D(wheel_pos, StringFormat("W: %.1f, S: %.2f\nSlipLateral: %.1f, SlipLong: %.2f\nFrLateral: %.1f, FrLong: %.1f", (double)w->GetAngularVelocity(), (double)w->GetSuspensionLength(), (double)RadiansToDegrees(w->mLateralSlip), (double)w->mLongitudinalSlip, (double)w->mCombinedLateralFriction, (double)w->mCombinedLongitudinalFriction), Color::sWhite, constraint_size);
  682. }
  683. else
  684. {
  685. // Draw 'no hit'
  686. DebugRenderer::sInstance->DrawText3D(wheel_pos, StringFormat("W: %.1f", (double)w->GetAngularVelocity()), Color::sRed, constraint_size);
  687. }
  688. }
  689. }
  690. #endif // JPH_DEBUG_RENDERER
  691. void WheeledVehicleController::SaveState(StateRecorder &inStream) const
  692. {
  693. inStream.Write(mForwardInput);
  694. inStream.Write(mRightInput);
  695. inStream.Write(mBrakeInput);
  696. inStream.Write(mHandBrakeInput);
  697. inStream.Write(mPreviousDeltaTime);
  698. mEngine.SaveState(inStream);
  699. mTransmission.SaveState(inStream);
  700. }
  701. void WheeledVehicleController::RestoreState(StateRecorder &inStream)
  702. {
  703. inStream.Read(mForwardInput);
  704. inStream.Read(mRightInput);
  705. inStream.Read(mBrakeInput);
  706. inStream.Read(mHandBrakeInput);
  707. inStream.Read(mPreviousDeltaTime);
  708. mEngine.RestoreState(inStream);
  709. mTransmission.RestoreState(inStream);
  710. }
  711. JPH_NAMESPACE_END