CharacterVirtual.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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/Character/CharacterVirtual.h>
  6. #include <Jolt/Physics/Body/Body.h>
  7. #include <Jolt/Physics/PhysicsSystem.h>
  8. #include <Jolt/Physics/Collision/ShapeCast.h>
  9. #include <Jolt/Physics/Collision/CollideShape.h>
  10. #include <Jolt/Physics/Collision/Shape/RotatedTranslatedShape.h>
  11. #include <Jolt/Core/QuickSort.h>
  12. #include <Jolt/Geometry/ConvexSupport.h>
  13. #include <Jolt/Geometry/GJKClosestPoint.h>
  14. #ifdef JPH_DEBUG_RENDERER
  15. #include <Jolt/Renderer/DebugRenderer.h>
  16. #endif // JPH_DEBUG_RENDERER
  17. JPH_NAMESPACE_BEGIN
  18. CharacterVirtual::CharacterVirtual(const CharacterVirtualSettings *inSettings, RVec3Arg inPosition, QuatArg inRotation, PhysicsSystem *inSystem) :
  19. CharacterBase(inSettings, inSystem),
  20. mBackFaceMode(inSettings->mBackFaceMode),
  21. mPredictiveContactDistance(inSettings->mPredictiveContactDistance),
  22. mMaxCollisionIterations(inSettings->mMaxCollisionIterations),
  23. mMaxConstraintIterations(inSettings->mMaxConstraintIterations),
  24. mMinTimeRemaining(inSettings->mMinTimeRemaining),
  25. mCollisionTolerance(inSettings->mCollisionTolerance),
  26. mCharacterPadding(inSettings->mCharacterPadding),
  27. mMaxNumHits(inSettings->mMaxNumHits),
  28. mHitReductionCosMaxAngle(inSettings->mHitReductionCosMaxAngle),
  29. mPenetrationRecoverySpeed(inSettings->mPenetrationRecoverySpeed),
  30. mShapeOffset(inSettings->mShapeOffset),
  31. mPosition(inPosition),
  32. mRotation(inRotation)
  33. {
  34. // Copy settings
  35. SetMaxStrength(inSettings->mMaxStrength);
  36. SetMass(inSettings->mMass);
  37. }
  38. void CharacterVirtual::GetAdjustedBodyVelocity(const Body& inBody, Vec3 &outLinearVelocity, Vec3 &outAngularVelocity) const
  39. {
  40. // Get real velocity of body
  41. if (!inBody.IsStatic())
  42. {
  43. const MotionProperties *mp = inBody.GetMotionPropertiesUnchecked();
  44. outLinearVelocity = mp->GetLinearVelocity();
  45. outAngularVelocity = mp->GetAngularVelocity();
  46. }
  47. else
  48. {
  49. outLinearVelocity = outAngularVelocity = Vec3::sZero();
  50. }
  51. // Allow application to override
  52. if (mListener != nullptr)
  53. mListener->OnAdjustBodyVelocity(this, inBody, outLinearVelocity, outAngularVelocity);
  54. }
  55. Vec3 CharacterVirtual::CalculateCharacterGroundVelocity(RVec3Arg inCenterOfMass, Vec3Arg inLinearVelocity, Vec3Arg inAngularVelocity, float inDeltaTime) const
  56. {
  57. // Get angular velocity
  58. float angular_velocity_len_sq = inAngularVelocity.LengthSq();
  59. if (angular_velocity_len_sq < 1.0e-12f)
  60. return inLinearVelocity;
  61. float angular_velocity_len = sqrt(angular_velocity_len_sq);
  62. // Calculate the rotation that the object will make in the time step
  63. Quat rotation = Quat::sRotation(inAngularVelocity / angular_velocity_len, angular_velocity_len * inDeltaTime);
  64. // Calculate where the new character position will be
  65. RVec3 new_position = inCenterOfMass + rotation * Vec3(mPosition - inCenterOfMass);
  66. // Calculate the velocity
  67. return inLinearVelocity + Vec3(new_position - mPosition) / inDeltaTime;
  68. }
  69. template <class taCollector>
  70. void CharacterVirtual::sFillContactProperties(const CharacterVirtual *inCharacter, Contact &outContact, const Body &inBody, Vec3Arg inUp, RVec3Arg inBaseOffset, const taCollector &inCollector, const CollideShapeResult &inResult)
  71. {
  72. // Get adjusted body velocity
  73. Vec3 linear_velocity, angular_velocity;
  74. inCharacter->GetAdjustedBodyVelocity(inBody, linear_velocity, angular_velocity);
  75. outContact.mPosition = inBaseOffset + inResult.mContactPointOn2;
  76. outContact.mLinearVelocity = linear_velocity + angular_velocity.Cross(Vec3(outContact.mPosition - inBody.GetCenterOfMassPosition())); // Calculate point velocity
  77. outContact.mContactNormal = -inResult.mPenetrationAxis.NormalizedOr(Vec3::sZero());
  78. outContact.mSurfaceNormal = inCollector.GetContext()->GetWorldSpaceSurfaceNormal(inResult.mSubShapeID2, outContact.mPosition);
  79. if (outContact.mContactNormal.Dot(outContact.mSurfaceNormal) < 0.0f)
  80. outContact.mSurfaceNormal = -outContact.mSurfaceNormal; // Flip surface normal if we're hitting a back face
  81. if (outContact.mContactNormal.Dot(inUp) > outContact.mSurfaceNormal.Dot(inUp))
  82. outContact.mSurfaceNormal = outContact.mContactNormal; // Replace surface normal with contact normal if the contact normal is pointing more upwards
  83. outContact.mDistance = -inResult.mPenetrationDepth;
  84. outContact.mBodyB = inResult.mBodyID2;
  85. outContact.mSubShapeIDB = inResult.mSubShapeID2;
  86. outContact.mMotionTypeB = inBody.GetMotionType();
  87. outContact.mUserData = inBody.GetUserData();
  88. outContact.mMaterial = inCollector.GetContext()->GetMaterial(inResult.mSubShapeID2);
  89. }
  90. void CharacterVirtual::ContactCollector::AddHit(const CollideShapeResult &inResult)
  91. {
  92. // If we exceed our contact limit, try to clean up near-duplicate contacts
  93. if (mContacts.size() == mMaxHits)
  94. {
  95. // Flag that we hit this code path
  96. mMaxHitsExceeded = true;
  97. // Check if we can do reduction
  98. if (mHitReductionCosMaxAngle > -1.0f)
  99. {
  100. // Loop all contacts and find similar contacts
  101. for (int i = (int)mContacts.size() - 1; i >= 0; --i)
  102. {
  103. Contact &contact_i = mContacts[i];
  104. for (int j = i - 1; j >= 0; --j)
  105. {
  106. Contact &contact_j = mContacts[j];
  107. if (contact_i.mBodyB == contact_j.mBodyB // Same body
  108. && contact_i.mContactNormal.Dot(contact_j.mContactNormal) > mHitReductionCosMaxAngle) // Very similar contact normals
  109. {
  110. // Remove the contact with the biggest distance
  111. bool i_is_last = i == (int)mContacts.size() - 1;
  112. if (contact_i.mDistance > contact_j.mDistance)
  113. {
  114. // Remove i
  115. if (!i_is_last)
  116. contact_i = mContacts.back();
  117. mContacts.pop_back();
  118. // Break out of the loop, i is now an element that we already processed
  119. break;
  120. }
  121. else
  122. {
  123. // Remove j
  124. contact_j = mContacts.back();
  125. mContacts.pop_back();
  126. // If i was the last element, we just moved it into position j. Break out of the loop, we'll see it again later.
  127. if (i_is_last)
  128. break;
  129. }
  130. }
  131. }
  132. }
  133. }
  134. if (mContacts.size() == mMaxHits)
  135. {
  136. // There are still too many hits, give up!
  137. ForceEarlyOut();
  138. return;
  139. }
  140. }
  141. BodyLockRead lock(mSystem->GetBodyLockInterface(), inResult.mBodyID2);
  142. if (lock.SucceededAndIsInBroadPhase())
  143. {
  144. // We don't collide with sensors, note that you should set up your collision layers so that sensors don't collide with the character.
  145. // Rejecting the contact here means a lot of extra work for the collision detection system.
  146. const Body &body = lock.GetBody();
  147. if (!body.IsSensor())
  148. {
  149. mContacts.emplace_back();
  150. Contact &contact = mContacts.back();
  151. sFillContactProperties(mCharacter, contact, body, mUp, mBaseOffset, *this, inResult);
  152. contact.mFraction = 0.0f;
  153. }
  154. }
  155. }
  156. void CharacterVirtual::ContactCastCollector::AddHit(const ShapeCastResult &inResult)
  157. {
  158. // Should not have gotten here without a lower fraction
  159. JPH_ASSERT(inResult.mFraction < mContact.mFraction);
  160. if (inResult.mFraction > 0.0f // Ignore collisions at fraction = 0
  161. && inResult.mPenetrationAxis.Dot(mDisplacement) > 0.0f) // Ignore penetrations that we're moving away from
  162. {
  163. // Test if this contact should be ignored
  164. for (const IgnoredContact &c : mIgnoredContacts)
  165. if (c.mBodyID == inResult.mBodyID2 && c.mSubShapeID == inResult.mSubShapeID2)
  166. return;
  167. Contact contact;
  168. // Lock body only while we fetch contact properties
  169. {
  170. BodyLockRead lock(mSystem->GetBodyLockInterface(), inResult.mBodyID2);
  171. if (!lock.SucceededAndIsInBroadPhase())
  172. return;
  173. // We don't collide with sensors, note that you should set up your collision layers so that sensors don't collide with the character.
  174. // Rejecting the contact here means a lot of extra work for the collision detection system.
  175. const Body &body = lock.GetBody();
  176. if (body.IsSensor())
  177. return;
  178. // Convert the hit result into a contact
  179. sFillContactProperties(mCharacter, contact, body, mUp, mBaseOffset, *this, inResult);
  180. }
  181. contact.mFraction = inResult.mFraction;
  182. // Check if the contact that will make us penetrate more than the allowed tolerance
  183. if (contact.mDistance + contact.mContactNormal.Dot(mDisplacement) < -mCharacter->mCollisionTolerance
  184. && mCharacter->ValidateContact(contact))
  185. {
  186. mContact = contact;
  187. UpdateEarlyOutFraction(contact.mFraction);
  188. }
  189. }
  190. }
  191. void CharacterVirtual::CheckCollision(RVec3Arg inPosition, QuatArg inRotation, Vec3Arg inMovementDirection, float inMaxSeparationDistance, const Shape *inShape, RVec3Arg inBaseOffset, CollideShapeCollector &ioCollector, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const
  192. {
  193. // Query shape transform
  194. RMat44 transform = GetCenterOfMassTransform(inPosition, inRotation, inShape);
  195. // Settings for collide shape
  196. CollideShapeSettings settings;
  197. settings.mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive;
  198. settings.mBackFaceMode = mBackFaceMode;
  199. settings.mActiveEdgeMovementDirection = inMovementDirection;
  200. settings.mMaxSeparationDistance = mCharacterPadding + inMaxSeparationDistance;
  201. // Collide shape
  202. mSystem->GetNarrowPhaseQuery().CollideShape(inShape, Vec3::sReplicate(1.0f), transform, settings, inBaseOffset, ioCollector, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  203. }
  204. void CharacterVirtual::GetContactsAtPosition(RVec3Arg inPosition, Vec3Arg inMovementDirection, const Shape *inShape, TempContactList &outContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const
  205. {
  206. // Remove previous results
  207. outContacts.clear();
  208. // Collide shape
  209. ContactCollector collector(mSystem, this, mMaxNumHits, mHitReductionCosMaxAngle, mUp, mPosition, outContacts);
  210. CheckCollision(inPosition, mRotation, inMovementDirection, mPredictiveContactDistance, inShape, mPosition, collector, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  211. // Flag if we exceeded the max number of hits
  212. mMaxHitsExceeded = collector.mMaxHitsExceeded;
  213. // Reduce distance to contact by padding to ensure we stay away from the object by a little margin
  214. // (this will make collision detection cheaper - especially for sweep tests as they won't hit the surface if we're properly sliding)
  215. for (Contact &c : outContacts)
  216. c.mDistance -= mCharacterPadding;
  217. }
  218. void CharacterVirtual::RemoveConflictingContacts(TempContactList &ioContacts, IgnoredContactList &outIgnoredContacts) const
  219. {
  220. // Only use this algorithm if we're penetrating further than this (due to numerical precision issues we can always penetrate a little bit and we don't want to discard contacts if they just have a tiny penetration)
  221. // We do need to account for padding (see GetContactsAtPosition) that is removed from the contact distances, to compensate we add it to the cMinRequiredPenetration
  222. const float cMinRequiredPenetration = 1.25f * mCharacterPadding;
  223. // Discard conflicting penetrating contacts
  224. for (size_t c1 = 0; c1 < ioContacts.size(); c1++)
  225. {
  226. Contact &contact1 = ioContacts[c1];
  227. if (contact1.mDistance <= -cMinRequiredPenetration) // Only for penetrations
  228. for (size_t c2 = c1 + 1; c2 < ioContacts.size(); c2++)
  229. {
  230. Contact &contact2 = ioContacts[c2];
  231. if (contact1.mBodyB == contact2.mBodyB // Only same body
  232. && contact2.mDistance <= -cMinRequiredPenetration // Only for penetrations
  233. && contact1.mContactNormal.Dot(contact2.mContactNormal) < 0.0f) // Only opposing normals
  234. {
  235. // Discard contacts with the least amount of penetration
  236. if (contact1.mDistance < contact2.mDistance)
  237. {
  238. // Discard the 2nd contact
  239. outIgnoredContacts.emplace_back(contact2.mBodyB, contact2.mSubShapeIDB);
  240. ioContacts.erase(ioContacts.begin() + c2);
  241. c2--;
  242. }
  243. else
  244. {
  245. // Discard the first contact
  246. outIgnoredContacts.emplace_back(contact1.mBodyB, contact1.mSubShapeIDB);
  247. ioContacts.erase(ioContacts.begin() + c1);
  248. c1--;
  249. break;
  250. }
  251. }
  252. }
  253. }
  254. }
  255. bool CharacterVirtual::ValidateContact(const Contact &inContact) const
  256. {
  257. if (mListener == nullptr)
  258. return true;
  259. return mListener->OnContactValidate(this, inContact.mBodyB, inContact.mSubShapeIDB);
  260. }
  261. template <class T>
  262. inline static bool sCorrectFractionForCharacterPadding(const Shape *inShape, Mat44Arg inStart, Vec3Arg inDisplacement, const T &inPolygon, float &ioFraction)
  263. {
  264. if (inShape->GetType() == EShapeType::Convex)
  265. {
  266. // Get the support function for the shape we're casting
  267. const ConvexShape *convex_shape = static_cast<const ConvexShape *>(inShape);
  268. ConvexShape::SupportBuffer buffer;
  269. const ConvexShape::Support *support = convex_shape->GetSupportFunction(ConvexShape::ESupportMode::IncludeConvexRadius, buffer, Vec3::sReplicate(1.0f));
  270. // Cast the shape against the polygon
  271. GJKClosestPoint gjk;
  272. return gjk.CastShape(inStart, inDisplacement, cDefaultCollisionTolerance, *support, inPolygon, ioFraction);
  273. }
  274. else if (inShape->GetSubType() == EShapeSubType::RotatedTranslated)
  275. {
  276. const RotatedTranslatedShape *rt_shape = static_cast<const RotatedTranslatedShape *>(inShape);
  277. return sCorrectFractionForCharacterPadding(rt_shape->GetInnerShape(), inStart * Mat44::sRotation(rt_shape->GetRotation()), inDisplacement, inPolygon, ioFraction);
  278. }
  279. else
  280. {
  281. JPH_ASSERT(false, "Not supported yet!");
  282. return false;
  283. }
  284. }
  285. bool CharacterVirtual::GetFirstContactForSweep(RVec3Arg inPosition, Vec3Arg inDisplacement, Contact &outContact, const IgnoredContactList &inIgnoredContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter) const
  286. {
  287. // Too small distance -> skip checking
  288. float displacement_len_sq = inDisplacement.LengthSq();
  289. if (displacement_len_sq < 1.0e-8f)
  290. return false;
  291. // Calculate start transform
  292. RMat44 start = GetCenterOfMassTransform(inPosition, mRotation, mShape);
  293. // Settings for the cast
  294. ShapeCastSettings settings;
  295. settings.mBackFaceModeTriangles = mBackFaceMode;
  296. settings.mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;
  297. settings.mActiveEdgeMode = EActiveEdgeMode::CollideOnlyWithActive;
  298. settings.mUseShrunkenShapeAndConvexRadius = true;
  299. settings.mReturnDeepestPoint = false;
  300. // Calculate how much extra fraction we need to add to the cast to account for the character padding
  301. float character_padding_fraction = mCharacterPadding / sqrt(displacement_len_sq);
  302. // Cast shape
  303. Contact contact;
  304. contact.mFraction = 1.0f + character_padding_fraction;
  305. ContactCastCollector collector(mSystem, this, inDisplacement, mUp, inIgnoredContacts, start.GetTranslation(), contact);
  306. collector.ResetEarlyOutFraction(contact.mFraction);
  307. RShapeCast shape_cast(mShape, Vec3::sReplicate(1.0f), start, inDisplacement);
  308. mSystem->GetNarrowPhaseQuery().CastShape(shape_cast, settings, start.GetTranslation(), collector, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  309. if (contact.mBodyB.IsInvalid())
  310. return false;
  311. // Store contact
  312. outContact = contact;
  313. // Fetch the face we're colliding with
  314. TransformedShape ts = mSystem->GetBodyInterface().GetTransformedShape(outContact.mBodyB);
  315. Shape::SupportingFace face;
  316. ts.GetSupportingFace(outContact.mSubShapeIDB, -outContact.mContactNormal, start.GetTranslation(), face);
  317. bool corrected = false;
  318. if (face.size() >= 2)
  319. {
  320. // Inflate the colliding face by the character padding
  321. PolygonConvexSupport polygon(face);
  322. AddConvexRadius add_cvx(polygon, mCharacterPadding);
  323. // Correct fraction to hit this inflated face instead of the inner shape
  324. corrected = sCorrectFractionForCharacterPadding(mShape, start.GetRotation(), inDisplacement, add_cvx, outContact.mFraction);
  325. }
  326. if (!corrected)
  327. {
  328. // When there's only a single contact point or when we were unable to correct the fraction,
  329. // we can just move the fraction back so that the character and its padding don't hit the contact point anymore
  330. outContact.mFraction = max(0.0f, outContact.mFraction - character_padding_fraction);
  331. }
  332. // Ensure that we never return a fraction that's bigger than 1 (which could happen due to float precision issues).
  333. outContact.mFraction = min(outContact.mFraction, 1.0f);
  334. return true;
  335. }
  336. void CharacterVirtual::DetermineConstraints(TempContactList &inContacts, float inDeltaTime, ConstraintList &outConstraints) const
  337. {
  338. for (Contact &c : inContacts)
  339. {
  340. Vec3 contact_velocity = c.mLinearVelocity;
  341. // Penetrating contact: Add a contact velocity that pushes the character out at the desired speed
  342. if (c.mDistance < 0.0f)
  343. contact_velocity -= c.mContactNormal * c.mDistance * mPenetrationRecoverySpeed / inDeltaTime;
  344. // Convert to a constraint
  345. outConstraints.emplace_back();
  346. Constraint &constraint = outConstraints.back();
  347. constraint.mContact = &c;
  348. constraint.mLinearVelocity = contact_velocity;
  349. constraint.mPlane = Plane(c.mContactNormal, c.mDistance);
  350. // Next check if the angle is too steep and if it is add an additional constraint that holds the character back
  351. if (IsSlopeTooSteep(c.mSurfaceNormal))
  352. {
  353. // Only take planes that point up.
  354. // Note that we use the contact normal to allow for better sliding as the surface normal may be in the opposite direction of movement.
  355. float dot = c.mContactNormal.Dot(mUp);
  356. if (dot > 1.0e-3f) // Add a little slack, if the normal is perfectly horizontal we already have our vertical plane.
  357. {
  358. // Mark the slope constraint as steep
  359. constraint.mIsSteepSlope = true;
  360. // Make horizontal normal
  361. Vec3 normal = (c.mContactNormal - dot * mUp).Normalized();
  362. // Create a secondary constraint that blocks horizontal movement
  363. outConstraints.emplace_back();
  364. Constraint &vertical_constraint = outConstraints.back();
  365. vertical_constraint.mContact = &c;
  366. vertical_constraint.mLinearVelocity = contact_velocity.Dot(normal) * normal; // Project the contact velocity on the new normal so that both planes push at an equal rate
  367. vertical_constraint.mPlane = Plane(normal, c.mDistance / normal.Dot(c.mContactNormal)); // Calculate the distance we have to travel horizontally to hit the contact plane
  368. }
  369. }
  370. }
  371. }
  372. bool CharacterVirtual::HandleContact(Vec3Arg inVelocity, Constraint &ioConstraint, float inDeltaTime) const
  373. {
  374. Contact &contact = *ioConstraint.mContact;
  375. // Validate the contact point
  376. if (!ValidateContact(contact))
  377. return false;
  378. // Send contact added event
  379. CharacterContactSettings settings;
  380. if (mListener != nullptr)
  381. mListener->OnContactAdded(this, contact.mBodyB, contact.mSubShapeIDB, contact.mPosition, -contact.mContactNormal, settings);
  382. contact.mCanPushCharacter = settings.mCanPushCharacter;
  383. // If body B cannot receive an impulse, we're done
  384. if (!settings.mCanReceiveImpulses || contact.mMotionTypeB != EMotionType::Dynamic)
  385. return true;
  386. // Lock the body we're colliding with
  387. BodyLockWrite lock(mSystem->GetBodyLockInterface(), contact.mBodyB);
  388. if (!lock.SucceededAndIsInBroadPhase())
  389. return false; // Body has been removed, we should not collide with it anymore
  390. const Body &body = lock.GetBody();
  391. // Calculate the velocity that we want to apply at B so that it will start moving at the character's speed at the contact point
  392. constexpr float cDamping = 0.9f;
  393. constexpr float cPenetrationResolution = 0.4f;
  394. Vec3 relative_velocity = inVelocity - contact.mLinearVelocity;
  395. float projected_velocity = relative_velocity.Dot(contact.mContactNormal);
  396. float delta_velocity = -projected_velocity * cDamping - min(contact.mDistance, 0.0f) * cPenetrationResolution / inDeltaTime;
  397. // Don't apply impulses if we're separating
  398. if (delta_velocity < 0.0f)
  399. return true;
  400. // Determine mass properties of the body we're colliding with
  401. const MotionProperties *motion_properties = body.GetMotionProperties();
  402. RVec3 center_of_mass = body.GetCenterOfMassPosition();
  403. Mat44 inverse_inertia = body.GetInverseInertia();
  404. float inverse_mass = motion_properties->GetInverseMass();
  405. // Calculate the inverse of the mass of body B as seen at the contact point in the direction of the contact normal
  406. Vec3 jacobian = Vec3(contact.mPosition - center_of_mass).Cross(contact.mContactNormal);
  407. float inv_effective_mass = inverse_inertia.Multiply3x3(jacobian).Dot(jacobian) + inverse_mass;
  408. // Impulse P = M dv
  409. float impulse = delta_velocity / inv_effective_mass;
  410. // Clamp the impulse according to the character strength, character strength is a force in newtons, P = F dt
  411. float max_impulse = mMaxStrength * inDeltaTime;
  412. impulse = min(impulse, max_impulse);
  413. // Calculate the world space impulse to apply
  414. Vec3 world_impulse = -impulse * contact.mContactNormal;
  415. // Cancel impulse in down direction (we apply gravity later)
  416. float impulse_dot_up = world_impulse.Dot(mUp);
  417. if (impulse_dot_up < 0.0f)
  418. world_impulse -= impulse_dot_up * mUp;
  419. // Now apply the impulse (body is already locked so we use the no-lock interface)
  420. mSystem->GetBodyInterfaceNoLock().AddImpulse(contact.mBodyB, world_impulse, contact.mPosition);
  421. return true;
  422. }
  423. void CharacterVirtual::SolveConstraints(Vec3Arg inVelocity, float inDeltaTime, float inTimeRemaining, ConstraintList &ioConstraints, IgnoredContactList &ioIgnoredContacts, float &outTimeSimulated, Vec3 &outDisplacement, TempAllocator &inAllocator
  424. #ifdef JPH_DEBUG_RENDERER
  425. , bool inDrawConstraints
  426. #endif // JPH_DEBUG_RENDERER
  427. ) const
  428. {
  429. // If there are no constraints we can immediately move to our target
  430. if (ioConstraints.empty())
  431. {
  432. outDisplacement = inVelocity * inTimeRemaining;
  433. outTimeSimulated = inTimeRemaining;
  434. return;
  435. }
  436. // Create array that holds the constraints in order of time of impact (sort will happen later)
  437. std::vector<Constraint *, STLTempAllocator<Constraint *>> sorted_constraints(inAllocator);
  438. sorted_constraints.resize(ioConstraints.size());
  439. for (size_t index = 0; index < sorted_constraints.size(); index++)
  440. sorted_constraints[index] = &ioConstraints[index];
  441. // This is the velocity we use for the displacement, if we hit something it will be shortened
  442. Vec3 velocity = inVelocity;
  443. // Keep track of the last velocity that was applied to the character so that we can detect when the velocity reverses
  444. Vec3 last_velocity = inVelocity;
  445. // Start with no displacement
  446. outDisplacement = Vec3::sZero();
  447. outTimeSimulated = 0.0f;
  448. // These are the contacts that we hit previously without moving a significant distance
  449. std::vector<Constraint *, STLTempAllocator<Constraint *>> previous_contacts(inAllocator);
  450. previous_contacts.resize(mMaxConstraintIterations);
  451. int num_previous_contacts = 0;
  452. // Loop for a max amount of iterations
  453. for (uint iteration = 0; iteration < mMaxConstraintIterations; iteration++)
  454. {
  455. // Calculate time of impact for all constraints
  456. for (Constraint &c : ioConstraints)
  457. {
  458. // Project velocity on plane direction
  459. c.mProjectedVelocity = c.mPlane.GetNormal().Dot(c.mLinearVelocity - velocity);
  460. if (c.mProjectedVelocity < 1.0e-6f)
  461. {
  462. c.mTOI = FLT_MAX;
  463. }
  464. else
  465. {
  466. // Distance to plane
  467. float dist = c.mPlane.SignedDistance(outDisplacement);
  468. if (dist - c.mProjectedVelocity * inTimeRemaining > -1.0e-4f)
  469. {
  470. // Too little penetration, accept the movement
  471. c.mTOI = FLT_MAX;
  472. }
  473. else
  474. {
  475. // Calculate time of impact
  476. c.mTOI = max(0.0f, dist / c.mProjectedVelocity);
  477. }
  478. }
  479. }
  480. // Sort constraints on proximity
  481. QuickSort(sorted_constraints.begin(), sorted_constraints.end(), [](const Constraint *inLHS, const Constraint *inRHS) {
  482. // If both constraints hit at t = 0 then order the one that will push the character furthest first
  483. // Note that because we add velocity to penetrating contacts, this will also resolve contacts that penetrate the most
  484. if (inLHS->mTOI <= 0.0f && inRHS->mTOI <= 0.0f)
  485. return inLHS->mProjectedVelocity > inRHS->mProjectedVelocity;
  486. // Then sort on time of impact
  487. if (inLHS->mTOI != inRHS->mTOI)
  488. return inLHS->mTOI < inRHS->mTOI;
  489. // As a tie breaker sort static first so it has the most influence
  490. return inLHS->mContact->mMotionTypeB > inRHS->mContact->mMotionTypeB;
  491. });
  492. // Find the first valid constraint
  493. Constraint *constraint = nullptr;
  494. for (Constraint *c : sorted_constraints)
  495. {
  496. // Take the first contact and see if we can reach it
  497. if (c->mTOI >= inTimeRemaining)
  498. {
  499. // We can reach our goal!
  500. outDisplacement += velocity * inTimeRemaining;
  501. outTimeSimulated += inTimeRemaining;
  502. return;
  503. }
  504. // Test if this contact was discarded by the contact callback before
  505. if (c->mContact->mWasDiscarded)
  506. continue;
  507. // Check if we made contact with this before
  508. if (!c->mContact->mHadCollision)
  509. {
  510. // Handle the contact
  511. if (!HandleContact(velocity, *c, inDeltaTime))
  512. {
  513. // Constraint should be ignored, remove it from the list
  514. c->mContact->mWasDiscarded = true;
  515. // Mark it as ignored for GetFirstContactForSweep
  516. ioIgnoredContacts.emplace_back(c->mContact->mBodyB, c->mContact->mSubShapeIDB);
  517. continue;
  518. }
  519. c->mContact->mHadCollision = true;
  520. }
  521. // Cancel velocity of constraint if it cannot push the character
  522. if (!c->mContact->mCanPushCharacter)
  523. c->mLinearVelocity = Vec3::sZero();
  524. // We found the first constraint that we want to collide with
  525. constraint = c;
  526. break;
  527. }
  528. if (constraint == nullptr)
  529. {
  530. // All constraints were discarded, we can reach our goal!
  531. outDisplacement += velocity * inTimeRemaining;
  532. outTimeSimulated += inTimeRemaining;
  533. return;
  534. }
  535. // Move to the contact
  536. outDisplacement += velocity * constraint->mTOI;
  537. inTimeRemaining -= constraint->mTOI;
  538. outTimeSimulated += constraint->mTOI;
  539. // If there's not enough time left to be simulated, bail
  540. if (inTimeRemaining < mMinTimeRemaining)
  541. return;
  542. // If we've moved significantly, clear all previous contacts
  543. if (constraint->mTOI > 1.0e-4f)
  544. num_previous_contacts = 0;
  545. // Get the normal of the plane we're hitting
  546. Vec3 plane_normal = constraint->mPlane.GetNormal();
  547. // If we're hitting a steep slope we cancel the velocity towards the slope first so that we don't end up slidinng up the slope
  548. // (we may hit the slope before the vertical wall constraint we added which will result in a small movement up causing jitter in the character movement)
  549. if (constraint->mIsSteepSlope)
  550. {
  551. // We're hitting a steep slope, create a vertical plane that blocks any further movement up the slope (note: not normalized)
  552. Vec3 vertical_plane_normal = plane_normal - plane_normal.Dot(mUp) * mUp;
  553. // Get the relative velocity between the character and the constraint
  554. Vec3 relative_velocity = velocity - constraint->mLinearVelocity;
  555. // Remove velocity towards the slope
  556. velocity = velocity - min(0.0f, relative_velocity.Dot(vertical_plane_normal)) * vertical_plane_normal / vertical_plane_normal.LengthSq();
  557. }
  558. // Get the relative velocity between the character and the constraint
  559. Vec3 relative_velocity = velocity - constraint->mLinearVelocity;
  560. // Calculate new velocity if we cancel the relative velocity in the normal direction
  561. Vec3 new_velocity = velocity - relative_velocity.Dot(plane_normal) * plane_normal;
  562. // Find the normal of the previous contact that we will violate the most if we move in this new direction
  563. float highest_penetration = 0.0f;
  564. Constraint *other_constraint = nullptr;
  565. for (Constraint **c = previous_contacts.data(); c < previous_contacts.data() + num_previous_contacts; ++c)
  566. if (*c != constraint)
  567. {
  568. // Calculate how much we will penetrate if we move in this direction
  569. Vec3 other_normal = (*c)->mPlane.GetNormal();
  570. float penetration = ((*c)->mLinearVelocity - new_velocity).Dot(other_normal);
  571. if (penetration > highest_penetration)
  572. {
  573. // We don't want parallel or anti-parallel normals as that will cause our cross product below to become zero. Slack is approx 10 degrees.
  574. float dot = other_normal.Dot(plane_normal);
  575. if (dot < 0.984f && dot > -0.984f)
  576. {
  577. highest_penetration = penetration;
  578. other_constraint = *c;
  579. }
  580. }
  581. }
  582. // Check if we found a 2nd constraint
  583. if (other_constraint != nullptr)
  584. {
  585. // Calculate the sliding direction and project the new velocity onto that sliding direction
  586. Vec3 other_normal = other_constraint->mPlane.GetNormal();
  587. Vec3 slide_dir = plane_normal.Cross(other_normal).Normalized();
  588. Vec3 velocity_in_slide_dir = new_velocity.Dot(slide_dir) * slide_dir;
  589. // Cancel the constraint velocity in the other constraint plane's direction so that we won't try to apply it again and keep ping ponging between planes
  590. constraint->mLinearVelocity -= min(0.0f, constraint->mLinearVelocity.Dot(other_normal)) * other_normal;
  591. // Cancel the other constraints velocity in this constraint plane's direction so that we won't try to apply it again and keep ping ponging between planes
  592. other_constraint->mLinearVelocity -= min(0.0f, other_constraint->mLinearVelocity.Dot(plane_normal)) * plane_normal;
  593. // Calculate the velocity of this constraint perpendicular to the slide direction
  594. Vec3 perpendicular_velocity = constraint->mLinearVelocity - constraint->mLinearVelocity.Dot(slide_dir) * slide_dir;
  595. // Calculate the velocity of the other constraint perpendicular to the slide direction
  596. Vec3 other_perpendicular_velocity = other_constraint->mLinearVelocity - other_constraint->mLinearVelocity.Dot(slide_dir) * slide_dir;
  597. // Add all components together
  598. new_velocity = velocity_in_slide_dir + perpendicular_velocity + other_perpendicular_velocity;
  599. }
  600. // Allow application to modify calculated velocity
  601. if (mListener != nullptr)
  602. mListener->OnContactSolve(this, constraint->mContact->mBodyB, constraint->mContact->mSubShapeIDB, constraint->mContact->mPosition, constraint->mContact->mContactNormal, constraint->mContact->mLinearVelocity, constraint->mContact->mMaterial, velocity, new_velocity);
  603. #ifdef JPH_DEBUG_RENDERER
  604. if (inDrawConstraints)
  605. {
  606. // Calculate where to draw
  607. RVec3 offset = mPosition + Vec3(0, 0, 2.5f * (iteration + 1));
  608. // Draw constraint plane
  609. DebugRenderer::sInstance->DrawPlane(offset, constraint->mPlane.GetNormal(), Color::sCyan, 1.0f);
  610. // Draw 2nd constraint plane
  611. if (other_constraint != nullptr)
  612. DebugRenderer::sInstance->DrawPlane(offset, other_constraint->mPlane.GetNormal(), Color::sBlue, 1.0f);
  613. // Draw starting velocity
  614. DebugRenderer::sInstance->DrawArrow(offset, offset + velocity, Color::sGreen, 0.05f);
  615. // Draw resulting velocity
  616. DebugRenderer::sInstance->DrawArrow(offset, offset + new_velocity, Color::sRed, 0.05f);
  617. }
  618. #endif // JPH_DEBUG_RENDERER
  619. // Update the velocity
  620. velocity = new_velocity;
  621. // Add the contact to the list so that next iteration we can avoid violating it again
  622. previous_contacts[num_previous_contacts] = constraint;
  623. num_previous_contacts++;
  624. // Check early out
  625. if (constraint->mProjectedVelocity < 1.0e-8f // Constraint should not be pushing, otherwise there may be other constraints that are pushing us
  626. && velocity.LengthSq() < 1.0e-8f) // There's not enough velocity left
  627. return;
  628. // If the constraint has velocity we accept the new velocity, otherwise check that we didn't reverse velocity
  629. if (!constraint->mLinearVelocity.IsNearZero(1.0e-8f))
  630. last_velocity = constraint->mLinearVelocity;
  631. else if (velocity.Dot(last_velocity) < 0.0f)
  632. return;
  633. }
  634. }
  635. void CharacterVirtual::UpdateSupportingContact(bool inSkipContactVelocityCheck, TempAllocator &inAllocator)
  636. {
  637. // Flag contacts as having a collision if they're close enough but ignore contacts we're moving away from.
  638. // Note that if we did MoveShape before we want to preserve any contacts that it marked as colliding
  639. for (Contact &c : mActiveContacts)
  640. if (!c.mWasDiscarded
  641. && !c.mHadCollision
  642. && c.mDistance < mCollisionTolerance
  643. && (inSkipContactVelocityCheck || c.mSurfaceNormal.Dot(mLinearVelocity - c.mLinearVelocity) <= 1.0e-4f))
  644. {
  645. if (ValidateContact(c))
  646. c.mHadCollision = true;
  647. else
  648. c.mWasDiscarded = true;
  649. }
  650. // Calculate transform that takes us to character local space
  651. RMat44 inv_transform = RMat44::sInverseRotationTranslation(mRotation, mPosition);
  652. // Determine if we're supported or not
  653. int num_supported = 0;
  654. int num_sliding = 0;
  655. int num_avg_normal = 0;
  656. Vec3 avg_normal = Vec3::sZero();
  657. Vec3 avg_velocity = Vec3::sZero();
  658. const Contact *supporting_contact = nullptr;
  659. float max_cos_angle = -FLT_MAX;
  660. const Contact *deepest_contact = nullptr;
  661. float smallest_distance = FLT_MAX;
  662. for (const Contact &c : mActiveContacts)
  663. if (c.mHadCollision)
  664. {
  665. // Calculate the angle between the plane normal and the up direction
  666. float cos_angle = c.mSurfaceNormal.Dot(mUp);
  667. // Find the deepest contact
  668. if (c.mDistance < smallest_distance)
  669. {
  670. deepest_contact = &c;
  671. smallest_distance = c.mDistance;
  672. }
  673. // If this contact is in front of our plane, we cannot be supported by it
  674. if (mSupportingVolume.SignedDistance(Vec3(inv_transform * c.mPosition)) > 0.0f)
  675. continue;
  676. // Find the contact with the normal that is pointing most upwards and store it
  677. if (max_cos_angle < cos_angle)
  678. {
  679. supporting_contact = &c;
  680. max_cos_angle = cos_angle;
  681. }
  682. // Check if this is a sliding or supported contact
  683. bool is_supported = mCosMaxSlopeAngle > cNoMaxSlopeAngle || cos_angle >= mCosMaxSlopeAngle;
  684. if (is_supported)
  685. num_supported++;
  686. else
  687. num_sliding++;
  688. // If the angle between the two is less than 85 degrees we also use it to calculate the average normal
  689. if (cos_angle >= 0.08f)
  690. {
  691. avg_normal += c.mSurfaceNormal;
  692. num_avg_normal++;
  693. // For static or dynamic objects or for contacts that don't support us just take the contact velocity
  694. if (c.mMotionTypeB != EMotionType::Kinematic || !is_supported)
  695. avg_velocity += c.mLinearVelocity;
  696. else
  697. {
  698. // For keyframed objects that support us calculate the velocity at our position rather than at the contact position so that we properly follow the object
  699. BodyLockRead lock(mSystem->GetBodyLockInterface(), c.mBodyB);
  700. if (lock.SucceededAndIsInBroadPhase())
  701. {
  702. const Body &body = lock.GetBody();
  703. // Get adjusted body velocity
  704. Vec3 linear_velocity, angular_velocity;
  705. GetAdjustedBodyVelocity(body, linear_velocity, angular_velocity);
  706. // Calculate the ground velocity
  707. avg_velocity += CalculateCharacterGroundVelocity(body.GetCenterOfMassPosition(), linear_velocity, angular_velocity, mLastDeltaTime);
  708. }
  709. else
  710. {
  711. // Fall back to contact velocity
  712. avg_velocity += c.mLinearVelocity;
  713. }
  714. }
  715. }
  716. }
  717. // Take either the most supporting contact or the deepest contact
  718. const Contact *best_contact = supporting_contact != nullptr? supporting_contact : deepest_contact;
  719. // Calculate average normal and velocity
  720. if (num_avg_normal >= 1)
  721. {
  722. mGroundNormal = avg_normal.Normalized();
  723. mGroundVelocity = avg_velocity / float(num_avg_normal);
  724. }
  725. else if (best_contact != nullptr)
  726. {
  727. mGroundNormal = best_contact->mSurfaceNormal;
  728. mGroundVelocity = best_contact->mLinearVelocity;
  729. }
  730. else
  731. {
  732. mGroundNormal = Vec3::sZero();
  733. mGroundVelocity = Vec3::sZero();
  734. }
  735. // Copy contact properties
  736. if (best_contact != nullptr)
  737. {
  738. mGroundBodyID = best_contact->mBodyB;
  739. mGroundBodySubShapeID = best_contact->mSubShapeIDB;
  740. mGroundPosition = best_contact->mPosition;
  741. mGroundMaterial = best_contact->mMaterial;
  742. mGroundUserData = best_contact->mUserData;
  743. }
  744. else
  745. {
  746. mGroundBodyID = BodyID();
  747. mGroundBodySubShapeID = SubShapeID();
  748. mGroundPosition = RVec3::sZero();
  749. mGroundMaterial = PhysicsMaterial::sDefault;
  750. mGroundUserData = 0;
  751. }
  752. // Determine ground state
  753. if (num_supported > 0)
  754. {
  755. // We made contact with something that supports us
  756. mGroundState = EGroundState::OnGround;
  757. }
  758. else if (num_sliding > 0)
  759. {
  760. if ((mLinearVelocity - deepest_contact->mLinearVelocity).Dot(mUp) > 1.0e-4f)
  761. {
  762. // We cannot be on ground if we're moving upwards relative to the ground
  763. mGroundState = EGroundState::OnSteepGround;
  764. }
  765. else
  766. {
  767. // If we're sliding down, we may actually be standing on multiple sliding contacts in such a way that we can't slide off, in this case we're also supported
  768. // Convert the contacts into constraints
  769. TempContactList contacts(mActiveContacts.begin(), mActiveContacts.end(), inAllocator);
  770. ConstraintList constraints(inAllocator);
  771. constraints.reserve(contacts.size() * 2);
  772. DetermineConstraints(contacts, mLastDeltaTime, constraints);
  773. // Solve the displacement using these constraints, this is used to check if we didn't move at all because we are supported
  774. Vec3 displacement;
  775. float time_simulated;
  776. IgnoredContactList ignored_contacts(inAllocator);
  777. ignored_contacts.reserve(contacts.size());
  778. SolveConstraints(-mUp, 1.0f, 1.0f, constraints, ignored_contacts, time_simulated, displacement, inAllocator);
  779. // If we're blocked then we're supported, otherwise we're sliding
  780. float min_required_displacement_sq = Square(0.6f * mLastDeltaTime);
  781. if (time_simulated < 0.001f || displacement.LengthSq() < min_required_displacement_sq)
  782. mGroundState = EGroundState::OnGround;
  783. else
  784. mGroundState = EGroundState::OnSteepGround;
  785. }
  786. }
  787. else
  788. {
  789. // Not supported by anything
  790. mGroundState = best_contact != nullptr? EGroundState::NotSupported : EGroundState::InAir;
  791. }
  792. }
  793. void CharacterVirtual::StoreActiveContacts(const TempContactList &inContacts, TempAllocator &inAllocator)
  794. {
  795. mActiveContacts.assign(inContacts.begin(), inContacts.end());
  796. UpdateSupportingContact(true, inAllocator);
  797. }
  798. void CharacterVirtual::MoveShape(RVec3 &ioPosition, Vec3Arg inVelocity, float inDeltaTime, ContactList *outActiveContacts, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator
  799. #ifdef JPH_DEBUG_RENDERER
  800. , bool inDrawConstraints
  801. #endif // JPH_DEBUG_RENDERER
  802. ) const
  803. {
  804. Vec3 movement_direction = inVelocity.NormalizedOr(Vec3::sZero());
  805. float time_remaining = inDeltaTime;
  806. for (uint iteration = 0; iteration < mMaxCollisionIterations && time_remaining >= mMinTimeRemaining; iteration++)
  807. {
  808. // Determine contacts in the neighborhood
  809. TempContactList contacts(inAllocator);
  810. contacts.reserve(mMaxNumHits);
  811. GetContactsAtPosition(ioPosition, movement_direction, mShape, contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  812. // Remove contacts with the same body that have conflicting normals
  813. IgnoredContactList ignored_contacts(inAllocator);
  814. ignored_contacts.reserve(contacts.size());
  815. RemoveConflictingContacts(contacts, ignored_contacts);
  816. // Convert contacts into constraints
  817. ConstraintList constraints(inAllocator);
  818. constraints.reserve(contacts.size() * 2);
  819. DetermineConstraints(contacts, inDeltaTime, constraints);
  820. #ifdef JPH_DEBUG_RENDERER
  821. bool draw_constraints = inDrawConstraints && iteration == 0;
  822. if (draw_constraints)
  823. {
  824. for (const Constraint &c : constraints)
  825. {
  826. // Draw contact point
  827. DebugRenderer::sInstance->DrawMarker(c.mContact->mPosition, Color::sYellow, 0.05f);
  828. Vec3 dist_to_plane = -c.mPlane.GetConstant() * c.mPlane.GetNormal();
  829. // Draw arrow towards surface that we're hitting
  830. DebugRenderer::sInstance->DrawArrow(c.mContact->mPosition, c.mContact->mPosition - dist_to_plane, Color::sYellow, 0.05f);
  831. // Draw plane around the player position indicating the space that we can move
  832. DebugRenderer::sInstance->DrawPlane(mPosition + dist_to_plane, c.mPlane.GetNormal(), Color::sCyan, 1.0f);
  833. DebugRenderer::sInstance->DrawArrow(mPosition + dist_to_plane, mPosition + dist_to_plane + c.mContact->mSurfaceNormal, Color::sRed, 0.05f);
  834. }
  835. }
  836. #endif // JPH_DEBUG_RENDERER
  837. // Solve the displacement using these constraints
  838. Vec3 displacement;
  839. float time_simulated;
  840. SolveConstraints(inVelocity, inDeltaTime, time_remaining, constraints, ignored_contacts, time_simulated, displacement, inAllocator
  841. #ifdef JPH_DEBUG_RENDERER
  842. , draw_constraints
  843. #endif // JPH_DEBUG_RENDERER
  844. );
  845. // Store the contacts now that the colliding ones have been marked
  846. if (outActiveContacts != nullptr)
  847. outActiveContacts->assign(contacts.begin(), contacts.end());
  848. // Do a sweep to test if the path is really unobstructed
  849. Contact cast_contact;
  850. if (GetFirstContactForSweep(ioPosition, displacement, cast_contact, ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))
  851. {
  852. displacement *= cast_contact.mFraction;
  853. time_simulated *= cast_contact.mFraction;
  854. }
  855. // Update the position
  856. ioPosition += displacement;
  857. time_remaining -= time_simulated;
  858. // If the displacement during this iteration was too small we assume we cannot further progress this update
  859. if (displacement.LengthSq() < 1.0e-8f)
  860. break;
  861. }
  862. }
  863. Vec3 CharacterVirtual::CancelVelocityTowardsSteepSlopes(Vec3Arg inDesiredVelocity) const
  864. {
  865. // If we're not pushing against a steep slope, return the desired velocity
  866. // Note: This is important as WalkStairs overrides the ground state to OnGround when its first check fails but the second succeeds
  867. if (mGroundState == CharacterVirtual::EGroundState::OnGround
  868. || mGroundState == CharacterVirtual::EGroundState::InAir)
  869. return inDesiredVelocity;
  870. Vec3 desired_velocity = inDesiredVelocity;
  871. for (const Contact &c : mActiveContacts)
  872. if (c.mHadCollision
  873. && IsSlopeTooSteep(c.mSurfaceNormal))
  874. {
  875. // Note that we use the contact normal to allow for better sliding as the surface normal may be in the opposite direction of movement.
  876. Vec3 normal = c.mContactNormal;
  877. // Remove normal vertical component
  878. normal -= normal.Dot(mUp) * mUp;
  879. // Cancel horizontal movement in opposite direction
  880. float dot = normal.Dot(desired_velocity);
  881. if (dot < 0.0f)
  882. desired_velocity -= (dot * normal) / normal.LengthSq();
  883. }
  884. return desired_velocity;
  885. }
  886. void CharacterVirtual::Update(float inDeltaTime, Vec3Arg inGravity, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  887. {
  888. // If there's no delta time, we don't need to do anything
  889. if (inDeltaTime <= 0.0f)
  890. return;
  891. // Remember delta time for checking if we're supported by the ground
  892. mLastDeltaTime = inDeltaTime;
  893. // Slide the shape through the world
  894. MoveShape(mPosition, mLinearVelocity, inDeltaTime, &mActiveContacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator
  895. #ifdef JPH_DEBUG_RENDERER
  896. , sDrawConstraints
  897. #endif // JPH_DEBUG_RENDERER
  898. );
  899. // Determine the object that we're standing on
  900. UpdateSupportingContact(false, inAllocator);
  901. // If we're on the ground
  902. if (!mGroundBodyID.IsInvalid() && mMass > 0.0f)
  903. {
  904. // Add the impulse to the ground due to gravity: P = F dt = M g dt
  905. float normal_dot_gravity = mGroundNormal.Dot(inGravity);
  906. if (normal_dot_gravity < 0.0f)
  907. {
  908. Vec3 world_impulse = -(mMass * normal_dot_gravity / inGravity.Length() * inDeltaTime) * inGravity;
  909. mSystem->GetBodyInterface().AddImpulse(mGroundBodyID, world_impulse, mGroundPosition);
  910. }
  911. }
  912. }
  913. void CharacterVirtual::RefreshContacts(const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  914. {
  915. // Determine the contacts
  916. TempContactList contacts(inAllocator);
  917. contacts.reserve(mMaxNumHits);
  918. GetContactsAtPosition(mPosition, mLinearVelocity.NormalizedOr(Vec3::sZero()), mShape, contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  919. StoreActiveContacts(contacts, inAllocator);
  920. }
  921. void CharacterVirtual::UpdateGroundVelocity()
  922. {
  923. BodyLockRead lock(mSystem->GetBodyLockInterface(), mGroundBodyID);
  924. if (lock.SucceededAndIsInBroadPhase())
  925. {
  926. const Body &body = lock.GetBody();
  927. // Get adjusted body velocity
  928. Vec3 linear_velocity, angular_velocity;
  929. GetAdjustedBodyVelocity(body, linear_velocity, angular_velocity);
  930. // Calculate the ground velocity
  931. mGroundVelocity = CalculateCharacterGroundVelocity(body.GetCenterOfMassPosition(), linear_velocity, angular_velocity, mLastDeltaTime);
  932. }
  933. }
  934. void CharacterVirtual::MoveToContact(RVec3Arg inPosition, const Contact &inContact, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  935. {
  936. // Set the new position
  937. SetPosition(inPosition);
  938. // Determine the contacts
  939. TempContactList contacts(inAllocator);
  940. contacts.reserve(mMaxNumHits + 1); // +1 because we can add one extra below
  941. GetContactsAtPosition(mPosition, mLinearVelocity.NormalizedOr(Vec3::sZero()), mShape, contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  942. // Ensure that we mark inContact as colliding
  943. bool found_contact = false;
  944. for (Contact &c : contacts)
  945. if (c.mBodyB == inContact.mBodyB
  946. && c.mSubShapeIDB == inContact.mSubShapeIDB)
  947. {
  948. c.mHadCollision = true;
  949. found_contact = true;
  950. }
  951. if (!found_contact)
  952. {
  953. contacts.push_back(inContact);
  954. Contact &copy = contacts.back();
  955. copy.mHadCollision = true;
  956. }
  957. StoreActiveContacts(contacts, inAllocator);
  958. JPH_ASSERT(mGroundState != EGroundState::InAir);
  959. }
  960. bool CharacterVirtual::SetShape(const Shape *inShape, float inMaxPenetrationDepth, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  961. {
  962. if (mShape == nullptr || mSystem == nullptr)
  963. {
  964. // It hasn't been initialized yet
  965. mShape = inShape;
  966. return true;
  967. }
  968. if (inShape != mShape && inShape != nullptr)
  969. {
  970. if (inMaxPenetrationDepth < FLT_MAX)
  971. {
  972. // Check collision around the new shape
  973. TempContactList contacts(inAllocator);
  974. contacts.reserve(mMaxNumHits);
  975. GetContactsAtPosition(mPosition, mLinearVelocity.NormalizedOr(Vec3::sZero()), inShape, contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter);
  976. // Test if this results in penetration, if so cancel the transition
  977. for (const Contact &c : contacts)
  978. if (c.mDistance < -inMaxPenetrationDepth)
  979. return false;
  980. StoreActiveContacts(contacts, inAllocator);
  981. }
  982. // Set new shape
  983. mShape = inShape;
  984. }
  985. return mShape == inShape;
  986. }
  987. bool CharacterVirtual::CanWalkStairs(Vec3Arg inLinearVelocity) const
  988. {
  989. // We can only walk stairs if we're supported
  990. if (!IsSupported())
  991. return false;
  992. // Check if there's enough horizontal velocity to trigger a stair walk
  993. Vec3 horizontal_velocity = inLinearVelocity - inLinearVelocity.Dot(mUp) * mUp;
  994. if (horizontal_velocity.IsNearZero(1.0e-6f))
  995. return false;
  996. // Check contacts for steep slopes
  997. for (const Contact &c : mActiveContacts)
  998. if (c.mHadCollision
  999. && c.mSurfaceNormal.Dot(horizontal_velocity - c.mLinearVelocity) < 0.0f // Pushing into the contact
  1000. && IsSlopeTooSteep(c.mSurfaceNormal)) // Slope too steep
  1001. return true;
  1002. return false;
  1003. }
  1004. bool CharacterVirtual::WalkStairs(float inDeltaTime, Vec3Arg inStepUp, Vec3Arg inStepForward, Vec3Arg inStepForwardTest, Vec3Arg inStepDownExtra, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  1005. {
  1006. // Move up
  1007. Vec3 up = inStepUp;
  1008. Contact contact;
  1009. IgnoredContactList dummy_ignored_contacts(inAllocator);
  1010. if (GetFirstContactForSweep(mPosition, up, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))
  1011. {
  1012. if (contact.mFraction < 1.0e-6f)
  1013. return false; // No movement, cancel
  1014. // Limit up movement to the first contact point
  1015. up *= contact.mFraction;
  1016. }
  1017. RVec3 up_position = mPosition + up;
  1018. #ifdef JPH_DEBUG_RENDERER
  1019. // Draw sweep up
  1020. if (sDrawWalkStairs)
  1021. DebugRenderer::sInstance->DrawArrow(mPosition, up_position, Color::sWhite, 0.01f);
  1022. #endif // JPH_DEBUG_RENDERER
  1023. // Collect normals of steep slopes that we would like to walk stairs on.
  1024. // We need to do this before calling MoveShape because it will update mActiveContacts.
  1025. Vec3 character_velocity = inStepForward / inDeltaTime;
  1026. Vec3 horizontal_velocity = character_velocity - character_velocity.Dot(mUp) * mUp;
  1027. std::vector<Vec3, STLTempAllocator<Vec3>> steep_slope_normals(inAllocator);
  1028. steep_slope_normals.reserve(mActiveContacts.size());
  1029. for (const Contact &c : mActiveContacts)
  1030. if (c.mHadCollision
  1031. && c.mSurfaceNormal.Dot(horizontal_velocity - c.mLinearVelocity) < 0.0f // Pushing into the contact
  1032. && IsSlopeTooSteep(c.mSurfaceNormal)) // Slope too steep
  1033. steep_slope_normals.push_back(c.mSurfaceNormal);
  1034. if (steep_slope_normals.empty())
  1035. return false; // No steep slopes, cancel
  1036. // Horizontal movement
  1037. RVec3 new_position = up_position;
  1038. MoveShape(new_position, character_velocity, inDeltaTime, nullptr, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1039. Vec3 horizontal_movement = Vec3(new_position - up_position);
  1040. float horizontal_movement_sq = horizontal_movement.LengthSq();
  1041. if (horizontal_movement_sq < 1.0e-8f)
  1042. return false; // No movement, cancel
  1043. // Check if we made any progress towards any of the steep slopes, if not we just slid along the slope
  1044. // so we need to cancel the stair walk or else we will move faster than we should as we've done
  1045. // normal movement first and then stair walk.
  1046. bool made_progress = false;
  1047. float max_dot = -0.05f * inStepForward.Length();
  1048. for (const Vec3 &normal : steep_slope_normals)
  1049. if (normal.Dot(horizontal_movement) < max_dot)
  1050. {
  1051. // We moved more than 5% of the forward step against a steep slope, accept this as progress
  1052. made_progress = true;
  1053. break;
  1054. }
  1055. if (!made_progress)
  1056. return false;
  1057. #ifdef JPH_DEBUG_RENDERER
  1058. // Draw horizontal sweep
  1059. if (sDrawWalkStairs)
  1060. DebugRenderer::sInstance->DrawArrow(up_position, new_position, Color::sWhite, 0.01f);
  1061. #endif // JPH_DEBUG_RENDERER
  1062. // Move down towards the floor.
  1063. // Note that we travel the same amount down as we travelled up with the specified extra
  1064. Vec3 down = -up + inStepDownExtra;
  1065. if (!GetFirstContactForSweep(new_position, down, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))
  1066. return false; // No floor found, we're in mid air, cancel stair walk
  1067. #ifdef JPH_DEBUG_RENDERER
  1068. // Draw sweep down
  1069. if (sDrawWalkStairs)
  1070. {
  1071. RVec3 debug_pos = new_position + contact.mFraction * down;
  1072. DebugRenderer::sInstance->DrawArrow(new_position, debug_pos, Color::sWhite, 0.01f);
  1073. DebugRenderer::sInstance->DrawArrow(contact.mPosition, contact.mPosition + contact.mSurfaceNormal, Color::sWhite, 0.01f);
  1074. mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(debug_pos, mRotation, mShape), Vec3::sReplicate(1.0f), Color::sWhite, false, true);
  1075. }
  1076. #endif // JPH_DEBUG_RENDERER
  1077. // Test for floor that will support the character
  1078. if (IsSlopeTooSteep(contact.mSurfaceNormal))
  1079. {
  1080. // If no test position was provided, we cancel the stair walk
  1081. if (inStepForwardTest.IsNearZero())
  1082. return false;
  1083. // Delta time may be very small, so it may be that we hit the edge of a step and the normal is too horizontal.
  1084. // In order to judge if the floor is flat further along the sweep, we test again for a floor at inStepForwardTest
  1085. // and check if the normal is valid there.
  1086. RVec3 test_position = up_position;
  1087. MoveShape(test_position, inStepForwardTest / inDeltaTime, inDeltaTime, nullptr, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1088. float test_horizontal_movement_sq = Vec3(test_position - up_position).LengthSq();
  1089. if (test_horizontal_movement_sq <= horizontal_movement_sq + 1.0e-8f)
  1090. return false; // We didn't move any further than in the previous test
  1091. #ifdef JPH_DEBUG_RENDERER
  1092. // Draw 2nd sweep horizontal
  1093. if (sDrawWalkStairs)
  1094. DebugRenderer::sInstance->DrawArrow(up_position, test_position, Color::sCyan, 0.01f);
  1095. #endif // JPH_DEBUG_RENDERER
  1096. // Then sweep down
  1097. Contact test_contact;
  1098. if (!GetFirstContactForSweep(test_position, down, test_contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))
  1099. return false;
  1100. #ifdef JPH_DEBUG_RENDERER
  1101. // Draw 2nd sweep down
  1102. if (sDrawWalkStairs)
  1103. {
  1104. RVec3 debug_pos = test_position + test_contact.mFraction * down;
  1105. DebugRenderer::sInstance->DrawArrow(test_position, debug_pos, Color::sCyan, 0.01f);
  1106. DebugRenderer::sInstance->DrawArrow(test_contact.mPosition, test_contact.mPosition + test_contact.mSurfaceNormal, Color::sCyan, 0.01f);
  1107. mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(debug_pos, mRotation, mShape), Vec3::sReplicate(1.0f), Color::sCyan, false, true);
  1108. }
  1109. #endif // JPH_DEBUG_RENDERER
  1110. if (IsSlopeTooSteep(test_contact.mSurfaceNormal))
  1111. return false;
  1112. }
  1113. // Calculate new down position
  1114. down *= contact.mFraction;
  1115. new_position += down;
  1116. // Move the character to the new location
  1117. MoveToContact(new_position, contact, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1118. // Override ground state to 'on ground', it is possible that the contact normal is too steep, but in this case the inStepForwardTest has found a contact normal that is not too steep
  1119. mGroundState = EGroundState::OnGround;
  1120. return true;
  1121. }
  1122. bool CharacterVirtual::StickToFloor(Vec3Arg inStepDown, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  1123. {
  1124. // Try to find the floor
  1125. Contact contact;
  1126. IgnoredContactList dummy_ignored_contacts(inAllocator);
  1127. if (!GetFirstContactForSweep(mPosition, inStepDown, contact, dummy_ignored_contacts, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter))
  1128. return false; // If no floor found, don't update our position
  1129. // Calculate new position
  1130. RVec3 new_position = mPosition + contact.mFraction * inStepDown;
  1131. #ifdef JPH_DEBUG_RENDERER
  1132. // Draw sweep down
  1133. if (sDrawStickToFloor)
  1134. {
  1135. DebugRenderer::sInstance->DrawArrow(mPosition, new_position, Color::sOrange, 0.01f);
  1136. mShape->Draw(DebugRenderer::sInstance, GetCenterOfMassTransform(new_position, mRotation, mShape), Vec3::sReplicate(1.0f), Color::sOrange, false, true);
  1137. }
  1138. #endif // JPH_DEBUG_RENDERER
  1139. // Move the character to the new location
  1140. MoveToContact(new_position, contact, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1141. return true;
  1142. }
  1143. void CharacterVirtual::ExtendedUpdate(float inDeltaTime, Vec3Arg inGravity, const ExtendedUpdateSettings &inSettings, const BroadPhaseLayerFilter &inBroadPhaseLayerFilter, const ObjectLayerFilter &inObjectLayerFilter, const BodyFilter &inBodyFilter, const ShapeFilter &inShapeFilter, TempAllocator &inAllocator)
  1144. {
  1145. // Update the velocity
  1146. Vec3 desired_velocity = mLinearVelocity;
  1147. mLinearVelocity = CancelVelocityTowardsSteepSlopes(desired_velocity);
  1148. // Remember old position
  1149. RVec3 old_position = mPosition;
  1150. // Track if on ground before the update
  1151. bool ground_to_air = IsSupported();
  1152. // Update the character position (instant, do not have to wait for physics update)
  1153. Update(inDeltaTime, inGravity, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1154. // ... and that we got into air after
  1155. if (IsSupported())
  1156. ground_to_air = false;
  1157. // If stick to floor enabled and we're going from supported to not supported
  1158. if (ground_to_air && !inSettings.mStickToFloorStepDown.IsNearZero())
  1159. {
  1160. // If we're not moving up, stick to the floor
  1161. float velocity = Vec3(mPosition - old_position).Dot(mUp) / inDeltaTime;
  1162. if (velocity <= 1.0e-6f)
  1163. StickToFloor(inSettings.mStickToFloorStepDown, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1164. }
  1165. // If walk stairs enabled
  1166. if (!inSettings.mWalkStairsStepUp.IsNearZero())
  1167. {
  1168. // Calculate how much we wanted to move horizontally
  1169. Vec3 desired_horizontal_step = desired_velocity * inDeltaTime;
  1170. desired_horizontal_step -= desired_horizontal_step.Dot(mUp) * mUp;
  1171. float desired_horizontal_step_len = desired_horizontal_step.Length();
  1172. if (desired_horizontal_step_len > 0.0f)
  1173. {
  1174. // Calculate how much we moved horizontally
  1175. Vec3 achieved_horizontal_step = Vec3(mPosition - old_position);
  1176. achieved_horizontal_step -= achieved_horizontal_step.Dot(mUp) * mUp;
  1177. // Only count movement in the direction of the desired movement
  1178. // (otherwise we find it ok if we're sliding downhill while we're trying to climb uphill)
  1179. Vec3 step_forward_normalized = desired_horizontal_step / desired_horizontal_step_len;
  1180. achieved_horizontal_step = max(0.0f, achieved_horizontal_step.Dot(step_forward_normalized)) * step_forward_normalized;
  1181. float achieved_horizontal_step_len = achieved_horizontal_step.Length();
  1182. // If we didn't move as far as we wanted and we're against a slope that's too steep
  1183. if (achieved_horizontal_step_len + 1.0e-4f < desired_horizontal_step_len
  1184. && CanWalkStairs(desired_velocity))
  1185. {
  1186. // Calculate how much we should step forward
  1187. // Note that we clamp the step forward to a minimum distance. This is done because at very high frame rates the delta time
  1188. // may be very small, causing a very small step forward. If the step becomes small enough, we may not move far enough
  1189. // horizontally to actually end up at the top of the step.
  1190. Vec3 step_forward = step_forward_normalized * max(inSettings.mWalkStairsMinStepForward, desired_horizontal_step_len - achieved_horizontal_step_len);
  1191. // Calculate how far to scan ahead for a floor. This is only used in case the floor normal at step_forward is too steep.
  1192. // In that case an additional check will be performed at this distance to check if that normal is not too steep.
  1193. // Start with the ground normal in the horizontal plane and normalizing it
  1194. Vec3 step_forward_test = -mGroundNormal;
  1195. step_forward_test -= step_forward_test.Dot(mUp) * mUp;
  1196. step_forward_test = step_forward_test.NormalizedOr(step_forward_normalized);
  1197. // If this normalized vector and the character forward vector is bigger than a preset angle, we use the character forward vector instead of the ground normal
  1198. // to do our forward test
  1199. if (step_forward_test.Dot(step_forward_normalized) < inSettings.mWalkStairsCosAngleForwardContact)
  1200. step_forward_test = step_forward_normalized;
  1201. // Calculate the correct magnitude for the test vector
  1202. step_forward_test *= inSettings.mWalkStairsStepForwardTest;
  1203. WalkStairs(inDeltaTime, inSettings.mWalkStairsStepUp, step_forward, step_forward_test, inSettings.mWalkStairsStepDownExtra, inBroadPhaseLayerFilter, inObjectLayerFilter, inBodyFilter, inShapeFilter, inAllocator);
  1204. }
  1205. }
  1206. }
  1207. }
  1208. void CharacterVirtual::Contact::SaveState(StateRecorder &inStream) const
  1209. {
  1210. inStream.Write(mPosition);
  1211. inStream.Write(mLinearVelocity);
  1212. inStream.Write(mContactNormal);
  1213. inStream.Write(mSurfaceNormal);
  1214. inStream.Write(mDistance);
  1215. inStream.Write(mFraction);
  1216. inStream.Write(mBodyB);
  1217. inStream.Write(mSubShapeIDB);
  1218. inStream.Write(mMotionTypeB);
  1219. inStream.Write(mHadCollision);
  1220. inStream.Write(mWasDiscarded);
  1221. inStream.Write(mCanPushCharacter);
  1222. // Cannot store user data (may be a pointer) and material
  1223. }
  1224. void CharacterVirtual::Contact::RestoreState(StateRecorder &inStream)
  1225. {
  1226. inStream.Read(mPosition);
  1227. inStream.Read(mLinearVelocity);
  1228. inStream.Read(mContactNormal);
  1229. inStream.Read(mSurfaceNormal);
  1230. inStream.Read(mDistance);
  1231. inStream.Read(mFraction);
  1232. inStream.Read(mBodyB);
  1233. inStream.Read(mSubShapeIDB);
  1234. inStream.Read(mMotionTypeB);
  1235. inStream.Read(mHadCollision);
  1236. inStream.Read(mWasDiscarded);
  1237. inStream.Read(mCanPushCharacter);
  1238. mUserData = 0; // Cannot restore user data
  1239. mMaterial = PhysicsMaterial::sDefault; // Cannot restore material
  1240. }
  1241. void CharacterVirtual::SaveState(StateRecorder &inStream) const
  1242. {
  1243. CharacterBase::SaveState(inStream);
  1244. inStream.Write(mPosition);
  1245. inStream.Write(mRotation);
  1246. inStream.Write(mLinearVelocity);
  1247. inStream.Write(mLastDeltaTime);
  1248. inStream.Write(mMaxHitsExceeded);
  1249. // Store contacts that had collision, we're using it at the beginning of the step in CancelVelocityTowardsSteepSlopes
  1250. uint32 num_contacts = 0;
  1251. for (const Contact &c : mActiveContacts)
  1252. if (c.mHadCollision)
  1253. ++num_contacts;
  1254. inStream.Write(num_contacts);
  1255. for (const Contact &c : mActiveContacts)
  1256. if (c.mHadCollision)
  1257. c.SaveState(inStream);
  1258. }
  1259. void CharacterVirtual::RestoreState(StateRecorder &inStream)
  1260. {
  1261. CharacterBase::RestoreState(inStream);
  1262. inStream.Read(mPosition);
  1263. inStream.Read(mRotation);
  1264. inStream.Read(mLinearVelocity);
  1265. inStream.Read(mLastDeltaTime);
  1266. inStream.Read(mMaxHitsExceeded);
  1267. // When validating remove contacts that don't have collision since we didn't save them
  1268. if (inStream.IsValidating())
  1269. for (int i = (int)mActiveContacts.size() - 1; i >= 0; --i)
  1270. if (!mActiveContacts[i].mHadCollision)
  1271. mActiveContacts.erase(mActiveContacts.begin() + i);
  1272. uint32 num_contacts = (uint32)mActiveContacts.size();
  1273. inStream.Read(num_contacts);
  1274. mActiveContacts.resize(num_contacts);
  1275. for (Contact &c : mActiveContacts)
  1276. c.RestoreState(inStream);
  1277. }
  1278. JPH_NAMESPACE_END