Path: blob/master/thirdparty/jolt_physics/Jolt/Physics/PhysicsSystem.cpp
9906 views
// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)1// SPDX-FileCopyrightText: 2021 Jorrit Rouwe2// SPDX-License-Identifier: MIT34#include <Jolt/Jolt.h>56#include <Jolt/Physics/PhysicsSystem.h>7#include <Jolt/Physics/PhysicsSettings.h>8#include <Jolt/Physics/PhysicsUpdateContext.h>9#include <Jolt/Physics/PhysicsStepListener.h>10#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseBruteForce.h>11#include <Jolt/Physics/Collision/BroadPhase/BroadPhaseQuadTree.h>12#include <Jolt/Physics/Collision/CollisionDispatch.h>13#include <Jolt/Physics/Collision/AABoxCast.h>14#include <Jolt/Physics/Collision/ShapeCast.h>15#include <Jolt/Physics/Collision/CollideShape.h>16#include <Jolt/Physics/Collision/CollisionCollectorImpl.h>17#include <Jolt/Physics/Collision/CastResult.h>18#include <Jolt/Physics/Collision/CollideConvexVsTriangles.h>19#include <Jolt/Physics/Collision/ManifoldBetweenTwoFaces.h>20#include <Jolt/Physics/Collision/Shape/ConvexShape.h>21#include <Jolt/Physics/Collision/SimShapeFilterWrapper.h>22#include <Jolt/Physics/Collision/InternalEdgeRemovingCollector.h>23#include <Jolt/Physics/Constraints/CalculateSolverSteps.h>24#include <Jolt/Physics/Constraints/ConstraintPart/AxisConstraintPart.h>25#include <Jolt/Physics/DeterminismLog.h>26#include <Jolt/Physics/SoftBody/SoftBodyMotionProperties.h>27#include <Jolt/Physics/SoftBody/SoftBodyShape.h>28#include <Jolt/Geometry/RayAABox.h>29#include <Jolt/Geometry/ClosestPoint.h>30#include <Jolt/Core/JobSystem.h>31#include <Jolt/Core/TempAllocator.h>32#include <Jolt/Core/QuickSort.h>33#include <Jolt/Core/ScopeExit.h>34#ifdef JPH_DEBUG_RENDERER35#include <Jolt/Renderer/DebugRenderer.h>36#endif // JPH_DEBUG_RENDERER3738JPH_NAMESPACE_BEGIN3940#ifdef JPH_DEBUG_RENDERER41bool PhysicsSystem::sDrawMotionQualityLinearCast = false;42#endif // JPH_DEBUG_RENDERER4344//#define BROAD_PHASE BroadPhaseBruteForce45#define BROAD_PHASE BroadPhaseQuadTree4647static const Color cColorUpdateBroadPhaseFinalize = Color::sGetDistinctColor(1);48static const Color cColorUpdateBroadPhasePrepare = Color::sGetDistinctColor(2);49static const Color cColorFindCollisions = Color::sGetDistinctColor(3);50static const Color cColorApplyGravity = Color::sGetDistinctColor(4);51static const Color cColorSetupVelocityConstraints = Color::sGetDistinctColor(5);52static const Color cColorBuildIslandsFromConstraints = Color::sGetDistinctColor(6);53static const Color cColorDetermineActiveConstraints = Color::sGetDistinctColor(7);54static const Color cColorFinalizeIslands = Color::sGetDistinctColor(8);55static const Color cColorContactRemovedCallbacks = Color::sGetDistinctColor(9);56static const Color cColorBodySetIslandIndex = Color::sGetDistinctColor(10);57static const Color cColorStartNextStep = Color::sGetDistinctColor(11);58static const Color cColorSolveVelocityConstraints = Color::sGetDistinctColor(12);59static const Color cColorPreIntegrateVelocity = Color::sGetDistinctColor(13);60static const Color cColorIntegrateVelocity = Color::sGetDistinctColor(14);61static const Color cColorPostIntegrateVelocity = Color::sGetDistinctColor(15);62static const Color cColorResolveCCDContacts = Color::sGetDistinctColor(16);63static const Color cColorSolvePositionConstraints = Color::sGetDistinctColor(17);64static const Color cColorFindCCDContacts = Color::sGetDistinctColor(18);65static const Color cColorStepListeners = Color::sGetDistinctColor(19);66static const Color cColorSoftBodyPrepare = Color::sGetDistinctColor(20);67static const Color cColorSoftBodyCollide = Color::sGetDistinctColor(21);68static const Color cColorSoftBodySimulate = Color::sGetDistinctColor(22);69static const Color cColorSoftBodyFinalize = Color::sGetDistinctColor(23);7071PhysicsSystem::~PhysicsSystem()72{73// Remove broadphase74delete mBroadPhase;75}7677void PhysicsSystem::Init(uint inMaxBodies, uint inNumBodyMutexes, uint inMaxBodyPairs, uint inMaxContactConstraints, const BroadPhaseLayerInterface &inBroadPhaseLayerInterface, const ObjectVsBroadPhaseLayerFilter &inObjectVsBroadPhaseLayerFilter, const ObjectLayerPairFilter &inObjectLayerPairFilter)78{79// Clamp max bodies80uint max_bodies = min(inMaxBodies, cMaxBodiesLimit);81JPH_ASSERT(max_bodies == inMaxBodies, "Cannot support this many bodies!");8283mObjectVsBroadPhaseLayerFilter = &inObjectVsBroadPhaseLayerFilter;84mObjectLayerPairFilter = &inObjectLayerPairFilter;8586// Initialize body manager87mBodyManager.Init(max_bodies, inNumBodyMutexes, inBroadPhaseLayerInterface);8889// Create broadphase90mBroadPhase = new BROAD_PHASE();91mBroadPhase->Init(&mBodyManager, inBroadPhaseLayerInterface);9293// Init contact constraint manager94mContactManager.Init(inMaxBodyPairs, inMaxContactConstraints);9596// Init islands builder97mIslandBuilder.Init(max_bodies);9899// Initialize body interface100mBodyInterfaceLocking.Init(mBodyLockInterfaceLocking, mBodyManager, *mBroadPhase);101mBodyInterfaceNoLock.Init(mBodyLockInterfaceNoLock, mBodyManager, *mBroadPhase);102103// Initialize narrow phase query104mNarrowPhaseQueryLocking.Init(mBodyLockInterfaceLocking, *mBroadPhase);105mNarrowPhaseQueryNoLock.Init(mBodyLockInterfaceNoLock, *mBroadPhase);106}107108void PhysicsSystem::OptimizeBroadPhase()109{110mBroadPhase->Optimize();111}112113void PhysicsSystem::AddStepListener(PhysicsStepListener *inListener)114{115lock_guard lock(mStepListenersMutex);116117JPH_ASSERT(std::find(mStepListeners.begin(), mStepListeners.end(), inListener) == mStepListeners.end());118mStepListeners.push_back(inListener);119}120121void PhysicsSystem::RemoveStepListener(PhysicsStepListener *inListener)122{123lock_guard lock(mStepListenersMutex);124125StepListeners::iterator i = std::find(mStepListeners.begin(), mStepListeners.end(), inListener);126JPH_ASSERT(i != mStepListeners.end());127*i = mStepListeners.back();128mStepListeners.pop_back();129}130131EPhysicsUpdateError PhysicsSystem::Update(float inDeltaTime, int inCollisionSteps, TempAllocator *inTempAllocator, JobSystem *inJobSystem)132{133JPH_PROFILE_FUNCTION();134135JPH_DET_LOG("PhysicsSystem::Update: dt: " << inDeltaTime << " steps: " << inCollisionSteps);136137JPH_ASSERT(inCollisionSteps > 0);138JPH_ASSERT(inDeltaTime >= 0.0f);139140// Sync point for the broadphase. This will allow it to do clean up operations without having any mutexes locked yet.141mBroadPhase->FrameSync();142143// If there are no active bodies (and no step listener to wake them up) or there's no time delta144uint32 num_active_rigid_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);145uint32 num_active_soft_bodies = mBodyManager.GetNumActiveBodies(EBodyType::SoftBody);146if ((num_active_rigid_bodies == 0 && num_active_soft_bodies == 0 && mStepListeners.empty()) || inDeltaTime <= 0.0f)147{148mBodyManager.LockAllBodies();149150// Update broadphase151mBroadPhase->LockModifications();152BroadPhase::UpdateState update_state = mBroadPhase->UpdatePrepare();153mBroadPhase->UpdateFinalize(update_state);154mBroadPhase->UnlockModifications();155156// If time has passed, call contact removal callbacks from contacts that existed in the previous update157if (inDeltaTime > 0.0f)158mContactManager.FinalizeContactCacheAndCallContactPointRemovedCallbacks(0, 0);159160mBodyManager.UnlockAllBodies();161return EPhysicsUpdateError::None;162}163164// Calculate ratio between current and previous frame delta time to scale initial constraint forces165float step_delta_time = inDeltaTime / inCollisionSteps;166float warm_start_impulse_ratio = mPhysicsSettings.mConstraintWarmStart && mPreviousStepDeltaTime > 0.0f? step_delta_time / mPreviousStepDeltaTime : 0.0f;167mPreviousStepDeltaTime = step_delta_time;168169// Create the context used for passing information between jobs170PhysicsUpdateContext context(*inTempAllocator);171context.mPhysicsSystem = this;172context.mJobSystem = inJobSystem;173context.mBarrier = inJobSystem->CreateBarrier();174context.mIslandBuilder = &mIslandBuilder;175context.mStepDeltaTime = step_delta_time;176context.mWarmStartImpulseRatio = warm_start_impulse_ratio;177context.mSteps.resize(inCollisionSteps);178179// Allocate space for body pairs180JPH_ASSERT(context.mBodyPairs == nullptr);181context.mBodyPairs = static_cast<BodyPair *>(inTempAllocator->Allocate(sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs));182183// Lock all bodies for write so that we can freely touch them184mStepListenersMutex.lock();185mBodyManager.LockAllBodies();186mBroadPhase->LockModifications();187188// Get max number of concurrent jobs189int max_concurrency = context.GetMaxConcurrency();190191// Calculate how many step listener jobs we spawn192int num_step_listener_jobs = mStepListeners.empty()? 0 : max(1, min((int)mStepListeners.size() / mPhysicsSettings.mStepListenersBatchSize / mPhysicsSettings.mStepListenerBatchesPerJob, max_concurrency));193194// Number of gravity jobs depends on the amount of active bodies.195// Launch max 1 job per batch of active bodies196// Leave 1 thread for update broadphase prepare and 1 for determine active constraints197int num_apply_gravity_jobs = max(1, min(((int)num_active_rigid_bodies + cApplyGravityBatchSize - 1) / cApplyGravityBatchSize, max_concurrency - 2));198199// Number of determine active constraints jobs to run depends on number of constraints.200// Leave 1 thread for update broadphase prepare and 1 for apply gravity201int num_determine_active_constraints_jobs = max(1, min(((int)mConstraintManager.GetNumConstraints() + cDetermineActiveConstraintsBatchSize - 1) / cDetermineActiveConstraintsBatchSize, max_concurrency - 2));202203// Number of setup velocity constraints jobs to run depends on number of constraints.204int num_setup_velocity_constraints_jobs = max(1, min(((int)mConstraintManager.GetNumConstraints() + cSetupVelocityConstraintsBatchSize - 1) / cSetupVelocityConstraintsBatchSize, max_concurrency));205206// Number of find collisions jobs to run depends on number of active bodies.207// 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 constraints208// (which may activate additional bodies that need to be processed) while the second job can start processing collision work.209int num_find_collisions_jobs = max(max_concurrency == 1? 1 : 2, min(((int)num_active_rigid_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_concurrency));210211// Number of integrate velocity jobs depends on number of active bodies.212int num_integrate_velocity_jobs = max(1, min(((int)num_active_rigid_bodies + cIntegrateVelocityBatchSize - 1) / cIntegrateVelocityBatchSize, max_concurrency));213214{215JPH_PROFILE("Build Jobs");216217// Iterate over collision steps218for (int step_idx = 0; step_idx < inCollisionSteps; ++step_idx)219{220bool is_first_step = step_idx == 0;221bool is_last_step = step_idx == inCollisionSteps - 1;222223PhysicsUpdateContext::Step &step = context.mSteps[step_idx];224step.mContext = &context;225step.mIsFirst = is_first_step;226step.mIsLast = is_last_step;227228// Create job to do broadphase finalization229// This job must finish before integrating velocities. Until then the positions will not be updated neither will bodies be added / removed.230step.mUpdateBroadphaseFinalize = inJobSystem->CreateJob("UpdateBroadPhaseFinalize", cColorUpdateBroadPhaseFinalize, [&context, &step]()231{232// Validate that all find collision jobs have stopped233JPH_ASSERT(step.mActiveFindCollisionJobs.load(memory_order_relaxed) == 0);234235// Finalize the broadphase update236context.mPhysicsSystem->mBroadPhase->UpdateFinalize(step.mBroadPhaseUpdateState);237238// Signal that it is done239step.mPreIntegrateVelocity.RemoveDependency();240}, num_find_collisions_jobs + 2); // depends on: find collisions, broadphase prepare update, finish building jobs241242// The immediate jobs below are only immediate for the first step, the all finished job will kick them for the next step243int previous_step_dependency_count = is_first_step? 0 : 1;244245// Start job immediately: Start the prepare broadphase246// Must be done under body lock protection since the order is body locks then broadphase mutex247// If this is turned around the RemoveBody call will hang since it locks in that order248step.mBroadPhasePrepare = inJobSystem->CreateJob("UpdateBroadPhasePrepare", cColorUpdateBroadPhasePrepare, [&context, &step]()249{250// Prepare the broadphase update251step.mBroadPhaseUpdateState = context.mPhysicsSystem->mBroadPhase->UpdatePrepare();252253// Now the finalize can run (if other dependencies are met too)254step.mUpdateBroadphaseFinalize.RemoveDependency();255}, previous_step_dependency_count);256257// This job will find all collisions258step.mBodyPairQueues.resize(max_concurrency);259step.mMaxBodyPairsPerQueue = mPhysicsSettings.mMaxInFlightBodyPairs / max_concurrency;260step.mActiveFindCollisionJobs.store(~PhysicsUpdateContext::JobMask(0) >> (sizeof(PhysicsUpdateContext::JobMask) * 8 - num_find_collisions_jobs), memory_order_release);261step.mFindCollisions.resize(num_find_collisions_jobs);262for (int i = 0; i < num_find_collisions_jobs; ++i)263{264// 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 bodies265int num_dep_build_islands_from_constraints = i == 0? 1 : 0;266step.mFindCollisions[i] = inJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [&step, i]()267{268step.mContext->mPhysicsSystem->JobFindCollisions(&step, i);269}, 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 constraints270}271272if (is_first_step)273{274#ifdef JPH_ENABLE_ASSERTS275// Don't allow write operations to the active bodies list276mBodyManager.SetActiveBodiesLocked(true);277#endif278279// Store the number of active bodies at the start of the step280step.mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);281282// Lock all constraints283mConstraintManager.LockAllConstraints();284285// Allocate memory for storing the active constraints286JPH_ASSERT(context.mActiveConstraints == nullptr);287context.mActiveConstraints = static_cast<Constraint **>(inTempAllocator->Allocate(mConstraintManager.GetNumConstraints() * sizeof(Constraint *)));288289// Prepare contact buffer290mContactManager.PrepareConstraintBuffer(&context);291292// Setup island builder293mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), context.mTempAllocator);294}295296// This job applies gravity to all active bodies297step.mApplyGravity.resize(num_apply_gravity_jobs);298for (int i = 0; i < num_apply_gravity_jobs; ++i)299step.mApplyGravity[i] = inJobSystem->CreateJob("ApplyGravity", cColorApplyGravity, [&context, &step]()300{301context.mPhysicsSystem->JobApplyGravity(&context, &step);302303JobHandle::sRemoveDependencies(step.mFindCollisions);304}, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)305306// This job will setup velocity constraints for non-collision constraints307step.mSetupVelocityConstraints.resize(num_setup_velocity_constraints_jobs);308for (int i = 0; i < num_setup_velocity_constraints_jobs; ++i)309step.mSetupVelocityConstraints[i] = inJobSystem->CreateJob("SetupVelocityConstraints", cColorSetupVelocityConstraints, [&context, &step]()310{311context.mPhysicsSystem->JobSetupVelocityConstraints(context.mStepDeltaTime, &step);312313JobHandle::sRemoveDependencies(step.mSolveVelocityConstraints);314}, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs315316// This job will build islands from constraints317step.mBuildIslandsFromConstraints = inJobSystem->CreateJob("BuildIslandsFromConstraints", cColorBuildIslandsFromConstraints, [&context, &step]()318{319context.mPhysicsSystem->JobBuildIslandsFromConstraints(&context, &step);320321step.mFindCollisions[0].RemoveDependency(); // The first collisions job cannot start running until we've finished building islands and activated all bodies322step.mFinalizeIslands.RemoveDependency();323}, num_determine_active_constraints_jobs + 1); // depends on: determine active constraints, finish building jobs324325// This job determines active constraints326step.mDetermineActiveConstraints.resize(num_determine_active_constraints_jobs);327for (int i = 0; i < num_determine_active_constraints_jobs; ++i)328step.mDetermineActiveConstraints[i] = inJobSystem->CreateJob("DetermineActiveConstraints", cColorDetermineActiveConstraints, [&context, &step]()329{330context.mPhysicsSystem->JobDetermineActiveConstraints(&step);331332step.mBuildIslandsFromConstraints.RemoveDependency();333334// Kick these jobs last as they will use up all CPU cores leaving no space for the previous job, we prefer setup velocity constraints to finish first so we kick it first335JobHandle::sRemoveDependencies(step.mSetupVelocityConstraints);336JobHandle::sRemoveDependencies(step.mFindCollisions);337}, num_step_listener_jobs > 0? num_step_listener_jobs : previous_step_dependency_count); // depends on: step listeners (or previous step if no step listeners)338339// This job calls the step listeners340step.mStepListeners.resize(num_step_listener_jobs);341for (int i = 0; i < num_step_listener_jobs; ++i)342step.mStepListeners[i] = inJobSystem->CreateJob("StepListeners", cColorStepListeners, [&context, &step]()343{344// Call the step listeners345context.mPhysicsSystem->JobStepListeners(&step);346347// Kick apply gravity and determine active constraint jobs348JobHandle::sRemoveDependencies(step.mApplyGravity);349JobHandle::sRemoveDependencies(step.mDetermineActiveConstraints);350}, previous_step_dependency_count);351352// Unblock the previous step353if (!is_first_step)354context.mSteps[step_idx - 1].mStartNextStep.RemoveDependency();355356// This job will finalize the simulation islands357step.mFinalizeIslands = inJobSystem->CreateJob("FinalizeIslands", cColorFinalizeIslands, [&context, &step]()358{359// Validate that all find collision jobs have stopped360JPH_ASSERT(step.mActiveFindCollisionJobs.load(memory_order_relaxed) == 0);361362context.mPhysicsSystem->JobFinalizeIslands(&context);363364JobHandle::sRemoveDependencies(step.mSolveVelocityConstraints);365step.mBodySetIslandIndex.RemoveDependency();366}, num_find_collisions_jobs + 2); // depends on: find collisions, build islands from constraints, finish building jobs367368// Unblock previous job369// 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 left370step.mBuildIslandsFromConstraints.RemoveDependency();371372// This job will call the contact removed callbacks373step.mContactRemovedCallbacks = inJobSystem->CreateJob("ContactRemovedCallbacks", cColorContactRemovedCallbacks, [&context, &step]()374{375context.mPhysicsSystem->JobContactRemovedCallbacks(&step);376377if (step.mStartNextStep.IsValid())378step.mStartNextStep.RemoveDependency();379}, 1); // depends on the find ccd contacts380381// This job will set the island index on each body (only used for debug drawing purposes)382// It will also delete any bodies that have been destroyed in the last frame383step.mBodySetIslandIndex = inJobSystem->CreateJob("BodySetIslandIndex", cColorBodySetIslandIndex, [&context, &step]()384{385context.mPhysicsSystem->JobBodySetIslandIndex();386387JobHandle::sRemoveDependencies(step.mSolvePositionConstraints);388}, 2); // depends on: finalize islands, finish building jobs389390// Job to start the next collision step391if (!is_last_step)392{393PhysicsUpdateContext::Step *next_step = &context.mSteps[step_idx + 1];394step.mStartNextStep = inJobSystem->CreateJob("StartNextStep", cColorStartNextStep, [this, next_step]()395{396#ifdef JPH_DEBUG397// Validate that the cached bounds are correct398mBodyManager.ValidateActiveBodyBounds();399#endif // JPH_DEBUG400401// Store the number of active bodies at the start of the step402next_step->mNumActiveBodiesAtStepStart = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);403404// Clear the large island splitter405TempAllocator *temp_allocator = next_step->mContext->mTempAllocator;406mLargeIslandSplitter.Reset(temp_allocator);407408// Clear the island builder409mIslandBuilder.ResetIslands(temp_allocator);410411// Setup island builder412mIslandBuilder.PrepareContactConstraints(mContactManager.GetMaxConstraints(), temp_allocator);413414// Restart the contact manager415mContactManager.RecycleConstraintBuffer();416417// Kick the jobs of the next step (in the same order as the first step)418next_step->mBroadPhasePrepare.RemoveDependency();419if (next_step->mStepListeners.empty())420{421// Kick the gravity and active constraints jobs immediately422JobHandle::sRemoveDependencies(next_step->mApplyGravity);423JobHandle::sRemoveDependencies(next_step->mDetermineActiveConstraints);424}425else426{427// Kick the step listeners job first428JobHandle::sRemoveDependencies(next_step->mStepListeners);429}430}, 3); // depends on: update soft bodies, contact removed callbacks, finish building the previous step431}432433// This job will solve the velocity constraints434step.mSolveVelocityConstraints.resize(max_concurrency);435for (int i = 0; i < max_concurrency; ++i)436step.mSolveVelocityConstraints[i] = inJobSystem->CreateJob("SolveVelocityConstraints", cColorSolveVelocityConstraints, [&context, &step]()437{438context.mPhysicsSystem->JobSolveVelocityConstraints(&context, &step);439440step.mPreIntegrateVelocity.RemoveDependency();441}, num_setup_velocity_constraints_jobs + 2); // depends on: finalize islands, setup velocity constraints, finish building jobs.442443// We prefer setup velocity constraints to finish first so we kick it first444JobHandle::sRemoveDependencies(step.mSetupVelocityConstraints);445JobHandle::sRemoveDependencies(step.mFindCollisions);446447// Finalize islands is a dependency on find collisions so it can go last448step.mFinalizeIslands.RemoveDependency();449450// This job will prepare the position update of all active bodies451step.mPreIntegrateVelocity = inJobSystem->CreateJob("PreIntegrateVelocity", cColorPreIntegrateVelocity, [&context, &step]()452{453context.mPhysicsSystem->JobPreIntegrateVelocity(&context, &step);454455JobHandle::sRemoveDependencies(step.mIntegrateVelocity);456}, 2 + max_concurrency); // depends on: broadphase update finalize, solve velocity constraints, finish building jobs.457458// Unblock previous jobs459step.mUpdateBroadphaseFinalize.RemoveDependency();460JobHandle::sRemoveDependencies(step.mSolveVelocityConstraints);461462// This job will update the positions of all active bodies463step.mIntegrateVelocity.resize(num_integrate_velocity_jobs);464for (int i = 0; i < num_integrate_velocity_jobs; ++i)465step.mIntegrateVelocity[i] = inJobSystem->CreateJob("IntegrateVelocity", cColorIntegrateVelocity, [&context, &step]()466{467context.mPhysicsSystem->JobIntegrateVelocity(&context, &step);468469step.mPostIntegrateVelocity.RemoveDependency();470}, 2); // depends on: pre integrate velocity, finish building jobs.471472// Unblock previous job473step.mPreIntegrateVelocity.RemoveDependency();474475// This job will finish the position update of all active bodies476step.mPostIntegrateVelocity = inJobSystem->CreateJob("PostIntegrateVelocity", cColorPostIntegrateVelocity, [&context, &step]()477{478context.mPhysicsSystem->JobPostIntegrateVelocity(&context, &step);479480step.mResolveCCDContacts.RemoveDependency();481}, num_integrate_velocity_jobs + 1); // depends on: integrate velocity, finish building jobs482483// Unblock previous jobs484JobHandle::sRemoveDependencies(step.mIntegrateVelocity);485486// This job will update the positions and velocities for all bodies that need continuous collision detection487step.mResolveCCDContacts = inJobSystem->CreateJob("ResolveCCDContacts", cColorResolveCCDContacts, [&context, &step]()488{489context.mPhysicsSystem->JobResolveCCDContacts(&context, &step);490491JobHandle::sRemoveDependencies(step.mSolvePositionConstraints);492}, 2); // depends on: integrate velocities, detect ccd contacts (added dynamically), finish building jobs.493494// Unblock previous job495step.mPostIntegrateVelocity.RemoveDependency();496497// Fixes up drift in positions and updates the broadphase with new body positions498step.mSolvePositionConstraints.resize(max_concurrency);499for (int i = 0; i < max_concurrency; ++i)500step.mSolvePositionConstraints[i] = inJobSystem->CreateJob("SolvePositionConstraints", cColorSolvePositionConstraints, [&context, &step]()501{502context.mPhysicsSystem->JobSolvePositionConstraints(&context, &step);503504// Kick the next step505if (step.mSoftBodyPrepare.IsValid())506step.mSoftBodyPrepare.RemoveDependency();507}, 3); // depends on: resolve ccd contacts, body set island index, finish building jobs.508509// Unblock previous jobs.510step.mResolveCCDContacts.RemoveDependency();511step.mBodySetIslandIndex.RemoveDependency();512513// The soft body prepare job will create other jobs if needed514step.mSoftBodyPrepare = inJobSystem->CreateJob("SoftBodyPrepare", cColorSoftBodyPrepare, [&context, &step]()515{516context.mPhysicsSystem->JobSoftBodyPrepare(&context, &step);517}, max_concurrency); // depends on: solve position constraints.518519// Unblock previous jobs520JobHandle::sRemoveDependencies(step.mSolvePositionConstraints);521}522}523524// Build the list of jobs to wait for525JobSystem::Barrier *barrier = context.mBarrier;526{527JPH_PROFILE("Build job barrier");528529StaticArray<JobHandle, cMaxPhysicsJobs> handles;530for (const PhysicsUpdateContext::Step &step : context.mSteps)531{532if (step.mBroadPhasePrepare.IsValid())533handles.push_back(step.mBroadPhasePrepare);534for (const JobHandle &h : step.mStepListeners)535handles.push_back(h);536for (const JobHandle &h : step.mDetermineActiveConstraints)537handles.push_back(h);538for (const JobHandle &h : step.mApplyGravity)539handles.push_back(h);540for (const JobHandle &h : step.mFindCollisions)541handles.push_back(h);542if (step.mUpdateBroadphaseFinalize.IsValid())543handles.push_back(step.mUpdateBroadphaseFinalize);544for (const JobHandle &h : step.mSetupVelocityConstraints)545handles.push_back(h);546handles.push_back(step.mBuildIslandsFromConstraints);547handles.push_back(step.mFinalizeIslands);548handles.push_back(step.mBodySetIslandIndex);549for (const JobHandle &h : step.mSolveVelocityConstraints)550handles.push_back(h);551handles.push_back(step.mPreIntegrateVelocity);552for (const JobHandle &h : step.mIntegrateVelocity)553handles.push_back(h);554handles.push_back(step.mPostIntegrateVelocity);555handles.push_back(step.mResolveCCDContacts);556for (const JobHandle &h : step.mSolvePositionConstraints)557handles.push_back(h);558handles.push_back(step.mContactRemovedCallbacks);559if (step.mSoftBodyPrepare.IsValid())560handles.push_back(step.mSoftBodyPrepare);561if (step.mStartNextStep.IsValid())562handles.push_back(step.mStartNextStep);563}564barrier->AddJobs(handles.data(), handles.size());565}566567// Wait until all jobs finish568// Note we don't just wait for the last job. If we would and another job569// would be scheduled in between there is the possibility of a deadlock.570// The other job could try to e.g. add/remove a body which would try to571// lock a body mutex while this thread has already locked the mutex572inJobSystem->WaitForJobs(barrier);573574// We're done with the barrier for this update575inJobSystem->DestroyBarrier(barrier);576577#ifdef JPH_DEBUG578// Validate that the cached bounds are correct579mBodyManager.ValidateActiveBodyBounds();580#endif // JPH_DEBUG581582// Clear the large island splitter583mLargeIslandSplitter.Reset(inTempAllocator);584585// Clear the island builder586mIslandBuilder.ResetIslands(inTempAllocator);587588// Clear the contact manager589mContactManager.FinishConstraintBuffer();590591// Free active constraints592inTempAllocator->Free(context.mActiveConstraints, mConstraintManager.GetNumConstraints() * sizeof(Constraint *));593context.mActiveConstraints = nullptr;594595// Free body pairs596inTempAllocator->Free(context.mBodyPairs, sizeof(BodyPair) * mPhysicsSettings.mMaxInFlightBodyPairs);597context.mBodyPairs = nullptr;598599// Unlock the broadphase600mBroadPhase->UnlockModifications();601602// Unlock all constraints603mConstraintManager.UnlockAllConstraints();604605#ifdef JPH_ENABLE_ASSERTS606// Allow write operations to the active bodies list607mBodyManager.SetActiveBodiesLocked(false);608#endif609610// Unlock all bodies611mBodyManager.UnlockAllBodies();612613// Unlock step listeners614mStepListenersMutex.unlock();615616// Return any errors617EPhysicsUpdateError errors = static_cast<EPhysicsUpdateError>(context.mErrors.load(memory_order_acquire));618JPH_ASSERT(errors == EPhysicsUpdateError::None, "An error occurred during the physics update, see EPhysicsUpdateError for more information");619return errors;620}621622void PhysicsSystem::JobStepListeners(PhysicsUpdateContext::Step *ioStep)623{624#ifdef JPH_ENABLE_ASSERTS625// Read positions (broadphase updates concurrently so we can't write), read/write velocities626BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);627628// Can activate bodies only (we cache the amount of active bodies at the beginning of the step in mNumActiveBodiesAtStepStart so we cannot deactivate here)629BodyManager::GrantActiveBodiesAccess grant_active(true, false);630#endif631632PhysicsStepListenerContext context;633context.mDeltaTime = ioStep->mContext->mStepDeltaTime;634context.mIsFirstStep = ioStep->mIsFirst;635context.mIsLastStep = ioStep->mIsLast;636context.mPhysicsSystem = this;637638uint32 batch_size = mPhysicsSettings.mStepListenersBatchSize;639for (;;)640{641// Get the start of a new batch642uint32 batch = ioStep->mStepListenerReadIdx.fetch_add(batch_size);643if (batch >= mStepListeners.size())644break;645646// Call the listeners647for (uint32 i = batch, i_end = min((uint32)mStepListeners.size(), batch + batch_size); i < i_end; ++i)648mStepListeners[i]->OnStep(context);649}650}651652void PhysicsSystem::JobDetermineActiveConstraints(PhysicsUpdateContext::Step *ioStep) const653{654#ifdef JPH_ENABLE_ASSERTS655// No body access656BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);657#endif658659uint32 num_constraints = mConstraintManager.GetNumConstraints();660uint32 num_active_constraints;661Constraint **active_constraints = (Constraint **)JPH_STACK_ALLOC(cDetermineActiveConstraintsBatchSize * sizeof(Constraint *));662663for (;;)664{665// Atomically fetch a batch of constraints666uint32 constraint_idx = ioStep->mDetermineActiveConstraintReadIdx.fetch_add(cDetermineActiveConstraintsBatchSize);667if (constraint_idx >= num_constraints)668break;669670// Calculate the end of the batch671uint32 constraint_idx_end = min(num_constraints, constraint_idx + cDetermineActiveConstraintsBatchSize);672673// 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)674mConstraintManager.GetActiveConstraints(constraint_idx, constraint_idx_end, active_constraints, num_active_constraints);675676// Copy the block of active constraints to the global list of active constraints677if (num_active_constraints > 0)678{679uint32 active_constraint_idx = ioStep->mNumActiveConstraints.fetch_add(num_active_constraints);680memcpy(ioStep->mContext->mActiveConstraints + active_constraint_idx, active_constraints, num_active_constraints * sizeof(Constraint *));681}682}683}684685void PhysicsSystem::JobApplyGravity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)686{687#ifdef JPH_ENABLE_ASSERTS688// We update velocities and need the rotation to do so689BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);690#endif691692// Get list of active bodies that we had at the start of the physics update.693// Any body that is activated as part of the simulation step does not receive gravity this frame.694// Note that bodies may be activated during this job but not deactivated, this means that only elements695// will be added to the array. Since the array is made to not reallocate, this is a safe operation.696const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody);697uint32 num_active_bodies_at_step_start = ioStep->mNumActiveBodiesAtStepStart;698699// Fetch delta time once outside the loop700float delta_time = ioContext->mStepDeltaTime;701702// Update velocities from forces703for (;;)704{705// Atomically fetch a batch of bodies706uint32 active_body_idx = ioStep->mApplyGravityReadIdx.fetch_add(cApplyGravityBatchSize);707if (active_body_idx >= num_active_bodies_at_step_start)708break;709710// Calculate the end of the batch711uint32 active_body_idx_end = min(num_active_bodies_at_step_start, active_body_idx + cApplyGravityBatchSize);712713// Process the batch714while (active_body_idx < active_body_idx_end)715{716Body &body = mBodyManager.GetBody(active_bodies[active_body_idx]);717if (body.IsDynamic())718{719MotionProperties *mp = body.GetMotionProperties();720Quat rotation = body.GetRotation();721722if (body.GetApplyGyroscopicForce())723mp->ApplyGyroscopicForceInternal(rotation, delta_time);724725mp->ApplyForceTorqueAndDragInternal(rotation, mGravity, delta_time);726}727active_body_idx++;728}729}730}731732void PhysicsSystem::JobSetupVelocityConstraints(float inDeltaTime, PhysicsUpdateContext::Step *ioStep) const733{734#ifdef JPH_ENABLE_ASSERTS735// We only read positions736BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);737#endif738739uint32 num_constraints = ioStep->mNumActiveConstraints;740741for (;;)742{743// Atomically fetch a batch of constraints744uint32 constraint_idx = ioStep->mSetupVelocityConstraintsReadIdx.fetch_add(cSetupVelocityConstraintsBatchSize);745if (constraint_idx >= num_constraints)746break;747748ConstraintManager::sSetupVelocityConstraints(ioStep->mContext->mActiveConstraints + constraint_idx, min<uint32>(cSetupVelocityConstraintsBatchSize, num_constraints - constraint_idx), inDeltaTime);749}750}751752void PhysicsSystem::JobBuildIslandsFromConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)753{754#ifdef JPH_ENABLE_ASSERTS755// We read constraints and positions756BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);757758// Can only activate bodies759BodyManager::GrantActiveBodiesAccess grant_active(true, false);760#endif761762// Prepare the island builder763mIslandBuilder.PrepareNonContactConstraints(ioStep->mNumActiveConstraints, ioContext->mTempAllocator);764765// Build the islands766ConstraintManager::sBuildIslands(ioStep->mContext->mActiveConstraints, ioStep->mNumActiveConstraints, mIslandBuilder, mBodyManager);767}768769void PhysicsSystem::TrySpawnJobFindCollisions(PhysicsUpdateContext::Step *ioStep) const770{771// Get how many jobs we can spawn and check if we can spawn more772uint max_jobs = ioStep->mBodyPairQueues.size();773if (CountBits(ioStep->mActiveFindCollisionJobs.load(memory_order_relaxed)) >= max_jobs)774return;775776// Count how many body pairs we have waiting777uint32 num_body_pairs = 0;778for (const PhysicsUpdateContext::BodyPairQueue &queue : ioStep->mBodyPairQueues)779num_body_pairs += queue.mWriteIdx - queue.mReadIdx;780781// Count how many active bodies we have waiting782uint32 num_active_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody) - ioStep->mActiveBodyReadIdx;783784// Calculate how many jobs we would like785uint desired_num_jobs = min((num_body_pairs + cNarrowPhaseBatchSize - 1) / cNarrowPhaseBatchSize + (num_active_bodies + cActiveBodiesBatchSize - 1) / cActiveBodiesBatchSize, max_jobs);786787for (;;)788{789// Get the bit mask of active jobs and see if we can spawn more790PhysicsUpdateContext::JobMask current_active_jobs = ioStep->mActiveFindCollisionJobs.load(memory_order_relaxed);791uint job_index = CountTrailingZeros(~current_active_jobs);792if (job_index >= desired_num_jobs)793break;794795// Try to claim the job index796PhysicsUpdateContext::JobMask job_mask = PhysicsUpdateContext::JobMask(1) << job_index;797PhysicsUpdateContext::JobMask prev_value = ioStep->mActiveFindCollisionJobs.fetch_or(job_mask, memory_order_acquire);798if ((prev_value & job_mask) == 0)799{800// Add dependencies from the find collisions job to the next jobs801ioStep->mUpdateBroadphaseFinalize.AddDependency();802ioStep->mFinalizeIslands.AddDependency();803804// Start the job805JobHandle job = ioStep->mContext->mJobSystem->CreateJob("FindCollisions", cColorFindCollisions, [step = ioStep, job_index]()806{807step->mContext->mPhysicsSystem->JobFindCollisions(step, job_index);808});809810// Add the job to the job barrier so the main updating thread can execute the job too811ioStep->mContext->mBarrier->AddJob(job);812813// Spawn only 1 extra job at a time814return;815}816}817}818819static void sFinalizeContactAllocator(PhysicsUpdateContext::Step &ioStep, const ContactConstraintManager::ContactAllocator &inAllocator)820{821// Atomically accumulate the number of found manifolds and body pairs822ioStep.mNumBodyPairs.fetch_add(inAllocator.mNumBodyPairs, memory_order_relaxed);823ioStep.mNumManifolds.fetch_add(inAllocator.mNumManifolds, memory_order_relaxed);824825// Combine update errors826ioStep.mContext->mErrors.fetch_or((uint32)inAllocator.mErrors, memory_order_relaxed);827}828829// Disable TSAN for this function. It detects a false positive race condition on mBodyPairs.830// We have written mBodyPairs before doing mWriteIdx++ and we check mWriteIdx before reading mBodyPairs, so this should be safe.831JPH_TSAN_NO_SANITIZE832void PhysicsSystem::JobFindCollisions(PhysicsUpdateContext::Step *ioStep, int inJobIndex)833{834#ifdef JPH_ENABLE_ASSERTS835// We read positions and read velocities (for elastic collisions)836BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);837838// Can only activate bodies839BodyManager::GrantActiveBodiesAccess grant_active(true, false);840#endif841842// Allocation context for allocating new contact points843ContactAllocator contact_allocator(mContactManager.GetContactAllocator());844845// Determine initial queue to read pairs from if no broadphase work can be done846// (always start looking at results from the next job)847int read_queue_idx = (inJobIndex + 1) % ioStep->mBodyPairQueues.size();848849// Allocate space to temporarily store a batch of active bodies850BodyID *active_bodies = (BodyID *)JPH_STACK_ALLOC(cActiveBodiesBatchSize * sizeof(BodyID));851852for (;;)853{854// Check if there are active bodies to be processed855uint32 active_bodies_read_idx = ioStep->mActiveBodyReadIdx;856uint32 num_active_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);857if (active_bodies_read_idx < num_active_bodies)858{859// Take a batch of active bodies860uint32 active_bodies_read_idx_end = min(num_active_bodies, active_bodies_read_idx + cActiveBodiesBatchSize);861if (ioStep->mActiveBodyReadIdx.compare_exchange_strong(active_bodies_read_idx, active_bodies_read_idx_end))862{863// Callback when a new body pair is found864class MyBodyPairCallback : public BodyPairCollector865{866public:867// Constructor868MyBodyPairCallback(PhysicsUpdateContext::Step *inStep, ContactAllocator &ioContactAllocator, int inJobIndex) :869mStep(inStep),870mContactAllocator(ioContactAllocator),871mJobIndex(inJobIndex)872{873}874875// Callback function when a body pair is found876virtual void AddHit(const BodyPair &inPair) override877{878// Check if we have space in our write queue879PhysicsUpdateContext::BodyPairQueue &queue = mStep->mBodyPairQueues[mJobIndex];880uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;881if (body_pairs_in_queue >= mStep->mMaxBodyPairsPerQueue)882{883// Buffer full, process the pair now884mStep->mContext->mPhysicsSystem->ProcessBodyPair(mContactAllocator, inPair);885}886else887{888// Store the pair in our own queue889mStep->mContext->mBodyPairs[mJobIndex * mStep->mMaxBodyPairsPerQueue + queue.mWriteIdx % mStep->mMaxBodyPairsPerQueue] = inPair;890++queue.mWriteIdx;891}892}893894private:895PhysicsUpdateContext::Step * mStep;896ContactAllocator & mContactAllocator;897int mJobIndex;898};899MyBodyPairCallback add_pair(ioStep, contact_allocator, inJobIndex);900901// Copy active bodies to temporary array, broadphase will reorder them902uint32 batch_size = active_bodies_read_idx_end - active_bodies_read_idx;903memcpy(active_bodies, mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody) + active_bodies_read_idx, batch_size * sizeof(BodyID));904905// Find pairs in the broadphase906mBroadPhase->FindCollidingPairs(active_bodies, batch_size, mPhysicsSettings.mSpeculativeContactDistance, *mObjectVsBroadPhaseLayerFilter, *mObjectLayerPairFilter, add_pair);907908// Check if we have enough pairs in the buffer to start a new job909const PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[inJobIndex];910uint32 body_pairs_in_queue = queue.mWriteIdx - queue.mReadIdx;911if (body_pairs_in_queue >= cNarrowPhaseBatchSize)912TrySpawnJobFindCollisions(ioStep);913}914}915else916{917// Lockless loop to get the next body pair from the pairs buffer918const PhysicsUpdateContext *context = ioStep->mContext;919int first_read_queue_idx = read_queue_idx;920for (;;)921{922PhysicsUpdateContext::BodyPairQueue &queue = ioStep->mBodyPairQueues[read_queue_idx];923924// Get the next pair to process925uint32 pair_idx = queue.mReadIdx;926927// If the pair hasn't been written yet928if (pair_idx >= queue.mWriteIdx)929{930// Go to the next queue931read_queue_idx = (read_queue_idx + 1) % ioStep->mBodyPairQueues.size();932933// If we're back at the first queue, we've looked at all of them and found nothing934if (read_queue_idx == first_read_queue_idx)935{936// Collect information from the contact allocator and accumulate it in the step.937sFinalizeContactAllocator(*ioStep, contact_allocator);938939// Mark this job as inactive940ioStep->mActiveFindCollisionJobs.fetch_and(~PhysicsUpdateContext::JobMask(1 << inJobIndex), memory_order_release);941942// Trigger the next jobs943ioStep->mUpdateBroadphaseFinalize.RemoveDependency();944ioStep->mFinalizeIslands.RemoveDependency();945return;946}947948// Try again reading from the next queue949continue;950}951952// Copy the body pair out of the buffer953const BodyPair bp = context->mBodyPairs[read_queue_idx * ioStep->mMaxBodyPairsPerQueue + pair_idx % ioStep->mMaxBodyPairsPerQueue];954955// Mark this pair as taken956if (queue.mReadIdx.compare_exchange_strong(pair_idx, pair_idx + 1))957{958// Process the actual body pair959ProcessBodyPair(contact_allocator, bp);960break;961}962}963}964}965}966967void PhysicsSystem::sDefaultSimCollideBodyVsBody(const Body &inBody1, const Body &inBody2, Mat44Arg inCenterOfMassTransform1, Mat44Arg inCenterOfMassTransform2, CollideShapeSettings &ioCollideShapeSettings, CollideShapeCollector &ioCollector, const ShapeFilter &inShapeFilter)968{969SubShapeIDCreator part1, part2;970971if (inBody1.GetEnhancedInternalEdgeRemovalWithBody(inBody2))972{973// Collide with enhanced internal edge removal974ioCollideShapeSettings.mActiveEdgeMode = EActiveEdgeMode::CollideWithAll;975InternalEdgeRemovingCollector::sCollideShapeVsShape(inBody1.GetShape(), inBody2.GetShape(), Vec3::sOne(), Vec3::sOne(), inCenterOfMassTransform1, inCenterOfMassTransform2, part1, part2, ioCollideShapeSettings, ioCollector, inShapeFilter);976}977else978{979// Regular collide980CollisionDispatch::sCollideShapeVsShape(inBody1.GetShape(), inBody2.GetShape(), Vec3::sOne(), Vec3::sOne(), inCenterOfMassTransform1, inCenterOfMassTransform2, part1, part2, ioCollideShapeSettings, ioCollector, inShapeFilter);981}982}983984void PhysicsSystem::ProcessBodyPair(ContactAllocator &ioContactAllocator, const BodyPair &inBodyPair)985{986JPH_PROFILE_FUNCTION();987988// Fetch body pair989Body *body1 = &mBodyManager.GetBody(inBodyPair.mBodyA);990Body *body2 = &mBodyManager.GetBody(inBodyPair.mBodyB);991JPH_ASSERT(body1->IsActive());992993JPH_DET_LOG("ProcessBodyPair: id1: " << inBodyPair.mBodyA << " id2: " << inBodyPair.mBodyB << " p1: " << body1->GetCenterOfMassPosition() << " p2: " << body2->GetCenterOfMassPosition() << " r1: " << body1->GetRotation() << " r2: " << body2->GetRotation());994995// Check for soft bodies996if (body2->IsSoftBody())997{998// If the 2nd body is a soft body and not active, we activate it now999if (!body2->IsActive())1000mBodyManager.ActivateBodies(&inBodyPair.mBodyB, 1);10011002// Soft body processing is done later in the pipeline1003return;1004}10051006// Ensure that body1 has the higher motion type (i.e. dynamic trumps kinematic), this ensures that we do the collision detection in the space of a moving body,1007// which avoids accuracy problems when testing a very large static object against a small dynamic object1008// Ensure that body1 id < body2 id when motion types are the same.1009if (body1->GetMotionType() < body2->GetMotionType()1010|| (body1->GetMotionType() == body2->GetMotionType() && inBodyPair.mBodyB < inBodyPair.mBodyA))1011std::swap(body1, body2);10121013// Check if the contact points from the previous frame are reusable and if so copy them1014bool pair_handled = false, constraint_created = false;1015if (mPhysicsSettings.mUseBodyPairContactCache && !(body1->IsCollisionCacheInvalid() || body2->IsCollisionCacheInvalid()))1016mContactManager.GetContactsFromCache(ioContactAllocator, *body1, *body2, pair_handled, constraint_created);10171018// If the cache hasn't handled this body pair do actual collision detection1019if (!pair_handled)1020{1021// Create entry in the cache for this body pair1022// Needs to happen irrespective if we found a collision or not (we want to remember that no collision was found too)1023ContactConstraintManager::BodyPairHandle body_pair_handle = mContactManager.AddBodyPair(ioContactAllocator, *body1, *body2);1024if (body_pair_handle == nullptr)1025return; // Out of cache space10261027// Create the query settings1028CollideShapeSettings settings;1029settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;1030settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;1031settings.mMaxSeparationDistance = body1->IsSensor() || body2->IsSensor()? 0.0f : mPhysicsSettings.mSpeculativeContactDistance;1032settings.mActiveEdgeMovementDirection = body1->GetLinearVelocity() - body2->GetLinearVelocity();10331034// Create shape filter1035SimShapeFilterWrapperUnion shape_filter_union(mSimShapeFilter, body1);1036SimShapeFilterWrapper &shape_filter = shape_filter_union.GetSimShapeFilterWrapper();1037shape_filter.SetBody2(body2);10381039// Get transforms relative to body11040RVec3 offset = body1->GetCenterOfMassPosition();1041Mat44 transform1 = Mat44::sRotation(body1->GetRotation());1042Mat44 transform2 = body2->GetCenterOfMassTransform().PostTranslated(-offset).ToMat44();10431044if (mPhysicsSettings.mUseManifoldReduction // Check global flag1045&& body1->GetUseManifoldReductionWithBody(*body2)) // Check body flag1046{1047// Version WITH contact manifold reduction10481049class MyManifold : public ContactManifold1050{1051public:1052Vec3 mFirstWorldSpaceNormal;1053};10541055// A temporary structure that allows us to keep track of the all manifolds between this body pair1056using Manifolds = StaticArray<MyManifold, 32>;10571058// Create collector1059class ReductionCollideShapeCollector : public CollideShapeCollector1060{1061public:1062ReductionCollideShapeCollector(PhysicsSystem *inSystem, const Body *inBody1, const Body *inBody2) :1063mSystem(inSystem),1064mBody1(inBody1),1065mBody2(inBody2)1066{1067}10681069virtual void AddHit(const CollideShapeResult &inResult) override1070{1071// The first body should be the one with the highest motion type1072JPH_ASSERT(mBody1->GetMotionType() >= mBody2->GetMotionType());1073JPH_ASSERT(!ShouldEarlyOut());10741075// Test if we want to accept this hit1076if (mValidateBodyPair)1077{1078switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, mBody1->GetCenterOfMassPosition(), inResult))1079{1080case ValidateResult::AcceptContact:1081// We're just accepting this one, nothing to do1082break;10831084case ValidateResult::AcceptAllContactsForThisBodyPair:1085// Accept and stop calling the validate callback1086mValidateBodyPair = false;1087break;10881089case ValidateResult::RejectContact:1090// Skip this contact1091return;10921093case ValidateResult::RejectAllContactsForThisBodyPair:1094// Skip this and early out1095ForceEarlyOut();1096return;1097}1098}10991100// Calculate normal1101Vec3 world_space_normal = inResult.mPenetrationAxis.Normalized();11021103// Check if we can add it to an existing manifold1104Manifolds::iterator manifold;1105float contact_normal_cos_max_delta_rot = mSystem->mPhysicsSettings.mContactNormalCosMaxDeltaRotation;1106for (manifold = mManifolds.begin(); manifold != mManifolds.end(); ++manifold)1107if (world_space_normal.Dot(manifold->mFirstWorldSpaceNormal) >= contact_normal_cos_max_delta_rot)1108{1109// Update average normal1110manifold->mWorldSpaceNormal += world_space_normal;1111manifold->mPenetrationDepth = max(manifold->mPenetrationDepth, inResult.mPenetrationDepth);1112break;1113}1114if (manifold == mManifolds.end())1115{1116// Check if array is full1117if (mManifolds.size() == mManifolds.capacity())1118{1119// Full, find manifold with least amount of penetration1120manifold = mManifolds.begin();1121for (Manifolds::iterator m = mManifolds.begin() + 1; m < mManifolds.end(); ++m)1122if (m->mPenetrationDepth < manifold->mPenetrationDepth)1123manifold = m;11241125// If this contacts penetration is smaller than the smallest manifold, we skip this contact1126if (inResult.mPenetrationDepth < manifold->mPenetrationDepth)1127return;11281129// Replace the manifold1130*manifold = { { mBody1->GetCenterOfMassPosition(), world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal };1131}1132else1133{1134// Not full, create new manifold1135mManifolds.push_back({ { mBody1->GetCenterOfMassPosition(), world_space_normal, inResult.mPenetrationDepth, inResult.mSubShapeID1, inResult.mSubShapeID2, { }, { } }, world_space_normal });1136manifold = mManifolds.end() - 1;1137}1138}11391140// Determine contact points1141const PhysicsSettings &settings = mSystem->mPhysicsSettings;1142ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, settings.mSpeculativeContactDistance + settings.mManifoldTolerance, inResult.mShape1Face, inResult.mShape2Face, manifold->mRelativeContactPointsOn1, manifold->mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, mBody1->GetCenterOfMassPosition()));11431144// Prune if we have more than 32 points (this means we could run out of space in the next iteration)1145if (manifold->mRelativeContactPointsOn1.size() > 32)1146PruneContactPoints(manifold->mFirstWorldSpaceNormal, manifold->mRelativeContactPointsOn1, manifold->mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold->mBaseOffset));1147}11481149PhysicsSystem * mSystem;1150const Body * mBody1;1151const Body * mBody2;1152bool mValidateBodyPair = true;1153Manifolds mManifolds;1154};1155ReductionCollideShapeCollector collector(this, body1, body2);11561157// Perform collision detection between the two shapes1158mSimCollideBodyVsBody(*body1, *body2, transform1, transform2, settings, collector, shape_filter);11591160// Add the contacts1161for (ContactManifold &manifold : collector.mManifolds)1162{1163// Normalize the normal (is a sum of all normals from merged manifolds)1164manifold.mWorldSpaceNormal = manifold.mWorldSpaceNormal.Normalized();11651166// If we still have too many points, prune them now1167if (manifold.mRelativeContactPointsOn1.size() > 4)1168PruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));11691170// Actually add the contact points to the manager1171constraint_created |= mContactManager.AddContactConstraint(ioContactAllocator, body_pair_handle, *body1, *body2, manifold);1172}1173}1174else1175{1176// Version WITHOUT contact manifold reduction11771178// Create collector1179class NonReductionCollideShapeCollector : public CollideShapeCollector1180{1181public:1182NonReductionCollideShapeCollector(PhysicsSystem *inSystem, ContactAllocator &ioContactAllocator, Body *inBody1, Body *inBody2, const ContactConstraintManager::BodyPairHandle &inPairHandle) :1183mSystem(inSystem),1184mContactAllocator(ioContactAllocator),1185mBody1(inBody1),1186mBody2(inBody2),1187mBodyPairHandle(inPairHandle)1188{1189}11901191virtual void AddHit(const CollideShapeResult &inResult) override1192{1193// The first body should be the one with the highest motion type1194JPH_ASSERT(mBody1->GetMotionType() >= mBody2->GetMotionType());1195JPH_ASSERT(!ShouldEarlyOut());11961197// Test if we want to accept this hit1198if (mValidateBodyPair)1199{1200switch (mSystem->mContactManager.ValidateContactPoint(*mBody1, *mBody2, mBody1->GetCenterOfMassPosition(), inResult))1201{1202case ValidateResult::AcceptContact:1203// We're just accepting this one, nothing to do1204break;12051206case ValidateResult::AcceptAllContactsForThisBodyPair:1207// Accept and stop calling the validate callback1208mValidateBodyPair = false;1209break;12101211case ValidateResult::RejectContact:1212// Skip this contact1213return;12141215case ValidateResult::RejectAllContactsForThisBodyPair:1216// Skip this and early out1217ForceEarlyOut();1218return;1219}1220}12211222// Determine contact points1223ContactManifold manifold;1224manifold.mBaseOffset = mBody1->GetCenterOfMassPosition();1225const PhysicsSettings &settings = mSystem->mPhysicsSettings;1226ManifoldBetweenTwoFaces(inResult.mContactPointOn1, inResult.mContactPointOn2, inResult.mPenetrationAxis, settings.mSpeculativeContactDistance + settings.mManifoldTolerance, inResult.mShape1Face, inResult.mShape2Face, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));12271228// Calculate normal1229manifold.mWorldSpaceNormal = inResult.mPenetrationAxis.Normalized();12301231// Store penetration depth1232manifold.mPenetrationDepth = inResult.mPenetrationDepth;12331234// Prune if we have more than 4 points1235if (manifold.mRelativeContactPointsOn1.size() > 4)1236PruneContactPoints(manifold.mWorldSpaceNormal, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));12371238// Set other properties1239manifold.mSubShapeID1 = inResult.mSubShapeID1;1240manifold.mSubShapeID2 = inResult.mSubShapeID2;12411242// Actually add the contact points to the manager1243mConstraintCreated |= mSystem->mContactManager.AddContactConstraint(mContactAllocator, mBodyPairHandle, *mBody1, *mBody2, manifold);1244}12451246PhysicsSystem * mSystem;1247ContactAllocator & mContactAllocator;1248Body * mBody1;1249Body * mBody2;1250ContactConstraintManager::BodyPairHandle mBodyPairHandle;1251bool mValidateBodyPair = true;1252bool mConstraintCreated = false;1253};1254NonReductionCollideShapeCollector collector(this, ioContactAllocator, body1, body2, body_pair_handle);12551256// Perform collision detection between the two shapes1257mSimCollideBodyVsBody(*body1, *body2, transform1, transform2, settings, collector, shape_filter);12581259constraint_created = collector.mConstraintCreated;1260}1261}12621263// If a contact constraint was created, we need to do some extra work1264if (constraint_created)1265{1266// Wake up sleeping bodies1267BodyID body_ids[2];1268int num_bodies = 0;1269if (body1->IsDynamic() && !body1->IsActive())1270body_ids[num_bodies++] = body1->GetID();1271if (body2->IsDynamic() && !body2->IsActive())1272body_ids[num_bodies++] = body2->GetID();1273if (num_bodies > 0)1274mBodyManager.ActivateBodies(body_ids, num_bodies);12751276// Link the two bodies1277mIslandBuilder.LinkBodies(body1->GetIndexInActiveBodiesInternal(), body2->GetIndexInActiveBodiesInternal());1278}1279}12801281void PhysicsSystem::JobFinalizeIslands(PhysicsUpdateContext *ioContext)1282{1283#ifdef JPH_ENABLE_ASSERTS1284// We only touch island data1285BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);1286#endif12871288// Finish collecting the islands, at this point the active body list doesn't change so it's safe to access1289mIslandBuilder.Finalize(mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody), mBodyManager.GetNumActiveBodies(EBodyType::RigidBody), mContactManager.GetNumConstraints(), ioContext->mTempAllocator);12901291// Prepare the large island splitter1292if (mPhysicsSettings.mUseLargeIslandSplitter)1293mLargeIslandSplitter.Prepare(mIslandBuilder, mBodyManager.GetNumActiveBodies(EBodyType::RigidBody), ioContext->mTempAllocator);1294}12951296void PhysicsSystem::JobBodySetIslandIndex()1297{1298#ifdef JPH_ENABLE_ASSERTS1299// We only touch island data1300BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);1301#endif13021303// Loop through the result and tag all bodies with an island index1304for (uint32 island_idx = 0, n = mIslandBuilder.GetNumIslands(); island_idx < n; ++island_idx)1305{1306BodyID *body_start, *body_end;1307mIslandBuilder.GetBodiesInIsland(island_idx, body_start, body_end);1308for (const BodyID *body = body_start; body < body_end; ++body)1309mBodyManager.GetBody(*body).GetMotionProperties()->SetIslandIndexInternal(island_idx);1310}1311}13121313JPH_SUPPRESS_WARNING_PUSH1314JPH_CLANG_SUPPRESS_WARNING("-Wundefined-func-template") // ConstraintManager::sWarmStartVelocityConstraints / ContactConstraintManager::WarmStartVelocityConstraints is instantiated in the cpp file13151316void PhysicsSystem::JobSolveVelocityConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)1317{1318#ifdef JPH_ENABLE_ASSERTS1319// We update velocities and need to read positions to do so1320BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);1321#endif13221323float delta_time = ioContext->mStepDeltaTime;1324Constraint **active_constraints = ioContext->mActiveConstraints;13251326// Only the first step to correct for the delta time difference in the previous update1327float warm_start_impulse_ratio = ioStep->mIsFirst? ioContext->mWarmStartImpulseRatio : 1.0f;13281329bool check_islands = true, check_split_islands = mPhysicsSettings.mUseLargeIslandSplitter;1330for (;;)1331{1332// First try to get work from large islands1333if (check_split_islands)1334{1335bool first_iteration;1336uint split_island_index;1337uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;1338switch (mLargeIslandSplitter.FetchNextBatch(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, first_iteration))1339{1340case LargeIslandSplitter::EStatus::BatchRetrieved:1341{1342if (first_iteration)1343{1344// Iteration 0 is used to warm start the batch (we added 1 to the number of iterations in LargeIslandSplitter::SplitIsland)1345DummyCalculateSolverSteps dummy;1346ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio, dummy);1347mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio, dummy);1348}1349else1350{1351// Solve velocity constraints1352ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);1353mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);1354}13551356// Mark the batch as processed1357bool last_iteration, final_batch;1358mLargeIslandSplitter.MarkBatchProcessed(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, last_iteration, final_batch);13591360// Save back the lambdas in the contact cache for the warm start of the next physics update1361if (last_iteration)1362mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);13631364// We processed work, loop again1365continue;1366}13671368case LargeIslandSplitter::EStatus::WaitingForBatch:1369break;13701371case LargeIslandSplitter::EStatus::AllBatchesDone:1372check_split_islands = false;1373break;1374}1375}13761377// If that didn't succeed try to process an island1378if (check_islands)1379{1380// Next island1381uint32 island_idx = ioStep->mSolveVelocityConstraintsNextIsland++;1382if (island_idx >= mIslandBuilder.GetNumIslands())1383{1384// We processed all islands, stop checking islands1385check_islands = false;1386continue;1387}13881389JPH_PROFILE("Island");13901391// Get iterators for this island1392uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;1393bool has_constraints = mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);1394bool has_contacts = mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);13951396// If we don't have any contacts or constraints, we know that none of the following islands have any contacts or constraints1397// (because they're sorted by most constraints first). This means we're done.1398if (!has_contacts && !has_constraints)1399{1400#ifdef JPH_ENABLE_ASSERTS1401// Validate our assumption that the next islands don't have any constraints or contacts1402for (; island_idx < mIslandBuilder.GetNumIslands(); ++island_idx)1403{1404JPH_ASSERT(!mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end));1405JPH_ASSERT(!mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end));1406}1407#endif // JPH_ENABLE_ASSERTS14081409check_islands = false;1410continue;1411}14121413// Sorting is costly but needed for a deterministic simulation, allow the user to turn this off1414if (mPhysicsSettings.mDeterministicSimulation)1415{1416// Sort constraints to give a deterministic simulation1417ConstraintManager::sSortConstraints(active_constraints, constraints_begin, constraints_end);14181419// Sort contacts to give a deterministic simulation1420mContactManager.SortContacts(contacts_begin, contacts_end);1421}14221423// Split up large islands1424CalculateSolverSteps steps_calculator(mPhysicsSettings);1425if (mPhysicsSettings.mUseLargeIslandSplitter1426&& mLargeIslandSplitter.SplitIsland(island_idx, mIslandBuilder, mBodyManager, mContactManager, active_constraints, steps_calculator))1427continue; // Loop again to try to fetch the newly split island14281429// We didn't create a split, just run the solver now for this entire island. Begin by warm starting.1430ConstraintManager::sWarmStartVelocityConstraints(active_constraints, constraints_begin, constraints_end, warm_start_impulse_ratio, steps_calculator);1431mContactManager.WarmStartVelocityConstraints(contacts_begin, contacts_end, warm_start_impulse_ratio, steps_calculator);1432steps_calculator.Finalize();14331434// Store the number of position steps for later1435mIslandBuilder.SetNumPositionSteps(island_idx, steps_calculator.GetNumPositionSteps());14361437// Solve velocity constraints1438for (uint velocity_step = 0; velocity_step < steps_calculator.GetNumVelocitySteps(); ++velocity_step)1439{1440bool applied_impulse = ConstraintManager::sSolveVelocityConstraints(active_constraints, constraints_begin, constraints_end, delta_time);1441applied_impulse |= mContactManager.SolveVelocityConstraints(contacts_begin, contacts_end);1442if (!applied_impulse)1443break;1444}14451446// Save back the lambdas in the contact cache for the warm start of the next physics update1447mContactManager.StoreAppliedImpulses(contacts_begin, contacts_end);14481449// We processed work, loop again1450continue;1451}14521453if (check_islands)1454{1455// If there are islands, we don't need to wait and can pick up new work1456continue;1457}1458else if (check_split_islands)1459{1460// If there are split islands, but we didn't do any work, give up a time slice1461std::this_thread::yield();1462}1463else1464{1465// No more work1466break;1467}1468}1469}14701471JPH_SUPPRESS_WARNING_POP14721473void PhysicsSystem::JobPreIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)1474{1475// Reserve enough space for all bodies that may need a cast1476TempAllocator *temp_allocator = ioContext->mTempAllocator;1477JPH_ASSERT(ioStep->mCCDBodies == nullptr);1478ioStep->mCCDBodiesCapacity = mBodyManager.GetNumActiveCCDBodies();1479ioStep->mCCDBodies = (CCDBody *)temp_allocator->Allocate(ioStep->mCCDBodiesCapacity * sizeof(CCDBody));14801481// Initialize the mapping table between active body and CCD body1482JPH_ASSERT(ioStep->mActiveBodyToCCDBody == nullptr);1483ioStep->mNumActiveBodyToCCDBody = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);1484ioStep->mActiveBodyToCCDBody = (int *)temp_allocator->Allocate(ioStep->mNumActiveBodyToCCDBody * sizeof(int));14851486// Prepare the split island builder for solving the position constraints1487mLargeIslandSplitter.PrepareForSolvePositions();1488}14891490void PhysicsSystem::JobIntegrateVelocity(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)1491{1492#ifdef JPH_ENABLE_ASSERTS1493// We update positions and need velocity to do so, we also clamp velocities so need to write to them1494BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);1495#endif14961497float delta_time = ioContext->mStepDeltaTime;1498const BodyID *active_bodies = mBodyManager.GetActiveBodiesUnsafe(EBodyType::RigidBody);1499uint32 num_active_bodies = mBodyManager.GetNumActiveBodies(EBodyType::RigidBody);1500uint32 num_active_bodies_after_find_collisions = ioStep->mActiveBodyReadIdx;15011502// We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.1503static constexpr int cBodiesBatch = 64;1504BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));1505int num_bodies_to_update_bounds = 0;15061507for (;;)1508{1509// Atomically fetch a batch of bodies1510uint32 active_body_idx = ioStep->mIntegrateVelocityReadIdx.fetch_add(cIntegrateVelocityBatchSize);1511if (active_body_idx >= num_active_bodies)1512break;15131514// Calculate the end of the batch1515uint32 active_body_idx_end = min(num_active_bodies, active_body_idx + cIntegrateVelocityBatchSize);15161517// Process the batch1518while (active_body_idx < active_body_idx_end)1519{1520// Update the positions using an Symplectic Euler step (which integrates using the updated velocity v1' rather1521// than the original velocity v1):1522// x1' = x1 + h * v1'1523// At this point the active bodies list does not change, so it is safe to access the array.1524BodyID body_id = active_bodies[active_body_idx];1525Body &body = mBodyManager.GetBody(body_id);1526MotionProperties *mp = body.GetMotionProperties();15271528JPH_DET_LOG("JobIntegrateVelocity: id: " << body_id << " v: " << body.GetLinearVelocity() << " w: " << body.GetAngularVelocity());15291530// Clamp velocities (not for kinematic bodies)1531if (body.IsDynamic())1532{1533mp->ClampLinearVelocity();1534mp->ClampAngularVelocity();1535}15361537// Update the rotation of the body according to the angular velocity1538// For motion type discrete we need to do this anyway, for motion type linear cast we have multiple choices1539// 1. Rotate the body first and then sweep1540// 2. First sweep and then rotate the body at the end1541// 3. Pick some in between rotation (e.g. half way), then sweep and finally rotate the remainder1542// (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.1543// 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 using1544// 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 previous1545// 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 effects1546// too as simulating the rotation first may cause it to tunnel through a small object that the linear cast might have otherwise detected. In any case a linear cast is not good for detecting1547// 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).1548body.AddRotationStep(body.GetAngularVelocity() * delta_time);15491550// Get delta position1551Vec3 delta_pos = body.GetLinearVelocity() * delta_time;15521553// If the position should be updated (or if it is delayed because of CCD)1554bool update_position = true;15551556switch (mp->GetMotionQuality())1557{1558case EMotionQuality::Discrete:1559// No additional collision checking to be done1560break;15611562case EMotionQuality::LinearCast:1563if (body.IsDynamic() // Kinematic bodies cannot be stopped1564&& !body.IsSensor()) // We don't support CCD sensors1565{1566// Determine inner radius (the smallest sphere that fits into the shape)1567float inner_radius = body.GetShape()->GetInnerRadius();1568JPH_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.");15691570// Measure translation in this step and check if it above the threshold to perform a linear cast1571float linear_cast_threshold_sq = Square(mPhysicsSettings.mLinearCastThreshold * inner_radius);1572if (delta_pos.LengthSq() > linear_cast_threshold_sq)1573{1574// This body needs a cast1575uint32 ccd_body_idx = ioStep->mNumCCDBodies++;1576JPH_ASSERT(active_body_idx < ioStep->mNumActiveBodyToCCDBody);1577ioStep->mActiveBodyToCCDBody[active_body_idx] = ccd_body_idx;1578new (&ioStep->mCCDBodies[ccd_body_idx]) CCDBody(body_id, delta_pos, linear_cast_threshold_sq, min(mPhysicsSettings.mPenetrationSlop, mPhysicsSettings.mLinearCastMaxPenetration * inner_radius));15791580update_position = false;1581}1582}1583break;1584}15851586if (update_position)1587{1588// Move the body now1589body.AddPositionStep(delta_pos);15901591// If the body was activated due to an earlier CCD step it will have an index in the active1592// body list that it higher than the highest one we processed during FindCollisions1593// which means it hasn't been assigned an island and will not be updated by an island1594// this means that we need to update its bounds manually1595if (mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)1596{1597body.CalculateWorldSpaceBoundsInternal();1598bodies_to_update_bounds[num_bodies_to_update_bounds++] = body.GetID();1599if (num_bodies_to_update_bounds == cBodiesBatch)1600{1601// Buffer full, flush now1602mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);1603num_bodies_to_update_bounds = 0;1604}1605}16061607// We did not create a CCD body1608ioStep->mActiveBodyToCCDBody[active_body_idx] = -1;1609}16101611active_body_idx++;1612}1613}16141615// Notify change bounds on requested bodies1616if (num_bodies_to_update_bounds > 0)1617mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);1618}16191620void PhysicsSystem::JobPostIntegrateVelocity(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep) const1621{1622// Validate that our reservations were correct1623JPH_ASSERT(ioStep->mNumCCDBodies <= mBodyManager.GetNumActiveCCDBodies());16241625if (ioStep->mNumCCDBodies == 0)1626{1627// No continuous collision detection jobs -> kick the next job ourselves1628ioStep->mContactRemovedCallbacks.RemoveDependency();1629}1630else1631{1632// Run the continuous collision detection jobs1633int num_continuous_collision_jobs = min(int(ioStep->mNumCCDBodies + cNumCCDBodiesPerJob - 1) / cNumCCDBodiesPerJob, ioContext->GetMaxConcurrency());1634ioStep->mResolveCCDContacts.AddDependency(num_continuous_collision_jobs);1635ioStep->mContactRemovedCallbacks.AddDependency(num_continuous_collision_jobs - 1); // Already had 1 dependency1636for (int i = 0; i < num_continuous_collision_jobs; ++i)1637{1638JobHandle job = ioContext->mJobSystem->CreateJob("FindCCDContacts", cColorFindCCDContacts, [ioContext, ioStep]()1639{1640ioContext->mPhysicsSystem->JobFindCCDContacts(ioContext, ioStep);16411642ioStep->mResolveCCDContacts.RemoveDependency();1643ioStep->mContactRemovedCallbacks.RemoveDependency();1644});1645ioContext->mBarrier->AddJob(job);1646}1647}1648}16491650// Helper function to calculate the motion of a body during this CCD step1651inline static Vec3 sCalculateBodyMotion(const Body &inBody, float inDeltaTime)1652{1653// If the body is linear casting, the body has not yet moved so we need to calculate its motion1654if (inBody.IsDynamic() && inBody.GetMotionProperties()->GetMotionQuality() == EMotionQuality::LinearCast)1655return inDeltaTime * inBody.GetLinearVelocity();16561657// Body has already moved, so we don't need to correct for anything1658return Vec3::sZero();1659}16601661// Helper function that finds the CCD body corresponding to a body (if it exists)1662inline static PhysicsUpdateContext::Step::CCDBody *sGetCCDBody(const Body &inBody, PhysicsUpdateContext::Step *inStep)1663{1664// Only rigid bodies can have a CCD body1665if (!inBody.IsRigidBody())1666return nullptr;16671668// If the body has no motion properties it cannot have a CCD body1669const MotionProperties *motion_properties = inBody.GetMotionPropertiesUnchecked();1670if (motion_properties == nullptr)1671return nullptr;16721673// If it is not active it cannot have a CCD body1674uint32 active_index = motion_properties->GetIndexInActiveBodiesInternal();1675if (active_index == Body::cInactiveIndex)1676return nullptr;16771678// Check if the active body has a corresponding CCD body1679JPH_ASSERT(active_index < inStep->mNumActiveBodyToCCDBody); // Ensure that the body has a mapping to CCD body1680int ccd_index = inStep->mActiveBodyToCCDBody[active_index];1681if (ccd_index < 0)1682return nullptr;16831684PhysicsUpdateContext::Step::CCDBody *ccd_body = &inStep->mCCDBodies[ccd_index];1685JPH_ASSERT(ccd_body->mBodyID1 == inBody.GetID(), "We found the wrong CCD body!");1686return ccd_body;1687}16881689void PhysicsSystem::JobFindCCDContacts(const PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)1690{1691#ifdef JPH_ENABLE_ASSERTS1692// We only read positions, but the validate callback may read body positions and velocities1693BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);1694#endif16951696// Allocation context for allocating new contact points1697ContactAllocator contact_allocator(mContactManager.GetContactAllocator());16981699// Settings1700ShapeCastSettings settings;1701settings.mUseShrunkenShapeAndConvexRadius = true;1702settings.mBackFaceModeTriangles = EBackFaceMode::IgnoreBackFaces;1703settings.mBackFaceModeConvex = EBackFaceMode::IgnoreBackFaces;1704settings.mReturnDeepestPoint = true;1705settings.mCollectFacesMode = ECollectFacesMode::CollectFaces;1706settings.mActiveEdgeMode = mPhysicsSettings.mCheckActiveEdges? EActiveEdgeMode::CollideOnlyWithActive : EActiveEdgeMode::CollideWithAll;17071708for (;;)1709{1710// Fetch the next body to cast1711uint32 idx = ioStep->mNextCCDBody++;1712if (idx >= ioStep->mNumCCDBodies)1713break;1714CCDBody &ccd_body = ioStep->mCCDBodies[idx];1715const Body &body = mBodyManager.GetBody(ccd_body.mBodyID1);17161717// Filter out layers1718DefaultBroadPhaseLayerFilter broadphase_layer_filter = GetDefaultBroadPhaseLayerFilter(body.GetObjectLayer());1719DefaultObjectLayerFilter object_layer_filter = GetDefaultLayerFilter(body.GetObjectLayer());17201721#ifdef JPH_DEBUG_RENDERER1722// Draw start and end shape of cast1723if (sDrawMotionQualityLinearCast)1724{1725RMat44 com = body.GetCenterOfMassTransform();1726body.GetShape()->Draw(DebugRenderer::sInstance, com, Vec3::sOne(), Color::sGreen, false, true);1727DebugRenderer::sInstance->DrawArrow(com.GetTranslation(), com.GetTranslation() + ccd_body.mDeltaPosition, Color::sGreen, 0.1f);1728body.GetShape()->Draw(DebugRenderer::sInstance, com.PostTranslated(ccd_body.mDeltaPosition), Vec3::sOne(), Color::sRed, false, true);1729}1730#endif // JPH_DEBUG_RENDERER17311732// Create a collector that will find the maximum distance allowed to travel while not penetrating more than 'max penetration'1733class CCDNarrowPhaseCollector : public CastShapeCollector1734{1735public:1736CCDNarrowPhaseCollector(const BodyManager &inBodyManager, ContactConstraintManager &inContactConstraintManager, CCDBody &inCCDBody, ShapeCastResult &inResult, float inDeltaTime) :1737mBodyManager(inBodyManager),1738mContactConstraintManager(inContactConstraintManager),1739mCCDBody(inCCDBody),1740mResult(inResult),1741mDeltaTime(inDeltaTime)1742{1743}17441745virtual void AddHit(const ShapeCastResult &inResult) override1746{1747JPH_PROFILE_FUNCTION();17481749// Check if this is a possible earlier hit than the one before1750float fraction = inResult.mFraction;1751if (fraction < mCCDBody.mFractionPlusSlop)1752{1753// Normalize normal1754Vec3 normal = inResult.mPenetrationAxis.Normalized();17551756// Calculate how much we can add to the fraction to penetrate the collision point by mMaxPenetration.1757// Note that the normal is pointing towards body 2!1758// 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|1759// <=> dist = mMaxPenetration * |delta_pos| / normal . delta_pos1760// Converting to a faction: delta_fraction = dist / |delta_pos| = mLinearCastTreshold / normal . delta_pos1761float denominator = normal.Dot(mCCDBody.mDeltaPosition);1762if (denominator > mCCDBody.mMaxPenetration) // Avoid dividing by zero, if extra hit fraction > 1 there's also no point in continuing1763{1764float fraction_plus_slop = fraction + mCCDBody.mMaxPenetration / denominator;1765if (fraction_plus_slop < mCCDBody.mFractionPlusSlop)1766{1767const Body &body2 = mBodyManager.GetBody(inResult.mBodyID2);17681769// Check if we've already accepted all hits from this body1770if (mValidateBodyPair)1771{1772// Validate the contact result1773const Body &body1 = mBodyManager.GetBody(mCCDBody.mBodyID1);1774ValidateResult validate_result = mContactConstraintManager.ValidateContactPoint(body1, body2, body1.GetCenterOfMassPosition(), inResult); // Note that the center of mass of body 1 is the start of the sweep and is used as base offset below1775switch (validate_result)1776{1777case ValidateResult::AcceptContact:1778// Just continue1779break;17801781case ValidateResult::AcceptAllContactsForThisBodyPair:1782// Accept this and all following contacts from this body1783mValidateBodyPair = false;1784break;17851786case ValidateResult::RejectContact:1787return;17881789case ValidateResult::RejectAllContactsForThisBodyPair:1790// Reject this and all following contacts from this body1791mRejectAll = true;1792ForceEarlyOut();1793return;1794}1795}17961797// This is the earliest hit so far, store it1798mCCDBody.mContactNormal = normal;1799mCCDBody.mBodyID2 = inResult.mBodyID2;1800mCCDBody.mSubShapeID2 = inResult.mSubShapeID2;1801mCCDBody.mFraction = fraction;1802mCCDBody.mFractionPlusSlop = fraction_plus_slop;1803mResult = inResult;18041805// Result was assuming body 2 is not moving, but it is, so we need to correct for it1806Vec3 movement2 = fraction * sCalculateBodyMotion(body2, mDeltaTime);1807if (!movement2.IsNearZero())1808{1809mResult.mContactPointOn1 += movement2;1810mResult.mContactPointOn2 += movement2;1811for (Vec3 &v : mResult.mShape1Face)1812v += movement2;1813for (Vec3 &v : mResult.mShape2Face)1814v += movement2;1815}18161817// Update early out fraction1818UpdateEarlyOutFraction(fraction_plus_slop);1819}1820}1821}1822}18231824bool mValidateBodyPair; ///< If we still have to call the ValidateContactPoint for this body pair1825bool mRejectAll; ///< Reject all further contacts between this body pair18261827private:1828const BodyManager & mBodyManager;1829ContactConstraintManager & mContactConstraintManager;1830CCDBody & mCCDBody;1831ShapeCastResult & mResult;1832float mDeltaTime;1833BodyID mAcceptedBodyID;1834};18351836// Narrowphase collector1837ShapeCastResult cast_shape_result;1838CCDNarrowPhaseCollector np_collector(mBodyManager, mContactManager, ccd_body, cast_shape_result, ioContext->mStepDeltaTime);18391840// This collector wraps the narrowphase collector and collects the closest hit1841class CCDBroadPhaseCollector : public CastShapeBodyCollector1842{1843public:1844CCDBroadPhaseCollector(const CCDBody &inCCDBody, const Body &inBody1, const RShapeCast &inShapeCast, ShapeCastSettings &inShapeCastSettings, SimShapeFilterWrapper &inShapeFilter, CCDNarrowPhaseCollector &ioCollector, const BodyManager &inBodyManager, PhysicsUpdateContext::Step *inStep, float inDeltaTime) :1845mCCDBody(inCCDBody),1846mBody1(inBody1),1847mBody1Extent(inShapeCast.mShapeWorldBounds.GetExtent()),1848mShapeCast(inShapeCast),1849mShapeCastSettings(inShapeCastSettings),1850mShapeFilter(inShapeFilter),1851mCollector(ioCollector),1852mBodyManager(inBodyManager),1853mStep(inStep),1854mDeltaTime(inDeltaTime)1855{1856}18571858virtual void AddHit(const BroadPhaseCastResult &inResult) override1859{1860JPH_PROFILE_FUNCTION();18611862JPH_ASSERT(inResult.mFraction <= GetEarlyOutFraction(), "This hit should not have been passed on to the collector");18631864// Test if we're colliding with ourselves1865if (mBody1.GetID() == inResult.mBodyID)1866return;18671868// Avoid treating duplicates, if both bodies are doing CCD then only consider collision if body ID < other body ID1869const Body &body2 = mBodyManager.GetBody(inResult.mBodyID);1870const CCDBody *ccd_body2 = sGetCCDBody(body2, mStep);1871if (ccd_body2 != nullptr && mCCDBody.mBodyID1 > ccd_body2->mBodyID1)1872return;18731874// Test group filter1875if (!mBody1.GetCollisionGroup().CanCollide(body2.GetCollisionGroup()))1876return;18771878// TODO: For now we ignore sensors1879if (body2.IsSensor())1880return;18811882// Get relative movement of these two bodies1883Vec3 direction = mShapeCast.mDirection - sCalculateBodyMotion(body2, mDeltaTime);18841885// Test if the remaining movement is less than our movement threshold1886if (direction.LengthSq() < mCCDBody.mLinearCastThresholdSq)1887return;18881889// 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 fraction1890AABox bounds = body2.GetWorldSpaceBounds();1891bounds.mMin -= mBody1Extent;1892bounds.mMax += mBody1Extent;1893float hit_fraction = RayAABox(Vec3(mShapeCast.mCenterOfMassStart.GetTranslation()), RayInvDirection(direction), bounds.mMin, bounds.mMax);1894if (hit_fraction > GetPositiveEarlyOutFraction()) // If early out fraction <= 0, we have the possibility of finding a deeper hit so we need to clamp the early out fraction1895return;18961897// Reset collector (this is a new body pair)1898mCollector.ResetEarlyOutFraction(GetEarlyOutFraction());1899mCollector.mValidateBodyPair = true;1900mCollector.mRejectAll = false;19011902// Set body ID on shape filter1903mShapeFilter.SetBody2(&body2);19041905// Provide direction as hint for the active edges algorithm1906mShapeCastSettings.mActiveEdgeMovementDirection = direction;19071908// Do narrow phase collision check1909RShapeCast relative_cast(mShapeCast.mShape, mShapeCast.mScale, mShapeCast.mCenterOfMassStart, direction, mShapeCast.mShapeWorldBounds);1910body2.GetTransformedShape().CastShape(relative_cast, mShapeCastSettings, mShapeCast.mCenterOfMassStart.GetTranslation(), mCollector, mShapeFilter);19111912// Update early out fraction based on narrow phase collector1913if (!mCollector.mRejectAll)1914UpdateEarlyOutFraction(mCollector.GetEarlyOutFraction());1915}19161917const CCDBody & mCCDBody;1918const Body & mBody1;1919Vec3 mBody1Extent;1920RShapeCast mShapeCast;1921ShapeCastSettings & mShapeCastSettings;1922SimShapeFilterWrapper & mShapeFilter;1923CCDNarrowPhaseCollector & mCollector;1924const BodyManager & mBodyManager;1925PhysicsUpdateContext::Step *mStep;1926float mDeltaTime;1927};19281929// Create shape filter1930SimShapeFilterWrapperUnion shape_filter_union(mSimShapeFilter, &body);1931SimShapeFilterWrapper &shape_filter = shape_filter_union.GetSimShapeFilterWrapper();19321933// 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.1934RShapeCast shape_cast(body.GetShape(), Vec3::sOne(), body.GetCenterOfMassTransform(), ccd_body.mDeltaPosition);1935CCDBroadPhaseCollector bp_collector(ccd_body, body, shape_cast, settings, shape_filter, np_collector, mBodyManager, ioStep, ioContext->mStepDeltaTime);1936mBroadPhase->CastAABoxNoLock({ shape_cast.mShapeWorldBounds, shape_cast.mDirection }, bp_collector, broadphase_layer_filter, object_layer_filter);19371938// Check if there was a hit1939if (ccd_body.mFractionPlusSlop < 1.0f)1940{1941const Body &body2 = mBodyManager.GetBody(ccd_body.mBodyID2);19421943// Determine contact manifold1944ContactManifold manifold;1945manifold.mBaseOffset = shape_cast.mCenterOfMassStart.GetTranslation();1946ManifoldBetweenTwoFaces(cast_shape_result.mContactPointOn1, cast_shape_result.mContactPointOn2, cast_shape_result.mPenetrationAxis, mPhysicsSettings.mManifoldTolerance, cast_shape_result.mShape1Face, cast_shape_result.mShape2Face, manifold.mRelativeContactPointsOn1, manifold.mRelativeContactPointsOn2 JPH_IF_DEBUG_RENDERER(, manifold.mBaseOffset));1947manifold.mSubShapeID1 = cast_shape_result.mSubShapeID1;1948manifold.mSubShapeID2 = cast_shape_result.mSubShapeID2;1949manifold.mPenetrationDepth = cast_shape_result.mPenetrationDepth;1950manifold.mWorldSpaceNormal = ccd_body.mContactNormal;19511952// Call contact point callbacks1953mContactManager.OnCCDContactAdded(contact_allocator, body, body2, manifold, ccd_body.mContactSettings);19541955if (ccd_body.mContactSettings.mIsSensor)1956{1957// If this is a sensor, we don't want to solve the contact1958ccd_body.mFractionPlusSlop = 1.0f;1959ccd_body.mBodyID2 = BodyID();1960}1961else1962{1963// Calculate the average position from the manifold (this will result in the same impulse applied as when we apply impulses to all contact points)1964if (manifold.mRelativeContactPointsOn2.size() > 1)1965{1966Vec3 average_contact_point = Vec3::sZero();1967for (const Vec3 &v : manifold.mRelativeContactPointsOn2)1968average_contact_point += v;1969average_contact_point /= (float)manifold.mRelativeContactPointsOn2.size();1970ccd_body.mContactPointOn2 = manifold.mBaseOffset + average_contact_point;1971}1972else1973ccd_body.mContactPointOn2 = manifold.mBaseOffset + cast_shape_result.mContactPointOn2;1974}1975}1976}19771978// Collect information from the contact allocator and accumulate it in the step.1979sFinalizeContactAllocator(*ioStep, contact_allocator);1980}19811982void PhysicsSystem::JobResolveCCDContacts(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)1983{1984#ifdef JPH_ENABLE_ASSERTS1985// Read/write body access1986BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);19871988// We activate bodies that we collide with1989BodyManager::GrantActiveBodiesAccess grant_active(true, false);1990#endif19911992uint32 num_active_bodies_after_find_collisions = ioStep->mActiveBodyReadIdx;1993TempAllocator *temp_allocator = ioContext->mTempAllocator;19941995// Check if there's anything to do1996uint num_ccd_bodies = ioStep->mNumCCDBodies;1997if (num_ccd_bodies > 0)1998{1999// Sort on fraction so that we process earliest collisions first2000// This is needed to make the simulation deterministic and also to be able to stop contact processing2001// between body pairs if an earlier hit was found involving the body by another CCD body2002// (if it's body ID < this CCD body's body ID - see filtering logic in CCDBroadPhaseCollector)2003CCDBody **sorted_ccd_bodies = (CCDBody **)temp_allocator->Allocate(num_ccd_bodies * sizeof(CCDBody *));2004JPH_SCOPE_EXIT([temp_allocator, sorted_ccd_bodies, num_ccd_bodies]{ temp_allocator->Free(sorted_ccd_bodies, num_ccd_bodies * sizeof(CCDBody *)); });2005{2006JPH_PROFILE("Sort");20072008// We don't want to copy the entire struct (it's quite big), so we create a pointer array first2009CCDBody *src_ccd_bodies = ioStep->mCCDBodies;2010CCDBody **dst_ccd_bodies = sorted_ccd_bodies;2011CCDBody **dst_ccd_bodies_end = dst_ccd_bodies + num_ccd_bodies;2012while (dst_ccd_bodies < dst_ccd_bodies_end)2013*(dst_ccd_bodies++) = src_ccd_bodies++;20142015// Which we then sort2016QuickSort(sorted_ccd_bodies, sorted_ccd_bodies + num_ccd_bodies, [](const CCDBody *inBody1, const CCDBody *inBody2)2017{2018if (inBody1->mFractionPlusSlop != inBody2->mFractionPlusSlop)2019return inBody1->mFractionPlusSlop < inBody2->mFractionPlusSlop;20202021return inBody1->mBodyID1 < inBody2->mBodyID1;2022});2023}20242025// We can collide with bodies that are not active, we track them here so we can activate them in one go at the end.2026// This is also needed because we can't modify the active body array while we iterate it.2027static constexpr int cBodiesBatch = 64;2028BodyID *bodies_to_activate = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));2029int num_bodies_to_activate = 0;20302031// We can move bodies that are not part of an island. In this case we need to notify the broadphase of the movement.2032BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));2033int num_bodies_to_update_bounds = 0;20342035for (uint i = 0; i < num_ccd_bodies; ++i)2036{2037const CCDBody *ccd_body = sorted_ccd_bodies[i];2038Body &body1 = mBodyManager.GetBody(ccd_body->mBodyID1);2039MotionProperties *body_mp = body1.GetMotionProperties();20402041// If there was a hit2042if (!ccd_body->mBodyID2.IsInvalid())2043{2044Body &body2 = mBodyManager.GetBody(ccd_body->mBodyID2);20452046// Determine if the other body has a CCD body2047CCDBody *ccd_body2 = sGetCCDBody(body2, ioStep);2048if (ccd_body2 != nullptr)2049{2050JPH_ASSERT(ccd_body2->mBodyID2 != ccd_body->mBodyID1, "If we collided with another body, that other body should have ignored collisions with us!");20512052// Check if the other body found a hit that is further away2053if (ccd_body2->mFraction > ccd_body->mFraction)2054{2055// Reset the colliding body of the other CCD body. The other body will shorten its distance traveled and will not do any collision response (we'll do that).2056// This means that at this point we have triggered a contact point add/persist for our further hit by accident for the other body.2057// 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.2058ccd_body2->mBodyID2 = BodyID();2059ccd_body2->mFractionPlusSlop = ccd_body->mFraction;2060}2061}20622063// 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.2064// 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.2065if (ccd_body2 == nullptr || ccd_body2->mFraction >= ccd_body->mFraction)2066{2067const ContactSettings &contact_settings = ccd_body->mContactSettings;20682069// Calculate contact point velocity for body 12070Vec3 r1_plus_u = Vec3(ccd_body->mContactPointOn2 - (body1.GetCenterOfMassPosition() + ccd_body->mFraction * ccd_body->mDeltaPosition));2071Vec3 v1 = body1.GetPointVelocityCOM(r1_plus_u);20722073// Calculate inverse mass for body 12074float inv_m1 = contact_settings.mInvMassScale1 * body_mp->GetInverseMass();20752076if (body2.IsRigidBody())2077{2078// Calculate contact point velocity for body 22079Vec3 r2 = Vec3(ccd_body->mContactPointOn2 - body2.GetCenterOfMassPosition());2080Vec3 v2 = body2.GetPointVelocityCOM(r2);20812082// Calculate relative contact velocity2083Vec3 relative_velocity = v2 - v1;2084float normal_velocity = relative_velocity.Dot(ccd_body->mContactNormal);20852086// Calculate velocity bias due to restitution2087float normal_velocity_bias;2088if (contact_settings.mCombinedRestitution > 0.0f && normal_velocity < -mPhysicsSettings.mMinVelocityForRestitution)2089normal_velocity_bias = contact_settings.mCombinedRestitution * normal_velocity;2090else2091normal_velocity_bias = 0.0f;20922093// Get inverse mass of body 22094float inv_m2 = body2.GetMotionPropertiesUnchecked() != nullptr? contact_settings.mInvMassScale2 * body2.GetMotionPropertiesUnchecked()->GetInverseMassUnchecked() : 0.0f;20952096// Solve contact constraint2097AxisConstraintPart contact_constraint;2098contact_constraint.CalculateConstraintPropertiesWithMassOverride(body1, inv_m1, contact_settings.mInvInertiaScale1, r1_plus_u, body2, inv_m2, contact_settings.mInvInertiaScale2, r2, ccd_body->mContactNormal, normal_velocity_bias);2099contact_constraint.SolveVelocityConstraintWithMassOverride(body1, inv_m1, body2, inv_m2, ccd_body->mContactNormal, -FLT_MAX, FLT_MAX);21002101// Apply friction2102if (contact_settings.mCombinedFriction > 0.0f)2103{2104// Calculate friction direction by removing normal velocity from the relative velocity2105Vec3 friction_direction = relative_velocity - normal_velocity * ccd_body->mContactNormal;2106float friction_direction_len_sq = friction_direction.LengthSq();2107if (friction_direction_len_sq > 1.0e-12f)2108{2109// Normalize friction direction2110friction_direction /= sqrt(friction_direction_len_sq);21112112// Calculate max friction impulse2113float max_lambda_f = contact_settings.mCombinedFriction * contact_constraint.GetTotalLambda();21142115AxisConstraintPart friction;2116friction.CalculateConstraintPropertiesWithMassOverride(body1, inv_m1, contact_settings.mInvInertiaScale1, r1_plus_u, body2, inv_m2, contact_settings.mInvInertiaScale2, r2, friction_direction);2117friction.SolveVelocityConstraintWithMassOverride(body1, inv_m1, body2, inv_m2, friction_direction, -max_lambda_f, max_lambda_f);2118}2119}21202121// Clamp velocity of body 22122if (body2.IsDynamic())2123{2124MotionProperties *body2_mp = body2.GetMotionProperties();2125body2_mp->ClampLinearVelocity();2126body2_mp->ClampAngularVelocity();2127}2128}2129else2130{2131SoftBodyMotionProperties *soft_mp = static_cast<SoftBodyMotionProperties *>(body2.GetMotionProperties());2132const SoftBodyShape *soft_shape = static_cast<const SoftBodyShape *>(body2.GetShape());21332134// Convert the sub shape ID of the soft body to a face2135uint32 face_idx = soft_shape->GetFaceIndex(ccd_body->mSubShapeID2);2136const SoftBodyMotionProperties::Face &face = soft_mp->GetFace(face_idx);21372138// Get vertices of the face2139SoftBodyMotionProperties::Vertex &vtx0 = soft_mp->GetVertex(face.mVertex[0]);2140SoftBodyMotionProperties::Vertex &vtx1 = soft_mp->GetVertex(face.mVertex[1]);2141SoftBodyMotionProperties::Vertex &vtx2 = soft_mp->GetVertex(face.mVertex[2]);21422143// Inverse mass of the face2144float vtx0_mass = vtx0.mInvMass > 0.0f? 1.0f / vtx0.mInvMass : 1.0e10f;2145float vtx1_mass = vtx1.mInvMass > 0.0f? 1.0f / vtx1.mInvMass : 1.0e10f;2146float vtx2_mass = vtx2.mInvMass > 0.0f? 1.0f / vtx2.mInvMass : 1.0e10f;2147float inv_m2 = 1.0f / (vtx0_mass + vtx1_mass + vtx2_mass);21482149// Calculate barycentric coordinates of the contact point on the soft body's face2150float u, v, w;2151RMat44 inv_body2_transform = body2.GetInverseCenterOfMassTransform();2152Vec3 local_contact = Vec3(inv_body2_transform * ccd_body->mContactPointOn2);2153ClosestPoint::GetBaryCentricCoordinates(vtx0.mPosition - local_contact, vtx1.mPosition - local_contact, vtx2.mPosition - local_contact, u, v, w);21542155// Calculate contact point velocity for the face2156Vec3 v2 = inv_body2_transform.Multiply3x3Transposed(u * vtx0.mVelocity + v * vtx1.mVelocity + w * vtx2.mVelocity);2157float normal_velocity = (v2 - v1).Dot(ccd_body->mContactNormal);21582159// Calculate velocity bias due to restitution2160float normal_velocity_bias;2161if (contact_settings.mCombinedRestitution > 0.0f && normal_velocity < -mPhysicsSettings.mMinVelocityForRestitution)2162normal_velocity_bias = contact_settings.mCombinedRestitution * normal_velocity;2163else2164normal_velocity_bias = 0.0f;21652166// Calculate resulting velocity change (the math here is similar to AxisConstraintPart but without an inertia term for body 2 as we treat it as a point mass)2167Vec3 r1_plus_u_x_n = r1_plus_u.Cross(ccd_body->mContactNormal);2168Vec3 invi1_r1_plus_u_x_n = contact_settings.mInvInertiaScale1 * body1.GetInverseInertia().Multiply3x3(r1_plus_u_x_n);2169float jv = r1_plus_u_x_n.Dot(body_mp->GetAngularVelocity()) - normal_velocity - normal_velocity_bias;2170float inv_effective_mass = inv_m1 + inv_m2 + invi1_r1_plus_u_x_n.Dot(r1_plus_u_x_n);2171float lambda = jv / inv_effective_mass;2172body_mp->SubLinearVelocityStep((lambda * inv_m1) * ccd_body->mContactNormal);2173body_mp->SubAngularVelocityStep(lambda * invi1_r1_plus_u_x_n);2174Vec3 delta_v2 = inv_body2_transform.Multiply3x3(lambda * ccd_body->mContactNormal);2175vtx0.mVelocity += delta_v2 * vtx0.mInvMass;2176vtx1.mVelocity += delta_v2 * vtx1.mInvMass;2177vtx2.mVelocity += delta_v2 * vtx2.mInvMass;2178}21792180// Clamp velocity of body 12181body_mp->ClampLinearVelocity();2182body_mp->ClampAngularVelocity();21832184// Activate the 2nd body if it is not already active2185if (body2.IsDynamic() && !body2.IsActive())2186{2187bodies_to_activate[num_bodies_to_activate++] = ccd_body->mBodyID2;2188if (num_bodies_to_activate == cBodiesBatch)2189{2190// Batch is full, activate now2191mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);2192num_bodies_to_activate = 0;2193}2194}21952196#ifdef JPH_DEBUG_RENDERER2197if (sDrawMotionQualityLinearCast)2198{2199// Draw the collision location2200RMat44 collision_transform = body1.GetCenterOfMassTransform().PostTranslated(ccd_body->mFraction * ccd_body->mDeltaPosition);2201body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform, Vec3::sOne(), Color::sYellow, false, true);22022203// Draw the collision location + slop2204RMat44 collision_transform_plus_slop = body1.GetCenterOfMassTransform().PostTranslated(ccd_body->mFractionPlusSlop * ccd_body->mDeltaPosition);2205body1.GetShape()->Draw(DebugRenderer::sInstance, collision_transform_plus_slop, Vec3::sOne(), Color::sOrange, false, true);22062207// Draw contact normal2208DebugRenderer::sInstance->DrawArrow(ccd_body->mContactPointOn2, ccd_body->mContactPointOn2 - ccd_body->mContactNormal, Color::sYellow, 0.1f);22092210// Draw post contact velocity2211DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetLinearVelocity(), Color::sOrange, 0.1f);2212DebugRenderer::sInstance->DrawArrow(collision_transform.GetTranslation(), collision_transform.GetTranslation() + body1.GetAngularVelocity(), Color::sPurple, 0.1f);2213}2214#endif // JPH_DEBUG_RENDERER2215}2216}22172218// Update body position2219body1.AddPositionStep(ccd_body->mDeltaPosition * ccd_body->mFractionPlusSlop);22202221// If the body was activated due to an earlier CCD step it will have an index in the active2222// body list that it higher than the highest one we processed during FindCollisions2223// which means it hasn't been assigned an island and will not be updated by an island2224// this means that we need to update its bounds manually2225if (body_mp->GetIndexInActiveBodiesInternal() >= num_active_bodies_after_find_collisions)2226{2227body1.CalculateWorldSpaceBoundsInternal();2228bodies_to_update_bounds[num_bodies_to_update_bounds++] = body1.GetID();2229if (num_bodies_to_update_bounds == cBodiesBatch)2230{2231// Buffer full, flush now2232mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);2233num_bodies_to_update_bounds = 0;2234}2235}2236}22372238// Activate the requested bodies2239if (num_bodies_to_activate > 0)2240mBodyManager.ActivateBodies(bodies_to_activate, num_bodies_to_activate);22412242// Notify change bounds on requested bodies2243if (num_bodies_to_update_bounds > 0)2244mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);2245}22462247// Ensure we free the CCD bodies array now, will not call the destructor!2248temp_allocator->Free(ioStep->mActiveBodyToCCDBody, ioStep->mNumActiveBodyToCCDBody * sizeof(int));2249ioStep->mActiveBodyToCCDBody = nullptr;2250ioStep->mNumActiveBodyToCCDBody = 0;2251temp_allocator->Free(ioStep->mCCDBodies, ioStep->mCCDBodiesCapacity * sizeof(CCDBody));2252ioStep->mCCDBodies = nullptr;2253ioStep->mCCDBodiesCapacity = 0;2254}22552256void PhysicsSystem::JobContactRemovedCallbacks(const PhysicsUpdateContext::Step *ioStep)2257{2258#ifdef JPH_ENABLE_ASSERTS2259// We don't touch any bodies2260BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::None);2261#endif22622263// Reset the Body::EFlags::InvalidateContactCache flag for all bodies2264mBodyManager.ValidateContactCacheForAllBodies();22652266// Finalize the contact cache (this swaps the read and write versions of the contact cache)2267// Trigger all contact removed callbacks by looking at last step contact points that have not been flagged as reused2268mContactManager.FinalizeContactCacheAndCallContactPointRemovedCallbacks(ioStep->mNumBodyPairs, ioStep->mNumManifolds);2269}22702271class PhysicsSystem::BodiesToSleep : public NonCopyable2272{2273public:2274static constexpr int cBodiesToSleepSize = 512;2275static constexpr int cMaxBodiesToPutInBuffer = 128;22762277inline BodiesToSleep(BodyManager &inBodyManager, BodyID *inBodiesToSleepBuffer) : mBodyManager(inBodyManager), mBodiesToSleepBuffer(inBodiesToSleepBuffer), mBodiesToSleepCur(inBodiesToSleepBuffer) { }22782279inline ~BodiesToSleep()2280{2281// Flush the bodies to sleep buffer2282int num_bodies_in_buffer = int(mBodiesToSleepCur - mBodiesToSleepBuffer);2283if (num_bodies_in_buffer > 0)2284mBodyManager.DeactivateBodies(mBodiesToSleepBuffer, num_bodies_in_buffer);2285}22862287inline void PutToSleep(const BodyID *inBegin, const BodyID *inEnd)2288{2289int num_bodies_to_sleep = int(inEnd - inBegin);2290if (num_bodies_to_sleep > cMaxBodiesToPutInBuffer)2291{2292// Too many bodies, deactivate immediately2293mBodyManager.DeactivateBodies(inBegin, num_bodies_to_sleep);2294}2295else2296{2297// Check if there's enough space in the bodies to sleep buffer2298int num_bodies_in_buffer = int(mBodiesToSleepCur - mBodiesToSleepBuffer);2299if (num_bodies_in_buffer + num_bodies_to_sleep > cBodiesToSleepSize)2300{2301// Flush the bodies to sleep buffer2302mBodyManager.DeactivateBodies(mBodiesToSleepBuffer, num_bodies_in_buffer);2303mBodiesToSleepCur = mBodiesToSleepBuffer;2304}23052306// Copy the bodies in the buffer2307memcpy(mBodiesToSleepCur, inBegin, num_bodies_to_sleep * sizeof(BodyID));2308mBodiesToSleepCur += num_bodies_to_sleep;2309}2310}23112312private:2313BodyManager & mBodyManager;2314BodyID * mBodiesToSleepBuffer;2315BodyID * mBodiesToSleepCur;2316};23172318void PhysicsSystem::CheckSleepAndUpdateBounds(uint32 inIslandIndex, const PhysicsUpdateContext *ioContext, const PhysicsUpdateContext::Step *ioStep, BodiesToSleep &ioBodiesToSleep)2319{2320// Get the bodies that belong to this island2321BodyID *bodies_begin, *bodies_end;2322mIslandBuilder.GetBodiesInIsland(inIslandIndex, bodies_begin, bodies_end);23232324// Only check sleeping in the last step2325// Also resets force and torque used during the apply gravity phase2326if (ioStep->mIsLast)2327{2328JPH_PROFILE("Check Sleeping");23292330static_assert(int(ECanSleep::CannotSleep) == 0 && int(ECanSleep::CanSleep) == 1, "Loop below makes this assumption");2331int all_can_sleep = mPhysicsSettings.mAllowSleeping? int(ECanSleep::CanSleep) : int(ECanSleep::CannotSleep);23322333float time_before_sleep = mPhysicsSettings.mTimeBeforeSleep;2334float max_movement = mPhysicsSettings.mPointVelocitySleepThreshold * time_before_sleep;23352336for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)2337{2338Body &body = mBodyManager.GetBody(*body_id);23392340// Update bounding box2341body.CalculateWorldSpaceBoundsInternal();23422343// Update sleeping2344all_can_sleep &= int(body.UpdateSleepStateInternal(ioContext->mStepDeltaTime, max_movement, time_before_sleep));23452346// Reset force and torque2347MotionProperties *mp = body.GetMotionProperties();2348mp->ResetForce();2349mp->ResetTorque();2350}23512352// If all bodies indicate they can sleep we can deactivate them2353if (all_can_sleep == int(ECanSleep::CanSleep))2354ioBodiesToSleep.PutToSleep(bodies_begin, bodies_end);2355}2356else2357{2358JPH_PROFILE("Update Bounds");23592360// Update bounding box only for all other steps2361for (const BodyID *body_id = bodies_begin; body_id < bodies_end; ++body_id)2362{2363Body &body = mBodyManager.GetBody(*body_id);2364body.CalculateWorldSpaceBoundsInternal();2365}2366}23672368// Notify broadphase of changed objects (find ccd contacts can do linear casts in the next step, so we need to do this every step)2369// Note: Shuffles the BodyID's around!!!2370mBroadPhase->NotifyBodiesAABBChanged(bodies_begin, int(bodies_end - bodies_begin), false);2371}23722373void PhysicsSystem::JobSolvePositionConstraints(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)2374{2375#ifdef JPH_ENABLE_ASSERTS2376// We fix up position errors2377BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::ReadWrite);23782379// Can only deactivate bodies2380BodyManager::GrantActiveBodiesAccess grant_active(false, true);2381#endif23822383float delta_time = ioContext->mStepDeltaTime;2384float baumgarte = mPhysicsSettings.mBaumgarte;2385Constraint **active_constraints = ioContext->mActiveConstraints;23862387// Keep a buffer of bodies that need to go to sleep in order to not constantly lock the active bodies mutex and create contention between all solving threads2388BodiesToSleep bodies_to_sleep(mBodyManager, (BodyID *)JPH_STACK_ALLOC(BodiesToSleep::cBodiesToSleepSize * sizeof(BodyID)));23892390bool check_islands = true, check_split_islands = mPhysicsSettings.mUseLargeIslandSplitter;2391for (;;)2392{2393// First try to get work from large islands2394if (check_split_islands)2395{2396bool first_iteration;2397uint split_island_index;2398uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;2399switch (mLargeIslandSplitter.FetchNextBatch(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, first_iteration))2400{2401case LargeIslandSplitter::EStatus::BatchRetrieved:2402// Solve the batch2403ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);2404mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);24052406// Mark the batch as processed2407bool last_iteration, final_batch;2408mLargeIslandSplitter.MarkBatchProcessed(split_island_index, constraints_begin, constraints_end, contacts_begin, contacts_end, last_iteration, final_batch);24092410// The final batch will update all bounds and check sleeping2411if (final_batch)2412CheckSleepAndUpdateBounds(mLargeIslandSplitter.GetIslandIndex(split_island_index), ioContext, ioStep, bodies_to_sleep);24132414// We processed work, loop again2415continue;24162417case LargeIslandSplitter::EStatus::WaitingForBatch:2418break;24192420case LargeIslandSplitter::EStatus::AllBatchesDone:2421check_split_islands = false;2422break;2423}2424}24252426// If that didn't succeed try to process an island2427if (check_islands)2428{2429// Next island2430uint32 island_idx = ioStep->mSolvePositionConstraintsNextIsland++;2431if (island_idx >= mIslandBuilder.GetNumIslands())2432{2433// We processed all islands, stop checking islands2434check_islands = false;2435continue;2436}24372438JPH_PROFILE("Island");24392440// Get iterators for this island2441uint32 *constraints_begin, *constraints_end, *contacts_begin, *contacts_end;2442mIslandBuilder.GetConstraintsInIsland(island_idx, constraints_begin, constraints_end);2443mIslandBuilder.GetContactsInIsland(island_idx, contacts_begin, contacts_end);24442445// If this island is a large island, it will be picked up as a batch and we don't need to do anything here2446uint num_items = uint(constraints_end - constraints_begin) + uint(contacts_end - contacts_begin);2447if (mPhysicsSettings.mUseLargeIslandSplitter2448&& num_items >= LargeIslandSplitter::cLargeIslandTreshold)2449continue;24502451// Check if this island needs solving2452if (num_items > 0)2453{2454// Iterate2455uint num_position_steps = mIslandBuilder.GetNumPositionSteps(island_idx);2456for (uint position_step = 0; position_step < num_position_steps; ++position_step)2457{2458bool applied_impulse = ConstraintManager::sSolvePositionConstraints(active_constraints, constraints_begin, constraints_end, delta_time, baumgarte);2459applied_impulse |= mContactManager.SolvePositionConstraints(contacts_begin, contacts_end);2460if (!applied_impulse)2461break;2462}2463}24642465// After solving we will update all bounds and check sleeping2466CheckSleepAndUpdateBounds(island_idx, ioContext, ioStep, bodies_to_sleep);24672468// We processed work, loop again2469continue;2470}24712472if (check_islands)2473{2474// If there are islands, we don't need to wait and can pick up new work2475continue;2476}2477else if (check_split_islands)2478{2479// If there are split islands, but we didn't do any work, give up a time slice2480std::this_thread::yield();2481}2482else2483{2484// No more work2485break;2486}2487}2488}24892490void PhysicsSystem::JobSoftBodyPrepare(PhysicsUpdateContext *ioContext, PhysicsUpdateContext::Step *ioStep)2491{2492JPH_PROFILE_FUNCTION();24932494{2495#ifdef JPH_ENABLE_ASSERTS2496// Reading soft body positions2497BodyAccess::Grant grant(BodyAccess::EAccess::None, BodyAccess::EAccess::Read);2498#endif24992500// Get the active soft bodies2501BodyIDVector active_bodies;2502mBodyManager.GetActiveBodies(EBodyType::SoftBody, active_bodies);25032504// Quit if there are no active soft bodies2505if (active_bodies.empty())2506{2507// Kick the next step2508if (ioStep->mStartNextStep.IsValid())2509ioStep->mStartNextStep.RemoveDependency();2510return;2511}25122513// Sort to get a deterministic update order2514QuickSort(active_bodies.begin(), active_bodies.end());25152516// Allocate soft body contexts2517ioContext->mNumSoftBodies = (uint)active_bodies.size();2518ioContext->mSoftBodyUpdateContexts = (SoftBodyUpdateContext *)ioContext->mTempAllocator->Allocate(ioContext->mNumSoftBodies * sizeof(SoftBodyUpdateContext));25192520// Initialize soft body contexts2521for (SoftBodyUpdateContext *sb_ctx = ioContext->mSoftBodyUpdateContexts, *sb_ctx_end = ioContext->mSoftBodyUpdateContexts + ioContext->mNumSoftBodies; sb_ctx < sb_ctx_end; ++sb_ctx)2522{2523new (sb_ctx) SoftBodyUpdateContext;2524Body &body = mBodyManager.GetBody(active_bodies[sb_ctx - ioContext->mSoftBodyUpdateContexts]);2525SoftBodyMotionProperties *mp = static_cast<SoftBodyMotionProperties *>(body.GetMotionProperties());2526mp->InitializeUpdateContext(ioContext->mStepDeltaTime, body, *this, *sb_ctx);2527}2528}25292530// We're ready to collide the first soft body2531ioContext->mSoftBodyToCollide.store(0, memory_order_release);25322533// Determine number of jobs to spawn2534int num_soft_body_jobs = ioContext->GetMaxConcurrency();25352536// Create finalize job2537ioStep->mSoftBodyFinalize = ioContext->mJobSystem->CreateJob("SoftBodyFinalize", cColorSoftBodyFinalize, [ioContext, ioStep]()2538{2539ioContext->mPhysicsSystem->JobSoftBodyFinalize(ioContext);25402541// Kick the next step2542if (ioStep->mStartNextStep.IsValid())2543ioStep->mStartNextStep.RemoveDependency();2544}, num_soft_body_jobs); // depends on: soft body simulate2545ioContext->mBarrier->AddJob(ioStep->mSoftBodyFinalize);25462547// Create simulate jobs2548ioStep->mSoftBodySimulate.resize(num_soft_body_jobs);2549for (int i = 0; i < num_soft_body_jobs; ++i)2550ioStep->mSoftBodySimulate[i] = ioContext->mJobSystem->CreateJob("SoftBodySimulate", cColorSoftBodySimulate, [ioStep, i]()2551{2552ioStep->mContext->mPhysicsSystem->JobSoftBodySimulate(ioStep->mContext, i);25532554ioStep->mSoftBodyFinalize.RemoveDependency();2555}, num_soft_body_jobs); // depends on: soft body collide2556ioContext->mBarrier->AddJobs(ioStep->mSoftBodySimulate.data(), ioStep->mSoftBodySimulate.size());25572558// Create collision jobs2559ioStep->mSoftBodyCollide.resize(num_soft_body_jobs);2560for (int i = 0; i < num_soft_body_jobs; ++i)2561ioStep->mSoftBodyCollide[i] = ioContext->mJobSystem->CreateJob("SoftBodyCollide", cColorSoftBodyCollide, [ioContext, ioStep]()2562{2563ioContext->mPhysicsSystem->JobSoftBodyCollide(ioContext);25642565for (const JobHandle &h : ioStep->mSoftBodySimulate)2566h.RemoveDependency();2567}); // depends on: nothing2568ioContext->mBarrier->AddJobs(ioStep->mSoftBodyCollide.data(), ioStep->mSoftBodyCollide.size());2569}25702571void PhysicsSystem::JobSoftBodyCollide(PhysicsUpdateContext *ioContext) const2572{2573#ifdef JPH_ENABLE_ASSERTS2574// Reading rigid body positions and velocities2575BodyAccess::Grant grant(BodyAccess::EAccess::Read, BodyAccess::EAccess::Read);2576#endif25772578for (;;)2579{2580// Fetch the next soft body2581uint sb_idx = ioContext->mSoftBodyToCollide.fetch_add(1, std::memory_order_acquire);2582if (sb_idx >= ioContext->mNumSoftBodies)2583break;25842585// Do a broadphase check2586SoftBodyUpdateContext &sb_ctx = ioContext->mSoftBodyUpdateContexts[sb_idx];2587sb_ctx.mMotionProperties->DetermineCollidingShapes(sb_ctx, *this, GetBodyLockInterfaceNoLock());2588}2589}25902591void PhysicsSystem::JobSoftBodySimulate(PhysicsUpdateContext *ioContext, uint inThreadIndex) const2592{2593#ifdef JPH_ENABLE_ASSERTS2594// Updating velocities of soft bodies, allow the contact listener to read the soft body state2595BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::Read);2596#endif25972598// Calculate at which body we start to distribute the workload across the threads2599uint num_soft_bodies = ioContext->mNumSoftBodies;2600uint start_idx = inThreadIndex * num_soft_bodies / ioContext->GetMaxConcurrency();26012602// Keep running partial updates until everything has been updated2603uint status;2604do2605{2606// Reset status2607status = 0;26082609// Update all soft bodies2610for (uint i = 0; i < num_soft_bodies; ++i)2611{2612// Fetch the soft body context2613SoftBodyUpdateContext &sb_ctx = ioContext->mSoftBodyUpdateContexts[(start_idx + i) % num_soft_bodies];26142615// To avoid trashing the cache too much, we prefer to stick to one soft body until we cannot progress it any further2616uint sb_status;2617do2618{2619sb_status = (uint)sb_ctx.mMotionProperties->ParallelUpdate(sb_ctx, mPhysicsSettings);2620status |= sb_status;2621} while (sb_status == (uint)SoftBodyMotionProperties::EStatus::DidWork);2622}26232624// If we didn't perform any work, yield the thread so that something else can run2625if (!(status & (uint)SoftBodyMotionProperties::EStatus::DidWork))2626std::this_thread::yield();2627}2628while (status != (uint)SoftBodyMotionProperties::EStatus::Done);2629}26302631void PhysicsSystem::JobSoftBodyFinalize(PhysicsUpdateContext *ioContext)2632{2633#ifdef JPH_ENABLE_ASSERTS2634// Updating rigid body velocities and soft body positions / velocities2635BodyAccess::Grant grant(BodyAccess::EAccess::ReadWrite, BodyAccess::EAccess::ReadWrite);26362637// Can activate and deactivate bodies2638BodyManager::GrantActiveBodiesAccess grant_active(true, true);2639#endif26402641static constexpr int cBodiesBatch = 64;2642BodyID *bodies_to_update_bounds = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));2643int num_bodies_to_update_bounds = 0;2644BodyID *bodies_to_put_to_sleep = (BodyID *)JPH_STACK_ALLOC(cBodiesBatch * sizeof(BodyID));2645int num_bodies_to_put_to_sleep = 0;26462647for (SoftBodyUpdateContext *sb_ctx = ioContext->mSoftBodyUpdateContexts, *sb_ctx_end = ioContext->mSoftBodyUpdateContexts + ioContext->mNumSoftBodies; sb_ctx < sb_ctx_end; ++sb_ctx)2648{2649// Apply the rigid body velocity deltas2650sb_ctx->mMotionProperties->UpdateRigidBodyVelocities(*sb_ctx, GetBodyInterfaceNoLock());26512652// Update the position2653sb_ctx->mBody->SetPositionAndRotationInternal(sb_ctx->mBody->GetPosition() + sb_ctx->mDeltaPosition, sb_ctx->mBody->GetRotation(), false);26542655BodyID id = sb_ctx->mBody->GetID();2656bodies_to_update_bounds[num_bodies_to_update_bounds++] = id;2657if (num_bodies_to_update_bounds == cBodiesBatch)2658{2659// Buffer full, flush now2660mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);2661num_bodies_to_update_bounds = 0;2662}26632664if (sb_ctx->mCanSleep == ECanSleep::CanSleep)2665{2666// This body should go to sleep2667bodies_to_put_to_sleep[num_bodies_to_put_to_sleep++] = id;2668if (num_bodies_to_put_to_sleep == cBodiesBatch)2669{2670mBodyManager.DeactivateBodies(bodies_to_put_to_sleep, num_bodies_to_put_to_sleep);2671num_bodies_to_put_to_sleep = 0;2672}2673}2674}26752676// Notify change bounds on requested bodies2677if (num_bodies_to_update_bounds > 0)2678mBroadPhase->NotifyBodiesAABBChanged(bodies_to_update_bounds, num_bodies_to_update_bounds, false);26792680// Notify bodies to go to sleep2681if (num_bodies_to_put_to_sleep > 0)2682mBodyManager.DeactivateBodies(bodies_to_put_to_sleep, num_bodies_to_put_to_sleep);26832684// Free soft body contexts2685ioContext->mTempAllocator->Free(ioContext->mSoftBodyUpdateContexts, ioContext->mNumSoftBodies * sizeof(SoftBodyUpdateContext));2686}26872688void PhysicsSystem::SaveState(StateRecorder &inStream, EStateRecorderState inState, const StateRecorderFilter *inFilter) const2689{2690JPH_PROFILE_FUNCTION();26912692inStream.Write(inState);26932694if (uint8(inState) & uint8(EStateRecorderState::Global))2695{2696inStream.Write(mPreviousStepDeltaTime);2697inStream.Write(mGravity);2698}26992700if (uint8(inState) & uint8(EStateRecorderState::Bodies))2701mBodyManager.SaveState(inStream, inFilter);27022703if (uint8(inState) & uint8(EStateRecorderState::Contacts))2704mContactManager.SaveState(inStream, inFilter);27052706if (uint8(inState) & uint8(EStateRecorderState::Constraints))2707mConstraintManager.SaveState(inStream, inFilter);2708}27092710bool PhysicsSystem::RestoreState(StateRecorder &inStream, const StateRecorderFilter *inFilter)2711{2712JPH_PROFILE_FUNCTION();27132714EStateRecorderState state = EStateRecorderState::All; // Set this value for validation. If a partial state is saved, validation will not work anyway.2715inStream.Read(state);27162717if (uint8(state) & uint8(EStateRecorderState::Global))2718{2719inStream.Read(mPreviousStepDeltaTime);2720inStream.Read(mGravity);2721}27222723if (uint8(state) & uint8(EStateRecorderState::Bodies))2724{2725if (!mBodyManager.RestoreState(inStream))2726return false;27272728// Update bounding boxes for all bodies in the broadphase2729if (inStream.IsLastPart())2730{2731Array<BodyID> bodies;2732for (const Body *b : mBodyManager.GetBodies())2733if (BodyManager::sIsValidBodyPointer(b) && b->IsInBroadPhase())2734bodies.push_back(b->GetID());2735if (!bodies.empty())2736mBroadPhase->NotifyBodiesAABBChanged(&bodies[0], (int)bodies.size());2737}2738}27392740if (uint8(state) & uint8(EStateRecorderState::Contacts))2741{2742if (!mContactManager.RestoreState(inStream, inFilter))2743return false;2744}27452746if (uint8(state) & uint8(EStateRecorderState::Constraints))2747{2748if (!mConstraintManager.RestoreState(inStream))2749return false;2750}27512752return true;2753}27542755void PhysicsSystem::SaveBodyState(const Body &inBody, StateRecorder &inStream) const2756{2757mBodyManager.SaveBodyState(inBody, inStream);2758}27592760void PhysicsSystem::RestoreBodyState(Body &ioBody, StateRecorder &inStream)2761{2762mBodyManager.RestoreBodyState(ioBody, inStream);27632764BodyID id = ioBody.GetID();2765mBroadPhase->NotifyBodiesAABBChanged(&id, 1);2766}27672768JPH_NAMESPACE_END276927702771