CharacterVirtual.cpp 70 KB

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