CharacterVirtual.cpp 57 KB

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