WheeledVehicleController.cpp 31 KB

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