CharacterVirtual.cpp 61 KB

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