PhysicsSystem.cpp 92 KB

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