PhysicsSystem.cpp 118 KB

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