PhysicsSystem.cpp 93 KB

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