WheeledVehicleController.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. && mEngine.GetCurrentRPM() <= 1.01f * mEngine.mMinRPM; // Engine is idling
  192. }
  193. void WheeledVehicleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  194. {
  195. JPH_PROFILE_FUNCTION();
  196. #ifdef JPH_TRACE_VEHICLE_STATS
  197. static bool sTracedHeader = false;
  198. if (!sTracedHeader)
  199. {
  200. Trace("Time, ForwardInput, Gear, ClutchFriction, EngineRPM, WheelRPM, Velocity (km/h)");
  201. sTracedHeader = true;
  202. }
  203. static float sTime = 0.0f;
  204. sTime += inDeltaTime;
  205. Trace("%.3f, %.1f, %d, %.1f, %.1f, %.1f, %.1f", sTime, mForwardInput, mTransmission.GetCurrentGear(), mTransmission.GetClutchFriction(), mEngine.GetCurrentRPM(), GetWheelSpeedAtClutch(), mConstraint.GetVehicleBody()->GetLinearVelocity().Length() * 3.6f);
  206. #endif // JPH_TRACE_VEHICLE_STATS
  207. for (Wheel *w_base : mConstraint.GetWheels())
  208. {
  209. WheelWV *w = static_cast<WheelWV *>(w_base);
  210. // Set steering angle
  211. w->SetSteerAngle(-mRightInput * w->GetSettings()->mMaxSteerAngle);
  212. }
  213. }
  214. void WheeledVehicleController::PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  215. {
  216. JPH_PROFILE_FUNCTION();
  217. // Remember old RPM so we're increasing or decreasing
  218. float old_engine_rpm = mEngine.GetCurrentRPM();
  219. Wheels &wheels = mConstraint.GetWheels();
  220. // Update wheel angle, do this before applying torque to the wheels (as friction will slow them down again)
  221. for (Wheel *w_base : wheels)
  222. {
  223. WheelWV *w = static_cast<WheelWV *>(w_base);
  224. w->Update(inDeltaTime, mConstraint);
  225. }
  226. // In auto transmission mode, don't accelerate the engine when switching gears
  227. float forward_input = abs(mForwardInput);
  228. if (mTransmission.mMode == ETransmissionMode::Auto)
  229. forward_input *= mTransmission.GetClutchFriction();
  230. // Apply damping if there is no acceleration
  231. if (forward_input < 1.0e-3f)
  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. };
  306. Array<DrivenWheel> driven_wheels;
  307. driven_wheels.reserve(wheels.size());
  308. // Collect driven wheels
  309. float transmission_ratio = mTransmission.GetCurrentRatio();
  310. for (const DrivenDifferential &dd : driven_differentials)
  311. {
  312. VehicleDifferentialSettings d = *dd.mDifferential;
  313. WheelWV *wl = d.mLeftWheel != -1? static_cast<WheelWV *>(wheels[d.mLeftWheel]) : nullptr;
  314. WheelWV *wr = d.mRightWheel != -1? static_cast<WheelWV *>(wheels[d.mRightWheel]) : nullptr;
  315. float clutch_to_wheel_ratio = transmission_ratio * d.mDifferentialRatio;
  316. if (wl != nullptr && wr != nullptr)
  317. {
  318. // Calculate torque ratio
  319. float ratio_l, ratio_r;
  320. d.CalculateTorqueRatio(wl->GetAngularVelocity(), wr->GetAngularVelocity(), ratio_l, ratio_r);
  321. // Add both wheels
  322. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_l });
  323. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio * ratio_r });
  324. }
  325. else if (wl != nullptr)
  326. {
  327. // Only left wheel, all power to left
  328. driven_wheels.push_back({ wl, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio });
  329. }
  330. else if (wr != nullptr)
  331. {
  332. // Only right wheel, all power to right
  333. driven_wheels.push_back({ wr, clutch_to_wheel_ratio, dd.mClutchToDifferentialTorqueRatio });
  334. }
  335. }
  336. bool solved = false;
  337. if (!driven_wheels.empty())
  338. {
  339. // Define the torque at the clutch at time t as:
  340. //
  341. // tc(t):=S*(we(t)-sum(R(j)*ww(j,t),j,1,N)/N)
  342. //
  343. // Where:
  344. // S is the total strength of clutch (= friction * strength)
  345. // we(t) is the engine angular velocity at time t
  346. // R(j) is the total gear ratio of clutch to wheel for wheel j
  347. // ww(j,t) is the angular velocity of wheel j at time t
  348. // N is the amount of wheels
  349. //
  350. // The torque that increases the engine angular velocity at time t is:
  351. //
  352. // te(t):=TE-tc(t)
  353. //
  354. // Where:
  355. // TE is the torque delivered by the engine
  356. //
  357. // The torque that increases the wheel angular velocity for wheel i at time t is:
  358. //
  359. // tw(i,t):=TW(i)+R(i)*F(i)*tc(t)
  360. //
  361. // Where:
  362. // TW(i) is the torque applied to the wheel outside of the engine (brake + torque due to friction with the ground)
  363. // F(i) is the fraction of the engine torque applied from engine to wheel i
  364. //
  365. // Because the angular accelaration and torque are connected through: Torque = I * dw/dt
  366. //
  367. // We have the angular acceleration of the engine at time t:
  368. //
  369. // ddt_we(t):=te(t)/Ie
  370. //
  371. // Where:
  372. // Ie is the inertia of the engine
  373. //
  374. // We have the angular acceleration of wheel i at time t:
  375. //
  376. // ddt_ww(i,t):=tw(i,t)/Iw(i)
  377. //
  378. // Where:
  379. // Iw(i) is the inertia of wheel i
  380. //
  381. // 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:
  382. //
  383. // we(t+dt)=we(t)+dt*ddt_we(t+dt)
  384. //
  385. // and:
  386. //
  387. // ww(i,t+dt)=ww(i,t)+dt*ddt_ww(i,t+dt)
  388. //
  389. // Expanding both equations (the equations above are in wxMaxima format and this can easily be done by expand(%)):
  390. //
  391. // For wheel:
  392. //
  393. // 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)
  394. //
  395. // For engine:
  396. //
  397. // 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
  398. //
  399. // 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:
  400. //
  401. // a * w(t + dt) = b
  402. //
  403. // We then invert the matrix to get the new angular velocities.
  404. //
  405. // Note that currently we set TW(i) = 0 so that the wheels will accelerate as if no external force was applied to them. These external forces are applied later and will slow down the wheel before the end of the time step.
  406. // Dimension of matrix is N + 1
  407. int n = (int)driven_wheels.size() + 1;
  408. // Last column of w is for the engine angular velocity
  409. int engine = n - 1;
  410. // Define a and b
  411. DynMatrix a(n, n);
  412. DynMatrix b(n, 1);
  413. // Get number of driven wheels as a float
  414. float num_driven_wheels_float = float(driven_wheels.size());
  415. // Angular velocity of engine
  416. float w_engine = mEngine.GetAngularVelocity();
  417. // Calculate the total strength of the clutch
  418. float clutch_strength = transmission_ratio != 0.0f? mTransmission.GetClutchFriction() * mTransmission.mClutchStrength : 0.0f;
  419. // dt / Ie
  420. float dt_div_ie = inDeltaTime / mEngine.mInertia;
  421. // Iterate the rows for the wheels
  422. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  423. {
  424. const DrivenWheel &w_i = driven_wheels[i];
  425. // dt / Iw
  426. float dt_div_iw = inDeltaTime / w_i.mWheel->GetSettings()->mInertia;
  427. // S * R(i)
  428. float s_r = clutch_strength * w_i.mClutchToWheelRatio;
  429. // dt * S * R(i) * F(i) / Iw
  430. float dt_s_r_f_div_iw = dt_div_iw * s_r * w_i.mClutchToWheelTorqueRatio;
  431. // Fill in the columns of a for wheel j
  432. for (int j = 0; j < (int)driven_wheels.size(); ++j)
  433. {
  434. const DrivenWheel &w_j = driven_wheels[j];
  435. a(i, j) = dt_s_r_f_div_iw * w_j.mClutchToWheelRatio / num_driven_wheels_float;
  436. }
  437. // Add ww(i, t+dt)
  438. a(i, i) += 1.0f;
  439. // Add the column for the engine
  440. a(i, engine) = -dt_s_r_f_div_iw;
  441. // Fill in the constant b
  442. b(i, 0) = w_i.mWheel->GetAngularVelocity(); // + dt_div_iw * (brake and tire torques)
  443. // To avoid looping over the wheels again, we also fill in the wheel columns of the engine row here
  444. a(engine, i) = -dt_div_ie * s_r / num_driven_wheels_float;
  445. }
  446. // Finalize the engine row
  447. a(engine, engine) = (1.0f + dt_div_ie * clutch_strength);
  448. b(engine, 0) = w_engine + dt_div_ie * engine_torque;
  449. // Solve the linear equation
  450. if (GaussianElimination(a, b))
  451. {
  452. // Update the angular velocities for the wheels
  453. for (int i = 0; i < (int)driven_wheels.size(); ++i)
  454. {
  455. DrivenWheel &dw1 = driven_wheels[i];
  456. dw1.mWheel->SetAngularVelocity(b(i, 0));
  457. }
  458. // Update the engine RPM
  459. mEngine.SetCurrentRPM(b(engine, 0) * VehicleEngine::cAngularVelocityToRPM);
  460. // The speeds have been solved
  461. solved = true;
  462. }
  463. else
  464. {
  465. JPH_ASSERT(false, "New engine/wheel speeds could not be calculated!");
  466. }
  467. }
  468. if (!solved)
  469. {
  470. // Engine not connected to wheels, apply all torque to engine rotation
  471. mEngine.ApplyTorque(engine_torque, inDeltaTime);
  472. }
  473. // Calculate if any of the wheels are slipping, this is used to prevent gear switching
  474. bool wheels_slipping = false;
  475. for (const DrivenWheel &w : driven_wheels)
  476. wheels_slipping |= w.mClutchToWheelTorqueRatio > 0.0f && (!w.mWheel->HasContact() || w.mWheel->mLongitudinalSlip > 0.1f);
  477. // Only allow shifting up when we're not slipping and we're increasing our RPM.
  478. // 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
  479. // during that time.
  480. bool can_shift_up = !wheels_slipping && mEngine.GetCurrentRPM() >= old_engine_rpm;
  481. // Update transmission
  482. mTransmission.Update(inDeltaTime, mEngine.GetCurrentRPM(), mForwardInput, can_shift_up);
  483. // Braking
  484. for (Wheel *w_base : wheels)
  485. {
  486. WheelWV *w = static_cast<WheelWV *>(w_base);
  487. const WheelSettingsWV *settings = w->GetSettings();
  488. // Combine brake with hand brake torque
  489. float brake_torque = mBrakeInput * settings->mMaxBrakeTorque + mHandBrakeInput * settings->mMaxHandBrakeTorque;
  490. if (brake_torque > 0.0f)
  491. {
  492. // Calculate how much torque is needed to stop the wheels from rotating in this time step
  493. float brake_torque_to_lock_wheels = abs(w->GetAngularVelocity()) * settings->mInertia / inDeltaTime;
  494. if (brake_torque > brake_torque_to_lock_wheels)
  495. {
  496. // Wheels are locked
  497. w->SetAngularVelocity(0.0f);
  498. w->mBrakeImpulse = (brake_torque - brake_torque_to_lock_wheels) * inDeltaTime / settings->mRadius;
  499. }
  500. else
  501. {
  502. // Slow down the wheels
  503. w->ApplyTorque(-Sign(w->GetAngularVelocity()) * brake_torque, inDeltaTime);
  504. w->mBrakeImpulse = 0.0f;
  505. }
  506. }
  507. else
  508. {
  509. // Not braking
  510. w->mBrakeImpulse = 0.0f;
  511. }
  512. }
  513. }
  514. bool WheeledVehicleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  515. {
  516. bool impulse = false;
  517. for (Wheel *w_base : mConstraint.GetWheels())
  518. if (w_base->HasContact())
  519. {
  520. WheelWV *w = static_cast<WheelWV *>(w_base);
  521. const WheelSettingsWV *settings = w->GetSettings();
  522. // Calculate max impulse that we can apply on the ground
  523. float max_longitudinal_friction_impulse = w->mCombinedLongitudinalFriction * w->GetSuspensionLambda();
  524. // Calculate relative velocity between wheel contact point and floor in longitudinal direction
  525. Vec3 relative_velocity = mConstraint.GetVehicleBody()->GetPointVelocity(w->GetContactPosition()) - w->GetContactPointVelocity();
  526. float relative_longitudinal_velocity = relative_velocity.Dot(w->GetContactLongitudinal());
  527. // Calculate brake force to apply
  528. float min_longitudinal_impulse, max_longitudinal_impulse;
  529. if (w->mBrakeImpulse != 0.0f)
  530. {
  531. // Limit brake force by max tire friction
  532. float brake_impulse = min(w->mBrakeImpulse, max_longitudinal_friction_impulse);
  533. // Check which direction the brakes should be applied (we don't want to apply an impulse that would accelerate the vehicle)
  534. if (relative_longitudinal_velocity >= 0.0f)
  535. {
  536. min_longitudinal_impulse = -brake_impulse;
  537. max_longitudinal_impulse = 0.0f;
  538. }
  539. else
  540. {
  541. min_longitudinal_impulse = 0.0f;
  542. max_longitudinal_impulse = brake_impulse;
  543. }
  544. // 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
  545. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  546. }
  547. else
  548. {
  549. // 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
  550. float desired_angular_velocity = relative_longitudinal_velocity / settings->mRadius;
  551. float linear_impulse = (w->GetAngularVelocity() - desired_angular_velocity) * settings->mInertia / settings->mRadius;
  552. // Limit the impulse by max tire friction
  553. min_longitudinal_impulse = max_longitudinal_impulse = w->GetLongitudinalLambda() + Sign(linear_impulse) * min(abs(linear_impulse), max_longitudinal_friction_impulse);
  554. // Longitudinal impulse
  555. float prev_lambda = w->GetLongitudinalLambda();
  556. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  557. // Update the angular velocity of the wheels according to the lambda that was applied
  558. w->SetAngularVelocity(w->GetAngularVelocity() - (w->GetLongitudinalLambda() - prev_lambda) * settings->mRadius / settings->mInertia);
  559. }
  560. }
  561. for (Wheel *w_base : mConstraint.GetWheels())
  562. if (w_base->HasContact())
  563. {
  564. WheelWV *w = static_cast<WheelWV *>(w_base);
  565. // Lateral friction
  566. float max_lateral_friction_impulse = w->mCombinedLateralFriction * w->GetSuspensionLambda();
  567. impulse |= w->SolveLateralConstraintPart(mConstraint, -max_lateral_friction_impulse, max_lateral_friction_impulse);
  568. }
  569. return impulse;
  570. }
  571. #ifdef JPH_DEBUG_RENDERER
  572. void WheeledVehicleController::Draw(DebugRenderer *inRenderer) const
  573. {
  574. float constraint_size = mConstraint.GetDrawConstraintSize();
  575. // Draw RPM
  576. Body *body = mConstraint.GetVehicleBody();
  577. Vec3 rpm_meter_up = body->GetRotation() * mConstraint.GetLocalUp();
  578. RVec3 rpm_meter_pos = body->GetPosition() + body->GetRotation() * mRPMMeterPosition;
  579. Vec3 rpm_meter_fwd = body->GetRotation() * mConstraint.GetLocalForward();
  580. mEngine.DrawRPM(inRenderer, rpm_meter_pos, rpm_meter_fwd, rpm_meter_up, mRPMMeterSize, mTransmission.mShiftDownRPM, mTransmission.mShiftUpRPM);
  581. // Calculate average wheel speed at clutch
  582. float wheel_speed_at_clutch = GetWheelSpeedAtClutch();
  583. // Draw the average wheel speed measured at clutch to compare engine RPM with wheel RPM
  584. 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);
  585. // Draw current vehicle state
  586. String status = StringFormat("Forward: %.1f, Right: %.1f\nBrake: %.1f, HandBrake: %.1f\n"
  587. "Gear: %d, Clutch: %.1f\nEngineRPM: %.0f, V: %.1f km/h",
  588. (double)mForwardInput, (double)mRightInput, (double)mBrakeInput, (double)mHandBrakeInput,
  589. mTransmission.GetCurrentGear(), (double)mTransmission.GetClutchFriction(), (double)mEngine.GetCurrentRPM(), (double)body->GetLinearVelocity().Length() * 3.6);
  590. inRenderer->DrawText3D(body->GetPosition(), status, Color::sWhite, constraint_size);
  591. RMat44 body_transform = body->GetWorldTransform();
  592. for (const Wheel *w_base : mConstraint.GetWheels())
  593. {
  594. const WheelWV *w = static_cast<const WheelWV *>(w_base);
  595. const WheelSettings *settings = w->GetSettings();
  596. // Calculate where the suspension attaches to the body in world space
  597. RVec3 ws_position = body_transform * settings->mPosition;
  598. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  599. // Draw suspension
  600. RVec3 min_suspension_pos = ws_position + ws_direction * settings->mSuspensionMinLength;
  601. RVec3 max_suspension_pos = ws_position + ws_direction * settings->mSuspensionMaxLength;
  602. inRenderer->DrawLine(ws_position, min_suspension_pos, Color::sRed);
  603. inRenderer->DrawLine(min_suspension_pos, max_suspension_pos, Color::sGreen);
  604. // Draw current length
  605. RVec3 wheel_pos = ws_position + ws_direction * w->GetSuspensionLength();
  606. inRenderer->DrawMarker(wheel_pos, w->GetSuspensionLength() < settings->mSuspensionMinLength? Color::sRed : Color::sGreen, constraint_size);
  607. // Draw wheel basis
  608. Vec3 wheel_forward, wheel_up, wheel_right;
  609. mConstraint.GetWheelLocalBasis(w, wheel_forward, wheel_up, wheel_right);
  610. wheel_forward = body_transform.Multiply3x3(wheel_forward);
  611. wheel_up = body_transform.Multiply3x3(wheel_up);
  612. wheel_right = body_transform.Multiply3x3(wheel_right);
  613. Vec3 steering_axis = body_transform.Multiply3x3(settings->mSteeringAxis);
  614. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_forward, Color::sRed);
  615. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_up, Color::sGreen);
  616. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_right, Color::sBlue);
  617. inRenderer->DrawLine(wheel_pos, wheel_pos + steering_axis, Color::sYellow);
  618. if (w->HasContact())
  619. {
  620. // Draw contact
  621. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactNormal(), Color::sYellow);
  622. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLongitudinal(), Color::sRed);
  623. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLateral(), Color::sBlue);
  624. 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);
  625. }
  626. else
  627. {
  628. // Draw 'no hit'
  629. DebugRenderer::sInstance->DrawText3D(wheel_pos, StringFormat("W: %.1f", (double)w->GetAngularVelocity()), Color::sRed, constraint_size);
  630. }
  631. }
  632. }
  633. #endif // JPH_DEBUG_RENDERER
  634. void WheeledVehicleController::SaveState(StateRecorder &inStream) const
  635. {
  636. inStream.Write(mForwardInput);
  637. inStream.Write(mRightInput);
  638. inStream.Write(mBrakeInput);
  639. inStream.Write(mHandBrakeInput);
  640. mEngine.SaveState(inStream);
  641. mTransmission.SaveState(inStream);
  642. }
  643. void WheeledVehicleController::RestoreState(StateRecorder &inStream)
  644. {
  645. inStream.Read(mForwardInput);
  646. inStream.Read(mRightInput);
  647. inStream.Read(mBrakeInput);
  648. inStream.Read(mHandBrakeInput);
  649. mEngine.RestoreState(inStream);
  650. mTransmission.RestoreState(inStream);
  651. }
  652. JPH_NAMESPACE_END