PhysicsSystem.cpp 96 KB

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