VehicleConstraint.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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/VehicleConstraint.h>
  6. #include <Jolt/Physics/Vehicle/VehicleController.h>
  7. #include <Jolt/Physics/PhysicsSystem.h>
  8. #include <Jolt/ObjectStream/TypeDeclarations.h>
  9. #include <Jolt/Core/StreamIn.h>
  10. #include <Jolt/Core/StreamOut.h>
  11. #include <Jolt/Core/Factory.h>
  12. JPH_NAMESPACE_BEGIN
  13. JPH_IMPLEMENT_SERIALIZABLE_VIRTUAL(VehicleConstraintSettings)
  14. {
  15. JPH_ADD_BASE_CLASS(VehicleConstraintSettings, ConstraintSettings)
  16. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mUp)
  17. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mForward)
  18. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mMaxPitchRollAngle)
  19. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mWheels)
  20. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mAntiRollBars)
  21. JPH_ADD_ATTRIBUTE(VehicleConstraintSettings, mController)
  22. }
  23. void VehicleConstraintSettings::SaveBinaryState(StreamOut &inStream) const
  24. {
  25. ConstraintSettings::SaveBinaryState(inStream);
  26. inStream.Write(mUp);
  27. inStream.Write(mForward);
  28. inStream.Write(mMaxPitchRollAngle);
  29. uint32 num_anti_rollbars = (uint32)mAntiRollBars.size();
  30. inStream.Write(num_anti_rollbars);
  31. for (const VehicleAntiRollBar &r : mAntiRollBars)
  32. r.SaveBinaryState(inStream);
  33. uint32 num_wheels = (uint32)mWheels.size();
  34. inStream.Write(num_wheels);
  35. for (const WheelSettings *w : mWheels)
  36. w->SaveBinaryState(inStream);
  37. inStream.Write(mController->GetRTTI()->GetHash());
  38. mController->SaveBinaryState(inStream);
  39. }
  40. void VehicleConstraintSettings::RestoreBinaryState(StreamIn &inStream)
  41. {
  42. ConstraintSettings::RestoreBinaryState(inStream);
  43. inStream.Read(mUp);
  44. inStream.Read(mForward);
  45. inStream.Read(mMaxPitchRollAngle);
  46. uint32 num_anti_rollbars = 0;
  47. inStream.Read(num_anti_rollbars);
  48. mAntiRollBars.resize(num_anti_rollbars);
  49. for (VehicleAntiRollBar &r : mAntiRollBars)
  50. r.RestoreBinaryState(inStream);
  51. uint32 num_wheels = 0;
  52. inStream.Read(num_wheels);
  53. mWheels.resize(num_wheels);
  54. for (WheelSettings *w : mWheels)
  55. w->RestoreBinaryState(inStream);
  56. uint32 hash = 0;
  57. inStream.Read(hash);
  58. const RTTI *rtti = Factory::sInstance->Find(hash);
  59. mController = reinterpret_cast<VehicleControllerSettings *>(rtti->CreateObject());
  60. mController->RestoreBinaryState(inStream);
  61. }
  62. VehicleConstraint::VehicleConstraint(Body &inVehicleBody, const VehicleConstraintSettings &inSettings) :
  63. Constraint(inSettings)
  64. {
  65. // Check sanity of incoming settings
  66. JPH_ASSERT(inSettings.mForward.IsNormalized());
  67. JPH_ASSERT(inSettings.mUp.IsNormalized());
  68. JPH_ASSERT(!inSettings.mWheels.empty());
  69. // Store general properties
  70. mBody = &inVehicleBody;
  71. mUp = inSettings.mUp;
  72. mForward = inSettings.mForward;
  73. SetMaxPitchRollAngle(inSettings.mMaxPitchRollAngle);
  74. // Copy anti-rollbar settings
  75. mAntiRollBars.resize(inSettings.mAntiRollBars.size());
  76. for (uint i = 0; i < mAntiRollBars.size(); ++i)
  77. {
  78. const VehicleAntiRollBar &r = inSettings.mAntiRollBars[i];
  79. mAntiRollBars[i] = r;
  80. JPH_ASSERT(r.mStiffness >= 0.0f);
  81. }
  82. // Construct our controler class
  83. mController = inSettings.mController->ConstructController(*this);
  84. // Create wheels
  85. mWheels.resize(inSettings.mWheels.size());
  86. for (uint i = 0; i < mWheels.size(); ++i)
  87. mWheels[i] = mController->ConstructWheel(*inSettings.mWheels[i]);
  88. }
  89. VehicleConstraint::~VehicleConstraint()
  90. {
  91. // Destroy controller
  92. delete mController;
  93. // Destroy our wheels
  94. for (Wheel *w : mWheels)
  95. delete w;
  96. }
  97. void VehicleConstraint::GetWheelLocalBasis(const Wheel *inWheel, Vec3 &outForward, Vec3 &outUp, Vec3 &outRight) const
  98. {
  99. const WheelSettings *settings = inWheel->mSettings;
  100. Quat steer_rotation = Quat::sRotation(settings->mSteeringAxis, inWheel->mSteerAngle);
  101. outUp = steer_rotation * settings->mWheelUp;
  102. outForward = steer_rotation * settings->mWheelForward;
  103. outRight = outForward.Cross(outUp).Normalized();
  104. outForward = outUp.Cross(outRight).Normalized();
  105. }
  106. Mat44 VehicleConstraint::GetWheelLocalTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const
  107. {
  108. JPH_ASSERT(inWheelIndex < mWheels.size());
  109. const Wheel *wheel = mWheels[inWheelIndex];
  110. const WheelSettings *settings = wheel->mSettings;
  111. // Use the two vectors provided to calculate a matrix that takes us from wheel model space to X = right, Y = up, Z = forward (the space where we will rotate the wheel)
  112. Mat44 wheel_to_rotational = Mat44(Vec4(inWheelRight, 0), Vec4(inWheelUp, 0), Vec4(inWheelUp.Cross(inWheelRight), 0), Vec4(0, 0, 0, 1)).Transposed();
  113. // Calculate the matrix that takes us from the rotational space to vehicle local space
  114. Vec3 local_forward, local_up, local_right;
  115. GetWheelLocalBasis(wheel, local_forward, local_up, local_right);
  116. Vec3 local_wheel_pos = settings->mPosition + settings->mSuspensionDirection * wheel->mSuspensionLength;
  117. Mat44 rotational_to_local(Vec4(local_right, 0), Vec4(local_up, 0), Vec4(local_forward, 0), Vec4(local_wheel_pos, 1));
  118. // Calculate transform of rotated wheel
  119. return rotational_to_local * Mat44::sRotationX(wheel->mAngle) * wheel_to_rotational;
  120. }
  121. RMat44 VehicleConstraint::GetWheelWorldTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const
  122. {
  123. return mBody->GetWorldTransform() * GetWheelLocalTransform(inWheelIndex, inWheelRight, inWheelUp);
  124. }
  125. void VehicleConstraint::OnStep(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  126. {
  127. JPH_PROFILE_FUNCTION();
  128. // Callback on our controller
  129. mController->PreCollide(inDeltaTime, inPhysicsSystem);
  130. // Calculate if this constraint is active by checking if our main vehicle body is active or any of the bodies we touch are active
  131. mIsActive = mBody->IsActive();
  132. RMat44 body_transform = mBody->GetWorldTransform();
  133. // Test collision for wheels
  134. for (uint wheel_index = 0; wheel_index < mWheels.size(); ++wheel_index)
  135. {
  136. Wheel *w = mWheels[wheel_index];
  137. const WheelSettings *settings = w->mSettings;
  138. // Reset contact
  139. w->mContactBodyID = BodyID();
  140. w->mContactBody = nullptr;
  141. w->mContactSubShapeID = SubShapeID();
  142. w->mSuspensionLength = settings->mSuspensionMaxLength;
  143. // Test collision to find the floor
  144. RVec3 ws_origin = body_transform * settings->mPosition;
  145. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  146. if (mVehicleCollisionTester->Collide(inPhysicsSystem, *this, wheel_index, ws_origin, ws_direction, mBody->GetID(), w->mContactBody, w->mContactSubShapeID, w->mContactPosition, w->mContactNormal, w->mSuspensionLength))
  147. {
  148. // Store ID (pointer is not valid outside of the simulation step)
  149. w->mContactBodyID = w->mContactBody->GetID();
  150. // Store contact velocity, cache this as the contact body may be removed
  151. w->mContactPointVelocity = w->mContactBody->GetPointVelocity(w->mContactPosition);
  152. // Determine plane constant for axle contact plane
  153. w->mAxlePlaneConstant = RVec3(w->mContactNormal).Dot(ws_origin + w->mSuspensionLength * ws_direction);
  154. // Check if body is active, if so the entire vehicle should be active
  155. mIsActive |= w->mContactBody->IsActive();
  156. // Determine world space forward using steering angle and body rotation
  157. Vec3 forward, up, right;
  158. GetWheelLocalBasis(w, forward, up, right);
  159. forward = body_transform.Multiply3x3(forward);
  160. right = body_transform.Multiply3x3(right);
  161. // The longitudinal axis is in the up/forward plane
  162. w->mContactLongitudinal = w->mContactNormal.Cross(right);
  163. // Make sure that the longitudinal axis is aligned with the forward axis
  164. if (w->mContactLongitudinal.Dot(forward) < 0.0f)
  165. w->mContactLongitudinal = -w->mContactLongitudinal;
  166. // Normalize it
  167. w->mContactLongitudinal = w->mContactLongitudinal.NormalizedOr(w->mContactNormal.GetNormalizedPerpendicular());
  168. // The lateral axis is perpendicular to contact normal and longitudinal axis
  169. w->mContactLateral = w->mContactLongitudinal.Cross(w->mContactNormal).Normalized();
  170. }
  171. }
  172. // Calculate anti-rollbar impulses
  173. for (const VehicleAntiRollBar &r : mAntiRollBars)
  174. {
  175. Wheel *lw = mWheels[r.mLeftWheel];
  176. Wheel *rw = mWheels[r.mRightWheel];
  177. if (lw->mContactBody != nullptr && rw->mContactBody != nullptr)
  178. {
  179. // Calculate the impulse to apply based on the difference in suspension length
  180. float difference = rw->mSuspensionLength - lw->mSuspensionLength;
  181. float impulse = difference * r.mStiffness * inDeltaTime;
  182. lw->mAntiRollBarImpulse = -impulse;
  183. rw->mAntiRollBarImpulse = impulse;
  184. }
  185. else
  186. {
  187. // When one of the wheels is not on the ground we don't apply any impulses
  188. lw->mAntiRollBarImpulse = rw->mAntiRollBarImpulse = 0.0f;
  189. }
  190. }
  191. // Callback on our controller
  192. mController->PostCollide(inDeltaTime, inPhysicsSystem);
  193. // If the wheels are rotating, we don't want to go to sleep yet
  194. bool allow_sleep = mController->AllowSleep();
  195. if (allow_sleep)
  196. for (const Wheel *w : mWheels)
  197. if (abs(w->mAngularVelocity) > DegreesToRadians(10.0f))
  198. {
  199. allow_sleep = false;
  200. break;
  201. }
  202. if (mBody->GetAllowSleeping() != allow_sleep)
  203. mBody->SetAllowSleeping(allow_sleep);
  204. }
  205. void VehicleConstraint::BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager)
  206. {
  207. // Find dynamic bodies that our wheels are touching
  208. BodyID *body_ids = (BodyID *)JPH_STACK_ALLOC((mWheels.size() + 1) * sizeof(BodyID));
  209. int num_bodies = 0;
  210. bool needs_to_activate = false;
  211. for (const Wheel *w : mWheels)
  212. if (w->mContactBody != nullptr)
  213. {
  214. // Avoid adding duplicates
  215. bool duplicate = false;
  216. BodyID id = w->mContactBody->GetID();
  217. for (int i = 0; i < num_bodies; ++i)
  218. if (body_ids[i] == id)
  219. {
  220. duplicate = true;
  221. break;
  222. }
  223. if (duplicate)
  224. continue;
  225. if (w->mContactBody->IsDynamic())
  226. {
  227. body_ids[num_bodies++] = id;
  228. needs_to_activate |= !w->mContactBody->IsActive();
  229. }
  230. }
  231. // Activate bodies, note that if we get here we have already told the system that we're active so that means our main body needs to be active too
  232. if (!mBody->IsActive())
  233. {
  234. // Our main body is not active, activate it too
  235. body_ids[num_bodies] = mBody->GetID();
  236. inBodyManager.ActivateBodies(body_ids, num_bodies + 1);
  237. }
  238. else if (needs_to_activate)
  239. {
  240. // Only activate bodies the wheels are touching
  241. inBodyManager.ActivateBodies(body_ids, num_bodies);
  242. }
  243. // Link the bodies into the same island
  244. uint32 min_active_index = Body::cInactiveIndex;
  245. for (int i = 0; i < num_bodies; ++i)
  246. {
  247. const Body &body = inBodyManager.GetBody(body_ids[i]);
  248. min_active_index = min(min_active_index, body.GetIndexInActiveBodiesInternal());
  249. ioBuilder.LinkBodies(mBody->GetIndexInActiveBodiesInternal(), body.GetIndexInActiveBodiesInternal());
  250. }
  251. // Link the constraint in the island
  252. ioBuilder.LinkConstraint(inConstraintIndex, mBody->GetIndexInActiveBodiesInternal(), min_active_index);
  253. }
  254. uint VehicleConstraint::BuildIslandSplits(LargeIslandSplitter &ioSplitter) const
  255. {
  256. return ioSplitter.AssignToNonParallelSplit(mBody);
  257. }
  258. void VehicleConstraint::CalculateWheelContactPoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const
  259. {
  260. outR1PlusU = Vec3(inWheel.mContactPosition - mBody->GetCenterOfMassPosition());
  261. outR2 = Vec3(inWheel.mContactPosition - inWheel.mContactBody->GetCenterOfMassPosition());
  262. }
  263. void VehicleConstraint::CalculatePitchRollConstraintProperties(float inDeltaTime, RMat44Arg inBodyTransform)
  264. {
  265. // Check if a limit was specified
  266. if (mCosMaxPitchRollAngle < JPH_PI)
  267. {
  268. // Calculate cos of angle between world up vector and vehicle up vector
  269. Vec3 vehicle_up = inBodyTransform.Multiply3x3(mUp);
  270. mCosPitchRollAngle = mUp.Dot(vehicle_up);
  271. if (mCosPitchRollAngle < mCosMaxPitchRollAngle)
  272. {
  273. // Calculate rotation axis to rotate vehicle towards up
  274. Vec3 rotation_axis = mUp.Cross(vehicle_up);
  275. float len = rotation_axis.Length();
  276. if (len > 0.0f)
  277. mPitchRollRotationAxis = rotation_axis / len;
  278. mPitchRollPart.CalculateConstraintProperties(inDeltaTime, *mBody, Body::sFixedToWorld, mPitchRollRotationAxis);
  279. }
  280. else
  281. mPitchRollPart.Deactivate();
  282. }
  283. else
  284. mPitchRollPart.Deactivate();
  285. }
  286. void VehicleConstraint::SetupVelocityConstraint(float inDeltaTime)
  287. {
  288. RMat44 body_transform = mBody->GetWorldTransform();
  289. for (Wheel *w : mWheels)
  290. if (w->mContactBody != nullptr)
  291. {
  292. const WheelSettings *settings = w->mSettings;
  293. Vec3 neg_contact_normal = -w->mContactNormal;
  294. Vec3 r1_plus_u, r2;
  295. CalculateWheelContactPoint(*w, r1_plus_u, r2);
  296. // Suspension spring
  297. if (settings->mSuspensionMaxLength > settings->mSuspensionMinLength)
  298. {
  299. // Calculate the damping and frequency of the suspension spring given the angle between the suspension direction and the contact normal
  300. // If the angle between the suspension direction and the inverse of the contact normal is alpha then the force on the spring relates to the force along the contact normal as:
  301. //
  302. // Fspring = Fnormal * cos(alpha)
  303. //
  304. // The spring force is:
  305. //
  306. // Fspring = -k * x
  307. //
  308. // where k is the spring constant and x is the displacement of the spring. So we have:
  309. //
  310. // Fnormal * cos(alpha) = -k * x <=> Fnormal = -k / cos(alpha) * x
  311. //
  312. // So we can see this as a spring with spring constant:
  313. //
  314. // k' = k / cos(alpha)
  315. //
  316. // In the same way the velocity relates like:
  317. //
  318. // Vspring = Vnormal * cos(alpha)
  319. //
  320. // Which results in the modified damping constant c:
  321. //
  322. // c' = c / cos(alpha)
  323. //
  324. // Since we're not supplying k and c directly but rather the frequency and damping we can calculate the spring constant and damping constant as:
  325. //
  326. // w = 2 * pi * f
  327. // k = m * w^2
  328. // c = 2 * m * w * d
  329. //
  330. // where m is the mass of the spring, f is the frequency and d is the damping factor (see SpringPart::CalculateSpringProperties). So we have:
  331. //
  332. // w' = w * pi * f'
  333. // k' = m * w'^2
  334. // c' = 2 * m * w' * d'
  335. //
  336. // where f' = f / sqrt(cos(alpha)) and d' = d / sqrt(cos(alpha))
  337. //
  338. // Note that we clamp 1 / cos(alpha) to the range [0.1, 1] in order not to increase the stiffness / damping by too much.
  339. // We also ensure that the frequency doesn't go over half the simulation frequency to prevent the spring from getting unstable.
  340. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  341. float sqrt_cos_angle = sqrt(max(0.1f, ws_direction.Dot(neg_contact_normal)));
  342. float damping = settings->mSuspensionDamping / sqrt_cos_angle;
  343. float frequency = min(0.5f / inDeltaTime, settings->mSuspensionFrequency / sqrt_cos_angle);
  344. // Get the value of the constraint equation
  345. float c = w->mSuspensionLength - settings->mSuspensionMaxLength - settings->mSuspensionPreloadLength;
  346. w->mSuspensionPart.CalculateConstraintProperties(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal, w->mAntiRollBarImpulse, c, frequency, damping);
  347. }
  348. else
  349. w->mSuspensionPart.Deactivate();
  350. // Check if we reached the 'max up' position and if so add a hard velocity constraint that stops any further movement in the normal direction
  351. if (w->mSuspensionLength < settings->mSuspensionMinLength)
  352. w->mSuspensionMaxUpPart.CalculateConstraintProperties(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  353. else
  354. w->mSuspensionMaxUpPart.Deactivate();
  355. // Friction and propulsion
  356. w->mLongitudinalPart.CalculateConstraintProperties(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLongitudinal, 0.0f, 0.0f, 0.0f, 0.0f);
  357. w->mLateralPart.CalculateConstraintProperties(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLateral, 0.0f, 0.0f, 0.0f, 0.0f);
  358. }
  359. else
  360. {
  361. // No contact -> disable everything
  362. w->mSuspensionPart.Deactivate();
  363. w->mSuspensionMaxUpPart.Deactivate();
  364. w->mLongitudinalPart.Deactivate();
  365. w->mLateralPart.Deactivate();
  366. }
  367. CalculatePitchRollConstraintProperties(inDeltaTime, body_transform);
  368. }
  369. void VehicleConstraint::WarmStartVelocityConstraint(float inWarmStartImpulseRatio)
  370. {
  371. for (Wheel *w : mWheels)
  372. if (w->mContactBody != nullptr)
  373. {
  374. Vec3 neg_contact_normal = -w->mContactNormal;
  375. w->mSuspensionPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  376. w->mSuspensionMaxUpPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  377. w->mLongitudinalPart.WarmStart(*mBody, *w->mContactBody, -w->mContactLongitudinal, 0.0f); // Don't warm start the longitudinal part (the engine/brake force, we don't want to preserve anything from the last frame)
  378. w->mLateralPart.WarmStart(*mBody, *w->mContactBody, -w->mContactLateral, inWarmStartImpulseRatio);
  379. }
  380. mPitchRollPart.WarmStart(*mBody, Body::sFixedToWorld, inWarmStartImpulseRatio);
  381. }
  382. bool VehicleConstraint::SolveVelocityConstraint(float inDeltaTime)
  383. {
  384. bool impulse = false;
  385. // Solve suspension
  386. for (Wheel *w : mWheels)
  387. if (w->mContactBody != nullptr)
  388. {
  389. Vec3 neg_contact_normal = -w->mContactNormal;
  390. // Suspension spring, note that it can only push and not pull
  391. if (w->mSuspensionPart.IsActive())
  392. impulse |= w->mSuspensionPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  393. // When reaching the minimal suspension length only allow forces pushing the bodies away
  394. if (w->mSuspensionMaxUpPart.IsActive())
  395. impulse |= w->mSuspensionMaxUpPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  396. }
  397. // Solve the horizontal movement of the vehicle
  398. impulse |= mController->SolveLongitudinalAndLateralConstraints(inDeltaTime);
  399. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  400. if (mPitchRollPart.IsActive())
  401. impulse |= mPitchRollPart.SolveVelocityConstraint(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis, 0, FLT_MAX);
  402. return impulse;
  403. }
  404. bool VehicleConstraint::SolvePositionConstraint(float inDeltaTime, float inBaumgarte)
  405. {
  406. bool impulse = false;
  407. RMat44 body_transform = mBody->GetWorldTransform();
  408. for (Wheel *w : mWheels)
  409. if (w->mContactBody != nullptr)
  410. {
  411. const WheelSettings *settings = w->mSettings;
  412. // Check if we reached the 'max up' position now that the body has possibly moved
  413. // We do this by calculating the axle position at minimum suspension length and making sure it does not go through the
  414. // plane defined by the contact normal and the axle position when the contact happened
  415. // TODO: This assumes that only the vehicle moved and not the ground as we kept the axle contact plane in world space
  416. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  417. RVec3 ws_position = body_transform * settings->mPosition;
  418. RVec3 min_suspension_pos = ws_position + settings->mSuspensionMinLength * ws_direction;
  419. float max_up_error = float(RVec3(w->mContactNormal).Dot(min_suspension_pos) - w->mAxlePlaneConstant);
  420. if (max_up_error < 0.0f)
  421. {
  422. Vec3 neg_contact_normal = -w->mContactNormal;
  423. // Recalculate constraint properties since the body may have moved
  424. Vec3 r1_plus_u, r2;
  425. CalculateWheelContactPoint(*w, r1_plus_u, r2);
  426. w->mSuspensionMaxUpPart.CalculateConstraintProperties(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal, 0.0f, max_up_error);
  427. impulse |= w->mSuspensionMaxUpPart.SolvePositionConstraint(*mBody, *w->mContactBody, neg_contact_normal, max_up_error, inBaumgarte);
  428. }
  429. }
  430. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  431. CalculatePitchRollConstraintProperties(inDeltaTime, body_transform);
  432. if (mPitchRollPart.IsActive())
  433. impulse |= mPitchRollPart.SolvePositionConstraint(*mBody, Body::sFixedToWorld, mCosPitchRollAngle - mCosMaxPitchRollAngle, inBaumgarte);
  434. return impulse;
  435. }
  436. #ifdef JPH_DEBUG_RENDERER
  437. void VehicleConstraint::DrawConstraint(DebugRenderer *inRenderer) const
  438. {
  439. mController->Draw(inRenderer);
  440. }
  441. void VehicleConstraint::DrawConstraintLimits(DebugRenderer *inRenderer) const
  442. {
  443. }
  444. #endif // JPH_DEBUG_RENDERER
  445. void VehicleConstraint::SaveState(StateRecorder &inStream) const
  446. {
  447. Constraint::SaveState(inStream);
  448. mController->SaveState(inStream);
  449. for (const Wheel *w : mWheels)
  450. {
  451. inStream.Write(w->mAngularVelocity);
  452. inStream.Write(w->mAngle);
  453. inStream.Write(w->mContactBodyID); // Used by MotorcycleController::PreCollide
  454. inStream.Write(w->mContactNormal); // Used by MotorcycleController::PreCollide
  455. inStream.Write(w->mContactLateral); // Used by MotorcycleController::PreCollide
  456. w->mSuspensionPart.SaveState(inStream);
  457. w->mSuspensionMaxUpPart.SaveState(inStream);
  458. w->mLongitudinalPart.SaveState(inStream);
  459. w->mLateralPart.SaveState(inStream);
  460. }
  461. inStream.Write(mPitchRollRotationAxis); // When rotation is too small we use last frame so we need to store it
  462. mPitchRollPart.SaveState(inStream);
  463. }
  464. void VehicleConstraint::RestoreState(StateRecorder &inStream)
  465. {
  466. Constraint::RestoreState(inStream);
  467. mController->RestoreState(inStream);
  468. for (Wheel *w : mWheels)
  469. {
  470. inStream.Read(w->mAngularVelocity);
  471. inStream.Read(w->mAngle);
  472. inStream.Read(w->mContactBodyID);
  473. inStream.Read(w->mContactNormal);
  474. inStream.Read(w->mContactLateral);
  475. w->mContactBody = nullptr; // No longer valid
  476. w->mSuspensionPart.RestoreState(inStream);
  477. w->mSuspensionMaxUpPart.RestoreState(inStream);
  478. w->mLongitudinalPart.RestoreState(inStream);
  479. w->mLateralPart.RestoreState(inStream);
  480. }
  481. inStream.Read(mPitchRollRotationAxis);
  482. mPitchRollPart.RestoreState(inStream);
  483. }
  484. Ref<ConstraintSettings> VehicleConstraint::GetConstraintSettings() const
  485. {
  486. JPH_ASSERT(false); // Not implemented yet
  487. return nullptr;
  488. }
  489. JPH_NAMESPACE_END