WheeledVehicleController.cpp 31 KB

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