PhysicsSystem.cpp 117 KB

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