PhysicsSystem.cpp 93 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <Jolt/Jolt.h>
  4. #include <Jolt/Physics/PhysicsSystem.h>
  5. #include <Jolt/Physics/PhysicsSettings.h>
  6. #include <Jolt/Physics/PhysicsUpdateContext.h>
  7. #include <Jolt/Physics/PhysicsStepListener.h>
  8. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseBruteForce.h>
  9. #include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h>
  10. #include <Jolt/Physics/Collision/CollisionDispatch.h>
  11. #include <Jolt/Physics/Collision/AABoxCast.h>
  12. #include <Jolt/Physics/Collision/ShapeCast.h>
  13. #include <Jolt/Physics/Collision/CollideShape.h>
  14. #include <Jolt/Physics/Collision/CollisionCollectorImpl.h>
  15. #include <Jolt/Physics/Collision/CastResult.h>
  16. #include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>
  17. #include <Jolt/Physics/Collision/ManifoldBetweenTwoFaces.h>
  18. #include <Jolt/Physics/Collision/Shape/ConvexShape.h>
  19. #include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>
  20. #include <Jolt/Geometry/RayAABox.h>
  21. #include <Jolt/Core/JobSystem.h>
  22. #include <Jolt/Core/TempAllocator.h>
  23. #include <Jolt/Core/QuickSort.h>
  24. #ifdef JPH_DEBUG_RENDERER
  25. #include <Jolt/Renderer/DebugRenderer.h>
  26. #endif // JPH_DEBUG_RENDERER
  27. JPH_NAMESPACE_BEGIN
  28. #ifdef JPH_DEBUG_RENDERER
  29. bool PhysicsSystem::sDrawMotionQualityLinearCast = false;
  30. #endif // JPH_DEBUG_RENDERER
  31. //#define BROAD_PHASE BroadPhaseBruteForce
  32. #define BROAD_PHASE BroadPhaseQuadTree
  33. static const Color cColorUpdateBroadPhaseFinalize = Color::sGetDistinctColor(1);
  34. static const Color cColorUpdateBroadPhasePrepare = Color::sGetDistinctColor(2);
  35. static const Color cColorFindCollisions = Color::sGetDistinctColor(3);
  36. static const Color cColorApplyGravity = Color::sGetDistinctColor(4);
  37. static const Color cColorSetupVelocityConstraints = Color::sGetDistinctColor(5);
  38. static const Color cColorBuildIslandsFromConstraints = Color::sGetDistinctColor(6);
  39. static const Color cColorDetermineActiveConstraints = Color::sGetDistinctColor(7);
  40. static const Color cColorFinalizeIslands = Color::sGetDistinctColor(8);
  41. static const Color cColorContactRemovedCallbacks = Color::sGetDistinctColor(9);
  42. static const Color cColorBodySetIslandIndex = Color::sGetDistinctColor(10);
  43. static const Color cColorStartNextStep = Color::sGetDistinctColor(11);
  44. static const Color cColorSolveVelocityConstraints = Color::sGetDistinctColor(12);
  45. static const Color cColorPreIntegrateVelocity = Color::sGetDistinctColor(13);
  46. static const Color cColorIntegrateVelocity = Color::sGetDistinctColor(14);
  47. static const Color cColorPostIntegrateVelocity = Color::sGetDistinctColor(15);
  48. static const Color cColorResolveCCDContacts = Color::sGetDistinctColor(16);
  49. static const Color cColorSolvePositionConstraints = Color::sGetDistinctColor(17);
  50. static const Color cColorStartNextSubStep = Color::sGetDistinctColor(18);
  51. static const Color cColorFindCCDContacts = Color::sGetDistinctColor(19);
  52. static const Color cColorStepListeners = Color::sGetDistinctColor(20);
  53. PhysicsSystem::~PhysicsSystem()
  54. {
  55. // Remove broadphase
  56. delete mBroadPhase;
  57. }
  58. void PhysicsSystem::Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, ObjectVsBroadPhaseLayerFilter inObjectVsBroadPhaseLayerFilter, ObjectLayerPairFilter inObjectLayerPairFilter)
  59. {
  60. mObjectVsBroadPhaseLayerFilter = inObjectVsBroadPhaseLayerFilter;
  61. mObjectLayerPairFilter = inObjectLayerPairFilter;
  62. // Initialize body manager
  63. mBodyManager.Init(inMaxBodies, inNumBodyMutexes, inBroadPhaseLayerInterface);
  64. // Create broadphase
  65. mBroadPhase = new BROAD_PHASE();
  66. mBroadPhase->Init(&mBodyManager, inBroadPhaseLayerInterface);
  67. // Init contact constraint manager
  68. mContactManager.Init(inMaxBodyPairs, inMaxContactConstraints);
  69. // Init islands builder
  70. mIslandBuilder.Init(inMaxBodies);
  71. // Initialize body interface
  72. mBodyInterfaceLocking.Init(mBodyLockInterfaceLocking, mBodyManager, *mBroadPhase);
  73. mBodyInterfaceNoLock.Init(mBodyLockInterfaceNoLock, mBodyManager, *mBroadPhase);
  74. // Initialize narrow phase query
  75. mNarrowPhaseQueryLocking.Init(mBodyLockInterfaceLocking, *mBroadPhase);
  76. mNarrowPhaseQueryNoLock.Init(mBodyLockInterfaceNoLock, *mBroadPhase);
  77. }
  78. void PhysicsSystem::OptimizeBroadPhase()
  79. {
  80. mBroadPhase->Optimize();
  81. }
  82. void PhysicsSystem::AddStepListener(PhysicsStepListener *inListener)
  83. {
  84. lock_guard lock(mStepListenersMutex);
  85. JPH_ASSERT(find(mStepListeners.begin(), mStepListeners.end(), inListener) == mStepListeners.end());
  86. mStepListeners.push_back(inListener);
  87. }
  88. void PhysicsSystem::RemoveStepListener(PhysicsStepListener *inListener)
  89. {
  90. lock_guard lock(mStepListenersMutex);
  91. StepListeners::iterator i = find(mStepListeners.begin(), mStepListeners.end(), inListener);
  92. JPH_ASSERT(i != mStepListeners.end());
  93. mStepListeners.erase(i);
  94. }
  95. void PhysicsSystem::Update(float inDeltaTime, int inCollisionSteps, int inIntegrationSubSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem)
  96. {
  97. JPH_PROFILE_FUNCTION();
  98. JPH_ASSERT(inDeltaTime >= 0.0f);
  99. JPH_ASSERT(inIntegrationSubSteps <= PhysicsUpdateContext::cMaxSubSteps);
  100. // Sync point for the broadphase. This will allow it to do clean up operations without having any mutexes locked yet.
  101. mBroadPhase->FrameSync();
  102. // If there are no active bodies or there's no time delta
  103. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies();
  104. if (num_active_bodies == 0 || inDeltaTime <= 0.0f)
  105. {
  106. mBodyManager.LockAllBodies();
  107. // Update broadphase
  108. mBroadPhase->LockModifications();
  109. BroadPhase::UpdateState update_state = mBroadPhase->UpdatePrepare();
  110. mBroadPhase->UpdateFinalize(update_state);
  111. mBroadPhase->UnlockModifications();
  112. // Call contact removal callbacks from contacts that existed in the previous update
  113. mContactManager.ContactPointRemovedCallbacks();
  114. mContactManager.FinalizeContactCache(0, 0);
  115. mBodyManager.UnlockAllBodies();
  116. return;
  117. }
  118. // Calculate ratio between current and previous frame delta time to scale initial constraint forces
  119. float sub_step_delta_time = inDeltaTime / (inCollisionSteps * inIntegrationSubSteps);
  120. float warm_start_impulse_ratio = mPhysicsSettings.mConstraintWarmStart && mPreviousSubStepDeltaTime > 0.0f? sub_step_delta_time / mPreviousSubStepDeltaTime : 0.0f;
  121. mPreviousSubStepDeltaTime = sub_step_delta_time;
  122. // Create the context used for passing information between jobs
  123. PhysicsUpdateContext context(*inTempAllocator);
  124. context.mPhysicsSystem = this;
  125. context.mJobSystem = inJobSystem;
  126. context.mBarrier = inJobSystem->CreateBarrier();
  127. context.mIslandBuilder = &mIslandBuilder;
  128. context.mStepDeltaTime = inDeltaTime / inCollisionSteps;
  129. context.mSubStepDeltaTime = sub_step_delta_time;
  130. context.mWarmStartImpulseRatio = warm_start_impulse_ratio;
  131. context.mSteps.resize(inCollisionSteps);
  132. // Allocate space for body pairs
  133. JPH_ASSERT(context.mBodyPairs == nullptr);
  134. context.mBodyPairs = static_cast<BodyPair *>(inTempAllocator->Allocate(sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs));
  135. // Lock all bodies for write so that we can freely touch them
  136. mStepListenersMutex.lock();
  137. mBodyManager.LockAllBodies();
  138. mBroadPhase->LockModifications();
  139. // Get max number of concurrent jobs
  140. int max_concurrency = context.GetMaxConcurrency();
  141. // Calculate how many step listener jobs we spawn
  142. int num_step_listener_jobs = mStepListeners.empty()? 0 : max(1, min((int)mStepListeners.size() / mPhysicsSettings.mStepListenersBatchSize / mPhysicsSettings.mStepListenerBatchesPerJob, max_concurrency));
  143. // Number of gravity jobs depends on the amount of active bodies.
  144. // Launch max 1 job per batch of active bodies
  145. // Leave 1 thread for update broadphase prepare and 1 for determine active constraints
  146. int num_apply_gravity_jobs = max(1, min(((int)num_active_bodies + cApplyGravityBatchSize - 1) / cApplyGravityBatchSize, max_concurrency - 2));
  147. // Number of determine active constraints jobs to run depends on number of constraints.
  148. // Leave 1 thread for update broadphase prepare and 1 for apply gravity
  149. int num_determine_active_constraints_jobs = max(1, min(((int)mConstraintManager.GetNumConstraints() + cDetermineActiveConstraintsBatchSize - 1) / cDetermineActiveConstraintsBatchSize, max_concurrency - 2));
  150. // Number of find collisions jobs to run depends on number of active bodies.
  151. // 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
  152. // (which may activate additional bodies that need to be processed) while the second job can start processing collision work.
  153. int num_find_collisions_jobs = max(max_concurrency == 1? 1 : 2, min(((int)num_active_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_concurrency));
  154. // Number of integrate velocity jobs depends on number of active bodies.
  155. int num_integrate_velocity_jobs = max(1, min(((int)num_active_bodies + cIntegrateVelocityBatchSize - 1) / cIntegrateVelocityBatchSize, max_concurrency));
  156. {
  157. JPH_PROFILE("Build Jobs");
  158. // Iterate over collision steps
  159. for (int step_idx = 0; step_idx < inCollisionSteps; ++step_idx)
  160. {
  161. bool is_first_step = step_idx == 0;
  162. bool is_last_step = step_idx == inCollisionSteps - 1;
  163. PhysicsUpdateContext::Step &step = context.mSteps[step_idx];
  164. step.mContext = &context;
  165. step.mSubSteps.resize(inIntegrationSubSteps);
  166. // Create job to do broadphase finalization
  167. // This job must finish before integrating velocities. Until then the positions will not be updated neither will bodies be added / removed.
  168. step.mUpdateBroadphaseFinalize = inJobSystem->CreateJob("UpdateBroadPhaseFinalize", cColorUpdateBroadPhaseFinalize, [&context, &step]()
  169. {
  170. // Validate that all find collision jobs have stopped
  171. JPH_ASSERT(step.mActiveFindCollisionJobs == 0);
  172. // Finalize the broadphase update
  173. context.mPhysicsSystem->mBroadPhase->UpdateFinalize(step.mBroadPhaseUpdateState);
  174. // Signal that it is done
  175. step.mSubSteps[0].mPreIntegrateVelocity.RemoveDependency();
  176. }, num_find_collisions_jobs + 2); // depends on: find collisions, broadphase prepare update, finish building jobs
  177. // The immediate jobs below are only immediate for the first step, the all finished job will kick them for the next step
  178. int previous_step_dependency_count = is_first_step? 0 : 1;
  179. // Start job immediately: Start the prepare broadphase
  180. // Must be done under body lock protection since the order is body locks then broadphase mutex
  181. // If this is turned around the RemoveBody call will hang since it locks in that order
  182. step.mBroadPhasePrepare = inJobSystem->CreateJob("UpdateBroadPhasePrepare", cColorUpdateBroadPhasePrepare, [&context, &step]()
  183. {
  184. // Prepare the broadphase update
  185. step.mBroadPhaseUpdateState = context.mPhysicsSystem->mBroadPhase->UpdatePrepare();
  186. // Now the finalize can run (if other dependencies are met too)
  187. step.mUpdateBroadphaseFinalize.RemoveDependency();
  188. }, previous_step_dependency_count);
  189. // This job will find all collisions
  190. step.mBodyPairQueues.resize(max_concurrency);
  191. step.mMaxBodyPairsPerQueue = mPhysicsSettings.mMaxInFlightBodyPairs / max_concurrency;
  192. step.mActiveFindCollisionJobs = ~PhysicsUpdateContext::JobMask(0) >> (sizeof(PhysicsUpdateContext::JobMask) * 8 - num_find_collisions_jobs);
  193. step.mFindCollisions.resize(num_find_collisions_jobs);
  194. for (int i = 0; i < num_find_collisions_jobs; ++i)
  195. {
  196. // 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
  197. int num_dep_build_islands_from_constraints = i == 0? 1 : 0;
  198. step.mFindCollisions[i] = inJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [&step, i]()
  199. {
  200. step.mContext->mPhysicsSystem->JobFindCollisions(&step, i);
  201. }, 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
  202. }
  203. if (is_first_step)
  204. {
  205. #ifdef JPH_ENABLE_ASSERTS
  206. // Don't allow write operations to the active bodies list
  207. mBodyManager.SetActiveBodiesLocked(true);
  208. #endif
  209. // Store the number of active bodies at the start of the step
  210. step.mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies();
  211. // Lock all constraints
  212. mConstraintManager.LockAllConstraints();
  213. // Allocate memory for storing the active constraints
  214. JPH_ASSERT(context.mActiveConstraints == nullptr);
  215. context.mActiveConstraints = static_cast<Constraint **>(inTempAllocator->Allocate(mConstraintManager.GetNumConstraints() * sizeof(Constraint *)));
  216. // Prepare contact buffer
  217. mContactManager.PrepareConstraintBuffer(&context);
  218. // Setup island builder
  219. mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), context.mTempAllocator);
  220. }
  221. // This job applies gravity to all active bodies
  222. step.mApplyGravity.resize(num_apply_gravity_jobs);
  223. for (int i = 0; i < num_apply_gravity_jobs; ++i)
  224. step.mApplyGravity[i] = inJobSystem->CreateJob("ApplyGravity", cColorApplyGravity, [&context, &step]()
  225. {
  226. context.mPhysicsSystem->JobApplyGravity(&context, &step);
  227. JobHandle::sRemoveDependencies(step.mFindCollisions);
  228. }, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)
  229. // This job will setup velocity constraints for non-collision constraints
  230. step.mSetupVelocityConstraints = inJobSystem->CreateJob("SetupVelocityConstraints", cColorSetupVelocityConstraints, [&context, &step]()
  231. {
  232. context.mPhysicsSystem->JobSetupVelocityConstraints(context.mSubStepDeltaTime, &step);
  233. JobHandle::sRemoveDependencies(step.mSubSteps[0].mSolveVelocityConstraints);
  234. }, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs
  235. // This job will build islands from constraints
  236. step.mBuildIslandsFromConstraints = inJobSystem->CreateJob("BuildIslandsFromConstraints", cColorBuildIslandsFromConstraints, [&context, &step]()
  237. {
  238. context.mPhysicsSystem->JobBuildIslandsFromConstraints(&context, &step);
  239. step.mFindCollisions[0].RemoveDependency(); // The first collisions job cannot start running until we've finished building islands and activated all bodies
  240. step.mFinalizeIslands.RemoveDependency();
  241. }, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs
  242. // This job determines active constraints
  243. step.mDetermineActiveConstraints.resize(num_determine_active_constraints_jobs);
  244. for (int i = 0; i < num_determine_active_constraints_jobs; ++i)
  245. step.mDetermineActiveConstraints[i] = inJobSystem->CreateJob("DetermineActiveConstraints", cColorDetermineActiveConstraints, [&context, &step]()
  246. {
  247. context.mPhysicsSystem->JobDetermineActiveConstraints(&step);
  248. step.mSetupVelocityConstraints.RemoveDependency();
  249. step.mBuildIslandsFromConstraints.RemoveDependency();
  250. // Kick find collisions last as they will use up all CPU cores leaving no space for the previous 2 jobs
  251. JobHandle::sRemoveDependencies(step.mFindCollisions);
  252. }, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)
  253. // This job calls the step listeners
  254. step.mStepListeners.resize(num_step_listener_jobs);
  255. for (int i = 0; i < num_step_listener_jobs; ++i)
  256. step.mStepListeners[i] = inJobSystem->CreateJob("StepListeners", cColorStepListeners, [&context, &step]()
  257. {
  258. // Call the step listeners
  259. context.mPhysicsSystem->JobStepListeners(&step);
  260. // Kick apply gravity and determine active constraint jobs
  261. JobHandle::sRemoveDependencies(step.mApplyGravity);
  262. JobHandle::sRemoveDependencies(step.mDetermineActiveConstraints);
  263. }, previous_step_dependency_count);
  264. // Unblock the previous step
  265. if (!is_first_step)
  266. context.mSteps[step_idx - 1].mStartNextStep.RemoveDependency();
  267. // This job will finalize the simulation islands
  268. step.mFinalizeIslands = inJobSystem->CreateJob("FinalizeIslands", cColorFinalizeIslands, [&context, &step]()
  269. {
  270. // Validate that all find collision jobs have stopped
  271. JPH_ASSERT(step.mActiveFindCollisionJobs == 0);
  272. context.mPhysicsSystem->JobFinalizeIslands(&context);
  273. JobHandle::sRemoveDependencies(step.mSubSteps[0].mSolveVelocityConstraints);
  274. step.mBodySetIslandIndex.RemoveDependency();
  275. }, num_find_collisions_jobs + 2); // depends on: find collisions, build islands from constraints, finish building jobs
  276. // Unblock previous job
  277. // 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
  278. step.mBuildIslandsFromConstraints.RemoveDependency();
  279. // This job will call the contact removed callbacks
  280. step.mContactRemovedCallbacks = inJobSystem->CreateJob("ContactRemovedCallbacks", cColorContactRemovedCallbacks, [&context, &step]()
  281. {
  282. context.mPhysicsSystem->JobContactRemovedCallbacks(&step);
  283. if (step.mStartNextStep.IsValid())
  284. step.mStartNextStep.RemoveDependency();
  285. }, 1); // depends on the find ccd contacts of the last sub step
  286. // This job will set the island index on each body (only used for debug drawing purposes)
  287. // It will also delete any bodies that have been destroyed in the last frame
  288. step.mBodySetIslandIndex = inJobSystem->CreateJob("BodySetIslandIndex", cColorBodySetIslandIndex, [&context, &step]()
  289. {
  290. context.mPhysicsSystem->JobBodySetIslandIndex();
  291. if (step.mStartNextStep.IsValid())
  292. step.mStartNextStep.RemoveDependency();
  293. }, 1); // depends on: finalize islands
  294. // Job to start the next collision step
  295. if (!is_last_step)
  296. {
  297. PhysicsUpdateContext::Step *next_step = &context.mSteps[step_idx + 1];
  298. step.mStartNextStep = inJobSystem->CreateJob("StartNextStep", cColorStartNextStep, [this, next_step]()
  299. {
  300. #ifdef _DEBUG
  301. // Validate that the cached bounds are correct
  302. mBodyManager.ValidateActiveBodyBounds();
  303. #endif // _DEBUG
  304. // Store the number of active bodies at the start of the step
  305. next_step->mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies();
  306. // Clear the island builder
  307. TempAllocator *temp_allocator = next_step->mContext->mTempAllocator;
  308. mIslandBuilder.ResetIslands(temp_allocator);
  309. // Setup island builder
  310. mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), temp_allocator);
  311. // Restart the contact manager
  312. mContactManager.RecycleConstraintBuffer();
  313. // Kick the jobs of the next step (in the same order as the first step)
  314. next_step->mBroadPhasePrepare.RemoveDependency();
  315. if (next_step->mStepListeners.empty())
  316. {
  317. // Kick the gravity and active constraints jobs immediately
  318. JobHandle::sRemoveDependencies(next_step->mApplyGravity);
  319. JobHandle::sRemoveDependencies(next_step->mDetermineActiveConstraints);
  320. }
  321. else
  322. {
  323. // Kick the step listeners job first
  324. JobHandle::sRemoveDependencies(next_step->mStepListeners);
  325. }
  326. }, max_concurrency + 3); // depends on: solve position constraints of the last step, body set island index, contact removed callbacks, finish building the previous step
  327. }
  328. // Create solve jobs for each of the integration sub steps
  329. for (int sub_step_idx = 0; sub_step_idx < inIntegrationSubSteps; ++sub_step_idx)
  330. {
  331. bool is_first_sub_step = sub_step_idx == 0;
  332. bool is_last_sub_step = sub_step_idx == inIntegrationSubSteps - 1;
  333. PhysicsUpdateContext::SubStep &sub_step = step.mSubSteps[sub_step_idx];
  334. sub_step.mStep = &step;
  335. sub_step.mIsFirst = is_first_sub_step;
  336. sub_step.mIsLast = is_last_sub_step;
  337. sub_step.mIsLastOfAll = is_last_step && is_last_sub_step;
  338. // This job will solve the velocity constraints
  339. int num_dependencies_solve_velocity_constraints = is_first_sub_step? 3 : 2; // in first sub step depends on: finalize islands, setup velocity constraints, in later sub steps depends on: previous sub step finished. For both: finish building jobs.
  340. sub_step.mSolveVelocityConstraints.resize(max_concurrency);
  341. for (int i = 0; i < max_concurrency; ++i)
  342. sub_step.mSolveVelocityConstraints[i] = inJobSystem->CreateJob("SolveVelocityConstraints", cColorSolveVelocityConstraints, [&context, &sub_step]()
  343. {
  344. context.mPhysicsSystem->JobSolveVelocityConstraints(&context, &sub_step);
  345. sub_step.mPreIntegrateVelocity.RemoveDependency();
  346. }, num_dependencies_solve_velocity_constraints);
  347. // Unblock previous jobs
  348. if (is_first_sub_step)
  349. {
  350. // Kick find collisions after setup velocity constraints because the former job will use up all CPU cores
  351. step.mSetupVelocityConstraints.RemoveDependency();
  352. JobHandle::sRemoveDependencies(step.mFindCollisions);
  353. // Finalize islands is a dependency on find collisions so it can go last
  354. step.mFinalizeIslands.RemoveDependency();
  355. }
  356. else
  357. {
  358. step.mSubSteps[sub_step_idx - 1].mStartNextSubStep.RemoveDependency();
  359. }
  360. // This job will prepare the position update of all active bodies
  361. int num_dependencies_integrate_velocity = is_first_sub_step? 2 + max_concurrency : 1 + max_concurrency; // depends on: broadphase update finalize in first step, solve velocity constraints in all steps. For both: finish building jobs.
  362. sub_step.mPreIntegrateVelocity = inJobSystem->CreateJob("PreIntegrateVelocity", cColorPreIntegrateVelocity, [&context, &sub_step]()
  363. {
  364. context.mPhysicsSystem->JobPreIntegrateVelocity(&context, &sub_step);
  365. JobHandle::sRemoveDependencies(sub_step.mIntegrateVelocity);
  366. }, num_dependencies_integrate_velocity);
  367. // Unblock previous jobs
  368. if (is_first_sub_step)
  369. step.mUpdateBroadphaseFinalize.RemoveDependency();
  370. JobHandle::sRemoveDependencies(sub_step.mSolveVelocityConstraints);
  371. // This job will update the positions of all active bodies
  372. sub_step.mIntegrateVelocity.resize(num_integrate_velocity_jobs);
  373. for (int i = 0; i < num_integrate_velocity_jobs; ++i)
  374. sub_step.mIntegrateVelocity[i] = inJobSystem->CreateJob("IntegrateVelocity", cColorIntegrateVelocity, [&context, &sub_step]()
  375. {
  376. context.mPhysicsSystem->JobIntegrateVelocity(&context, &sub_step);
  377. sub_step.mPostIntegrateVelocity.RemoveDependency();
  378. }, 2); // depends on: pre integrate velocity, finish building jobs.
  379. // Unblock previous job
  380. sub_step.mPreIntegrateVelocity.RemoveDependency();
  381. // This job will finish the position update of all active bodies
  382. sub_step.mPostIntegrateVelocity = inJobSystem->CreateJob("PostIntegrateVelocity", cColorPostIntegrateVelocity, [&context, &sub_step]()
  383. {
  384. context.mPhysicsSystem->JobPostIntegrateVelocity(&context, &sub_step);
  385. sub_step.mResolveCCDContacts.RemoveDependency();
  386. }, num_integrate_velocity_jobs + 1); // depends on: integrate velocity, finish building jobs
  387. // Unblock previous jobs
  388. JobHandle::sRemoveDependencies(sub_step.mIntegrateVelocity);
  389. // This job will update the positions and velocities for all bodies that need continuous collision detection
  390. sub_step.mResolveCCDContacts = inJobSystem->CreateJob("ResolveCCDContacts", cColorResolveCCDContacts, [&context, &sub_step]()
  391. {
  392. context.mPhysicsSystem->JobResolveCCDContacts(&context, &sub_step);
  393. JobHandle::sRemoveDependencies(sub_step.mSolvePositionConstraints);
  394. }, 2); // depends on: integrate velocities, detect ccd contacts (added dynamically), finish building jobs.
  395. // Unblock previous job
  396. sub_step.mPostIntegrateVelocity.RemoveDependency();
  397. // Fixes up drift in positions and updates the broadphase with new body positions
  398. sub_step.mSolvePositionConstraints.resize(max_concurrency);
  399. for (int i = 0; i < max_concurrency; ++i)
  400. sub_step.mSolvePositionConstraints[i] = inJobSystem->CreateJob("SolvePositionConstraints", cColorSolvePositionConstraints, [&context, &sub_step]()
  401. {
  402. context.mPhysicsSystem->JobSolvePositionConstraints(&context, &sub_step);
  403. // Kick the next sub step
  404. if (sub_step.mStartNextSubStep.IsValid())
  405. sub_step.mStartNextSubStep.RemoveDependency();
  406. }, 2); // depends on: resolve ccd contacts, finish building jobs.
  407. // Unblock previous job.
  408. sub_step.mResolveCCDContacts.RemoveDependency();
  409. // This job starts the next sub step
  410. if (!is_last_sub_step)
  411. {
  412. PhysicsUpdateContext::SubStep &next_sub_step = step.mSubSteps[sub_step_idx + 1];
  413. sub_step.mStartNextSubStep = inJobSystem->CreateJob("StartNextSubStep", cColorStartNextSubStep, [&next_sub_step]()
  414. {
  415. // Kick velocity constraint solving for the next sub step
  416. JobHandle::sRemoveDependencies(next_sub_step.mSolveVelocityConstraints);
  417. }, max_concurrency + 1); // depends on: solve position constraints, finish building jobs.
  418. }
  419. else
  420. sub_step.mStartNextSubStep = step.mStartNextStep;
  421. // Unblock previous jobs
  422. JobHandle::sRemoveDependencies(sub_step.mSolvePositionConstraints);
  423. }
  424. }
  425. }
  426. // Build the list of jobs to wait for
  427. JobSystem::Barrier *barrier = context.mBarrier;
  428. {
  429. JPH_PROFILE("Build job barrier");
  430. StaticArray<JobHandle, cMaxPhysicsJobs> handles;
  431. for (const PhysicsUpdateContext::Step &step : context.mSteps)
  432. {
  433. if (step.mBroadPhasePrepare.IsValid())
  434. handles.push_back(step.mBroadPhasePrepare);
  435. for (const JobHandle &h : step.mStepListeners)
  436. handles.push_back(h);
  437. for (const JobHandle &h : step.mDetermineActiveConstraints)
  438. handles.push_back(h);
  439. for (const JobHandle &h : step.mApplyGravity)
  440. handles.push_back(h);
  441. for (const JobHandle &h : step.mFindCollisions)
  442. handles.push_back(h);
  443. if (step.mUpdateBroadphaseFinalize.IsValid())
  444. handles.push_back(step.mUpdateBroadphaseFinalize);
  445. handles.push_back(step.mSetupVelocityConstraints);
  446. handles.push_back(step.mBuildIslandsFromConstraints);
  447. handles.push_back(step.mFinalizeIslands);
  448. handles.push_back(step.mBodySetIslandIndex);
  449. for (const PhysicsUpdateContext::SubStep &sub_step : step.mSubSteps)
  450. {
  451. for (const JobHandle &h : sub_step.mSolveVelocityConstraints)
  452. handles.push_back(h);
  453. handles.push_back(sub_step.mPreIntegrateVelocity);
  454. for (const JobHandle &h : sub_step.mIntegrateVelocity)
  455. handles.push_back(h);
  456. handles.push_back(sub_step.mPostIntegrateVelocity);
  457. handles.push_back(sub_step.mResolveCCDContacts);
  458. for (const JobHandle &h : sub_step.mSolvePositionConstraints)
  459. handles.push_back(h);
  460. if (sub_step.mStartNextSubStep.IsValid())
  461. handles.push_back(sub_step.mStartNextSubStep);
  462. }
  463. handles.push_back(step.mContactRemovedCallbacks);
  464. }
  465. barrier->AddJobs(handles.data(), handles.size());
  466. }
  467. // Wait until all jobs finish
  468. // Note we don't just wait for the last job. If we would and another job
  469. // would be scheduled in between there is the possibility of a deadlock.
  470. // The other job could try to e.g. add/remove a body which would try to
  471. // lock a body mutex while this thread has already locked the mutex
  472. inJobSystem->WaitForJobs(barrier);
  473. // We're done with the barrier for this update
  474. inJobSystem->DestroyBarrier(barrier);
  475. #ifdef _DEBUG
  476. // Validate that the cached bounds are correct
  477. mBodyManager.ValidateActiveBodyBounds();
  478. #endif // _DEBUG
  479. // Clear the island builder
  480. mIslandBuilder.ResetIslands(inTempAllocator);
  481. // Clear the contact manager
  482. mContactManager.FinishConstraintBuffer();
  483. // Free active constraints
  484. inTempAllocator->Free(context.mActiveConstraints, mConstraintManager.GetNumConstraints() * sizeof(Constraint *));
  485. context.mActiveConstraints = nullptr;
  486. // Free body pairs
  487. inTempAllocator->Free(context.mBodyPairs, sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs);
  488. context.mBodyPairs = nullptr;
  489. // Unlock the broadphase
  490. mBroadPhase->UnlockModifications();
  491. // Unlock all constraints
  492. mConstraintManager.UnlockAllConstraints();
  493. #ifdef JPH_ENABLE_ASSERTS
  494. // Allow write operations to the active bodies list
  495. mBodyManager.SetActiveBodiesLocked(false);
  496. #endif
  497. // Unlock all bodies
  498. mBodyManager.UnlockAllBodies();
  499. // Unlock step listeners
  500. mStepListenersMutex.unlock();
  501. }
  502. void PhysicsSystem::JobStepListeners(PhysicsUpdateContext::Step *ioStep)
  503. {
  504. #ifdef JPH_ENABLE_ASSERTS
  505. // Read positions (broadphase updates concurrently so we can't write), read/write velocities
  506. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  507. // Can activate bodies only (we cache the amount of active bodies at the beginning of the step in mNumActiveBodiesAtStepStart so we cannot deactivate here)
  508. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  509. #endif
  510. float step_time = ioStep->mContext->mStepDeltaTime;
  511. uint32 batch_size = mPhysicsSettings.mStepListenersBatchSize;
  512. for (;;)
  513. {
  514. // Get the start of a new batch
  515. uint32 batch = ioStep->mStepListenerReadIdx.fetch_add(batch_size);
  516. if (batch >= mStepListeners.size())
  517. break;
  518. // Call the listeners
  519. for (uint32 i = batch, i_end = min((uint32)mStepListeners.size(), batch + batch_size); i < i_end; ++i)
  520. mStepListeners[i]->OnStep(step_time, *this);
  521. }
  522. }
  523. void PhysicsSystem::JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const
  524. {
  525. #ifdef JPH_ENABLE_ASSERTS
  526. // No body access
  527. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  528. #endif
  529. uint32 num_constraints = mConstraintManager.GetNumConstraints();
  530. uint32 num_active_constraints;
  531. Constraint **active_constraints = (Constraint **)JPH_STACK_ALLOC(cDetermineActiveConstraintsBatchSize * sizeof(Constraint *));
  532. for (;;)
  533. {
  534. // Atomically fetch a batch of constraints
  535. uint32 constraint_idx = ioStep->mConstraintReadIdx.fetch_add(cDetermineActiveConstraintsBatchSize);
  536. if (constraint_idx >= num_constraints)
  537. break;
  538. // Calculate the end of the batch
  539. uint32 constraint_idx_end = min(num_constraints, constraint_idx + cDetermineActiveConstraintsBatchSize);
  540. // 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)
  541. mConstraintManager.GetActiveConstraints(constraint_idx, constraint_idx_end, active_constraints, num_active_constraints);
  542. // Copy the block of active constraints to the global list of active constraints
  543. if (num_active_constraints > 0)
  544. {
  545. uint32 active_constraint_idx = ioStep->mNumActiveConstraints.fetch_add(num_active_constraints);
  546. memcpy(ioStep->mContext->mActiveConstraints + active_constraint_idx, active_constraints, num_active_constraints * sizeof(Constraint *));
  547. }
  548. }
  549. }
  550. void PhysicsSystem::JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  551. {
  552. #ifdef JPH_ENABLE_ASSERTS
  553. // We update velocities and need the rotation to do so
  554. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  555. #endif
  556. // Get list of active bodies that we had at the start of the physics update.
  557. // Any body that is activated as part of the simulation step does not receive gravity this frame.
  558. // Note that bodies may be activated during this job but not deactivated, this means that only elements
  559. // will be added to the array. Since the array is made to not reallocate, this is a safe operation.
  560. const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe();
  561. uint32 num_active_bodies_at_step_start = ioStep->mNumActiveBodiesAtStepStart;
  562. // Fetch delta time once outside the loop
  563. float delta_time = ioContext->mSubStepDeltaTime;
  564. // Update velocities from forces
  565. for (;;)
  566. {
  567. // Atomically fetch a batch of bodies
  568. uint32 active_body_idx = ioStep->mApplyGravityReadIdx.fetch_add(cApplyGravityBatchSize);
  569. if (active_body_idx >= num_active_bodies_at_step_start)
  570. break;
  571. // Calculate the end of the batch
  572. uint32 active_body_idx_end = min(num_active_bodies_at_step_start, active_body_idx + cApplyGravityBatchSize);
  573. // Process the batch
  574. while (active_body_idx < active_body_idx_end)
  575. {
  576. Body &body = mBodyManager.GetBody(active_bodies[active_body_idx]);
  577. if (body.IsDynamic())
  578. body.GetMotionProperties()->ApplyForceTorqueAndDragInternal(body.GetRotation(), mGravity, delta_time);
  579. active_body_idx++;
  580. }
  581. }
  582. }
  583. void PhysicsSystem::JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const
  584. {
  585. #ifdef JPH_ENABLE_ASSERTS
  586. // We only read positions
  587. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  588. #endif
  589. ConstraintManager::sSetupVelocityConstraints(ioStep->mContext->mActiveConstraints, ioStep->mNumActiveConstraints, inDeltaTime);
  590. }
  591. void PhysicsSystem::JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)
  592. {
  593. #ifdef JPH_ENABLE_ASSERTS
  594. // We read constraints and positions
  595. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  596. // Can only activate bodies
  597. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  598. #endif
  599. // Prepare the island builder
  600. mIslandBuilder.PrepareNonContactConstraints(ioStep->mNumActiveConstraints, ioContext->mTempAllocator);
  601. // Build the islands
  602. ConstraintManager::sBuildIslands(ioStep->mContext->mActiveConstraints, ioStep->mNumActiveConstraints, mIslandBuilder, mBodyManager);
  603. }
  604. void PhysicsSystem::TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const
  605. {
  606. // Get how many jobs we can spawn and check if we can spawn more
  607. uint max_jobs = ioStep->mBodyPairQueues.size();
  608. if (CountBits(ioStep->mActiveFindCollisionJobs) >= max_jobs)
  609. return;
  610. // Count how many body pairs we have waiting
  611. uint32 num_body_pairs = 0;
  612. for (const PhysicsUpdateContext::BodyPairQueue &queue : ioStep->mBodyPairQueues)
  613. num_body_pairs += queue.mWriteIdx - queue.mReadIdx;
  614. // Count how many active bodies we have waiting
  615. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies() - ioStep->mActiveBodyReadIdx;
  616. // Calculate how many jobs we would like
  617. uint desired_num_jobs = min((num_body_pairs + cNarrowPhaseBatchSize - 1) / cNarrowPhaseBatchSize + (num_active_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_jobs);
  618. for (;;)
  619. {
  620. // Get the bit mask of active jobs and see if we can spawn more
  621. PhysicsUpdateContext::JobMask current_active_jobs = ioStep->mActiveFindCollisionJobs;
  622. if (CountBits(current_active_jobs) >= desired_num_jobs)
  623. break;
  624. // Loop through all possible job indices
  625. for (uint job_index = 0; job_index < max_jobs; ++job_index)
  626. {
  627. // Test if it has been started
  628. PhysicsUpdateContext::JobMask job_mask = PhysicsUpdateContext::JobMask(1) << job_index;
  629. if ((current_active_jobs & job_mask) == 0)
  630. {
  631. // Try to claim the job index
  632. PhysicsUpdateContext::JobMask prev_value = ioStep->mActiveFindCollisionJobs.fetch_or(job_mask);
  633. if ((prev_value & job_mask) == 0)
  634. {
  635. // Add dependencies from the find collisions job to the next jobs
  636. ioStep->mUpdateBroadphaseFinalize.AddDependency();
  637. ioStep->mFinalizeIslands.AddDependency();
  638. // Start the job
  639. JobHandle job = ioStep->mContext->mJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [step = ioStep, job_index]()
  640. {
  641. step->mContext->mPhysicsSystem->JobFindCollisions(step, job_index);
  642. });
  643. // Add the job to the job barrier so the main updating thread can execute the job too
  644. ioStep->mContext->mBarrier->AddJob(job);
  645. // Spawn only 1 extra job at a time
  646. return;
  647. }
  648. }
  649. }
  650. }
  651. }
  652. void PhysicsSystem::JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex)
  653. {
  654. #ifdef JPH_ENABLE_ASSERTS
  655. // We only read positions
  656. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);
  657. #endif
  658. // Allocation context for allocating new contact points
  659. ContactAllocator contact_allocator(mContactManager.GetContactAllocator());
  660. // Determine initial queue to read pairs from if no broadphase work can be done
  661. // (always start looking at results from the next job)
  662. int read_queue_idx = (inJobIndex + 1) % ioStep->mBodyPairQueues.size();
  663. for (;;)
  664. {
  665. // Check if there are active bodies to be processed
  666. uint32 active_bodies_read_idx = ioStep->mActiveBodyReadIdx;
  667. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies();
  668. if (active_bodies_read_idx < num_active_bodies)
  669. {
  670. // Take a batch of active bodies
  671. uint32 active_bodies_read_idx_end = min(num_active_bodies, active_bodies_read_idx + cActiveBodiesBatchSize);
  672. if (ioStep->mActiveBodyReadIdx.compare_exchange_strong(active_bodies_read_idx, active_bodies_read_idx_end))
  673. {
  674. // Callback when a new body pair is found
  675. class MyBodyPairCallback : public BodyPairCollector
  676. {
  677. public:
  678. // Constructor
  679. MyBodyPairCallback(PhysicsUpdateContext::Step *inStep, ContactAllocator &ioContactAllocator, int inJobIndex) :
  680. mStep(inStep),
  681. mContactAllocator(ioContactAllocator),
  682. mJobIndex(inJobIndex)
  683. {
  684. }
  685. // Callback function when a body pair is found
  686. virtual void AddHit(const BodyPair &inPair) override
  687. {
  688. // Check if we have space in our write queue
  689. PhysicsUpdateContext::BodyPairQueue &queue = mStep->mBodyPairQueues[mJobIndex];
  690. uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;
  691. if (body_pairs_in_queue >= mStep->mMaxBodyPairsPerQueue)
  692. {
  693. // Buffer full, process the pair now
  694. mStep->mContext->mPhysicsSystem->ProcessBodyPair(mContactAllocator, inPair);
  695. }
  696. else
  697. {
  698. // Store the pair in our own queue
  699. mStep->mContext->mBodyPairs[mJobIndex * mStep->mMaxBodyPairsPerQueue + queue.mWriteIdx % mStep->mMaxBodyPairsPerQueue] = inPair;
  700. ++queue.mWriteIdx;
  701. }
  702. }
  703. private:
  704. PhysicsUpdateContext::Step * mStep;
  705. ContactAllocator & mContactAllocator;
  706. int mJobIndex;
  707. };
  708. MyBodyPairCallback add_pair(ioStep, contact_allocator, inJobIndex);
  709. // Copy active bodies to temporary array, broadphase will reorder them
  710. uint32 batch_size = active_bodies_read_idx_end - active_bodies_read_idx;
  711. BodyID *active_bodies = (BodyID *)JPH_STACK_ALLOC(batch_size * sizeof(BodyID));
  712. memcpy(active_bodies, mBodyManager.GetActiveBodiesUnsafe() + active_bodies_read_idx, batch_size * sizeof(BodyID));
  713. // Find pairs in the broadphase
  714. mBroadPhase->FindCollidingPairs(active_bodies, batch_size, mPhysicsSettings.mSpeculativeContactDistance, mObjectVsBroadPhaseLayerFilter, mObjectLayerPairFilter, add_pair);
  715. // Check if we have enough pairs in the buffer to start a new job
  716. const PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[inJobIndex];
  717. uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;
  718. if (body_pairs_in_queue >= cNarrowPhaseBatchSize)
  719. TrySpawnJobFindCollisions(ioStep);
  720. }
  721. }
  722. else
  723. {
  724. // Lockless loop to get the next body pair from the pairs buffer
  725. const PhysicsUpdateContext *context = ioStep->mContext;
  726. int first_read_queue_idx = read_queue_idx;
  727. for (;;)
  728. {
  729. PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[read_queue_idx];
  730. // Get the next pair to process
  731. uint32 pair_idx = queue.mReadIdx;
  732. // If the pair hasn't been written yet
  733. if (pair_idx >= queue.mWriteIdx)
  734. {
  735. // Go to the next queue
  736. read_queue_idx = (read_queue_idx + 1) % ioStep->mBodyPairQueues.size();
  737. // If we're back at the first queue, we've looked at all of them and found nothing
  738. if (read_queue_idx == first_read_queue_idx)
  739. {
  740. // Atomically accumulate the number of found manifolds and body pairs
  741. ioStep->mNumBodyPairs += contact_allocator.mNumBodyPairs;
  742. ioStep->mNumManifolds += contact_allocator.mNumManifolds;
  743. // Mark this job as inactive
  744. ioStep->mActiveFindCollisionJobs.fetch_and(~PhysicsUpdateContext::JobMask(1 << inJobIndex));
  745. // Trigger the next jobs
  746. ioStep->mUpdateBroadphaseFinalize.RemoveDependency();
  747. ioStep->mFinalizeIslands.RemoveDependency();
  748. return;
  749. }
  750. // Try again reading from the next queue
  751. continue;
  752. }
  753. // Copy the body pair out of the buffer
  754. const BodyPair bp = context->mBodyPairs[read_queue_idx * ioStep->mMaxBodyPairsPerQueue + pair_idx % ioStep->mMaxBodyPairsPerQueue];
  755. // Mark this pair as taken
  756. if (queue.mReadIdx.compare_exchange_strong(pair_idx, pair_idx + 1))
  757. {
  758. // Process the actual body pair
  759. ProcessBodyPair(contact_allocator, bp);
  760. break;
  761. }
  762. }
  763. }
  764. }
  765. }
  766. void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair)
  767. {
  768. JPH_PROFILE_FUNCTION();
  769. #ifdef JPH_ENABLE_ASSERTS
  770. // We read positions and read velocities (for elastic collisions)
  771. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  772. // Can only activate bodies
  773. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  774. #endif
  775. // Fetch body pair
  776. Body *body1 = &mBodyManager.GetBody(inBodyPair.mBodyA);
  777. Body *body2 = &mBodyManager.GetBody(inBodyPair.mBodyB);
  778. JPH_ASSERT(body1->IsActive());
  779. // Ensure that body1 is dynamic, this ensures that we do the collision detection in the space of a moving body, which avoids accuracy problems when testing a very large static object against a small dynamic object
  780. // Ensure that body1 id < body2 id for dynamic vs dynamic
  781. // Keep body order unchanged when colliding with a sensor
  782. if ((!body1->IsDynamic() || (body2->IsDynamic() && inBodyPair.mBodyB < inBodyPair.mBodyA))
  783. && !body2->IsSensor())
  784. swap(body1, body2);
  785. JPH_ASSERT(body1->IsDynamic() || (body1->IsKinematic() && body2->IsSensor()));
  786. // Check if the contact points from the previous frame are reusable and if so copy them
  787. bool pair_handled = false, constraint_created = false;
  788. if (mPhysicsSettings.mUseBodyPairContactCache && !(body1->IsCollisionCacheInvalid() || body2->IsCollisionCacheInvalid()))
  789. mContactManager.GetContactsFromCache(ioContactAllocator, *body1, *body2, pair_handled, constraint_created);
  790. // If the cache hasn't handled this body pair do actual collision detection
  791. if (!pair_handled)
  792. {
  793. // Create entry in the cache for this body pair
  794. // Needs to happen irrespective if we found a collision or not (we want to remember that no collision was found too)
  795. ContactConstraintManager::BodyPairHandle body_pair_handle = mContactManager.AddBodyPair(ioContactAllocator, *body1, *body2);
  796. if (body_pair_handle == nullptr)
  797. return; // Out of cache space
  798. // Create the query settings
  799. CollideShapeSettings settings;
  800. settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;
  801. settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  802. settings.mMaxSeparationDistance = mPhysicsSettings.mSpeculativeContactDistance;
  803. settings.mActiveEdgeMovementDirection = body1->GetLinearVelocity() - body2->GetLinearVelocity();
  804. if (mPhysicsSettings.mUseManifoldReduction)
  805. {
  806. // Version WITH contact manifold reduction
  807. class MyManifold : public ContactManifold
  808. {
  809. public:
  810. Vec3 mFirstWorldSpaceNormal;
  811. };
  812. // A temporary structure that allows us to keep track of the all manifolds between this body pair
  813. using Manifolds = StaticArray<MyManifold, 32>;
  814. // Create collector
  815. class ReductionCollideShapeCollector : public CollideShapeCollector
  816. {
  817. public:
  818. ReductionCollideShapeCollector(PhysicsSystem *inSystem, const Body *inBody1, const Body *inBody2) :
  819. mSystem(inSystem),
  820. mBody1(inBody1),
  821. mBody2(inBody2)
  822. {
  823. }
  824. virtual void AddHit(const CollideShapeResult &inResult) override
  825. {
  826. // One of the following should be true:
  827. // - Body 1 is dynamic and body 2 may be dynamic, static or kinematic
  828. // - Body 1 is kinematic in which case body 2 should be a sensor
  829. JPH_ASSERT(mBody1->IsDynamic() || (mBody1->IsKinematic() && mBody2->IsSensor()));
  830. JPH_ASSERT(!ShouldEarlyOut());
  831. // Test if we want to accept this hit
  832. if (mValidateBodyPair)
  833. {
  834. switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, inResult))
  835. {
  836. case ValidateResult::AcceptContact:
  837. // We're just accepting this one, nothing to do
  838. break;
  839. case ValidateResult::AcceptAllContactsForThisBodyPair:
  840. // Accept and stop calling the validate callback
  841. mValidateBodyPair = false;
  842. break;
  843. case ValidateResult::RejectContact:
  844. // Skip this contact
  845. return;
  846. case ValidateResult::RejectAllContactsForThisBodyPair:
  847. // Skip this and early out
  848. ForceEarlyOut();
  849. return;
  850. }
  851. }
  852. // Calculate normal
  853. Vec3 world_space_normal = inResult.mPenetrationAxis.Normalized();
  854. // Check if we can add it to an existing manifold
  855. Manifolds::iterator manifold;
  856. float contact_normal_cos_max_delta_rot = mSystem->mPhysicsSettings.mContactNormalCosMaxDeltaRotation;
  857. for (manifold = mManifolds.begin(); manifold != mManifolds.end(); ++manifold)
  858. if (world_space_normal.Dot(manifold->mFirstWorldSpaceNormal) >= contact_normal_cos_max_delta_rot)
  859. {
  860. // Update average normal
  861. manifold->mWorldSpaceNormal += world_space_normal;
  862. manifold->mPenetrationDepth = max(manifold->mPenetrationDepth, inResult.mPenetrationDepth);
  863. break;
  864. }
  865. if (manifold == mManifolds.end())
  866. {
  867. // Check if array is full
  868. if (mManifolds.size() == mManifolds.capacity())
  869. {
  870. // Full, find manifold with least amount of penetration
  871. manifold = mManifolds.begin();
  872. for (Manifolds::iterator m = mManifolds.begin() + 1; m < mManifolds.end(); ++m)
  873. if (m->mPenetrationDepth < manifold->mPenetrationDepth)
  874. manifold = m;
  875. // If this contacts penetration is smaller than the smallest manifold, we skip this contact
  876. if (inResult.mPenetrationDepth < manifold->mPenetrationDepth)
  877. return;
  878. // Replace the manifold
  879. *manifold = { { world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal };
  880. }
  881. else
  882. {
  883. // Not full, create new manifold
  884. mManifolds.push_back({ { world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal });
  885. manifold = mManifolds.end() - 1;
  886. }
  887. }
  888. // Determine contact points
  889. const PhysicsSettings &settings = mSystem->mPhysicsSettings;
  890. ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, Square(settings.mSpeculativeContactDistance) + settings.mManifoldToleranceSq, inResult.mShape1Face, inResult.mShape2Face, manifold->mWorldSpaceContactPointsOn1, manifold->mWorldSpaceContactPointsOn2);
  891. // Prune if we have more than 32 points (this means we could run out of space in the next iteration)
  892. if (manifold->mWorldSpaceContactPointsOn1.size() > 32)
  893. PruneContactPoints(mBody1->GetCenterOfMassPosition(), manifold->mFirstWorldSpaceNormal, manifold->mWorldSpaceContactPointsOn1, manifold->mWorldSpaceContactPointsOn2);
  894. }
  895. PhysicsSystem * mSystem;
  896. const Body * mBody1;
  897. const Body * mBody2;
  898. bool mValidateBodyPair = true;
  899. Manifolds mManifolds;
  900. };
  901. ReductionCollideShapeCollector collector(this, body1, body2);
  902. // Perform collision detection between the two shapes
  903. SubShapeIDCreator part1, part2;
  904. CollisionDispatch::sCollideShapeVsShape(body1->GetShape(), body2->GetShape(), Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), body1->GetCenterOfMassTransform(), body2->GetCenterOfMassTransform(), part1, part2, settings, collector);
  905. // Add the contacts
  906. for (ContactManifold &manifold : collector.mManifolds)
  907. {
  908. // Normalize the normal (is a sum of all normals from merged manifolds)
  909. manifold.mWorldSpaceNormal = manifold.mWorldSpaceNormal.Normalized();
  910. // If we still have too many points, prune them now
  911. if (manifold.mWorldSpaceContactPointsOn1.size() > 4)
  912. PruneContactPoints(body1->GetCenterOfMassPosition(), manifold.mWorldSpaceNormal, manifold.mWorldSpaceContactPointsOn1, manifold.mWorldSpaceContactPointsOn2);
  913. // Actually add the contact points to the manager
  914. constraint_created |= mContactManager.AddContactConstraint(ioContactAllocator, body_pair_handle, *body1, *body2, manifold);
  915. }
  916. }
  917. else
  918. {
  919. // Version WITHOUT contact manifold reduction
  920. // Create collector
  921. class NonReductionCollideShapeCollector : public CollideShapeCollector
  922. {
  923. public:
  924. NonReductionCollideShapeCollector(PhysicsSystem *inSystem, ContactAllocator &ioContactAllocator, Body *inBody1, Body *inBody2, const ContactConstraintManager::BodyPairHandle &inPairHandle) :
  925. mSystem(inSystem),
  926. mContactAllocator(ioContactAllocator),
  927. mBody1(inBody1),
  928. mBody2(inBody2),
  929. mBodyPairHandle(inPairHandle)
  930. {
  931. }
  932. virtual void AddHit(const CollideShapeResult &inResult) override
  933. {
  934. // Body 1 should always be dynamic, body 2 may be static / kinematic
  935. JPH_ASSERT(mBody1->IsDynamic());
  936. JPH_ASSERT(!ShouldEarlyOut());
  937. // Test if we want to accept this hit
  938. if (mValidateBodyPair)
  939. {
  940. switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, inResult))
  941. {
  942. case ValidateResult::AcceptContact:
  943. // We're just accepting this one, nothing to do
  944. break;
  945. case ValidateResult::AcceptAllContactsForThisBodyPair:
  946. // Accept and stop calling the validate callback
  947. mValidateBodyPair = false;
  948. break;
  949. case ValidateResult::RejectContact:
  950. // Skip this contact
  951. return;
  952. case ValidateResult::RejectAllContactsForThisBodyPair:
  953. // Skip this and early out
  954. ForceEarlyOut();
  955. return;
  956. }
  957. }
  958. // Determine contact points
  959. ContactManifold manifold;
  960. const PhysicsSettings &settings = mSystem->mPhysicsSettings;
  961. ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, Square(settings.mSpeculativeContactDistance) + settings.mManifoldToleranceSq, inResult.mShape1Face, inResult.mShape2Face, manifold.mWorldSpaceContactPointsOn1, manifold.mWorldSpaceContactPointsOn2);
  962. // Calculate normal
  963. manifold.mWorldSpaceNormal = inResult.mPenetrationAxis.Normalized();
  964. // Store penetration depth
  965. manifold.mPenetrationDepth = inResult.mPenetrationDepth;
  966. // Prune if we have more than 4 points
  967. if (manifold.mWorldSpaceContactPointsOn1.size() > 4)
  968. PruneContactPoints(mBody1->GetCenterOfMassPosition(), manifold.mWorldSpaceNormal, manifold.mWorldSpaceContactPointsOn1, manifold.mWorldSpaceContactPointsOn2);
  969. // Set other properties
  970. manifold.mSubShapeID1 = inResult.mSubShapeID1;
  971. manifold.mSubShapeID2 = inResult.mSubShapeID2;
  972. // Actually add the contact points to the manager
  973. mConstraintCreated |= mSystem->mContactManager.AddContactConstraint(mContactAllocator, mBodyPairHandle, *mBody1, *mBody2, manifold);
  974. }
  975. PhysicsSystem * mSystem;
  976. ContactAllocator & mContactAllocator;
  977. Body * mBody1;
  978. Body * mBody2;
  979. ContactConstraintManager::BodyPairHandle mBodyPairHandle;
  980. bool mValidateBodyPair = true;
  981. bool mConstraintCreated = false;
  982. };
  983. NonReductionCollideShapeCollector collector(this, ioContactAllocator, body1, body2, body_pair_handle);
  984. // Perform collision detection between the two shapes
  985. SubShapeIDCreator part1, part2;
  986. CollisionDispatch::sCollideShapeVsShape(body1->GetShape(), body2->GetShape(), Vec3::sReplicate(1.0f), Vec3::sReplicate(1.0f), body1->GetCenterOfMassTransform(), body2->GetCenterOfMassTransform(), part1, part2, settings, collector);
  987. constraint_created = collector.mConstraintCreated;
  988. }
  989. }
  990. // If a contact constraint was created, we need to do some extra work
  991. if (constraint_created)
  992. {
  993. // Wake up sleeping bodies
  994. BodyID body_ids[2];
  995. int num_bodies = 0;
  996. if (body1->IsDynamic() && !body1->IsActive())
  997. body_ids[num_bodies++] = body1->GetID();
  998. if (body2->IsDynamic() && !body2->IsActive())
  999. body_ids[num_bodies++] = body2->GetID();
  1000. if (num_bodies > 0)
  1001. mBodyManager.ActivateBodies(body_ids, num_bodies);
  1002. // Link the two bodies
  1003. mIslandBuilder.LinkBodies(body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());
  1004. }
  1005. }
  1006. void PhysicsSystem::JobFinalizeIslands(PhysicsUpdateContext *ioContext)
  1007. {
  1008. #ifdef JPH_ENABLE_ASSERTS
  1009. // We only touch island data
  1010. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1011. #endif
  1012. // Finish collecting the islands, at this point the active body list doesn't change so it's safe to access
  1013. mIslandBuilder.Finalize(mBodyManager.GetActiveBodiesUnsafe(), mBodyManager.GetNumActiveBodies(), mContactManager.GetNumConstraints(), ioContext->mTempAllocator);
  1014. }
  1015. void PhysicsSystem::JobBodySetIslandIndex()
  1016. {
  1017. #ifdef JPH_ENABLE_ASSERTS
  1018. // We only touch island data
  1019. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1020. #endif
  1021. // Loop through the result and tag all bodies with an island index
  1022. for (uint32 island_idx = 0, n = mIslandBuilder.GetNumIslands(); island_idx < n; ++island_idx)
  1023. {
  1024. BodyID *body_start, *body_end;
  1025. mIslandBuilder.GetBodiesInIsland(island_idx, body_start, body_end);
  1026. for (const BodyID *body = body_start; body < body_end; ++body)
  1027. mBodyManager.GetBody(*body).GetMotionProperties()->SetIslandIndexInternal(island_idx);
  1028. }
  1029. }
  1030. void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1031. {
  1032. #ifdef JPH_ENABLE_ASSERTS
  1033. // We update velocities and need to read positions to do so
  1034. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);
  1035. #endif
  1036. float delta_time = ioContext->mSubStepDeltaTime;
  1037. float warm_start_impulse_ratio = ioContext->mWarmStartImpulseRatio;
  1038. Constraint **active_constraints = ioContext->mActiveConstraints;
  1039. bool first_sub_step = ioSubStep->mIsFirst;
  1040. bool last_sub_step = ioSubStep->mIsLast;
  1041. for (;;)
  1042. {
  1043. // Next island
  1044. uint32 island_idx = ioSubStep->mSolveVelocityConstraintsNextIsland++;
  1045. if (island_idx >= mIslandBuilder.GetNumIslands())
  1046. break;
  1047. JPH_PROFILE("Island");
  1048. // Get iterators
  1049. uint32 *constraints_begin, *constraints_end;
  1050. bool has_constraints = mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);
  1051. uint32 *contacts_begin, *contacts_end;
  1052. bool has_contacts = mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);
  1053. if (first_sub_step)
  1054. {
  1055. // If we don't have any contacts or constraints, we know that none of the following islands have any contacts or constraints
  1056. // (because they're sorted by most constraints first). This means we're done.
  1057. if (!has_contacts && !has_constraints)
  1058. {
  1059. #ifdef JPH_ENABLE_ASSERTS
  1060. // Validate our assumption that the next islands don't have any constraints or contacts
  1061. for (; island_idx < mIslandBuilder.GetNumIslands(); ++island_idx)
  1062. {
  1063. JPH_ASSERT(!mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end));
  1064. JPH_ASSERT(!mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end));
  1065. }
  1066. #endif // JPH_ENABLE_ASSERTS
  1067. return;
  1068. }
  1069. // Sort constraints to give a deterministic simulation
  1070. ConstraintManager::sSortConstraints(active_constraints, constraints_begin, constraints_end);
  1071. // Sort contacts to give a deterministic simulation
  1072. mContactManager.SortContacts(contacts_begin, contacts_end);
  1073. }
  1074. else
  1075. {
  1076. {
  1077. JPH_PROFILE("Apply Gravity");
  1078. // Get bodies in this island
  1079. BodyID *bodies_begin, *bodies_end;
  1080. mIslandBuilder.GetBodiesInIsland(island_idx, bodies_begin, bodies_end);
  1081. // Apply gravity. In the first step this is done in a separate job.
  1082. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1083. {
  1084. Body &body = mBodyManager.GetBody(*body_id);
  1085. if (body.IsDynamic())
  1086. body.GetMotionProperties()->ApplyForceTorqueAndDragInternal(body.GetRotation(), mGravity, delta_time);
  1087. }
  1088. }
  1089. // If we don't have any contacts or constraints, we don't need to run the solver, but we do need to process
  1090. // the next island in order to apply gravity
  1091. if (!has_contacts && !has_constraints)
  1092. continue;
  1093. // Prepare velocity constraints. In the first step this is done when adding the contact constraints.
  1094. ConstraintManager::sSetupVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1095. mContactManager.SetupVelocityConstraints(contacts_begin, contacts_end, delta_time);
  1096. }
  1097. // Warm start
  1098. ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio);
  1099. mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio);
  1100. // Solve
  1101. for (int velocity_step = 0; velocity_step < mPhysicsSettings.mNumVelocitySteps; ++velocity_step)
  1102. {
  1103. bool constraint_impulse = ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);
  1104. bool contact_impulse = mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);
  1105. if (!constraint_impulse && !contact_impulse)
  1106. break;
  1107. }
  1108. // Save back the lambdas in the contact cache for the warm start of the next physics update
  1109. if (last_sub_step)
  1110. mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);
  1111. }
  1112. }
  1113. void PhysicsSystem::JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const
  1114. {
  1115. // Reserve enough space for all bodies that may need a cast
  1116. TempAllocator *temp_allocator = ioContext->mTempAllocator;
  1117. JPH_ASSERT(ioSubStep->mCCDBodies == nullptr);
  1118. ioSubStep->mCCDBodiesCapacity = mBodyManager.GetNumActiveCCDBodies();
  1119. ioSubStep->mCCDBodies = (CCDBody *)temp_allocator->Allocate(ioSubStep->mCCDBodiesCapacity * sizeof(CCDBody));
  1120. // Initialize the mapping table between active body and CCD body
  1121. JPH_ASSERT(ioSubStep->mActiveBodyToCCDBody == nullptr);
  1122. ioSubStep->mNumActiveBodyToCCDBody = mBodyManager.GetNumActiveBodies();
  1123. ioSubStep->mActiveBodyToCCDBody = (int *)temp_allocator->Allocate(ioSubStep->mNumActiveBodyToCCDBody * sizeof(int));
  1124. }
  1125. void PhysicsSystem::JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1126. {
  1127. #ifdef JPH_ENABLE_ASSERTS
  1128. // We update positions and need velocity to do so, we also clamp velocities so need to write to them
  1129. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  1130. #endif
  1131. float delta_time = ioContext->mSubStepDeltaTime;
  1132. const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe();
  1133. uint32 num_active_bodies = mBodyManager.GetNumActiveBodies();
  1134. uint32 num_active_bodies_after_find_collisions = ioSubStep->mStep->mActiveBodyReadIdx;
  1135. // We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.
  1136. static constexpr int cBodiesBatch = 64;
  1137. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1138. int num_bodies_to_update_bounds = 0;
  1139. for (;;)
  1140. {
  1141. // Atomically fetch a batch of bodies
  1142. uint32 active_body_idx = ioSubStep->mIntegrateVelocityReadIdx.fetch_add(cIntegrateVelocityBatchSize);
  1143. if (active_body_idx >= num_active_bodies)
  1144. break;
  1145. // Calculate the end of the batch
  1146. uint32 active_body_idx_end = min(num_active_bodies, active_body_idx + cIntegrateVelocityBatchSize);
  1147. // Process the batch
  1148. while (active_body_idx < active_body_idx_end)
  1149. {
  1150. // Update the positions using an Symplectic Euler step (which integrates using the updated velocity v1' rather
  1151. // than the original velocity v1):
  1152. // x1' = x1 + h * v1'
  1153. // At this point the active bodies list does not change, so it is safe to access the array.
  1154. BodyID body_id = active_bodies[active_body_idx];
  1155. Body &body = mBodyManager.GetBody(body_id);
  1156. MotionProperties *mp = body.GetMotionProperties();
  1157. // Clamp velocities (not for kinematic bodies)
  1158. if (body.IsDynamic())
  1159. {
  1160. mp->ClampLinearVelocity();
  1161. mp->ClampAngularVelocity();
  1162. }
  1163. // Update the rotation of the body according to the angular velocity
  1164. // For motion type discrete we need to do this anyway, for motion type linear cast we have multiple choices
  1165. // 1. Rotate the body first and then sweep
  1166. // 2. First sweep and then rotate the body at the end
  1167. // 3. Pick some inbetween rotation (e.g. half way), then sweep and finally rotate the remainder
  1168. // (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.
  1169. // 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
  1170. // 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
  1171. // 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
  1172. // too as simulating the rotation first may cause it to tunnel through a small object that the linear cast might have otherwise dectected. In any case a linear cast is not good for detecting
  1173. // 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).
  1174. body.AddRotationStep(body.GetAngularVelocity() * delta_time);
  1175. // Get delta position
  1176. Vec3 delta_pos = body.GetLinearVelocity() * delta_time;
  1177. // If the position should be updated (or if it is delayed because of CCD)
  1178. bool update_position = true;
  1179. switch (mp->GetMotionQuality())
  1180. {
  1181. case EMotionQuality::Discrete:
  1182. // No additional collision checking to be done
  1183. break;
  1184. case EMotionQuality::LinearCast:
  1185. if (body.IsDynamic() // Kinematic bodies cannot be stopped
  1186. && !body.IsSensor()) // We don't support CCD sensors
  1187. {
  1188. // Determine inner radius (the smallest sphere that fits into the shape)
  1189. float inner_radius = body.GetShape()->GetInnerRadius();
  1190. 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.");
  1191. // Measure translation in this step and check if it above the treshold to perform a linear cast
  1192. float linear_cast_threshold_sq = Square(mPhysicsSettings.mLinearCastThreshold * inner_radius);
  1193. if (delta_pos.LengthSq() > linear_cast_threshold_sq)
  1194. {
  1195. // This body needs a cast
  1196. uint32 ccd_body_idx = ioSubStep->mNumCCDBodies++;
  1197. ioSubStep->mActiveBodyToCCDBody[active_body_idx] = ccd_body_idx;
  1198. new (&ioSubStep->mCCDBodies[ccd_body_idx]) CCDBody(body_id, delta_pos, linear_cast_threshold_sq, min(mPhysicsSettings.mPenetrationSlop, mPhysicsSettings.mLinearCastMaxPenetration * inner_radius));
  1199. update_position = false;
  1200. }
  1201. }
  1202. break;
  1203. }
  1204. if (update_position)
  1205. {
  1206. // Move the body now
  1207. body.AddPositionStep(delta_pos);
  1208. // If the body was activated due to an earlier CCD step it will have an index in the active
  1209. // body list that it higher than the highest one we processed during FindCollisions
  1210. // which means it hasn't been assigned an island and will not be updated by an island
  1211. // this means that we need to update its bounds manually
  1212. if (mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)
  1213. {
  1214. body.CalculateWorldSpaceBoundsInternal();
  1215. bodies_to_update_bounds[num_bodies_to_update_bounds++] = body.GetID();
  1216. if (num_bodies_to_update_bounds == cBodiesBatch)
  1217. {
  1218. // Buffer full, flush now
  1219. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds);
  1220. num_bodies_to_update_bounds = 0;
  1221. }
  1222. }
  1223. // We did not create a CCD body
  1224. ioSubStep->mActiveBodyToCCDBody[active_body_idx] = -1;
  1225. }
  1226. active_body_idx++;
  1227. }
  1228. }
  1229. // Notify change bounds on requested bodies
  1230. if (num_bodies_to_update_bounds > 0)
  1231. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1232. }
  1233. void PhysicsSystem::JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep) const
  1234. {
  1235. // Validate that our reservations were correct
  1236. JPH_ASSERT(ioSubStep->mNumCCDBodies <= mBodyManager.GetNumActiveCCDBodies());
  1237. if (ioSubStep->mNumCCDBodies == 0)
  1238. {
  1239. // No continous collision detection jobs -> kick the next job ourselves
  1240. if (ioSubStep->mIsLast)
  1241. ioSubStep->mStep->mContactRemovedCallbacks.RemoveDependency();
  1242. }
  1243. else
  1244. {
  1245. // Run the continous collision detection jobs
  1246. int num_continuous_collision_jobs = min(int(ioSubStep->mNumCCDBodies + cNumCCDBodiesPerJob - 1) / cNumCCDBodiesPerJob, ioContext->GetMaxConcurrency());
  1247. ioSubStep->mResolveCCDContacts.AddDependency(num_continuous_collision_jobs);
  1248. if (ioSubStep->mIsLast)
  1249. ioSubStep->mStep->mContactRemovedCallbacks.AddDependency(num_continuous_collision_jobs - 1); // Already had 1 dependency
  1250. for (int i = 0; i < num_continuous_collision_jobs; ++i)
  1251. {
  1252. JobHandle job = ioContext->mJobSystem->CreateJob("FindCCDContacts", cColorFindCCDContacts, [ioContext, ioSubStep]()
  1253. {
  1254. ioContext->mPhysicsSystem->JobFindCCDContacts(ioContext, ioSubStep);
  1255. ioSubStep->mResolveCCDContacts.RemoveDependency();
  1256. if (ioSubStep->mIsLast)
  1257. ioSubStep->mStep->mContactRemovedCallbacks.RemoveDependency();
  1258. });
  1259. ioContext->mBarrier->AddJob(job);
  1260. }
  1261. }
  1262. }
  1263. // Helper function to calculate the motion of a body during this CCD step
  1264. inline static Vec3 sCalculateBodyMotion(const Body &inBody, float inDeltaTime)
  1265. {
  1266. // If the body is linear casting, the body has not yet moved so we need to calculate its motion
  1267. if (inBody.IsDynamic() && inBody.GetMotionProperties()->GetMotionQuality() == EMotionQuality::LinearCast)
  1268. return inDeltaTime * inBody.GetLinearVelocity();
  1269. // Body has already moved, so we don't need to correct for anything
  1270. return Vec3::sZero();
  1271. }
  1272. // Helper function that finds the CCD body corresponding to a body (if it exists)
  1273. inline static PhysicsUpdateContext::SubStep::CCDBody *sGetCCDBody(const Body &inBody, PhysicsUpdateContext::SubStep *inSubStep)
  1274. {
  1275. // If the body has no motion properties it cannot have a CCD body
  1276. const MotionProperties *motion_properties = inBody.GetMotionPropertiesUnchecked();
  1277. if (motion_properties == nullptr)
  1278. return nullptr;
  1279. // If it is not active it cannot have a CCD body
  1280. uint32 active_index = motion_properties->GetIndexInActiveBodiesInternal();
  1281. if (active_index == Body::cInactiveIndex)
  1282. return nullptr;
  1283. // Check if the active body has a corresponding CCD body
  1284. JPH_ASSERT(active_index < inSubStep->mNumActiveBodyToCCDBody); // Ensure that the body has a mapping to CCD body
  1285. int ccd_index = inSubStep->mActiveBodyToCCDBody[active_index];
  1286. if (ccd_index < 0)
  1287. return nullptr;
  1288. PhysicsUpdateContext::SubStep::CCDBody *ccd_body = &inSubStep->mCCDBodies[ccd_index];
  1289. JPH_ASSERT(ccd_body->mBodyID1 == inBody.GetID(), "We found the wrong CCD body!");
  1290. return ccd_body;
  1291. }
  1292. void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1293. {
  1294. #ifdef JPH_ENABLE_ASSERTS
  1295. // We only read positions, but the validate callback may read body positions and velocities
  1296. BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);
  1297. #endif
  1298. // Allocation context for allocating new contact points
  1299. ContactAllocator contact_allocator(mContactManager.GetContactAllocator());
  1300. // Settings
  1301. ShapeCastSettings settings;
  1302. settings.mUseShrunkenShapeAndConvexRadius = true;
  1303. settings.mBackFaceModeTriangles = EBackFaceMode::IgnoreBackFaces;
  1304. settings.mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;
  1305. settings.mReturnDeepestPoint = true;
  1306. settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;
  1307. settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;
  1308. for (;;)
  1309. {
  1310. // Fetch the next body to cast
  1311. uint32 idx = ioSubStep->mNextCCDBody++;
  1312. if (idx >= ioSubStep->mNumCCDBodies)
  1313. break;
  1314. CCDBody &ccd_body = ioSubStep->mCCDBodies[idx];
  1315. const Body &body = mBodyManager.GetBody(ccd_body.mBodyID1);
  1316. // Filter out layers
  1317. DefaultBroadPhaseLayerFilter broadphase_layer_filter = GetDefaultBroadPhaseLayerFilter(body.GetObjectLayer());
  1318. DefaultObjectLayerFilter object_layer_filter = GetDefaultLayerFilter(body.GetObjectLayer());
  1319. #ifdef JPH_DEBUG_RENDERER
  1320. // Draw start and end shape of cast
  1321. if (sDrawMotionQualityLinearCast)
  1322. {
  1323. Mat44 com = body.GetCenterOfMassTransform();
  1324. body.GetShape()->Draw(DebugRenderer::sInstance, com, Vec3::sReplicate(1.0f), Color::sGreen, false, true);
  1325. DebugRenderer::sInstance->DrawArrow(com.GetTranslation(), com.GetTranslation() + ccd_body.mDeltaPosition, Color::sGreen, 0.1f);
  1326. body.GetShape()->Draw(DebugRenderer::sInstance, Mat44::sTranslation(ccd_body.mDeltaPosition) * com, Vec3::sReplicate(1.0f), Color::sRed, false, true);
  1327. }
  1328. #endif // JPH_DEBUG_RENDERER
  1329. // Create a collector that will find the maximum distance allowed to travel while not penetrating more than 'max penetration'
  1330. class CCDNarrowPhaseCollector : public CastShapeCollector
  1331. {
  1332. public:
  1333. CCDNarrowPhaseCollector(const BodyManager &inBodyManager, ContactConstraintManager &inContactConstraintManager, CCDBody &inCCDBody, ShapeCastResult &inResult, float inDeltaTime) :
  1334. mBodyManager(inBodyManager),
  1335. mContactConstraintManager(inContactConstraintManager),
  1336. mCCDBody(inCCDBody),
  1337. mResult(inResult),
  1338. mDeltaTime(inDeltaTime)
  1339. {
  1340. }
  1341. virtual void AddHit(const ShapeCastResult &inResult) override
  1342. {
  1343. JPH_PROFILE_FUNCTION();
  1344. // Check if this is a possible earlier hit than the one before
  1345. float fraction = inResult.mFraction;
  1346. if (fraction < mCCDBody.mFractionPlusSlop)
  1347. {
  1348. // Normalize normal
  1349. Vec3 normal = inResult.mPenetrationAxis.Normalized();
  1350. // Calculate how much we can add to the fraction to penetrate the collision point by mMaxPenetration.
  1351. // Note that the normal is pointing towards body 2!
  1352. // 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|
  1353. // <=> dist = mMaxPenetration * |delta_pos| / normal . delta_pos
  1354. // Converting to a faction: delta_fraction = dist / |delta_pos| = mLinearCastTreshold / normal . delta_pos
  1355. float denominator = normal.Dot(mCCDBody.mDeltaPosition);
  1356. if (denominator > mCCDBody.mMaxPenetration) // Avoid dividing by zero, if extra hit fraction > 1 there's also no point in continuing
  1357. {
  1358. float fraction_plus_slop = fraction + mCCDBody.mMaxPenetration / denominator;
  1359. if (fraction_plus_slop < mCCDBody.mFractionPlusSlop)
  1360. {
  1361. const Body &body2 = mBodyManager.GetBody(inResult.mBodyID2);
  1362. // Check if we've already accepted all hits from this body
  1363. if (mValidateBodyPair)
  1364. {
  1365. // Validate the contact result
  1366. ValidateResult validate_result = mContactConstraintManager.ValidateContactPoint(mBodyManager.GetBody(mCCDBody.mBodyID1), body2, inResult);
  1367. switch (validate_result)
  1368. {
  1369. case ValidateResult::AcceptContact:
  1370. // Just continue
  1371. break;
  1372. case ValidateResult::AcceptAllContactsForThisBodyPair:
  1373. // Accept this and all following contacts from this body
  1374. mValidateBodyPair = false;
  1375. break;
  1376. case ValidateResult::RejectContact:
  1377. return;
  1378. case ValidateResult::RejectAllContactsForThisBodyPair:
  1379. // Reject this and all following contacts from this body
  1380. mRejectAll = true;
  1381. ForceEarlyOut();
  1382. return;
  1383. }
  1384. }
  1385. // This is the earliest hit so far, store it
  1386. mCCDBody.mContactNormal = normal;
  1387. mCCDBody.mBodyID2 = inResult.mBodyID2;
  1388. mCCDBody.mFraction = fraction;
  1389. mCCDBody.mFractionPlusSlop = fraction_plus_slop;
  1390. mResult = inResult;
  1391. // Result was assuming body 2 is not moving, but it is, so we need to correct for it
  1392. Vec3 movement2 = fraction * sCalculateBodyMotion(body2, mDeltaTime);
  1393. if (!movement2.IsNearZero())
  1394. {
  1395. mResult.mContactPointOn1 += movement2;
  1396. mResult.mContactPointOn2 += movement2;
  1397. for (Vec3 &v : mResult.mShape1Face)
  1398. v += movement2;
  1399. for (Vec3 &v : mResult.mShape2Face)
  1400. v += movement2;
  1401. }
  1402. // Update early out fraction
  1403. CastShapeCollector::UpdateEarlyOutFraction(fraction_plus_slop);
  1404. }
  1405. }
  1406. }
  1407. }
  1408. bool mValidateBodyPair; ///< If we still have to call the ValidateContactPoint for this body pair
  1409. bool mRejectAll; ///< Reject all further contacts between this body pair
  1410. private:
  1411. const BodyManager & mBodyManager;
  1412. ContactConstraintManager & mContactConstraintManager;
  1413. CCDBody & mCCDBody;
  1414. ShapeCastResult & mResult;
  1415. float mDeltaTime;
  1416. BodyID mAcceptedBodyID;
  1417. };
  1418. // Narrowphase collector
  1419. ShapeCastResult cast_shape_result;
  1420. CCDNarrowPhaseCollector np_collector(mBodyManager, mContactManager, ccd_body, cast_shape_result, ioContext->mSubStepDeltaTime);
  1421. // This collector wraps the narrowphase collector and collects the closest hit
  1422. class CCDBroadPhaseCollector : public CastShapeBodyCollector
  1423. {
  1424. public:
  1425. CCDBroadPhaseCollector(const CCDBody &inCCDBody, const Body &inBody1, const ShapeCast &inShapeCast, ShapeCastSettings &inShapeCastSettings, CCDNarrowPhaseCollector &ioCollector, const BodyManager &inBodyManager, PhysicsUpdateContext::SubStep *inSubStep, float inDeltaTime) :
  1426. mCCDBody(inCCDBody),
  1427. mBody1(inBody1),
  1428. mBody1Extent(inShapeCast.mShapeWorldBounds.GetExtent()),
  1429. mShapeCast(inShapeCast),
  1430. mShapeCastSettings(inShapeCastSettings),
  1431. mCollector(ioCollector),
  1432. mBodyManager(inBodyManager),
  1433. mSubStep(inSubStep),
  1434. mDeltaTime(inDeltaTime)
  1435. {
  1436. }
  1437. virtual void AddHit(const BroadPhaseCastResult &inResult) override
  1438. {
  1439. JPH_PROFILE_FUNCTION();
  1440. JPH_ASSERT(inResult.mFraction <= GetEarlyOutFraction(), "This hit should not have been passed on to the collector");
  1441. // Test if we're colliding with ourselves
  1442. if (mBody1.GetID() == inResult.mBodyID)
  1443. return;
  1444. // Avoid treating duplicates, if both bodies are doing CCD then only consider collision if body ID < other body ID
  1445. const Body &body2 = mBodyManager.GetBody(inResult.mBodyID);
  1446. const CCDBody *ccd_body2 = sGetCCDBody(body2, mSubStep);
  1447. if (ccd_body2 != nullptr && mCCDBody.mBodyID1 > ccd_body2->mBodyID1)
  1448. return;
  1449. // Test group filter
  1450. if (!mBody1.GetCollisionGroup().CanCollide(body2.GetCollisionGroup()))
  1451. return;
  1452. // TODO: For now we ignore sensors
  1453. if (body2.IsSensor())
  1454. return;
  1455. // Get relative movement of these two bodies
  1456. Vec3 direction = mShapeCast.mDirection - sCalculateBodyMotion(body2, mDeltaTime);
  1457. // Test if the remaining movement is less than our movement threshold
  1458. if (direction.LengthSq() < mCCDBody.mLinearCastThresholdSq)
  1459. return;
  1460. // 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
  1461. AABox bounds = body2.GetWorldSpaceBounds();
  1462. bounds.mMin -= mBody1Extent;
  1463. bounds.mMax += mBody1Extent;
  1464. float hit_fraction = RayAABox(mShapeCast.mCenterOfMassStart.GetTranslation(), RayInvDirection(direction), bounds.mMin, bounds.mMax);
  1465. if (hit_fraction > max(FLT_MIN, GetEarlyOutFraction())) // If early out fraction <= 0, we have the possibility of finding a deeper hit so we need to clamp the early out fraction
  1466. return;
  1467. // Reset collector (this is a new body pair)
  1468. mCollector.ResetEarlyOutFraction(GetEarlyOutFraction());
  1469. mCollector.mValidateBodyPair = true;
  1470. mCollector.mRejectAll = false;
  1471. // Provide direction as hint for the active edges algorithm
  1472. mShapeCastSettings.mActiveEdgeMovementDirection = direction;
  1473. // Do narrow phase collision check
  1474. ShapeCast relative_cast(mShapeCast.mShape, mShapeCast.mScale, mShapeCast.mCenterOfMassStart, direction, mShapeCast.mShapeWorldBounds);
  1475. body2.GetTransformedShape().CastShape(relative_cast, mShapeCastSettings, mCollector);
  1476. // Update early out fraction based on narrow phase collector
  1477. if (!mCollector.mRejectAll)
  1478. UpdateEarlyOutFraction(mCollector.GetEarlyOutFraction());
  1479. }
  1480. const CCDBody & mCCDBody;
  1481. const Body & mBody1;
  1482. Vec3 mBody1Extent;
  1483. ShapeCast mShapeCast;
  1484. ShapeCastSettings & mShapeCastSettings;
  1485. CCDNarrowPhaseCollector & mCollector;
  1486. const BodyManager & mBodyManager;
  1487. PhysicsUpdateContext::SubStep *mSubStep;
  1488. float mDeltaTime;
  1489. };
  1490. // 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.
  1491. ShapeCast shape_cast(body.GetShape(), Vec3::sReplicate(1.0f), body.GetCenterOfMassTransform(), ccd_body.mDeltaPosition);
  1492. CCDBroadPhaseCollector bp_collector(ccd_body, body, shape_cast, settings, np_collector, mBodyManager, ioSubStep, ioContext->mSubStepDeltaTime);
  1493. mBroadPhase->CastAABoxNoLock({ shape_cast.mShapeWorldBounds, shape_cast.mDirection }, bp_collector, broadphase_layer_filter, object_layer_filter);
  1494. // Check if there was a hit
  1495. if (ccd_body.mFractionPlusSlop < 1.0f)
  1496. {
  1497. const Body &body2 = mBodyManager.GetBody(ccd_body.mBodyID2);
  1498. // Determine contact manifold
  1499. ContactManifold manifold;
  1500. ManifoldBetweenTwoFaces(cast_shape_result.mContactPointOn1, cast_shape_result.mContactPointOn2, cast_shape_result.mPenetrationAxis, mPhysicsSettings.mManifoldToleranceSq, cast_shape_result.mShape1Face, cast_shape_result.mShape2Face, manifold.mWorldSpaceContactPointsOn1, manifold.mWorldSpaceContactPointsOn2);
  1501. manifold.mSubShapeID1 = cast_shape_result.mSubShapeID1;
  1502. manifold.mSubShapeID2 = cast_shape_result.mSubShapeID2;
  1503. manifold.mPenetrationDepth = cast_shape_result.mPenetrationDepth;
  1504. manifold.mWorldSpaceNormal = ccd_body.mContactNormal;
  1505. // Call contact point callbacks
  1506. mContactManager.OnCCDContactAdded(contact_allocator, body, body2, manifold, ccd_body.mContactSettings);
  1507. // Calculate the average position from the manifold (this will result in the same impulse applied as when we apply impulses to all contact points)
  1508. if (manifold.mWorldSpaceContactPointsOn2.size() > 1)
  1509. {
  1510. Vec3 average_contact_point = Vec3::sZero();
  1511. for (const Vec3 &v : manifold.mWorldSpaceContactPointsOn2)
  1512. average_contact_point += v;
  1513. average_contact_point /= (float)manifold.mWorldSpaceContactPointsOn2.size();
  1514. ccd_body.mContactPointOn2 = average_contact_point;
  1515. }
  1516. else
  1517. ccd_body.mContactPointOn2 = cast_shape_result.mContactPointOn2;
  1518. }
  1519. }
  1520. // Atomically accumulate the number of found manifolds and body pairs
  1521. ioSubStep->mStep->mNumBodyPairs += contact_allocator.mNumBodyPairs;
  1522. ioSubStep->mStep->mNumManifolds += contact_allocator.mNumManifolds;
  1523. }
  1524. void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1525. {
  1526. #ifdef JPH_ENABLE_ASSERTS
  1527. // Read/write body access
  1528. BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);
  1529. // We activate bodies that we collide with
  1530. BodyManager::GrantActiveBodiesAccess grant_active(true, false);
  1531. #endif
  1532. uint32 num_active_bodies_after_find_collisions = ioSubStep->mStep->mActiveBodyReadIdx;
  1533. TempAllocator *temp_allocator = ioContext->mTempAllocator;
  1534. // Check if there's anything to do
  1535. uint num_ccd_bodies = ioSubStep->mNumCCDBodies;
  1536. if (num_ccd_bodies > 0)
  1537. {
  1538. // Sort on fraction so that we process earliest collisions first
  1539. // This is needed to make the simulation deterministic and also to be able to stop contact processing
  1540. // between body pairs if an earlier hit was found involving the body by another CCD body
  1541. // (if it's body ID < this CCD body's body ID - see filtering logic in CCDBroadPhaseCollector)
  1542. CCDBody **sorted_ccd_bodies = (CCDBody **)temp_allocator->Allocate(num_ccd_bodies * sizeof(CCDBody *));
  1543. {
  1544. JPH_PROFILE("Sort");
  1545. // We don't want to copy the entire struct (it's quite big), so we create a pointer array first
  1546. CCDBody *src_ccd_bodies = ioSubStep->mCCDBodies;
  1547. CCDBody **dst_ccd_bodies = sorted_ccd_bodies;
  1548. CCDBody **dst_ccd_bodies_end = dst_ccd_bodies + num_ccd_bodies;
  1549. while (dst_ccd_bodies < dst_ccd_bodies_end)
  1550. *(dst_ccd_bodies++) = src_ccd_bodies++;
  1551. // Which we then sort
  1552. QuickSort(sorted_ccd_bodies, sorted_ccd_bodies + num_ccd_bodies, [](const CCDBody *inBody1, const CCDBody *inBody2)
  1553. {
  1554. if (inBody1->mFractionPlusSlop != inBody2->mFractionPlusSlop)
  1555. return inBody1->mFractionPlusSlop < inBody2->mFractionPlusSlop;
  1556. return inBody1->mBodyID1 < inBody2->mBodyID1;
  1557. });
  1558. }
  1559. // We can collide with bodies that are not active, we track them here so we can activate them in one go at the end.
  1560. // This is also needed because we can't modify the active body array while we iterate it.
  1561. static constexpr int cBodiesBatch = 64;
  1562. BodyID *bodies_to_activate = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1563. int num_bodies_to_activate = 0;
  1564. // We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.
  1565. BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));
  1566. int num_bodies_to_update_bounds = 0;
  1567. for (uint i = 0; i < num_ccd_bodies; ++i)
  1568. {
  1569. const CCDBody *ccd_body = sorted_ccd_bodies[i];
  1570. Body &body1 = mBodyManager.GetBody(ccd_body->mBodyID1);
  1571. MotionProperties *body_mp = body1.GetMotionProperties();
  1572. // If there was a hit
  1573. if (!ccd_body->mBodyID2.IsInvalid())
  1574. {
  1575. Body &body2 = mBodyManager.GetBody(ccd_body->mBodyID2);
  1576. // Determine if the other body has a CCD body
  1577. CCDBody *ccd_body2 = sGetCCDBody(body2, ioSubStep);
  1578. if (ccd_body2 != nullptr)
  1579. {
  1580. JPH_ASSERT(ccd_body2->mBodyID2 != ccd_body->mBodyID1, "If we collided with another body, that other body should have ignored collisions with us!");
  1581. // Check if the other body found a hit that is further away
  1582. if (ccd_body2->mFraction > ccd_body->mFraction)
  1583. {
  1584. // Reset the colliding body of the other CCD body. The other body will shorten its distance travelled and will not do any collision response (we'll do that).
  1585. // This means that at this point we have triggered a contact point add/persist for our further hit by accident for the other body.
  1586. // 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.
  1587. ccd_body2->mBodyID2 = BodyID();
  1588. ccd_body2->mFractionPlusSlop = ccd_body->mFraction;
  1589. }
  1590. }
  1591. // 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.
  1592. // 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.
  1593. if (ccd_body2 == nullptr || ccd_body2->mFraction >= ccd_body->mFraction)
  1594. {
  1595. // Calculate contact points relative to center of mass of both bodies
  1596. Vec3 r1_plus_u = ccd_body->mContactPointOn2 - (body1.GetCenterOfMassPosition() + ccd_body->mFraction * ccd_body->mDeltaPosition);
  1597. Vec3 r2 = ccd_body->mContactPointOn2 - body2.GetCenterOfMassPosition();
  1598. // Calculate velocity of collision points
  1599. Vec3 v1 = body1.GetPointVelocityCOM(r1_plus_u);
  1600. Vec3 v2 = body2.GetPointVelocityCOM(r2);
  1601. Vec3 relative_velocity = v2 - v1;
  1602. float normal_velocity = relative_velocity.Dot(ccd_body->mContactNormal);
  1603. // Calculate velocity bias due to restitution
  1604. float normal_velocity_bias;
  1605. if (ccd_body->mContactSettings.mCombinedRestitution > 0.0f && normal_velocity < -mPhysicsSettings.mMinVelocityForRestitution)
  1606. normal_velocity_bias = ccd_body->mContactSettings.mCombinedRestitution * normal_velocity;
  1607. else
  1608. normal_velocity_bias = 0.0f;
  1609. // Solve contact constraint
  1610. AxisConstraintPart contact_constraint;
  1611. contact_constraint.CalculateConstraintProperties(ioContext->mSubStepDeltaTime, body1, r1_plus_u, body2, r2, ccd_body->mContactNormal, normal_velocity_bias);
  1612. contact_constraint.SolveVelocityConstraint(body1, body2, ccd_body->mContactNormal, -FLT_MAX, FLT_MAX);
  1613. // Apply friction
  1614. if (ccd_body->mContactSettings.mCombinedFriction > 0.0f)
  1615. {
  1616. Vec3 tangent1 = ccd_body->mContactNormal.GetNormalizedPerpendicular();
  1617. Vec3 tangent2 = ccd_body->mContactNormal.Cross(tangent1);
  1618. float max_lambda_f = ccd_body->mContactSettings.mCombinedFriction * contact_constraint.GetTotalLambda();
  1619. AxisConstraintPart friction1;
  1620. friction1.CalculateConstraintProperties(ioContext->mSubStepDeltaTime, body1, r1_plus_u, body2, r2, tangent1, 0.0f);
  1621. friction1.SolveVelocityConstraint(body1, body2, tangent1, -max_lambda_f, max_lambda_f);
  1622. AxisConstraintPart friction2;
  1623. friction2.CalculateConstraintProperties(ioContext->mSubStepDeltaTime, body1, r1_plus_u, body2, r2, tangent2, 0.0f);
  1624. friction2.SolveVelocityConstraint(body1, body2, tangent2, -max_lambda_f, max_lambda_f);
  1625. }
  1626. // Clamp velocities
  1627. body_mp->ClampLinearVelocity();
  1628. body_mp->ClampAngularVelocity();
  1629. if (body2.IsDynamic())
  1630. {
  1631. MotionProperties *body2_mp = body2.GetMotionProperties();
  1632. body2_mp->ClampLinearVelocity();
  1633. body2_mp->ClampAngularVelocity();
  1634. // Activate the body if it is not already active
  1635. if (!body2.IsActive())
  1636. {
  1637. bodies_to_activate[num_bodies_to_activate++] = ccd_body->mBodyID2;
  1638. if (num_bodies_to_activate == cBodiesBatch)
  1639. {
  1640. // Batch is full, activate now
  1641. mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);
  1642. num_bodies_to_activate = 0;
  1643. }
  1644. }
  1645. }
  1646. #ifdef JPH_DEBUG_RENDERER
  1647. if (sDrawMotionQualityLinearCast)
  1648. {
  1649. // Draw the collision location
  1650. Mat44 collision_transform = Mat44::sTranslation(ccd_body->mFraction * ccd_body->mDeltaPosition) * body1.GetCenterOfMassTransform();
  1651. body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform, Vec3::sReplicate(1.0f), Color::sYellow, false, true);
  1652. // Draw the collision location + slop
  1653. Mat44 collision_transform_plus_slop = Mat44::sTranslation(ccd_body->mFractionPlusSlop * ccd_body->mDeltaPosition) * body1.GetCenterOfMassTransform();
  1654. body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform_plus_slop, Vec3::sReplicate(1.0f), Color::sOrange, false, true);
  1655. // Draw contact normal
  1656. DebugRenderer::sInstance->DrawArrow(ccd_body->mContactPointOn2, ccd_body->mContactPointOn2 - ccd_body->mContactNormal, Color::sYellow, 0.1f);
  1657. // Draw post contact velocity
  1658. DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetLinearVelocity(), Color::sOrange, 0.1f);
  1659. DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetAngularVelocity(), Color::sPurple, 0.1f);
  1660. }
  1661. #endif // JPH_DEBUG_RENDERER
  1662. }
  1663. }
  1664. // Update body position
  1665. body1.AddPositionStep(ccd_body->mDeltaPosition * ccd_body->mFractionPlusSlop);
  1666. // If the body was activated due to an earlier CCD step it will have an index in the active
  1667. // body list that it higher than the highest one we processed during FindCollisions
  1668. // which means it hasn't been assigned an island and will not be updated by an island
  1669. // this means that we need to update its bounds manually
  1670. if (body_mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)
  1671. {
  1672. body1.CalculateWorldSpaceBoundsInternal();
  1673. bodies_to_update_bounds[num_bodies_to_update_bounds++] = body1.GetID();
  1674. if (num_bodies_to_update_bounds == cBodiesBatch)
  1675. {
  1676. // Buffer full, flush now
  1677. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds);
  1678. num_bodies_to_update_bounds = 0;
  1679. }
  1680. }
  1681. }
  1682. // Activate the requested bodies
  1683. if (num_bodies_to_activate > 0)
  1684. mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);
  1685. // Notify change bounds on requested bodies
  1686. if (num_bodies_to_update_bounds > 0)
  1687. mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);
  1688. // Free the sorted ccd bodies
  1689. temp_allocator->Free(sorted_ccd_bodies, num_ccd_bodies * sizeof(CCDBody *));
  1690. }
  1691. // Ensure we free the CCD bodies array now, will not call the destructor!
  1692. temp_allocator->Free(ioSubStep->mActiveBodyToCCDBody, ioSubStep->mNumActiveBodyToCCDBody * sizeof(int));
  1693. ioSubStep->mActiveBodyToCCDBody = nullptr;
  1694. ioSubStep->mNumActiveBodyToCCDBody = 0;
  1695. temp_allocator->Free(ioSubStep->mCCDBodies, ioSubStep->mCCDBodiesCapacity * sizeof(CCDBody));
  1696. ioSubStep->mCCDBodies = nullptr;
  1697. ioSubStep->mCCDBodiesCapacity = 0;
  1698. }
  1699. void PhysicsSystem::JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep)
  1700. {
  1701. #ifdef JPH_ENABLE_ASSERTS
  1702. // We don't touch any bodies
  1703. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);
  1704. #endif
  1705. // Reset the Body::EFlags::InvalidateContactCache flag for all bodies
  1706. mBodyManager.ValidateContactCacheForAllBodies();
  1707. // Trigger all contact removed callbacks by looking at last step contact points that have not been flagged as reused
  1708. mContactManager.ContactPointRemovedCallbacks();
  1709. // Finalize the contact cache (this swaps the read and write versions of the contact cache)
  1710. mContactManager.FinalizeContactCache(ioStep->mNumBodyPairs, ioStep->mNumManifolds);
  1711. }
  1712. void PhysicsSystem::JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::SubStep *ioSubStep)
  1713. {
  1714. #ifdef JPH_ENABLE_ASSERTS
  1715. // We fix up position errors
  1716. BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::ReadWrite);
  1717. // Can only deactivate bodies
  1718. BodyManager::GrantActiveBodiesAccess grant_active(false, true);
  1719. #endif
  1720. float delta_time = ioContext->mSubStepDeltaTime;
  1721. Constraint **active_constraints = ioContext->mActiveConstraints;
  1722. for (;;)
  1723. {
  1724. // Next island
  1725. uint32 island_idx = ioSubStep->mSolvePositionConstraintsNextIsland++;
  1726. if (island_idx >= mIslandBuilder.GetNumIslands())
  1727. break;
  1728. JPH_PROFILE("Island");
  1729. // Get iterators for this island
  1730. BodyID *bodies_begin, *bodies_end;
  1731. mIslandBuilder.GetBodiesInIsland(island_idx, bodies_begin, bodies_end);
  1732. uint32 *constraints_begin, *constraints_end;
  1733. bool has_constraints = mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);
  1734. uint32 *contacts_begin, *contacts_end;
  1735. bool has_contacts = mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);
  1736. // Correct positions
  1737. if (has_contacts || has_constraints)
  1738. {
  1739. float baumgarte = mPhysicsSettings.mBaumgarte;
  1740. for (int position_step = 0; position_step < mPhysicsSettings.mNumPositionSteps; ++position_step)
  1741. {
  1742. bool constraint_impulse = ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);
  1743. bool contact_impulse = mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);
  1744. if (!constraint_impulse && !contact_impulse)
  1745. break;
  1746. }
  1747. }
  1748. // Only check sleeping in the last sub step of the last step
  1749. // Also resets force and torque used during the apply gravity phase
  1750. if (ioSubStep->mIsLastOfAll)
  1751. {
  1752. JPH_PROFILE("Check Sleeping");
  1753. static_assert(int(Body::ECanSleep::CannotSleep) == 0 && int(Body::ECanSleep::CanSleep) == 1, "Loop below makes this assumption");
  1754. int all_can_sleep = mPhysicsSettings.mAllowSleeping? int(Body::ECanSleep::CanSleep) : int(Body::ECanSleep::CannotSleep);
  1755. float time_before_sleep = mPhysicsSettings.mTimeBeforeSleep;
  1756. float max_movement = mPhysicsSettings.mPointVelocitySleepThreshold * time_before_sleep;
  1757. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1758. {
  1759. Body &body = mBodyManager.GetBody(*body_id);
  1760. // Update bounding box
  1761. body.CalculateWorldSpaceBoundsInternal();
  1762. // Update sleeping
  1763. all_can_sleep &= int(body.UpdateSleepStateInternal(ioContext->mSubStepDeltaTime, max_movement, time_before_sleep));
  1764. // Reset force and torque
  1765. body.GetMotionProperties()->ResetForceAndTorqueInternal();
  1766. }
  1767. // If all bodies indicate they can sleep we can deactivate them
  1768. if (all_can_sleep == int(Body::ECanSleep::CanSleep))
  1769. mBodyManager.DeactivateBodies(bodies_begin, int(bodies_end - bodies_begin));
  1770. }
  1771. else
  1772. {
  1773. JPH_PROFILE("Update Bounds");
  1774. // Update bounding box only for all other sub steps
  1775. for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)
  1776. {
  1777. Body &body = mBodyManager.GetBody(*body_id);
  1778. body.CalculateWorldSpaceBoundsInternal();
  1779. }
  1780. }
  1781. // Notify broadphase of changed objects (find ccd contacts can do linear casts in the next step, so
  1782. // we need to do this every sub step)
  1783. // Note: Shuffles the BodyID's around!!!
  1784. mBroadPhase->NotifyBodiesAABBChanged(bodies_begin, int(bodies_end - bodies_begin), false);
  1785. }
  1786. }
  1787. void PhysicsSystem::SaveState(StateRecorder &inStream) const
  1788. {
  1789. JPH_PROFILE_FUNCTION();
  1790. inStream.Write(mPreviousSubStepDeltaTime);
  1791. inStream.Write(mGravity);
  1792. mBodyManager.SaveState(inStream);
  1793. mContactManager.SaveState(inStream);
  1794. mConstraintManager.SaveState(inStream);
  1795. }
  1796. bool PhysicsSystem::RestoreState(StateRecorder &inStream)
  1797. {
  1798. JPH_PROFILE_FUNCTION();
  1799. inStream.Read(mPreviousSubStepDeltaTime);
  1800. inStream.Read(mGravity);
  1801. if (!mBodyManager.RestoreState(inStream))
  1802. return false;
  1803. if (!mContactManager.RestoreState(inStream))
  1804. return false;
  1805. if (!mConstraintManager.RestoreState(inStream))
  1806. return false;
  1807. // Update bounding boxes for all bodies in the broadphase
  1808. Array<BodyID> bodies;
  1809. for (const Body *b : mBodyManager.GetBodies())
  1810. if (BodyManager::sIsValidBodyPointer(b) && b->IsInBroadPhase())
  1811. bodies.push_back(b->GetID());
  1812. if (!bodies.empty())
  1813. mBroadPhase->NotifyBodiesAABBChanged(&bodies[0], (int)bodies.size());
  1814. return true;
  1815. }
  1816. JPH_NAMESPACE_END