PhysicsSystem.cpp 95 KB

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