CharacterVirtual.cpp 55 KB

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