PhysicsSystem.cpp 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768
  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/PhysicsSystem.h>
  6. #include <Jolt/Physics/PhysicsSettings.h>
  7. #include <Jolt/Physics/PhysicsUpdateContext.h>
  8. #include <Jolt/Physics/PhysicsStepListener.h>
  9. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseBruteForce.h>
  10. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h>
  11. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  12. #include <Jolt/Physics/Collision/AABoxCast.h>
  13. #include <Jolt/Physics/Collision/ShapeCast.h>
  14. #include <Jolt/Physics/Collision/CollideShape.h>
  15. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  16. #include <Jolt/Physics/Collision/CastResult.h>
  17. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  18. #include <Jolt/Physics/Collision/ManifoldBetweenTwoFaces.h>
  19. #include <Jolt/Physics/Collision/Shape/ConvexShape.h>
  20. #include <Jolt/Physics/Collision/SimShapeFilterWrapper.h>
  21. #include <Jolt/Physics/Collision/InternalEdgeRemovingCollector.h>
  22. #include <Jolt/Physics/Constraints/CalculateSolverSteps.h>
  23. #include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
  24. #include <Jolt/Physics/DeterminismLog.h>
  25. #include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>
  26. #include <Jolt/Physics/SoftBody/SoftBodyShape.h>
  27. #include <Jolt/Geometry/RayAABox.h>
  28. #include <Jolt/Geometry/ClosestPoint.h>
  29. #include <Jolt/Core/JobSystem.h>
  30. #include <Jolt/Core/TempAllocator.h>
  31. #include <Jolt/Core/QuickSort.h>
  32. #include <Jolt/Core/ScopeExit.h>
  33. #ifdef JPH_DEBUG_RENDERER
  34. #include <Jolt/Renderer/DebugRenderer.h>
  35. #endif // JPH_DEBUG_RENDERER
  36. JPH_NAMESPACE_BEGIN
  37. #ifdef JPH_DEBUG_RENDERER
  38. bool PhysicsSystem::sDrawMotionQualityLinearCast = false;
  39. #endif // JPH_DEBUG_RENDERER
  40. //#define BROAD_PHASE BroadPhaseBruteForce
  41. #define BROAD_PHASE BroadPhaseQuadTree
  42. static const Color cColorUpdateBroadPhaseFinalize = Color::sGetDistinctColor(1);
  43. static const Color cColorUpdateBroadPhasePrepare = Color::sGetDistinctColor(2);
  44. static const Color cColorFindCollisions = Color::sGetDistinctColor(3);
  45. static const Color cColorApplyGravity = Color::sGetDistinctColor(4);
  46. static const Color cColorSetupVelocityConstraints = Color::sGetDistinctColor(5);
  47. static const Color cColorBuildIslandsFromConstraints = Color::sGetDistinctColor(6);
  48. static const Color cColorDetermineActiveConstraints = Color::sGetDistinctColor(7);
  49. static const Color cColorFinalizeIslands = Color::sGetDistinctColor(8);
  50. static const Color cColorContactRemovedCallbacks = Color::sGetDistinctColor(9);
  51. static const Color cColorBodySetIslandIndex = Color::sGetDistinctColor(10);
  52. static const Color cColorStartNextStep = Color::sGetDistinctColor(11);
  53. static const Color cColorSolveVelocityConstraints = Color::sGetDistinctColor(12);
  54. static const Color cColorPreIntegrateVelocity = Color::sGetDistinctColor(13);
  55. static const Color cColorIntegrateVelocity = Color::sGetDistinctColor(14);
  56. static const Color cColorPostIntegrateVelocity = Color::sGetDistinctColor(15);
  57. static const Color cColorResolveCCDContacts = Color::sGetDistinctColor(16);
  58. static const Color cColorSolvePositionConstraints = Color::sGetDistinctColor(17);
  59. static const Color cColorFindCCDContacts = Color::sGetDistinctColor(18);
  60. static const Color cColorStepListeners = Color::sGetDistinctColor(19);
  61. static const Color cColorSoftBodyPrepare = Color::sGetDistinctColor(20);
  62. static const Color cColorSoftBodyCollide = Color::sGetDistinctColor(21);
  63. static const Color cColorSoftBodySimulate = Color::sGetDistinctColor(22);
  64. static const Color cColorSoftBodyFinalize = Color::sGetDistinctColor(23);
  65. PhysicsSystem::~PhysicsSystem()
  66. {
  67. // Remove broadphase
  68. delete mBroadPhase;
  69. }
  70. void PhysicsSystem::Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter)
  71. {
  72. // Clamp max bodies
  73. uint max_bodies = min(inMaxBodies, cMaxBodiesLimit);
  74. JPH_ASSERT(max_bodies == inMaxBodies, "Cannot support this many bodies!");
  75. mObjectVsBroadPhaseLayerFilter = &inObjectVsBroadPhaseLayerFilter;
  76. mObjectLayerPairFilter = &inObjectLayerPairFilter;
  77. // Initialize body manager
  78. mBodyManager.Init(max_bodies, inNumBodyMutexes, inBroadPhaseLayerInterface);
  79. // Create broadphase
  80. mBroadPhase = new BROAD_PHASE();
  81. mBroadPhase->Init(&mBodyManager, inBroadPhaseLayerInterface);
  82. // Init contact constraint manager
  83. mContactManager.Init(inMaxBodyPairs, inMaxContactConstraints);
  84. // Init islands builder
  85. mIslandBuilder.Init(max_bodies);
  86. // Initialize body interface
  87. mBodyInterfaceLocking.Init(mBodyLockInterfaceLocking, mBodyManager, *mBroadPhase);
  88. mBodyInterfaceNoLock.Init(mBodyLockInterfaceNoLock, mBodyManager, *mBroadPhase);
  89. // Initialize narrow phase query
  90. mNarrowPhaseQueryLocking.Init(mBodyLockInterfaceLocking, *mBroadPhase);
  91. mNarrowPhaseQueryNoLock.Init(mBodyLockInterfaceNoLock, *mBroadPhase);
  92. }
  93. void PhysicsSystem::OptimizeBroadPhase()
  94. {
  95. mBroadPhase->Optimize();
  96. }
  97. void PhysicsSystem::AddStepListener(PhysicsStepListener *inListener)
  98. {
  99. lock_guard lock(mStepListenersMutex);
  100. JPH_ASSERT(std::find(mStepListeners.begin(), mStepListeners.end(), inListener) == mStepListeners.end());
  101. mStepListeners.push_back(inListener);
  102. }
  103. void PhysicsSystem::RemoveStepListener(PhysicsStepListener *inListener)
  104. {
  105. lock_guard lock(mStepListenersMutex);
  106. StepListeners::iterator i = std::find(mStepListeners.begin(), mStepListeners.end(), inListener);
  107. JPH_ASSERT(i != mStepListeners.end());
  108. *i = mStepListeners.back();
  109. mStepListeners.pop_back();
  110. }
  111. EPhysicsUpdateError PhysicsSystem::Update(float inDeltaTime, int inCollisionSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem)
  112. {
  113. JPH_PROFILE_FUNCTION();
  114. JPH_DET_LOG("PhysicsSystem::Update: dt: " << inDeltaTime << " steps: " << inCollisionSteps);
  115. JPH_ASSERT(inCollisionSteps > 0);
  116. JPH_ASSERT(inDeltaTime >= 0.0f);
  117. // Sync point for the broadphase. This will allow it to do clean up operations without having any mutexes locked yet.
  118. mBroadPhase->FrameSync();
  119. // If there are no active bodies or there's no time delta
  120. uint32 num_active_rigid_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);
  121. uint32 num_active_soft_bodies = mBodyManager.GetNumActiveBodies(EBodyType::SoftBody);
  122. if ((num_active_rigid_bodies == 0 && num_active_soft_bodies == 0) || inDeltaTime <= 0.0f)
  123. {
  124. mBodyManager.LockAllBodies();
  125. // Update broadphase
  126. mBroadPhase->LockModifications();
  127. BroadPhase::UpdateState update_state = mBroadPhase->UpdatePrepare();
  128. mBroadPhase->UpdateFinalize(update_state);
  129. mBroadPhase->UnlockModifications();
  130. // Call contact removal callbacks from contacts that existed in the previous update
  131. mContactManager.FinalizeContactCacheAndCallContactPointRemovedCallbacks(0, 0);
  132. mBodyManager.UnlockAllBodies();
  133. return EPhysicsUpdateError::None;
  134. }
  135. // Calculate ratio between current and previous frame delta time to scale initial constraint forces
  136. float step_delta_time = inDeltaTime / inCollisionSteps;
  137. float warm_start_impulse_ratio = mPhysicsSettings.mConstraintWarmStart && mPreviousStepDeltaTime > 0.0f? step_delta_time / mPreviousStepDeltaTime : 0.0f;
  138. mPreviousStepDeltaTime = step_delta_time;
  139. // Create the context used for passing information between jobs
  140. PhysicsUpdateContext context(*inTempAllocator);
  141. context.mPhysicsSystem = this;
  142. context.mJobSystem = inJobSystem;
  143. context.mBarrier = inJobSystem->CreateBarrier();
  144. context.mIslandBuilder = &mIslandBuilder;
  145. context.mStepDeltaTime = step_delta_time;
  146. context.mWarmStartImpulseRatio = warm_start_impulse_ratio;
  147. context.mSteps.resize(inCollisionSteps);
  148. // Allocate space for body pairs
  149. JPH_ASSERT(context.mBodyPairs == nullptr);
  150. context.mBodyPairs = static_cast<BodyPair *>(inTempAllocator->Allocate(sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs));
  151. // Lock all bodies for write so that we can freely touch them
  152. mStepListenersMutex.lock();
  153. mBodyManager.LockAllBodies();
  154. mBroadPhase->LockModifications();
  155. // Get max number of concurrent jobs
  156. int max_concurrency = context.GetMaxConcurrency();
  157. // Calculate how many step listener jobs we spawn
  158. int num_step_listener_jobs = mStepListeners.empty()? 0 : max(1, min((int)mStepListeners.size() / mPhysicsSettings.mStepListenersBatchSize / mPhysicsSettings.mStepListenerBatchesPerJob, max_concurrency));
  159. // Number of gravity jobs depends on the amount of active bodies.
  160. // Launch max 1 job per batch of active bodies
  161. // Leave 1 thread for update broadphase prepare and 1 for determine active constraints
  162. int num_apply_gravity_jobs = max(1, min(((int)num_active_rigid_bodies + cApplyGravityBatchSize - 1) / cApplyGravityBatchSize, max_concurrency - 2));
  163. // Number of determine active constraints jobs to run depends on number of constraints.
  164. // Leave 1 thread for update broadphase prepare and 1 for apply gravity
  165. int num_determine_active_constraints_jobs = max(1, min(((int)mConstraintManager.GetNumConstraints() + cDetermineActiveConstraintsBatchSize - 1) / cDetermineActiveConstraintsBatchSize, max_concurrency - 2));
  166. // Number of setup velocity constraints jobs to run depends on number of constraints.
  167. int num_setup_velocity_constraints_jobs = max(1, min(((int)mConstraintManager.GetNumConstraints() + cSetupVelocityConstraintsBatchSize - 1) / cSetupVelocityConstraintsBatchSize, max_concurrency));
  168. // Number of find collisions jobs to run depends on number of active bodies.
  169. // Note that when we have more than 1 thread, we always spawn at least 2 find collisions jobs so that the first job can wait for build islands from constraints
  170. // (which may activate additional bodies that need to be processed) while the second job can start processing collision work.
  171. int num_find_collisions_jobs = max(max_concurrency == 1? 1 : 2, min(((int)num_active_rigid_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_concurrency));
  172. // Number of integrate velocity jobs depends on number of active bodies.
  173. int num_integrate_velocity_jobs = max(1, min(((int)num_active_rigid_bodies + cIntegrateVelocityBatchSize - 1) / cIntegrateVelocityBatchSize, max_concurrency));
  174. {
  175. JPH_PROFILE("Build Jobs");
  176. // Iterate over collision steps
  177. for (int step_idx = 0; step_idx < inCollisionSteps; ++step_idx)
  178. {
  179. bool is_first_step = step_idx == 0;
  180. bool is_last_step = step_idx == inCollisionSteps - 1;
  181. PhysicsUpdateContext::Step &step = context.mSteps[step_idx];
  182. step.mContext = &context;
  183. step.mIsFirst = is_first_step;
  184. step.mIsLast = is_last_step;
  185. // Create job to do broadphase finalization
  186. // This job must finish before integrating velocities. Until then the positions will not be updated neither will bodies be added / removed.
  187. step.mUpdateBroadphaseFinalize = inJobSystem->CreateJob("UpdateBroadPhaseFinalize", cColorUpdateBroadPhaseFinalize, [&context, &step]()
  188. {
  189. // Validate that all find collision jobs have stopped
  190. JPH_ASSERT(step.mActiveFindCollisionJobs.load(memory_order_relaxed) == 0);
  191. // Finalize the broadphase update
  192. context.mPhysicsSystem->mBroadPhase->UpdateFinalize(step.mBroadPhaseUpdateState);
  193. // Signal that it is done
  194. step.mPreIntegrateVelocity.RemoveDependency();
  195. }, num_find_collisions_jobs + 2); // depends on: find collisions, broadphase prepare update, finish building jobs
  196. // The immediate jobs below are only immediate for the first step, the all finished job will kick them for the next step
  197. int previous_step_dependency_count = is_first_step? 0 : 1;
  198. // Start job immediately: Start the prepare broadphase
  199. // Must be done under body lock protection since the order is body locks then broadphase mutex
  200. // If this is turned around the RemoveBody call will hang since it locks in that order
  201. step.mBroadPhasePrepare = inJobSystem->CreateJob("UpdateBroadPhasePrepare", cColorUpdateBroadPhasePrepare, [&context, &step]()
  202. {
  203. // Prepare the broadphase update
  204. step.mBroadPhaseUpdateState = context.mPhysicsSystem->mBroadPhase->UpdatePrepare();
  205. // Now the finalize can run (if other dependencies are met too)
  206. step.mUpdateBroadphaseFinalize.RemoveDependency();
  207. }, previous_step_dependency_count);
  208. // This job will find all collisions
  209. step.mBodyPairQueues.resize(max_concurrency);
  210. step.mMaxBodyPairsPerQueue = mPhysicsSettings.mMaxInFlightBodyPairs / max_concurrency;
  211. step.mActiveFindCollisionJobs.store(~PhysicsUpdateContext::JobMask(0) >> (sizeof(PhysicsUpdateContext::JobMask) * 8 - num_find_collisions_jobs), memory_order_release);
  212. step.mFindCollisions.resize(num_find_collisions_jobs);
  213. for (int i = 0; i < num_find_collisions_jobs; ++i)
  214. {
  215. // Build islands from constraints may activate additional bodies, so the first job will wait for this to finish in order to not miss any active bodies
  216. int num_dep_build_islands_from_constraints = i == 0? 1 : 0;
  217. step.mFindCollisions[i] = inJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [&step, i]()
  218. {
  219. step.mContext->mPhysicsSystem->JobFindCollisions(&step, i);
  220. }, num_apply_gravity_jobs + num_determine_active_constraints_jobs + 1 + num_dep_build_islands_from_constraints); // depends on: apply gravity, determine active constraints, finish building jobs, build islands from constraints
  221. }
  222. if (is_first_step)
  223. {
  224. #ifdef JPH_ENABLE_ASSERTS
  225. // Don't allow write operations to the active bodies list
  226. mBodyManager.SetActiveBodiesLocked(true);
  227. #endif
  228. // Store the number of active bodies at the start of the step
  229. step.mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);
  230. // Lock all constraints
  231. mConstraintManager.LockAllConstraints();
  232. // Allocate memory for storing the active constraints
  233. JPH_ASSERT(context.mActiveConstraints == nullptr);
  234. context.mActiveConstraints = static_cast<Constraint **>(inTempAllocator->Allocate(mConstraintManager.GetNumConstraints() * sizeof(Constraint *)));
  235. // Prepare contact buffer
  236. mContactManager.PrepareConstraintBuffer(&context);
  237. // Setup island builder
  238. mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), context.mTempAllocator);
  239. }
  240. // This job applies gravity to all active bodies
  241. step.mApplyGravity.resize(num_apply_gravity_jobs);
  242. for (int i = 0; i < num_apply_gravity_jobs; ++i)
  243. step.mApplyGravity[i] = inJobSystem->CreateJob("ApplyGravity", cColorApplyGravity, [&context, &step]()
  244. {
  245. context.mPhysicsSystem->JobApplyGravity(&context, &step);
  246. JobHandle::sRemoveDependencies(step.mFindCollisions);
  247. }, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)
  248. // This job will setup velocity constraints for non-collision constraints
  249. step.mSetupVelocityConstraints.resize(num_setup_velocity_constraints_jobs);
  250. for (int i = 0; i < num_setup_velocity_constraints_jobs; ++i)
  251. step.mSetupVelocityConstraints[i] = inJobSystem->CreateJob("SetupVelocityConstraints", cColorSetupVelocityConstraints, [&context, &step]()
  252. {
  253. context.mPhysicsSystem->JobSetupVelocityConstraints(context.mStepDeltaTime, &step);
  254. JobHandle::sRemoveDependencies(step.mSolveVelocityConstraints);
  255. }, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs
  256. // This job will build islands from constraints
  257. step.mBuildIslandsFromConstraints = inJobSystem->CreateJob("BuildIslandsFromConstraints", cColorBuildIslandsFromConstraints, [&context, &step]()
  258. {
  259. context.mPhysicsSystem->JobBuildIslandsFromConstraints(&context, &step);
  260. step.mFindCollisions[0].RemoveDependency(); // The first collisions job cannot start running until we've finished building islands and activated all bodies
  261. step.mFinalizeIslands.RemoveDependency();
  262. }, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs
  263. // This job determines active constraints
  264. step.mDetermineActiveConstraints.resize(num_determine_active_constraints_jobs);
  265. for (int i = 0; i < num_determine_active_constraints_jobs; ++i)
  266. step.mDetermineActiveConstraints[i] = inJobSystem->CreateJob("DetermineActiveConstraints", cColorDetermineActiveConstraints, [&context, &step]()
  267. {
  268. context.mPhysicsSystem->JobDetermineActiveConstraints(&step);
  269. step.mBuildIslandsFromConstraints.RemoveDependency();
  270. // Kick these jobs last as they will use up all CPU cores leaving no space for the previous job, we prefer setup velocity constraints to finish first so we kick it first
  271. JobHandle::sRemoveDependencies(step.mSetupVelocityConstraints);
  272. JobHandle::sRemoveDependencies(step.mFindCollisions);
  273. }, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)
  274. // This job calls the step listeners
  275. step.mStepListeners.resize(num_step_listener_jobs);
  276. for (int i = 0; i < num_step_listener_jobs; ++i)
  277. step.mStepListeners[i] = inJobSystem->CreateJob("StepListeners", cColorStepListeners, [&context, &step]()
  278. {
  279. // Call the step listeners
  280. context.mPhysicsSystem->JobStepListeners(&step);
  281. // Kick apply gravity and determine active constraint jobs
  282. JobHandle::sRemoveDependencies(step.mApplyGravity);
  283. JobHandle::sRemoveDependencies(step.mDetermineActiveConstraints);
  284. }, previous_step_dependency_count);
  285. // Unblock the previous step
  286. if (!is_first_step)
  287. context.mSteps[step_idx - 1].mStartNextStep.RemoveDependency();
  288. // This job will finalize the simulation islands
  289. step.mFinalizeIslands = inJobSystem->CreateJob("FinalizeIslands", cColorFinalizeIslands, [&context, &step]()
  290. {
  291. // Validate that all find collision jobs have stopped
  292. JPH_ASSERT(step.mActiveFindCollisionJobs.load(memory_order_relaxed) == 0);
  293. context.mPhysicsSystem->JobFinalizeIslands(&context);
  294. JobHandle::sRemoveDependencies(step.mSolveVelocityConstraints);
  295. step.mBodySetIslandIndex.RemoveDependency();
  296. }, num_find_collisions_jobs + 2); // depends on: find collisions, build islands from constraints, finish building jobs
  297. // Unblock previous job
  298. // Note: technically we could release find collisions here but we don't want to because that could make them run before 'setup velocity constraints' which means that job won't have a thread left
  299. step.mBuildIslandsFromConstraints.RemoveDependency();
  300. // This job will call the contact removed callbacks
  301. step.mContactRemovedCallbacks = inJobSystem->CreateJob("ContactRemovedCallbacks", cColorContactRemovedCallbacks, [&context, &step]()
  302. {
  303. context.mPhysicsSystem->JobContactRemovedCallbacks(&step);
  304. if (step.mStartNextStep.IsValid())
  305. step.mStartNextStep.RemoveDependency();
  306. }, 1); // depends on the find ccd contacts
  307. // This job will set the island index on each body (only used for debug drawing purposes)
  308. // It will also delete any bodies that have been destroyed in the last frame
  309. step.mBodySetIslandIndex = inJobSystem->CreateJob("BodySetIslandIndex", cColorBodySetIslandIndex, [&context, &step]()
  310. {
  311. context.mPhysicsSystem->JobBodySetIslandIndex();
  312. JobHandle::sRemoveDependencies(step.mSolvePositionConstraints);
  313. }, 2); // depends on: finalize islands, finish building jobs
  314. // Job to start the next collision step
  315. if (!is_last_step)
  316. {
  317. PhysicsUpdateContext::Step *next_step = &context.mSteps[step_idx + 1];
  318. step.mStartNextStep = inJobSystem->CreateJob("StartNextStep", cColorStartNextStep, [this, next_step]()
  319. {
  320. #ifdef JPH_DEBUG
  321. // Validate that the cached bounds are correct
  322. mBodyManager.ValidateActiveBodyBounds();
  323. #endif // JPH_DEBUG
  324. // Store the number of active bodies at the start of the step
  325. next_step->mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);
  326. // Clear the large island splitter
  327. TempAllocator *temp_allocator = next_step->mContext->mTempAllocator;
  328. mLargeIslandSplitter.Reset(temp_allocator);
  329. // Clear the island builder
  330. mIslandBuilder.ResetIslands(temp_allocator);
  331. // Setup island builder
  332. mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), temp_allocator);
  333. // Restart the contact manager
  334. mContactManager.RecycleConstraintBuffer();
  335. // Kick the jobs of the next step (in the same order as the first step)
  336. next_step->mBroadPhasePrepare.RemoveDependency();
  337. if (next_step->mStepListeners.empty())
  338. {
  339. // Kick the gravity and active constraints jobs immediately
  340. JobHandle::sRemoveDependencies(next_step->mApplyGravity);
  341. JobHandle::sRemoveDependencies(next_step->mDetermineActiveConstraints);
  342. }
  343. else
  344. {
  345. // Kick the step listeners job first
  346. JobHandle::sRemoveDependencies(next_step->mStepListeners);
  347. }
  348. }, 3); // depends on: update soft bodies, contact removed callbacks, finish building the previous step
  349. }
  350. // This job will solve the velocity constraints
  351. step.mSolveVelocityConstraints.resize(max_concurrency);
  352. for (int i = 0; i < max_concurrency; ++i)
  353. step.mSolveVelocityConstraints[i] = inJobSystem->CreateJob("SolveVelocityConstraints", cColorSolveVelocityConstraints, [&context, &step]()
  354. {
  355. context.mPhysicsSystem->JobSolveVelocityConstraints(&context, &step);
  356. step.mPreIntegrateVelocity.RemoveDependency();
  357. }, num_setup_velocity_constraints_jobs + 2); // depends on: finalize islands, setup velocity constraints, finish building jobs.
  358. // We prefer setup velocity constraints to finish first so we kick it first
  359. JobHandle::sRemoveDependencies(step.mSetupVelocityConstraints);
  360. JobHandle::sRemoveDependencies(step.mFindCollisions);
  361. // Finalize islands is a dependency on find collisions so it can go last
  362. step.mFinalizeIslands.RemoveDependency();
  363. // This job will prepare the position update of all active bodies
  364. step.mPreIntegrateVelocity = inJobSystem->CreateJob("PreIntegrateVelocity", cColorPreIntegrateVelocity, [&context, &step]()
  365. {
  366. context.mPhysicsSystem->JobPreIntegrateVelocity(&context, &step);
  367. JobHandle::sRemoveDependencies(step.mIntegrateVelocity);
  368. }, 2 + max_concurrency); // depends on: broadphase update finalize, solve velocity constraints, finish building jobs.
  369. // Unblock previous jobs
  370. step.mUpdateBroadphaseFinalize.RemoveDependency();
  371. JobHandle::sRemoveDependencies(step.mSolveVelocityConstraints);
  372. // This job will update the positions of all active bodies
  373. step.mIntegrateVelocity.resize(num_integrate_velocity_jobs);
  374. for (int i = 0; i < num_integrate_velocity_jobs; ++i)
  375. step.mIntegrateVelocity[i] = inJobSystem->CreateJob("IntegrateVelocity", cColorIntegrateVelocity, [&context, &step]()
  376. {
  377. context.mPhysicsSystem->JobIntegrateVelocity(&context, &step);
  378. step.mPostIntegrateVelocity.RemoveDependency();
  379. }, 2); // depends on: pre integrate velocity, finish building jobs.
  380. // Unblock previous job
  381. step.mPreIntegrateVelocity.RemoveDependency();
  382. // This job will finish the position update of all active bodies
  383. step.mPostIntegrateVelocity = inJobSystem->CreateJob("PostIntegrateVelocity", cColorPostIntegrateVelocity, [&context, &step]()
  384. {
  385. context.mPhysicsSystem->JobPostIntegrateVelocity(&context, &step);
  386. step.mResolveCCDContacts.RemoveDependency();
  387. }, num_integrate_velocity_jobs + 1); // depends on: integrate velocity, finish building jobs
  388. // Unblock previous jobs
  389. JobHandle::sRemoveDependencies(step.mIntegrateVelocity);
  390. // This job will update the positions and velocities for all bodies that need continuous collision detection
  391. step.mResolveCCDContacts = inJobSystem->CreateJob("ResolveCCDContacts", cColorResolveCCDContacts, [&context, &step]()
  392. {
  393. context.mPhysicsSystem->JobResolveCCDContacts(&context, &step);
  394. JobHandle::sRemoveDependencies(step.mSolvePositionConstraints);
  395. }, 2); // depends on: integrate velocities, detect ccd contacts (added dynamically), finish building jobs.
  396. // Unblock previous job
  397. step.mPostIntegrateVelocity.RemoveDependency();
  398. // Fixes up drift in positions and updates the broadphase with new body positions
  399. step.mSolvePositionConstraints.resize(max_concurrency);
  400. for (int i = 0; i < max_concurrency; ++i)
  401. step.mSolvePositionConstraints[i] = inJobSystem->CreateJob("SolvePositionConstraints", cColorSolvePositionConstraints, [&context, &step]()
  402. {
  403. context.mPhysicsSystem->JobSolvePositionConstraints(&context, &step);
  404. // Kick the next step
  405. if (step.mSoftBodyPrepare.IsValid())
  406. step.mSoftBodyPrepare.RemoveDependency();
  407. }, 3); // depends on: resolve ccd contacts, body set island index, finish building jobs.
  408. // Unblock previous jobs.
  409. step.mResolveCCDContacts.RemoveDependency();
  410. step.mBodySetIslandIndex.RemoveDependency();
  411. // The soft body prepare job will create other jobs if needed
  412. step.mSoftBodyPrepare = inJobSystem->CreateJob("SoftBodyPrepare", cColorSoftBodyPrepare, [&context, &step]()
  413. {
  414. context.mPhysicsSystem->JobSoftBodyPrepare(&context, &step);
  415. }, max_concurrency); // depends on: solve position constraints.
  416. // Unblock previous jobs
  417. JobHandle::sRemoveDependencies(step.mSolvePositionConstraints);
  418. }
  419. }
  420. // Build the list of jobs to wait for
  421. JobSystem::Barrier *barrier = context.mBarrier;
  422. {
  423. JPH_PROFILE("Build job barrier");
  424. StaticArray<JobHandle, cMaxPhysicsJobs> handles;
  425. for (const PhysicsUpdateContext::Step &step : context.mSteps)
  426. {
  427. if (step.mBroadPhasePrepare.IsValid())
  428. handles.push_back(step.mBroadPhasePrepare);
  429. for (const JobHandle &h : step.mStepListeners)
  430. handles.push_back(h);
  431. for (const JobHandle &h : step.mDetermineActiveConstraints)
  432. handles.push_back(h);
  433. for (const JobHandle &h : step.mApplyGravity)
  434. handles.push_back(h);
  435. for (const JobHandle &h : step.mFindCollisions)
  436. handles.push_back(h);
  437. if (step.mUpdateBroadphaseFinalize.IsValid())
  438. handles.push_back(step.mUpdateBroadphaseFinalize);
  439. for (const JobHandle &h : step.mSetupVelocityConstraints)
  440. handles.push_back(h);
  441. handles.push_back(step.mBuildIslandsFromConstraints);
  442. handles.push_back(step.mFinalizeIslands);
  443. handles.push_back(step.mBodySetIslandIndex);
  444. for (const JobHandle &h : step.mSolveVelocityConstraints)
  445. handles.push_back(h);
  446. handles.push_back(step.mPreIntegrateVelocity);
  447. for (const JobHandle &h : step.mIntegrateVelocity)
  448. handles.push_back(h);
  449. handles.push_back(step.mPostIntegrateVelocity);
  450. handles.push_back(step.mResolveCCDContacts);
  451. for (const JobHandle &h : step.mSolvePositionConstraints)
  452. handles.push_back(h);
  453. handles.push_back(step.mContactRemovedCallbacks);
  454. if (step.mSoftBodyPrepare.IsValid())
  455. handles.push_back(step.mSoftBodyPrepare);
  456. if (step.mStartNextStep.IsValid())
  457. handles.push_back(step.mStartNextStep);
  458. }
  459. barrier->AddJobs(handles.data(), handles.size());
  460. }
  461. // Wait until all jobs finish
  462. // Note we don't just wait for the last job. If we would and another job
  463. // would be scheduled in between there is the possibility of a deadlock.
  464. // The other job could try to e.g. add/remove a body which would try to
  465. // lock a body mutex while this thread has already locked the mutex
  466. inJobSystem->WaitForJobs(barrier);
  467. // We're done with the barrier for this update
  468. inJobSystem->DestroyBarrier(barrier);
  469. #ifdef JPH_DEBUG
  470. // Validate that the cached bounds are correct
  471. mBodyManager.ValidateActiveBodyBounds();
  472. #endif // JPH_DEBUG
  473. // Clear the large island splitter
  474. mLargeIslandSplitter.Reset(inTempAllocator);
  475. // Clear the island builder
  476. mIslandBuilder.ResetIslands(inTempAllocator);
  477. // Clear the contact manager
  478. mContactManager.FinishConstraintBuffer();
  479. // Free active constraints
  480. inTempAllocator->Free(context.mActiveConstraints, mConstraintManager.GetNumConstraints() * sizeof(Constraint *));
  481. context.mActiveConstraints = nullptr;
  482. // Free body pairs
  483. inTempAllocator->Free(context.mBodyPairs, sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs);
  484. context.mBodyPairs = nullptr;
  485. // Unlock the broadphase
  486. mBroadPhase->UnlockModifications();
  487. // Unlock all constraints
  488. mConstraintManager.UnlockAllConstraints();
  489. #ifdef JPH_ENABLE_ASSERTS
  490. // Allow write operations to the active bodies list
  491. mBodyManager.SetActiveBodiesLocked(false);
  492. #endif
  493. // Unlock all bodies
  494. mBodyManager.UnlockAllBodies();
  495. // Unlock step listeners
  496. mStepListenersMutex.unlock();
  497. // Return any errors
  498. EPhysicsUpdateError errors = static_cast<EPhysicsUpdateError>(context.mErrors.load(memory_order_acquire));
  499. JPH_ASSERT(errors == EPhysicsUpdateError::None, "An error occurred during the physics update, see EPhysicsUpdateError for more information");
  500. return errors;
  501. }
  502. void PhysicsSystem::JobStepListeners(PhysicsUpdateContext::Step *ioStep)
  503. {
  504. #ifdef JPH_ENABLE_ASSERTS
  505. // Read positions (broadphase updates concurrently so we can't write), read/write velocities
  506. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  507. // Can activate bodies only (we cache the amount of active bodies at the beginning of the step in mNumActiveBodiesAtStepStart so we cannot deactivate here)
  508. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  509. #endif
  510. PhysicsStepListenerContext context;
  511. context.mDeltaTime = ioStep->mContext->mStepDeltaTime;
  512. context.mIsFirstStep = ioStep->mIsFirst;
  513. context.mIsLastStep = ioStep->mIsLast;
  514. context.mPhysicsSystem = this;
  515. uint32 batch_size = mPhysicsSettings.mStepListenersBatchSize;
  516. for (;;)
  517. {
  518. // Get the start of a new batch
  519. uint32 batch = ioStep->mStepListenerReadIdx.fetch_add(batch_size);
  520. if (batch >= mStepListeners.size())
  521. break;
  522. // Call the listeners
  523. for (uint32 i = batch, i_end = min((uint32)mStepListeners.size(), batch + batch_size); i < i_end; ++i)
  524. mStepListeners[i]->OnStep(context);
  525. }
  526. }
  527. void PhysicsSystem::JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const
  528. {
  529. #ifdef JPH_ENABLE_ASSERTS
  530. // No body access
  531. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  532. #endif
  533. uint32 num_constraints = mConstraintManager.GetNumConstraints();
  534. uint32 num_active_constraints;
  535. Constraint **active_constraints = (Constraint **)JPH_STACK_ALLOC(cDetermineActiveConstraintsBatchSize * sizeof(Constraint *));
  536. for (;;)
  537. {
  538. // Atomically fetch a batch of constraints
  539. uint32 constraint_idx = ioStep->mDetermineActiveConstraintReadIdx.fetch_add(cDetermineActiveConstraintsBatchSize);
  540. if (constraint_idx >= num_constraints)
  541. break;
  542. // Calculate the end of the batch
  543. uint32 constraint_idx_end = min(num_constraints, constraint_idx + cDetermineActiveConstraintsBatchSize);
  544. // Store the active constraints at the start of the step (bodies get activated during the step which in turn may activate constraints leading to an inconsistent shapshot)
  545. mConstraintManager.GetActiveConstraints(constraint_idx, constraint_idx_end, active_constraints, num_active_constraints);
  546. // Copy the block of active constraints to the global list of active constraints
  547. if (num_active_constraints > 0)
  548. {
  549. uint32 active_constraint_idx = ioStep->mNumActiveConstraints.fetch_add(num_active_constraints);
  550. memcpy(ioStep->mContext->mActiveConstraints + active_constraint_idx, active_constraints, num_active_constraints * sizeof(Constraint *));
  551. }
  552. }
  553. }
  554. void PhysicsSystem::JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  555. {
  556. #ifdef JPH_ENABLE_ASSERTS
  557. // We update velocities and need the rotation to do so
  558. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  559. #endif
  560. // Get list of active bodies that we had at the start of the physics update.
  561. // Any body that is activated as part of the simulation step does not receive gravity this frame.
  562. // Note that bodies may be activated during this job but not deactivated, this means that only elements
  563. // will be added to the array. Since the array is made to not reallocate, this is a safe operation.
  564. const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody);
  565. uint32 num_active_bodies_at_step_start = ioStep->mNumActiveBodiesAtStepStart;
  566. // Fetch delta time once outside the loop
  567. float delta_time = ioContext->mStepDeltaTime;
  568. // Update velocities from forces
  569. for (;;)
  570. {
  571. // Atomically fetch a batch of bodies
  572. uint32 active_body_idx = ioStep->mApplyGravityReadIdx.fetch_add(cApplyGravityBatchSize);
  573. if (active_body_idx >= num_active_bodies_at_step_start)
  574. break;
  575. // Calculate the end of the batch
  576. uint32 active_body_idx_end = min(num_active_bodies_at_step_start, active_body_idx + cApplyGravityBatchSize);
  577. // Process the batch
  578. while (active_body_idx < active_body_idx_end)
  579. {
  580. Body &body = mBodyManager.GetBody(active_bodies[active_body_idx]);
  581. if (body.IsDynamic())
  582. {
  583. MotionProperties *mp = body.GetMotionProperties();
  584. Quat rotation = body.GetRotation();
  585. if (body.GetApplyGyroscopicForce())
  586. mp->ApplyGyroscopicForceInternal(rotation, delta_time);
  587. mp->ApplyForceTorqueAndDragInternal(rotation, mGravity, delta_time);
  588. }
  589. active_body_idx++;
  590. }
  591. }
  592. }
  593. void PhysicsSystem::JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const
  594. {
  595. #ifdef JPH_ENABLE_ASSERTS
  596. // We only read positions
  597. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  598. #endif
  599. uint32 num_constraints = ioStep->mNumActiveConstraints;
  600. for (;;)
  601. {
  602. // Atomically fetch a batch of constraints
  603. uint32 constraint_idx = ioStep->mSetupVelocityConstraintsReadIdx.fetch_add(cSetupVelocityConstraintsBatchSize);
  604. if (constraint_idx >= num_constraints)
  605. break;
  606. ConstraintManager::sSetupVelocityConstraints(ioStep->mContext->mActiveConstraints + constraint_idx, min<uint32>(cSetupVelocityConstraintsBatchSize, num_constraints - constraint_idx), inDeltaTime);
  607. }
  608. }
  609. void PhysicsSystem::JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  610. {
  611. #ifdef JPH_ENABLE_ASSERTS
  612. // We read constraints and positions
  613. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  614. // Can only activate bodies
  615. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  616. #endif
  617. // Prepare the island builder
  618. mIslandBuilder.PrepareNonContactConstraints(ioStep->mNumActiveConstraints, ioContext->mTempAllocator);
  619. // Build the islands
  620. ConstraintManager::sBuildIslands(ioStep->mContext->mActiveConstraints, ioStep->mNumActiveConstraints, mIslandBuilder, mBodyManager);
  621. }
  622. void PhysicsSystem::TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const
  623. {
  624. // Get how many jobs we can spawn and check if we can spawn more
  625. uint max_jobs = ioStep->mBodyPairQueues.size();
  626. if (CountBits(ioStep->mActiveFindCollisionJobs.load(memory_order_relaxed)) >= max_jobs)
  627. return;
  628. // Count how many body pairs we have waiting
  629. uint32 num_body_pairs = 0;
  630. for (const PhysicsUpdateContext::BodyPairQueue &queue : ioStep->mBodyPairQueues)
  631. num_body_pairs += queue.mWriteIdx - queue.mReadIdx;
  632. // Count how many active bodies we have waiting
  633. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody) - ioStep->mActiveBodyReadIdx;
  634. // Calculate how many jobs we would like
  635. uint desired_num_jobs = min((num_body_pairs + cNarrowPhaseBatchSize - 1) / cNarrowPhaseBatchSize + (num_active_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_jobs);
  636. for (;;)
  637. {
  638. // Get the bit mask of active jobs and see if we can spawn more
  639. PhysicsUpdateContext::JobMask current_active_jobs = ioStep->mActiveFindCollisionJobs.load(memory_order_relaxed);
  640. uint job_index = CountTrailingZeros(~current_active_jobs);
  641. if (job_index >= desired_num_jobs)
  642. break;
  643. // Try to claim the job index
  644. PhysicsUpdateContext::JobMask job_mask = PhysicsUpdateContext::JobMask(1) << job_index;
  645. PhysicsUpdateContext::JobMask prev_value = ioStep->mActiveFindCollisionJobs.fetch_or(job_mask, memory_order_acquire);
  646. if ((prev_value & job_mask) == 0)
  647. {
  648. // Add dependencies from the find collisions job to the next jobs
  649. ioStep->mUpdateBroadphaseFinalize.AddDependency();
  650. ioStep->mFinalizeIslands.AddDependency();
  651. // Start the job
  652. JobHandle job = ioStep->mContext->mJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [step = ioStep, job_index]()
  653. {
  654. step->mContext->mPhysicsSystem->JobFindCollisions(step, job_index);
  655. });
  656. // Add the job to the job barrier so the main updating thread can execute the job too
  657. ioStep->mContext->mBarrier->AddJob(job);
  658. // Spawn only 1 extra job at a time
  659. return;
  660. }
  661. }
  662. }
  663. static void sFinalizeContactAllocator(PhysicsUpdateContext::Step &ioStep, const ContactConstraintManager::ContactAllocator &inAllocator)
  664. {
  665. // Atomically accumulate the number of found manifolds and body pairs
  666. ioStep.mNumBodyPairs.fetch_add(inAllocator.mNumBodyPairs, memory_order_relaxed);
  667. ioStep.mNumManifolds.fetch_add(inAllocator.mNumManifolds, memory_order_relaxed);
  668. // Combine update errors
  669. ioStep.mContext->mErrors.fetch_or((uint32)inAllocator.mErrors, memory_order_relaxed);
  670. }
  671. // Disable TSAN for this function. It detects a false positive race condition on mBodyPairs.
  672. // We have written mBodyPairs before doing mWriteIdx++ and we check mWriteIdx before reading mBodyPairs, so this should be safe.
  673. JPH_TSAN_NO_SANITIZE
  674. void PhysicsSystem::JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex)
  675. {
  676. #ifdef JPH_ENABLE_ASSERTS
  677. // We read positions and read velocities (for elastic collisions)
  678. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  679. // Can only activate bodies
  680. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  681. #endif
  682. // Allocation context for allocating new contact points
  683. ContactAllocator contact_allocator(mContactManager.GetContactAllocator());
  684. // Determine initial queue to read pairs from if no broadphase work can be done
  685. // (always start looking at results from the next job)
  686. int read_queue_idx = (inJobIndex + 1) % ioStep->mBodyPairQueues.size();
  687. // Allocate space to temporarily store a batch of active bodies
  688. BodyID *active_bodies = (BodyID *)JPH_STACK_ALLOC(cActiveBodiesBatchSize * sizeof(BodyID));
  689. for (;;)
  690. {
  691. // Check if there are active bodies to be processed
  692. uint32 active_bodies_read_idx = ioStep->mActiveBodyReadIdx;
  693. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);
  694. if (active_bodies_read_idx < num_active_bodies)
  695. {
  696. // Take a batch of active bodies
  697. uint32 active_bodies_read_idx_end = min(num_active_bodies, active_bodies_read_idx + cActiveBodiesBatchSize);
  698. if (ioStep->mActiveBodyReadIdx.compare_exchange_strong(active_bodies_read_idx, active_bodies_read_idx_end))
  699. {
  700. // Callback when a new body pair is found
  701. class MyBodyPairCallback : public BodyPairCollector
  702. {
  703. public:
  704. // Constructor
  705. MyBodyPairCallback(PhysicsUpdateContext::Step *inStep, ContactAllocator &ioContactAllocator, int inJobIndex) :
  706. mStep(inStep),
  707. mContactAllocator(ioContactAllocator),
  708. mJobIndex(inJobIndex)
  709. {
  710. }
  711. // Callback function when a body pair is found
  712. virtual void AddHit(const BodyPair &inPair) override
  713. {
  714. // Check if we have space in our write queue
  715. PhysicsUpdateContext::BodyPairQueue &queue = mStep->mBodyPairQueues[mJobIndex];
  716. uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;
  717. if (body_pairs_in_queue >= mStep->mMaxBodyPairsPerQueue)
  718. {
  719. // Buffer full, process the pair now
  720. mStep->mContext->mPhysicsSystem->ProcessBodyPair(mContactAllocator, inPair);
  721. }
  722. else
  723. {
  724. // Store the pair in our own queue
  725. mStep->mContext->mBodyPairs[mJobIndex * mStep->mMaxBodyPairsPerQueue + queue.mWriteIdx % mStep->mMaxBodyPairsPerQueue] = inPair;
  726. ++queue.mWriteIdx;
  727. }
  728. }
  729. private:
  730. PhysicsUpdateContext::Step * mStep;
  731. ContactAllocator & mContactAllocator;
  732. int mJobIndex;
  733. };
  734. MyBodyPairCallback add_pair(ioStep, contact_allocator, inJobIndex);
  735. // Copy active bodies to temporary array, broadphase will reorder them
  736. uint32 batch_size = active_bodies_read_idx_end - active_bodies_read_idx;
  737. memcpy(active_bodies, mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody) + active_bodies_read_idx, batch_size * sizeof(BodyID));
  738. // Find pairs in the broadphase
  739. mBroadPhase->FindCollidingPairs(active_bodies, batch_size, mPhysicsSettings.mSpeculativeContactDistance, *mObjectVsBroadPhaseLayerFilter, *mObjectLayerPairFilter, add_pair);
  740. // Check if we have enough pairs in the buffer to start a new job
  741. const PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[inJobIndex];
  742. uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;
  743. if (body_pairs_in_queue >= cNarrowPhaseBatchSize)
  744. TrySpawnJobFindCollisions(ioStep);
  745. }
  746. }
  747. else
  748. {
  749. // Lockless loop to get the next body pair from the pairs buffer
  750. const PhysicsUpdateContext *context = ioStep->mContext;
  751. int first_read_queue_idx = read_queue_idx;
  752. for (;;)
  753. {
  754. PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[read_queue_idx];
  755. // Get the next pair to process
  756. uint32 pair_idx = queue.mReadIdx;
  757. // If the pair hasn't been written yet
  758. if (pair_idx >= queue.mWriteIdx)
  759. {
  760. // Go to the next queue
  761. read_queue_idx = (read_queue_idx + 1) % ioStep->mBodyPairQueues.size();
  762. // If we're back at the first queue, we've looked at all of them and found nothing
  763. if (read_queue_idx == first_read_queue_idx)
  764. {
  765. // Collect information from the contact allocator and accumulate it in the step.
  766. sFinalizeContactAllocator(*ioStep, contact_allocator);
  767. // Mark this job as inactive
  768. ioStep->mActiveFindCollisionJobs.fetch_and(~PhysicsUpdateContext::JobMask(1 << inJobIndex), memory_order_release);
  769. // Trigger the next jobs
  770. ioStep->mUpdateBroadphaseFinalize.RemoveDependency();
  771. ioStep->mFinalizeIslands.RemoveDependency();
  772. return;
  773. }
  774. // Try again reading from the next queue
  775. continue;
  776. }
  777. // Copy the body pair out of the buffer
  778. const BodyPair bp = context->mBodyPairs[read_queue_idx * ioStep->mMaxBodyPairsPerQueue + pair_idx % ioStep->mMaxBodyPairsPerQueue];
  779. // Mark this pair as taken
  780. if (queue.mReadIdx.compare_exchange_strong(pair_idx, pair_idx + 1))
  781. {
  782. // Process the actual body pair
  783. ProcessBodyPair(contact_allocator, bp);
  784. break;
  785. }
  786. }
  787. }
  788. }
  789. }
  790. void PhysicsSystem::sDefaultSimCollideBodyVsBody(const Body &inBody1, const Body &inBody2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, CollideShapeSettings &ioCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter)
  791. {
  792. SubShapeIDCreator part1, part2;
  793. if (inBody1.GetEnhancedInternalEdgeRemovalWithBody(inBody2))
  794. {
  795. // Collide with enhanced internal edge removal
  796. ioCollideShapeSettings.mActiveEdgeMode = EActiveEdgeMode::CollideWithAll;
  797. InternalEdgeRemovingCollector::sCollideShapeVsShape(inBody1.GetShape(), inBody2.GetShape(), Vec3::sOne(), Vec3::sOne(), inCenterOfMassTransform1, inCenterOfMassTransform2, part1, part2, ioCollideShapeSettings, ioCollector, inShapeFilter);
  798. }
  799. else
  800. {
  801. // Regular collide
  802. CollisionDispatch::sCollideShapeVsShape(inBody1.GetShape(), inBody2.GetShape(), Vec3::sOne(), Vec3::sOne(), inCenterOfMassTransform1, inCenterOfMassTransform2, part1, part2, ioCollideShapeSettings, ioCollector, inShapeFilter);
  803. }
  804. }
  805. void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair)
  806. {
  807. JPH_PROFILE_FUNCTION();
  808. // Fetch body pair
  809. Body *body1 = &mBodyManager.GetBody(inBodyPair.mBodyA);
  810. Body *body2 = &mBodyManager.GetBody(inBodyPair.mBodyB);
  811. JPH_ASSERT(body1->IsActive());
  812. JPH_DET_LOG("ProcessBodyPair: id1: " << inBodyPair.mBodyA << " id2: " << inBodyPair.mBodyB << " p1: " << body1->GetCenterOfMassPosition() << " p2: " << body2->GetCenterOfMassPosition() << " r1: " << body1->GetRotation() << " r2: " << body2->GetRotation());
  813. // Check for soft bodies
  814. if (body2->IsSoftBody())
  815. {
  816. // If the 2nd body is a soft body and not active, we activate it now
  817. if (!body2->IsActive())
  818. mBodyManager.ActivateBodies(&inBodyPair.mBodyB, 1);
  819. // Soft body processing is done later in the pipeline
  820. return;
  821. }
  822. // Ensure that body1 has the higher motion type (i.e. dynamic trumps kinematic), this ensures that we do the collision detection in the space of a moving body,
  823. // which avoids accuracy problems when testing a very large static object against a small dynamic object
  824. // Ensure that body1 id < body2 id when motion types are the same.
  825. if (body1->GetMotionType() < body2->GetMotionType()
  826. || (body1->GetMotionType() == body2->GetMotionType() && inBodyPair.mBodyB < inBodyPair.mBodyA))
  827. std::swap(body1, body2);
  828. // Check if the contact points from the previous frame are reusable and if so copy them
  829. bool pair_handled = false, constraint_created = false;
  830. if (mPhysicsSettings.mUseBodyPairContactCache && !(body1->IsCollisionCacheInvalid() || body2->IsCollisionCacheInvalid()))
  831. mContactManager.GetContactsFromCache(ioContactAllocator, *body1, *body2, pair_handled, constraint_created);
  832. // If the cache hasn't handled this body pair do actual collision detection
  833. if (!pair_handled)
  834. {
  835. // Create entry in the cache for this body pair
  836. // Needs to happen irrespective if we found a collision or not (we want to remember that no collision was found too)
  837. ContactConstraintManager::BodyPairHandle body_pair_handle = mContactManager.AddBodyPair(ioContactAllocator, *body1, *body2);
  838. if (body_pair_handle == nullptr)
  839. return; // Out of cache space
  840. // Create the query settings
  841. CollideShapeSettings settings;
  842. settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;
  843. settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  844. settings.mMaxSeparationDistance = body1->IsSensor() || body2->IsSensor()? 0.0f : mPhysicsSettings.mSpeculativeContactDistance;
  845. settings.mActiveEdgeMovementDirection = body1->GetLinearVelocity() - body2->GetLinearVelocity();
  846. // Create shape filter
  847. SimShapeFilterWrapperUnion shape_filter_union(mSimShapeFilter, body1);
  848. SimShapeFilterWrapper &shape_filter = shape_filter_union.GetSimShapeFilterWrapper();
  849. shape_filter.SetBody2(body2);
  850. // Get transforms relative to body1
  851. RVec3 offset = body1->GetCenterOfMassPosition();
  852. Mat44 transform1 = Mat44::sRotation(body1->GetRotation());
  853. Mat44 transform2 = body2->GetCenterOfMassTransform().PostTranslated(-offset).ToMat44();
  854. if (mPhysicsSettings.mUseManifoldReduction // Check global flag
  855. && body1->GetUseManifoldReductionWithBody(*body2)) // Check body flag
  856. {
  857. // Version WITH contact manifold reduction
  858. class MyManifold : public ContactManifold
  859. {
  860. public:
  861. Vec3 mFirstWorldSpaceNormal;
  862. };
  863. // A temporary structure that allows us to keep track of the all manifolds between this body pair
  864. using Manifolds = StaticArray<MyManifold, 32>;
  865. // Create collector
  866. class ReductionCollideShapeCollector : public CollideShapeCollector
  867. {
  868. public:
  869. ReductionCollideShapeCollector(PhysicsSystem *inSystem, const Body *inBody1, const Body *inBody2) :
  870. mSystem(inSystem),
  871. mBody1(inBody1),
  872. mBody2(inBody2)
  873. {
  874. }
  875. virtual void AddHit(const CollideShapeResult &inResult) override
  876. {
  877. // The first body should be the one with the highest motion type
  878. JPH_ASSERT(mBody1->GetMotionType() >= mBody2->GetMotionType());
  879. JPH_ASSERT(!ShouldEarlyOut());
  880. // Test if we want to accept this hit
  881. if (mValidateBodyPair)
  882. {
  883. switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, mBody1->GetCenterOfMassPosition(), inResult))
  884. {
  885. case ValidateResult::AcceptContact:
  886. // We're just accepting this one, nothing to do
  887. break;
  888. case ValidateResult::AcceptAllContactsForThisBodyPair:
  889. // Accept and stop calling the validate callback
  890. mValidateBodyPair = false;
  891. break;
  892. case ValidateResult::RejectContact:
  893. // Skip this contact
  894. return;
  895. case ValidateResult::RejectAllContactsForThisBodyPair:
  896. // Skip this and early out
  897. ForceEarlyOut();
  898. return;
  899. }
  900. }
  901. // Calculate normal
  902. Vec3 world_space_normal = inResult.mPenetrationAxis.Normalized();
  903. // Check if we can add it to an existing manifold
  904. Manifolds::iterator manifold;
  905. float contact_normal_cos_max_delta_rot = mSystem->mPhysicsSettings.mContactNormalCosMaxDeltaRotation;
  906. for (manifold = mManifolds.begin(); manifold != mManifolds.end(); ++manifold)
  907. if (world_space_normal.Dot(manifold->mFirstWorldSpaceNormal) >= contact_normal_cos_max_delta_rot)
  908. {
  909. // Update average normal
  910. manifold->mWorldSpaceNormal += world_space_normal;
  911. manifold->mPenetrationDepth = max(manifold->mPenetrationDepth, inResult.mPenetrationDepth);
  912. break;
  913. }
  914. if (manifold == mManifolds.end())
  915. {
  916. // Check if array is full
  917. if (mManifolds.size() == mManifolds.capacity())
  918. {
  919. // Full, find manifold with least amount of penetration
  920. manifold = mManifolds.begin();
  921. for (Manifolds::iterator m = mManifolds.begin() + 1; m < mManifolds.end(); ++m)
  922. if (m->mPenetrationDepth < manifold->mPenetrationDepth)
  923. manifold = m;
  924. // If this contacts penetration is smaller than the smallest manifold, we skip this contact
  925. if (inResult.mPenetrationDepth < manifold->mPenetrationDepth)
  926. return;
  927. // Replace the manifold
  928. *manifold = { { mBody1->GetCenterOfMassPosition(), world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal };
  929. }
  930. else
  931. {
  932. // Not full, create new manifold
  933. mManifolds.push_back({ { mBody1->GetCenterOfMassPosition(), world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal });
  934. manifold = mManifolds.end() - 1;
  935. }
  936. }
  937. // Determine contact points
  938. const PhysicsSettings &settings = mSystem->mPhysicsSettings;
  939. ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, settings.mSpeculativeContactDistance + settings.mManifoldTolerance, inResult.mShape1Face, inResult.mShape2Face, manifold->mRelativeContactPointsOn1, manifold->mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, mBody1->GetCenterOfMassPosition()));
  940. // Prune if we have more than 32 points (this means we could run out of space in the next iteration)
  941. if (manifold->mRelativeContactPointsOn1.size() > 32)
  942. PruneContactPoints(manifold->mFirstWorldSpaceNormal, manifold->mRelativeContactPointsOn1, manifold->mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold->mBaseOffset));
  943. }
  944. PhysicsSystem * mSystem;
  945. const Body * mBody1;
  946. const Body * mBody2;
  947. bool mValidateBodyPair = true;
  948. Manifolds mManifolds;
  949. };
  950. ReductionCollideShapeCollector collector(this, body1, body2);
  951. // Perform collision detection between the two shapes
  952. mSimCollideBodyVsBody(*body1, *body2, transform1, transform2, settings, collector, shape_filter);
  953. // Add the contacts
  954. for (ContactManifold &manifold : collector.mManifolds)
  955. {
  956. // Normalize the normal (is a sum of all normals from merged manifolds)
  957. manifold.mWorldSpaceNormal = manifold.mWorldSpaceNormal.Normalized();
  958. // If we still have too many points, prune them now
  959. if (manifold.mRelativeContactPointsOn1.size() > 4)
  960. PruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  961. // Actually add the contact points to the manager
  962. constraint_created |= mContactManager.AddContactConstraint(ioContactAllocator, body_pair_handle, *body1, *body2, manifold);
  963. }
  964. }
  965. else
  966. {
  967. // Version WITHOUT contact manifold reduction
  968. // Create collector
  969. class NonReductionCollideShapeCollector : public CollideShapeCollector
  970. {
  971. public:
  972. NonReductionCollideShapeCollector(PhysicsSystem *inSystem, ContactAllocator &ioContactAllocator, Body *inBody1, Body *inBody2, const ContactConstraintManager::BodyPairHandle &inPairHandle) :
  973. mSystem(inSystem),
  974. mContactAllocator(ioContactAllocator),
  975. mBody1(inBody1),
  976. mBody2(inBody2),
  977. mBodyPairHandle(inPairHandle)
  978. {
  979. }
  980. virtual void AddHit(const CollideShapeResult &inResult) override
  981. {
  982. // The first body should be the one with the highest motion type
  983. JPH_ASSERT(mBody1->GetMotionType() >= mBody2->GetMotionType());
  984. JPH_ASSERT(!ShouldEarlyOut());
  985. // Test if we want to accept this hit
  986. if (mValidateBodyPair)
  987. {
  988. switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, mBody1->GetCenterOfMassPosition(), inResult))
  989. {
  990. case ValidateResult::AcceptContact:
  991. // We're just accepting this one, nothing to do
  992. break;
  993. case ValidateResult::AcceptAllContactsForThisBodyPair:
  994. // Accept and stop calling the validate callback
  995. mValidateBodyPair = false;
  996. break;
  997. case ValidateResult::RejectContact:
  998. // Skip this contact
  999. return;
  1000. case ValidateResult::RejectAllContactsForThisBodyPair:
  1001. // Skip this and early out
  1002. ForceEarlyOut();
  1003. return;
  1004. }
  1005. }
  1006. // Determine contact points
  1007. ContactManifold manifold;
  1008. manifold.mBaseOffset = mBody1->GetCenterOfMassPosition();
  1009. const PhysicsSettings &settings = mSystem->mPhysicsSettings;
  1010. ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, settings.mSpeculativeContactDistance + settings.mManifoldTolerance, inResult.mShape1Face, inResult.mShape2Face, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  1011. // Calculate normal
  1012. manifold.mWorldSpaceNormal = inResult.mPenetrationAxis.Normalized();
  1013. // Store penetration depth
  1014. manifold.mPenetrationDepth = inResult.mPenetrationDepth;
  1015. // Prune if we have more than 4 points
  1016. if (manifold.mRelativeContactPointsOn1.size() > 4)
  1017. PruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  1018. // Set other properties
  1019. manifold.mSubShapeID1 = inResult.mSubShapeID1;
  1020. manifold.mSubShapeID2 = inResult.mSubShapeID2;
  1021. // Actually add the contact points to the manager
  1022. mConstraintCreated |= mSystem->mContactManager.AddContactConstraint(mContactAllocator, mBodyPairHandle, *mBody1, *mBody2, manifold);
  1023. }
  1024. PhysicsSystem * mSystem;
  1025. ContactAllocator & mContactAllocator;
  1026. Body * mBody1;
  1027. Body * mBody2;
  1028. ContactConstraintManager::BodyPairHandle mBodyPairHandle;
  1029. bool mValidateBodyPair = true;
  1030. bool mConstraintCreated = false;
  1031. };
  1032. NonReductionCollideShapeCollector collector(this, ioContactAllocator, body1, body2, body_pair_handle);
  1033. // Perform collision detection between the two shapes
  1034. mSimCollideBodyVsBody(*body1, *body2, transform1, transform2, settings, collector, shape_filter);
  1035. constraint_created = collector.mConstraintCreated;
  1036. }
  1037. }
  1038. // If a contact constraint was created, we need to do some extra work
  1039. if (constraint_created)
  1040. {
  1041. // Wake up sleeping bodies
  1042. BodyID body_ids[2];
  1043. int num_bodies = 0;
  1044. if (body1->IsDynamic() && !body1->IsActive())
  1045. body_ids[num_bodies++] = body1->GetID();
  1046. if (body2->IsDynamic() && !body2->IsActive())
  1047. body_ids[num_bodies++] = body2->GetID();
  1048. if (num_bodies > 0)
  1049. mBodyManager.ActivateBodies(body_ids, num_bodies);
  1050. // Link the two bodies
  1051. mIslandBuilder.LinkBodies(body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  1052. }
  1053. }
  1054. void PhysicsSystem::JobFinalizeIslands(PhysicsUpdateContext *ioContext)
  1055. {
  1056. #ifdef JPH_ENABLE_ASSERTS
  1057. // We only touch island data
  1058. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1059. #endif
  1060. // Finish collecting the islands, at this point the active body list doesn't change so it's safe to access
  1061. mIslandBuilder.Finalize(mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody), mBodyManager.GetNumActiveBodies(EBodyType::RigidBody), mContactManager.GetNumConstraints(), ioContext->mTempAllocator);
  1062. // Prepare the large island splitter
  1063. if (mPhysicsSettings.mUseLargeIslandSplitter)
  1064. mLargeIslandSplitter.Prepare(mIslandBuilder, mBodyManager.GetNumActiveBodies(EBodyType::RigidBody), ioContext->mTempAllocator);
  1065. }
  1066. void PhysicsSystem::JobBodySetIslandIndex()
  1067. {
  1068. #ifdef JPH_ENABLE_ASSERTS
  1069. // We only touch island data
  1070. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1071. #endif
  1072. // Loop through the result and tag all bodies with an island index
  1073. for (uint32 island_idx = 0, n = mIslandBuilder.GetNumIslands(); island_idx < n; ++island_idx)
  1074. {
  1075. BodyID *body_start, *body_end;
  1076. mIslandBuilder.GetBodiesInIsland(island_idx, body_start, body_end);
  1077. for (const BodyID *body = body_start; body < body_end; ++body)
  1078. mBodyManager.GetBody(*body).GetMotionProperties()->SetIslandIndexInternal(island_idx);
  1079. }
  1080. }
  1081. JPH_SUPPRESS_WARNING_PUSH
  1082. JPH_CLANG_SUPPRESS_WARNING("-Wundefined-func-template") // ConstraintManager::sWarmStartVelocityConstraints / ContactConstraintManager::WarmStartVelocityConstraints is instantiated in the cpp file
  1083. void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  1084. {
  1085. #ifdef JPH_ENABLE_ASSERTS
  1086. // We update velocities and need to read positions to do so
  1087. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  1088. #endif
  1089. float delta_time = ioContext->mStepDeltaTime;
  1090. Constraint **active_constraints = ioContext->mActiveConstraints;
  1091. // Only the first step to correct for the delta time difference in the previous update
  1092. float warm_start_impulse_ratio = ioStep->mIsFirst? ioContext->mWarmStartImpulseRatio : 1.0f;
  1093. bool check_islands = true, check_split_islands = mPhysicsSettings.mUseLargeIslandSplitter;
  1094. for (;;)
  1095. {
  1096. // First try to get work from large islands
  1097. if (check_split_islands)
  1098. {
  1099. bool first_iteration;
  1100. uint split_island_index;
  1101. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1102. switch (mLargeIslandSplitter.FetchNextBatch(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, first_iteration))
  1103. {
  1104. case LargeIslandSplitter::EStatus::BatchRetrieved:
  1105. {
  1106. if (first_iteration)
  1107. {
  1108. // Iteration 0 is used to warm start the batch (we added 1 to the number of iterations in LargeIslandSplitter::SplitIsland)
  1109. DummyCalculateSolverSteps dummy;
  1110. ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio, dummy);
  1111. mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio, dummy);
  1112. }
  1113. else
  1114. {
  1115. // Solve velocity constraints
  1116. ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1117. mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);
  1118. }
  1119. // Mark the batch as processed
  1120. bool last_iteration, final_batch;
  1121. mLargeIslandSplitter.MarkBatchProcessed(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, last_iteration, final_batch);
  1122. // Save back the lambdas in the contact cache for the warm start of the next physics update
  1123. if (last_iteration)
  1124. mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);
  1125. // We processed work, loop again
  1126. continue;
  1127. }
  1128. case LargeIslandSplitter::EStatus::WaitingForBatch:
  1129. break;
  1130. case LargeIslandSplitter::EStatus::AllBatchesDone:
  1131. check_split_islands = false;
  1132. break;
  1133. }
  1134. }
  1135. // If that didn't succeed try to process an island
  1136. if (check_islands)
  1137. {
  1138. // Next island
  1139. uint32 island_idx = ioStep->mSolveVelocityConstraintsNextIsland++;
  1140. if (island_idx >= mIslandBuilder.GetNumIslands())
  1141. {
  1142. // We processed all islands, stop checking islands
  1143. check_islands = false;
  1144. continue;
  1145. }
  1146. JPH_PROFILE("Island");
  1147. // Get iterators for this island
  1148. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1149. bool has_constraints = mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);
  1150. bool has_contacts = mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);
  1151. // If we don't have any contacts or constraints, we know that none of the following islands have any contacts or constraints
  1152. // (because they're sorted by most constraints first). This means we're done.
  1153. if (!has_contacts && !has_constraints)
  1154. {
  1155. #ifdef JPH_ENABLE_ASSERTS
  1156. // Validate our assumption that the next islands don't have any constraints or contacts
  1157. for (; island_idx < mIslandBuilder.GetNumIslands(); ++island_idx)
  1158. {
  1159. JPH_ASSERT(!mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end));
  1160. JPH_ASSERT(!mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end));
  1161. }
  1162. #endif // JPH_ENABLE_ASSERTS
  1163. check_islands = false;
  1164. continue;
  1165. }
  1166. // Sorting is costly but needed for a deterministic simulation, allow the user to turn this off
  1167. if (mPhysicsSettings.mDeterministicSimulation)
  1168. {
  1169. // Sort constraints to give a deterministic simulation
  1170. ConstraintManager::sSortConstraints(active_constraints, constraints_begin, constraints_end);
  1171. // Sort contacts to give a deterministic simulation
  1172. mContactManager.SortContacts(contacts_begin, contacts_end);
  1173. }
  1174. // Split up large islands
  1175. CalculateSolverSteps steps_calculator(mPhysicsSettings);
  1176. if (mPhysicsSettings.mUseLargeIslandSplitter
  1177. && mLargeIslandSplitter.SplitIsland(island_idx, mIslandBuilder, mBodyManager, mContactManager, active_constraints, steps_calculator))
  1178. continue; // Loop again to try to fetch the newly split island
  1179. // We didn't create a split, just run the solver now for this entire island. Begin by warm starting.
  1180. ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio, steps_calculator);
  1181. mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio, steps_calculator);
  1182. steps_calculator.Finalize();
  1183. // Store the number of position steps for later
  1184. mIslandBuilder.SetNumPositionSteps(island_idx, steps_calculator.GetNumPositionSteps());
  1185. // Solve velocity constraints
  1186. for (uint velocity_step = 0; velocity_step < steps_calculator.GetNumVelocitySteps(); ++velocity_step)
  1187. {
  1188. bool applied_impulse = ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1189. applied_impulse |= mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);
  1190. if (!applied_impulse)
  1191. break;
  1192. }
  1193. // Save back the lambdas in the contact cache for the warm start of the next physics update
  1194. mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);
  1195. // We processed work, loop again
  1196. continue;
  1197. }
  1198. if (check_islands)
  1199. {
  1200. // If there are islands, we don't need to wait and can pick up new work
  1201. continue;
  1202. }
  1203. else if (check_split_islands)
  1204. {
  1205. // If there are split islands, but we didn't do any work, give up a time slice
  1206. std::this_thread::yield();
  1207. }
  1208. else
  1209. {
  1210. // No more work
  1211. break;
  1212. }
  1213. }
  1214. }
  1215. JPH_SUPPRESS_WARNING_POP
  1216. void PhysicsSystem::JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  1217. {
  1218. // Reserve enough space for all bodies that may need a cast
  1219. TempAllocator *temp_allocator = ioContext->mTempAllocator;
  1220. JPH_ASSERT(ioStep->mCCDBodies == nullptr);
  1221. ioStep->mCCDBodiesCapacity = mBodyManager.GetNumActiveCCDBodies();
  1222. ioStep->mCCDBodies = (CCDBody *)temp_allocator->Allocate(ioStep->mCCDBodiesCapacity * sizeof(CCDBody));
  1223. // Initialize the mapping table between active body and CCD body
  1224. JPH_ASSERT(ioStep->mActiveBodyToCCDBody == nullptr);
  1225. ioStep->mNumActiveBodyToCCDBody = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);
  1226. ioStep->mActiveBodyToCCDBody = (int *)temp_allocator->Allocate(ioStep->mNumActiveBodyToCCDBody * sizeof(int));
  1227. // Prepare the split island builder for solving the position constraints
  1228. mLargeIslandSplitter.PrepareForSolvePositions();
  1229. }
  1230. void PhysicsSystem::JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  1231. {
  1232. #ifdef JPH_ENABLE_ASSERTS
  1233. // We update positions and need velocity to do so, we also clamp velocities so need to write to them
  1234. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  1235. #endif
  1236. float delta_time = ioContext->mStepDeltaTime;
  1237. const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody);
  1238. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);
  1239. uint32 num_active_bodies_after_find_collisions = ioStep->mActiveBodyReadIdx;
  1240. // We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.
  1241. static constexpr int cBodiesBatch = 64;
  1242. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1243. int num_bodies_to_update_bounds = 0;
  1244. for (;;)
  1245. {
  1246. // Atomically fetch a batch of bodies
  1247. uint32 active_body_idx = ioStep->mIntegrateVelocityReadIdx.fetch_add(cIntegrateVelocityBatchSize);
  1248. if (active_body_idx >= num_active_bodies)
  1249. break;
  1250. // Calculate the end of the batch
  1251. uint32 active_body_idx_end = min(num_active_bodies, active_body_idx + cIntegrateVelocityBatchSize);
  1252. // Process the batch
  1253. while (active_body_idx < active_body_idx_end)
  1254. {
  1255. // Update the positions using an Symplectic Euler step (which integrates using the updated velocity v1' rather
  1256. // than the original velocity v1):
  1257. // x1' = x1 + h * v1'
  1258. // At this point the active bodies list does not change, so it is safe to access the array.
  1259. BodyID body_id = active_bodies[active_body_idx];
  1260. Body &body = mBodyManager.GetBody(body_id);
  1261. MotionProperties *mp = body.GetMotionProperties();
  1262. JPH_DET_LOG("JobIntegrateVelocity: id: " << body_id << " v: " << body.GetLinearVelocity() << " w: " << body.GetAngularVelocity());
  1263. // Clamp velocities (not for kinematic bodies)
  1264. if (body.IsDynamic())
  1265. {
  1266. mp->ClampLinearVelocity();
  1267. mp->ClampAngularVelocity();
  1268. }
  1269. // Update the rotation of the body according to the angular velocity
  1270. // For motion type discrete we need to do this anyway, for motion type linear cast we have multiple choices
  1271. // 1. Rotate the body first and then sweep
  1272. // 2. First sweep and then rotate the body at the end
  1273. // 3. Pick some in between rotation (e.g. half way), then sweep and finally rotate the remainder
  1274. // (1) has some clear advantages as when a long thin body hits a surface away from the center of mass, this will result in a large angular velocity and a limited reduction in linear velocity.
  1275. // When simulation the rotation first before doing the translation, the body will be able to rotate away from the contact point allowing the center of mass to approach the surface. When using
  1276. // approach (2) in this case what will happen is that we will immediately detect the same collision again (the body has not rotated and the body was already colliding at the end of the previous
  1277. // time step) resulting in a lot of stolen time and the body appearing to be frozen in an unnatural pose (like it is glued at an angle to the surface). (2) obviously has some negative side effects
  1278. // too as simulating the rotation first may cause it to tunnel through a small object that the linear cast might have otherwise detected. In any case a linear cast is not good for detecting
  1279. // tunneling due to angular rotation, so we don't care about that too much (you'd need a full cast to take angular effects into account).
  1280. body.AddRotationStep(body.GetAngularVelocity() * delta_time);
  1281. // Get delta position
  1282. Vec3 delta_pos = body.GetLinearVelocity() * delta_time;
  1283. // If the position should be updated (or if it is delayed because of CCD)
  1284. bool update_position = true;
  1285. switch (mp->GetMotionQuality())
  1286. {
  1287. case EMotionQuality::Discrete:
  1288. // No additional collision checking to be done
  1289. break;
  1290. case EMotionQuality::LinearCast:
  1291. if (body.IsDynamic() // Kinematic bodies cannot be stopped
  1292. && !body.IsSensor()) // We don't support CCD sensors
  1293. {
  1294. // Determine inner radius (the smallest sphere that fits into the shape)
  1295. float inner_radius = body.GetShape()->GetInnerRadius();
  1296. JPH_ASSERT(inner_radius > 0.0f, "The shape has no inner radius, this makes the shape unsuitable for the linear cast motion quality as we cannot move it without risking tunneling.");
  1297. // Measure translation in this step and check if it above the threshold to perform a linear cast
  1298. float linear_cast_threshold_sq = Square(mPhysicsSettings.mLinearCastThreshold * inner_radius);
  1299. if (delta_pos.LengthSq() > linear_cast_threshold_sq)
  1300. {
  1301. // This body needs a cast
  1302. uint32 ccd_body_idx = ioStep->mNumCCDBodies++;
  1303. JPH_ASSERT(active_body_idx < ioStep->mNumActiveBodyToCCDBody);
  1304. ioStep->mActiveBodyToCCDBody[active_body_idx] = ccd_body_idx;
  1305. new (&ioStep->mCCDBodies[ccd_body_idx]) CCDBody(body_id, delta_pos, linear_cast_threshold_sq, min(mPhysicsSettings.mPenetrationSlop, mPhysicsSettings.mLinearCastMaxPenetration * inner_radius));
  1306. update_position = false;
  1307. }
  1308. }
  1309. break;
  1310. }
  1311. if (update_position)
  1312. {
  1313. // Move the body now
  1314. body.AddPositionStep(delta_pos);
  1315. // If the body was activated due to an earlier CCD step it will have an index in the active
  1316. // body list that it higher than the highest one we processed during FindCollisions
  1317. // which means it hasn't been assigned an island and will not be updated by an island
  1318. // this means that we need to update its bounds manually
  1319. if (mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)
  1320. {
  1321. body.CalculateWorldSpaceBoundsInternal();
  1322. bodies_to_update_bounds[num_bodies_to_update_bounds++] = body.GetID();
  1323. if (num_bodies_to_update_bounds == cBodiesBatch)
  1324. {
  1325. // Buffer full, flush now
  1326. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1327. num_bodies_to_update_bounds = 0;
  1328. }
  1329. }
  1330. // We did not create a CCD body
  1331. ioStep->mActiveBodyToCCDBody[active_body_idx] = -1;
  1332. }
  1333. active_body_idx++;
  1334. }
  1335. }
  1336. // Notify change bounds on requested bodies
  1337. if (num_bodies_to_update_bounds > 0)
  1338. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1339. }
  1340. void PhysicsSystem::JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep) const
  1341. {
  1342. // Validate that our reservations were correct
  1343. JPH_ASSERT(ioStep->mNumCCDBodies <= mBodyManager.GetNumActiveCCDBodies());
  1344. if (ioStep->mNumCCDBodies == 0)
  1345. {
  1346. // No continuous collision detection jobs -> kick the next job ourselves
  1347. ioStep->mContactRemovedCallbacks.RemoveDependency();
  1348. }
  1349. else
  1350. {
  1351. // Run the continuous collision detection jobs
  1352. int num_continuous_collision_jobs = min(int(ioStep->mNumCCDBodies + cNumCCDBodiesPerJob - 1) / cNumCCDBodiesPerJob, ioContext->GetMaxConcurrency());
  1353. ioStep->mResolveCCDContacts.AddDependency(num_continuous_collision_jobs);
  1354. ioStep->mContactRemovedCallbacks.AddDependency(num_continuous_collision_jobs - 1); // Already had 1 dependency
  1355. for (int i = 0; i < num_continuous_collision_jobs; ++i)
  1356. {
  1357. JobHandle job = ioContext->mJobSystem->CreateJob("FindCCDContacts", cColorFindCCDContacts, [ioContext, ioStep]()
  1358. {
  1359. ioContext->mPhysicsSystem->JobFindCCDContacts(ioContext, ioStep);
  1360. ioStep->mResolveCCDContacts.RemoveDependency();
  1361. ioStep->mContactRemovedCallbacks.RemoveDependency();
  1362. });
  1363. ioContext->mBarrier->AddJob(job);
  1364. }
  1365. }
  1366. }
  1367. // Helper function to calculate the motion of a body during this CCD step
  1368. inline static Vec3 sCalculateBodyMotion(const Body &inBody, float inDeltaTime)
  1369. {
  1370. // If the body is linear casting, the body has not yet moved so we need to calculate its motion
  1371. if (inBody.IsDynamic() && inBody.GetMotionProperties()->GetMotionQuality() == EMotionQuality::LinearCast)
  1372. return inDeltaTime * inBody.GetLinearVelocity();
  1373. // Body has already moved, so we don't need to correct for anything
  1374. return Vec3::sZero();
  1375. }
  1376. // Helper function that finds the CCD body corresponding to a body (if it exists)
  1377. inline static PhysicsUpdateContext::Step::CCDBody *sGetCCDBody(const Body &inBody, PhysicsUpdateContext::Step *inStep)
  1378. {
  1379. // Only rigid bodies can have a CCD body
  1380. if (!inBody.IsRigidBody())
  1381. return nullptr;
  1382. // If the body has no motion properties it cannot have a CCD body
  1383. const MotionProperties *motion_properties = inBody.GetMotionPropertiesUnchecked();
  1384. if (motion_properties == nullptr)
  1385. return nullptr;
  1386. // If it is not active it cannot have a CCD body
  1387. uint32 active_index = motion_properties->GetIndexInActiveBodiesInternal();
  1388. if (active_index == Body::cInactiveIndex)
  1389. return nullptr;
  1390. // Check if the active body has a corresponding CCD body
  1391. JPH_ASSERT(active_index < inStep->mNumActiveBodyToCCDBody); // Ensure that the body has a mapping to CCD body
  1392. int ccd_index = inStep->mActiveBodyToCCDBody[active_index];
  1393. if (ccd_index < 0)
  1394. return nullptr;
  1395. PhysicsUpdateContext::Step::CCDBody *ccd_body = &inStep->mCCDBodies[ccd_index];
  1396. JPH_ASSERT(ccd_body->mBodyID1 == inBody.GetID(), "We found the wrong CCD body!");
  1397. return ccd_body;
  1398. }
  1399. void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  1400. {
  1401. #ifdef JPH_ENABLE_ASSERTS
  1402. // We only read positions, but the validate callback may read body positions and velocities
  1403. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  1404. #endif
  1405. // Allocation context for allocating new contact points
  1406. ContactAllocator contact_allocator(mContactManager.GetContactAllocator());
  1407. // Settings
  1408. ShapeCastSettings settings;
  1409. settings.mUseShrunkenShapeAndConvexRadius = true;
  1410. settings.mBackFaceModeTriangles = EBackFaceMode::IgnoreBackFaces;
  1411. settings.mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;
  1412. settings.mReturnDeepestPoint = true;
  1413. settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;
  1414. settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  1415. for (;;)
  1416. {
  1417. // Fetch the next body to cast
  1418. uint32 idx = ioStep->mNextCCDBody++;
  1419. if (idx >= ioStep->mNumCCDBodies)
  1420. break;
  1421. CCDBody &ccd_body = ioStep->mCCDBodies[idx];
  1422. const Body &body = mBodyManager.GetBody(ccd_body.mBodyID1);
  1423. // Filter out layers
  1424. DefaultBroadPhaseLayerFilter broadphase_layer_filter = GetDefaultBroadPhaseLayerFilter(body.GetObjectLayer());
  1425. DefaultObjectLayerFilter object_layer_filter = GetDefaultLayerFilter(body.GetObjectLayer());
  1426. #ifdef JPH_DEBUG_RENDERER
  1427. // Draw start and end shape of cast
  1428. if (sDrawMotionQualityLinearCast)
  1429. {
  1430. RMat44 com = body.GetCenterOfMassTransform();
  1431. body.GetShape()->Draw(DebugRenderer::sInstance, com, Vec3::sOne(), Color::sGreen, false, true);
  1432. DebugRenderer::sInstance->DrawArrow(com.GetTranslation(), com.GetTranslation() + ccd_body.mDeltaPosition, Color::sGreen, 0.1f);
  1433. body.GetShape()->Draw(DebugRenderer::sInstance, com.PostTranslated(ccd_body.mDeltaPosition), Vec3::sOne(), Color::sRed, false, true);
  1434. }
  1435. #endif // JPH_DEBUG_RENDERER
  1436. // Create a collector that will find the maximum distance allowed to travel while not penetrating more than 'max penetration'
  1437. class CCDNarrowPhaseCollector : public CastShapeCollector
  1438. {
  1439. public:
  1440. CCDNarrowPhaseCollector(const BodyManager &inBodyManager, ContactConstraintManager &inContactConstraintManager, CCDBody &inCCDBody, ShapeCastResult &inResult, float inDeltaTime) :
  1441. mBodyManager(inBodyManager),
  1442. mContactConstraintManager(inContactConstraintManager),
  1443. mCCDBody(inCCDBody),
  1444. mResult(inResult),
  1445. mDeltaTime(inDeltaTime)
  1446. {
  1447. }
  1448. virtual void AddHit(const ShapeCastResult &inResult) override
  1449. {
  1450. JPH_PROFILE_FUNCTION();
  1451. // Check if this is a possible earlier hit than the one before
  1452. float fraction = inResult.mFraction;
  1453. if (fraction < mCCDBody.mFractionPlusSlop)
  1454. {
  1455. // Normalize normal
  1456. Vec3 normal = inResult.mPenetrationAxis.Normalized();
  1457. // Calculate how much we can add to the fraction to penetrate the collision point by mMaxPenetration.
  1458. // Note that the normal is pointing towards body 2!
  1459. // Let the extra distance that we can travel along delta_pos be 'dist': mMaxPenetration / dist = cos(angle between normal and delta_pos) = normal . delta_pos / |delta_pos|
  1460. // <=> dist = mMaxPenetration * |delta_pos| / normal . delta_pos
  1461. // Converting to a faction: delta_fraction = dist / |delta_pos| = mLinearCastTreshold / normal . delta_pos
  1462. float denominator = normal.Dot(mCCDBody.mDeltaPosition);
  1463. if (denominator > mCCDBody.mMaxPenetration) // Avoid dividing by zero, if extra hit fraction > 1 there's also no point in continuing
  1464. {
  1465. float fraction_plus_slop = fraction + mCCDBody.mMaxPenetration / denominator;
  1466. if (fraction_plus_slop < mCCDBody.mFractionPlusSlop)
  1467. {
  1468. const Body &body2 = mBodyManager.GetBody(inResult.mBodyID2);
  1469. // Check if we've already accepted all hits from this body
  1470. if (mValidateBodyPair)
  1471. {
  1472. // Validate the contact result
  1473. const Body &body1 = mBodyManager.GetBody(mCCDBody.mBodyID1);
  1474. ValidateResult validate_result = mContactConstraintManager.ValidateContactPoint(body1, body2, body1.GetCenterOfMassPosition(), inResult); // Note that the center of mass of body 1 is the start of the sweep and is used as base offset below
  1475. switch (validate_result)
  1476. {
  1477. case ValidateResult::AcceptContact:
  1478. // Just continue
  1479. break;
  1480. case ValidateResult::AcceptAllContactsForThisBodyPair:
  1481. // Accept this and all following contacts from this body
  1482. mValidateBodyPair = false;
  1483. break;
  1484. case ValidateResult::RejectContact:
  1485. return;
  1486. case ValidateResult::RejectAllContactsForThisBodyPair:
  1487. // Reject this and all following contacts from this body
  1488. mRejectAll = true;
  1489. ForceEarlyOut();
  1490. return;
  1491. }
  1492. }
  1493. // This is the earliest hit so far, store it
  1494. mCCDBody.mContactNormal = normal;
  1495. mCCDBody.mBodyID2 = inResult.mBodyID2;
  1496. mCCDBody.mSubShapeID2 = inResult.mSubShapeID2;
  1497. mCCDBody.mFraction = fraction;
  1498. mCCDBody.mFractionPlusSlop = fraction_plus_slop;
  1499. mResult = inResult;
  1500. // Result was assuming body 2 is not moving, but it is, so we need to correct for it
  1501. Vec3 movement2 = fraction * sCalculateBodyMotion(body2, mDeltaTime);
  1502. if (!movement2.IsNearZero())
  1503. {
  1504. mResult.mContactPointOn1 += movement2;
  1505. mResult.mContactPointOn2 += movement2;
  1506. for (Vec3 &v : mResult.mShape1Face)
  1507. v += movement2;
  1508. for (Vec3 &v : mResult.mShape2Face)
  1509. v += movement2;
  1510. }
  1511. // Update early out fraction
  1512. UpdateEarlyOutFraction(fraction_plus_slop);
  1513. }
  1514. }
  1515. }
  1516. }
  1517. bool mValidateBodyPair; ///< If we still have to call the ValidateContactPoint for this body pair
  1518. bool mRejectAll; ///< Reject all further contacts between this body pair
  1519. private:
  1520. const BodyManager & mBodyManager;
  1521. ContactConstraintManager & mContactConstraintManager;
  1522. CCDBody & mCCDBody;
  1523. ShapeCastResult & mResult;
  1524. float mDeltaTime;
  1525. BodyID mAcceptedBodyID;
  1526. };
  1527. // Narrowphase collector
  1528. ShapeCastResult cast_shape_result;
  1529. CCDNarrowPhaseCollector np_collector(mBodyManager, mContactManager, ccd_body, cast_shape_result, ioContext->mStepDeltaTime);
  1530. // This collector wraps the narrowphase collector and collects the closest hit
  1531. class CCDBroadPhaseCollector : public CastShapeBodyCollector
  1532. {
  1533. public:
  1534. CCDBroadPhaseCollector(const CCDBody &inCCDBody, const Body &inBody1, const RShapeCast &inShapeCast, ShapeCastSettings &inShapeCastSettings, SimShapeFilterWrapper &inShapeFilter, CCDNarrowPhaseCollector &ioCollector, const BodyManager &inBodyManager, PhysicsUpdateContext::Step *inStep, float inDeltaTime) :
  1535. mCCDBody(inCCDBody),
  1536. mBody1(inBody1),
  1537. mBody1Extent(inShapeCast.mShapeWorldBounds.GetExtent()),
  1538. mShapeCast(inShapeCast),
  1539. mShapeCastSettings(inShapeCastSettings),
  1540. mShapeFilter(inShapeFilter),
  1541. mCollector(ioCollector),
  1542. mBodyManager(inBodyManager),
  1543. mStep(inStep),
  1544. mDeltaTime(inDeltaTime)
  1545. {
  1546. }
  1547. virtual void AddHit(const BroadPhaseCastResult &inResult) override
  1548. {
  1549. JPH_PROFILE_FUNCTION();
  1550. JPH_ASSERT(inResult.mFraction <= GetEarlyOutFraction(), "This hit should not have been passed on to the collector");
  1551. // Test if we're colliding with ourselves
  1552. if (mBody1.GetID() == inResult.mBodyID)
  1553. return;
  1554. // Avoid treating duplicates, if both bodies are doing CCD then only consider collision if body ID < other body ID
  1555. const Body &body2 = mBodyManager.GetBody(inResult.mBodyID);
  1556. const CCDBody *ccd_body2 = sGetCCDBody(body2, mStep);
  1557. if (ccd_body2 != nullptr && mCCDBody.mBodyID1 > ccd_body2->mBodyID1)
  1558. return;
  1559. // Test group filter
  1560. if (!mBody1.GetCollisionGroup().CanCollide(body2.GetCollisionGroup()))
  1561. return;
  1562. // TODO: For now we ignore sensors
  1563. if (body2.IsSensor())
  1564. return;
  1565. // Get relative movement of these two bodies
  1566. Vec3 direction = mShapeCast.mDirection - sCalculateBodyMotion(body2, mDeltaTime);
  1567. // Test if the remaining movement is less than our movement threshold
  1568. if (direction.LengthSq() < mCCDBody.mLinearCastThresholdSq)
  1569. return;
  1570. // Get the bounds of 2, widen it by the extent of 1 and test a ray to see if it hits earlier than the current early out fraction
  1571. AABox bounds = body2.GetWorldSpaceBounds();
  1572. bounds.mMin -= mBody1Extent;
  1573. bounds.mMax += mBody1Extent;
  1574. float hit_fraction = RayAABox(Vec3(mShapeCast.mCenterOfMassStart.GetTranslation()), RayInvDirection(direction), bounds.mMin, bounds.mMax);
  1575. if (hit_fraction > GetPositiveEarlyOutFraction()) // If early out fraction <= 0, we have the possibility of finding a deeper hit so we need to clamp the early out fraction
  1576. return;
  1577. // Reset collector (this is a new body pair)
  1578. mCollector.ResetEarlyOutFraction(GetEarlyOutFraction());
  1579. mCollector.mValidateBodyPair = true;
  1580. mCollector.mRejectAll = false;
  1581. // Set body ID on shape filter
  1582. mShapeFilter.SetBody2(&body2);
  1583. // Provide direction as hint for the active edges algorithm
  1584. mShapeCastSettings.mActiveEdgeMovementDirection = direction;
  1585. // Do narrow phase collision check
  1586. RShapeCast relative_cast(mShapeCast.mShape, mShapeCast.mScale, mShapeCast.mCenterOfMassStart, direction, mShapeCast.mShapeWorldBounds);
  1587. body2.GetTransformedShape().CastShape(relative_cast, mShapeCastSettings, mShapeCast.mCenterOfMassStart.GetTranslation(), mCollector, mShapeFilter);
  1588. // Update early out fraction based on narrow phase collector
  1589. if (!mCollector.mRejectAll)
  1590. UpdateEarlyOutFraction(mCollector.GetEarlyOutFraction());
  1591. }
  1592. const CCDBody & mCCDBody;
  1593. const Body & mBody1;
  1594. Vec3 mBody1Extent;
  1595. RShapeCast mShapeCast;
  1596. ShapeCastSettings & mShapeCastSettings;
  1597. SimShapeFilterWrapper & mShapeFilter;
  1598. CCDNarrowPhaseCollector & mCollector;
  1599. const BodyManager & mBodyManager;
  1600. PhysicsUpdateContext::Step *mStep;
  1601. float mDeltaTime;
  1602. };
  1603. // Create shape filter
  1604. SimShapeFilterWrapperUnion shape_filter_union(mSimShapeFilter, &body);
  1605. SimShapeFilterWrapper &shape_filter = shape_filter_union.GetSimShapeFilterWrapper();
  1606. // Check if we collide with any other body. Note that we use the non-locking interface as we know the broadphase cannot be modified at this point.
  1607. RShapeCast shape_cast(body.GetShape(), Vec3::sOne(), body.GetCenterOfMassTransform(), ccd_body.mDeltaPosition);
  1608. CCDBroadPhaseCollector bp_collector(ccd_body, body, shape_cast, settings, shape_filter, np_collector, mBodyManager, ioStep, ioContext->mStepDeltaTime);
  1609. mBroadPhase->CastAABoxNoLock({ shape_cast.mShapeWorldBounds, shape_cast.mDirection }, bp_collector, broadphase_layer_filter, object_layer_filter);
  1610. // Check if there was a hit
  1611. if (ccd_body.mFractionPlusSlop < 1.0f)
  1612. {
  1613. const Body &body2 = mBodyManager.GetBody(ccd_body.mBodyID2);
  1614. // Determine contact manifold
  1615. ContactManifold manifold;
  1616. manifold.mBaseOffset = shape_cast.mCenterOfMassStart.GetTranslation();
  1617. ManifoldBetweenTwoFaces(cast_shape_result.mContactPointOn1, cast_shape_result.mContactPointOn2, cast_shape_result.mPenetrationAxis, mPhysicsSettings.mManifoldTolerance, cast_shape_result.mShape1Face, cast_shape_result.mShape2Face, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));
  1618. manifold.mSubShapeID1 = cast_shape_result.mSubShapeID1;
  1619. manifold.mSubShapeID2 = cast_shape_result.mSubShapeID2;
  1620. manifold.mPenetrationDepth = cast_shape_result.mPenetrationDepth;
  1621. manifold.mWorldSpaceNormal = ccd_body.mContactNormal;
  1622. // Call contact point callbacks
  1623. mContactManager.OnCCDContactAdded(contact_allocator, body, body2, manifold, ccd_body.mContactSettings);
  1624. if (ccd_body.mContactSettings.mIsSensor)
  1625. {
  1626. // If this is a sensor, we don't want to solve the contact
  1627. ccd_body.mFractionPlusSlop = 1.0f;
  1628. ccd_body.mBodyID2 = BodyID();
  1629. }
  1630. else
  1631. {
  1632. // Calculate the average position from the manifold (this will result in the same impulse applied as when we apply impulses to all contact points)
  1633. if (manifold.mRelativeContactPointsOn2.size() > 1)
  1634. {
  1635. Vec3 average_contact_point = Vec3::sZero();
  1636. for (const Vec3 &v : manifold.mRelativeContactPointsOn2)
  1637. average_contact_point += v;
  1638. average_contact_point /= (float)manifold.mRelativeContactPointsOn2.size();
  1639. ccd_body.mContactPointOn2 = manifold.mBaseOffset + average_contact_point;
  1640. }
  1641. else
  1642. ccd_body.mContactPointOn2 = manifold.mBaseOffset + cast_shape_result.mContactPointOn2;
  1643. }
  1644. }
  1645. }
  1646. // Collect information from the contact allocator and accumulate it in the step.
  1647. sFinalizeContactAllocator(*ioStep, contact_allocator);
  1648. }
  1649. void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  1650. {
  1651. #ifdef JPH_ENABLE_ASSERTS
  1652. // Read/write body access
  1653. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  1654. // We activate bodies that we collide with
  1655. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  1656. #endif
  1657. uint32 num_active_bodies_after_find_collisions = ioStep->mActiveBodyReadIdx;
  1658. TempAllocator *temp_allocator = ioContext->mTempAllocator;
  1659. // Check if there's anything to do
  1660. uint num_ccd_bodies = ioStep->mNumCCDBodies;
  1661. if (num_ccd_bodies > 0)
  1662. {
  1663. // Sort on fraction so that we process earliest collisions first
  1664. // This is needed to make the simulation deterministic and also to be able to stop contact processing
  1665. // between body pairs if an earlier hit was found involving the body by another CCD body
  1666. // (if it's body ID < this CCD body's body ID - see filtering logic in CCDBroadPhaseCollector)
  1667. CCDBody **sorted_ccd_bodies = (CCDBody **)temp_allocator->Allocate(num_ccd_bodies * sizeof(CCDBody *));
  1668. JPH_SCOPE_EXIT([temp_allocator, sorted_ccd_bodies, num_ccd_bodies]{ temp_allocator->Free(sorted_ccd_bodies, num_ccd_bodies * sizeof(CCDBody *)); });
  1669. {
  1670. JPH_PROFILE("Sort");
  1671. // We don't want to copy the entire struct (it's quite big), so we create a pointer array first
  1672. CCDBody *src_ccd_bodies = ioStep->mCCDBodies;
  1673. CCDBody **dst_ccd_bodies = sorted_ccd_bodies;
  1674. CCDBody **dst_ccd_bodies_end = dst_ccd_bodies + num_ccd_bodies;
  1675. while (dst_ccd_bodies < dst_ccd_bodies_end)
  1676. *(dst_ccd_bodies++) = src_ccd_bodies++;
  1677. // Which we then sort
  1678. QuickSort(sorted_ccd_bodies, sorted_ccd_bodies + num_ccd_bodies, [](const CCDBody *inBody1, const CCDBody *inBody2)
  1679. {
  1680. if (inBody1->mFractionPlusSlop != inBody2->mFractionPlusSlop)
  1681. return inBody1->mFractionPlusSlop < inBody2->mFractionPlusSlop;
  1682. return inBody1->mBodyID1 < inBody2->mBodyID1;
  1683. });
  1684. }
  1685. // We can collide with bodies that are not active, we track them here so we can activate them in one go at the end.
  1686. // This is also needed because we can't modify the active body array while we iterate it.
  1687. static constexpr int cBodiesBatch = 64;
  1688. BodyID *bodies_to_activate = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1689. int num_bodies_to_activate = 0;
  1690. // We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.
  1691. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1692. int num_bodies_to_update_bounds = 0;
  1693. for (uint i = 0; i < num_ccd_bodies; ++i)
  1694. {
  1695. const CCDBody *ccd_body = sorted_ccd_bodies[i];
  1696. Body &body1 = mBodyManager.GetBody(ccd_body->mBodyID1);
  1697. MotionProperties *body_mp = body1.GetMotionProperties();
  1698. // If there was a hit
  1699. if (!ccd_body->mBodyID2.IsInvalid())
  1700. {
  1701. Body &body2 = mBodyManager.GetBody(ccd_body->mBodyID2);
  1702. // Determine if the other body has a CCD body
  1703. CCDBody *ccd_body2 = sGetCCDBody(body2, ioStep);
  1704. if (ccd_body2 != nullptr)
  1705. {
  1706. JPH_ASSERT(ccd_body2->mBodyID2 != ccd_body->mBodyID1, "If we collided with another body, that other body should have ignored collisions with us!");
  1707. // Check if the other body found a hit that is further away
  1708. if (ccd_body2->mFraction > ccd_body->mFraction)
  1709. {
  1710. // Reset the colliding body of the other CCD body. The other body will shorten its distance traveled and will not do any collision response (we'll do that).
  1711. // This means that at this point we have triggered a contact point add/persist for our further hit by accident for the other body.
  1712. // We accept this as calling the contact point callbacks here would require persisting the manifolds up to this point and doing the callbacks single threaded.
  1713. ccd_body2->mBodyID2 = BodyID();
  1714. ccd_body2->mFractionPlusSlop = ccd_body->mFraction;
  1715. }
  1716. }
  1717. // If the other body moved less than us before hitting something, we're not colliding with it so we again have triggered contact point add/persist callbacks by accident.
  1718. // We'll just move to the collision position anyway (as that's the last position we know is good), but we won't do any collision response.
  1719. if (ccd_body2 == nullptr || ccd_body2->mFraction >= ccd_body->mFraction)
  1720. {
  1721. const ContactSettings &contact_settings = ccd_body->mContactSettings;
  1722. // Calculate contact point velocity for body 1
  1723. Vec3 r1_plus_u = Vec3(ccd_body->mContactPointOn2 - (body1.GetCenterOfMassPosition() + ccd_body->mFraction * ccd_body->mDeltaPosition));
  1724. Vec3 v1 = body1.GetPointVelocityCOM(r1_plus_u);
  1725. // Calculate inverse mass for body 1
  1726. float inv_m1 = contact_settings.mInvMassScale1 * body_mp->GetInverseMass();
  1727. if (body2.IsRigidBody())
  1728. {
  1729. // Calculate contact point velocity for body 2
  1730. Vec3 r2 = Vec3(ccd_body->mContactPointOn2 - body2.GetCenterOfMassPosition());
  1731. Vec3 v2 = body2.GetPointVelocityCOM(r2);
  1732. // Calculate relative contact velocity
  1733. Vec3 relative_velocity = v2 - v1;
  1734. float normal_velocity = relative_velocity.Dot(ccd_body->mContactNormal);
  1735. // Calculate velocity bias due to restitution
  1736. float normal_velocity_bias;
  1737. if (contact_settings.mCombinedRestitution > 0.0f && normal_velocity < -mPhysicsSettings.mMinVelocityForRestitution)
  1738. normal_velocity_bias = contact_settings.mCombinedRestitution * normal_velocity;
  1739. else
  1740. normal_velocity_bias = 0.0f;
  1741. // Get inverse mass of body 2
  1742. float inv_m2 = body2.GetMotionPropertiesUnchecked() != nullptr? contact_settings.mInvMassScale2 * body2.GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;
  1743. // Solve contact constraint
  1744. AxisConstraintPart contact_constraint;
  1745. contact_constraint.CalculateConstraintPropertiesWithMassOverride(body1, inv_m1, contact_settings.mInvInertiaScale1, r1_plus_u, body2, inv_m2, contact_settings.mInvInertiaScale2, r2, ccd_body->mContactNormal, normal_velocity_bias);
  1746. contact_constraint.SolveVelocityConstraintWithMassOverride(body1, inv_m1, body2, inv_m2, ccd_body->mContactNormal, -FLT_MAX, FLT_MAX);
  1747. // Apply friction
  1748. if (contact_settings.mCombinedFriction > 0.0f)
  1749. {
  1750. // Calculate friction direction by removing normal velocity from the relative velocity
  1751. Vec3 friction_direction = relative_velocity - normal_velocity * ccd_body->mContactNormal;
  1752. float friction_direction_len_sq = friction_direction.LengthSq();
  1753. if (friction_direction_len_sq > 1.0e-12f)
  1754. {
  1755. // Normalize friction direction
  1756. friction_direction /= sqrt(friction_direction_len_sq);
  1757. // Calculate max friction impulse
  1758. float max_lambda_f = contact_settings.mCombinedFriction * contact_constraint.GetTotalLambda();
  1759. AxisConstraintPart friction;
  1760. friction.CalculateConstraintPropertiesWithMassOverride(body1, inv_m1, contact_settings.mInvInertiaScale1, r1_plus_u, body2, inv_m2, contact_settings.mInvInertiaScale2, r2, friction_direction);
  1761. friction.SolveVelocityConstraintWithMassOverride(body1, inv_m1, body2, inv_m2, friction_direction, -max_lambda_f, max_lambda_f);
  1762. }
  1763. }
  1764. // Clamp velocity of body 2
  1765. if (body2.IsDynamic())
  1766. {
  1767. MotionProperties *body2_mp = body2.GetMotionProperties();
  1768. body2_mp->ClampLinearVelocity();
  1769. body2_mp->ClampAngularVelocity();
  1770. }
  1771. }
  1772. else
  1773. {
  1774. SoftBodyMotionProperties *soft_mp = static_cast<SoftBodyMotionProperties *>(body2.GetMotionProperties());
  1775. const SoftBodyShape *soft_shape = static_cast<const SoftBodyShape *>(body2.GetShape());
  1776. // Convert the sub shape ID of the soft body to a face
  1777. uint32 face_idx = soft_shape->GetFaceIndex(ccd_body->mSubShapeID2);
  1778. const SoftBodyMotionProperties::Face &face = soft_mp->GetFace(face_idx);
  1779. // Get vertices of the face
  1780. SoftBodyMotionProperties::Vertex &vtx0 = soft_mp->GetVertex(face.mVertex[0]);
  1781. SoftBodyMotionProperties::Vertex &vtx1 = soft_mp->GetVertex(face.mVertex[1]);
  1782. SoftBodyMotionProperties::Vertex &vtx2 = soft_mp->GetVertex(face.mVertex[2]);
  1783. // Inverse mass of the face
  1784. float vtx0_mass = vtx0.mInvMass > 0.0f? 1.0f / vtx0.mInvMass : 1.0e10f;
  1785. float vtx1_mass = vtx1.mInvMass > 0.0f? 1.0f / vtx1.mInvMass : 1.0e10f;
  1786. float vtx2_mass = vtx2.mInvMass > 0.0f? 1.0f / vtx2.mInvMass : 1.0e10f;
  1787. float inv_m2 = 1.0f / (vtx0_mass + vtx1_mass + vtx2_mass);
  1788. // Calculate barycentric coordinates of the contact point on the soft body's face
  1789. float u, v, w;
  1790. RMat44 inv_body2_transform = body2.GetInverseCenterOfMassTransform();
  1791. Vec3 local_contact = Vec3(inv_body2_transform * ccd_body->mContactPointOn2);
  1792. ClosestPoint::GetBaryCentricCoordinates(vtx0.mPosition - local_contact, vtx1.mPosition - local_contact, vtx2.mPosition - local_contact, u, v, w);
  1793. // Calculate contact point velocity for the face
  1794. Vec3 v2 = inv_body2_transform.Multiply3x3Transposed(u * vtx0.mVelocity + v * vtx1.mVelocity + w * vtx2.mVelocity);
  1795. float normal_velocity = (v2 - v1).Dot(ccd_body->mContactNormal);
  1796. // Calculate velocity bias due to restitution
  1797. float normal_velocity_bias;
  1798. if (contact_settings.mCombinedRestitution > 0.0f && normal_velocity < -mPhysicsSettings.mMinVelocityForRestitution)
  1799. normal_velocity_bias = contact_settings.mCombinedRestitution * normal_velocity;
  1800. else
  1801. normal_velocity_bias = 0.0f;
  1802. // Calculate resulting velocity change (the math here is similar to AxisConstraintPart but without an inertia term for body 2 as we treat it as a point mass)
  1803. Vec3 r1_plus_u_x_n = r1_plus_u.Cross(ccd_body->mContactNormal);
  1804. Vec3 invi1_r1_plus_u_x_n = contact_settings.mInvInertiaScale1 * body1.GetInverseInertia().Multiply3x3(r1_plus_u_x_n);
  1805. float jv = r1_plus_u_x_n.Dot(body_mp->GetAngularVelocity()) - normal_velocity - normal_velocity_bias;
  1806. float inv_effective_mass = inv_m1 + inv_m2 + invi1_r1_plus_u_x_n.Dot(r1_plus_u_x_n);
  1807. float lambda = jv / inv_effective_mass;
  1808. body_mp->SubLinearVelocityStep((lambda * inv_m1) * ccd_body->mContactNormal);
  1809. body_mp->SubAngularVelocityStep(lambda * invi1_r1_plus_u_x_n);
  1810. Vec3 delta_v2 = inv_body2_transform.Multiply3x3(lambda * ccd_body->mContactNormal);
  1811. vtx0.mVelocity += delta_v2 * vtx0.mInvMass;
  1812. vtx1.mVelocity += delta_v2 * vtx1.mInvMass;
  1813. vtx2.mVelocity += delta_v2 * vtx2.mInvMass;
  1814. }
  1815. // Clamp velocity of body 1
  1816. body_mp->ClampLinearVelocity();
  1817. body_mp->ClampAngularVelocity();
  1818. // Activate the 2nd body if it is not already active
  1819. if (body2.IsDynamic() && !body2.IsActive())
  1820. {
  1821. bodies_to_activate[num_bodies_to_activate++] = ccd_body->mBodyID2;
  1822. if (num_bodies_to_activate == cBodiesBatch)
  1823. {
  1824. // Batch is full, activate now
  1825. mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);
  1826. num_bodies_to_activate = 0;
  1827. }
  1828. }
  1829. #ifdef JPH_DEBUG_RENDERER
  1830. if (sDrawMotionQualityLinearCast)
  1831. {
  1832. // Draw the collision location
  1833. RMat44 collision_transform = body1.GetCenterOfMassTransform().PostTranslated(ccd_body->mFraction * ccd_body->mDeltaPosition);
  1834. body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform, Vec3::sOne(), Color::sYellow, false, true);
  1835. // Draw the collision location + slop
  1836. RMat44 collision_transform_plus_slop = body1.GetCenterOfMassTransform().PostTranslated(ccd_body->mFractionPlusSlop * ccd_body->mDeltaPosition);
  1837. body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform_plus_slop, Vec3::sOne(), Color::sOrange, false, true);
  1838. // Draw contact normal
  1839. DebugRenderer::sInstance->DrawArrow(ccd_body->mContactPointOn2, ccd_body->mContactPointOn2 - ccd_body->mContactNormal, Color::sYellow, 0.1f);
  1840. // Draw post contact velocity
  1841. DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetLinearVelocity(), Color::sOrange, 0.1f);
  1842. DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetAngularVelocity(), Color::sPurple, 0.1f);
  1843. }
  1844. #endif // JPH_DEBUG_RENDERER
  1845. }
  1846. }
  1847. // Update body position
  1848. body1.AddPositionStep(ccd_body->mDeltaPosition * ccd_body->mFractionPlusSlop);
  1849. // If the body was activated due to an earlier CCD step it will have an index in the active
  1850. // body list that it higher than the highest one we processed during FindCollisions
  1851. // which means it hasn't been assigned an island and will not be updated by an island
  1852. // this means that we need to update its bounds manually
  1853. if (body_mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)
  1854. {
  1855. body1.CalculateWorldSpaceBoundsInternal();
  1856. bodies_to_update_bounds[num_bodies_to_update_bounds++] = body1.GetID();
  1857. if (num_bodies_to_update_bounds == cBodiesBatch)
  1858. {
  1859. // Buffer full, flush now
  1860. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1861. num_bodies_to_update_bounds = 0;
  1862. }
  1863. }
  1864. }
  1865. // Activate the requested bodies
  1866. if (num_bodies_to_activate > 0)
  1867. mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);
  1868. // Notify change bounds on requested bodies
  1869. if (num_bodies_to_update_bounds > 0)
  1870. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1871. }
  1872. // Ensure we free the CCD bodies array now, will not call the destructor!
  1873. temp_allocator->Free(ioStep->mActiveBodyToCCDBody, ioStep->mNumActiveBodyToCCDBody * sizeof(int));
  1874. ioStep->mActiveBodyToCCDBody = nullptr;
  1875. ioStep->mNumActiveBodyToCCDBody = 0;
  1876. temp_allocator->Free(ioStep->mCCDBodies, ioStep->mCCDBodiesCapacity * sizeof(CCDBody));
  1877. ioStep->mCCDBodies = nullptr;
  1878. ioStep->mCCDBodiesCapacity = 0;
  1879. }
  1880. void PhysicsSystem::JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep)
  1881. {
  1882. #ifdef JPH_ENABLE_ASSERTS
  1883. // We don't touch any bodies
  1884. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1885. #endif
  1886. // Reset the Body::EFlags::InvalidateContactCache flag for all bodies
  1887. mBodyManager.ValidateContactCacheForAllBodies();
  1888. // Finalize the contact cache (this swaps the read and write versions of the contact cache)
  1889. // Trigger all contact removed callbacks by looking at last step contact points that have not been flagged as reused
  1890. mContactManager.FinalizeContactCacheAndCallContactPointRemovedCallbacks(ioStep->mNumBodyPairs, ioStep->mNumManifolds);
  1891. }
  1892. class PhysicsSystem::BodiesToSleep : public NonCopyable
  1893. {
  1894. public:
  1895. static constexpr int cBodiesToSleepSize = 512;
  1896. static constexpr int cMaxBodiesToPutInBuffer = 128;
  1897. inline BodiesToSleep(BodyManager &inBodyManager, BodyID *inBodiesToSleepBuffer) : mBodyManager(inBodyManager), mBodiesToSleepBuffer(inBodiesToSleepBuffer), mBodiesToSleepCur(inBodiesToSleepBuffer) { }
  1898. inline ~BodiesToSleep()
  1899. {
  1900. // Flush the bodies to sleep buffer
  1901. int num_bodies_in_buffer = int(mBodiesToSleepCur - mBodiesToSleepBuffer);
  1902. if (num_bodies_in_buffer > 0)
  1903. mBodyManager.DeactivateBodies(mBodiesToSleepBuffer, num_bodies_in_buffer);
  1904. }
  1905. inline void PutToSleep(const BodyID *inBegin, const BodyID *inEnd)
  1906. {
  1907. int num_bodies_to_sleep = int(inEnd - inBegin);
  1908. if (num_bodies_to_sleep > cMaxBodiesToPutInBuffer)
  1909. {
  1910. // Too many bodies, deactivate immediately
  1911. mBodyManager.DeactivateBodies(inBegin, num_bodies_to_sleep);
  1912. }
  1913. else
  1914. {
  1915. // Check if there's enough space in the bodies to sleep buffer
  1916. int num_bodies_in_buffer = int(mBodiesToSleepCur - mBodiesToSleepBuffer);
  1917. if (num_bodies_in_buffer + num_bodies_to_sleep > cBodiesToSleepSize)
  1918. {
  1919. // Flush the bodies to sleep buffer
  1920. mBodyManager.DeactivateBodies(mBodiesToSleepBuffer, num_bodies_in_buffer);
  1921. mBodiesToSleepCur = mBodiesToSleepBuffer;
  1922. }
  1923. // Copy the bodies in the buffer
  1924. memcpy(mBodiesToSleepCur, inBegin, num_bodies_to_sleep * sizeof(BodyID));
  1925. mBodiesToSleepCur += num_bodies_to_sleep;
  1926. }
  1927. }
  1928. private:
  1929. BodyManager & mBodyManager;
  1930. BodyID * mBodiesToSleepBuffer;
  1931. BodyID * mBodiesToSleepCur;
  1932. };
  1933. void PhysicsSystem::CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::Step *ioStep, BodiesToSleep &ioBodiesToSleep)
  1934. {
  1935. // Get the bodies that belong to this island
  1936. BodyID *bodies_begin, *bodies_end;
  1937. mIslandBuilder.GetBodiesInIsland(inIslandIndex, bodies_begin, bodies_end);
  1938. // Only check sleeping in the last step
  1939. // Also resets force and torque used during the apply gravity phase
  1940. if (ioStep->mIsLast)
  1941. {
  1942. JPH_PROFILE("Check Sleeping");
  1943. static_assert(int(ECanSleep::CannotSleep) == 0 && int(ECanSleep::CanSleep) == 1, "Loop below makes this assumption");
  1944. int all_can_sleep = mPhysicsSettings.mAllowSleeping? int(ECanSleep::CanSleep) : int(ECanSleep::CannotSleep);
  1945. float time_before_sleep = mPhysicsSettings.mTimeBeforeSleep;
  1946. float max_movement = mPhysicsSettings.mPointVelocitySleepThreshold * time_before_sleep;
  1947. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1948. {
  1949. Body &body = mBodyManager.GetBody(*body_id);
  1950. // Update bounding box
  1951. body.CalculateWorldSpaceBoundsInternal();
  1952. // Update sleeping
  1953. all_can_sleep &= int(body.UpdateSleepStateInternal(ioContext->mStepDeltaTime, max_movement, time_before_sleep));
  1954. // Reset force and torque
  1955. MotionProperties *mp = body.GetMotionProperties();
  1956. mp->ResetForce();
  1957. mp->ResetTorque();
  1958. }
  1959. // If all bodies indicate they can sleep we can deactivate them
  1960. if (all_can_sleep == int(ECanSleep::CanSleep))
  1961. ioBodiesToSleep.PutToSleep(bodies_begin, bodies_end);
  1962. }
  1963. else
  1964. {
  1965. JPH_PROFILE("Update Bounds");
  1966. // Update bounding box only for all other steps
  1967. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1968. {
  1969. Body &body = mBodyManager.GetBody(*body_id);
  1970. body.CalculateWorldSpaceBoundsInternal();
  1971. }
  1972. }
  1973. // Notify broadphase of changed objects (find ccd contacts can do linear casts in the next step, so we need to do this every step)
  1974. // Note: Shuffles the BodyID's around!!!
  1975. mBroadPhase->NotifyBodiesAABBChanged(bodies_begin, int(bodies_end - bodies_begin), false);
  1976. }
  1977. void PhysicsSystem::JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  1978. {
  1979. #ifdef JPH_ENABLE_ASSERTS
  1980. // We fix up position errors
  1981. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::ReadWrite);
  1982. // Can only deactivate bodies
  1983. BodyManager::GrantActiveBodiesAccess grant_active(false, true);
  1984. #endif
  1985. float delta_time = ioContext->mStepDeltaTime;
  1986. float baumgarte = mPhysicsSettings.mBaumgarte;
  1987. Constraint **active_constraints = ioContext->mActiveConstraints;
  1988. // Keep a buffer of bodies that need to go to sleep in order to not constantly lock the active bodies mutex and create contention between all solving threads
  1989. BodiesToSleep bodies_to_sleep(mBodyManager, (BodyID *)JPH_STACK_ALLOC(BodiesToSleep::cBodiesToSleepSize * sizeof(BodyID)));
  1990. bool check_islands = true, check_split_islands = mPhysicsSettings.mUseLargeIslandSplitter;
  1991. for (;;)
  1992. {
  1993. // First try to get work from large islands
  1994. if (check_split_islands)
  1995. {
  1996. bool first_iteration;
  1997. uint split_island_index;
  1998. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  1999. switch (mLargeIslandSplitter.FetchNextBatch(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, first_iteration))
  2000. {
  2001. case LargeIslandSplitter::EStatus::BatchRetrieved:
  2002. // Solve the batch
  2003. ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);
  2004. mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);
  2005. // Mark the batch as processed
  2006. bool last_iteration, final_batch;
  2007. mLargeIslandSplitter.MarkBatchProcessed(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, last_iteration, final_batch);
  2008. // The final batch will update all bounds and check sleeping
  2009. if (final_batch)
  2010. CheckSleepAndUpdateBounds(mLargeIslandSplitter.GetIslandIndex(split_island_index), ioContext, ioStep, bodies_to_sleep);
  2011. // We processed work, loop again
  2012. continue;
  2013. case LargeIslandSplitter::EStatus::WaitingForBatch:
  2014. break;
  2015. case LargeIslandSplitter::EStatus::AllBatchesDone:
  2016. check_split_islands = false;
  2017. break;
  2018. }
  2019. }
  2020. // If that didn't succeed try to process an island
  2021. if (check_islands)
  2022. {
  2023. // Next island
  2024. uint32 island_idx = ioStep->mSolvePositionConstraintsNextIsland++;
  2025. if (island_idx >= mIslandBuilder.GetNumIslands())
  2026. {
  2027. // We processed all islands, stop checking islands
  2028. check_islands = false;
  2029. continue;
  2030. }
  2031. JPH_PROFILE("Island");
  2032. // Get iterators for this island
  2033. uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;
  2034. mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);
  2035. mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);
  2036. // If this island is a large island, it will be picked up as a batch and we don't need to do anything here
  2037. uint num_items = uint(constraints_end - constraints_begin) + uint(contacts_end - contacts_begin);
  2038. if (mPhysicsSettings.mUseLargeIslandSplitter
  2039. && num_items >= LargeIslandSplitter::cLargeIslandTreshold)
  2040. continue;
  2041. // Check if this island needs solving
  2042. if (num_items > 0)
  2043. {
  2044. // Iterate
  2045. uint num_position_steps = mIslandBuilder.GetNumPositionSteps(island_idx);
  2046. for (uint position_step = 0; position_step < num_position_steps; ++position_step)
  2047. {
  2048. bool applied_impulse = ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);
  2049. applied_impulse |= mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);
  2050. if (!applied_impulse)
  2051. break;
  2052. }
  2053. }
  2054. // After solving we will update all bounds and check sleeping
  2055. CheckSleepAndUpdateBounds(island_idx, ioContext, ioStep, bodies_to_sleep);
  2056. // We processed work, loop again
  2057. continue;
  2058. }
  2059. if (check_islands)
  2060. {
  2061. // If there are islands, we don't need to wait and can pick up new work
  2062. continue;
  2063. }
  2064. else if (check_split_islands)
  2065. {
  2066. // If there are split islands, but we didn't do any work, give up a time slice
  2067. std::this_thread::yield();
  2068. }
  2069. else
  2070. {
  2071. // No more work
  2072. break;
  2073. }
  2074. }
  2075. }
  2076. void PhysicsSystem::JobSoftBodyPrepare(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  2077. {
  2078. JPH_PROFILE_FUNCTION();
  2079. {
  2080. #ifdef JPH_ENABLE_ASSERTS
  2081. // Reading soft body positions
  2082. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  2083. #endif
  2084. // Get the active soft bodies
  2085. BodyIDVector active_bodies;
  2086. mBodyManager.GetActiveBodies(EBodyType::SoftBody, active_bodies);
  2087. // Quit if there are no active soft bodies
  2088. if (active_bodies.empty())
  2089. {
  2090. // Kick the next step
  2091. if (ioStep->mStartNextStep.IsValid())
  2092. ioStep->mStartNextStep.RemoveDependency();
  2093. return;
  2094. }
  2095. // Sort to get a deterministic update order
  2096. QuickSort(active_bodies.begin(), active_bodies.end());
  2097. // Allocate soft body contexts
  2098. ioContext->mNumSoftBodies = (uint)active_bodies.size();
  2099. ioContext->mSoftBodyUpdateContexts = (SoftBodyUpdateContext *)ioContext->mTempAllocator->Allocate(ioContext->mNumSoftBodies * sizeof(SoftBodyUpdateContext));
  2100. // Initialize soft body contexts
  2101. for (SoftBodyUpdateContext *sb_ctx = ioContext->mSoftBodyUpdateContexts, *sb_ctx_end = ioContext->mSoftBodyUpdateContexts + ioContext->mNumSoftBodies; sb_ctx < sb_ctx_end; ++sb_ctx)
  2102. {
  2103. new (sb_ctx) SoftBodyUpdateContext;
  2104. Body &body = mBodyManager.GetBody(active_bodies[sb_ctx - ioContext->mSoftBodyUpdateContexts]);
  2105. SoftBodyMotionProperties *mp = static_cast<SoftBodyMotionProperties *>(body.GetMotionProperties());
  2106. mp->InitializeUpdateContext(ioContext->mStepDeltaTime, body, *this, *sb_ctx);
  2107. }
  2108. }
  2109. // We're ready to collide the first soft body
  2110. ioContext->mSoftBodyToCollide.store(0, memory_order_release);
  2111. // Determine number of jobs to spawn
  2112. int num_soft_body_jobs = ioContext->GetMaxConcurrency();
  2113. // Create finalize job
  2114. ioStep->mSoftBodyFinalize = ioContext->mJobSystem->CreateJob("SoftBodyFinalize", cColorSoftBodyFinalize, [ioContext, ioStep]()
  2115. {
  2116. ioContext->mPhysicsSystem->JobSoftBodyFinalize(ioContext);
  2117. // Kick the next step
  2118. if (ioStep->mStartNextStep.IsValid())
  2119. ioStep->mStartNextStep.RemoveDependency();
  2120. }, num_soft_body_jobs); // depends on: soft body simulate
  2121. ioContext->mBarrier->AddJob(ioStep->mSoftBodyFinalize);
  2122. // Create simulate jobs
  2123. ioStep->mSoftBodySimulate.resize(num_soft_body_jobs);
  2124. for (int i = 0; i < num_soft_body_jobs; ++i)
  2125. ioStep->mSoftBodySimulate[i] = ioContext->mJobSystem->CreateJob("SoftBodySimulate", cColorSoftBodySimulate, [ioStep, i]()
  2126. {
  2127. ioStep->mContext->mPhysicsSystem->JobSoftBodySimulate(ioStep->mContext, i);
  2128. ioStep->mSoftBodyFinalize.RemoveDependency();
  2129. }, num_soft_body_jobs); // depends on: soft body collide
  2130. ioContext->mBarrier->AddJobs(ioStep->mSoftBodySimulate.data(), ioStep->mSoftBodySimulate.size());
  2131. // Create collision jobs
  2132. ioStep->mSoftBodyCollide.resize(num_soft_body_jobs);
  2133. for (int i = 0; i < num_soft_body_jobs; ++i)
  2134. ioStep->mSoftBodyCollide[i] = ioContext->mJobSystem->CreateJob("SoftBodyCollide", cColorSoftBodyCollide, [ioContext, ioStep]()
  2135. {
  2136. ioContext->mPhysicsSystem->JobSoftBodyCollide(ioContext);
  2137. for (const JobHandle &h : ioStep->mSoftBodySimulate)
  2138. h.RemoveDependency();
  2139. }); // depends on: nothing
  2140. ioContext->mBarrier->AddJobs(ioStep->mSoftBodyCollide.data(), ioStep->mSoftBodyCollide.size());
  2141. }
  2142. void PhysicsSystem::JobSoftBodyCollide(PhysicsUpdateContext *ioContext) const
  2143. {
  2144. #ifdef JPH_ENABLE_ASSERTS
  2145. // Reading rigid body positions and velocities
  2146. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  2147. #endif
  2148. for (;;)
  2149. {
  2150. // Fetch the next soft body
  2151. uint sb_idx = ioContext->mSoftBodyToCollide.fetch_add(1, std::memory_order_acquire);
  2152. if (sb_idx >= ioContext->mNumSoftBodies)
  2153. break;
  2154. // Do a broadphase check
  2155. SoftBodyUpdateContext &sb_ctx = ioContext->mSoftBodyUpdateContexts[sb_idx];
  2156. sb_ctx.mMotionProperties->DetermineCollidingShapes(sb_ctx, *this, GetBodyLockInterfaceNoLock());
  2157. }
  2158. }
  2159. void PhysicsSystem::JobSoftBodySimulate(PhysicsUpdateContext *ioContext, uint inThreadIndex) const
  2160. {
  2161. #ifdef JPH_ENABLE_ASSERTS
  2162. // Updating velocities of soft bodies, allow the contact listener to read the soft body state
  2163. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  2164. #endif
  2165. // Calculate at which body we start to distribute the workload across the threads
  2166. uint num_soft_bodies = ioContext->mNumSoftBodies;
  2167. uint start_idx = inThreadIndex * num_soft_bodies / ioContext->GetMaxConcurrency();
  2168. // Keep running partial updates until everything has been updated
  2169. uint status;
  2170. do
  2171. {
  2172. // Reset status
  2173. status = 0;
  2174. // Update all soft bodies
  2175. for (uint i = 0; i < num_soft_bodies; ++i)
  2176. {
  2177. // Fetch the soft body context
  2178. SoftBodyUpdateContext &sb_ctx = ioContext->mSoftBodyUpdateContexts[(start_idx + i) % num_soft_bodies];
  2179. // To avoid trashing the cache too much, we prefer to stick to one soft body until we cannot progress it any further
  2180. uint sb_status;
  2181. do
  2182. {
  2183. sb_status = (uint)sb_ctx.mMotionProperties->ParallelUpdate(sb_ctx, mPhysicsSettings);
  2184. status |= sb_status;
  2185. } while (sb_status == (uint)SoftBodyMotionProperties::EStatus::DidWork);
  2186. }
  2187. // If we didn't perform any work, yield the thread so that something else can run
  2188. if (!(status & (uint)SoftBodyMotionProperties::EStatus::DidWork))
  2189. std::this_thread::yield();
  2190. }
  2191. while (status != (uint)SoftBodyMotionProperties::EStatus::Done);
  2192. }
  2193. void PhysicsSystem::JobSoftBodyFinalize(PhysicsUpdateContext *ioContext)
  2194. {
  2195. #ifdef JPH_ENABLE_ASSERTS
  2196. // Updating rigid body velocities and soft body positions / velocities
  2197. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  2198. // Can activate and deactivate bodies
  2199. BodyManager::GrantActiveBodiesAccess grant_active(true, true);
  2200. #endif
  2201. static constexpr int cBodiesBatch = 64;
  2202. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  2203. int num_bodies_to_update_bounds = 0;
  2204. BodyID *bodies_to_put_to_sleep = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  2205. int num_bodies_to_put_to_sleep = 0;
  2206. for (SoftBodyUpdateContext *sb_ctx = ioContext->mSoftBodyUpdateContexts, *sb_ctx_end = ioContext->mSoftBodyUpdateContexts + ioContext->mNumSoftBodies; sb_ctx < sb_ctx_end; ++sb_ctx)
  2207. {
  2208. // Apply the rigid body velocity deltas
  2209. sb_ctx->mMotionProperties->UpdateRigidBodyVelocities(*sb_ctx, GetBodyInterfaceNoLock());
  2210. // Update the position
  2211. sb_ctx->mBody->SetPositionAndRotationInternal(sb_ctx->mBody->GetPosition() + sb_ctx->mDeltaPosition, sb_ctx->mBody->GetRotation(), false);
  2212. BodyID id = sb_ctx->mBody->GetID();
  2213. bodies_to_update_bounds[num_bodies_to_update_bounds++] = id;
  2214. if (num_bodies_to_update_bounds == cBodiesBatch)
  2215. {
  2216. // Buffer full, flush now
  2217. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  2218. num_bodies_to_update_bounds = 0;
  2219. }
  2220. if (sb_ctx->mCanSleep == ECanSleep::CanSleep)
  2221. {
  2222. // This body should go to sleep
  2223. bodies_to_put_to_sleep[num_bodies_to_put_to_sleep++] = id;
  2224. if (num_bodies_to_put_to_sleep == cBodiesBatch)
  2225. {
  2226. mBodyManager.DeactivateBodies(bodies_to_put_to_sleep, num_bodies_to_put_to_sleep);
  2227. num_bodies_to_put_to_sleep = 0;
  2228. }
  2229. }
  2230. }
  2231. // Notify change bounds on requested bodies
  2232. if (num_bodies_to_update_bounds > 0)
  2233. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  2234. // Notify bodies to go to sleep
  2235. if (num_bodies_to_put_to_sleep > 0)
  2236. mBodyManager.DeactivateBodies(bodies_to_put_to_sleep, num_bodies_to_put_to_sleep);
  2237. // Free soft body contexts
  2238. ioContext->mTempAllocator->Free(ioContext->mSoftBodyUpdateContexts, ioContext->mNumSoftBodies * sizeof(SoftBodyUpdateContext));
  2239. }
  2240. void PhysicsSystem::SaveState(StateRecorder &inStream, EStateRecorderState inState, const StateRecorderFilter *inFilter) const
  2241. {
  2242. JPH_PROFILE_FUNCTION();
  2243. inStream.Write(inState);
  2244. if (uint8(inState) & uint8(EStateRecorderState::Global))
  2245. {
  2246. inStream.Write(mPreviousStepDeltaTime);
  2247. inStream.Write(mGravity);
  2248. }
  2249. if (uint8(inState) & uint8(EStateRecorderState::Bodies))
  2250. mBodyManager.SaveState(inStream, inFilter);
  2251. if (uint8(inState) & uint8(EStateRecorderState::Contacts))
  2252. mContactManager.SaveState(inStream, inFilter);
  2253. if (uint8(inState) & uint8(EStateRecorderState::Constraints))
  2254. mConstraintManager.SaveState(inStream, inFilter);
  2255. }
  2256. bool PhysicsSystem::RestoreState(StateRecorder &inStream, const StateRecorderFilter *inFilter)
  2257. {
  2258. JPH_PROFILE_FUNCTION();
  2259. EStateRecorderState state = EStateRecorderState::All; // Set this value for validation. If a partial state is saved, validation will not work anyway.
  2260. inStream.Read(state);
  2261. if (uint8(state) & uint8(EStateRecorderState::Global))
  2262. {
  2263. inStream.Read(mPreviousStepDeltaTime);
  2264. inStream.Read(mGravity);
  2265. }
  2266. if (uint8(state) & uint8(EStateRecorderState::Bodies))
  2267. {
  2268. if (!mBodyManager.RestoreState(inStream))
  2269. return false;
  2270. // Update bounding boxes for all bodies in the broadphase
  2271. if (inStream.IsLastPart())
  2272. {
  2273. Array<BodyID> bodies;
  2274. for (const Body *b : mBodyManager.GetBodies())
  2275. if (BodyManager::sIsValidBodyPointer(b) && b->IsInBroadPhase())
  2276. bodies.push_back(b->GetID());
  2277. if (!bodies.empty())
  2278. mBroadPhase->NotifyBodiesAABBChanged(&bodies[0], (int)bodies.size());
  2279. }
  2280. }
  2281. if (uint8(state) & uint8(EStateRecorderState::Contacts))
  2282. {
  2283. if (!mContactManager.RestoreState(inStream, inFilter))
  2284. return false;
  2285. }
  2286. if (uint8(state) & uint8(EStateRecorderState::Constraints))
  2287. {
  2288. if (!mConstraintManager.RestoreState(inStream))
  2289. return false;
  2290. }
  2291. return true;
  2292. }
  2293. void PhysicsSystem::SaveBodyState(const Body &inBody, StateRecorder &inStream) const
  2294. {
  2295. mBodyManager.SaveBodyState(inBody, inStream);
  2296. }
  2297. void PhysicsSystem::RestoreBodyState(Body &ioBody, StateRecorder &inStream)
  2298. {
  2299. mBodyManager.RestoreBodyState(ioBody, inStream);
  2300. BodyID id = ioBody.GetID();
  2301. mBroadPhase->NotifyBodiesAABBChanged(&id, 1);
  2302. }
  2303. JPH_NAMESPACE_END