PhysicsSystem.cpp 115 KB

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