VehicleConstraint.cpp 25 KB

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