TrackedVehicleController.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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/TrackedVehicleController.h>
  6. #include <Jolt/Physics/PhysicsSystem.h>
  7. #include <Jolt/ObjectStream/TypeDeclarations.h>
  8. #include <Jolt/Core/StreamIn.h>
  9. #include <Jolt/Core/StreamOut.h>
  10. #ifdef JPH_DEBUG_RENDERER
  11. #include <Jolt/Renderer/DebugRenderer.h>
  12. #endif // JPH_DEBUG_RENDERER
  13. JPH_NAMESPACE_BEGIN
  14. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(TrackedVehicleControllerSettings)
  15. {
  16. JPH_ADD_BASE_CLASS(TrackedVehicleControllerSettings, VehicleControllerSettings)
  17. JPH_ADD_ATTRIBUTE(TrackedVehicleControllerSettings, mEngine)
  18. JPH_ADD_ATTRIBUTE(TrackedVehicleControllerSettings, mTransmission)
  19. JPH_ADD_ATTRIBUTE(TrackedVehicleControllerSettings, mTracks)
  20. }
  21. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(WheelSettingsTV)
  22. {
  23. JPH_ADD_ATTRIBUTE(WheelSettingsTV, mLongitudinalFriction)
  24. JPH_ADD_ATTRIBUTE(WheelSettingsTV, mLateralFriction)
  25. }
  26. void WheelSettingsTV::SaveBinaryState(StreamOut &inStream) const
  27. {
  28. inStream.Write(mLongitudinalFriction);
  29. inStream.Write(mLateralFriction);
  30. }
  31. void WheelSettingsTV::RestoreBinaryState(StreamIn &inStream)
  32. {
  33. inStream.Read(mLongitudinalFriction);
  34. inStream.Read(mLateralFriction);
  35. }
  36. WheelTV::WheelTV(const WheelSettingsTV &inSettings) :
  37. Wheel(inSettings)
  38. {
  39. }
  40. void WheelTV::CalculateAngularVelocity(const VehicleConstraint &inConstraint)
  41. {
  42. const WheelSettingsTV *settings = GetSettings();
  43. const Wheels &wheels = inConstraint.GetWheels();
  44. const VehicleTrack &track = static_cast<const TrackedVehicleController *>(inConstraint.GetController())->GetTracks()[mTrackIndex];
  45. // Calculate angular velocity of this wheel
  46. mAngularVelocity = track.mAngularVelocity * wheels[track.mDrivenWheel]->GetSettings()->mRadius / settings->mRadius;
  47. }
  48. void WheelTV::Update(uint inWheelIndex, float inDeltaTime, const VehicleConstraint &inConstraint)
  49. {
  50. CalculateAngularVelocity(inConstraint);
  51. // Update rotation of wheel
  52. mAngle = fmod(mAngle + mAngularVelocity * inDeltaTime, 2.0f * JPH_PI);
  53. // Reset brake impulse, will be set during post collision again
  54. mBrakeImpulse = 0.0f;
  55. if (mContactBody != nullptr)
  56. {
  57. // Friction at the point of this wheel between track and floor
  58. const WheelSettingsTV *settings = GetSettings();
  59. VehicleConstraint::CombineFunction combine_friction = inConstraint.GetCombineFriction();
  60. mCombinedLongitudinalFriction = settings->mLongitudinalFriction;
  61. mCombinedLateralFriction = settings->mLateralFriction;
  62. combine_friction(inWheelIndex, mCombinedLongitudinalFriction, mCombinedLateralFriction, *mContactBody, mContactSubShapeID);
  63. }
  64. else
  65. {
  66. // No collision
  67. mCombinedLongitudinalFriction = mCombinedLateralFriction = 0.0f;
  68. }
  69. }
  70. VehicleController *TrackedVehicleControllerSettings::ConstructController(VehicleConstraint &inConstraint) const
  71. {
  72. return new TrackedVehicleController(*this, inConstraint);
  73. }
  74. TrackedVehicleControllerSettings::TrackedVehicleControllerSettings()
  75. {
  76. // Numbers guestimated from: https://en.wikipedia.org/wiki/M1_Abrams
  77. mEngine.mMinRPM = 500.0f;
  78. mEngine.mMaxRPM = 4000.0f;
  79. mEngine.mMaxTorque = 500.0f; // Note actual torque for M1 is around 5000 but we need a reduced mass in order to keep the simulation sane
  80. mTransmission.mShiftDownRPM = 1000.0f;
  81. mTransmission.mShiftUpRPM = 3500.0f;
  82. mTransmission.mGearRatios = { 4.0f, 3.0f, 2.0f, 1.0f };
  83. mTransmission.mReverseGearRatios = { -4.0f, -3.0f };
  84. }
  85. void TrackedVehicleControllerSettings::SaveBinaryState(StreamOut &inStream) const
  86. {
  87. mEngine.SaveBinaryState(inStream);
  88. mTransmission.SaveBinaryState(inStream);
  89. for (const VehicleTrackSettings &t : mTracks)
  90. t.SaveBinaryState(inStream);
  91. }
  92. void TrackedVehicleControllerSettings::RestoreBinaryState(StreamIn &inStream)
  93. {
  94. mEngine.RestoreBinaryState(inStream);
  95. mTransmission.RestoreBinaryState(inStream);
  96. for (VehicleTrackSettings &t : mTracks)
  97. t.RestoreBinaryState(inStream);
  98. }
  99. TrackedVehicleController::TrackedVehicleController(const TrackedVehicleControllerSettings &inSettings, VehicleConstraint &inConstraint) :
  100. VehicleController(inConstraint)
  101. {
  102. // Copy engine settings
  103. static_cast<VehicleEngineSettings &>(mEngine) = inSettings.mEngine;
  104. JPH_ASSERT(inSettings.mEngine.mMinRPM >= 0.0f);
  105. JPH_ASSERT(inSettings.mEngine.mMinRPM <= inSettings.mEngine.mMaxRPM);
  106. mEngine.SetCurrentRPM(mEngine.mMinRPM);
  107. // Copy transmission settings
  108. static_cast<VehicleTransmissionSettings &>(mTransmission) = inSettings.mTransmission;
  109. #ifdef JPH_ENABLE_ASSERTS
  110. for (float r : inSettings.mTransmission.mGearRatios)
  111. JPH_ASSERT(r > 0.0f);
  112. for (float r : inSettings.mTransmission.mReverseGearRatios)
  113. JPH_ASSERT(r < 0.0f);
  114. #endif // JPH_ENABLE_ASSERTS
  115. JPH_ASSERT(inSettings.mTransmission.mSwitchTime >= 0.0f);
  116. JPH_ASSERT(inSettings.mTransmission.mShiftDownRPM > 0.0f);
  117. JPH_ASSERT(inSettings.mTransmission.mMode != ETransmissionMode::Auto || inSettings.mTransmission.mShiftUpRPM < inSettings.mEngine.mMaxRPM);
  118. JPH_ASSERT(inSettings.mTransmission.mShiftUpRPM > inSettings.mTransmission.mShiftDownRPM);
  119. // Copy track settings
  120. for (uint i = 0; i < size(mTracks); ++i)
  121. {
  122. const VehicleTrackSettings &d = inSettings.mTracks[i];
  123. static_cast<VehicleTrackSettings &>(mTracks[i]) = d;
  124. JPH_ASSERT(d.mInertia >= 0.0f);
  125. JPH_ASSERT(d.mAngularDamping >= 0.0f);
  126. JPH_ASSERT(d.mMaxBrakeTorque >= 0.0f);
  127. JPH_ASSERT(d.mDifferentialRatio > 0.0f);
  128. }
  129. }
  130. bool TrackedVehicleController::AllowSleep() const
  131. {
  132. return mForwardInput == 0.0f // No user input
  133. && mTransmission.AllowSleep() // Transmission is not shifting
  134. && mEngine.AllowSleep(); // Engine is idling
  135. }
  136. void TrackedVehicleController::PreCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  137. {
  138. Wheels &wheels = mConstraint.GetWheels();
  139. // Fill in track index
  140. for (size_t t = 0; t < size(mTracks); ++t)
  141. for (uint w : mTracks[t].mWheels)
  142. static_cast<WheelTV *>(wheels[w])->mTrackIndex = (uint)t;
  143. // Angular damping: dw/dt = -c * w
  144. // Solution: w(t) = w(0) * e^(-c * t) or w2 = w1 * e^(-c * dt)
  145. // Taylor expansion of e^(-c * dt) = 1 - c * dt + ...
  146. // Since dt is usually in the order of 1/60 and c is a low number too this approximation is good enough
  147. for (VehicleTrack &t : mTracks)
  148. t.mAngularVelocity *= max(0.0f, 1.0f - t.mAngularDamping * inDeltaTime);
  149. }
  150. void TrackedVehicleController::SyncLeftRightTracks()
  151. {
  152. // Apply left to right ratio according to track inertias
  153. VehicleTrack &tl = mTracks[(int)ETrackSide::Left];
  154. VehicleTrack &tr = mTracks[(int)ETrackSide::Right];
  155. if (mLeftRatio * mRightRatio > 0.0f)
  156. {
  157. // Solve: (tl.mAngularVelocity + dl) / (tr.mAngularVelocity + dr) = mLeftRatio / mRightRatio and dl * tr.mInertia = -dr * tl.mInertia, where dl/dr are the delta angular velocities for left and right tracks
  158. float impulse = (mLeftRatio * tr.mAngularVelocity - mRightRatio * tl.mAngularVelocity) / (mLeftRatio * tr.mInertia + mRightRatio * tl.mInertia);
  159. tl.mAngularVelocity += impulse * tl.mInertia;
  160. tr.mAngularVelocity -= impulse * tr.mInertia;
  161. }
  162. else
  163. {
  164. // Solve: (tl.mAngularVelocity + dl) / (tr.mAngularVelocity + dr) = mLeftRatio / mRightRatio and dl * tr.mInertia = dr * tl.mInertia, where dl/dr are the delta angular velocities for left and right tracks
  165. float impulse = (mLeftRatio * tr.mAngularVelocity - mRightRatio * tl.mAngularVelocity) / (mRightRatio * tl.mInertia - mLeftRatio * tr.mInertia);
  166. tl.mAngularVelocity += impulse * tl.mInertia;
  167. tr.mAngularVelocity += impulse * tr.mInertia;
  168. }
  169. }
  170. void TrackedVehicleController::PostCollide(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  171. {
  172. JPH_PROFILE_FUNCTION();
  173. Wheels &wheels = mConstraint.GetWheels();
  174. // Update wheel angle, do this before applying torque to the wheels (as friction will slow them down again)
  175. for (uint wheel_index = 0, num_wheels = (uint)wheels.size(); wheel_index < num_wheels; ++wheel_index)
  176. {
  177. WheelTV *w = static_cast<WheelTV *>(wheels[wheel_index]);
  178. w->Update(wheel_index, inDeltaTime, mConstraint);
  179. }
  180. // First calculate engine speed based on speed of all wheels
  181. bool can_engine_apply_torque = false;
  182. if (mTransmission.GetCurrentGear() != 0 && mTransmission.GetClutchFriction() > 1.0e-3f)
  183. {
  184. float transmission_ratio = mTransmission.GetCurrentRatio();
  185. bool forward = transmission_ratio >= 0.0f;
  186. float fastest_wheel_speed = forward? -FLT_MAX : FLT_MAX;
  187. for (const VehicleTrack &t : mTracks)
  188. {
  189. if (forward)
  190. fastest_wheel_speed = max(fastest_wheel_speed, t.mAngularVelocity * t.mDifferentialRatio);
  191. else
  192. fastest_wheel_speed = min(fastest_wheel_speed, t.mAngularVelocity * t.mDifferentialRatio);
  193. for (uint w : t.mWheels)
  194. if (wheels[w]->HasContact())
  195. {
  196. can_engine_apply_torque = true;
  197. break;
  198. }
  199. }
  200. // Update RPM only if the tracks are connected to the engine
  201. if (fastest_wheel_speed > -FLT_MAX && fastest_wheel_speed < FLT_MAX)
  202. mEngine.SetCurrentRPM(fastest_wheel_speed * mTransmission.GetCurrentRatio() * VehicleEngine::cAngularVelocityToRPM);
  203. }
  204. else
  205. {
  206. // Update engine with damping
  207. mEngine.ApplyDamping(inDeltaTime);
  208. // In auto transmission mode, don't accelerate the engine when switching gears
  209. float forward_input = mTransmission.mMode == ETransmissionMode::Manual? abs(mForwardInput) : 0.0f;
  210. // Engine not connected to wheels, update RPM based on engine inertia alone
  211. mEngine.ApplyTorque(mEngine.GetTorque(forward_input), inDeltaTime);
  212. }
  213. // Update transmission
  214. // Note: only allow switching gears up when the tracks are rolling in the same direction
  215. mTransmission.Update(inDeltaTime, mEngine.GetCurrentRPM(), mForwardInput, mLeftRatio * mRightRatio > 0.0f && can_engine_apply_torque);
  216. // Calculate the amount of torque the transmission gives to the differentials
  217. float transmission_ratio = mTransmission.GetCurrentRatio();
  218. float transmission_torque = mTransmission.GetClutchFriction() * transmission_ratio * mEngine.GetTorque(abs(mForwardInput));
  219. if (transmission_torque != 0.0f)
  220. {
  221. // Apply the transmission torque to the wheels
  222. for (uint i = 0; i < size(mTracks); ++i)
  223. {
  224. VehicleTrack &t = mTracks[i];
  225. // Get wheel rotation ratio for this track
  226. float ratio = i == 0? mLeftRatio : mRightRatio;
  227. // Calculate the max angular velocity of the driven wheel of the track given current engine RPM
  228. // Note this adds 0.1% slop to avoid numerical accuracy issues
  229. float track_max_angular_velocity = mEngine.GetCurrentRPM() / (transmission_ratio * t.mDifferentialRatio * ratio * VehicleEngine::cAngularVelocityToRPM) * 1.001f;
  230. // Calculate torque on the driven wheel
  231. float differential_torque = t.mDifferentialRatio * ratio * transmission_torque;
  232. // Apply torque to driven wheel
  233. if (t.mAngularVelocity * track_max_angular_velocity < 0.0f || abs(t.mAngularVelocity) < abs(track_max_angular_velocity))
  234. t.mAngularVelocity += differential_torque * inDeltaTime / t.mInertia;
  235. }
  236. }
  237. // Ensure that we have the correct ratio between the two tracks
  238. SyncLeftRightTracks();
  239. // Braking
  240. for (VehicleTrack &t : mTracks)
  241. {
  242. // Calculate brake torque
  243. float brake_torque = mBrakeInput * t.mMaxBrakeTorque;
  244. if (brake_torque > 0.0f)
  245. {
  246. // Calculate how much torque is needed to stop the track from rotating in this time step
  247. float brake_torque_to_lock_track = abs(t.mAngularVelocity) * t.mInertia / inDeltaTime;
  248. if (brake_torque > brake_torque_to_lock_track)
  249. {
  250. // Wheels are locked
  251. t.mAngularVelocity = 0.0f;
  252. brake_torque -= brake_torque_to_lock_track;
  253. }
  254. else
  255. {
  256. // Slow down the track
  257. t.mAngularVelocity -= Sign(t.mAngularVelocity) * brake_torque * inDeltaTime / t.mInertia;
  258. }
  259. }
  260. if (brake_torque > 0.0f)
  261. {
  262. // Sum the radius of all wheels touching the floor
  263. float total_radius = 0.0f;
  264. for (uint wheel_index : t.mWheels)
  265. {
  266. const WheelTV *w = static_cast<WheelTV *>(wheels[wheel_index]);
  267. if (w->HasContact())
  268. total_radius += w->GetSettings()->mRadius;
  269. }
  270. if (total_radius > 0.0f)
  271. {
  272. brake_torque /= total_radius;
  273. for (uint wheel_index : t.mWheels)
  274. {
  275. WheelTV *w = static_cast<WheelTV *>(wheels[wheel_index]);
  276. if (w->HasContact())
  277. {
  278. // Impulse: p = F * dt = Torque / Wheel_Radius * dt, Torque = Total_Torque * Wheel_Radius / Summed_Radius => p = Total_Torque * dt / Summed_Radius
  279. w->mBrakeImpulse = brake_torque * inDeltaTime;
  280. }
  281. }
  282. }
  283. }
  284. }
  285. // Update wheel angular velocity based on that of the track
  286. for (Wheel *w_base : wheels)
  287. {
  288. WheelTV *w = static_cast<WheelTV *>(w_base);
  289. w->CalculateAngularVelocity(mConstraint);
  290. }
  291. }
  292. bool TrackedVehicleController::SolveLongitudinalAndLateralConstraints(float inDeltaTime)
  293. {
  294. bool impulse = false;
  295. for (Wheel *w_base : mConstraint.GetWheels())
  296. if (w_base->HasContact())
  297. {
  298. WheelTV *w = static_cast<WheelTV *>(w_base);
  299. const WheelSettingsTV *settings = w->GetSettings();
  300. VehicleTrack &track = mTracks[w->mTrackIndex];
  301. // Calculate max impulse that we can apply on the ground
  302. float max_longitudinal_friction_impulse = w->mCombinedLongitudinalFriction * w->GetSuspensionLambda();
  303. // Calculate relative velocity between wheel contact point and floor in longitudinal direction
  304. Vec3 relative_velocity = mConstraint.GetVehicleBody()->GetPointVelocity(w->GetContactPosition()) - w->GetContactPointVelocity();
  305. float relative_longitudinal_velocity = relative_velocity.Dot(w->GetContactLongitudinal());
  306. // Calculate brake force to apply
  307. float min_longitudinal_impulse, max_longitudinal_impulse;
  308. if (w->mBrakeImpulse != 0.0f)
  309. {
  310. // Limit brake force by max tire friction
  311. float brake_impulse = min(w->mBrakeImpulse, max_longitudinal_friction_impulse);
  312. // Check which direction the brakes should be applied (we don't want to apply an impulse that would accelerate the vehicle)
  313. if (relative_longitudinal_velocity >= 0.0f)
  314. {
  315. min_longitudinal_impulse = -brake_impulse;
  316. max_longitudinal_impulse = 0.0f;
  317. }
  318. else
  319. {
  320. min_longitudinal_impulse = 0.0f;
  321. max_longitudinal_impulse = brake_impulse;
  322. }
  323. // 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
  324. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  325. }
  326. else
  327. {
  328. // Assume we want to apply an angular impulse that makes the delta velocity between track and ground zero in one time step, calculate the amount of linear impulse needed to do that
  329. float desired_angular_velocity = relative_longitudinal_velocity / settings->mRadius;
  330. float linear_impulse = (track.mAngularVelocity - desired_angular_velocity) * track.mInertia / settings->mRadius;
  331. // Limit the impulse by max track friction
  332. float prev_lambda = w->GetLongitudinalLambda();
  333. min_longitudinal_impulse = max_longitudinal_impulse = Clamp(prev_lambda + linear_impulse, -max_longitudinal_friction_impulse, max_longitudinal_friction_impulse);
  334. // Longitudinal impulse
  335. impulse |= w->SolveLongitudinalConstraintPart(mConstraint, min_longitudinal_impulse, max_longitudinal_impulse);
  336. // Update the angular velocity of the track according to the lambda that was applied
  337. track.mAngularVelocity -= (w->GetLongitudinalLambda() - prev_lambda) * settings->mRadius / track.mInertia;
  338. SyncLeftRightTracks();
  339. }
  340. }
  341. for (Wheel *w_base : mConstraint.GetWheels())
  342. if (w_base->HasContact())
  343. {
  344. WheelTV *w = static_cast<WheelTV *>(w_base);
  345. // Update angular velocity of wheel for the next iteration
  346. w->CalculateAngularVelocity(mConstraint);
  347. // Lateral friction
  348. float max_lateral_friction_impulse = w->mCombinedLateralFriction * w->GetSuspensionLambda();
  349. impulse |= w->SolveLateralConstraintPart(mConstraint, -max_lateral_friction_impulse, max_lateral_friction_impulse);
  350. }
  351. return impulse;
  352. }
  353. #ifdef JPH_DEBUG_RENDERER
  354. void TrackedVehicleController::Draw(DebugRenderer *inRenderer) const
  355. {
  356. float constraint_size = mConstraint.GetDrawConstraintSize();
  357. // Draw RPM
  358. Body *body = mConstraint.GetVehicleBody();
  359. Vec3 rpm_meter_up = body->GetRotation() * mConstraint.GetLocalUp();
  360. RVec3 rpm_meter_pos = body->GetPosition() + body->GetRotation() * mRPMMeterPosition;
  361. Vec3 rpm_meter_fwd = body->GetRotation() * mConstraint.GetLocalForward();
  362. mEngine.DrawRPM(inRenderer, rpm_meter_pos, rpm_meter_fwd, rpm_meter_up, mRPMMeterSize, mTransmission.mShiftDownRPM, mTransmission.mShiftUpRPM);
  363. // Draw current vehicle state
  364. String status = StringFormat("Forward: %.1f, LRatio: %.1f, RRatio: %.1f, Brake: %.1f\n"
  365. "Gear: %d, Clutch: %.1f, EngineRPM: %.0f, V: %.1f km/h",
  366. (double)mForwardInput, (double)mLeftRatio, (double)mRightRatio, (double)mBrakeInput,
  367. mTransmission.GetCurrentGear(), (double)mTransmission.GetClutchFriction(), (double)mEngine.GetCurrentRPM(), (double)body->GetLinearVelocity().Length() * 3.6);
  368. inRenderer->DrawText3D(body->GetPosition(), status, Color::sWhite, constraint_size);
  369. for (const VehicleTrack &t : mTracks)
  370. {
  371. const WheelTV *w = static_cast<const WheelTV *>(mConstraint.GetWheels()[t.mDrivenWheel]);
  372. const WheelSettings *settings = w->GetSettings();
  373. // Calculate where the suspension attaches to the body in world space
  374. RVec3 ws_position = body->GetCenterOfMassPosition() + body->GetRotation() * (settings->mPosition - body->GetShape()->GetCenterOfMass());
  375. DebugRenderer::sInstance->DrawText3D(ws_position, StringFormat("W: %.1f", (double)t.mAngularVelocity), Color::sWhite, constraint_size);
  376. }
  377. RMat44 body_transform = body->GetWorldTransform();
  378. for (const Wheel *w_base : mConstraint.GetWheels())
  379. {
  380. const WheelTV *w = static_cast<const WheelTV *>(w_base);
  381. const WheelSettings *settings = w->GetSettings();
  382. // Calculate where the suspension attaches to the body in world space
  383. RVec3 ws_position = body_transform * settings->mPosition;
  384. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  385. // Draw suspension
  386. RVec3 min_suspension_pos = ws_position + ws_direction * settings->mSuspensionMinLength;
  387. RVec3 max_suspension_pos = ws_position + ws_direction * settings->mSuspensionMaxLength;
  388. inRenderer->DrawLine(ws_position, min_suspension_pos, Color::sRed);
  389. inRenderer->DrawLine(min_suspension_pos, max_suspension_pos, Color::sGreen);
  390. // Draw current length
  391. RVec3 wheel_pos = ws_position + ws_direction * w->GetSuspensionLength();
  392. inRenderer->DrawMarker(wheel_pos, w->GetSuspensionLength() < settings->mSuspensionMinLength? Color::sRed : Color::sGreen, constraint_size);
  393. // Draw wheel basis
  394. Vec3 wheel_forward, wheel_up, wheel_right;
  395. mConstraint.GetWheelLocalBasis(w, wheel_forward, wheel_up, wheel_right);
  396. wheel_forward = body_transform.Multiply3x3(wheel_forward);
  397. wheel_up = body_transform.Multiply3x3(wheel_up);
  398. wheel_right = body_transform.Multiply3x3(wheel_right);
  399. Vec3 steering_axis = body_transform.Multiply3x3(settings->mSteeringAxis);
  400. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_forward, Color::sRed);
  401. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_up, Color::sGreen);
  402. inRenderer->DrawLine(wheel_pos, wheel_pos + wheel_right, Color::sBlue);
  403. inRenderer->DrawLine(wheel_pos, wheel_pos + steering_axis, Color::sYellow);
  404. // Draw wheel
  405. RMat44 wheel_transform(Vec4(wheel_up, 0.0f), Vec4(wheel_right, 0.0f), Vec4(wheel_forward, 0.0f), wheel_pos);
  406. wheel_transform.SetRotation(wheel_transform.GetRotation() * Mat44::sRotationY(-w->GetRotationAngle()));
  407. inRenderer->DrawCylinder(wheel_transform, settings->mWidth * 0.5f, settings->mRadius, w->GetSuspensionLength() <= settings->mSuspensionMinLength? Color::sRed : Color::sGreen, DebugRenderer::ECastShadow::Off, DebugRenderer::EDrawMode::Wireframe);
  408. if (w->HasContact())
  409. {
  410. // Draw contact
  411. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactNormal(), Color::sYellow);
  412. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLongitudinal(), Color::sRed);
  413. inRenderer->DrawLine(w->GetContactPosition(), w->GetContactPosition() + w->GetContactLateral(), Color::sBlue);
  414. DebugRenderer::sInstance->DrawText3D(w->GetContactPosition(), StringFormat("S: %.2f", (double)w->GetSuspensionLength()), Color::sWhite, constraint_size);
  415. }
  416. }
  417. }
  418. #endif // JPH_DEBUG_RENDERER
  419. void TrackedVehicleController::SaveState(StateRecorder &inStream) const
  420. {
  421. inStream.Write(mForwardInput);
  422. inStream.Write(mLeftRatio);
  423. inStream.Write(mRightRatio);
  424. inStream.Write(mBrakeInput);
  425. mEngine.SaveState(inStream);
  426. mTransmission.SaveState(inStream);
  427. for (const VehicleTrack &t : mTracks)
  428. t.SaveState(inStream);
  429. }
  430. void TrackedVehicleController::RestoreState(StateRecorder &inStream)
  431. {
  432. inStream.Read(mForwardInput);
  433. inStream.Read(mLeftRatio);
  434. inStream.Read(mRightRatio);
  435. inStream.Read(mBrakeInput);
  436. mEngine.RestoreState(inStream);
  437. mTransmission.RestoreState(inStream);
  438. for (VehicleTrack &t : mTracks)
  439. t.RestoreState(inStream);
  440. }
  441. JPH_NAMESPACE_END