VehicleConstraint.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  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. mBody(&inVehicleBody),
  65. mForward(inSettings.mForward),
  66. mUp(inSettings.mUp),
  67. mWorldUp(inSettings.mUp)
  68. {
  69. // Check sanity of incoming settings
  70. JPH_ASSERT(inSettings.mUp.IsNormalized());
  71. JPH_ASSERT(inSettings.mForward.IsNormalized());
  72. JPH_ASSERT(!inSettings.mWheels.empty());
  73. // Store max pitch/roll angle
  74. SetMaxPitchRollAngle(inSettings.mMaxPitchRollAngle);
  75. // Copy anti-rollbar settings
  76. mAntiRollBars.resize(inSettings.mAntiRollBars.size());
  77. for (uint i = 0; i < mAntiRollBars.size(); ++i)
  78. {
  79. const VehicleAntiRollBar &r = inSettings.mAntiRollBars[i];
  80. mAntiRollBars[i] = r;
  81. JPH_ASSERT(r.mStiffness >= 0.0f);
  82. }
  83. // Construct our controler class
  84. mController = inSettings.mController->ConstructController(*this);
  85. // Create wheels
  86. mWheels.resize(inSettings.mWheels.size());
  87. for (uint i = 0; i < mWheels.size(); ++i)
  88. mWheels[i] = mController->ConstructWheel(*inSettings.mWheels[i]);
  89. }
  90. VehicleConstraint::~VehicleConstraint()
  91. {
  92. // Destroy controller
  93. delete mController;
  94. // Destroy our wheels
  95. for (Wheel *w : mWheels)
  96. delete w;
  97. }
  98. void VehicleConstraint::GetWheelLocalBasis(const Wheel *inWheel, Vec3 &outForward, Vec3 &outUp, Vec3 &outRight) const
  99. {
  100. const WheelSettings *settings = inWheel->mSettings;
  101. Quat steer_rotation = Quat::sRotation(settings->mSteeringAxis, inWheel->mSteerAngle);
  102. outUp = steer_rotation * settings->mWheelUp;
  103. outForward = steer_rotation * settings->mWheelForward;
  104. outRight = outForward.Cross(outUp).Normalized();
  105. outForward = outUp.Cross(outRight).Normalized();
  106. }
  107. Mat44 VehicleConstraint::GetWheelLocalTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const
  108. {
  109. JPH_ASSERT(inWheelIndex < mWheels.size());
  110. const Wheel *wheel = mWheels[inWheelIndex];
  111. const WheelSettings *settings = wheel->mSettings;
  112. // 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)
  113. Mat44 wheel_to_rotational = Mat44(Vec4(inWheelRight, 0), Vec4(inWheelUp, 0), Vec4(inWheelUp.Cross(inWheelRight), 0), Vec4(0, 0, 0, 1)).Transposed();
  114. // Calculate the matrix that takes us from the rotational space to vehicle local space
  115. Vec3 local_forward, local_up, local_right;
  116. GetWheelLocalBasis(wheel, local_forward, local_up, local_right);
  117. Vec3 local_wheel_pos = settings->mPosition + settings->mSuspensionDirection * wheel->mSuspensionLength;
  118. Mat44 rotational_to_local(Vec4(local_right, 0), Vec4(local_up, 0), Vec4(local_forward, 0), Vec4(local_wheel_pos, 1));
  119. // Calculate transform of rotated wheel
  120. return rotational_to_local * Mat44::sRotationX(wheel->mAngle) * wheel_to_rotational;
  121. }
  122. RMat44 VehicleConstraint::GetWheelWorldTransform(uint inWheelIndex, Vec3Arg inWheelRight, Vec3Arg inWheelUp) const
  123. {
  124. return mBody->GetWorldTransform() * GetWheelLocalTransform(inWheelIndex, inWheelRight, inWheelUp);
  125. }
  126. void VehicleConstraint::OnStep(float inDeltaTime, PhysicsSystem &inPhysicsSystem)
  127. {
  128. JPH_PROFILE_FUNCTION();
  129. // Callback to higher-level systems. We do it before PreCollide, in case steering changes.
  130. if (mPreStepCallback != nullptr)
  131. mPreStepCallback(*this, inDeltaTime, inPhysicsSystem);
  132. // Calculate new world up vector by inverting gravity
  133. mWorldUp = (-inPhysicsSystem.GetGravity()).NormalizedOr(mWorldUp);
  134. // Callback on our controller
  135. mController->PreCollide(inDeltaTime, inPhysicsSystem);
  136. // Calculate if this constraint is active by checking if our main vehicle body is active or any of the bodies we touch are active
  137. mIsActive = mBody->IsActive();
  138. RMat44 body_transform = mBody->GetWorldTransform();
  139. // Test collision for wheels
  140. for (uint wheel_index = 0; wheel_index < mWheels.size(); ++wheel_index)
  141. {
  142. Wheel *w = mWheels[wheel_index];
  143. const WheelSettings *settings = w->mSettings;
  144. // Reset contact
  145. w->mContactBodyID = BodyID();
  146. w->mContactBody = nullptr;
  147. w->mContactSubShapeID = SubShapeID();
  148. w->mSuspensionLength = settings->mSuspensionMaxLength;
  149. // Test collision to find the floor
  150. RVec3 ws_origin = body_transform * settings->mPosition;
  151. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  152. if (mVehicleCollisionTester->Collide(inPhysicsSystem, *this, wheel_index, ws_origin, ws_direction, mBody->GetID(), w->mContactBody, w->mContactSubShapeID, w->mContactPosition, w->mContactNormal, w->mSuspensionLength))
  153. {
  154. // Store ID (pointer is not valid outside of the simulation step)
  155. w->mContactBodyID = w->mContactBody->GetID();
  156. // Store contact velocity, cache this as the contact body may be removed
  157. w->mContactPointVelocity = w->mContactBody->GetPointVelocity(w->mContactPosition);
  158. // Determine plane constant for axle contact plane
  159. w->mAxlePlaneConstant = RVec3(w->mContactNormal).Dot(ws_origin + w->mSuspensionLength * ws_direction);
  160. // Check if body is active, if so the entire vehicle should be active
  161. mIsActive |= w->mContactBody->IsActive();
  162. // Determine world space forward using steering angle and body rotation
  163. Vec3 forward, up, right;
  164. GetWheelLocalBasis(w, forward, up, right);
  165. forward = body_transform.Multiply3x3(forward);
  166. right = body_transform.Multiply3x3(right);
  167. // The longitudinal axis is in the up/forward plane
  168. w->mContactLongitudinal = w->mContactNormal.Cross(right);
  169. // Make sure that the longitudinal axis is aligned with the forward axis
  170. if (w->mContactLongitudinal.Dot(forward) < 0.0f)
  171. w->mContactLongitudinal = -w->mContactLongitudinal;
  172. // Normalize it
  173. w->mContactLongitudinal = w->mContactLongitudinal.NormalizedOr(w->mContactNormal.GetNormalizedPerpendicular());
  174. // The lateral axis is perpendicular to contact normal and longitudinal axis
  175. w->mContactLateral = w->mContactLongitudinal.Cross(w->mContactNormal).Normalized();
  176. }
  177. }
  178. // Callback to higher-level systems. We do it immediately after wheel collision.
  179. if (mPostCollideCallback != nullptr)
  180. mPostCollideCallback(*this, inDeltaTime, inPhysicsSystem);
  181. // Calculate anti-rollbar impulses
  182. for (const VehicleAntiRollBar &r : mAntiRollBars)
  183. {
  184. Wheel *lw = mWheels[r.mLeftWheel];
  185. Wheel *rw = mWheels[r.mRightWheel];
  186. if (lw->mContactBody != nullptr && rw->mContactBody != nullptr)
  187. {
  188. // Calculate the impulse to apply based on the difference in suspension length
  189. float difference = rw->mSuspensionLength - lw->mSuspensionLength;
  190. float impulse = difference * r.mStiffness * inDeltaTime;
  191. lw->mAntiRollBarImpulse = -impulse;
  192. rw->mAntiRollBarImpulse = impulse;
  193. }
  194. else
  195. {
  196. // When one of the wheels is not on the ground we don't apply any impulses
  197. lw->mAntiRollBarImpulse = rw->mAntiRollBarImpulse = 0.0f;
  198. }
  199. }
  200. // Callback on our controller
  201. mController->PostCollide(inDeltaTime, inPhysicsSystem);
  202. // Callback to higher-level systems. We do it before the sleep section, in case velocities change.
  203. if (mPostStepCallback != nullptr)
  204. mPostStepCallback(*this, inDeltaTime, inPhysicsSystem);
  205. // If the wheels are rotating, we don't want to go to sleep yet
  206. bool allow_sleep = mController->AllowSleep();
  207. if (allow_sleep)
  208. for (const Wheel *w : mWheels)
  209. if (abs(w->mAngularVelocity) > DegreesToRadians(10.0f))
  210. {
  211. allow_sleep = false;
  212. break;
  213. }
  214. if (mBody->GetAllowSleeping() != allow_sleep)
  215. mBody->SetAllowSleeping(allow_sleep);
  216. }
  217. void VehicleConstraint::BuildIslands(uint32 inConstraintIndex, IslandBuilder &ioBuilder, BodyManager &inBodyManager)
  218. {
  219. // Find dynamic bodies that our wheels are touching
  220. BodyID *body_ids = (BodyID *)JPH_STACK_ALLOC((mWheels.size() + 1) * sizeof(BodyID));
  221. int num_bodies = 0;
  222. bool needs_to_activate = false;
  223. for (const Wheel *w : mWheels)
  224. if (w->mContactBody != nullptr)
  225. {
  226. // Avoid adding duplicates
  227. bool duplicate = false;
  228. BodyID id = w->mContactBody->GetID();
  229. for (int i = 0; i < num_bodies; ++i)
  230. if (body_ids[i] == id)
  231. {
  232. duplicate = true;
  233. break;
  234. }
  235. if (duplicate)
  236. continue;
  237. if (w->mContactBody->IsDynamic())
  238. {
  239. body_ids[num_bodies++] = id;
  240. needs_to_activate |= !w->mContactBody->IsActive();
  241. }
  242. }
  243. // 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
  244. if (!mBody->IsActive())
  245. {
  246. // Our main body is not active, activate it too
  247. body_ids[num_bodies] = mBody->GetID();
  248. inBodyManager.ActivateBodies(body_ids, num_bodies + 1);
  249. }
  250. else if (needs_to_activate)
  251. {
  252. // Only activate bodies the wheels are touching
  253. inBodyManager.ActivateBodies(body_ids, num_bodies);
  254. }
  255. // Link the bodies into the same island
  256. uint32 min_active_index = Body::cInactiveIndex;
  257. for (int i = 0; i < num_bodies; ++i)
  258. {
  259. const Body &body = inBodyManager.GetBody(body_ids[i]);
  260. min_active_index = min(min_active_index, body.GetIndexInActiveBodiesInternal());
  261. ioBuilder.LinkBodies(mBody->GetIndexInActiveBodiesInternal(), body.GetIndexInActiveBodiesInternal());
  262. }
  263. // Link the constraint in the island
  264. ioBuilder.LinkConstraint(inConstraintIndex, mBody->GetIndexInActiveBodiesInternal(), min_active_index);
  265. }
  266. uint VehicleConstraint::BuildIslandSplits(LargeIslandSplitter &ioSplitter) const
  267. {
  268. return ioSplitter.AssignToNonParallelSplit(mBody);
  269. }
  270. void VehicleConstraint::CalculateSuspensionForcePoint(const Wheel &inWheel, Vec3 &outR1PlusU, Vec3 &outR2) const
  271. {
  272. // Determine point to apply force to
  273. RVec3 force_point;
  274. if (inWheel.mSettings->mEnableSuspensionForcePoint)
  275. force_point = mBody->GetWorldTransform() * inWheel.mSettings->mSuspensionForcePoint;
  276. else
  277. force_point = inWheel.mContactPosition;
  278. // Calculate r1 + u and r2
  279. outR1PlusU = Vec3(force_point - mBody->GetCenterOfMassPosition());
  280. outR2 = Vec3(force_point - inWheel.mContactBody->GetCenterOfMassPosition());
  281. }
  282. void VehicleConstraint::CalculatePitchRollConstraintProperties(RMat44Arg inBodyTransform)
  283. {
  284. // Check if a limit was specified
  285. if (mCosMaxPitchRollAngle > -1.0f)
  286. {
  287. // Calculate cos of angle between world up vector and vehicle up vector
  288. Vec3 vehicle_up = inBodyTransform.Multiply3x3(mUp);
  289. mCosPitchRollAngle = mWorldUp.Dot(vehicle_up);
  290. if (mCosPitchRollAngle < mCosMaxPitchRollAngle)
  291. {
  292. // Calculate rotation axis to rotate vehicle towards up
  293. Vec3 rotation_axis = mWorldUp.Cross(vehicle_up);
  294. float len = rotation_axis.Length();
  295. if (len > 0.0f)
  296. mPitchRollRotationAxis = rotation_axis / len;
  297. mPitchRollPart.CalculateConstraintProperties(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis);
  298. }
  299. else
  300. mPitchRollPart.Deactivate();
  301. }
  302. else
  303. mPitchRollPart.Deactivate();
  304. }
  305. void VehicleConstraint::SetupVelocityConstraint(float inDeltaTime)
  306. {
  307. RMat44 body_transform = mBody->GetWorldTransform();
  308. for (Wheel *w : mWheels)
  309. if (w->mContactBody != nullptr)
  310. {
  311. const WheelSettings *settings = w->mSettings;
  312. Vec3 neg_contact_normal = -w->mContactNormal;
  313. Vec3 r1_plus_u, r2;
  314. CalculateSuspensionForcePoint(*w, r1_plus_u, r2);
  315. // Suspension spring
  316. if (settings->mSuspensionMaxLength > settings->mSuspensionMinLength)
  317. {
  318. float stiffness, damping;
  319. if (settings->mSuspensionSpring.mMode == ESpringMode::FrequencyAndDamping)
  320. {
  321. // Calculate effective mass based on vehicle configuration (the stiffness of the spring should not be affected by the dynamics of the vehicle): K = 1 / (J M^-1 J^T)
  322. // Note that if no suspension force point is supplied we don't know where the force is applied so we assume it is applied at average suspension length
  323. Vec3 force_point = settings->mEnableSuspensionForcePoint? settings->mSuspensionForcePoint : settings->mPosition + 0.5f * (settings->mSuspensionMinLength + settings->mSuspensionMaxLength) * settings->mSuspensionDirection;
  324. Vec3 force_point_x_neg_up = force_point.Cross(-mUp);
  325. const MotionProperties *mp = mBody->GetMotionProperties();
  326. float effective_mass = 1.0f / (mp->GetInverseMass() + force_point_x_neg_up.Dot(mp->GetLocalSpaceInverseInertia().Multiply3x3(force_point_x_neg_up)));
  327. // Convert frequency and damping to stiffness and damping
  328. float omega = 2.0f * JPH_PI * settings->mSuspensionSpring.mFrequency;
  329. stiffness = effective_mass * Square(omega);
  330. damping = 2.0f * effective_mass * settings->mSuspensionSpring.mDamping * omega;
  331. }
  332. else
  333. {
  334. // In this case we can simply copy the properties
  335. stiffness = settings->mSuspensionSpring.mStiffness;
  336. damping = settings->mSuspensionSpring.mDamping;
  337. }
  338. // Calculate the damping and frequency of the suspension spring given the angle between the suspension direction and the contact normal
  339. // 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:
  340. //
  341. // Fspring = Fnormal * cos(alpha)
  342. //
  343. // The spring force is:
  344. //
  345. // Fspring = -k * x
  346. //
  347. // where k is the spring constant and x is the displacement of the spring. So we have:
  348. //
  349. // Fnormal * cos(alpha) = -k * x <=> Fnormal = -k / cos(alpha) * x
  350. //
  351. // So we can see this as a spring with spring constant:
  352. //
  353. // k' = k / cos(alpha)
  354. //
  355. // In the same way the velocity relates like:
  356. //
  357. // Vspring = Vnormal * cos(alpha)
  358. //
  359. // Which results in the modified damping constant c:
  360. //
  361. // c' = c / cos(alpha)
  362. //
  363. // Note that we clamp 1 / cos(alpha) to the range [0.1, 1] in order not to increase the stiffness / damping by too much.
  364. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  365. float cos_angle = max(0.1f, ws_direction.Dot(neg_contact_normal));
  366. stiffness /= cos_angle;
  367. damping /= cos_angle;
  368. // Get the value of the constraint equation
  369. float c = w->mSuspensionLength - settings->mSuspensionMaxLength - settings->mSuspensionPreloadLength;
  370. w->mSuspensionPart.CalculateConstraintPropertiesWithStiffnessAndDamping(inDeltaTime, *mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal, w->mAntiRollBarImpulse, c, stiffness, damping);
  371. }
  372. else
  373. w->mSuspensionPart.Deactivate();
  374. // 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
  375. if (w->mSuspensionLength < settings->mSuspensionMinLength)
  376. w->mSuspensionMaxUpPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  377. else
  378. w->mSuspensionMaxUpPart.Deactivate();
  379. // Friction and propulsion
  380. w->mLongitudinalPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLongitudinal);
  381. w->mLateralPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, -w->mContactLateral);
  382. }
  383. else
  384. {
  385. // No contact -> disable everything
  386. w->mSuspensionPart.Deactivate();
  387. w->mSuspensionMaxUpPart.Deactivate();
  388. w->mLongitudinalPart.Deactivate();
  389. w->mLateralPart.Deactivate();
  390. }
  391. CalculatePitchRollConstraintProperties(body_transform);
  392. }
  393. void VehicleConstraint::WarmStartVelocityConstraint(float inWarmStartImpulseRatio)
  394. {
  395. for (Wheel *w : mWheels)
  396. if (w->mContactBody != nullptr)
  397. {
  398. Vec3 neg_contact_normal = -w->mContactNormal;
  399. w->mSuspensionPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  400. w->mSuspensionMaxUpPart.WarmStart(*mBody, *w->mContactBody, neg_contact_normal, inWarmStartImpulseRatio);
  401. 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)
  402. w->mLateralPart.WarmStart(*mBody, *w->mContactBody, -w->mContactLateral, inWarmStartImpulseRatio);
  403. }
  404. mPitchRollPart.WarmStart(*mBody, Body::sFixedToWorld, inWarmStartImpulseRatio);
  405. }
  406. bool VehicleConstraint::SolveVelocityConstraint(float inDeltaTime)
  407. {
  408. bool impulse = false;
  409. // Solve suspension
  410. for (Wheel *w : mWheels)
  411. if (w->mContactBody != nullptr)
  412. {
  413. Vec3 neg_contact_normal = -w->mContactNormal;
  414. // Suspension spring, note that it can only push and not pull
  415. if (w->mSuspensionPart.IsActive())
  416. impulse |= w->mSuspensionPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  417. // When reaching the minimal suspension length only allow forces pushing the bodies away
  418. if (w->mSuspensionMaxUpPart.IsActive())
  419. impulse |= w->mSuspensionMaxUpPart.SolveVelocityConstraint(*mBody, *w->mContactBody, neg_contact_normal, 0.0f, FLT_MAX);
  420. }
  421. // Solve the horizontal movement of the vehicle
  422. impulse |= mController->SolveLongitudinalAndLateralConstraints(inDeltaTime);
  423. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  424. if (mPitchRollPart.IsActive())
  425. impulse |= mPitchRollPart.SolveVelocityConstraint(*mBody, Body::sFixedToWorld, mPitchRollRotationAxis, 0, FLT_MAX);
  426. return impulse;
  427. }
  428. bool VehicleConstraint::SolvePositionConstraint(float inDeltaTime, float inBaumgarte)
  429. {
  430. bool impulse = false;
  431. RMat44 body_transform = mBody->GetWorldTransform();
  432. for (Wheel *w : mWheels)
  433. if (w->mContactBody != nullptr)
  434. {
  435. const WheelSettings *settings = w->mSettings;
  436. // Check if we reached the 'max up' position now that the body has possibly moved
  437. // We do this by calculating the axle position at minimum suspension length and making sure it does not go through the
  438. // plane defined by the contact normal and the axle position when the contact happened
  439. // TODO: This assumes that only the vehicle moved and not the ground as we kept the axle contact plane in world space
  440. Vec3 ws_direction = body_transform.Multiply3x3(settings->mSuspensionDirection);
  441. RVec3 ws_position = body_transform * settings->mPosition;
  442. RVec3 min_suspension_pos = ws_position + settings->mSuspensionMinLength * ws_direction;
  443. float max_up_error = float(RVec3(w->mContactNormal).Dot(min_suspension_pos) - w->mAxlePlaneConstant);
  444. if (max_up_error < 0.0f)
  445. {
  446. Vec3 neg_contact_normal = -w->mContactNormal;
  447. // Recalculate constraint properties since the body may have moved
  448. Vec3 r1_plus_u, r2;
  449. CalculateSuspensionForcePoint(*w, r1_plus_u, r2);
  450. w->mSuspensionMaxUpPart.CalculateConstraintProperties(*mBody, r1_plus_u, *w->mContactBody, r2, neg_contact_normal);
  451. impulse |= w->mSuspensionMaxUpPart.SolvePositionConstraint(*mBody, *w->mContactBody, neg_contact_normal, max_up_error, inBaumgarte);
  452. }
  453. }
  454. // Apply the pitch / roll constraint to avoid the vehicle from toppling over
  455. CalculatePitchRollConstraintProperties(body_transform);
  456. if (mPitchRollPart.IsActive())
  457. impulse |= mPitchRollPart.SolvePositionConstraint(*mBody, Body::sFixedToWorld, mCosPitchRollAngle - mCosMaxPitchRollAngle, inBaumgarte);
  458. return impulse;
  459. }
  460. #ifdef JPH_DEBUG_RENDERER
  461. void VehicleConstraint::DrawConstraint(DebugRenderer *inRenderer) const
  462. {
  463. mController->Draw(inRenderer);
  464. }
  465. void VehicleConstraint::DrawConstraintLimits(DebugRenderer *inRenderer) const
  466. {
  467. }
  468. #endif // JPH_DEBUG_RENDERER
  469. void VehicleConstraint::SaveState(StateRecorder &inStream) const
  470. {
  471. Constraint::SaveState(inStream);
  472. mController->SaveState(inStream);
  473. for (const Wheel *w : mWheels)
  474. {
  475. inStream.Write(w->mAngularVelocity);
  476. inStream.Write(w->mAngle);
  477. inStream.Write(w->mContactBodyID); // Used by MotorcycleController::PreCollide
  478. inStream.Write(w->mContactNormal); // Used by MotorcycleController::PreCollide
  479. inStream.Write(w->mContactLateral); // Used by MotorcycleController::PreCollide
  480. w->mSuspensionPart.SaveState(inStream);
  481. w->mSuspensionMaxUpPart.SaveState(inStream);
  482. w->mLongitudinalPart.SaveState(inStream);
  483. w->mLateralPart.SaveState(inStream);
  484. }
  485. inStream.Write(mPitchRollRotationAxis); // When rotation is too small we use last frame so we need to store it
  486. mPitchRollPart.SaveState(inStream);
  487. }
  488. void VehicleConstraint::RestoreState(StateRecorder &inStream)
  489. {
  490. Constraint::RestoreState(inStream);
  491. mController->RestoreState(inStream);
  492. for (Wheel *w : mWheels)
  493. {
  494. inStream.Read(w->mAngularVelocity);
  495. inStream.Read(w->mAngle);
  496. inStream.Read(w->mContactBodyID);
  497. inStream.Read(w->mContactNormal);
  498. inStream.Read(w->mContactLateral);
  499. w->mContactBody = nullptr; // No longer valid
  500. w->mSuspensionPart.RestoreState(inStream);
  501. w->mSuspensionMaxUpPart.RestoreState(inStream);
  502. w->mLongitudinalPart.RestoreState(inStream);
  503. w->mLateralPart.RestoreState(inStream);
  504. }
  505. inStream.Read(mPitchRollRotationAxis);
  506. mPitchRollPart.RestoreState(inStream);
  507. }
  508. Ref<ConstraintSettings> VehicleConstraint::GetConstraintSettings() const
  509. {
  510. JPH_ASSERT(false); // Not implemented yet
  511. return nullptr;
  512. }
  513. JPH_NAMESPACE_END