file_path
stringlengths 21
207
| content
stringlengths 5
1.02M
| size
int64 5
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 1.33
100
| max_line_length
int64 4
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsSimpleIslandManager.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "common/PxProfileZone.h"
#include "PxsSimpleIslandManager.h"
#include "foundation/PxSort.h"
#include "PxsContactManager.h"
#include "CmTask.h"
#include "DyVArticulation.h"
#define IG_SANITY_CHECKS 0
using namespace physx;
using namespace IG;
ThirdPassTask::ThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager, IslandSim& islandSim) : Cm::Task(contextID), mIslandManager(islandManager), mIslandSim(islandSim)
{
}
PostThirdPassTask::PostThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager) : Cm::Task(contextID), mIslandManager(islandManager)
{
}
SimpleIslandManager::SimpleIslandManager(bool useEnhancedDeterminism, PxU64 contextID) :
mDestroyedNodes ("mDestroyedNodes"),
mDestroyedEdges ("mDestroyedEdges"),
mFirstPartitionEdges ("mFirstPartitionEdges"),
mDestroyedPartitionEdges ("IslandSim::mDestroyedPartitionEdges"),
mIslandManager (&mFirstPartitionEdges, mEdgeNodeIndices, &mDestroyedPartitionEdges, contextID),
mSpeculativeIslandManager (NULL, mEdgeNodeIndices, NULL, contextID),
mSpeculativeThirdPassTask (contextID, *this, mSpeculativeIslandManager),
mAccurateThirdPassTask (contextID, *this, mIslandManager),
mPostThirdPassTask (contextID, *this),
mContextID (contextID)
{
mFirstPartitionEdges.resize(1024);
mMaxDirtyNodesPerFrame = useEnhancedDeterminism ? 0xFFFFFFFF : 1000u;
}
SimpleIslandManager::~SimpleIslandManager()
{
}
PxNodeIndex SimpleIslandManager::addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addRigidBody(body, isKinematic, isActive, nodeIndex);
mSpeculativeIslandManager.addRigidBody(body, isKinematic, isActive, nodeIndex);
return nodeIndex;
}
void SimpleIslandManager::removeNode(const PxNodeIndex index)
{
PX_ASSERT(mNodeHandles.isValidHandle(index.index()));
mDestroyedNodes.pushBack(index);
}
PxNodeIndex SimpleIslandManager::addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addArticulation(llArtic, isActive, nodeIndex);
mSpeculativeIslandManager.addArticulation(llArtic, isActive, nodeIndex);
return nodeIndex;
}
#if PX_SUPPORT_GPU_PHYSX
PxNodeIndex SimpleIslandManager::addSoftBody(Dy::SoftBody* llSoftBody, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addSoftBody(llSoftBody, isActive, nodeIndex);
mSpeculativeIslandManager.addSoftBody(llSoftBody, isActive, nodeIndex);
return nodeIndex;
}
PxNodeIndex SimpleIslandManager::addFEMCloth(Dy::FEMCloth* llFEMCloth, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addFEMCloth(llFEMCloth, isActive, nodeIndex);
mSpeculativeIslandManager.addFEMCloth(llFEMCloth, isActive, nodeIndex);
return nodeIndex;
}
PxNodeIndex SimpleIslandManager::addParticleSystem(Dy::ParticleSystem* llParticleSystem, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addParticleSystem(llParticleSystem, isActive, nodeIndex);
mSpeculativeIslandManager.addParticleSystem(llParticleSystem, isActive, nodeIndex);
return nodeIndex;
}
PxNodeIndex SimpleIslandManager::addHairSystem(Dy::HairSystem* llHairSystem, bool isActive)
{
const PxU32 handle = mNodeHandles.getHandle();
const PxNodeIndex nodeIndex(handle);
mIslandManager.addHairSystem(llHairSystem, isActive, nodeIndex);
mSpeculativeIslandManager.addHairSystem(llHairSystem, isActive, nodeIndex);
return nodeIndex;
}
#endif //PX_SUPPORT_GPU_PHYSX
EdgeIndex SimpleIslandManager::addContactManager(PxsContactManager* manager, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction, Edge::EdgeType edgeType)
{
const EdgeIndex handle = mEdgeHandles.getHandle();
const PxU32 nodeIds = 2 * handle;
if (mEdgeNodeIndices.size() == nodeIds)
{
PX_PROFILE_ZONE("ReserveEdges", getContextId());
const PxU32 newSize = nodeIds + 2048;
mEdgeNodeIndices.resize(newSize);
mConstraintOrCm.resize(newSize);
mInteractions.resize(newSize);
}
mEdgeNodeIndices[nodeIds] = nodeHandle1;
mEdgeNodeIndices[nodeIds+1] = nodeHandle2;
mConstraintOrCm[handle] = manager;
mInteractions[handle] = interaction;
mSpeculativeIslandManager.addConnection(nodeHandle1, nodeHandle2, edgeType, handle);
if (manager)
manager->getWorkUnit().mEdgeIndex = handle;
if (mConnectedMap.size() == handle)
mConnectedMap.resize(2 * (handle + 1));
if (mFirstPartitionEdges.capacity() == handle)
mFirstPartitionEdges.resize(2 * (handle + 1));
mConnectedMap.reset(handle);
return handle;
}
EdgeIndex SimpleIslandManager::addConstraint(Dy::Constraint* constraint, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction)
{
const EdgeIndex handle = mEdgeHandles.getHandle();
const PxU32 nodeIds = 2 * handle;
if (mEdgeNodeIndices.size() == nodeIds)
{
const PxU32 newSize = nodeIds + 2048;
mEdgeNodeIndices.resize(newSize);
mConstraintOrCm.resize(newSize);
mInteractions.resize(newSize);
}
mEdgeNodeIndices[nodeIds] = nodeHandle1;
mEdgeNodeIndices[nodeIds + 1] = nodeHandle2;
mConstraintOrCm[handle] = constraint;
mInteractions[handle] = interaction;
mIslandManager.addConstraint(constraint, nodeHandle1, nodeHandle2, handle);
mSpeculativeIslandManager.addConstraint(constraint, nodeHandle1, nodeHandle2, handle);
if(mConnectedMap.size() == handle)
mConnectedMap.resize(2*(mConnectedMap.size()+1));
if (mFirstPartitionEdges.capacity() == handle)
mFirstPartitionEdges.resize(2 * (mFirstPartitionEdges.capacity() + 1));
mConnectedMap.set(handle);
return handle;
}
void SimpleIslandManager::activateNode(PxNodeIndex index)
{
mIslandManager.activateNode(index);
mSpeculativeIslandManager.activateNode(index);
}
void SimpleIslandManager::deactivateNode(PxNodeIndex index)
{
mIslandManager.deactivateNode(index);
mSpeculativeIslandManager.deactivateNode(index);
}
void SimpleIslandManager::putNodeToSleep(PxNodeIndex index)
{
mIslandManager.putNodeToSleep(index);
mSpeculativeIslandManager.putNodeToSleep(index);
}
void SimpleIslandManager::removeConnection(EdgeIndex edgeIndex)
{
if(edgeIndex == IG_INVALID_EDGE)
return;
mDestroyedEdges.pushBack(edgeIndex);
mSpeculativeIslandManager.removeConnection(edgeIndex);
if(mConnectedMap.test(edgeIndex))
{
mIslandManager.removeConnection(edgeIndex);
mConnectedMap.reset(edgeIndex);
}
mConstraintOrCm[edgeIndex] = NULL;
mInteractions[edgeIndex] = NULL;
}
void SimpleIslandManager::firstPassIslandGen()
{
PX_PROFILE_ZONE("Basic.firstPassIslandGen", getContextId());
mSpeculativeIslandManager.clearDeactivations();
mSpeculativeIslandManager.wakeIslands();
mSpeculativeIslandManager.processNewEdges();
mSpeculativeIslandManager.removeDestroyedEdges();
mSpeculativeIslandManager.processLostEdges(mDestroyedNodes, false, false, mMaxDirtyNodesPerFrame);
}
void SimpleIslandManager::additionalSpeculativeActivation()
{
mSpeculativeIslandManager.wakeIslands2();
}
void SimpleIslandManager::secondPassIslandGen()
{
PX_PROFILE_ZONE("Basic.secondPassIslandGen", getContextId());
mIslandManager.wakeIslands();
mIslandManager.processNewEdges();
mIslandManager.removeDestroyedEdges();
mIslandManager.processLostEdges(mDestroyedNodes, false, false, mMaxDirtyNodesPerFrame);
for(PxU32 a = 0; a < mDestroyedNodes.size(); ++a)
mNodeHandles.freeHandle(mDestroyedNodes[a].index());
mDestroyedNodes.clear();
//mDestroyedEdges.clear();
}
bool SimpleIslandManager::validateDeactivations() const
{
//This method sanity checks the deactivations produced by third-pass island gen. Specifically, it ensures that any bodies that
//the speculative IG wants to deactivate are also candidates for deactivation in the accurate island gen. In practice, both should be the case. If this fails, something went wrong...
const PxNodeIndex* const nodeIndices = mSpeculativeIslandManager.getNodesToDeactivate(Node::eRIGID_BODY_TYPE);
const PxU32 nbNodesToDeactivate = mSpeculativeIslandManager.getNbNodesToDeactivate(Node::eRIGID_BODY_TYPE);
for(PxU32 i = 0; i < nbNodesToDeactivate; ++i)
{
//Node is active in accurate sim => mismatch between accurate and inaccurate sim!
const Node& node = mIslandManager.getNode(nodeIndices[i]);
const Node& speculativeNode = mSpeculativeIslandManager.getNode(nodeIndices[i]);
//KS - we need to verify that the bodies in the "deactivating" list are still candidates for deactivation. There are cases where they may not no longer be candidates, e.g. if the application
//put bodies to sleep and activated them
if(node.isActive() && !speculativeNode.isActive())
return false;
}
return true;
}
void ThirdPassTask::runInternal()
{
PX_PROFILE_ZONE("Basic.thirdPassIslandGen", mIslandSim.getContextId());
mIslandSim.removeDestroyedEdges();
mIslandSim.processLostEdges(mIslandManager.mDestroyedNodes, true, true, mIslandManager.mMaxDirtyNodesPerFrame);
}
void PostThirdPassTask::runInternal()
{
for (PxU32 a = 0; a < mIslandManager.mDestroyedNodes.size(); ++a)
mIslandManager.mNodeHandles.freeHandle(mIslandManager.mDestroyedNodes[a].index());
mIslandManager.mDestroyedNodes.clear();
for (PxU32 a = 0; a < mIslandManager.mDestroyedEdges.size(); ++a)
mIslandManager.mEdgeHandles.freeHandle(mIslandManager.mDestroyedEdges[a]);
mIslandManager.mDestroyedEdges.clear();
PX_ASSERT(mIslandManager.validateDeactivations());
}
void SimpleIslandManager::thirdPassIslandGen(PxBaseTask* continuation)
{
mIslandManager.clearDeactivations();
mPostThirdPassTask.setContinuation(continuation);
mSpeculativeThirdPassTask.setContinuation(&mPostThirdPassTask);
mAccurateThirdPassTask.setContinuation(&mPostThirdPassTask);
mSpeculativeThirdPassTask.removeReference();
mAccurateThirdPassTask.removeReference();
mPostThirdPassTask.removeReference();
//PX_PROFILE_ZONE("Basic.thirdPassIslandGen", getContextId());
//mSpeculativeIslandManager.removeDestroyedEdges();
//mSpeculativeIslandManager.processLostEdges(mDestroyedNodes, true, true);
//mIslandManager.removeDestroyedEdges();
//mIslandManager.processLostEdges(mDestroyedNodes, true, true);
}
bool SimpleIslandManager::checkInternalConsistency()
{
return mIslandManager.checkInternalConsistency() && mSpeculativeIslandManager.checkInternalConsistency();
}
void SimpleIslandManager::setEdgeConnected(EdgeIndex edgeIndex, Edge::EdgeType edgeType)
{
if(!mConnectedMap.test(edgeIndex))
{
mIslandManager.addConnection(mEdgeNodeIndices[edgeIndex * 2], mEdgeNodeIndices[edgeIndex * 2 + 1], edgeType, edgeIndex);
mConnectedMap.set(edgeIndex);
}
}
bool SimpleIslandManager::getIsEdgeConnected(EdgeIndex edgeIndex)
{
return !!mConnectedMap.test(edgeIndex);
}
void SimpleIslandManager::deactivateEdge(const EdgeIndex edgeIndex)
{
if (mFirstPartitionEdges[edgeIndex])
{
mDestroyedPartitionEdges.pushBack(mFirstPartitionEdges[edgeIndex]);
mFirstPartitionEdges[edgeIndex] = NULL;
}
}
void SimpleIslandManager::setEdgeDisconnected(EdgeIndex edgeIndex)
{
if(mConnectedMap.test(edgeIndex))
{
//PX_ASSERT(!mIslandManager.getEdge(edgeIndex).isInDirtyList());
mIslandManager.removeConnection(edgeIndex);
mConnectedMap.reset(edgeIndex);
}
}
void SimpleIslandManager::setEdgeRigidCM(const EdgeIndex edgeIndex, PxsContactManager* cm)
{
mConstraintOrCm[edgeIndex] = cm;
cm->getWorkUnit().mEdgeIndex = edgeIndex;
}
void SimpleIslandManager::clearEdgeRigidCM(const EdgeIndex edgeIndex)
{
mConstraintOrCm[edgeIndex] = NULL;
if (mFirstPartitionEdges[edgeIndex])
{
//this is the partition edges created/updated by the gpu solver
mDestroyedPartitionEdges.pushBack(mFirstPartitionEdges[edgeIndex]);
mFirstPartitionEdges[edgeIndex] = NULL;
}
}
void SimpleIslandManager::setKinematic(PxNodeIndex nodeIndex)
{
mIslandManager.setKinematic(nodeIndex);
mSpeculativeIslandManager.setKinematic(nodeIndex);
}
void SimpleIslandManager::setDynamic(PxNodeIndex nodeIndex)
{
mIslandManager.setDynamic(nodeIndex);
mSpeculativeIslandManager.setDynamic(nodeIndex);
}
| 13,879 | C++ | 34.228426 | 192 | 0.797824 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsContactManager.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxsContactManager.h"
using namespace physx;
PxsContactManager::PxsContactManager(PxsContext*, PxU32 index)
{
mFlags = 0;
// PT: TODO: any reason why we don't initialize all members here, e.g. shapeCore pointers?
mNpUnit.index = index;
mNpUnit.rigidCore0 = NULL;
mNpUnit.rigidCore1 = NULL;
mNpUnit.restDistance = 0;
mNpUnit.dominance0 = 1u;
mNpUnit.dominance1 = 1u;
mNpUnit.frictionDataPtr = NULL;
mNpUnit.frictionPatchCount = 0;
}
PxsContactManager::~PxsContactManager()
{
}
void PxsContactManager::setCCD(bool enable)
{
PxU32 flags = mFlags & (~PXS_CM_CCD_CONTACT);
if (enable)
flags |= PXS_CM_CCD_LINEAR;
else
flags &= ~PXS_CM_CCD_LINEAR;
mFlags = flags;
}
| 2,405 | C++ | 37.190476 | 91 | 0.75052 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsNphaseImplementationContext.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxsContext.h"
#include "CmFlushPool.h"
#include "PxsSimpleIslandManager.h"
#include "common/PxProfileZone.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
#endif
#include "PxsContactManagerState.h"
#include "PxsNphaseImplementationContext.h"
#include "PxvGeometry.h"
#include "PxvDynamics.h"
#include "PxvGlobals.h"
#include "PxcNpContactPrepShared.h"
using namespace physx;
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4324)
#endif
class PxsCMUpdateTask : public Cm::Task
{
public:
static const PxU32 BATCH_SIZE = 128;
//static const PxU32 BATCH_SIZE = 32;
PxsCMUpdateTask(PxsContext* context, PxReal dt, PxsContactManager** cmArray, PxsContactManagerOutput* cmOutputs, Gu::Cache* caches, PxU32 cmCount, PxContactModifyCallback* callback) :
Cm::Task (context->getContextId()),
mCmArray (cmArray),
mCmOutputs (cmOutputs),
mCaches (caches),
mContext (context),
mCallback (callback),
mCmCount (cmCount),
mDt (dt),
mNbPatchChanged(0)
{
}
virtual void release();
/*PX_FORCE_INLINE void insert(PxsContactManager* cm)
{
PX_ASSERT(mCmCount < BATCH_SIZE);
mCmArray[mCmCount++]=cm;
}*/
public:
//PxsContactManager* mCmArray[BATCH_SIZE];
PxsContactManager** mCmArray;
PxsContactManagerOutput* mCmOutputs;
Gu::Cache* mCaches;
PxsContext* mContext;
PxContactModifyCallback* mCallback;
PxU32 mCmCount;
PxReal mDt; //we could probably retrieve from context to save space?
PxU32 mNbPatchChanged;
PxsContactManagerOutputCounts mPatchChangedOutputCounts[BATCH_SIZE];
PxsContactManager* mPatchChangedCms[BATCH_SIZE];
};
#if PX_VC
#pragma warning(pop)
#endif
void PxsCMUpdateTask::release()
{
// We used to do Task::release(); here before fixing DE1106 (xbox pure virtual crash)
// Release in turn causes the dependent tasks to start running
// The problem was that between the time release was called and by the time we got to the destructor
// The task chain would get all the way to scene finalization code which would reset the allocation pool
// And a new task would get allocated at the same address, then we would invoke the destructor on that freshly created task
// This could potentially cause any number of other problems, it is suprising that it only manifested itself
// as a pure virtual crash
PxBaseTask* saveContinuation = mCont;
this->~PxsCMUpdateTask();
if (saveContinuation)
saveContinuation->removeReference();
}
static const bool gUseNewTaskAllocationScheme = false;
class PxsCMDiscreteUpdateTask : public PxsCMUpdateTask
{
public:
PxsCMDiscreteUpdateTask(PxsContext* context, PxReal dt, PxsContactManager** cms, PxsContactManagerOutput* cmOutputs, Gu::Cache* caches, PxU32 nbCms,
PxContactModifyCallback* callback):
PxsCMUpdateTask(context, dt, cms, cmOutputs, caches, nbCms, callback)
{}
virtual ~PxsCMDiscreteUpdateTask()
{}
void runModifiableContactManagers(PxU32* modifiableIndices, PxU32 nbModifiableManagers, PxcNpThreadContext& threadContext, PxU32& maxPatches_)
{
PX_ASSERT(nbModifiableManagers != 0);
PxU32 maxPatches = maxPatches_;
class PxcContactSet: public PxContactSet
{
public:
PxcContactSet(PxU32 count, PxModifiableContact *contacts)
{
mContacts = contacts;
mCount = count;
}
PxModifiableContact* getContacts() { return mContacts; }
PxU32 getCount() { return mCount; }
};
if(mCallback)
{
PX_ALLOCA(mModifiablePairArray, PxContactModifyPair, nbModifiableManagers);
PxsTransformCache& transformCache = mContext->getTransformCache();
for(PxU32 i = 0; i < nbModifiableManagers; ++i)
{
PxU32 index = modifiableIndices[i];
PxsContactManager& cm = *mCmArray[index];
PxsContactManagerOutput& output = mCmOutputs[index];
PxU32 count = output.nbContacts;
if(count)
{
PxContactModifyPair& p = mModifiablePairArray[i];
PxcNpWorkUnit &unit = cm.getWorkUnit();
p.shape[0] = gPxvOffsetTable.convertPxsShape2Px(unit.shapeCore0);
p.shape[1] = gPxvOffsetTable.convertPxsShape2Px(unit.shapeCore1);
p.actor[0] = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(unit.rigidCore0)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(unit.rigidCore0);
p.actor[1] = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(unit.rigidCore1)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(unit.rigidCore1);
p.transform[0] = transformCache.getTransformCache(unit.mTransformCache0).transform;
p.transform[1] = transformCache.getTransformCache(unit.mTransformCache1).transform;
PxModifiableContact* contacts = reinterpret_cast<PxModifiableContact*>(output.contactPoints);
static_cast<PxcContactSet&>(p.contacts) = PxcContactSet(count, contacts);
PxReal mi0 = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0) ? static_cast<const PxsBodyCore*>(unit.rigidCore0)->maxContactImpulse : PX_MAX_F32;
PxReal mi1 = unit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1) ? static_cast<const PxsBodyCore*>(unit.rigidCore1)->maxContactImpulse : PX_MAX_F32;
PxReal maxImpulse = PxMin(mi0, mi1);
for (PxU32 j = 0; j < count; j++)
contacts[j].maxImpulse = maxImpulse;
#if PX_ENABLE_SIM_STATS
PxU8 gt0 = PxTo8(unit.geomType0), gt1 = PxTo8(unit.geomType1);
threadContext.mModifiedContactPairs[PxMin(gt0, gt1)][PxMax(gt0, gt1)]++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
}
mCallback->onContactModify(mModifiablePairArray, nbModifiableManagers);
}
for(PxU32 i = 0; i < nbModifiableManagers; ++i)
{
PxU32 index = modifiableIndices[i];
PxsContactManager& cm = *mCmArray[index];
//Loop through the contacts in the contact stream and update contact count!
PxU32 numContacts = 0;
PxcNpWorkUnit& unit = cm.getWorkUnit();
PxsContactManagerOutput& output = mCmOutputs[index];
PxU32 numPatches = output.nbPatches;
if (output.nbContacts)
{
//PxU8* compressedContacts = cm.getWorkUnit().compressedContacts;
//PxModifyContactHeader* header = reinterpret_cast<PxModifyContactHeader*>(compressedContacts);
PxContactPatch* patches = reinterpret_cast<PxContactPatch*>(output.contactPatches);
PxModifiableContact* points = reinterpret_cast<PxModifiableContact*>(output.contactPoints);
if (patches->internalFlags & PxContactPatch::eREGENERATE_PATCHES)
{
//Some data was modified that must trigger patch re-generation...
for (PxU8 k = 0; k < numPatches; ++k)
{
PxU32 startIndex = patches[k].startContactIndex;
patches[k].normal = points[startIndex].normal;
patches[k].dynamicFriction = points[startIndex].dynamicFriction;
patches[k].staticFriction = points[startIndex].staticFriction;
patches[k].restitution = points[startIndex].restitution;
for (PxU32 j = 1; j < patches[k].nbContacts; ++j)
{
if (points[startIndex].normal.dot(points[j + startIndex].normal) < PXC_SAME_NORMAL
&& points[j + startIndex].maxImpulse > 0.f) //TODO - this needs extending for material indices but we don't support modifying those yet
{
//The points are now in a separate friction patch...
// Shift all patches above index k up by one to make space
for (PxU32 c = numPatches - 1; c > k; --c)
{
patches[c + 1] = patches[c];
}
numPatches++;
patches[k + 1].materialFlags = patches[k].materialFlags;
patches[k + 1].internalFlags = patches[k].internalFlags;
patches[k + 1].startContactIndex = PxTo8(j + startIndex);
patches[k + 1].nbContacts = PxTo8(patches[k].nbContacts - j);
//Fill in patch information now that final patches are available
patches[k].nbContacts = PxU8(j);
break; // we're done with all contacts in patch k because the remaining were just transferrred to patch k+1
}
}
}
}
maxPatches = PxMax(maxPatches, PxU32(numPatches));
output.nbPatches = PxU8(numPatches);
for (PxU32 a = 0; a < output.nbContacts; ++a)
{
numContacts += points[a].maxImpulse != 0.f;
}
}
if (!numContacts)
{
output.nbPatches = 0;
output.nbContacts = 0;
}
if(output.nbPatches != output.prevPatches)
{
mPatchChangedCms[mNbPatchChanged] = &cm;
PxsContactManagerOutputCounts& counts = mPatchChangedOutputCounts[mNbPatchChanged++];
counts.nbPatches = PxU8(numPatches);
counts.prevPatches = output.prevPatches;
counts.statusFlag = output.statusFlag;
//counts.nbContacts = output.nbContacts16;
}
if(!numContacts)
{
//KS - we still need to retain the patch count from the previous frame to detect found/lost events...
unit.clearCachedState();
continue;
}
if(threadContext.mContactStreamPool)
{
//We need to allocate a new structure inside the contact stream pool
PxU32 patchSize = output.nbPatches * sizeof(PxContactPatch);
PxU32 contactSize = output.nbContacts * sizeof(PxExtendedContact);
/*PxI32 increment = (PxI32)(patchSize + contactSize);
PxI32 index = PxAtomicAdd(&mContactStreamPool->mSharedContactIndex, increment) - increment;
PxU8* address = mContactStreamPool->mContactStream + index;*/
bool isOverflown = false;
PxI32 contactIncrement = PxI32(contactSize);
PxI32 contactIndex = PxAtomicAdd(&threadContext.mContactStreamPool->mSharedDataIndex, contactIncrement);
if (threadContext.mContactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
PxU8* contactAddress = threadContext.mContactStreamPool->mDataStream + threadContext.mContactStreamPool->mDataStreamSize - contactIndex;
PxI32 patchIncrement = PxI32(patchSize);
PxI32 patchIndex = PxAtomicAdd(&threadContext.mPatchStreamPool->mSharedDataIndex, patchIncrement);
if (threadContext.mPatchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
PxU8* patchAddress = threadContext.mPatchStreamPool->mDataStream + threadContext.mPatchStreamPool->mDataStreamSize - patchIndex;
PxU32 internalFlags = reinterpret_cast<PxContactPatch*>(output.contactPatches)->internalFlags;
PxI32 increment2 = PxI32(output.nbContacts * sizeof(PxReal));
PxI32 index2 = PxAtomicAdd(&threadContext.mForceAndIndiceStreamPool->mSharedDataIndex, increment2);
if (threadContext.mForceAndIndiceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
if (isOverflown)
{
output.contactPoints = NULL;
output.contactPatches = NULL;
output.contactForces = NULL;
output.nbContacts = output.nbPatches = 0;
}
else
{
output.contactForces = reinterpret_cast<PxReal*>(threadContext.mForceAndIndiceStreamPool->mDataStream + threadContext.mForceAndIndiceStreamPool->mDataStreamSize - index2);
PxMemZero(output.contactForces, sizeof(PxReal) * output.nbContacts);
PxExtendedContact* contacts = reinterpret_cast<PxExtendedContact*>(contactAddress);
PxMemCopy(patchAddress, output.contactPatches, sizeof(PxContactPatch) * output.nbPatches);
PxContactPatch* newPatches = reinterpret_cast<PxContactPatch*>(patchAddress);
internalFlags |= PxContactPatch::eCOMPRESSED_MODIFIED_CONTACT;
for(PxU32 a = 0; a < output.nbPatches; ++a)
{
newPatches[a].internalFlags = PxU8(internalFlags);
}
//KS - only the first patch will have mass modification properties set. For the GPU solver, this must be propagated to the remaining patches
for(PxU32 a = 1; a < output.nbPatches; ++a)
{
newPatches[a].mMassModification = newPatches->mMassModification;
}
PxModifiableContact* sourceContacts = reinterpret_cast<PxModifiableContact*>(output.contactPoints);
for(PxU32 a = 0; a < output.nbContacts; ++a)
{
PxExtendedContact& contact = contacts[a];
PxModifiableContact& srcContact = sourceContacts[a];
contact.contact = srcContact.contact;
contact.separation = srcContact.separation;
contact.targetVelocity = srcContact.targetVelocity;
contact.maxImpulse = srcContact.maxImpulse;
}
output.contactPatches = patchAddress;
output.contactPoints = reinterpret_cast<PxU8*>(contacts);
}
}
}
maxPatches_ = maxPatches;
}
template < void (*NarrowPhase)(PxcNpThreadContext&, const PxcNpWorkUnit&, Gu::Cache&, PxsContactManagerOutput&, PxU64)>
void processCms(PxcNpThreadContext* threadContext)
{
const PxU64 contextID = mContext->getContextId();
//PX_PROFILE_ZONE("processCms", mContext->getContextId());
// PT: use local variables to avoid reading class members N times, if possible
const PxU32 nb = mCmCount;
PxsContactManager** PX_RESTRICT cmArray = mCmArray;
PxU32 maxPatches = threadContext->mMaxPatches;
PxU32 newTouchCMCount = 0, lostTouchCMCount = 0;
PxBitMap& localChangeTouchCM = threadContext->getLocalChangeTouch();
PX_ALLOCA(modifiableIndices, PxU32, nb);
PxU32 modifiableCount = 0;
for(PxU32 i=0;i<nb;i++)
{
const PxU32 prefetch1 = PxMin(i + 1, nb - 1);
const PxU32 prefetch2 = PxMin(i + 2, nb - 1);
PxPrefetchLine(cmArray[prefetch2]);
PxPrefetchLine(&mCmOutputs[prefetch2]);
PxPrefetchLine(cmArray[prefetch1]->getWorkUnit().shapeCore0);
PxPrefetchLine(cmArray[prefetch1]->getWorkUnit().shapeCore1);
PxPrefetchLine(&threadContext->mTransformCache->getTransformCache(cmArray[prefetch1]->getWorkUnit().mTransformCache0));
PxPrefetchLine(&threadContext->mTransformCache->getTransformCache(cmArray[prefetch1]->getWorkUnit().mTransformCache1));
PxsContactManager* const cm = cmArray[i];
if(cm)
{
PxsContactManagerOutput& output = mCmOutputs[i];
PxcNpWorkUnit& unit = cm->getWorkUnit();
output.prevPatches = output.nbPatches;
PxU8 oldStatusFlag = output.statusFlag;
PxU8 oldTouch = PxTo8(oldStatusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH);
Gu::Cache& cache = mCaches[i];
NarrowPhase(*threadContext, unit, cache, output, contextID);
PxU16 newTouch = PxTo8(output.statusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH);
bool modifiable = output.nbPatches != 0 && unit.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT;
if(modifiable)
{
modifiableIndices[modifiableCount++] = i;
}
else
{
maxPatches = PxMax(maxPatches, PxTo32(output.nbPatches));
if(output.prevPatches != output.nbPatches)
{
mPatchChangedCms[mNbPatchChanged] = cm;
PxsContactManagerOutputCounts& counts = mPatchChangedOutputCounts[mNbPatchChanged++];
counts.nbPatches = output.nbPatches;
counts.prevPatches = output.prevPatches;
counts.statusFlag = output.statusFlag;
//counts.nbContacts = output.nbContacts;
}
}
if (newTouch ^ oldTouch)
{
unit.statusFlags = PxU8(output.statusFlag | (unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)); //KS - todo - remove the need to access the work unit at all!
localChangeTouchCM.growAndSet(cmArray[i]->getIndex());
if(newTouch)
newTouchCMCount++;
else
lostTouchCMCount++;
}
else if (!(oldStatusFlag&PxsContactManagerStatusFlag::eTOUCH_KNOWN))
{
unit.statusFlags = PxU8(output.statusFlag | (unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)); //KS - todo - remove the need to access the work unit at all!
}
}
}
if(modifiableCount)
runModifiableContactManagers(modifiableIndices, modifiableCount, *threadContext, maxPatches);
threadContext->addLocalNewTouchCount(newTouchCMCount);
threadContext->addLocalLostTouchCount(lostTouchCMCount);
threadContext->mMaxPatches = maxPatches;
}
virtual void runInternal()
{
PX_PROFILE_ZONE("Sim.narrowPhase", mContext->getContextId());
PxcNpThreadContext* PX_RESTRICT threadContext = mContext->getNpThreadContext();
threadContext->mDt = mDt;
const bool pcm = mContext->getPCM();
threadContext->mPCM = pcm;
threadContext->mCreateAveragePoint = mContext->getCreateAveragePoint();
threadContext->mContactCache = mContext->getContactCacheFlag();
threadContext->mTransformCache = &mContext->getTransformCache();
threadContext->mContactDistances = mContext->getContactDistances();
if(pcm)
processCms<PxcDiscreteNarrowPhasePCM>(threadContext);
else
processCms<PxcDiscreteNarrowPhase>(threadContext);
mContext->putNpThreadContext(threadContext);
}
virtual const char* getName() const
{
return "PxsContext.contactManagerDiscreteUpdate";
}
};
static void processContactManagers(PxsContext& context, PxsContactManagers& narrowPhasePairs, PxArray<PxsCMDiscreteUpdateTask*>& tasks, PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation, PxContactModifyCallback* modifyCallback)
{
Cm::FlushPool& taskPool = context.getTaskPool();
//Iterate all active contact managers
taskPool.lock();
/*const*/ PxU32 nbCmsToProcess = narrowPhasePairs.mContactManagerMapping.size();
// PT: TASK-CREATION TAG
if(!gUseNewTaskAllocationScheme)
{
for(PxU32 a=0; a<nbCmsToProcess;)
{
void* ptr = taskPool.allocateNotThreadSafe(sizeof(PxsCMDiscreteUpdateTask));
PxU32 nbToProcess = PxMin(nbCmsToProcess - a, PxsCMUpdateTask::BATCH_SIZE);
PxsCMDiscreteUpdateTask* task = PX_PLACEMENT_NEW(ptr, PxsCMDiscreteUpdateTask)(&context, dt, narrowPhasePairs.mContactManagerMapping.begin() + a,
cmOutputs + a, narrowPhasePairs.mCaches.begin() + a, nbToProcess, modifyCallback);
a += nbToProcess;
task->setContinuation(continuation);
task->removeReference();
tasks.pushBack(task);
}
}
else
{
// PT:
const PxU32 numCpuTasks = continuation->getTaskManager()->getCpuDispatcher()->getWorkerCount();
PxU32 nbPerTask;
if(numCpuTasks)
nbPerTask = nbCmsToProcess > numCpuTasks ? nbCmsToProcess / numCpuTasks : nbCmsToProcess;
else
nbPerTask = nbCmsToProcess;
// PT: we need to respect that limit even with a single thread, because of hardcoded buffer limits in ScAfterIntegrationTask.
if(nbPerTask>PxsCMUpdateTask::BATCH_SIZE)
nbPerTask = PxsCMUpdateTask::BATCH_SIZE;
PxU32 start = 0;
while(nbCmsToProcess)
{
const PxU32 nb = nbCmsToProcess < nbPerTask ? nbCmsToProcess : nbPerTask;
void* ptr = taskPool.allocateNotThreadSafe(sizeof(PxsCMDiscreteUpdateTask));
PxsCMDiscreteUpdateTask* task = PX_PLACEMENT_NEW(ptr, PxsCMDiscreteUpdateTask)(&context, dt, narrowPhasePairs.mContactManagerMapping.begin() + start,
cmOutputs + start, narrowPhasePairs.mCaches.begin() + start, nb, modifyCallback);
task->setContinuation(continuation);
task->removeReference();
tasks.pushBack(task);
start += nb;
nbCmsToProcess -= nb;
}
}
taskPool.unlock();
}
void PxsNphaseImplementationContext::processContactManager(PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation)
{
processContactManagers(mContext, mNarrowPhasePairs, mCmTasks, dt, cmOutputs, continuation, mModifyCallback);
}
void PxsNphaseImplementationContext::processContactManagerSecondPass(PxReal dt, PxBaseTask* continuation)
{
processContactManagers(mContext, mNewNarrowPhasePairs, mCmTasks, dt, mNewNarrowPhasePairs.mOutputContactManagers.begin(), continuation, mModifyCallback);
}
void PxsNphaseImplementationContext::updateContactManager(PxReal dt, bool /*hasContactDistanceChanged*/, PxBaseTask* continuation,
PxBaseTask* firstPassNpContinuation, Cm::FanoutTask* /*updateBoundAndShapeTask*/)
{
PX_PROFILE_ZONE("Sim.queueNarrowPhase", mContext.mContextID);
firstPassNpContinuation->removeReference();
mContext.clearManagerTouchEvents();
#if PX_ENABLE_SIM_STATS
mContext.mSimStats.mNbDiscreteContactPairsTotal = 0;
mContext.mSimStats.mNbDiscreteContactPairsWithCacheHits = 0;
mContext.mSimStats.mNbDiscreteContactPairsWithContacts = 0;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//KS - temporarily put this here. TODO - move somewhere better
mContext.mTotalCompressedCacheSize = 0;
mContext.mMaxPatches = 0;
processContactManager(dt, mNarrowPhasePairs.mOutputContactManagers.begin(), continuation);
}
void PxsNphaseImplementationContext::secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation)
{
PX_PROFILE_ZONE("Sim.queueNarrowPhase", mContext.mContextID);
processContactManagerSecondPass(dt, continuation);
}
void PxsNphaseImplementationContext::destroy()
{
this->~PxsNphaseImplementationContext();
PX_FREE_THIS;
}
/*void PxsNphaseImplementationContext::registerContactManagers(PxsContactManager** cms, Sc::ShapeInteraction** shapeInteractions, PxU32 nbContactManagers, PxU32 maxContactManagerId)
{
PX_UNUSED(maxContactManagerId);
for (PxU32 a = 0; a < nbContactManagers; ++a)
{
registerContactManager(cms[a], shapeInteractions[a], 0, 0);
}
}*/
void PxsNphaseImplementationContext::registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* shapeInteraction, PxI32 touching, PxU32 patchCount)
{
PX_ASSERT(cm);
PxcNpWorkUnit& workUnit = cm->getWorkUnit();
PxsContactManagerOutput output;
PX_ASSERT(workUnit.geomType0<PxGeometryType::eGEOMETRY_COUNT);
PX_ASSERT(workUnit.geomType1<PxGeometryType::eGEOMETRY_COUNT);
const PxGeometryType::Enum geomType0 = PxGeometryType::Enum(workUnit.geomType0);
const PxGeometryType::Enum geomType1 = PxGeometryType::Enum(workUnit.geomType1);
Gu::Cache cache;
mContext.createCache(cache, geomType0, geomType1);
PxMemZero(&output, sizeof(output));
output.nbPatches = PxTo8(patchCount);
if(workUnit.flags & PxcNpWorkUnitFlag::eOUTPUT_CONSTRAINTS)
output.statusFlag |= PxsContactManagerStatusFlag::eREQUEST_CONSTRAINTS;
if (touching > 0)
output.statusFlag |= PxsContactManagerStatusFlag::eHAS_TOUCH;
else if (touching < 0)
output.statusFlag |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
output.statusFlag |= PxsContactManagerStatusFlag::eDIRTY_MANAGER;
if (workUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_TOUCH)
workUnit.statusFlags |= PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH;
output.flags = workUnit.flags;
mNewNarrowPhasePairs.mOutputContactManagers.pushBack(output);
mNewNarrowPhasePairs.mCaches.pushBack(cache);
mNewNarrowPhasePairs.mContactManagerMapping.pushBack(cm);
if(mGPU)
{
mNewNarrowPhasePairs.mShapeInteractions.pushBack(shapeInteraction);
mNewNarrowPhasePairs.mRestDistances.pushBack(cm->getRestDistance());
mNewNarrowPhasePairs.mTorsionalProperties.pushBack(PxsTorsionalFrictionData(workUnit.mTorsionalPatchRadius, workUnit.mMinTorsionalPatchRadius));
}
PxU32 newSz = mNewNarrowPhasePairs.mOutputContactManagers.size();
workUnit.mNpIndex = mNewNarrowPhasePairs.computeId(newSz - 1) | PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK;
}
void PxsNphaseImplementationContext::removeContactManagersFallback(PxsContactManagerOutput* cmOutputs)
{
if (mRemovedContactManagers.size())
{
lock();
PxSort(mRemovedContactManagers.begin(), mRemovedContactManagers.size(), PxGreater<PxU32>());
for (PxU32 a = 0; a < mRemovedContactManagers.size(); ++a)
{
#if PX_DEBUG
if (a > 0)
PX_ASSERT(mRemovedContactManagers[a] < mRemovedContactManagers[a - 1]);
#endif
unregisterContactManagerInternal(mRemovedContactManagers[a], mNarrowPhasePairs, cmOutputs);
}
mRemovedContactManagers.forceSize_Unsafe(0);
unlock();
}
}
void PxsNphaseImplementationContext::unregisterContactManager(PxsContactManager* cm)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
unregisterAndForceSize(mNarrowPhasePairs, index);
}
else
{
//KS - the index in the "new" list will be the index
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
}
void PxsNphaseImplementationContext::refreshContactManager(PxsContactManager* cm)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
PxsContactManagerOutput output;
Sc::ShapeInteraction* interaction;
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
output = mNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(index)];
interaction = mGPU ? mNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index)] : cm->getShapeInteraction();
unregisterAndForceSize(mNarrowPhasePairs, index);
}
else
{
output = mNewNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))];
interaction = mGPU ? mNewNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))] : cm->getShapeInteraction();
//KS - the index in the "new" list will be the index
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
PxI32 touching = 0;
if(output.statusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH)
touching = 1;
else if (output.statusFlag & PxsContactManagerStatusFlag::eHAS_NO_TOUCH)
touching = -1;
registerContactManager(cm, interaction, touching, output.nbPatches);
}
void PxsNphaseImplementationContext::unregisterContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* /*cmOutputs*/)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
mRemovedContactManagers.pushBack(index);
}
else
{
//KS - the index in the "new" list will be the index
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
}
void PxsNphaseImplementationContext::refreshContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs)
{
PxcNpWorkUnit& unit = cm->getWorkUnit();
PxU32 index = unit.mNpIndex;
PX_ASSERT(index != 0xFFffFFff);
PxsContactManagerOutput output;
Sc::ShapeInteraction* interaction;
if (!(index & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))
{
output = cmOutputs[PxsContactManagerBase::computeIndexFromId(index)];
interaction = mGPU ? mNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))] : cm->getShapeInteraction();
//unregisterContactManagerInternal(index, mNarrowPhasePairs, cmOutputs);
unregisterContactManagerFallback(cm, cmOutputs);
}
else
{
//KS - the index in the "new" list will be the index
output = mNewNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))];
interaction = mGPU ? mNewNarrowPhasePairs.mShapeInteractions[PxsContactManagerBase::computeIndexFromId(index & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))] : cm->getShapeInteraction();
unregisterAndForceSize(mNewNarrowPhasePairs, index);
}
PxI32 touching = 0;
if(output.statusFlag & PxsContactManagerStatusFlag::eHAS_TOUCH)
{
touching = 1;
unit.statusFlags |= PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH;
}
else if (output.statusFlag & PxsContactManagerStatusFlag::eHAS_NO_TOUCH)
touching = -1;
registerContactManager(cm, interaction, touching, output.nbPatches);
}
void PxsNphaseImplementationContext::appendContactManagers()
{
//Copy new pairs to end of old pairs. Clear new flag, update npIndex on CM and clear the new pair buffer
const PxU32 existingSize = mNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 nbToAdd = mNewNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 newSize = existingSize + nbToAdd;
if(newSize > mNarrowPhasePairs.mContactManagerMapping.capacity())
{
PxU32 newSz = PxMax(256u, PxMax(mNarrowPhasePairs.mContactManagerMapping.capacity()*2, newSize));
mNarrowPhasePairs.mContactManagerMapping.reserve(newSz);
mNarrowPhasePairs.mOutputContactManagers.reserve(newSz);
mNarrowPhasePairs.mCaches.reserve(newSz);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.reserve(newSz);
mNarrowPhasePairs.mRestDistances.reserve(newSz);
mNarrowPhasePairs.mTorsionalProperties.reserve(newSz);
}
}
mNarrowPhasePairs.mContactManagerMapping.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mOutputContactManagers.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mCaches.forceSize_Unsafe(newSize);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mRestDistances.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mTorsionalProperties.forceSize_Unsafe(newSize);
}
PxMemCopy(mNarrowPhasePairs.mContactManagerMapping.begin() + existingSize, mNewNarrowPhasePairs.mContactManagerMapping.begin(), sizeof(PxsContactManager*)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mOutputContactManagers.begin() + existingSize, mNewNarrowPhasePairs.mOutputContactManagers.begin(), sizeof(PxsContactManagerOutput)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mCaches.begin() + existingSize, mNewNarrowPhasePairs.mCaches.begin(), sizeof(Gu::Cache)*nbToAdd);
if(mGPU)
{
PxMemCopy(mNarrowPhasePairs.mShapeInteractions.begin() + existingSize, mNewNarrowPhasePairs.mShapeInteractions.begin(), sizeof(Sc::ShapeInteraction*)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mRestDistances.begin() + existingSize, mNewNarrowPhasePairs.mRestDistances.begin(), sizeof(PxReal)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mTorsionalProperties.begin() + existingSize, mNewNarrowPhasePairs.mTorsionalProperties.begin(), sizeof(PxsTorsionalFrictionData)*nbToAdd);
}
PxU32* edgeNodeIndices = mIslandSim->getEdgeNodeIndexPtr();
for(PxU32 a = 0; a < mNewNarrowPhasePairs.mContactManagerMapping.size(); ++a)
{
PxsContactManager* cm = mNewNarrowPhasePairs.mContactManagerMapping[a];
PxcNpWorkUnit& unit = cm->getWorkUnit();
unit.mNpIndex = mNarrowPhasePairs.computeId(existingSize + a);
if(unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)
{
unit.statusFlags &= (~PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH);
if(!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE))
{
PartitionEdge* partitionEdge = mIslandSim->getFirstPartitionEdge(unit.mEdgeIndex);
while(partitionEdge)
{
edgeNodeIndices[partitionEdge->mUniqueIndex] = unit.mNpIndex;
partitionEdge = partitionEdge->mNextPatch;
}
}
}
}
mNewNarrowPhasePairs.clear();
appendNewLostPairs();
}
void PxsNphaseImplementationContext::appendContactManagersFallback(PxsContactManagerOutput* cmOutputs)
{
PX_PROFILE_ZONE("PxsNphaseImplementationContext.appendContactManagersFallback", mContext.mContextID);
//Copy new pairs to end of old pairs. Clear new flag, update npIndex on CM and clear the new pair buffer
const PxU32 existingSize = mNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 nbToAdd = mNewNarrowPhasePairs.mContactManagerMapping.size();
const PxU32 newSize =existingSize + nbToAdd;
if(newSize > mNarrowPhasePairs.mContactManagerMapping.capacity())
{
PxU32 newSz = PxMax(mNarrowPhasePairs.mContactManagerMapping.capacity()*2, newSize);
mNarrowPhasePairs.mContactManagerMapping.reserve(newSz);
mNarrowPhasePairs.mCaches.reserve(newSz);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.reserve(newSz);
mNarrowPhasePairs.mRestDistances.reserve(newSz);
mNarrowPhasePairs.mTorsionalProperties.reserve(newSz);
}
}
mNarrowPhasePairs.mContactManagerMapping.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mCaches.forceSize_Unsafe(newSize);
if(mGPU)
{
mNarrowPhasePairs.mShapeInteractions.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mRestDistances.forceSize_Unsafe(newSize);
mNarrowPhasePairs.mTorsionalProperties.forceSize_Unsafe(newSize);
}
PxMemCopy(mNarrowPhasePairs.mContactManagerMapping.begin() + existingSize, mNewNarrowPhasePairs.mContactManagerMapping.begin(), sizeof(PxsContactManager*)*nbToAdd);
PxMemCopy(cmOutputs + existingSize, mNewNarrowPhasePairs.mOutputContactManagers.begin(), sizeof(PxsContactManagerOutput)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mCaches.begin() + existingSize, mNewNarrowPhasePairs.mCaches.begin(), sizeof(Gu::Cache)*nbToAdd);
if(mGPU)
{
PxMemCopy(mNarrowPhasePairs.mShapeInteractions.begin() + existingSize, mNewNarrowPhasePairs.mShapeInteractions.begin(), sizeof(Sc::ShapeInteraction*)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mRestDistances.begin() + existingSize, mNewNarrowPhasePairs.mRestDistances.begin(), sizeof(PxReal)*nbToAdd);
PxMemCopy(mNarrowPhasePairs.mTorsionalProperties.begin() + existingSize, mNewNarrowPhasePairs.mTorsionalProperties.begin(), sizeof(PxsTorsionalFrictionData)*nbToAdd);
}
PxU32* edgeNodeIndices = mIslandSim->getEdgeNodeIndexPtr();
for(PxU32 a = 0; a < mNewNarrowPhasePairs.mContactManagerMapping.size(); ++a)
{
PxsContactManager* cm = mNewNarrowPhasePairs.mContactManagerMapping[a];
PxcNpWorkUnit& unit = cm->getWorkUnit();
unit.mNpIndex = mNarrowPhasePairs.computeId(existingSize + a);
if(unit.statusFlags & PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH)
{
unit.statusFlags &= (~PxcNpWorkUnitStatusFlag::eREFRESHED_WITH_TOUCH);
if(!(unit.flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE))
{
PartitionEdge* partitionEdge = mIslandSim->getFirstPartitionEdge(unit.mEdgeIndex);
while(partitionEdge)
{
edgeNodeIndices[partitionEdge->mUniqueIndex] = unit.mNpIndex;
partitionEdge = partitionEdge->mNextPatch;
}
}
}
}
mNewNarrowPhasePairs.clear();
appendNewLostPairs();
}
void PxsNphaseImplementationContext::appendNewLostPairs()
{
mCmFoundLostOutputCounts.forceSize_Unsafe(0);
mCmFoundLost.forceSize_Unsafe(0);
PxU32 count = 0;
for (PxU32 i = 0, taskSize = mCmTasks.size(); i < taskSize; ++i)
{
PxsCMDiscreteUpdateTask* task = mCmTasks[i];
const PxU32 patchCount = task->mNbPatchChanged;
if (patchCount)
{
const PxU32 newSize = mCmFoundLostOutputCounts.size() + patchCount;
//KS - TODO - consider switching to 2x loops to avoid frequent allocations. However, we'll probably only grow this rarely,
//so may not be worth the effort!
if (mCmFoundLostOutputCounts.capacity() < newSize)
{
//Allocate more memory!!!
const PxU32 newCapacity = PxMax(mCmFoundLostOutputCounts.capacity() * 2, newSize);
mCmFoundLostOutputCounts.reserve(newCapacity);
mCmFoundLost.reserve(newCapacity);
}
mCmFoundLostOutputCounts.forceSize_Unsafe(newSize);
mCmFoundLost.forceSize_Unsafe(newSize);
PxMemCopy(&mCmFoundLost[count], task->mPatchChangedCms, sizeof(PxsContactManager*)*patchCount);
PxMemCopy(&mCmFoundLostOutputCounts[count], task->mPatchChangedOutputCounts, sizeof(PxsContactManagerOutputCounts)*patchCount);
count += patchCount;
}
}
mCmTasks.forceSize_Unsafe(0);
}
void PxsNphaseImplementationContext::unregisterContactManagerInternal(PxU32 npIndex, PxsContactManagers& managers, PxsContactManagerOutput* cmOutputs)
{
// PX_PROFILE_ZONE("unregisterContactManagerInternal", 0);
//TODO - remove this element from the list.
const PxU32 index = PxsContactManagerBase::computeIndexFromId((npIndex & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK)));
//Now we replace-with-last and remove the elements...
const PxU32 replaceIndex = managers.mContactManagerMapping.size()-1;
PxsContactManager* replaceManager = managers.mContactManagerMapping[replaceIndex];
mContext.destroyCache(managers.mCaches[index]);
managers.mContactManagerMapping[index] = replaceManager;
managers.mCaches[index] = managers.mCaches[replaceIndex];
cmOutputs[index] = cmOutputs[replaceIndex];
if(mGPU)
{
managers.mShapeInteractions[index] = managers.mShapeInteractions[replaceIndex];
managers.mRestDistances[index] = managers.mRestDistances[replaceIndex];
managers.mTorsionalProperties[index] = managers.mTorsionalProperties[replaceIndex];
}
managers.mCaches[replaceIndex].reset();
PxcNpWorkUnit& replaceUnit = replaceManager->getWorkUnit();
replaceUnit.mNpIndex = npIndex;
if(replaceUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_TOUCH)
{
if(!(replaceUnit.flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE))
{
PxU32* edgeNodeIndices = mIslandSim->getEdgeNodeIndexPtr();
PartitionEdge* partitionEdge = mIslandSim->getFirstPartitionEdge(replaceUnit.mEdgeIndex);
while(partitionEdge)
{
edgeNodeIndices[partitionEdge->mUniqueIndex] = replaceUnit.mNpIndex;
partitionEdge = partitionEdge->mNextPatch;
}
}
}
managers.mContactManagerMapping.forceSize_Unsafe(replaceIndex);
managers.mCaches.forceSize_Unsafe(replaceIndex);
if(mGPU)
{
managers.mShapeInteractions.forceSize_Unsafe(replaceIndex);
managers.mRestDistances.forceSize_Unsafe(replaceIndex);
managers.mTorsionalProperties.forceSize_Unsafe(replaceIndex);
}
}
PxsContactManagerOutput& PxsNphaseImplementationContext::getNewContactManagerOutput(PxU32 npId)
{
PX_ASSERT(npId & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK);
return mNewNarrowPhasePairs.mOutputContactManagers[PxsContactManagerBase::computeIndexFromId(npId & (~PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK))];
}
PxsContactManagerOutputIterator PxsNphaseImplementationContext::getContactManagerOutputs()
{
PxU32 offsets[1] = {0};
return PxsContactManagerOutputIterator(offsets, 1, mNarrowPhasePairs.mOutputContactManagers.begin());
}
PxvNphaseImplementationContextUsableAsFallback* physx::createNphaseImplementationContext(PxsContext& context, IG::IslandSim* islandSim, PxVirtualAllocatorCallback* allocator, bool gpuDynamics)
{
// PT: TODO: remove useless placement new
PxsNphaseImplementationContext* npImplContext = reinterpret_cast<PxsNphaseImplementationContext*>(
PX_ALLOC(sizeof(PxsNphaseImplementationContext), "PxsNphaseImplementationContext"));
if(npImplContext)
npImplContext = PX_PLACEMENT_NEW(npImplContext, PxsNphaseImplementationContext)(context, islandSim, allocator, 0, gpuDynamics);
return npImplContext;
}
| 39,916 | C++ | 37.01619 | 249 | 0.761249 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsCCD.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "common/PxProfileZone.h"
#include "geomutils/PxContactPoint.h"
#include "PxsContactManager.h"
#include "PxsContext.h"
#include "PxsRigidBody.h"
#include "PxsMaterialManager.h"
#include "PxsCCD.h"
#include "PxsMaterialManager.h"
#include "PxsMaterialCombiner.h"
#include "PxcContactMethodImpl.h"
#include "PxcMaterialMethodImpl.h"
#include "PxcNpContactPrepShared.h"
#include "PxvGeometry.h"
#include "PxvGlobals.h"
#include "foundation/PxSort.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxMathUtils.h"
#include "CmFlushPool.h"
#include "DyThresholdTable.h"
#include "GuCCDSweepConvexMesh.h"
#include "GuBounds.h"
#include "GuConvexMesh.h"
#include "geometry/PxGeometryQuery.h"
#include "PxsIslandSim.h"
// PT: this one currently makes these UTs fail
// [ FAILED ] CCDReportTest.CCD_soakTest_mesh
// [ FAILED ] CCDReportTest.CCD_soakTest_heightfield
// [ FAILED ] CCDNegativeScalingTest.SLOW_ccdNegScaledMesh
// [ FAILED ] OriginShift.CCD
static const bool gUseGeometryQuery = false;
#if DEBUG_RENDER_CCD
#include "common/PxRenderOutput.h"
#include "common/PxRenderBuffer.h"
#include "PxPhysics.h"
#include "PxScene.h"
#endif
#define DEBUG_RENDER_CCD_FIRST_PASS_ONLY 1
#define DEBUG_RENDER_CCD_ATOM_PTR 0
#define DEBUG_RENDER_CCD_NORMAL 1
#define CCD_ANGULAR_IMPULSE 0 // PT: this doesn't compile anymore
using namespace physx;
using namespace physx::Dy;
using namespace Gu;
static PX_FORCE_INLINE void verifyCCDPair(const PxsCCDPair& /*pair*/)
{
#if 0
if (pair.mBa0)
pair.mBa0->getPose();
if (pair.mBa1)
pair.mBa1->getPose();
#endif
}
#if CCD_DEBUG_PRINTS
// PT: this is copied from PxsRigidBody.h and will need to be adapted if we ever need it again
// AP newccd todo: merge into get both velocities, compute inverse transform once, precompute mLastTransform.getInverse()
PX_FORCE_INLINE PxVec3 getLinearMotionVelocity(PxReal invDt) const
{
// delta(t0(x))=t1(x)
// delta(t0(t0`(x)))=t1(t0`(x))
// delta(x)=t1(t0`(x))
const PxVec3 deltaP = mCore->body2World.p - getLastCCDTransform().p;
return deltaP * invDt;
}
PX_FORCE_INLINE PxVec3 getAngularMotionVelocity(PxReal invDt) const
{
const PxQuat deltaQ = mCore->body2World.q * getLastCCDTransform().q.getConjugate();
PxVec3 axis;
PxReal angle;
deltaQ.toRadiansAndUnitAxis(angle, axis);
return axis * angle * invDt;
}
PX_FORCE_INLINE PxVec3 getLinearMotionVelocity(PxReal dt, const PxsBodyCore* PX_RESTRICT bodyCore) const
{
// delta(t0(x))=t1(x)
// delta(t0(t0`(x)))=t1(t0`(x))
// delta(x)=t1(t0`(x))
const PxVec3 deltaP = bodyCore->body2World.p - getLastCCDTransform().p;
return deltaP * 1.0f / dt;
}
PX_FORCE_INLINE PxVec3 getAngularMotionVelocity(PxReal dt, const PxsBodyCore* PX_RESTRICT bodyCore) const
{
const PxQuat deltaQ = bodyCore->body2World.q * getLastCCDTransform().q.getConjugate();
PxVec3 axis;
PxReal angle;
deltaQ.toRadiansAndUnitAxis(angle, axis);
return axis * angle * 1.0f/dt;
}
#include <stdio.h>
#pragma warning(disable: 4313)
namespace physx {
static const char* gGeomTypes[PxGeometryType::eGEOMETRY_COUNT+1] = {
"sphere", "plane", "capsule", "box", "convex", "trimesh", "heightfield", "*"
};
FILE* gCCDLog = NULL;
static inline void openCCDLog()
{
if (gCCDLog)
{
fclose(gCCDLog);
gCCDLog = NULL;
}
gCCDLog = fopen("c:\\ccd.txt", "wt");
fprintf(gCCDLog, ">>>>>>>>>>>>>>>>>>>>>>>>>>> CCD START FRAME <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n");
}
static inline void printSeparator(
const char* prefix, PxU32 pass, PxsRigidBody* atom0, PxGeometryType::Enum g0, PxsRigidBody* atom1, PxGeometryType::Enum g1)
{
fprintf(gCCDLog, "------- %s pass %d (%s %x) vs (%s %x)\n", prefix, pass, gGeomTypes[g0], atom0, gGeomTypes[g1], atom1);
fflush(gCCDLog);
}
static inline void printCCDToi(
const char* header, PxF32 t, const PxVec3& v,
PxsRigidBody* atom0, PxGeometryType::Enum g0, PxsRigidBody* atom1, PxGeometryType::Enum g1
)
{
fprintf(gCCDLog, "%s (%s %x vs %s %x): %.5f, (%.2f, %.2f, %.2f)\n", header, gGeomTypes[g0], atom0, gGeomTypes[g1], atom1, t, v.x, v.y, v.z);
fflush(gCCDLog);
}
static inline void printCCDPair(const char* header, PxsCCDPair& pair)
{
printCCDToi(header, pair.mMinToi, pair.mMinToiNormal, pair.mBa0, pair.mG0, pair.mBa1, pair.mG1);
}
// also used in PxcSweepConvexMesh.cpp
void printCCDDebug(const char* msg, const PxsRigidBody* atom0, PxGeometryType::Enum g0, bool printPtr)
{
fprintf(gCCDLog, " %s (%s %x)\n", msg, gGeomTypes[g0], printPtr ? atom0 : 0);
fflush(gCCDLog);
}
// also used in PxcSweepConvexMesh.cpp
void printShape(
PxsRigidBody* atom0, PxGeometryType::Enum g0, const char* annotation, PxReal dt, PxU32 pass, bool printPtr)
{
PX_UNUSED(pass);
// PT: I'm leaving this here but I doubt it works. The code passes "dt" to a function that wants "invDt"....
fprintf(gCCDLog, "%s (%s %x) atom=(%.2f, %.2f, %.2f)>(%.2f, %.2f, %.2f) v=(%.1f, %.1f, %.1f), mv=(%.1f, %.1f, %.1f)\n",
annotation, gGeomTypes[g0], printPtr ? atom0 : 0,
atom0->getLastCCDTransform().p.x, atom0->getLastCCDTransform().p.y, atom0->getLastCCDTransform().p.z,
atom0->getPose().p.x, atom0->getPose().p.y, atom0->getPose().p.z,
atom0->getLinearVelocity().x, atom0->getLinearVelocity().y, atom0->getLinearVelocity().z,
atom0->getLinearMotionVelocity(dt).x, atom0->getLinearMotionVelocity(dt).y, atom0->getLinearMotionVelocity(dt).z );
fflush(gCCDLog);
#if DEBUG_RENDER_CCD && DEBUG_RENDER_CCD_ATOM_PTR
if (!DEBUG_RENDER_CCD_FIRST_PASS_ONLY || pass == 0)
{
PxScene *s; PxGetPhysics()->getScenes(&s, 1, 0);
PxRenderOutput((PxRenderBufferImpl&)s->getRenderBuffer())
<< DebugText(atom0->getPose().p, 0.05f, "%x", atom0);
}
#endif
}
static inline void flushCCDLog()
{
fflush(gCCDLog);
}
} // namespace physx
#else
namespace physx
{
void printShape(PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/, const char* /*annotation*/, PxReal /*dt*/, PxU32 /*pass*/, bool printPtr = true)
{PX_UNUSED(printPtr);}
static inline void openCCDLog() {}
static inline void flushCCDLog() {}
void printCCDDebug(const char* /*msg*/, const PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/, bool printPtr = true) {PX_UNUSED(printPtr);}
static inline void printSeparator(
const char* /*prefix*/, PxU32 /*pass*/, PxsRigidBody* /*atom0*/, PxGeometryType::Enum /*g0*/,
PxsRigidBody* /*atom1*/, PxGeometryType::Enum /*g1*/) {}
} // namespace physx
#endif
float physx::computeCCDThreshold(const PxGeometry& geometry)
{
// Box, Convex, Mesh and HeightField will compute local bounds and pose to world space.
// Sphere, Capsule & Plane will compute world space bounds directly.
const PxReal inSphereRatio = 0.75f;
//The CCD thresholds are as follows:
//(1) sphere = inSphereRatio * radius
//(2) plane = inf (we never need CCD against this shape)
//(3) capsule = inSphereRatio * radius
//(4) box = inSphereRatio * (box minimum extent axis)
//(5) convex = inSphereRatio * convex in-sphere * min scale
//(6) triangle mesh = 0.0f (polygons have 0 thickness)
//(7) heightfields = 0.0f (polygons have 0 thickness)
//The decision to enter CCD depends on the sum of the shapes' CCD thresholds. One of the 2 shapes must be a
//sphere/capsule/box/convex so the sum of the CCD thresholds will be non-zero.
switch (geometry.getType())
{
case PxGeometryType::eSPHERE:
{
const PxSphereGeometry& shape = static_cast<const PxSphereGeometry&>(geometry);
return shape.radius*inSphereRatio;
}
case PxGeometryType::ePLANE:
{
return PX_MAX_REAL;
}
case PxGeometryType::eCAPSULE:
{
const PxCapsuleGeometry& shape = static_cast<const PxCapsuleGeometry&>(geometry);
return shape.radius * inSphereRatio;
}
case PxGeometryType::eBOX:
{
const PxBoxGeometry& shape = static_cast<const PxBoxGeometry&>(geometry);
return PxMin(PxMin(shape.halfExtents.x, shape.halfExtents.y), shape.halfExtents.z)*inSphereRatio;
}
case PxGeometryType::eCONVEXMESH:
{
const PxConvexMeshGeometry& shape = static_cast<const PxConvexMeshGeometry&>(geometry);
const Gu::ConvexHullData& hullData = static_cast<const Gu::ConvexMesh*>(shape.convexMesh)->getHull();
return PxMin(shape.scale.scale.z, PxMin(shape.scale.scale.x, shape.scale.scale.y)) * hullData.mInternal.mRadius * inSphereRatio;
}
case PxGeometryType::eTRIANGLEMESH: { return 0.0f; }
case PxGeometryType::eHEIGHTFIELD: { return 0.0f; }
case PxGeometryType::eTETRAHEDRONMESH: { return 0.0f; }
case PxGeometryType::ePARTICLESYSTEM: { return 0.0f; }
case PxGeometryType::eHAIRSYSTEM: { return 0.0f; }
case PxGeometryType::eCUSTOM: { return 0.0f; }
default:
{
PX_ASSERT(0);
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Gu::computeBoundsWithCCDThreshold::computeBounds: Unknown shape type.");
}
}
return PX_MAX_REAL;
}
static float computeBoundsWithCCDThreshold(PxVec3p& origin, PxVec3p& extent, const PxGeometry& geometry, const PxTransform& transform) //AABB in world space.
{
const PxBounds3 bounds = computeBounds(geometry, transform);
origin = bounds.getCenter();
extent = bounds.getExtents();
return computeCCDThreshold(geometry);
}
static PX_FORCE_INLINE void trTr(PxTransform& out, const PxTransform& a, const PxTransform& b)
{
// PT:: tag: scalar transform*transform
out = a * b;
}
static PX_FORCE_INLINE void trInvTr(PxTransform& out, const PxTransform& a, const PxTransform& b, const PxTransform& c)
{
// PT:: tag: scalar transform*transform
out = a * b.getInverse() * c;
}
// PT: TODO: refactor with ShapeSim version (SIMD), simplify code when shape local pose = idt
static PX_INLINE void getShapeAbsPose(PxTransform& out, const PxsShapeCore* shapeCore, const PxsRigidCore* rigidCore, const void* isDynamic)
{
if(isDynamic)
{
const PxsBodyCore* PX_RESTRICT bodyCore = static_cast<const PxsBodyCore*>(rigidCore);
trInvTr(out, bodyCore->body2World, bodyCore->getBody2Actor(), shapeCore->getTransform());
}
else
trTr(out, rigidCore->body2World, shapeCore->getTransform());
}
// \brief Returns the world-space pose for this shape
// \param[in] atom The rigid body that this CCD shape is associated with
static void getAbsPose(PxTransform32& out, const PxsCCDShape* ccdShape, const PxsRigidBody* atom)
{
// PT: TODO: refactor with ShapeSim version (SIMD) - or with redundant getShapeAbsPose() above in this same file!
// PT: TODO: simplify code when shape local pose = idt
if(atom)
trInvTr(out, atom->getPose(), atom->getCore().getBody2Actor(), ccdShape->mShapeCore->getTransform());
else
trTr(out, ccdShape->mRigidCore->body2World, ccdShape->mShapeCore->getTransform());
}
// \brief Returns the world-space previous pose for this shape
// \param[in] atom The rigid body that this CCD shape is associated with
static void getLastCCDAbsPose(PxTransform32& out, const PxsCCDShape* ccdShape, const PxsRigidBody* atom)
{
// PT: TODO: refactor with ShapeSim version (SIMD)
// PT: TODO: simplify code when shape local pose = idt
// PT:: tag: scalar transform*transform
trInvTr(out, atom->getLastCCDTransform(), atom->getCore().getBody2Actor(), ccdShape->mShapeCore->getTransform());
}
PxsCCDContext::PxsCCDContext(PxsContext* context, Dy::ThresholdStream& thresholdStream, PxvNphaseImplementationContext& nPhaseContext, PxReal ccdThreshold) :
mPostCCDSweepTask (context->getContextId(), this, "PxsContext.postCCDSweep"),
mPostCCDAdvanceTask (context->getContextId(), this, "PxsContext.postCCDAdvance"),
mPostCCDDepenetrateTask (context->getContextId(), this, "PxsContext.postCCDDepenetrate"),
mDisableCCDResweep (false),
miCCDPass (0),
mSweepTotalHits (0),
mCCDThreadContext (NULL),
mCCDPairsPerBatch (0),
mCCDMaxPasses (1),
mContext (context),
mThresholdStream (thresholdStream),
mNphaseContext (nPhaseContext),
mCCDThreshold (ccdThreshold)
{
}
PxsCCDContext::~PxsCCDContext()
{
}
void combineMaterials(const PxsMaterialManager* materialManager, PxU16 origMatIndex0, PxU16 origMatIndex1, PxReal& staticFriction, PxReal& dynamicFriction, PxReal& combinedRestitution, PxU32& materialFlags, PxReal& combinedDamping);
PxReal PxsCCDPair::sweepFindToi(PxcNpThreadContext& context, PxReal dt, PxU32 pass, PxReal ccdThreshold)
{
printSeparator("findToi", pass, mBa0, mG0, NULL, PxGeometryType::eGEOMETRY_COUNT);
//Update shape transforms if necessary
updateShapes();
//Extract the bodies
PxsRigidBody* atom0 = mBa0;
PxsRigidBody* atom1 = mBa1;
PxsCCDShape* ccdShape0 = mCCDShape0;
PxsCCDShape* ccdShape1 = mCCDShape1;
PxGeometryType::Enum g0 = mG0, g1 = mG1;
//If necessary, flip the bodies to make sure that g0 <= g1
if(mG1 < mG0)
{
g0 = mG1;
g1 = mG0;
ccdShape0 = mCCDShape1;
ccdShape1 = mCCDShape0;
atom0 = mBa1;
atom1 = mBa0;
}
const PxTransform32 tm0(ccdShape0->mCurrentTransform);
const PxTransform32 lastTm0(ccdShape0->mPrevTransform);
const PxTransform32 tm1(ccdShape1->mCurrentTransform);
const PxTransform32 lastTm1(ccdShape1->mPrevTransform);
const PxVec3 trA = tm0.p - lastTm0.p;
const PxVec3 trB = tm1.p - lastTm1.p;
const PxVec3 relTr = trA - trB;
// Do the sweep
PxVec3 sweepNormal(0.0f);
PxVec3 sweepPoint(0.0f);
context.mDt = dt;
context.mCCDFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
//Cull the sweep hit based on the relative velocity along the normal
const PxReal fastMovingThresh0 = ccdShape0->mFastMovingThreshold;
const PxReal fastMovingThresh1 = ccdShape1->mFastMovingThreshold;
const PxReal sumFastMovingThresh = PxMin(fastMovingThresh0 + fastMovingThresh1, ccdThreshold);
PxReal toi = PX_MAX_REAL;
if(gUseGeometryQuery)
{
// PT: TODO: support restDistance & sumFastMovingThresh here
PxVec3 unitDir = relTr;
const PxReal length = unitDir.normalize();
PxGeomSweepHit sweepHit;
if(PxGeometryQuery::sweep(unitDir, length, *ccdShape0->mGeometry, lastTm0, *ccdShape1->mGeometry, lastTm1, sweepHit, PxHitFlag::eDEFAULT|PxHitFlag::ePRECISE_SWEEP, 0.0f, PxGeometryQueryFlag::Enum(0), NULL))
{
sweepNormal = sweepHit.normal;
sweepPoint = sweepHit.position;
context.mCCDFaceIndex = sweepHit.faceIndex;
toi = sweepHit.distance/length;
}
}
else
{
const PxReal restDistance = PxMax(mCm->getWorkUnit().restDistance, 0.0f);
toi = Gu::SweepShapeShape(*ccdShape0, *ccdShape1, tm0, tm1, lastTm0, lastTm1, restDistance, sweepNormal, sweepPoint, mMinToi, context.mCCDFaceIndex, sumFastMovingThresh);
}
//If toi is after the end of TOI, return no hit
if (toi >= 1.0f)
{
mToiType = PxsCCDPair::ePrecise;
mPenetration = 0.0f;
mPenetrationPostStep = 0.0f;
mMinToi = PX_MAX_REAL; // needs to be reset in case of resweep
return toi;
}
PX_ASSERT(PxIsFinite(toi));
PX_ASSERT(sweepNormal.isFinite());
mFaceIndex = context.mCCDFaceIndex;
//Work out linear motion (used to cull the sweep hit)
const PxReal linearMotion = relTr.dot(-sweepNormal);
//If we swapped the shapes, swap them back
if(mG1 >= mG0)
sweepNormal = -sweepNormal;
mToiType = PxsCCDPair::ePrecise;
PxReal penetration = 0.0f;
PxReal penetrationPostStep = 0.0f;
//If linear motion along normal < the CCD threshold, set toi to no-hit.
if((linearMotion) < sumFastMovingThresh)
{
mMinToi = PX_MAX_REAL; // needs to be reset in case of resweep
return PX_MAX_REAL;
}
else if(toi <= 0.0f)
{
//If the toi <= 0.0f, this implies an initial overlap. If the value < 0.0f, it implies penetration
PxReal stepRatio0 = atom0 ? atom0->mCCD->mTimeLeft : 1.0f;
PxReal stepRatio1 = atom1 ? atom1->mCCD->mTimeLeft : 1.0f;
PxReal stepRatio = PxMin(stepRatio0, stepRatio1);
penetration = -toi;
toi = 0.0f;
if(stepRatio == 1.0f)
{
//If stepRatio == 1.f (i.e. neither body has stepped forwards any time at all)
//we extract the advance coefficients from the bodies and permit the bodies to step forwards a small amount
//to ensure that they won't remain jammed because TOI = 0.0
const PxReal advance0 = atom0 ? atom0->mCore->ccdAdvanceCoefficient : 1.0f;
const PxReal advance1 = atom1 ? atom1->mCore->ccdAdvanceCoefficient : 1.0f;
const PxReal advance = PxMin(advance0, advance1);
PxReal fastMoving = PxMin(fastMovingThresh0, atom1 ? fastMovingThresh1 : PX_MAX_REAL);
PxReal advanceCoeff = advance * fastMoving;
penetrationPostStep = advanceCoeff/linearMotion;
}
PX_ASSERT(PxIsFinite(toi));
}
//Store TOI, penetration and post-step (how much to step forward in initial overlap conditions)
mMinToi = toi;
mPenetration = penetration;
mPenetrationPostStep = penetrationPostStep;
mMinToiPoint = sweepPoint;
mMinToiNormal = sweepNormal;
//Work out the materials for the contact (restitution, friction etc.)
context.mContactBuffer.count = 0;
context.mContactBuffer.contact(mMinToiPoint, mMinToiNormal, 0.0f,
g0 == PxGeometryType::eTRIANGLEMESH || g0 == PxGeometryType::eHEIGHTFIELD ||
g1 == PxGeometryType::eTRIANGLEMESH || g1 == PxGeometryType::eHEIGHTFIELD ? mFaceIndex : PXC_CONTACT_NO_FACE_INDEX);
PxsMaterialInfo materialInfo;
g_GetSingleMaterialMethodTable[g0](ccdShape0->mShapeCore, 0, context, &materialInfo);
g_GetSingleMaterialMethodTable[g1](ccdShape1->mShapeCore, 1, context, &materialInfo);
PxU32 materialFlags;
PxReal combinedDamping;
combineMaterials(context.mMaterialManager, materialInfo.mMaterialIndex0, materialInfo.mMaterialIndex1, mStaticFriction, mDynamicFriction, mRestitution, materialFlags, combinedDamping);
mMaterialIndex0 = materialInfo.mMaterialIndex0;
mMaterialIndex1 = materialInfo.mMaterialIndex1;
return toi;
}
static void updateShape(PxsRigidBody* body, PxsCCDShape* shape)
{
if(body)
{
//If the CCD shape's update count doesn't match the body's update count, this shape needs its transforms and bounds re-calculated
if(body->mCCD->mUpdateCount != shape->mUpdateCount)
{
PxTransform32 tm;
getAbsPose(tm, shape, body);
PxTransform32 lastTm;
getLastCCDAbsPose(lastTm, shape, body);
const PxVec3 trA = tm.p - lastTm.p;
PxVec3p origin, extents;
computeBoundsWithCCDThreshold(origin, extents, shape->mShapeCore->mGeometry.getGeometry(), tm);
shape->mCenter = origin - trA;
shape->mExtents = extents;
shape->mPrevTransform = lastTm;
shape->mCurrentTransform = tm;
shape->mUpdateCount = body->mCCD->mUpdateCount;
}
}
}
void PxsCCDPair::updateShapes()
{
updateShape(mBa0, mCCDShape0);
updateShape(mBa1, mCCDShape1);
}
PxReal PxsCCDPair::sweepEstimateToi(PxReal ccdThreshold)
{
//Update shape transforms if necessary
updateShapes();
//PxsRigidBody* atom1 = mBa1;
//PxsRigidBody* atom0 = mBa0;
PxsCCDShape* ccdShape0 = mCCDShape0;
PxsCCDShape* ccdShape1 = mCCDShape1;
PxGeometryType::Enum g0 = mG0, g1 = mG1;
PX_UNUSED(g0);
//Flip shapes if necessary
if(mG1 < mG0)
{
g0 = mG1;
g1 = mG0;
/*atom0 = mBa1;
atom1 = mBa0;*/
ccdShape0 = mCCDShape1;
ccdShape1 = mCCDShape0;
}
//Extract previous/current transforms, translations etc.
const PxVec3 trA = ccdShape0->mCurrentTransform.p - ccdShape0->mPrevTransform.p;
const PxVec3 trB = ccdShape1->mCurrentTransform.p - ccdShape1->mPrevTransform.p;
const PxReal restDistance = PxMax(mCm->getWorkUnit().restDistance, 0.0f);
const PxVec3 relTr = trA - trB;
//Work out the sum of the fast moving thresholds scaled by the step ratio
const PxReal fastMovingThresh0 = ccdShape0->mFastMovingThreshold;
const PxReal fastMovingThresh1 = ccdShape1->mFastMovingThreshold;
const PxReal sumFastMovingThresh = PxMin(fastMovingThresh0 + fastMovingThresh1, ccdThreshold);
mToiType = eEstimate;
//If the objects are not moving fast-enough relative to each-other to warrant CCD, set estimated time as PX_MAX_REAL
if((relTr.magnitudeSquared()) <= (sumFastMovingThresh * sumFastMovingThresh))
{
mToiType = eEstimate;
mMinToi = PX_MAX_REAL;
return PX_MAX_REAL;
}
//Otherwise, the objects *are* moving fast-enough so perform estimation pass
if(g1 == PxGeometryType::eTRIANGLEMESH)
{
//Special-case estimation code for meshes
const PxF32 toi = Gu::SweepEstimateAnyShapeMesh(*ccdShape0, *ccdShape1, restDistance, sumFastMovingThresh);
mMinToi = toi;
return toi;
}
else if (g1 == PxGeometryType::eHEIGHTFIELD)
{
//Special-case estimation code for heightfields
const PxF32 toi = Gu::SweepEstimateAnyShapeHeightfield(*ccdShape0, *ccdShape1, restDistance, sumFastMovingThresh);
mMinToi = toi;
return toi;
}
//Generic estimation code for prim-prim sweeps
const PxVec3& centreA = ccdShape0->mCenter;
const PxVec3 extentsA = ccdShape0->mExtents + PxVec3(restDistance);
const PxVec3& centreB = ccdShape1->mCenter;
const PxVec3& extentsB = ccdShape1->mExtents;
const PxF32 toi = Gu::sweepAABBAABB(centreA, extentsA * 1.1f, centreB, extentsB * 1.1f, trA, trB);
mMinToi = toi;
return toi;
}
bool PxsCCDPair::sweepAdvanceToToi(PxReal dt, bool clipTrajectoryToToi)
{
PxsCCDShape* ccds0 = mCCDShape0;
PxsRigidBody* atom0 = mBa0;
PxsCCDShape* ccds1 = mCCDShape1;
PxsRigidBody* atom1 = mBa1;
const PxsCCDPair* thisPair = this;
//Both already had a pass so don't do anything
if ((atom0 == NULL || atom0->mCCD->mPassDone) && (atom1 == NULL || atom1->mCCD->mPassDone))
return false;
//Test to validate that they're both infinite mass objects. If so, there can be no response so terminate on a notification-only
if((atom0 == NULL || atom0->mCore->inverseMass == 0.0f) && (atom1 == NULL || atom1->mCore->inverseMass == 0.0f))
return false;
//If the TOI < 1.f. If not, this hit happens after this frame or at the very end of the frame. Either way, next frame can handle it
if (thisPair->mMinToi < 1.0f)
{
if(thisPair->mCm->getWorkUnit().flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE || thisPair->mMaxImpulse == 0.0f)
{
//Don't mark pass as done on either body
return true;
}
const PxReal minToi = thisPair->mMinToi;
const PxF32 penetration = -mPenetration * 10.0f;
const PxVec3 minToiNormal = thisPair->mMinToiNormal;
if (!minToiNormal.isNormalized())
{
// somehow we got zero normal. This can happen for instance if two identical objects spawn exactly on top of one another
// abort ccd and clip to current toi
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(minToi);
atom0->advanceToToi(minToi, dt, true);
atom0->mCCD->mUpdateCount++;
}
return true;
}
//Get the material indices...
const PxReal restitution = mRestitution;
const PxReal sFriction = mStaticFriction;
const PxReal dFriction = mDynamicFriction;
PxVec3 v0(0.0f), v1(0.0f);
PxReal invMass0(0.0f), invMass1(0.0f);
#if CCD_ANGULAR_IMPULSE
PxMat33 invInertia0(PxVec3(0.0f), PxVec3(0.0f), PxVec3(0.0f)), invInertia1(PxVec3(0.0f), PxVec3(0.0f), PxVec3(0.0f));
PxVec3 localPoint0(0.0f), localPoint1(0.0f);
#endif
const PxReal dom0 = mCm->getDominance0();
const PxReal dom1 = mCm->getDominance1();
//Work out velocity and invMass for body 0
if(atom0)
{
//Put contact point in local space, then find how much point is moving using point velocity...
#if CCD_ANGULAR_IMPULSE
localPoint0 = mMinToiPoint - trA.p;
v0 = atom0->mCore->linearVelocity + atom0->mCore->angularVelocity.cross(localPoint0);
physx::Cm::transformInertiaTensor(atom0->mCore->inverseInertia, PxMat33(trA.q),invInertia0);
invInertia0 *= dom0;
#else
v0 = atom0->mCore->linearVelocity + atom0->mCore->angularVelocity.cross(ccds0->mCurrentTransform.p - atom0->mCore->body2World.p);
#endif
invMass0 = atom0->getInvMass() * dom0;
}
//Work out velocity and invMass for body 1
if(atom1)
{
//Put contact point in local space, then find how much point is moving using point velocity...
#if CCD_ANGULAR_IMPULSE
localPoint1 = mMinToiPoint - trB.p;
v1 = atom1->mCore->linearVelocity + atom1->mCore->angularVelocity.cross(localPoint1);
physx::Cm::transformInertiaTensor(atom1->mCore->inverseInertia, PxMat33(trB.q),invInertia1);
invInertia1 *= dom1;
#else
v1 = atom1->mCore->linearVelocity + atom1->mCore->angularVelocity.cross(ccds1->mCurrentTransform.p - atom1->mCore->body2World.p);
#endif
invMass1 = atom1->getInvMass() * dom1;
}
PX_ASSERT(v0.isFinite() && v1.isFinite());
//Work out relative velocity
const PxVec3 vRel = v1 - v0;
//Project relative velocity onto contact normal and bias with penetration
const PxReal relNorVel = vRel.dot(minToiNormal);
const PxReal relNorVelPlusPen = relNorVel + penetration;
#if CCD_ANGULAR_IMPULSE
if(relNorVelPlusPen >= -1e-6f)
{
//we fall back on linear only parts...
localPoint0 = PxVec3(0.0f);
localPoint1 = PxVec3(0.0f);
v0 = atom0 ? atom0->getLinearVelocity() : PxVec3(0.0f);
v1 = atom1 ? atom1->getLinearVelocity() : PxVec3(0.0f);
vRel = v1 - v0;
relNorVel = vRel.dot(minToiNormal);
relNorVelPlusPen = relNorVel + penetration;
}
#endif
//If the relative motion is moving towards each-other, respond
if(relNorVelPlusPen < -1e-6f)
{
PxReal sumRecipMass = invMass0 + invMass1;
const PxReal jLin = relNorVelPlusPen;
const PxReal normalResponse = (1.0f + restitution) * jLin;
#if CCD_ANGULAR_IMPULSE
const PxVec3 angularMom0 = invInertia0 * (localPoint0.cross(mMinToiNormal));
const PxVec3 angularMom1 = invInertia1 * (localPoint1.cross(mMinToiNormal));
const PxReal jAng = minToiNormal.dot(angularMom0.cross(localPoint0) + angularMom1.cross(localPoint1));
const PxReal impulseDivisor = sumRecipMass + jAng;
#else
const PxReal impulseDivisor = sumRecipMass;
#endif
const PxReal jImp = PxMax(-mMaxImpulse, normalResponse/impulseDivisor);
PxVec3 j(0.0f);
//If the user requested CCD friction, calculate friction forces.
//Note, CCD is *linear* so friction is also linear. The net result is that CCD friction can stop bodies' lateral motion so its better to have it disabled
//unless there's a real need for it.
if(mHasFriction)
{
const PxVec3 vPerp = vRel - relNorVel * minToiNormal;
PxVec3 tDir = vPerp;
const PxReal length = tDir.normalize();
const PxReal vPerpImp = length/impulseDivisor;
PxF32 fricResponse = 0.0f;
const PxF32 staticResponse = (jImp*sFriction);
const PxF32 dynamicResponse = (jImp*dFriction);
if (PxAbs(staticResponse) >= vPerpImp)
fricResponse = vPerpImp;
else
{
fricResponse = -dynamicResponse /* times m0 */;
}
//const PxVec3 fricJ = -vPerp.getNormalized() * (fricResponse/impulseDivisor);
const PxVec3 fricJ = tDir * (fricResponse);
j = jImp * mMinToiNormal + fricJ;
}
else
{
j = jImp * mMinToiNormal;
}
verifyCCDPair(*this);
//If we have a negative impulse value, then we need to apply it. If not, the bodies are separating (no impulse to apply).
if(jImp < 0.0f)
{
mAppliedForce = -jImp;
//Adjust velocities
if((atom0 != NULL && atom0->mCCD->mPassDone) ||
(atom1 != NULL && atom1->mCCD->mPassDone))
{
mPenetrationPostStep = 0.0f;
}
else
{
if (atom0)
{
//atom0->mAcceleration.linear = atom0->getLinearVelocity(); // to provide pre-"solver" velocity in contact reports
atom0->setLinearVelocity(atom0->getLinearVelocity() + j * invMass0);
atom0->constrainLinearVelocity();
#if CCD_ANGULAR_IMPULSE
atom0->mAcceleration.angular = atom0->getAngularVelocity(); // to provide pre-"solver" velocity in contact reports
atom0->setAngularVelocity(atom0->getAngularVelocity() + invInertia0 * localPoint0.cross(j));
atom0->constrainAngularVelocity();
#endif
}
if (atom1)
{
//atom1->mAcceleration.linear = atom1->getLinearVelocity(); // to provide pre-"solver" velocity in contact reports
atom1->setLinearVelocity(atom1->getLinearVelocity() - j * invMass1);
atom1->constrainLinearVelocity();
#if CCD_ANGULAR_IMPULSE
atom1->mAcceleration.angular = atom1->getAngularVelocity(); // to provide pre-"solver" velocity in contact reports
atom1->setAngularVelocity(atom1->getAngularVelocity() - invInertia1 * localPoint1.cross(j));
atom1->constrainAngularVelocity();
#endif
}
}
}
}
//Update poses
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(minToi);
atom0->advanceToToi(minToi, dt, clipTrajectoryToToi && mPenetrationPostStep == 0.0f);
atom0->mCCD->mUpdateCount++;
}
if (atom1 && !atom1->mCCD->mPassDone)
{
atom1->advancePrevPoseToToi(minToi);
atom1->advanceToToi(minToi, dt, clipTrajectoryToToi && mPenetrationPostStep == 0.0f);
atom1->mCCD->mUpdateCount++;
}
//If we had a penetration post-step (i.e. an initial overlap), step forwards slightly after collision response
if(mPenetrationPostStep > 0.0f)
{
if (atom0 && !atom0->mCCD->mPassDone)
{
atom0->advancePrevPoseToToi(mPenetrationPostStep);
if(clipTrajectoryToToi)
atom0->advanceToToi(mPenetrationPostStep, dt, clipTrajectoryToToi);
}
if (atom1 && !atom1->mCCD->mPassDone)
{
atom1->advancePrevPoseToToi(mPenetrationPostStep);
if(clipTrajectoryToToi)
atom1->advanceToToi(mPenetrationPostStep, dt, clipTrajectoryToToi);
}
}
//Mark passes as done
if (atom0)
{
atom0->mCCD->mPassDone = true;
atom0->mCCD->mHasAnyPassDone = true;
}
if (atom1)
{
atom1->mCCD->mPassDone = true;
atom1->mCCD->mHasAnyPassDone = true;
}
return true;
//return false;
}
else
{
printCCDDebug("advToi: clean sweep", atom0, mG0);
}
return false;
}
namespace
{
struct IslandCompare
{
bool operator()(PxsCCDPair& a, PxsCCDPair& b) const { return a.mIslandId < b.mIslandId; }
};
struct IslandPtrCompare
{
bool operator()(PxsCCDPair*& a, PxsCCDPair*& b) const { return a->mIslandId < b->mIslandId; }
};
struct ToiCompare
{
bool operator()(PxsCCDPair& a, PxsCCDPair& b) const
{
return (a.mMinToi < b.mMinToi) ||
((a.mMinToi == b.mMinToi) && (a.mBa1 != NULL && b.mBa1 == NULL));
}
};
struct ToiPtrCompare
{
bool operator()(PxsCCDPair*& a, PxsCCDPair*& b) const
{
return (a->mMinToi < b->mMinToi) ||
((a->mMinToi == b->mMinToi) && (a->mBa1 != NULL && b->mBa1 == NULL));
}
};
// --------------------------------------------------------------
/**
\brief Class to perform a set of sweep estimate tasks
*/
class PxsCCDSweepTask : public Cm::Task
{
PxsCCDPair** mPairs;
PxU32 mNumPairs;
PxReal mCCDThreshold;
public:
PxsCCDSweepTask(PxU64 contextID, PxsCCDPair** pairs, PxU32 nPairs, PxReal ccdThreshold) :
Cm::Task(contextID), mPairs(pairs), mNumPairs(nPairs), mCCDThreshold(ccdThreshold)
{
}
virtual void runInternal()
{
for (PxU32 j = 0; j < mNumPairs; j++)
{
PxsCCDPair& pair = *mPairs[j];
pair.sweepEstimateToi(mCCDThreshold);
pair.mEstimatePass = 0;
}
}
virtual const char *getName() const
{
return "PxsContext.CCDSweep";
}
private:
PxsCCDSweepTask& operator=(const PxsCCDSweepTask&);
};
#define ENABLE_RESWEEP 1
// --------------------------------------------------------------
/**
\brief Class to advance a set of islands
*/
class PxsCCDAdvanceTask : public Cm::Task
{
PxsCCDPair** mCCDPairs;
PxU32 mNumPairs;
PxsContext* mContext;
PxsCCDContext* mCCDContext;
PxReal mDt;
PxU32 mCCDPass;
const PxsCCDBodyArray& mCCDBodies;
PxU32 mFirstThreadIsland;
PxU32 mIslandsPerThread;
PxU32 mTotalIslandCount;
PxU32 mFirstIslandPair; // pairs are sorted by island
PxsCCDBody** mIslandBodies;
PxU16* mNumIslandBodies;
PxI32* mSweepTotalHits;
bool mClipTrajectory;
bool mDisableResweep;
PxsCCDAdvanceTask& operator=(const PxsCCDAdvanceTask&);
public:
PxsCCDAdvanceTask(PxsCCDPair** pairs, PxU32 nPairs, const PxsCCDBodyArray& ccdBodies,
PxsContext* context, PxsCCDContext* ccdContext, PxReal dt, PxU32 ccdPass,
PxU32 firstIslandPair, PxU32 firstThreadIsland, PxU32 islandsPerThread, PxU32 totalIslands,
PxsCCDBody** islandBodies, PxU16* numIslandBodies, bool clipTrajectory, bool disableResweep,
PxI32* sweepTotalHits)
: Cm::Task(context->getContextId()), mCCDPairs(pairs), mNumPairs(nPairs), mContext(context), mCCDContext(ccdContext), mDt(dt),
mCCDPass(ccdPass), mCCDBodies(ccdBodies), mFirstThreadIsland(firstThreadIsland),
mIslandsPerThread(islandsPerThread), mTotalIslandCount(totalIslands), mFirstIslandPair(firstIslandPair),
mIslandBodies(islandBodies), mNumIslandBodies(numIslandBodies), mSweepTotalHits(sweepTotalHits),
mClipTrajectory(clipTrajectory), mDisableResweep(disableResweep)
{
PX_ASSERT(mFirstIslandPair < mNumPairs);
}
virtual void runInternal()
{
PxI32 sweepTotalHits = 0;
PxcNpThreadContext* threadContext = mContext->getNpThreadContext();
PxReal ccdThreshold = mCCDContext->getCCDThreshold();
// --------------------------------------------------------------------------------------
// loop over island labels assigned to this thread
PxU32 islandStart = mFirstIslandPair;
PxU32 lastIsland = PxMin(mFirstThreadIsland + mIslandsPerThread, mTotalIslandCount);
for (PxU32 iIsland = mFirstThreadIsland; iIsland < lastIsland; iIsland++)
{
if (islandStart >= mNumPairs)
// this is possible when for instance there are two islands with 0 pairs in the second
// since islands are initially segmented using bodies, not pairs, it can happen
break;
// --------------------------------------------------------------------------------------
// sort all pairs within current island by toi
PxU32 islandEnd = islandStart+1;
PX_ASSERT(mCCDPairs[islandStart]->mIslandId == iIsland);
while (islandEnd < mNumPairs && mCCDPairs[islandEnd]->mIslandId == iIsland) // find first index past the current island id
islandEnd++;
if (islandEnd > islandStart+1)
PxSort(mCCDPairs+islandStart, islandEnd-islandStart, ToiPtrCompare());
PX_ASSERT(islandEnd <= mNumPairs);
// --------------------------------------------------------------------------------------
// advance all affected pairs within each island to min toi
// for each pair (A,B) in toi order, find any later-toi pairs that collide against A or B
// and resweep against changed trajectories of either A or B (excluding statics and kinematics)
PxReal islandMinToi = PX_MAX_REAL;
PxU32 estimatePass = 1;
PxReal dt = mDt;
for (PxU32 iFront = islandStart; iFront < islandEnd; iFront++)
{
PxsCCDPair& pair = *mCCDPairs[iFront];
verifyCCDPair(pair);
//If we have reached a pair with a TOI after 1.0, we can terminate this island
if(pair.mMinToi > 1.0f)
break;
bool needSweep0 = (pair.mBa0 && pair.mBa0->mCCD->mPassDone == false);
bool needSweep1 = (pair.mBa1 && pair.mBa1->mCCD->mPassDone == false);
//If both bodies have been updated (or one has been updated and the other is static), we can skip to the next pair
if(!(needSweep0 || needSweep1))
continue;
{
//If the pair was an estimate, we must perform an accurate sweep now
if(pair.mToiType == PxsCCDPair::eEstimate)
{
pair.sweepFindToi(*threadContext, dt, mCCDPass, ccdThreshold);
//Test to see if the pair is still the earliest pair.
if((iFront + 1) < islandEnd && mCCDPairs[iFront+1]->mMinToi < pair.mMinToi)
{
//If there is an earlier pair, we push this pair into its correct place in the list and return to the start
//of this update loop
PxsCCDPair* tmp = &pair;
PxU32 index = iFront;
while((index + 1) < islandEnd && mCCDPairs[index+1]->mMinToi < pair.mMinToi)
{
mCCDPairs[index] = mCCDPairs[index+1];
++index;
}
mCCDPairs[index] = tmp;
--iFront;
continue;
}
}
if (pair.mMinToi > 1.0f)
break;
//We now have the earliest contact pair for this island and one/both of the bodies have not been updated. We now perform
//contact modification to find out if the user still wants to respond to the collision
if(pair.mMinToi <= islandMinToi &&
pair.mIsModifiable &&
mCCDContext->getCCDContactModifyCallback())
{
PX_ALIGN(16, PxU8 dataBuffer[sizeof(PxModifiableContact) + sizeof(PxContactPatch)]);
PxContactPatch* patch = reinterpret_cast<PxContactPatch*>(dataBuffer);
PxModifiableContact* point = reinterpret_cast<PxModifiableContact*>(patch + 1);
patch->mMassModification.linear0 = 1.f;
patch->mMassModification.linear1 = 1.f;
patch->mMassModification.angular0 = 1.f;
patch->mMassModification.angular1 = 1.f;
patch->normal = pair.mMinToiNormal;
patch->dynamicFriction = pair.mDynamicFriction;
patch->staticFriction = pair.mStaticFriction;
patch->materialIndex0 = pair.mMaterialIndex0;
patch->materialIndex1 = pair.mMaterialIndex1;
patch->startContactIndex = 0;
patch->nbContacts = 1;
patch->materialFlags = 0;
patch->internalFlags = 0; //44 //Can be a U16
point->contact = pair.mMinToiPoint;
point->normal = pair.mMinToiNormal;
//KS - todo - reintroduce face indices!!!!
//point.internalFaceIndex0 = PXC_CONTACT_NO_FACE_INDEX;
//point.internalFaceIndex1 = pair.mFaceIndex;
point->materialIndex0 = pair.mMaterialIndex0;
point->materialIndex1 = pair.mMaterialIndex1;
point->dynamicFriction = pair.mDynamicFriction;
point->staticFriction = pair.mStaticFriction;
point->restitution = pair.mRestitution;
point->separation = 0.0f;
point->maxImpulse = PX_MAX_REAL;
point->materialFlags = 0;
point->targetVelocity = PxVec3(0.0f);
mCCDContext->runCCDModifiableContact(point, 1, pair.mCCDShape0->mShapeCore, pair.mCCDShape1->mShapeCore,
pair.mCCDShape0->mRigidCore, pair.mCCDShape1->mRigidCore, pair.mBa0, pair.mBa1);
if ((patch->internalFlags & PxContactPatch::eHAS_MAX_IMPULSE))
pair.mMaxImpulse = point->maxImpulse;
pair.mDynamicFriction = point->dynamicFriction;
pair.mStaticFriction = point->staticFriction;
pair.mRestitution = point->restitution;
pair.mMinToiPoint = point->contact;
pair.mMinToiNormal = point->normal;
}
}
// pair.mIsEarliestToiHit is used for contact notification.
// only mark as such if this is the first impact for both atoms of this pair (the impacts are sorted)
// and there was an actual impact for this pair
bool atom0FirstSweep = (pair.mBa0 && pair.mBa0->mCCD->mPassDone == false) || pair.mBa0 == NULL;
bool atom1FirstSweep = (pair.mBa1 && pair.mBa1->mCCD->mPassDone == false) || pair.mBa1 == NULL;
if (pair.mMinToi <= 1.0f && atom0FirstSweep && atom1FirstSweep)
pair.mIsEarliestToiHit = true;
// sweepAdvanceToToi sets mCCD->mPassDone flags on both atoms, doesn't advance atoms with flag already set
// can advance one atom if the other already has the flag set
bool advanced = pair.sweepAdvanceToToi( dt, mClipTrajectory);
if(pair.mMinToi < 0.0f)
pair.mMinToi = 0.0f;
verifyCCDPair(pair);
if (advanced && pair.mMinToi <= 1.0f)
{
sweepTotalHits++;
PxU32 islandStartIndex = iIsland == 0 ? 0 : PxU32(mNumIslandBodies[iIsland - 1]);
PxU32 islandEndIndex = mNumIslandBodies[iIsland];
if(pair.mMinToi > 0.0f)
{
for(PxU32 a = islandStartIndex; a < islandEndIndex; ++a)
{
if(!mIslandBodies[a]->mPassDone)
{
//If the body has not updated, we advance it to the current time-step that the island has reached.
PxsRigidBody* atom = mIslandBodies[a]->mBody;
atom->advancePrevPoseToToi(pair.mMinToi);
atom->mCCD->mTimeLeft = PxMax(atom->mCCD->mTimeLeft * (1.0f - pair.mMinToi), CCD_MIN_TIME_LEFT);
atom->mCCD->mUpdateCount++;
}
}
//Adjust remaining dt for the island
dt -= dt * pair.mMinToi;
const PxReal recipOneMinusToi = 1.f/(1.f - pair.mMinToi);
for(PxU32 k = iFront+1; k < islandEnd; ++k)
{
PxsCCDPair& pair1 = *mCCDPairs[k];
pair1.mMinToi = (pair1.mMinToi - pair.mMinToi)*recipOneMinusToi;
}
}
//If we disabled response, we don't need to resweep at all
if(!mDisableResweep && !(pair.mCm->getWorkUnit().flags & PxcNpWorkUnitFlag::eDISABLE_RESPONSE) && pair.mMaxImpulse != 0.0f)
{
void* a0 = pair.mBa0 == NULL ? NULL : reinterpret_cast<void*>(pair.mBa0);
void* a1 = pair.mBa1 == NULL ? NULL : reinterpret_cast<void*>(pair.mBa1);
for(PxU32 k = iFront+1; k < islandEnd; ++k)
{
PxsCCDPair& pair1 = *mCCDPairs[k];
void* b0 = pair1.mBa0 == NULL ? reinterpret_cast<void*>(pair1.mCCDShape0) : reinterpret_cast<void*>(pair1.mBa0);
void* b1 = pair1.mBa1 == NULL ? reinterpret_cast<void*>(pair1.mCCDShape1) : reinterpret_cast<void*>(pair1.mBa1);
bool containsStatic = pair1.mBa0 == NULL || pair1.mBa1 == NULL;
PX_ASSERT(b0 != NULL && b1 != NULL);
if ((!containsStatic) &&
((b0 == a0 && b1 != a1) || (b1 == a0 && b0 != a1) ||
(b0 == a1 && b1 != a0) || (b1 == a1 && b0 != a0))
)
{
if(estimatePass != pair1.mEstimatePass)
{
pair1.mEstimatePass = estimatePass;
// resweep pair1 since either b0 or b1 trajectory has changed
PxReal oldToi = pair1.mMinToi;
verifyCCDPair(pair1);
PxReal toi1 = pair1.sweepEstimateToi(ccdThreshold);
PX_ASSERT(pair1.mBa0); // this is because mMinToiNormal is the impact point here
if (toi1 < oldToi)
{
// if toi decreased, resort the array backwards
PxU32 kk = k;
PX_ASSERT(kk > 0);
while (kk-1 > iFront && mCCDPairs[kk-1]->mMinToi > toi1)
{
PxsCCDPair* temp = mCCDPairs[kk-1];
mCCDPairs[kk-1] = mCCDPairs[kk];
mCCDPairs[kk] = temp;
kk--;
}
}
else if (toi1 > oldToi)
{
// if toi increased, resort the array forwards
PxU32 kk = k;
PX_ASSERT(kk > 0);
PxU32 stepped = 0;
while (kk+1 < islandEnd && mCCDPairs[kk+1]->mMinToi < toi1)
{
stepped = 1;
PxsCCDPair* temp = mCCDPairs[kk+1];
mCCDPairs[kk+1] = mCCDPairs[kk];
mCCDPairs[kk] = temp;
kk++;
}
k -= stepped;
}
}
}
}
}
estimatePass++;
} // if pair.minToi <= 1.0f
} // for iFront
islandStart = islandEnd;
} // for (PxU32 iIsland = mFirstThreadIsland; iIsland < lastIsland; iIsland++)
PxAtomicAdd(mSweepTotalHits, sweepTotalHits);
mContext->putNpThreadContext(threadContext);
}
virtual const char *getName() const
{
return "PxsContext.CCDAdvance";
}
};
}
// --------------------------------------------------------------
// CCD main function
// Overall structure:
/*
for nPasses (passes are now handled in void Sc::Scene::updateCCDMultiPass)
update CCD broadphase, generate a list of CMs
foreach CM
create CCDPairs, CCDBodies from CM
add shapes, overlappingShapes to CCDBodies
foreach CCDBody
assign island labels per body
uses overlappingShapes
foreach CCDPair
assign island label to pair
sort all pairs by islandId
foreach CCDPair
sweep/find toi
compute normal:
foreach island
sort within island by toi
foreach pair within island
advanceToToi
from curPairInIsland to lastPairInIsland
resweep if needed
*/
// --------------------------------------------------------------
void PxsCCDContext::updateCCDBegin()
{
openCCDLog();
miCCDPass = 0;
mSweepTotalHits = 0;
}
// --------------------------------------------------------------
void PxsCCDContext::updateCCDEnd()
{
if (miCCDPass == mCCDMaxPasses - 1 || mSweepTotalHits == 0)
{
// --------------------------------------------------------------------------------------
// At last CCD pass we need to reset mBody pointers back to NULL
// so that the next frame we know which ones need to be newly paired with PxsCCDBody objects
// also free the CCDBody memory blocks
mMutex.lock();
for (PxU32 j = 0, n = mCCDBodies.size(); j < n; j++)
{
if (mCCDBodies[j].mBody->mCCD && mCCDBodies[j].mBody->mCCD->mHasAnyPassDone)
{
//Record this body in the list of bodies that were updated
mUpdatedCCDBodies.pushBack(mCCDBodies[j].mBody);
}
mCCDBodies[j].mBody->mCCD = NULL;
mCCDBodies[j].mBody->getCore().isFastMoving = false; //Clear the "isFastMoving" bool
}
mMutex.unlock();
mCCDBodies.clear_NoDelete();
}
mCCDShapes.clear_NoDelete();
mMap.clear();
miCCDPass++;
}
// --------------------------------------------------------------
void PxsCCDContext::verifyCCDBegin()
{
#if 0
// validate that all bodies have a NULL mCCD pointer
if (miCCDPass == 0)
{
PxBitMap::Iterator it(mActiveContactManager);
for (PxU32 index = it.getNext(); index != PxBitMap::Iterator::DONE; index = it.getNext())
{
PxsContactManager* cm = mContactManagerPool.findByIndexFast(index);
PxsRigidBody* b0 = cm->mBodyShape0->getBodyAtom(), *b1 = cm->mBodyShape1->getBodyAtom();
PX_ASSERT(b0 == NULL || b0->mCCD == NULL);
PX_ASSERT(b1 == NULL || b1->mCCD == NULL);
}
}
#endif
}
void PxsCCDContext::resetContactManagers()
{
PxBitMap::Iterator it(mContext->mContactManagersWithCCDTouch);
for (PxU32 index = it.getNext(); index != PxBitMap::Iterator::DONE; index = it.getNext())
{
PxsContactManager* cm = mContext->mContactManagerPool.findByIndexFast(index);
cm->clearCCDContactInfo();
}
mContext->mContactManagersWithCCDTouch.clear();
}
// --------------------------------------------------------------
// PT: version that early exits & doesn't read all the data
static PX_FORCE_INLINE bool pairNeedsCCD(const PxsContactManager* cm)
{
// skip disabled pairs
if(!cm->getCCD())
return false;
const PxcNpWorkUnit& workUnit = cm->getWorkUnit();
// skip articulation vs articulation ccd
//Actually. This is fundamentally wrong also :(. We only want to skip links in the same articulation - not all articulations!!!
{
const bool isJoint0 = (workUnit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY0) == PxcNpWorkUnitFlag::eARTICULATION_BODY0;
if(isJoint0)
{
const bool isJoint1 = (workUnit.flags & PxcNpWorkUnitFlag::eARTICULATION_BODY1) == PxcNpWorkUnitFlag::eARTICULATION_BODY1;
if(isJoint1)
return false;
}
}
{
const bool isFastMoving0 = static_cast<const PxsBodyCore*>(workUnit.rigidCore0)->isFastMoving != 0;
if(isFastMoving0)
return true;
const bool isFastMoving1 = (workUnit.flags & (PxcNpWorkUnitFlag::eARTICULATION_BODY1 | PxcNpWorkUnitFlag::eDYNAMIC_BODY1)) ? static_cast<const PxsBodyCore*>(workUnit.rigidCore1)->isFastMoving != 0: false;
return isFastMoving1;
}
}
static PxsCCDShape* processShape(
PxVec3& tr, PxReal& threshold, PxsCCDShape* ccdShape,
const PxsRigidCore* const rc, const PxsShapeCore* const sc, const PxsRigidBody* const ba,
const PxsContactManager* const cm, IG::IslandSim& islandSim, PxsCCDShapeArray& mCCDShapes, PxHashMap<PxsRigidShapePair, PxsCCDShape*>& mMap, bool flag)
{
if(ccdShape == NULL)
{
//If we hadn't already created ccdShape, create one
ccdShape = &mCCDShapes.pushBack();
ccdShape->mRigidCore = rc;
ccdShape->mShapeCore = sc;
ccdShape->mGeometry = &sc->mGeometry.getGeometry();
mMap.insert(PxsRigidShapePair(rc, sc), ccdShape);
PxTransform32 tm;
getAbsPose(tm, ccdShape, ba);
PxTransform32 oldTm;
if(ba)
getLastCCDAbsPose(oldTm, ccdShape, ba);
else
oldTm = tm;
tr = tm.p - oldTm.p;
PxVec3p origin, extents;
//Compute the shape's bounds and CCD threshold
threshold = computeBoundsWithCCDThreshold(origin, extents, sc->mGeometry.getGeometry(), tm);
//Set up the CCD shape
ccdShape->mCenter = origin - tr;
ccdShape->mExtents = extents;
ccdShape->mFastMovingThreshold = threshold;
ccdShape->mPrevTransform = oldTm;
ccdShape->mCurrentTransform = tm;
ccdShape->mUpdateCount = 0;
ccdShape->mNodeIndex = flag ? islandSim.getNodeIndex2(cm->getWorkUnit().mEdgeIndex)
: islandSim.getNodeIndex1(cm->getWorkUnit().mEdgeIndex);
}
else
{
//We had already created the shape, so extract the threshold and translation components
threshold = ccdShape->mFastMovingThreshold;
tr = ccdShape->mCurrentTransform.p - ccdShape->mPrevTransform.p;
}
return ccdShape;
}
void PxsCCDContext::updateCCD(PxReal dt, PxBaseTask* continuation, IG::IslandSim& islandSim, bool disableResweep, PxI32 numFastMovingShapes)
{
//Flag to run a slightly less-accurate version of CCD that will ensure that objects don't tunnel through the static world but is not as reliable for dynamic-dynamic collisions
mDisableCCDResweep = disableResweep;
mThresholdStream.clear(); // clear force threshold report stream
mContext->clearManagerTouchEvents();
if (miCCDPass == 0)
{
resetContactManagers();
}
// If we're not in the first pass and the previous pass had no sweeps or the BP didn't generate any fast-moving shapes, we can skip CCD entirely
if ((miCCDPass > 0 && mSweepTotalHits == 0) || (numFastMovingShapes == 0))
{
mSweepTotalHits = 0;
updateCCDEnd();
return;
}
mSweepTotalHits = 0;
PX_ASSERT(continuation);
PX_ASSERT(continuation->getReference() > 0);
//printf("CCD 1\n");
mCCDThreadContext = mContext->getNpThreadContext();
mCCDThreadContext->mDt = dt; // doesn't get set anywhere else since it's only used for CCD now
verifyCCDBegin();
// --------------------------------------------------------------------------------------
// From a list of active CMs, build a temporary array of PxsCCDPair objects (allocated in blocks)
// this is done to gather scattered data from memory and also to reduce PxsRidigBody permanent memory footprint
// we have to do it every pass since new CMs can become fast moving after each pass (and sometimes cease to be)
mCCDPairs.clear_NoDelete();
mCCDPtrPairs.forceSize_Unsafe(0);
mUpdatedCCDBodies.forceSize_Unsafe(0);
mCCDOverlaps.clear_NoDelete();
PxU32 nbKinematicStaticCollisions = 0;
bool needsSweep = false;
{
PX_PROFILE_ZONE("Sim.ccdPair", mContext->mContextID);
PxBitMap::Iterator it(mContext->mActiveContactManagersWithCCD);
for (PxU32 index = it.getNext(); index != PxBitMap::Iterator::DONE; index = it.getNext())
{
PxsContactManager* cm = mContext->mContactManagerPool.findByIndexFast(index);
if(!pairNeedsCCD(cm))
continue;
const PxcNpWorkUnit& unit = cm->getWorkUnit();
const PxsRigidCore* rc0 = unit.rigidCore0;
const PxsRigidCore* rc1 = unit.rigidCore1;
{
const PxsShapeCore* sc0 = unit.shapeCore0;
const PxsShapeCore* sc1 = unit.shapeCore1;
PxsRigidBody* ba0 = cm->mRigidBody0;
PxsRigidBody* ba1 = cm->mRigidBody1;
//Look up the body/shape pair in our CCDShape map
const PxPair<const PxsRigidShapePair, PxsCCDShape*>* ccdShapePair0 = mMap.find(PxsRigidShapePair(rc0, sc0));
const PxPair<const PxsRigidShapePair, PxsCCDShape*>* ccdShapePair1 = mMap.find(PxsRigidShapePair(rc1, sc1));
//If the CCD shapes exist, extract them from the map
PxsCCDShape* ccdShape0 = ccdShapePair0 ? ccdShapePair0->second : NULL;
PxsCCDShape* ccdShape1 = ccdShapePair1 ? ccdShapePair1->second : NULL;
PxReal threshold0 = 0.0f;
PxReal threshold1 = 0.0f;
PxVec3 trA(0.0f);
PxVec3 trB(0.0f);
ccdShape0 = processShape(trA, threshold0, ccdShape0, rc0, sc0, ba0, cm, islandSim, mCCDShapes, mMap, false);
ccdShape1 = processShape(trB, threshold1, ccdShape1, rc1, sc1, ba1, cm, islandSim, mCCDShapes, mMap, true);
{
//Initialize the CCD bodies
PxsRigidBody* atoms[2] = {ba0, ba1};
for (int k = 0; k < 2; k++)
{
PxsRigidBody* b = atoms[k];
//If there isn't a body (i.e. it's a static), no need to create a CCD body
if (!b)
continue;
if (b->mCCD == NULL)
{
// this rigid body has no CCD body created for it yet. Create and initialize one.
PxsCCDBody& newB = mCCDBodies.pushBack();
b->mCCD = &newB;
b->mCCD->mIndex = PxTo16(mCCDBodies.size()-1);
b->mCCD->mBody = b;
b->mCCD->mTimeLeft = 1.0f;
b->mCCD->mOverlappingObjects = NULL;
b->mCCD->mUpdateCount = 0;
b->mCCD->mHasAnyPassDone = false;
b->mCCD->mNbInteractionsThisPass = 0;
}
b->mCCD->mPassDone = 0;
b->mCCD->mNbInteractionsThisPass++;
}
if(ba0 && ba1)
{
//If both bodies exist (i.e. this is dynamic-dynamic collision), we create an
//overlap between the 2 bodies used for island detection.
if(!(ba0->isKinematic() || ba1->isKinematic()))
{
if(!ba0->mCCD->overlaps(ba1->mCCD))
{
PxsCCDOverlap* overlapA = &mCCDOverlaps.pushBack();
PxsCCDOverlap* overlapB = &mCCDOverlaps.pushBack();
overlapA->mBody = ba1->mCCD;
overlapB->mBody = ba0->mCCD;
ba0->mCCD->addOverlap(overlapA);
ba1->mCCD->addOverlap(overlapB);
}
}
}
}
//We now create the CCD pair. These are used in the CCD sweep and update phases
if (ba0->isKinematic() && (ba1 == NULL || ba1->isKinematic()))
nbKinematicStaticCollisions++;
{
PxsCCDPair& p = mCCDPairs.pushBack();
p.mBa0 = ba0;
p.mBa1 = ba1;
p.mCCDShape0 = ccdShape0;
p.mCCDShape1 = ccdShape1;
p.mHasFriction = rc0->hasCCDFriction() || rc1->hasCCDFriction();
p.mMinToi = PX_MAX_REAL;
p.mG0 = cm->mNpUnit.shapeCore0->mGeometry.getType();
p.mG1 = cm->mNpUnit.shapeCore1->mGeometry.getType();
p.mCm = cm;
p.mIslandId = 0xFFFFffff;
p.mIsEarliestToiHit = false;
p.mFaceIndex = PXC_CONTACT_NO_FACE_INDEX;
p.mIsModifiable = cm->isChangeable() != 0;
p.mAppliedForce = 0.0f;
p.mMaxImpulse = PxMin((ba0->mCore->mFlags & PxRigidBodyFlag::eENABLE_CCD_MAX_CONTACT_IMPULSE) ? ba0->mCore->maxContactImpulse : PX_MAX_F32,
(ba1 && ba1->mCore->mFlags & PxRigidBodyFlag::eENABLE_CCD_MAX_CONTACT_IMPULSE) ? ba1->mCore->maxContactImpulse : PX_MAX_F32);
#if PX_ENABLE_SIM_STATS
mContext->mSimStats.mNbCCDPairs[PxMin(p.mG0, p.mG1)][PxMax(p.mG0, p.mG1)] ++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
//Calculate the sum of the thresholds and work out if we need to perform a sweep.
const PxReal thresh = PxMin(threshold0 + threshold1, mCCDThreshold);
//If no shape pairs in the entire scene are fast-moving, we can bypass the entire of the CCD.
needsSweep = needsSweep || (trA - trB).magnitudeSquared() >= (thresh * thresh);
}
}
}
//There are no fast-moving pairs in this scene, so we can terminate right now without proceeding any further
if(!needsSweep)
{
updateCCDEnd();
mContext->putNpThreadContext(mCCDThreadContext);
return;
}
}
//Create the pair pointer buffer. This is a flattened array of pointers to pairs. It is used to sort the pairs
//into islands and is also used to prioritize the pairs into their TOIs
{
const PxU32 size = mCCDPairs.size();
mCCDPtrPairs.reserve(size);
for(PxU32 a = 0; a < size; ++a)
{
mCCDPtrPairs.pushBack(&mCCDPairs[a]);
}
mThresholdStream.reserve(PxNextPowerOfTwo(size));
for (PxU32 a = 0; a < mCCDBodies.size(); ++a)
{
mCCDBodies[a].mPreSolverVelocity.linear = mCCDBodies[a].mBody->getLinearVelocity();
mCCDBodies[a].mPreSolverVelocity.angular = mCCDBodies[a].mBody->getAngularVelocity();
}
}
PxU32 ccdBodyCount = mCCDBodies.size();
// --------------------------------------------------------------------------------------
// assign island labels
const PxU16 noLabelYet = 0xFFFF;
//Temporary array allocations. Ideally, we should use the scratch pad for there
PxArray<PxU32> islandLabels;
islandLabels.resize(ccdBodyCount);
PxArray<const PxsCCDBody*> stack;
stack.reserve(ccdBodyCount);
stack.forceSize_Unsafe(ccdBodyCount);
//Initialize all islands labels (for each body) to be unitialized
mIslandSizes.forceSize_Unsafe(0);
mIslandSizes.reserve(ccdBodyCount + 1);
mIslandSizes.forceSize_Unsafe(ccdBodyCount + 1);
for (PxU32 j = 0; j < ccdBodyCount; j++)
islandLabels[j] = noLabelYet;
PxU32 islandCount = 0;
PxU32 stackSize = 0;
const PxsCCDBody* top = NULL;
for (PxU32 j = 0; j < ccdBodyCount; j++)
{
//If the body has already been labelled or if it is kinematic, continue
//Also, if the body has no interactions this pass, continue. In single-pass CCD, only bodies with interactions would be part of the CCD. However,
//with multi-pass CCD, we keep all bodies that interacted in previous passes. If the body now has no interactions, we skip it to ensure that island grouping doesn't fail in
//later stages by assigning an island ID to a body with no interactions
if (islandLabels[j] != noLabelYet || mCCDBodies[j].mBody->isKinematic() || mCCDBodies[j].mNbInteractionsThisPass == 0)
continue;
top = &mCCDBodies[j];
//Otherwise push it back into the queue and proceed
islandLabels[j] = islandCount;
stack[stackSize++] = top;
// assign new label to unlabeled atom
// assign the same label to all connected nodes using stack traversal
PxU16 islandSize = 0;
while (stackSize > 0)
{
--stackSize;
const PxsCCDBody* ccdb = top;
top = stack[PxMax(1u, stackSize)-1];
PxsCCDOverlap* overlaps = ccdb->mOverlappingObjects;
while(overlaps)
{
if (islandLabels[overlaps->mBody->mIndex] == noLabelYet) // non-static & unlabeled?
{
islandLabels[overlaps->mBody->mIndex] = islandCount;
stack[stackSize++] = overlaps->mBody; // push adjacent node to the top of the stack
top = overlaps->mBody;
islandSize++;
}
overlaps = overlaps->mNext;
}
}
//Record island size
mIslandSizes[islandCount] = PxU16(islandSize + 1);
islandCount++;
}
PxU32 kinematicIslandId = islandCount;
islandCount += nbKinematicStaticCollisions;
for (PxU32 i = kinematicIslandId; i < islandCount; ++i)
mIslandSizes[i] = 1;
// --------------------------------------------------------------------------------------
// label pairs with island ids
// (need an extra loop since we don't maintain a mapping from atom to all of it's pairs)
mCCDIslandHistogram.clear(); // number of pairs per island
mCCDIslandHistogram.resize(islandCount);
PxU32 totalActivePairs = 0;
for (PxU32 j = 0, n = mCCDPtrPairs.size(); j < n; j++)
{
const PxU32 staticLabel = 0xFFFFffff;
PxsCCDPair& p = *mCCDPtrPairs[j];
PxU32 id0 = p.mBa0 && !p.mBa0->isKinematic()? islandLabels[p.mBa0->mCCD->getIndex()] : staticLabel;
PxU32 id1 = p.mBa1 && !p.mBa1->isKinematic()? islandLabels[p.mBa1->mCCD->getIndex()] : staticLabel;
PxU32 islandId = PxMin(id0, id1);
if (islandId == staticLabel)
islandId = kinematicIslandId++;
p.mIslandId = islandId;
mCCDIslandHistogram[p.mIslandId] ++;
PX_ASSERT(p.mIslandId != staticLabel);
totalActivePairs++;
}
PxU16 count = 0;
for(PxU16 a = 0; a < islandCount+1; ++a)
{
PxU16 islandSize = mIslandSizes[a];
mIslandSizes[a] = count;
count += islandSize;
}
mIslandBodies.forceSize_Unsafe(0);
mIslandBodies.reserve(ccdBodyCount);
mIslandBodies.forceSize_Unsafe(ccdBodyCount);
for(PxU32 a = 0; a < mCCDBodies.size(); ++a)
{
const PxU32 island = islandLabels[mCCDBodies[a].mIndex];
if (island != 0xFFFF)
{
PxU16 writeIndex = mIslandSizes[island];
mIslandSizes[island] = PxU16(writeIndex + 1);
mIslandBodies[writeIndex] = &mCCDBodies[a];
}
}
// --------------------------------------------------------------------------------------
// setup tasks
mPostCCDDepenetrateTask.setContinuation(continuation);
mPostCCDAdvanceTask.setContinuation(&mPostCCDDepenetrateTask);
mPostCCDSweepTask.setContinuation(&mPostCCDAdvanceTask);
// --------------------------------------------------------------------------------------
// sort all pairs by islands
PxSort(mCCDPtrPairs.begin(), mCCDPtrPairs.size(), IslandPtrCompare());
// --------------------------------------------------------------------------------------
// sweep all CCD pairs
const PxU32 nPairs = mCCDPtrPairs.size();
const PxU32 numThreads = PxMax(1u, mContext->mTaskManager->getCpuDispatcher()->getWorkerCount()); PX_ASSERT(numThreads > 0);
mCCDPairsPerBatch = PxMax<PxU32>((nPairs)/numThreads, 1);
for (PxU32 batchBegin = 0; batchBegin < nPairs; batchBegin += mCCDPairsPerBatch)
{
void* ptr = mContext->mTaskPool.allocate(sizeof(PxsCCDSweepTask));
PX_ASSERT_WITH_MESSAGE(ptr, "Failed to allocate PxsCCDSweepTask");
const PxU32 batchEnd = PxMin(nPairs, batchBegin + mCCDPairsPerBatch);
PX_ASSERT(batchEnd >= batchBegin);
PxsCCDSweepTask* task = PX_PLACEMENT_NEW(ptr, PxsCCDSweepTask)(mContext->getContextId(), mCCDPtrPairs.begin() + batchBegin, batchEnd - batchBegin,
mCCDThreshold);
task->setContinuation(*mContext->mTaskManager, &mPostCCDSweepTask);
task->removeReference();
}
mPostCCDSweepTask.removeReference();
mPostCCDAdvanceTask.removeReference();
mPostCCDDepenetrateTask.removeReference();
}
void PxsCCDContext::postCCDSweep(PxBaseTask* continuation)
{
// --------------------------------------------------------------------------------------
// batch up the islands and send them over to worker threads
PxU32 firstIslandPair = 0;
PxU32 islandCount = mCCDIslandHistogram.size();
for (PxU32 firstIslandInBatch = 0; firstIslandInBatch < islandCount;)
{
PxU32 pairSum = 0;
PxU32 lastIslandInBatch = firstIslandInBatch+1;
PxU32 j;
// add up the numbers in the histogram until we reach target pairsPerBatch
for (j = firstIslandInBatch; j < islandCount; j++)
{
pairSum += mCCDIslandHistogram[j];
if (pairSum > mCCDPairsPerBatch)
{
lastIslandInBatch = j+1;
break;
}
}
if (j == islandCount) // j is islandCount if not enough pairs were left to fill up to pairsPerBatch
{
if (pairSum == 0)
break; // we are done and there are no islands in this batch
lastIslandInBatch = islandCount;
}
void* ptr = mContext->mTaskPool.allocate(sizeof(PxsCCDAdvanceTask));
PX_ASSERT_WITH_MESSAGE(ptr , "Failed to allocate PxsCCDSweepTask");
bool clipTrajectory = (miCCDPass == mCCDMaxPasses-1);
PxsCCDAdvanceTask* task = PX_PLACEMENT_NEW(ptr, PxsCCDAdvanceTask) (
mCCDPtrPairs.begin(), mCCDPtrPairs.size(), mCCDBodies, mContext, this, mCCDThreadContext->mDt, miCCDPass,
firstIslandPair, firstIslandInBatch, lastIslandInBatch-firstIslandInBatch, islandCount,
mIslandBodies.begin(), mIslandSizes.begin(), clipTrajectory, mDisableCCDResweep,
&mSweepTotalHits);
firstIslandInBatch = lastIslandInBatch;
firstIslandPair += pairSum;
task->setContinuation(*mContext->mTaskManager, continuation);
task->removeReference();
} // for iIsland
}
static PX_FORCE_INLINE bool shouldCreateContactReports(const PxsRigidCore* rigidCore)
{
return static_cast<const PxsBodyCore*>(rigidCore)->contactReportThreshold != PXV_CONTACT_REPORT_DISABLED;
}
void PxsCCDContext::postCCDAdvance(PxBaseTask* /*continuation*/)
{
// --------------------------------------------------------------------------------------
// contact notifications: update touch status (multi-threading this section would probably slow it down but might be worth a try)
PxU32 countLost = 0, countFound = 0, countRetouch = 0;
PxU32 islandCount = mCCDIslandHistogram.size();
PxU32 index = 0;
for (PxU32 island = 0; island < islandCount; ++island)
{
PxU32 islandEnd = mCCDIslandHistogram[island] + index;
for(PxU32 j = index; j < islandEnd; ++j)
{
PxsCCDPair& p = *mCCDPtrPairs[j];
//The CCD pairs are ordered by TOI. If we reach a TOI > 1, we can terminate
if(p.mMinToi > 1.f)
break;
//If this was the earliest touch for the pair of bodies, we can notify the user about it. If not, it's a future collision that we haven't stepped to yet
if (p.mIsEarliestToiHit)
{
//Flag that we had a CCD contact
p.mCm->setHadCCDContact();
//Test/set the changed touch map
PxU16 oldTouch = p.mCm->getTouchStatus();
if (!oldTouch)
{
mContext->mContactManagerTouchEvent.growAndSet(p.mCm->getIndex());
p.mCm->mNpUnit.statusFlags = PxU16((p.mCm->mNpUnit.statusFlags & (~PxcNpWorkUnitStatusFlag::eHAS_NO_TOUCH)) | PxcNpWorkUnitStatusFlag::eHAS_TOUCH);
//Also need to write it in the CmOutput structure!!!!!
////The achieve this, we need to unregister the CM from the Nphase, then re-register it with the status set. This is the only way to force a push to the GPU
Sc::ShapeInteraction* interaction = p.mCm->getShapeInteraction();
mNphaseContext.unregisterContactManager(p.mCm);
mNphaseContext.registerContactManager(p.mCm, interaction, 1, 0);
countFound++;
}
else
{
mContext->mContactManagerTouchEvent.growAndSet(p.mCm->getIndex());
p.mCm->raiseCCDRetouch();
countRetouch++;
}
//Do we want to create reports?
const bool createReports =
p.mCm->mNpUnit.flags & PxcNpWorkUnitFlag::eOUTPUT_CONTACTS
|| (p.mCm->mNpUnit.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD
&& ((p.mCm->mNpUnit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0) && shouldCreateContactReports(p.mCm->mNpUnit.rigidCore0))
|| (p.mCm->mNpUnit.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1) && shouldCreateContactReports(p.mCm->mNpUnit.rigidCore1))));
if(createReports)
{
mContext->mContactManagersWithCCDTouch.growAndSet(p.mCm->getIndex());
const PxU32 numContacts = 1;
PxsMaterialInfo matInfo;
PxContactBuffer& buffer = mCCDThreadContext->mContactBuffer;
PxContactPoint& cp = buffer.contacts[0];
cp.point = p.mMinToiPoint;
cp.normal = -p.mMinToiNormal; //KS - discrete contact gen produces contacts pointing in the opposite direction to CCD sweeps
cp.internalFaceIndex1 = p.mFaceIndex;
cp.separation = 0.0f;
cp.restitution = p.mRestitution;
cp.dynamicFriction = p.mDynamicFriction;
cp.staticFriction = p.mStaticFriction;
cp.targetVel = PxVec3(0.0f);
cp.maxImpulse = PX_MAX_REAL;
matInfo.mMaterialIndex0 = p.mMaterialIndex0;
matInfo.mMaterialIndex1 = p.mMaterialIndex1;
//Write contact stream for the contact. This will allocate memory for the contacts and forces
PxReal* contactForces;
//PxU8* contactStream;
PxU8* contactPatches;
PxU8* contactPoints;
PxU16 contactStreamSize;
PxU16 contactCount;
PxU8 nbPatches;
PxsCCDContactHeader* ccdHeader = reinterpret_cast<PxsCCDContactHeader*>(p.mCm->mNpUnit.ccdContacts);
if (writeCompressedContact(buffer.contacts, numContacts, mCCDThreadContext, contactCount, contactPatches,
contactPoints, contactStreamSize, contactForces, numContacts*sizeof(PxReal), mCCDThreadContext->mMaterialManager,
((p.mCm->mNpUnit.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT) != 0), true, &matInfo, nbPatches, sizeof(PxsCCDContactHeader),NULL, NULL,
false, NULL, NULL, NULL, p.mFaceIndex != PXC_CONTACT_NO_FACE_INDEX))
{
PxsCCDContactHeader* newCCDHeader = reinterpret_cast<PxsCCDContactHeader*>(contactPatches);
newCCDHeader->contactStreamSize = PxTo16(contactStreamSize);
newCCDHeader->isFromPreviousPass = 0;
p.mCm->mNpUnit.ccdContacts = contactPatches; // put the latest stream at the head of the linked list since it needs to get accessed every CCD pass
// to prepare the reports
if (!ccdHeader)
newCCDHeader->nextStream = NULL;
else
{
newCCDHeader->nextStream = ccdHeader;
ccdHeader->isFromPreviousPass = 1;
}
//And write the force and contact count
PX_ASSERT(contactForces != NULL);
contactForces[0] = p.mAppliedForce;
}
else if (!ccdHeader)
{
p.mCm->mNpUnit.ccdContacts = NULL;
// we do not set the status flag on failure because the pair might have written
// a contact stream sucessfully during discrete collision this frame.
}
else
ccdHeader->isFromPreviousPass = 1;
//If the touch event already existed, the solver would have already configured the threshold stream
if((p.mCm->mNpUnit.flags & (PxcNpWorkUnitFlag::eARTICULATION_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY1)) == 0 && p.mAppliedForce)
{
#if 1
ThresholdStreamElement elt;
elt.normalForce = p.mAppliedForce;
elt.accumulatedForce = 0.0f;
elt.threshold = PxMin<float>(p.mBa0 == NULL ? PX_MAX_REAL : p.mBa0->mCore->contactReportThreshold, p.mBa1 == NULL ? PX_MAX_REAL :
p.mBa1->mCore->contactReportThreshold);
elt.nodeIndexA = p.mCCDShape0->mNodeIndex;
elt.nodeIndexB =p.mCCDShape1->mNodeIndex;
PxOrder(elt.nodeIndexA,elt.nodeIndexB);
PX_ASSERT(elt.nodeIndexA.index() < elt.nodeIndexB.index());
mThresholdStream.pushBack(elt);
#endif
}
}
}
}
index = islandEnd;
}
mContext->mCMTouchEventCount[PXS_LOST_TOUCH_COUNT] += countLost;
mContext->mCMTouchEventCount[PXS_NEW_TOUCH_COUNT] += countFound;
mContext->mCMTouchEventCount[PXS_CCD_RETOUCH_COUNT] += countRetouch;
}
void PxsCCDContext::postCCDDepenetrate(PxBaseTask* /*continuation*/)
{
// --------------------------------------------------------------------------------------
// reset mOverlappingShapes array for all bodies
// we do it each pass because this set can change due to movement as well as new objects
// becoming fast moving due to intra-frame impacts
for (PxU32 j = 0; j < mCCDBodies.size(); j ++)
{
mCCDBodies[j].mOverlappingObjects = NULL;
mCCDBodies[j].mNbInteractionsThisPass = 0;
}
mCCDOverlaps.clear_NoDelete();
updateCCDEnd();
mContext->putNpThreadContext(mCCDThreadContext);
flushCCDLog();
}
Cm::SpatialVector PxsRigidBody::getPreSolverVelocities() const
{
if (mCCD)
return mCCD->mPreSolverVelocity;
return Cm::SpatialVector(PxVec3(0.0f), PxVec3(0.0f));
}
/*PxTransform PxsRigidBody::getAdvancedTransform(PxReal toi) const
{
//If it is kinematic, just return identity. We don't fully support kinematics yet
if (isKinematic())
return PxTransform(PxIdentity);
//Otherwise we interpolate the pose between the current and previous pose and return that pose
PxVec3 newLastP = mLastTransform.p*(1.0f-toi) + mCore->body2World.p*toi; // advance mLastTransform position to toi
PxQuat newLastQ = slerp(toi, getLastCCDTransform().q, mCore->body2World.q); // advance mLastTransform rotation to toi
return PxTransform(newLastP, newLastQ);
}*/
void PxsRigidBody::advancePrevPoseToToi(PxReal toi)
{
//If this is kinematic, just return
if (isKinematic())
return;
//update latest pose
const PxVec3 newLastP = mLastTransform.p*(1.0f-toi) + mCore->body2World.p*toi; // advance mLastTransform position to toi
mLastTransform.p = newLastP;
#if CCD_ROTATION_LOCKING
mCore->body2World.q = getLastCCDTransform().q;
#else
// slerp from last transform to current transform with ratio of toi
const PxQuat newLastQ = PxSlerp(toi, getLastCCDTransform().q, mCore->body2World.q); // advance mLastTransform rotation to toi
mLastTransform.q = newLastQ;
#endif
}
void PxsRigidBody::advanceToToi(PxReal toi, PxReal dt, bool clip)
{
if (isKinematic())
return;
if (clip)
{
//If clip is true, we set the previous and current pose to be the same. This basically makes the object appear stationary in the CCD
mCore->body2World.p = getLastCCDTransform().p;
#if !CCD_ROTATION_LOCKING
mCore->body2World.q = getLastCCDTransform().q;
#endif
}
else
{
// advance new CCD target after impact to remaining toi using post-impact velocities
mCore->body2World.p = getLastCCDTransform().p + getLinearVelocity() * dt * (1.0f - toi);
#if !CCD_ROTATION_LOCKING
const PxVec3 angularDelta = getAngularVelocity() * dt * (1.0f - toi);
const PxReal deltaMag = angularDelta.magnitude();
const PxVec3 deltaAng = deltaMag > 1e-20f ? angularDelta / deltaMag : PxVec3(1.0f, 0.0f, 0.0f);
const PxQuat angularQuat(deltaMag, deltaAng);
mCore->body2World.q = getLastCCDTransform().q * angularQuat;
#endif
PX_ASSERT(mCore->body2World.isSane());
}
// rescale total time left to elapse this frame
mCCD->mTimeLeft = PxMax(mCCD->mTimeLeft * (1.0f - toi), CCD_MIN_TIME_LEFT);
}
void PxsCCDContext::runCCDModifiableContact(PxModifiableContact* PX_RESTRICT contacts, PxU32 contactCount, const PxsShapeCore* PX_RESTRICT shapeCore0,
const PxsShapeCore* PX_RESTRICT shapeCore1, const PxsRigidCore* PX_RESTRICT rigidCore0, const PxsRigidCore* PX_RESTRICT rigidCore1,
const PxsRigidBody* PX_RESTRICT rigid0, const PxsRigidBody* PX_RESTRICT rigid1)
{
if(!mCCDContactModifyCallback)
return;
class PxcContactSet: public PxContactSet
{
public:
PxcContactSet(PxU32 count, PxModifiableContact* contacts_)
{
mContacts = contacts_;
mCount = count;
}
};
{
PxContactModifyPair p;
p.shape[0] = gPxvOffsetTable.convertPxsShape2Px(shapeCore0);
p.shape[1] = gPxvOffsetTable.convertPxsShape2Px(shapeCore1);
p.actor[0] = rigid0 != NULL ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(rigidCore0)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(rigidCore0);
p.actor[1] = rigid1 != NULL ? gPxvOffsetTable.convertPxsRigidCore2PxRigidBody(rigidCore1)
: gPxvOffsetTable.convertPxsRigidCore2PxRigidStatic(rigidCore1);
getShapeAbsPose(p.transform[0], shapeCore0, rigidCore0, rigid0);
getShapeAbsPose(p.transform[1], shapeCore1, rigidCore1, rigid1);
static_cast<PxcContactSet&>(p.contacts) =
PxcContactSet(contactCount, contacts);
mCCDContactModifyCallback->onCCDContactModify(&p, 1);
}
}
| 75,072 | C++ | 34.064456 | 232 | 0.69119 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsIslandSim.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxsIslandSim.h"
#include "foundation/PxSort.h"
#include "foundation/PxUtilities.h"
#include "common/PxProfileZone.h"
#include "DyFeatherstoneArticulation.h"
#define IG_SANITY_CHECKS 0
using namespace physx;
using namespace IG;
IslandSim::IslandSim(PxArray<PartitionEdge*>* firstPartitionEdges, Cm::BlockArray<PxNodeIndex>& edgeNodeIndices, PxArray<PartitionEdge*>* destroyedPartitionEdges, PxU64 contextID) :
mNodes ("IslandSim::mNodes"),
mActiveNodeIndex ("IslandSim::mActiveNodeIndex"),
mIslands ("IslandSim::mIslands"),
mIslandStaticTouchCount ("IslandSim.activeStaticTouchCount"),
mActiveKinematicNodes ("IslandSim::mActiveKinematicNodes"),
mHopCounts ("IslandSim::mHopCounts"),
mFastRoute ("IslandSim::mFastRoute"),
mIslandIds ("IslandSim::mIslandIds"),
mActiveIslands ("IslandSim::mActiveIslands"),
mLastMapIndex (0),
mActivatingNodes ("IslandSim::mActivatingNodes"),
mDestroyedEdges ("IslandSim::mDestroyedEdges"),
mTempIslandIds ("IslandSim::mTempIslandIds"),
mVisitedNodes ("IslandSim::mVisitedNodes"),
mFirstPartitionEdges (firstPartitionEdges),
mEdgeNodeIndices (edgeNodeIndices),
mDestroyedPartitionEdges(destroyedPartitionEdges),
mContextId (contextID)
{
mNpIndexPtr = NULL;
for (PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
mInitialActiveNodeCount[i] = 0;
mActiveEdgeCount[i] = 0;
}
}
#if PX_ENABLE_ASSERTS
template <typename Thing>
static bool contains(PxArray<Thing>& arr, const Thing& thing)
{
for(PxU32 a = 0; a < arr.size(); ++a)
{
if(thing == arr[a])
return true;
}
return false;
}
#endif
/*void IslandSim::resize(const PxU32 nbNodes, const PxU32 nbContactManagers, const PxU32 nbConstraints)
{
PxU32 totalEdges = nbContactManagers + nbConstraints;
mNodes.reserve(nbNodes);
mIslandIds.reserve(nbNodes);
mEdges.reserve(totalEdges);
mActiveContactEdges.resize(totalEdges);
mEdgeInstances.reserve(totalEdges*2);
}*/
void IslandSim::addNode(bool isActive, bool isKinematic, Node::NodeType type, PxNodeIndex nodeIndex)
{
// PT: the nodeIndex is assigned by the SimpleIslandManager one level higher.
const PxU32 handle = nodeIndex.index();
if(handle == mNodes.capacity())
{
const PxU32 newCapacity = PxMax(2*mNodes.capacity(), 256u);
mNodes.reserve(newCapacity);
mIslandIds.reserve(newCapacity);
mFastRoute.reserve(newCapacity);
mHopCounts.reserve(newCapacity);
mActiveNodeIndex.reserve(newCapacity);
}
const PxU32 newSize = PxMax(handle+1, mNodes.size());
mNodes.resize(newSize);
mIslandIds.resize(newSize);
mFastRoute.resize(newSize);
mHopCounts.resize(newSize);
mActiveNodeIndex.resize(newSize);
mActiveNodeIndex[handle] = PX_INVALID_NODE;
Node& node = mNodes[handle];
node.mType = PxTo8(type);
//Ensure that the node is not currently being used.
PX_ASSERT(node.isDeleted());
PxU8 flags = PxU16(isActive ? 0 : Node::eREADY_FOR_SLEEPING);
if(isKinematic)
flags |= Node::eKINEMATIC;
node.mFlags = flags;
mIslandIds[handle] = IG_INVALID_ISLAND;
mFastRoute[handle].setIndices(PX_INVALID_NODE);
mHopCounts[handle] = 0;
if(!isKinematic)
{
const IslandId islandHandle = mIslandHandles.getHandle();
if(islandHandle == mIslands.capacity())
{
const PxU32 newCapacity = PxMax(2*mIslands.capacity(), 256u);
mIslands.reserve(newCapacity);
mIslandAwake.resize(newCapacity);
mIslandStaticTouchCount.reserve(newCapacity);
}
mIslands.resize(PxMax(islandHandle+1, mIslands.size()));
mIslandStaticTouchCount.resize(PxMax(islandHandle+1, mIslands.size()));
mIslandAwake.growAndReset(PxMax(islandHandle+1, mIslands.size()));
Island& island = mIslands[islandHandle];
island.mLastNode = island.mRootNode = nodeIndex;
island.mNodeCount[type] = 1;
mIslandIds[handle] = islandHandle;
mIslandStaticTouchCount[islandHandle] = 0;
}
if(isActive)
activateNode(nodeIndex);
}
void IslandSim::addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, isKinematic, Node::eRIGID_BODY_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mRigidBody = body;
}
void IslandSim::addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eARTICULATION_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLArticulation = llArtic;
}
#if PX_SUPPORT_GPU_PHYSX
void IslandSim::addSoftBody(Dy::SoftBody* llSoftBody, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eSOFTBODY_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLSoftBody = llSoftBody;
}
void IslandSim::addFEMCloth(Dy::FEMCloth* llFEMCloth, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eFEMCLOTH_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLFEMCloth = llFEMCloth;
}
void IslandSim::addParticleSystem(Dy::ParticleSystem* llParticleSystem, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::ePARTICLESYSTEM_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLParticleSystem = llParticleSystem;
}
void IslandSim::addHairSystem(Dy::HairSystem* llHairSystem, bool isActive, PxNodeIndex nodeIndex)
{
addNode(isActive, false, Node::eHAIRSYSTEM_TYPE, nodeIndex);
Node& node = mNodes[nodeIndex.index()];
node.mLLHairSystem = llHairSystem;
}
#endif
Sc::ArticulationSim* IslandSim::getArticulationSim(PxNodeIndex nodeIndex) const
{
void* userData = getLLArticulation(nodeIndex)->getUserData();
return reinterpret_cast<Sc::ArticulationSim*>(userData);
}
void IslandSim::connectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& source, PxNodeIndex /*destination*/)
{
PX_ASSERT(instance.mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE);
instance.mNextEdge = source.mFirstEdgeIndex;
if(source.mFirstEdgeIndex != IG_INVALID_EDGE)
{
EdgeInstance& firstEdge = mEdgeInstances[source.mFirstEdgeIndex];
firstEdge.mPrevEdge = edgeIndex;
}
source.mFirstEdgeIndex = edgeIndex;
instance.mPrevEdge = IG_INVALID_EDGE;
}
void IslandSim::addConnection(PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Edge::EdgeType edgeType, EdgeIndex handle)
{
// PT: the EdgeIndex is assigned by the SimpleIslandManager one level higher.
PX_UNUSED(nodeHandle1);
PX_UNUSED(nodeHandle2);
if(handle >= mEdges.capacity())
{
PX_PROFILE_ZONE("ReserveIslandEdges", getContextId());
const PxU32 newSize = handle + 2048;
mEdges.reserve(newSize);
mActiveContactEdges.resize(mEdges.capacity());
}
mEdges.resize(PxMax(mEdges.size(), handle+1));
mActiveContactEdges.reset(handle);
Edge& edge = mEdges[handle];
if(edge.isPendingDestroyed())
{
//If it's in this state, then the edge has been tagged for destruction but actually is now not needed to be destroyed
edge.clearPendingDestroyed();
return;
}
if(edge.isInDirtyList())
{
PX_ASSERT(mEdgeNodeIndices[handle * 2].index() == nodeHandle1.index());
PX_ASSERT(mEdgeNodeIndices[handle * 2 + 1].index() == nodeHandle2.index());
PX_ASSERT(edge.mEdgeType == edgeType);
return;
}
PX_ASSERT(!edge.isInserted());
PX_ASSERT(edge.isDestroyed());
edge.clearDestroyed();
PX_ASSERT(edge.mNextIslandEdge == IG_INVALID_ISLAND);
PX_ASSERT(edge.mPrevIslandEdge == IG_INVALID_ISLAND);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle+1].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle].mPrevEdge == IG_INVALID_EDGE);
PX_ASSERT(mEdgeInstances.size() <= 2*handle || mEdgeInstances[2*handle+1].mPrevEdge == IG_INVALID_EDGE);
edge.mEdgeType = edgeType;
PX_ASSERT(handle*2 >= mEdgeInstances.size() || mEdgeInstances[handle*2].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(handle*2+1 >= mEdgeInstances.size() || mEdgeInstances[handle*2+1].mNextEdge == IG_INVALID_EDGE);
PX_ASSERT(handle*2 >= mEdgeInstances.size() || mEdgeInstances[handle*2].mPrevEdge == IG_INVALID_EDGE);
PX_ASSERT(handle*2+1 >= mEdgeInstances.size() || mEdgeInstances[handle*2+1].mPrevEdge == IG_INVALID_EDGE);
//Add the new handle
if(!edge.isInDirtyList())
{
PX_ASSERT(!contains(mDirtyEdges[edgeType], handle));
mDirtyEdges[edgeType].pushBack(handle);
edge.markInDirtyList();
}
edge.mEdgeState &= ~(Edge::eACTIVATING);
}
void IslandSim::addConnectionToGraph(EdgeIndex handle)
{
const EdgeInstanceIndex instanceHandle = 2*handle;
PX_ASSERT(instanceHandle < mEdgeInstances.capacity());
/*if(instanceHandle == mEdgeInstances.capacity())
{
mEdgeInstances.reserve(2*mEdgeInstances.capacity() + 2);
}*/
mEdgeInstances.resize(PxMax(instanceHandle+2, mEdgeInstances.size()));
Edge& edge = mEdges[handle];
// PT: TODO: int bools
bool activeEdge = false;
bool kinematicKinematicEdge = true;
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[instanceHandle];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[instanceHandle+1];
if(nodeIndex1.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex1.index()];
connectEdge(mEdgeInstances[instanceHandle], instanceHandle, node, nodeIndex2);
activeEdge = node.isActive() || node.isActivating();
kinematicKinematicEdge = node.isKinematic();
}
if(nodeIndex1.index() != nodeIndex2.index() && nodeIndex2.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex2.index()];
connectEdge(mEdgeInstances[instanceHandle + 1], instanceHandle + 1, node, nodeIndex1);
activeEdge = activeEdge || node.isActive() || node.isActivating();
kinematicKinematicEdge = kinematicKinematicEdge && node.isKinematic();
}
if(activeEdge && (!kinematicKinematicEdge || edge.getEdgeType() == IG::Edge::eCONTACT_MANAGER))
{
markEdgeActive(handle);
edge.activateEdge();
}
}
void IslandSim::removeConnectionFromGraph(EdgeIndex edgeIndex)
{
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[2 * edgeIndex];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[2 * edgeIndex+1];
if (nodeIndex1.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex1.index()];
if (nodeIndex2.index() == mFastRoute[nodeIndex1.index()].index())
mFastRoute[nodeIndex1.index()].setIndices(PX_INVALID_NODE);
if(!node.isDirty())
{
//mDirtyNodes.pushBack(nodeIndex1);
mDirtyMap.growAndSet(nodeIndex1.index());
node.markDirty();
}
}
if (nodeIndex2.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex2.index()];
if (nodeIndex1.index() == mFastRoute[nodeIndex2.index()].index())
mFastRoute[nodeIndex2.index()].setIndices(PX_INVALID_NODE);
if(!node.isDirty())
{
mDirtyMap.growAndSet(nodeIndex2.index());
node.markDirty();
}
}
}
void IslandSim::disconnectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& node)
{
PX_ASSERT(instance.mNextEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mNextEdge].mPrevEdge == edgeIndex);
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mPrevEdge].mNextEdge == edgeIndex);
if(node.mFirstEdgeIndex == edgeIndex)
{
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE);
node.mFirstEdgeIndex = instance.mNextEdge;
}
else
{
EdgeInstance& prev = mEdgeInstances[instance.mPrevEdge];
PX_ASSERT(prev.mNextEdge == edgeIndex);
prev.mNextEdge = instance.mNextEdge;
}
if(instance.mNextEdge != IG_INVALID_EDGE)
{
EdgeInstance& next = mEdgeInstances[instance.mNextEdge];
PX_ASSERT(next.mPrevEdge == edgeIndex);
next.mPrevEdge = instance.mPrevEdge;
}
PX_ASSERT(instance.mNextEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mNextEdge].mPrevEdge == instance.mPrevEdge);
PX_ASSERT(instance.mPrevEdge == IG_INVALID_EDGE || mEdgeInstances[instance.mPrevEdge].mNextEdge == instance.mNextEdge);
instance.mNextEdge = IG_INVALID_EDGE;
instance.mPrevEdge = IG_INVALID_EDGE;
}
void IslandSim::removeConnection(EdgeIndex edgeIndex)
{
Edge& edge = mEdges[edgeIndex];
if(!edge.isPendingDestroyed())// && edge.isInserted())
{
mDestroyedEdges.pushBack(edgeIndex);
/*if(!edge.isInserted())
edge.setReportOnlyDestroy();*/
}
edge.setPendingDestroyed();
}
void IslandSim::removeConnectionInternal(EdgeIndex edgeIndex)
{
PX_ASSERT(edgeIndex != IG_INVALID_EDGE);
const EdgeInstanceIndex edgeInstanceBase = edgeIndex*2;
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[edgeIndex * 2];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[edgeIndex * 2 + 1];
if (nodeIndex1.index() != PX_INVALID_NODE)
disconnectEdge(mEdgeInstances[edgeInstanceBase], edgeInstanceBase, mNodes[nodeIndex1.index()]);
if (nodeIndex2.index() != PX_INVALID_NODE && nodeIndex1.index() != nodeIndex2.index())
disconnectEdge(mEdgeInstances[edgeInstanceBase+1], edgeInstanceBase+1, mNodes[nodeIndex2.index()]);
}
/*void IslandSim::addContactManager(PxsContactManager*, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle)
{
addConnection(nodeHandle1, nodeHandle2, Edge::eCONTACT_MANAGER, handle);
}*/
void IslandSim::addConstraint(Dy::Constraint* /*constraint*/, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle)
{
addConnection(nodeHandle1, nodeHandle2, Edge::eCONSTRAINT, handle);
}
void IslandSim::activateNode(PxNodeIndex nodeIndex)
{
if(nodeIndex.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex.index()];
if(!(node.isActive() || node.isActivating()))
{
//If the node is kinematic and already in the active node list, then we need to remove it
//from the active kinematic node list, then re-add it after the wake-up. It's a bit stupid
//but it means that we don't need another index
if(node.isKinematic() && mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
//node.setActive();
//node.clearIsReadyForSleeping(); //Clear the "isReadyForSleeping" flag. Just in case it was set
//return;
const PxU32 activeRefCount = node.mActiveRefCount;
node.mActiveRefCount = 0;
node.clearActive();
markKinematicInactive(nodeIndex);
node.mActiveRefCount = activeRefCount;
}
node.setActivating(); //Tag it as activating
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
mActiveNodeIndex[nodeIndex.index()] = mActivatingNodes.size();
//Add to waking list
mActivatingNodes.pushBack(nodeIndex);
}
node.clearIsReadyForSleeping(); //Clear the "isReadyForSleeping" flag. Just in case it was set
node.clearDeactivating();
}
}
void IslandSim::deactivateNode(PxNodeIndex nodeIndex)
{
if(nodeIndex.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeIndex.index()];
//If the node is activating, clear its activating state and remove it from the activating list.
//If it wasn't already activating, then it's probably already in the active list
const bool wasActivating = node.isActivating();
if(wasActivating)
{
//Already activating, so remove it from the activating list
node.clearActivating();
PX_ASSERT(mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]].index() == nodeIndex.index());
const PxNodeIndex replaceIndex = mActivatingNodes[mActivatingNodes.size()-1];
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[nodeIndex.index()];
mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]] = replaceIndex;
mActivatingNodes.forceSize_Unsafe(mActivatingNodes.size()-1);
mActiveNodeIndex[nodeIndex.index()] = PX_INVALID_NODE;
if(node.isKinematic())
{
//If we were temporarily removed from the active kinematic list to be put in the waking kinematic list
//then add the node back in before deactivating the node. This is a bit counter-intuitive but the active
//kinematic list contains all active kinematics and all kinematics that are referenced by an active constraint
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
mActiveNodeIndex[nodeIndex.index()] = mActiveKinematicNodes.size();
mActiveKinematicNodes.pushBack(nodeIndex);
}
}
//Raise the "ready for sleeping" flag so that island gen can put this node to sleep
node.setIsReadyForSleeping();
}
}
void IslandSim::putNodeToSleep(PxNodeIndex nodeIndex)
{
if(nodeIndex.index() != PX_INVALID_NODE)
deactivateNode(nodeIndex);
}
void IslandSim::activateNodeInternal(PxNodeIndex nodeIndex)
{
//This method should activate the node, then activate all the connections involving this node
Node& node = mNodes[nodeIndex.index()];
if(!node.isActive())
{
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
//Activate all the edges + nodes...
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeIndex idx = index/2;
Edge& edge = mEdges[idx]; //InstanceIndex/2 = edgeIndex
if(!edge.isActive())
{
//Make the edge active...
PX_ASSERT(mEdgeNodeIndices[idx * 2].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2].index()].isKinematic());
PX_ASSERT(mEdgeNodeIndices[idx * 2 + 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isKinematic());
markEdgeActive(idx);
edge.activateEdge();
}
index = mEdgeInstances[index].mNextEdge;
}
if(node.isKinematic())
markKinematicActive(nodeIndex);
else
markActive(nodeIndex);
node.setActive();
}
}
void IslandSim::deactivateNodeInternal(PxNodeIndex nodeIndex)
{
//We deactivate a node, we need to loop through all the edges and deactivate them *if* both bodies are asleep
Node& node = mNodes[nodeIndex.index()];
if(node.isActive())
{
if(node.isKinematic())
markKinematicInactive(nodeIndex);
else
markInactive(nodeIndex);
//Clear the active status flag
node.clearActive();
node.clearActivating();
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[index];
const PxNodeIndex outboundNode = mEdgeNodeIndices[index ^ 1];
if(outboundNode.index() == PX_INVALID_NODE ||
!mNodes[outboundNode.index()].isActive())
{
const EdgeIndex idx = index/2;
Edge& edge = mEdges[idx]; //InstanceIndex/2 = edgeIndex
//PX_ASSERT(edge.isActive()); //The edge must currently be inactive because the node was active
//Deactivate the edge if both nodes connected are inactive OR if one node is static/kinematic and the other is inactive...
PX_ASSERT(mEdgeNodeIndices[index & (~1)].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[index & (~1)].index()].isActive());
PX_ASSERT(mEdgeNodeIndices[index | 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[index | 1].index()].isActive());
if(edge.isActive())
{
edge.deactivateEdge();
mActiveEdgeCount[edge.mEdgeType]--;
removeEdgeFromActivatingList(idx);
mDeactivatingEdges[edge.mEdgeType].pushBack(idx);
}
}
index = instance.mNextEdge;
}
}
}
bool IslandSim::canFindRoot(PxNodeIndex startNode, PxNodeIndex targetNode, PxArray<PxNodeIndex>* visitedNodes)
{
if(visitedNodes)
visitedNodes->pushBack(startNode);
if(startNode.index() == targetNode.index())
return true;
PxBitMap visitedState;
visitedState.resizeAndClear(mNodes.size());
PxArray<PxNodeIndex> stack;
stack.pushBack(startNode);
visitedState.set(startNode.index());
do
{
const PxNodeIndex currentIndex = stack.popBack();
const Node& currentNode = mNodes[currentIndex.index()];
EdgeInstanceIndex currentEdge = currentNode.mFirstEdgeIndex;
while(currentEdge != IG_INVALID_EDGE)
{
const EdgeInstance& edge = mEdgeInstances[currentEdge];
const PxNodeIndex outboundNode = mEdgeNodeIndices[currentEdge ^ 1];
if(outboundNode.index() != PX_INVALID_NODE && !mNodes[outboundNode.index()].isKinematic() && !visitedState.test(outboundNode.index()))
{
if(outboundNode.index() == targetNode.index())
return true;
visitedState.set(outboundNode.index());
stack.pushBack(outboundNode);
if(visitedNodes)
visitedNodes->pushBack(outboundNode);
}
currentEdge = edge.mNextEdge;
}
}
while(stack.size());
return false;
}
void IslandSim::unwindRoute(PxU32 traversalIndex, PxNodeIndex lastNode, PxU32 hopCount, IslandId id)
{
//We have found either a witness *or* the root node with this traversal. In the event of finding the root node, hopCount will be 0. In the event of finding
//a witness, hopCount will be the hopCount that witness reported as being the distance to the root.
PxU32 currIndex = traversalIndex;
PxU32 hc = hopCount+1; //Add on 1 for the hop to the witness/root node.
do
{
TraversalState& state = mVisitedNodes[currIndex];
mHopCounts[state.mNodeIndex.index()] = hc++;
mIslandIds[state.mNodeIndex.index()] = id;
mFastRoute[state.mNodeIndex.index()] = lastNode;
currIndex = state.mPrevIndex;
lastNode = state.mNodeIndex;
}
while(currIndex != PX_INVALID_NODE);
}
void IslandSim::activateIsland(IslandId islandId)
{
Island& island = mIslands[islandId];
PX_ASSERT(!mIslandAwake.test(islandId));
PX_ASSERT(island.mActiveIndex == IG_INVALID_ISLAND);
PxNodeIndex currentNode = island.mRootNode;
while(currentNode.index() != PX_INVALID_NODE)
{
activateNodeInternal(currentNode);
currentNode = mNodes[currentNode.index()].mNextNode;
}
markIslandActive(islandId);
}
void IslandSim::deactivateIsland(IslandId islandId)
{
PX_ASSERT(mIslandAwake.test(islandId));
Island& island = mIslands[islandId];
PxNodeIndex currentNode = island.mRootNode;
while(currentNode.index() != PX_INVALID_NODE)
{
const Node& node = mNodes[currentNode.index()];
//if(mActiveNodeIndex[currentNode.index()] < mInitialActiveNodeCount[node.mType])
mNodesToPutToSleep[node.mType].pushBack(currentNode); //If this node was previously active, then push it to the list of nodes to deactivate
deactivateNodeInternal(currentNode);
currentNode = node.mNextNode;
}
markIslandInactive(islandId);
}
void IslandSim::wakeIslands()
{
PX_PROFILE_ZONE("Basic.wakeIslands", getContextId());
//(1) Iterate over activating nodes and activate them
const PxU32 originalActiveIslands = mActiveIslands.size();
for (PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
for (PxU32 i = 0, count = mActivatedEdges[a].size(); i < count; ++i)
{
IG::Edge& edge = mEdges[mActivatedEdges[a][i]];
edge.mEdgeState &= (~Edge::eACTIVATING);
}
mActivatedEdges[a].forceSize_Unsafe(0);
}
/*mInitialActiveEdgeCount[0] = mActiveEdges[0].size();
mInitialActiveEdgeCount[1] = mActiveEdges[1].size();*/
for (PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
mInitialActiveNodeCount[a] = mActiveNodes[a].size();
}
for(PxU32 a = 0; a < mActivatingNodes.size(); ++a)
{
const PxNodeIndex wakeNode = mActivatingNodes[a];
const IslandId islandId = mIslandIds[wakeNode.index()];
Node& node = mNodes[wakeNode.index()];
node.clearActivating();
if(islandId != IG_INVALID_ISLAND)
{
if(!mIslandAwake.test(islandId))
markIslandActive(islandId);
mActiveNodeIndex[wakeNode.index()] = PX_INVALID_NODE; //Mark active node as invalid.
activateNodeInternal(wakeNode);
}
else
{
PX_ASSERT(node.isKinematic());
node.setActive();
PX_ASSERT(mActiveNodeIndex[wakeNode.index()] == a);
mActiveNodeIndex[wakeNode.index()] = mActiveKinematicNodes.size();
mActiveKinematicNodes.pushBack(wakeNode);
//Wake up the islands connected to this waking kinematic!
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeInstance& edgeInstance = mEdgeInstances[index];
const PxNodeIndex outboundNode = mEdgeNodeIndices[index ^ 1];
//Edge& edge = mEdges[index/2];
//if(edge.isConnected()) //Only wake up if the edge is not connected...
const PxNodeIndex nodeIndex = outboundNode;
if (nodeIndex.isStaticBody() || mIslandIds[nodeIndex.index()] == IG_INVALID_ISLAND)
{
//If the edge connects to a static body *or* it connects to a node which is not part of an island (i.e. a kinematic), then activate the edge
const EdgeIndex idx = index / 2;
Edge& edge = mEdges[idx];
if (!edge.isActive() && edge.getEdgeType() != IG::Edge::eCONSTRAINT)
{
//Make the edge active...
PX_ASSERT(mEdgeNodeIndices[idx * 2].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2].index()].isKinematic());
PX_ASSERT(mEdgeNodeIndices[idx * 2 + 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isKinematic());
markEdgeActive(idx);
edge.activateEdge();
}
}
else
{
const IslandId connectedIslandId = mIslandIds[nodeIndex.index()];
if(!mIslandAwake.test(connectedIslandId))
{
//Wake up that island
markIslandActive(connectedIslandId);
}
}
index = edgeInstance.mNextEdge;
}
}
}
mActivatingNodes.forceSize_Unsafe(0);
for(PxU32 a = originalActiveIslands; a < mActiveIslands.size(); ++a)
{
const Island& island = mIslands[mActiveIslands[a]];
PxNodeIndex currentNode = island.mRootNode;
while(currentNode.index() != PX_INVALID_NODE)
{
activateNodeInternal(currentNode);
currentNode = mNodes[currentNode.index()].mNextNode;
}
}
}
void IslandSim::wakeIslands2()
{
const PxU32 originalActiveIslands = mActiveIslands.size();
for (PxU32 a = 0; a < mActivatingNodes.size(); ++a)
{
const PxNodeIndex wakeNode = mActivatingNodes[a];
const IslandId islandId = mIslandIds[wakeNode.index()];
Node& node = mNodes[wakeNode.index()];
node.clearActivating();
if (islandId != IG_INVALID_ISLAND)
{
if (!mIslandAwake.test(islandId))
markIslandActive(islandId);
mActiveNodeIndex[wakeNode.index()] = PX_INVALID_NODE; //Mark active node as invalid.
activateNodeInternal(wakeNode);
}
else
{
PX_ASSERT(node.isKinematic());
node.setActive();
PX_ASSERT(mActiveNodeIndex[wakeNode.index()] == a);
mActiveNodeIndex[wakeNode.index()] = mActiveKinematicNodes.size();
mActiveKinematicNodes.pushBack(wakeNode);
//Wake up the islands connected to this waking kinematic!
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while (index != IG_INVALID_EDGE)
{
const EdgeInstance& edgeInstance = mEdgeInstances[index];
const PxNodeIndex outboundNode = mEdgeNodeIndices[index ^ 1];
//Edge& edge = mEdges[index/2];
//if(edge.isConnected()) //Only wake up if the edge is not connected...
const PxNodeIndex nodeIndex = outboundNode;
if (nodeIndex.isStaticBody() || mIslandIds[nodeIndex.index()] == IG_INVALID_ISLAND)
{
//If the edge connects to a static body *or* it connects to a node which is not part of an island (i.e. a kinematic), then activate the edge
const EdgeIndex idx = index / 2;
Edge& edge = mEdges[idx];
if (!edge.isActive() && edge.getEdgeType() != IG::Edge::eCONSTRAINT)
{
//Make the edge active...
PX_ASSERT(mEdgeNodeIndices[idx * 2].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2].index()].isKinematic());
PX_ASSERT(mEdgeNodeIndices[idx * 2 + 1].index() == PX_INVALID_NODE || !mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isActive() || mNodes[mEdgeNodeIndices[idx * 2 + 1].index()].isKinematic());
markEdgeActive(idx);
edge.activateEdge();
}
}
else
{
IslandId connectedIslandId = mIslandIds[nodeIndex.index()];
if (!mIslandAwake.test(connectedIslandId))
{
//Wake up that island
markIslandActive(connectedIslandId);
}
}
index = edgeInstance.mNextEdge;
}
}
}
mActivatingNodes.forceSize_Unsafe(0);
for (PxU32 a = originalActiveIslands; a < mActiveIslands.size(); ++a)
{
const Island& island = mIslands[mActiveIslands[a]];
PxNodeIndex currentNode = island.mRootNode;
while (currentNode.index() != PX_INVALID_NODE)
{
activateNodeInternal(currentNode);
currentNode = mNodes[currentNode.index()].mNextNode;
}
}
}
void IslandSim::insertNewEdges()
{
PX_PROFILE_ZONE("Basic.insertNewEdges", getContextId());
mEdgeInstances.reserve(mEdges.capacity()*2);
for(PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
for(PxU32 a = 0; a < mDirtyEdges[i].size(); ++a)
{
const EdgeIndex edgeIndex = mDirtyEdges[i][a];
Edge& edge = mEdges[edgeIndex];
if(!edge.isPendingDestroyed())
{
//PX_ASSERT(!edge.isInserted());
if(!edge.isInserted())
{
addConnectionToGraph(edgeIndex);
edge.setInserted();
}
}
}
}
}
void IslandSim::removeDestroyedEdges()
{
PX_PROFILE_ZONE("Basic.removeDestroyedEdges", getContextId());
for(PxU32 a = 0; a < mDestroyedEdges.size(); ++a)
{
const EdgeIndex edgeIndex = mDestroyedEdges[a];
const Edge& edge = mEdges[edgeIndex];
if(edge.isPendingDestroyed())
{
if(!edge.isInDirtyList() && edge.isInserted())
{
PX_ASSERT(edge.isInserted());
removeConnectionInternal(edgeIndex);
removeConnectionFromGraph(edgeIndex);
//edge.clearInserted();
}
//edge.clearDestroyed();
}
}
}
void IslandSim::processNewEdges()
{
PX_PROFILE_ZONE("Basic.processNewEdges", getContextId());
//Stage 1: we process the list of new pairs. To do this, we need to first sort them based on a predicate...
insertNewEdges();
mHopCounts.resize(mNodes.size()); //Make sure we have enough space for hop counts for all nodes
mFastRoute.resize(mNodes.size());
for(PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
for(PxU32 a = 0; a < mDirtyEdges[i].size(); ++a)
{
const EdgeIndex edgeIndex = mDirtyEdges[i][a];
const Edge& edge = mEdges[edgeIndex];
/*PX_ASSERT(edge.mState != Edge::eDESTROYED || ((edge.mNode1.index() == PX_INVALID_NODE || mNodes[edge.mNode1.index()].isKinematic() || mNodes[edge.mNode1.index()].isActive() == false) &&
(edge.mNode2.index() == PX_INVALID_NODE || mNodes[edge.mNode2.index()].isKinematic() || mNodes[edge.mNode2.index()].isActive() == false)));*/
//edge.clearInDirtyList();
//We do not process either destroyed or disconnected edges
if(/*edge.isConnected() && */!edge.isPendingDestroyed())
{
//Conditions:
//(1) Neither body is in an island (static/kinematics are never in islands) so we need to create a new island containing these bodies
// or just 1 body if the other is kinematic/static
//(2) Both bodies are already in the same island. Update root node hop count estimates for the bodies if a route through the new connection
// is shorter for either body
//(3) One body is already in an island and the other isn't, so we just add the new body to the existing island.
//(4) Both bodies are in different islands. In that case, we merge the islands
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[2 * edgeIndex];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[2 * edgeIndex+1];
const IslandId islandId1 = nodeIndex1.index() == PX_INVALID_NODE ? IG_INVALID_ISLAND : mIslandIds[nodeIndex1.index()];
const IslandId islandId2 = nodeIndex2.index() == PX_INVALID_NODE ? IG_INVALID_ISLAND : mIslandIds[nodeIndex2.index()];
//TODO - wake ups!!!!
//If one of the nodes is awake and the other is asleep, we need to wake 'em up
//When a node is activated, the island must also be activated...
const bool active1 = nodeIndex1.index() != PX_INVALID_NODE && mNodes[nodeIndex1.index()].isActive();
const bool active2 = nodeIndex2.index() != PX_INVALID_NODE && mNodes[nodeIndex2.index()].isActive();
IslandId islandId = IG_INVALID_ISLAND;
if(islandId1 == IG_INVALID_ISLAND && islandId2 == IG_INVALID_ISLAND)
{
//All nodes should be introduced in an island now unless they are static or kinematic. Therefore, if we get here, we have an edge
//between 2 kinematic nodes or a kinematic and static node. These should not influence island management so we should just ignore
//these edges.
}
else if(islandId1 == islandId2)
{
islandId = islandId1;
if(active1 || active2)
{
PX_ASSERT(mIslandAwake.test(islandId1)); //If we got here, where the 2 were already in an island, if 1 node is awake, the whole island must be awake
}
//Both bodies in the same island. Nothing major to do already but we should see if this creates a shorter path to root for either node
const PxU32 hopCount1 = mHopCounts[nodeIndex1.index()];
const PxU32 hopCount2 = mHopCounts[nodeIndex2.index()];
if((hopCount1+1) < hopCount2)
{
//It would be faster for node 2 to go through node 1
mHopCounts[nodeIndex2.index()] = hopCount1 + 1;
mFastRoute[nodeIndex2.index()] = nodeIndex1;
}
else if((hopCount2+1) < hopCount1)
{
//It would be faster for node 1 to go through node 2
mHopCounts[nodeIndex1.index()] = hopCount2 + 1;
mFastRoute[nodeIndex1.index()] = nodeIndex2;
}
//No need to activate/deactivate the island. Its state won't have changed
}
else if(islandId1 == IG_INVALID_ISLAND)
{
islandId = islandId2;
if (nodeIndex1.index() != PX_INVALID_NODE)
{
if (!mNodes[nodeIndex1.index()].isKinematic())
{
PX_ASSERT(islandId2 != IG_INVALID_ISLAND);
//We need to add node 1 to island2
PX_ASSERT(mNodes[nodeIndex1.index()].mNextNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
PX_ASSERT(mNodes[nodeIndex1.index()].mPrevNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
Island& island = mIslands[islandId2];
Node& lastNode = mNodes[island.mLastNode.index()];
PX_ASSERT(lastNode.mNextNode.index() == PX_INVALID_NODE);
Node& node = mNodes[nodeIndex1.index()];
lastNode.mNextNode = nodeIndex1;
node.mPrevNode = island.mLastNode;
island.mLastNode = nodeIndex1;
island.mNodeCount[node.mType]++;
mIslandIds[nodeIndex1.index()] = islandId2;
mHopCounts[nodeIndex1.index()] = mHopCounts[nodeIndex2.index()] + 1;
mFastRoute[nodeIndex1.index()] = nodeIndex2;
if(active1 || active2)
{
if(!mIslandAwake.test(islandId2))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId2);
}
if(!active1)
{
//Wake up this node...
activateNodeInternal(nodeIndex1);
}
}
}
else if(active1 && !active2)
{
//Active kinematic object -> wake island!
activateIsland(islandId2);
}
}
else
{
//A new touch with a static body...
Node& node = mNodes[nodeIndex2.index()];
node.mStaticTouchCount++; //Increment static touch counter on the body
//Island& island = mIslands[islandId2];
//island.mStaticTouchCount++; //Increment static touch counter on the island
mIslandStaticTouchCount[islandId2]++;
}
}
else if (islandId2 == IG_INVALID_ISLAND)
{
islandId = islandId1;
if (nodeIndex2.index() != PX_INVALID_NODE)
{
if (!mNodes[nodeIndex2.index()].isKinematic())
{
PX_ASSERT(islandId1 != PX_INVALID_NODE);
//We need to add node 1 to island2
PX_ASSERT(mNodes[nodeIndex2.index()].mNextNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
PX_ASSERT(mNodes[nodeIndex2.index()].mPrevNode.index() == PX_INVALID_NODE); //Ensure that this node is not in any other island
Island& island = mIslands[islandId1];
Node& lastNode = mNodes[island.mLastNode.index()];
PX_ASSERT(lastNode.mNextNode.index() == PX_INVALID_NODE);
Node& node = mNodes[nodeIndex2.index()];
lastNode.mNextNode = nodeIndex2;
node.mPrevNode = island.mLastNode;
island.mLastNode = nodeIndex2;
island.mNodeCount[node.mType]++;
mIslandIds[nodeIndex2.index()] = islandId1;
mHopCounts[nodeIndex2.index()] = mHopCounts[nodeIndex1.index()] + 1;
mFastRoute[nodeIndex2.index()] = nodeIndex1;
if(active1 || active2)
{
if(!mIslandAwake.test(islandId1))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId1);
}
if(!active1)
{
//Wake up this node...
activateNodeInternal(nodeIndex2);
}
}
}
else if(active2 && !active1)
{
//Active kinematic object -> wake island!
activateIsland(islandId1);
}
}
else
{
//New static touch
//A new touch with a static body...
Node& node = mNodes[nodeIndex1.index()];
node.mStaticTouchCount++; //Increment static touch counter on the body
//Island& island = mIslands[islandId1];
mIslandStaticTouchCount[islandId1]++;
//island.mStaticTouchCount++; //Increment static touch counter on the island
}
}
else
{
PX_ASSERT(islandId1 != islandId2);
PX_ASSERT(islandId1 != IG_INVALID_ISLAND && islandId2 != IG_INVALID_ISLAND);
if(active1 || active2)
{
//One of the 2 islands was awake, so need to wake the other one! We do this now, before we merge the islands, to ensure that all
//the bodies are activated
if(!mIslandAwake.test(islandId1))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId1);
}
if(!mIslandAwake.test(islandId2))
{
//This island wasn't already awake, so need to wake the whole island up
activateIsland(islandId2);
}
}
//OK. We need to merge these islands together...
islandId = mergeIslands(islandId1, islandId2, nodeIndex1, nodeIndex2);
}
if(islandId != IG_INVALID_ISLAND)
{
//Add new edge to existing island
Island& island = mIslands[islandId];
addEdgeToIsland(island, edgeIndex);
}
}
}
}
}
bool IslandSim::isPathTo(PxNodeIndex startNode, PxNodeIndex targetNode) const
{
const Node& node = mNodes[startNode.index()];
EdgeInstanceIndex index = node.mFirstEdgeIndex;
while(index != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[index];
if(/*mEdges[index/2].isConnected() &&*/ mEdgeNodeIndices[index^1].index() == targetNode.index())
return true;
index = instance.mNextEdge;
}
return false;
}
bool IslandSim::tryFastPath(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId)
{
PX_UNUSED(startNode);
PX_UNUSED(targetNode);
PxNodeIndex currentNode = startNode;
const PxU32 currentVisitedNodes = mVisitedNodes.size();
PxU32 depth = 0;
bool found = false;
do
{
//Get the fast path from this node...
if(mVisitedState.test(currentNode.index()))
{
found = mIslandIds[currentNode.index()] != IG_INVALID_ISLAND; //Already visited and not tagged with invalid island == a witness!
break;
}
if( currentNode.index() == targetNode.index())
{
found = true;
break;
}
mVisitedNodes.pushBack(TraversalState(currentNode, mVisitedNodes.size(), mVisitedNodes.size()-1, depth++));
PX_ASSERT(mFastRoute[currentNode.index()].index() == PX_INVALID_NODE || isPathTo(currentNode, mFastRoute[currentNode.index()]));
mIslandIds[currentNode.index()] = IG_INVALID_ISLAND;
mVisitedState.set(currentNode.index());
currentNode = mFastRoute[currentNode.index()];
}
while(currentNode.index() != PX_INVALID_NODE);
for(PxU32 a = currentVisitedNodes; a < mVisitedNodes.size(); ++a)
{
const TraversalState& state = mVisitedNodes[a];
mIslandIds[state.mNodeIndex.index()] = islandId;
}
if(!found)
{
for(PxU32 a = currentVisitedNodes; a < mVisitedNodes.size(); ++a)
{
const TraversalState& state = mVisitedNodes[a];
mVisitedState.reset(state.mNodeIndex.index());
}
mVisitedNodes.forceSize_Unsafe(currentVisitedNodes);
}
return found;
}
bool IslandSim::findRoute(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId)
{
//Firstly, traverse the fast path and tag up witnesses. TryFastPath can fail. In that case, no witnesses are left but this node is permitted to report
//that it is still part of the island. Whichever node lost its fast path will be tagged as dirty and will be responsible for recovering the fast path
//and tagging up the visited nodes
if(mFastRoute[startNode.index()].index() != PX_INVALID_NODE)
{
if(tryFastPath(startNode, targetNode, islandId))
return true;
//Try fast path can either be successful or not. If it was successful, then we had a valid fast path cached and all nodes on that fast path were tagged
//as witness nodes (visited and with a valid island ID). If the fast path was not successful, then no nodes were tagged as witnesses.
//Technically, we need to find a route to the root node but, as an optimization, we can simply return true from here with no witnesses added.
//Whichever node actually broke the "fast path" will also be on the list of dirty nodes and will be processed later.
//If that broken edge triggered an island separation, this node will be re-visited and added to that island, otherwise
//the path to the root node will be re-established. The end result is the same - the island state is computed - this just saves us some work.
//return true;
}
{
//If we got here, there was no fast path. Therefore, we need to fall back on searching for the root node. This is optimized by using "hop counts".
//These are per-node counts that indicate the expected number of hops from this node to the root node. These are lazily evaluated and updated
//as new edges are formed or when traversals occur to re-establish islands. As a result, they may be inaccurate but they still serve the purpose
//of guiding our search to minimize the chances of us doing an exhaustive search to find the root node.
mIslandIds[startNode.index()] = IG_INVALID_ISLAND;
TraversalState* startTraversal = &mVisitedNodes.pushBack(TraversalState(startNode, mVisitedNodes.size(), PX_INVALID_NODE, 0));
mVisitedState.set(startNode.index());
QueueElement element(startTraversal, mHopCounts[startNode.index()]);
mPriorityQueue.push(element);
do
{
const QueueElement currentQE = mPriorityQueue.pop();
const TraversalState& currentState = *currentQE.mState;
const Node& currentNode = mNodes[currentState.mNodeIndex.index()];
EdgeInstanceIndex edge = currentNode.mFirstEdgeIndex;
while(edge != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[edge];
{
const PxNodeIndex nextIndex = mEdgeNodeIndices[edge ^ 1];
//Static or kinematic nodes don't connect islands.
if(nextIndex.index() != PX_INVALID_NODE && !mNodes[nextIndex.index()].isKinematic())
{
if(nextIndex.index() == targetNode.index())
{
unwindRoute(currentState.mCurrentIndex, nextIndex, 0, islandId);
return true;
}
if(mVisitedState.test(nextIndex.index()))
{
//We already visited this node. This means that it's either in the priority queue already or we
//visited in on a previous pass. If it was visited on a previous pass, then it already knows what island it's in.
//We now need to test the island id to find out if this node knows the root.
//If it has a valid root id, that id *is* our new root. We can guesstimate our hop count based on the node's properties
const IslandId visitedIslandId = mIslandIds[nextIndex.index()];
if(visitedIslandId != IG_INVALID_ISLAND)
{
//If we get here, we must have found a node that knows a route to our root node. It must not be a different island
//because that would caused me to have been visited already because totally separate islands trigger a full traversal on
//the orphaned side.
PX_ASSERT(visitedIslandId == islandId);
unwindRoute(currentState.mCurrentIndex, nextIndex, mHopCounts[nextIndex.index()], islandId);
return true;
}
}
else
{
//This node has not been visited yet, so we need to push it into the stack and continue traversing
TraversalState* state = &mVisitedNodes.pushBack(TraversalState(nextIndex, mVisitedNodes.size(), currentState.mCurrentIndex, currentState.mDepth+1));
QueueElement qe(state, mHopCounts[nextIndex.index()]);
mPriorityQueue.push(qe);
mVisitedState.set(nextIndex.index());
PX_ASSERT(mIslandIds[nextIndex.index()] == islandId);
mIslandIds[nextIndex.index()] = IG_INVALID_ISLAND; //Flag as invalid island until we know whether we can find root or an island id.
}
}
}
edge = instance.mNextEdge;
}
}
while(mPriorityQueue.size());
return false;
}
}
#define IG_LIMIT_DIRTY_NODES 0
void IslandSim::processLostEdges(PxArray<PxNodeIndex>& destroyedNodes, bool allowDeactivation, bool permitKinematicDeactivation, PxU32 dirtyNodeLimit)
{
PX_UNUSED(dirtyNodeLimit);
PX_PROFILE_ZONE("Basic.processLostEdges", getContextId());
//At this point, all nodes and edges are activated.
//Bit map for visited
mVisitedState.resizeAndClear(mNodes.size());
//Reserve space on priority queue for at least 1024 nodes. It will resize if more memory is required during traversal.
mPriorityQueue.reserve(1024);
for (PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
mIslandSplitEdges[i].reserve(1024);
mVisitedNodes.reserve(mNodes.size()); //Make sure we have enough space for all nodes!
const PxU32 nbDestroyedEdges = mDestroyedEdges.size();
PX_UNUSED(nbDestroyedEdges);
{
PX_PROFILE_ZONE("Basic.removeEdgesFromIslands", getContextId());
for (PxU32 a = 0; a < mDestroyedEdges.size(); ++a)
{
const EdgeIndex lostIndex = mDestroyedEdges[a];
Edge& lostEdge = mEdges[lostIndex];
if (lostEdge.isPendingDestroyed() && !lostEdge.isInDirtyList())
{
//Process this edge...
if (!lostEdge.isReportOnlyDestroy() && lostEdge.isInserted())
{
const PxU32 index1 = mEdgeNodeIndices[mDestroyedEdges[a] * 2].index();
const PxU32 index2 = mEdgeNodeIndices[mDestroyedEdges[a] * 2 + 1].index();
IslandId islandId = IG_INVALID_ISLAND;
if (index1 != PX_INVALID_NODE && index2 != PX_INVALID_NODE)
{
PX_ASSERT(mIslandIds[index1] == IG_INVALID_ISLAND || mIslandIds[index2] == IG_INVALID_ISLAND ||
mIslandIds[index1] == mIslandIds[index2]);
islandId = mIslandIds[index1] != IG_INVALID_ISLAND ? mIslandIds[index1] : mIslandIds[index2];
}
else if (index1 != PX_INVALID_NODE)
{
PX_ASSERT(index2 == PX_INVALID_NODE);
Node& node = mNodes[index1];
if (!node.isKinematic())
{
islandId = mIslandIds[index1];
node.mStaticTouchCount--;
//Island& island = mIslands[islandId];
mIslandStaticTouchCount[islandId]--;
//island.mStaticTouchCount--;
}
}
else if (index2 != PX_INVALID_NODE)
{
PX_ASSERT(index1 == PX_INVALID_NODE);
Node& node = mNodes[index2];
if (!node.isKinematic())
{
islandId = mIslandIds[index2];
node.mStaticTouchCount--;
//Island& island = mIslands[islandId];
mIslandStaticTouchCount[islandId]--;
//island.mStaticTouchCount--;
}
}
if (islandId != IG_INVALID_ISLAND)
{
//We need to remove this edge from the island
Island& island = mIslands[islandId];
removeEdgeFromIsland(island, lostIndex);
}
}
lostEdge.clearInserted();
}
}
}
if (allowDeactivation)
{
PX_PROFILE_ZONE("Basic.findPathsAndBreakIslands", getContextId());
//KS - process only this many dirty nodes, deferring future dirty nodes to subsequent frames.
//This means that it may take several frames for broken edges to trigger islands to completely break but this is better
//than triggering large performance spikes.
#if IG_LIMIT_DIRTY_NODES
PxBitMap::PxCircularIterator iter(mDirtyMap, mLastMapIndex);
const PxU32 MaxCount = dirtyNodeLimit;// +10000000;
PxU32 lastMapIndex = mLastMapIndex;
PxU32 count = 0;
#else
PxBitMap::Iterator iter(mDirtyMap);
#endif
PxU32 dirtyIdx;
#if IG_LIMIT_DIRTY_NODES
while ((dirtyIdx = iter.getNext()) != PxBitMap::PxCircularIterator::DONE
&& (count++ < MaxCount)
#else
while ((dirtyIdx = iter.getNext()) != PxBitMap::Iterator::DONE
#endif
)
{
#if IG_LIMIT_DIRTY_NODES
lastMapIndex = dirtyIdx + 1;
#endif
//Process dirty nodes. Figure out if we can make our way from the dirty node to the root.
mPriorityQueue.clear(); //Clear the queue used for traversal
mVisitedNodes.forceSize_Unsafe(0); //Clear the list of nodes in this island
const PxNodeIndex dirtyNodeIndex(dirtyIdx);
Node& dirtyNode = mNodes[dirtyNodeIndex.index()];
//Check whether this node has already been touched. If it has been touched this frame, then its island state is reliable
//and we can just unclear the dirty flag on the body. If we were already visited, then the state should have already been confirmed in a
//previous pass.
if (!dirtyNode.isKinematic() && !dirtyNode.isDeleted() && !mVisitedState.test(dirtyNodeIndex.index()))
{
//We haven't visited this node in our island repair passes yet, so we still need to process until we've hit a visited node or found
//our root node. Note that, as soon as we hit a visited node that has already been processed in a previous pass, we know that we can rely
//on its island information although the hop counts may not be optimal. It also indicates that this island was not broken immediately because
//otherwise, the entire new sub-island would already have been visited and this node would have already had its new island state assigned.
//Indicate that I've been visited
const IslandId islandId = mIslandIds[dirtyNodeIndex.index()];
const Island& findIsland = mIslands[islandId];
const PxNodeIndex searchNode = findIsland.mRootNode;//The node that we're searching for!
if (searchNode.index() != dirtyNodeIndex.index()) //If we are the root node, we don't need to do anything!
{
if (findRoute(dirtyNodeIndex, searchNode, islandId))
{
//We found the root node so let's let every visited node know that we found its root
//and we can also update our hop counts because we recorded how many hops it took to reach this
//node
//We already filled in the path to the root/witness with accurate hop counts. Now we just need to fill in the estimates
//for the remaining nodes and re-define their islandIds. We approximate their path to the root by just routing them through
//the route we already found.
//This loop works because mVisitedNodes are recorded in the order they were visited and we already filled in the critical path
//so the remainder of the paths will just fork from that path.
//Verify state (that we can see the root from this node)...
#if IG_SANITY_CHECKS
PX_ASSERT(canFindRoot(dirtyNodeIndex, searchNode, NULL)); //Verify that we found the connection
#endif
for (PxU32 b = 0; b < mVisitedNodes.size(); ++b)
{
TraversalState& state = mVisitedNodes[b];
if (mIslandIds[state.mNodeIndex.index()] == IG_INVALID_ISLAND)
{
mHopCounts[state.mNodeIndex.index()] = mHopCounts[mVisitedNodes[state.mPrevIndex].mNodeIndex.index()] + 1;
mFastRoute[state.mNodeIndex.index()] = mVisitedNodes[state.mPrevIndex].mNodeIndex;
mIslandIds[state.mNodeIndex.index()] = islandId;
}
}
}
else
{
//If I traversed and could not find the root node, then I have established a new island. In this island, I am the root node
//and I will point all my nodes towards me. Furthermore, I have established how many steps it took to reach all nodes in my island
//OK. We need to separate the islands. We have a list of nodes that are part of the new island (mVisitedNodes) and we know that the
//first node in that list is the root node.
//OK, we need to remove all these actors from their current island, then add them to the new island...
Island& oldIsland = mIslands[islandId];
//We can just unpick these nodes from the island because they do not contain the root node (if they did, then we wouldn't be
//removing this node from the island at all). The only challenge is if we need to remove the last node. In that case
//we need to re-establish the new last node in the island but perhaps the simplest way to do that would be to traverse
//the island to establish the last node again
#if IG_SANITY_CHECKS
PX_ASSERT(!canFindRoot(dirtyNodeIndex, searchNode, NULL));
#endif
PxU32 totalStaticTouchCount = 0;
PxU32 nodeCount[Node::eTYPE_COUNT];
for (PxU32 t = 0; t < Node::eTYPE_COUNT; ++t)
{
nodeCount[t] = 0;
}
for (PxU32 t = 0; t < Edge::eEDGE_TYPE_COUNT; ++t)
{
mIslandSplitEdges[t].forceSize_Unsafe(0);
}
//NodeIndex lastIndex = oldIsland.mLastNode;
//nodeCount[node.mType] = 1;
for (PxU32 a = 0; a < mVisitedNodes.size(); ++a)
{
const PxNodeIndex index = mVisitedNodes[a].mNodeIndex;
Node& node = mNodes[index.index()];
if (node.mNextNode.index() != PX_INVALID_NODE)
mNodes[node.mNextNode.index()].mPrevNode = node.mPrevNode;
else
oldIsland.mLastNode = node.mPrevNode;
if (node.mPrevNode.index() != PX_INVALID_NODE)
mNodes[node.mPrevNode.index()].mNextNode = node.mNextNode;
nodeCount[node.mType]++;
node.mNextNode.setIndices(PX_INVALID_NODE);
node.mPrevNode.setIndices(PX_INVALID_NODE);
PX_ASSERT(mNodes[oldIsland.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
totalStaticTouchCount += node.mStaticTouchCount;
EdgeInstanceIndex idx = node.mFirstEdgeIndex;
while (idx != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[idx];
const EdgeIndex edgeIndex = idx / 2;
const Edge& edge = mEdges[edgeIndex];
//Only split the island if we're processing the first node or if the first node is infinte-mass
if (!(idx & 1) || (mEdgeNodeIndices[idx & (~1)].index() == PX_INVALID_NODE || mNodes[mEdgeNodeIndices[idx & (~1)].index()].isKinematic()))
{
//We will remove this edge from the island...
mIslandSplitEdges[edge.mEdgeType].pushBack(edgeIndex);
removeEdgeFromIsland(oldIsland, edgeIndex);
}
idx = instance.mNextEdge;
}
}
//oldIsland.mStaticTouchCount -= totalStaticTouchCount;
mIslandStaticTouchCount[islandId] -= totalStaticTouchCount;
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
{
PX_ASSERT(nodeCount[i] <= oldIsland.mNodeCount[i]);
oldIsland.mNodeCount[i] -= nodeCount[i];
}
//Now add all these nodes to the new island
//(1) Create the new island...
const IslandId newIslandHandle = mIslandHandles.getHandle();
/*if(newIslandHandle == mIslands.capacity())
{
mIslands.reserve(2*mIslands.capacity() + 1);
}*/
mIslands.resize(PxMax(newIslandHandle + 1, mIslands.size()));
mIslandStaticTouchCount.resize(PxMax(newIslandHandle + 1, mIslandStaticTouchCount.size()));
Island& newIsland = mIslands[newIslandHandle];
if (mIslandAwake.test(islandId))
{
newIsland.mActiveIndex = mActiveIslands.size();
mActiveIslands.pushBack(newIslandHandle);
mIslandAwake.growAndSet(newIslandHandle); //Separated island, so it should be awake
}
else
{
mIslandAwake.growAndReset(newIslandHandle);
}
newIsland.mRootNode = dirtyNodeIndex;
mHopCounts[dirtyNodeIndex.index()] = 0;
mIslandIds[dirtyNodeIndex.index()] = newIslandHandle;
//newIsland.mTotalSize = mVisitedNodes.size();
mNodes[dirtyNodeIndex.index()].mPrevNode.setIndices(PX_INVALID_NODE); //First node so doesn't have a preceding node
mFastRoute[dirtyNodeIndex.index()].setIndices(PX_INVALID_NODE);
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
nodeCount[i] = 0;
nodeCount[dirtyNode.mType] = 1;
for (PxU32 a = 1; a < mVisitedNodes.size(); ++a)
{
const PxNodeIndex index = mVisitedNodes[a].mNodeIndex;
Node& thisNode = mNodes[index.index()];
const PxNodeIndex prevNodeIndex = mVisitedNodes[a - 1].mNodeIndex;
thisNode.mPrevNode = prevNodeIndex;
mNodes[prevNodeIndex.index()].mNextNode = index;
nodeCount[thisNode.mType]++;
mIslandIds[index.index()] = newIslandHandle;
mHopCounts[index.index()] = mVisitedNodes[a].mDepth; //How many hops to root
mFastRoute[index.index()] = mVisitedNodes[mVisitedNodes[a].mPrevIndex].mNodeIndex;
}
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
newIsland.mNodeCount[i] = nodeCount[i];
//Last node in the island
const PxNodeIndex lastIndex = mVisitedNodes[mVisitedNodes.size() - 1].mNodeIndex;
mNodes[lastIndex.index()].mNextNode.setIndices(PX_INVALID_NODE);
newIsland.mLastNode = lastIndex;
//newIsland.mStaticTouchCount = totalStaticTouchCount;
mIslandStaticTouchCount[newIslandHandle] = totalStaticTouchCount;
PX_ASSERT(mNodes[newIsland.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
for (PxU32 j = 0; j < IG::Edge::eEDGE_TYPE_COUNT; ++j)
{
PxArray<EdgeIndex>& splitEdges = mIslandSplitEdges[j];
const PxU32 splitEdgeSize = splitEdges.size();
if (splitEdgeSize)
{
splitEdges.pushBack(IG_INVALID_EDGE); //Push in a dummy invalid edge to complete the connectivity
mEdges[splitEdges[0]].mNextIslandEdge = splitEdges[1];
for (PxU32 a = 1; a < splitEdgeSize; ++a)
{
const EdgeIndex edgeIndex = splitEdges[a];
Edge& edge = mEdges[edgeIndex];
edge.mNextIslandEdge = splitEdges[a + 1];
edge.mPrevIslandEdge = splitEdges[a - 1];
}
newIsland.mFirstEdge[j] = splitEdges[0];
newIsland.mLastEdge[j] = splitEdges[splitEdgeSize - 1];
newIsland.mEdgeCount[j] = splitEdgeSize;
}
}
}
}
}
dirtyNode.clearDirty();
#if IG_LIMIT_DIRTY_NODES
mDirtyMap.reset(dirtyIdx);
#endif
}
#if IG_LIMIT_DIRTY_NODES
mLastMapIndex = lastMapIndex;
if (count < MaxCount)
mLastMapIndex = 0;
#else
mDirtyMap.clear();
#endif
//mDirtyNodes.forceSize_Unsafe(0);
}
{
PX_PROFILE_ZONE("Basic.clearDestroyedEdges", getContextId());
//Now process the lost edges...
for (PxU32 a = 0; a < mDestroyedEdges.size(); ++a)
{
//Process these destroyed edges. Recompute island information. Update the islands and hop counters accordingly
const EdgeIndex index = mDestroyedEdges[a];
Edge& edge = mEdges[index];
if (edge.isPendingDestroyed())
{
//if(edge.mFirstPartitionEdge)
PartitionEdge* pEdge = mFirstPartitionEdges ? (*mFirstPartitionEdges)[index] : NULL;
if (pEdge)
{
mDestroyedPartitionEdges->pushBack(pEdge);
(*mFirstPartitionEdges)[index] = NULL; //Force first partition edge to NULL to ensure we don't have a clash
}
if (edge.isActive())
{
removeEdgeFromActivatingList(index); //TODO - can we remove this call? Can we handle this elsewhere, e.g. when destroying the nodes...
mActiveEdgeCount[edge.mEdgeType]--;
}
edge = Edge(); //Reset edge
mActiveContactEdges.growAndReset(index);
}
}
mDestroyedEdges.forceSize_Unsafe(0);
}
{
PX_PROFILE_ZONE("Basic.clearDestroyedNodes", getContextId());
for (PxU32 a = 0; a < destroyedNodes.size(); ++a)
{
const PxNodeIndex nodeIndex = destroyedNodes[a];
const IslandId islandId = mIslandIds[nodeIndex.index()];
Node& node = mNodes[nodeIndex.index()];
if (islandId != IG_INVALID_ISLAND)
{
Island& island = mIslands[islandId];
removeNodeFromIsland(island, nodeIndex);
mIslandIds[nodeIndex.index()] = IG_INVALID_ISLAND;
PxU32 nodeCountTotal = 0;
for (PxU32 t = 0; t < Node::eTYPE_COUNT; ++t)
{
nodeCountTotal += island.mNodeCount[t];
}
if (nodeCountTotal == 0)
{
mIslandHandles.freeHandle(islandId);
if (island.mActiveIndex != IG_INVALID_ISLAND)
{
const IslandId replaceId = mActiveIslands[mActiveIslands.size() - 1];
Island& replaceIsland = mIslands[replaceId];
replaceIsland.mActiveIndex = island.mActiveIndex;
mActiveIslands[island.mActiveIndex] = replaceId;
mActiveIslands.forceSize_Unsafe(mActiveIslands.size() - 1);
island.mActiveIndex = IG_INVALID_ISLAND;
//island.mStaticTouchCount -= node.mStaticTouchCount; //Remove the static touch count from the island
mIslandStaticTouchCount[islandId] -= node.mStaticTouchCount;
}
mIslandAwake.reset(islandId);
island.mLastNode.setIndices(PX_INVALID_NODE);
island.mRootNode.setIndices(PX_INVALID_NODE);
island.mActiveIndex = IG_INVALID_ISLAND;
}
}
if (node.isKinematic())
{
if (mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
//Remove from the active kinematics list...
markKinematicInactive(nodeIndex);
}
}
else
{
if (mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
markInactive(nodeIndex);
}
}
//node.reset();
node.mFlags |= Node::eDELETED;
}
}
//Now we need to produce the list of active edges and nodes!!!
//If we get here, we have a list of active islands. From this, we need to iterate over all active islands and establish if that island
//can, in fact, go to sleep. In order to become deactivated, all nodes in the island must be ready for sleeping...
if (allowDeactivation)
{
PX_PROFILE_ZONE("Basic.deactivation", getContextId());
for (PxU32 a = 0; a < mActiveIslands.size(); a++)
{
const IslandId islandId = mActiveIslands[a];
mIslandAwake.reset(islandId);
}
//Loop over the active kinematic nodes and tag all islands touched by active kinematics as awake
for (PxU32 a = mActiveKinematicNodes.size(); a > 0; --a)
{
const PxNodeIndex kinematicIndex = mActiveKinematicNodes[a - 1];
Node& kinematicNode = mNodes[kinematicIndex.index()];
if (kinematicNode.isReadyForSleeping())
{
if (permitKinematicDeactivation)
{
kinematicNode.clearActive();
markKinematicInactive(kinematicIndex);
}
}
else //if(!kinematicNode.isReadyForSleeping())
{
//KS - if kinematic is active, then wake up all islands the kinematic is touching
EdgeInstanceIndex edgeId = kinematicNode.mFirstEdgeIndex;
while (edgeId != IG_INVALID_EDGE)
{
EdgeInstance& instance = mEdgeInstances[edgeId];
//Edge& edge = mEdges[edgeId/2];
//Only wake up islands if a connection was present
//if(edge.isConnected())
{
PxNodeIndex outNode = mEdgeNodeIndices[edgeId ^ 1];
if (outNode.index() != PX_INVALID_NODE)
{
IslandId islandId = mIslandIds[outNode.index()];
if (islandId != IG_INVALID_ISLAND)
{
mIslandAwake.set(islandId);
PX_ASSERT(mIslands[islandId].mActiveIndex != IG_INVALID_ISLAND);
}
}
}
edgeId = instance.mNextEdge;
}
}
}
for (PxU32 a = mActiveIslands.size(); a > 0; --a)
{
const IslandId islandId = mActiveIslands[a - 1];
const Island& island = mIslands[islandId];
bool canDeactivate = !mIslandAwake.test(islandId);
mIslandAwake.set(islandId);
//If it was touched by an active kinematic in the above loop, we can't deactivate it.
//Therefore, no point in testing the nodes in the island. They must remain awake
if (canDeactivate)
{
PxNodeIndex nodeId = island.mRootNode;
while (nodeId.index() != PX_INVALID_NODE)
{
Node& node = mNodes[nodeId.index()];
if (!node.isReadyForSleeping())
{
canDeactivate = false;
break;
}
nodeId = node.mNextNode;
}
if (canDeactivate)
{
//If all nodes in this island are ready for sleeping and there were no active
//kinematics interacting with the any bodies in the island, we can deactivate the island.
deactivateIsland(islandId);
}
}
}
}
{
PX_PROFILE_ZONE("Basic.resetDirtyEdges", getContextId());
for (PxU32 i = 0; i < Edge::eEDGE_TYPE_COUNT; ++i)
{
for (PxU32 a = 0; a < mDirtyEdges[i].size(); ++a)
{
Edge& edge = mEdges[mDirtyEdges[i][a]];
edge.clearInDirtyList();
}
mDirtyEdges[i].clear(); //All new edges processed
}
}
}
IslandId IslandSim::mergeIslands(IslandId island0, IslandId island1, PxNodeIndex node0, PxNodeIndex node1)
{
Island& is0 = mIslands[island0];
Island& is1 = mIslands[island1];
//We defer this process and do it later instead. That way, if we have some pathalogical
//case where multiple islands get merged repeatedly, we don't end up repeatedly remapping all the nodes in those islands
//to their new island. Instead, we just choose the largest island and remap the smaller island to that.
PxU32 totalSize0 = 0;
PxU32 totalSize1 = 0;
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
{
totalSize0 += is0.mNodeCount[i];
totalSize1 += is1.mNodeCount[i];
}
if(totalSize0 > totalSize1)
{
mergeIslandsInternal(is0, is1, island0, island1, node0, node1);
mIslandAwake.reset(island1);
mIslandHandles.freeHandle(island1);
mFastRoute[node1.index()] = node0;
return island0;
}
else
{
mergeIslandsInternal(is1, is0, island1, island0, node1, node0);
mIslandAwake.reset(island0);
mIslandHandles.freeHandle(island0);
mFastRoute[node0.index()] = node1;
return island1;
}
}
bool IslandSim::checkInternalConsistency() const
{
//Loop over islands, confirming that the island data is consistent...
//Really expensive. Turn off unless investigating some random issue...
#if 0
for (PxU32 a = 0; a < mIslands.size(); ++a)
{
const Island& island = mIslands[a];
PxU32 expectedNodeCount = 0;
for (PxU32 t = 0; t < Node::eTYPE_COUNT; ++t)
{
expectedNodeCount += island.mNodeCount[t];
}
bool metLastNode = expectedNodeCount == 0;
PxNodeIndex nodeId = island.mRootNode;
while (nodeId.index() != PX_INVALID_NODE)
{
PX_ASSERT(mIslandIds[nodeId.index()] == a);
if (nodeId.index() == island.mLastNode.index())
{
metLastNode = true;
PX_ASSERT(mNodes[nodeId.index()].mNextNode.index() == PX_INVALID_NODE);
}
--expectedNodeCount;
nodeId = mNodes[nodeId.index()].mNextNode;
}
PX_ASSERT(expectedNodeCount == 0);
PX_ASSERT(metLastNode);
}
#endif
return true;
}
void IslandSim::mergeIslandsInternal(Island& island0, Island& island1, IslandId islandId0, IslandId islandId1, PxNodeIndex nodeIndex0, PxNodeIndex nodeIndex1)
{
#if PX_ENABLE_ASSERTS
PxU32 island0Size = 0;
PxU32 island1Size = 0;
for(PxU32 nodeType = 0; nodeType < Node::eTYPE_COUNT; ++nodeType)
{
island0Size += island0.mNodeCount[nodeType];
island1Size += island1.mNodeCount[nodeType];
}
#endif
PX_ASSERT(island0Size >= island1Size); //We only ever merge the smaller island to the larger island
//Stage 1 - we need to move all the nodes across to the new island ID (i.e. write all their new island indices, move them to the
//island and then also update their estimated hop counts to the root. As we don't want to do a full traversal at this point,
//instead, we estimate based on the route from the node to their previous root and then from that root to the new connection
//between the 2 islands. This is probably a very indirect route but it will be refined later.
//In this case, island1 is subsumed by island0
//It takes mHopCounts[nodeIndex1] to get from node1 to its old root. It takes mHopCounts[nodeIndex0] to get from nodeIndex0 to the new root
//and it takes 1 extra hop to go from node1 to node0. Therefore, a sub-optimal route can be planned going via the old root node that should take
//mHopCounts[nodeIndex0] + mHopCounts[nodeIndex1] + 1 + mHopCounts[nodeIndex] to travel from any arbitrary node (nodeIndex) in island1 to the root
//of island2.
const PxU32 extraPath = mHopCounts[nodeIndex0.index()] + mHopCounts[nodeIndex1.index()] + 1;
PxNodeIndex islandNode = island1.mRootNode;
while(islandNode.index() != PX_INVALID_NODE)
{
mHopCounts[islandNode.index()] += extraPath;
mIslandIds[islandNode.index()] = islandId0;
//mFastRoute[islandNode] = PX_INVALID_NODE;
Node& node = mNodes[islandNode.index()];
islandNode = node.mNextNode;
}
//Now fill in the hop count for node1, which is directly connected to node0.
mHopCounts[nodeIndex1.index()] = mHopCounts[nodeIndex0.index()] + 1;
Node& lastNode = mNodes[island0.mLastNode.index()];
Node& firstNode = mNodes[island1.mRootNode.index()];
PX_ASSERT(lastNode.mNextNode.index() == PX_INVALID_NODE);
PX_ASSERT(firstNode.mPrevNode.index() == PX_INVALID_NODE);
PX_ASSERT(island1.mRootNode.index() != island0.mLastNode.index());
PX_ASSERT(mNodes[island0.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
PX_ASSERT(mNodes[island1.mLastNode.index()].mNextNode.index() == PX_INVALID_NODE);
PX_ASSERT(mIslandIds[island0.mLastNode.index()] == islandId0);
lastNode.mNextNode = island1.mRootNode;
firstNode.mPrevNode = island0.mLastNode;
island0.mLastNode = island1.mLastNode;
//island0.mStaticTouchCount += island1.mStaticTouchCount;
mIslandStaticTouchCount[islandId0] += mIslandStaticTouchCount[islandId1];
//Merge the edge list for the islands...
for(PxU32 a = 0; a < IG::Edge::eEDGE_TYPE_COUNT; ++a)
{
if(island0.mLastEdge[a] != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[island0.mLastEdge[a]].mNextIslandEdge == IG_INVALID_EDGE);
mEdges[island0.mLastEdge[a]].mNextIslandEdge = island1.mFirstEdge[a];
}
else
{
PX_ASSERT(island0.mFirstEdge[a] == IG_INVALID_EDGE);
island0.mFirstEdge[a] = island1.mFirstEdge[a];
}
if(island1.mFirstEdge[a] != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[island1.mFirstEdge[a]].mPrevIslandEdge == IG_INVALID_EDGE);
mEdges[island1.mFirstEdge[a]].mPrevIslandEdge = island0.mLastEdge[a];
island0.mLastEdge[a] = island1.mLastEdge[a];
}
island0.mEdgeCount[a] += island1.mEdgeCount[a];
island1.mFirstEdge[a] = IG_INVALID_EDGE;
island1.mLastEdge[a] = IG_INVALID_EDGE;
island1.mEdgeCount[a] = 0;
}
for (PxU32 a = 0; a < IG::Node::eTYPE_COUNT; ++a)
{
island0.mNodeCount[a] += island1.mNodeCount[a];
island1.mNodeCount[a] = 0;
}
island1.mLastNode.setIndices(PX_INVALID_NODE);
island1.mRootNode.setIndices(PX_INVALID_NODE);
mIslandStaticTouchCount[islandId1] = 0;
//island1.mStaticTouchCount = 0;
//Remove from active island list
if(island1.mActiveIndex != IG_INVALID_ISLAND)
markIslandInactive(islandId1);
}
void IslandSim::removeEdgeFromActivatingList(EdgeIndex index)
{
Edge& edge = mEdges[index];
if (edge.mEdgeState & Edge::eACTIVATING)
{
for (PxU32 a = 0, count = mActivatedEdges[edge.mEdgeType].size(); a < count; a++)
{
if (mActivatedEdges[edge.mEdgeType][a] == index)
{
mActivatedEdges[edge.mEdgeType].replaceWithLast(a);
break;
}
}
edge.mEdgeState &= (~Edge::eACTIVATING);
}
const PxNodeIndex nodeIndex1 = mEdgeNodeIndices[index * 2];
const PxNodeIndex nodeIndex2 = mEdgeNodeIndices[index * 2 + 1];
if (nodeIndex1.isValid() && nodeIndex2.isValid())
{
{
Node& node = mNodes[nodeIndex1.index()];
node.mActiveRefCount--;
}
{
Node& node = mNodes[nodeIndex2.index()];
node.mActiveRefCount--;
}
}
if(edge.mEdgeType == Edge::eCONTACT_MANAGER)
mActiveContactEdges.reset(index);
}
void IslandSim::setKinematic(PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
if(!node.isKinematic())
{
//Transition from dynamic to kinematic:
//(1) Remove this node from the island
//(2) Remove this node from the active node list
//(3) If active or referenced, add it to the active kinematic list
//(4) Tag the node as kinematic
//External code will re-filter interactions and lost touches will be reported
const IslandId islandId = mIslandIds[nodeIndex.index()];
PX_ASSERT(islandId != IG_INVALID_ISLAND);
Island& island = mIslands[islandId];
mIslandIds[nodeIndex.index()] = IG_INVALID_ISLAND;
removeNodeFromIsland(island, nodeIndex);
const bool isActive = node.isActive();
if (isActive)
{
//Remove from active list...
markInactive(nodeIndex);
}
else if (node.isActivating())
{
//Remove from activating list...
node.clearActivating();
PX_ASSERT(mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]].index() == nodeIndex.index());
const PxNodeIndex replaceIndex = mActivatingNodes[mActivatingNodes.size() - 1];
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[nodeIndex.index()];
mActivatingNodes[mActiveNodeIndex[nodeIndex.index()]] = replaceIndex;
mActivatingNodes.forceSize_Unsafe(mActivatingNodes.size() - 1);
mActiveNodeIndex[nodeIndex.index()] = PX_INVALID_NODE;
}
node.setKinematicFlag();
node.clearActive();
if (/*isActive || */node.mActiveRefCount != 0)
{
//Add to active kinematic list...
PX_ASSERT(mActiveNodeIndex[nodeIndex.index()] == PX_INVALID_NODE);
mActiveNodeIndex[nodeIndex.index()] = mActivatingNodes.size();
mActivatingNodes.pushBack(nodeIndex);
node.setActivating();
}
{
//This node was potentially in an island with other bodies. We need to force an island recomputation in case the
//islands became broken due to losing this connection. Same rules as losing a contact, we just
//tag the nodes directly connected to the lost edge as "dirty" and force an island recomputation if
//it resulted in lost connections
EdgeInstanceIndex edgeId = node.mFirstEdgeIndex;
while(edgeId != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[edgeId];
const EdgeInstanceIndex nextId = instance.mNextEdge;
const PxU32 idx = edgeId/2;
IG::Edge& edge = mEdges[edgeId/2];
removeEdgeFromIsland(island, idx);
removeConnectionInternal(idx);
removeConnectionFromGraph(idx);
edge.clearInserted();
if (edge.isActive())
{
removeEdgeFromActivatingList(idx);
edge.deactivateEdge();
mActiveEdgeCount[edge.mEdgeType]--;
mDeactivatingEdges[edge.mEdgeType].pushBack(idx);
}
if(!edge.isPendingDestroyed())
{
if(!edge.isInDirtyList())
{
PX_ASSERT(!contains(mDirtyEdges[edge.mEdgeType], idx));
mDirtyEdges[edge.mEdgeType].pushBack(idx);
edge.markInDirtyList();
}
}
else
{
edge.setReportOnlyDestroy();
}
edgeId = nextId;
}
}
PxU32 newNodeCount = 0;
for(PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
newNodeCount += island.mNodeCount[i];
if(newNodeCount == 0)
{
// If this island is empty after having removed the edges of the node we've just set to kinematic
// we invalidate all edges and set the island to inactive
for(PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
island.mFirstEdge[a] = island.mLastEdge[a] = IG_INVALID_EDGE;
island.mEdgeCount[a] = 0;
mIslandStaticTouchCount[islandId] = 0;
//island.mStaticTouchCount = 0;
}
if(island.mActiveIndex != IG_INVALID_ISLAND)
{
markIslandInactive(islandId);
}
mIslandAwake.reset(islandId);
mIslandHandles.freeHandle(islandId);
}
}
}
void IslandSim::setDynamic(PxNodeIndex nodeIndex)
{
//(1) Remove all edges involving this node from all islands they may be in
//(2) Mark all edges as "new" edges - let island gen re-process them!
//(3) Remove this node from the active kinematic list
//(4) Add this node to the active dynamic list (if it is active)
//(5) Mark node as dynamic
Node& node = mNodes[nodeIndex.index()];
if(node.isKinematic())
{
//EdgeInstanceIndex edgeIndex = node.mFirstEdgeIndex;
EdgeInstanceIndex edgeId = node.mFirstEdgeIndex;
while(edgeId != IG_INVALID_EDGE)
{
const EdgeInstance& instance = mEdgeInstances[edgeId];
const EdgeInstanceIndex nextId = instance.mNextEdge;
const PxNodeIndex otherNode = mEdgeNodeIndices[edgeId^1];
const PxU32 idx = edgeId/2;
IG::Edge& edge = mEdges[edgeId/2];
if(!otherNode.isStaticBody())
{
const IslandId islandId = mIslandIds[otherNode.index()];
if(islandId != IG_INVALID_ISLAND)
removeEdgeFromIsland(mIslands[islandId], idx);
}
removeConnectionInternal(idx);
removeConnectionFromGraph(idx);
edge.clearInserted();
if (edge.isActive())
{
edge.deactivateEdge();
removeEdgeFromActivatingList(idx);
mActiveEdgeCount[edge.mEdgeType]--;
}
if(!edge.isPendingDestroyed())
{
if(!edge.isInDirtyList())
{
PX_ASSERT(!contains(mDirtyEdges[edge.mEdgeType], idx));
mDirtyEdges[edge.mEdgeType].pushBack(idx);
edge.markInDirtyList();
}
}
else
{
edge.setReportOnlyDestroy();
}
edgeId = nextId;
}
if(!node.isActivating() && mActiveNodeIndex[nodeIndex.index()] != PX_INVALID_NODE)
{
//Remove from active kinematic list, add to active dynamic list
PxU32 oldRefCount = node.mActiveRefCount;
node.mActiveRefCount = 0;
markKinematicInactive(nodeIndex);
node.mActiveRefCount = oldRefCount;
}
node.clearKinematicFlag();
//Create an island for this node. If there are any edges affecting this node, they will have been marked as
//"new" and will be processed next island update.
{
IslandId islandHandle = mIslandHandles.getHandle();
if(islandHandle == mIslands.capacity())
{
const PxU32 newCapacity = 2*mIslands.capacity()+1;
mIslands.reserve(newCapacity);
mIslandAwake.resize(newCapacity);
mIslandStaticTouchCount.resize(newCapacity);
}
mIslandAwake.reset(islandHandle);
mIslands.resize(PxMax(islandHandle+1, mIslands.size()));
mIslandStaticTouchCount.resize(PxMax(islandHandle + 1, mIslands.size()));
Island& island = mIslands[islandHandle];
island.mLastNode = island.mRootNode = nodeIndex;
PX_ASSERT(mNodes[nodeIndex.index()].mNextNode.index() == PX_INVALID_NODE);
island.mNodeCount[node.mType] = 1;
mIslandIds[nodeIndex.index()] = islandHandle;
mIslandStaticTouchCount[islandHandle] = 0;
if(node.isActive())
{
node.clearActive();
activateNode(nodeIndex);
}
}
}
}
| 79,924 | C++ | 33.420758 | 198 | 0.699052 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/src/PxsDefaultMemoryManager.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxsMemoryManager.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxArray.h"
using namespace physx;
namespace
{
class PxsDefaultMemoryAllocator : public PxVirtualAllocatorCallback
{
public:
virtual void* allocate(const size_t size, const int, const char*, const int) { return PX_ALLOC(size, "unused"); }
virtual void deallocate(void* ptr) { PX_FREE(ptr); }
};
class PxsDefaultMemoryManager : public PxsMemoryManager
{
public:
// PxsMemoryManager
virtual PxVirtualAllocatorCallback* getHostMemoryAllocator() PX_OVERRIDE { return &mDefaultMemoryAllocator; }
virtual PxVirtualAllocatorCallback* getDeviceMemoryAllocator() PX_OVERRIDE { return NULL; }
//~PxsMemoryManager
PxsDefaultMemoryAllocator mDefaultMemoryAllocator;
};
}
PxsMemoryManager* physx::createDefaultMemoryManager()
{
return PX_NEW(PxsDefaultMemoryManager);
}
| 2,590 | C++ | 42.915254 | 115 | 0.764865 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsRigidBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_RIGID_BODY_H
#define PXS_RIGID_BODY_H
#include "PxvDynamics.h"
#include "CmSpatialVector.h"
namespace physx
{
struct PxsCCDBody;
#define PX_INTERNAL_LOCK_FLAG_START 8
PX_ALIGN_PREFIX(16)
class PxsRigidBody
{
public:
enum PxsRigidBodyFlag
{
eFROZEN = 1 << 0, //This flag indicates that the stabilization is enabled and the body is
//"frozen". By "frozen", we mean that the body's transform is unchanged
//from the previous frame. This permits various optimizations.
eFREEZE_THIS_FRAME = 1 << 1,
eUNFREEZE_THIS_FRAME = 1 << 2,
eACTIVATE_THIS_FRAME = 1 << 3,
eDEACTIVATE_THIS_FRAME = 1 << 4,
// PT: this flag is now only used on the GPU. For the CPU the data is now stored directly in PxsBodyCore.
eDISABLE_GRAVITY_GPU = 1 << 5,
eSPECULATIVE_CCD = 1 << 6,
eENABLE_GYROSCOPIC = 1 << 7,
//KS - copied here for GPU simulation to avoid needing to pass another set of flags around.
eLOCK_LINEAR_X = 1 << (PX_INTERNAL_LOCK_FLAG_START),
eLOCK_LINEAR_Y = 1 << (PX_INTERNAL_LOCK_FLAG_START + 1),
eLOCK_LINEAR_Z = 1 << (PX_INTERNAL_LOCK_FLAG_START + 2),
eLOCK_ANGULAR_X = 1 << (PX_INTERNAL_LOCK_FLAG_START + 3),
eLOCK_ANGULAR_Y = 1 << (PX_INTERNAL_LOCK_FLAG_START + 4),
eLOCK_ANGULAR_Z = 1 << (PX_INTERNAL_LOCK_FLAG_START + 5),
eRETAIN_ACCELERATION = 1 << 14,
eFIRST_BODY_COPY_GPU = 1 << 15 // Flag to raise to indicate that the body is DMA'd to the GPU for the first time
};
PX_FORCE_INLINE PxsRigidBody(PxsBodyCore* core, PxReal freeze_count) :
// PT: TODO: unify naming conventions
mLastTransform (core->body2World),
mInternalFlags (0),
solverIterationCounts (core->solverIterationCounts),
mCCD (NULL),
mCore (core),
sleepLinVelAcc (PxVec3(0.0f)),
freezeCount (freeze_count),
sleepAngVelAcc (PxVec3(0.0f)),
accelScale (1.0f)
{}
PX_FORCE_INLINE ~PxsRigidBody() {}
PX_FORCE_INLINE const PxTransform& getPose() const { PX_ASSERT(mCore->body2World.isSane()); return mCore->body2World; }
PX_FORCE_INLINE const PxVec3& getLinearVelocity() const { PX_ASSERT(mCore->linearVelocity.isFinite()); return mCore->linearVelocity; }
PX_FORCE_INLINE const PxVec3& getAngularVelocity() const { PX_ASSERT(mCore->angularVelocity.isFinite()); return mCore->angularVelocity; }
PX_FORCE_INLINE void setVelocity(const PxVec3& linear,
const PxVec3& angular) { PX_ASSERT(linear.isFinite()); PX_ASSERT(angular.isFinite());
mCore->linearVelocity = linear;
mCore->angularVelocity = angular; }
PX_FORCE_INLINE void setLinearVelocity(const PxVec3& linear) { PX_ASSERT(linear.isFinite()); mCore->linearVelocity = linear; }
PX_FORCE_INLINE void setAngularVelocity(const PxVec3& angular) { PX_ASSERT(angular.isFinite()); mCore->angularVelocity = angular; }
PX_FORCE_INLINE void constrainLinearVelocity();
PX_FORCE_INLINE void constrainAngularVelocity();
PX_FORCE_INLINE PxU32 getIterationCounts() { return mCore->solverIterationCounts; }
PX_FORCE_INLINE PxReal getReportThreshold() const { return mCore->contactReportThreshold; }
PX_FORCE_INLINE const PxTransform& getLastCCDTransform() const { return mLastTransform; }
PX_FORCE_INLINE void saveLastCCDTransform() { mLastTransform = mCore->body2World; }
PX_FORCE_INLINE bool isKinematic() const { return mCore->inverseMass == 0.0f; }
PX_FORCE_INLINE void setPose(const PxTransform& pose) { mCore->body2World = pose; }
PX_FORCE_INLINE void setPosition(const PxVec3& position) { mCore->body2World.p = position; }
PX_FORCE_INLINE PxReal getInvMass() const { return mCore->inverseMass; }
PX_FORCE_INLINE PxVec3 getInvInertia() const { return mCore->inverseInertia; }
PX_FORCE_INLINE PxReal getMass() const { return 1.0f/mCore->inverseMass; }
PX_FORCE_INLINE PxVec3 getInertia() const { return PxVec3(1.0f/mCore->inverseInertia.x,
1.0f/mCore->inverseInertia.y,
1.0f/mCore->inverseInertia.z); }
PX_FORCE_INLINE PxsBodyCore& getCore() { return *mCore; }
PX_FORCE_INLINE const PxsBodyCore& getCore() const { return *mCore; }
PX_FORCE_INLINE PxU32 isActivateThisFrame() const { return PxU32(mInternalFlags & eACTIVATE_THIS_FRAME); }
PX_FORCE_INLINE PxU32 isDeactivateThisFrame() const { return PxU32(mInternalFlags & eDEACTIVATE_THIS_FRAME); }
PX_FORCE_INLINE PxU32 isFreezeThisFrame() const { return PxU32(mInternalFlags & eFREEZE_THIS_FRAME); }
PX_FORCE_INLINE PxU32 isUnfreezeThisFrame() const { return PxU32(mInternalFlags & eUNFREEZE_THIS_FRAME); }
PX_FORCE_INLINE void clearFreezeFlag() { mInternalFlags &= ~eFREEZE_THIS_FRAME; }
PX_FORCE_INLINE void clearUnfreezeFlag() { mInternalFlags &= ~eUNFREEZE_THIS_FRAME; }
PX_FORCE_INLINE void clearAllFrameFlags() { mInternalFlags &= ~(eFREEZE_THIS_FRAME | eUNFREEZE_THIS_FRAME | eACTIVATE_THIS_FRAME | eDEACTIVATE_THIS_FRAME); }
PX_FORCE_INLINE void resetSleepFilter() { sleepAngVelAcc = sleepLinVelAcc = PxVec3(0.0f); }
// PT: implemented in PxsCCD.cpp:
void advanceToToi(PxReal toi, PxReal dt, bool clip);
void advancePrevPoseToToi(PxReal toi);
// PxTransform getAdvancedTransform(PxReal toi) const;
Cm::SpatialVector getPreSolverVelocities() const;
PxTransform mLastTransform; //28 (28)
PxU16 mInternalFlags; //30 (30)
PxU16 solverIterationCounts; //32 (32)
PxsCCDBody* mCCD; //36 (40) // only valid during CCD
PxsBodyCore* mCore; //40 (48)
#if !PX_P64_FAMILY
PxU32 alignmentPad[2]; //48 (48)
#endif
PxVec3 sleepLinVelAcc; //60 (60)
PxReal freezeCount; //64 (64)
PxVec3 sleepAngVelAcc; //76 (76)
PxReal accelScale; //80 (80)
}
PX_ALIGN_SUFFIX(16);
PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxsRigidBody) & 0x0f));
void PxsRigidBody::constrainLinearVelocity()
{
const PxU32 lockFlags = mCore->lockFlags;
if(lockFlags)
{
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_X)
mCore->linearVelocity.x = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Y)
mCore->linearVelocity.y = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_LINEAR_Z)
mCore->linearVelocity.z = 0.0f;
}
}
void PxsRigidBody::constrainAngularVelocity()
{
const PxU32 lockFlags = mCore->lockFlags;
if(lockFlags)
{
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_X)
mCore->angularVelocity.x = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Y)
mCore->angularVelocity.y = 0.0f;
if(lockFlags & PxRigidDynamicLockFlag::eLOCK_ANGULAR_Z)
mCore->angularVelocity.z = 0.0f;
}
}
}
#endif
| 8,645 | C | 45.483871 | 166 | 0.686871 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsMemoryManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MEMORY_MANAGER_H
#define PXS_MEMORY_MANAGER_H
#include "foundation/PxPreprocessor.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
class PxVirtualAllocatorCallback;
class PxsMemoryManager : public PxUserAllocated
{
public:
virtual ~PxsMemoryManager(){}
virtual PxVirtualAllocatorCallback* getHostMemoryAllocator() = 0;
virtual PxVirtualAllocatorCallback* getDeviceMemoryAllocator() = 0;
};
// PT: this is for CPU, see createPxgMemoryManager for GPU
PxsMemoryManager* createDefaultMemoryManager();
}
#endif
| 2,253 | C | 42.346153 | 74 | 0.76964 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsCCD.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxGeometry.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxUserAllocated.h"
#include "GuCCDSweepConvexMesh.h"
#ifndef PXS_CCD_H
#define PXS_CCD_H
#define CCD_DEBUG_PRINTS 0
#define CCD_POST_DEPENETRATE_DIST 0.001f
#define CCD_ROTATION_LOCKING 0
#define CCD_MIN_TIME_LEFT 0.01f
#define DEBUG_RENDER_CCD 0
#if CCD_DEBUG_PRINTS
namespace physx {
extern void printCCDDebug(const char* msg, const PxsRigidBody* atom0, PxGeometryType::Enum g0, bool printPtr = true);
extern void printShape(PxsRigidBody* atom0, PxGeometryType::Enum g0, const char* annotation, PxReal dt, PxU32 pass, bool printPtr = true);
}
#define PRINTCCDSHAPE(x) printShape x
#define PRINTCCDDEBUG(x) printCCDDebug x
#else
#define PRINTCCDSHAPE(x)
#define PRINTCCDDEBUG(x)
#endif
namespace physx
{
float computeCCDThreshold(const PxGeometry& geometry);
// ------------------------------------------------------------------------------------------------------------
// a fraction of objects will be CCD active so this is dynamic, not a member of PsxRigidBody
// CCD code builds a temporary array of PxsCCDPair objects (allocated in blocks)
// this is done to gather scattered data from memory and also to reduce PxsRidigBody permanent memory footprint
// we have to do it every pass since new CMs can become fast moving after each pass (and sometimes cease to be)
//
struct PxsCCDBody;
class PxsRigidBody;
struct PxsShapeCore;
struct PxsRigidCore;
class PxsContactManager;
class PxsContext;
class PxCCDContactModifyCallback;
class PxcNpThreadContext;
class PxvNphaseImplementationContext;
namespace Dy
{
class ThresholdStream;
}
/**
\brief structure to represent interactions between a given body and another body.
*/
struct PxsCCDOverlap
{
//The body the interaction relates to
PxsCCDBody* mBody;
//The next interaction in the list
PxsCCDOverlap* mNext;
};
/**
\brief Temporary CCD representation for a shape.
Stores data about a shape that may be frequently used in CCD. It also stores update counters per-shape that can be compared with the body's update
counter to determine if the shape needs its transforms re-calculated. This avoids us needing to store a list of shapes in a CCD body.
*/
struct PxsCCDShape : public Gu::CCDShape
{
const PxsShapeCore* mShapeCore; //Shape core (can be shared)
const PxsRigidCore* mRigidCore; //Rigid body core
PxNodeIndex mNodeIndex;
};
/**
\brief Structure to represent a body in the CCD system.
*/
struct PxsCCDBody
{
Cm::SpatialVector mPreSolverVelocity;
PxU16 mIndex; //The CCD body's index
bool mPassDone; //Whether it has been processed in the current CCD pass
bool mHasAnyPassDone; //Whether this body was influenced by any passes
PxReal mTimeLeft; //CCD time left to elapse (normalized in range 0-1)
PxsRigidBody* mBody; //The rigid body
PxsCCDOverlap* mOverlappingObjects; //A list of overlapping bodies for island update
PxU32 mUpdateCount; //How many times this body has eben updated in the CCD. This is correlated with CCD shapes' update counts.
PxU32 mNbInteractionsThisPass; //How many interactions this pass
/**
\brief Returns the CCD body's index.
\return The CCD body's index.
*/
PX_FORCE_INLINE PxU32 getIndex() const { return mIndex; }
/**
\brief Tests whether this body has already registered an overlap with a given body.
\param[in] body The body to test against.
\return Whether this body has already registered an overlap with a given body.
*/
bool overlaps(PxsCCDBody* body) const
{
PxsCCDOverlap* overlaps = mOverlappingObjects;
while(overlaps)
{
if(overlaps->mBody == body)
return true;
overlaps = overlaps->mNext;
}
return false;
}
/**
\brief Registers an overlap with a given body
\param[in] overlap The CCD overlap to register.
*/
void addOverlap(PxsCCDOverlap* overlap)
{
overlap->mNext = mOverlappingObjects;
mOverlappingObjects = overlap;
}
};
/**
\brief a container class used in the CCD that minimizes frequency of hitting the allocator.
This class stores a set of blocks of memory. It is effectively an array that resizes more efficiently because it doesn't need to
reallocate an entire buffer and copy data.
*/
template<typename T, int BLOCK_SIZE>
struct PxsCCDBlockArray
{
/**
\brief A block of data
*/
struct Block : PxUserAllocated { T items[BLOCK_SIZE]; };
/**
\brief A header for a block of data.
*/
struct BlockInfo
{
Block* block;
PxU32 count; // number of elements in this block
BlockInfo(Block* aBlock, PxU32 aCount) : block(aBlock), count(aCount) {}
};
/*
\brief An array of block headers
*/
PxArray<BlockInfo> blocks;
/**
\brief The current block.
*/
PxU32 currentBlock;
/**
\brief Constructor
*/
PxsCCDBlockArray() : currentBlock(0)
{
blocks.pushBack(BlockInfo(PX_NEW(Block), 0));
}
/**
\brief Destructor
*/
~PxsCCDBlockArray()
{
for (PxU32 i = 0; i < blocks.size(); i++)
{
PX_DELETE(blocks[i].block);
}
currentBlock = 0;
}
/**
\brief Clears this block array.
\note This clear function also deletes all additional blocks
*/
void clear()
{
for (PxU32 i = 0; i < blocks.size(); i++)
{
PX_DELETE(blocks[i].block);
}
blocks.clear();
blocks.pushBack(BlockInfo(PX_NEW(Block), 0)); // at least one block is expected to always be present in the array
currentBlock = 0;
}
/**
\brief Clears this block array but does not release the memory.
*/
void clear_NoDelete()
{
currentBlock = 0;
blocks[0].count = 0;
}
/**
\brief Push a new element onto the back of the block array
\return The new element
*/
T& pushBack()
{
PxU32 numBlocks = blocks.size();
if (blocks[currentBlock].count == BLOCK_SIZE)
{
if((currentBlock + 1) == numBlocks)
{
blocks.pushBack(BlockInfo(PX_NEW(Block), 0));
numBlocks ++;
}
currentBlock++;
blocks[currentBlock].count = 0;
}
const PxU32 count = blocks[currentBlock].count ++;
return blocks[currentBlock].block->items[count];
}
/**
\brief Pushes a new element onto the back of this array, intitializing it to match the data
\param data The data to initialize the new element to
\return The new element
*/
T& pushBack(T& data)
{
PxU32 numBlocks = blocks.size();
if (blocks[currentBlock].count == BLOCK_SIZE)
{
if((currentBlock + 1) == numBlocks)
{
blocks.pushBack(BlockInfo(PX_NEW(Block), 0));
numBlocks ++;
}
currentBlock++;
blocks[currentBlock].count = 0;
}
const PxU32 count = blocks[currentBlock].count ++;
blocks[currentBlock].block->items[count] = data;
return blocks[currentBlock].block->items[count];
}
/**
\brief Pops the last element from the list.
*/
void popBack()
{
PX_ASSERT(blocks[currentBlock].count > 0);
if (blocks[currentBlock].count > 1)
blocks[currentBlock].count --;
else
{
PX_DELETE(blocks[currentBlock].block);
blocks.popBack();
currentBlock--;
}
}
/**
\brief Returns the current size of the array.
\return The current size of the array.
*/
PxU32 size() const
{
return (currentBlock)*BLOCK_SIZE + blocks[currentBlock].count;
}
/**
\brief Returns the element at a given index in the array
\param[in] index The index of the element in the array
\return The element at a given index in the array.
*/
T& operator[] (PxU32 index) const
{
PX_ASSERT(index/BLOCK_SIZE < blocks.size());
PX_ASSERT(index%BLOCK_SIZE < blocks[index/BLOCK_SIZE].count);
return blocks[index/BLOCK_SIZE].block->items[index%BLOCK_SIZE];
}
};
/**
\brief A structure to represent a potential CCD interaction between a pair of shapes
*/
struct PxsCCDPair
{
/**
\brief Defines whether this is an estimated TOI or an accurate TOI.
We store pairs in a priority queue based on the TOIs. We use cheap estimates to cull away work and lazily evaluate TOIs. This means that an element in the
priority queue may either be an estimate or a precise result.
*/
enum E_TOIType
{
eEstimate,
ePrecise
};
PxsRigidBody* mBa0; // Body A. Can be NULL for statics
PxsRigidBody* mBa1; // Body B. Can be NULL for statics
PxsCCDShape* mCCDShape0; // Shape A
PxsCCDShape* mCCDShape1; // Shape B
PxVec3 mMinToiNormal; // The contact normal. Only valid for precise results. On the surface of body/shape A
PxReal mMinToi; // Min TOI. Valid for both precise and estimated results but estimates may be too early (i.e. conservative).
PxReal mPenetrationPostStep; // Valid only for precise sweeps. Only used for initial intersections (i.e. at TOI = 0).
PxVec3 mMinToiPoint; // The contact point. Only valid for precise sweep results.
PxReal mPenetration; // The penetration. Only valid for precise sweep results.
PxsContactManager* mCm; // The contact manager.
PxU32 mIslandId; // The index of the island this pair is in
PxGeometryType::Enum mG0, mG1; // The geometry types for shapes 0 and 1
bool mIsEarliestToiHit; // Indicates this was the earliest hit for one of the bodies in the pair
bool mIsModifiable; // Indicates whether this contact is modifiable
PxU32 mFaceIndex; // The face index. Only valid for precise sweeps involving meshes or heightfields.
PxU16 mMaterialIndex0; // The material index for shape 0
PxU16 mMaterialIndex1; // The material index for shape 1
PxReal mDynamicFriction; // The dynamic friction coefficient
PxReal mStaticFriction; // The static friction coefficient
PxReal mRestitution; // The restitution coefficient
PxU32 mEstimatePass; // The current estimation pass. Used after a sweep hit was found to determine if the pair needs re-estimating.
PxReal mAppliedForce; // The applied force for this pair. Only valid if the pair has been responded to.
PxReal mMaxImpulse; // The maximum impulse to be applied
E_TOIType mToiType; // The TOI type (estimate, precise).
bool mHasFriction; // Whether we want to simulate CCD friction for this pair
/**
\brief Perform a precise sweep for this pair
\param[in] threadContext The per-thread context
\param[in] dt The time-step
\param[in] pass The current CCD pass
\return The normalized TOI. <=1.0 indicates a hit. Otherwise PX_MAX_REAL.
*/
PxReal sweepFindToi(PxcNpThreadContext& threadContext, PxReal dt, PxU32 pass, PxReal ccdThreshold);
/**
\brief Performs a sweep estimation for this pair
\return The normalized TOI. <= 1.0 indicates a potential hit, otherwise PX_MAX_REAL.
*/
PxReal sweepEstimateToi(PxReal ccdThreshold);
/**
\brief Advances this pair to the TOI
\param[in] dt The time-step
\param[in] clipTrajectoryToToi Indicates whether we clip the body's trajectory to the end pose. Only done in the final pass
\return Whether the advance was successful. An advance will be unsuccessful if body bodies were already updated.
*/
bool sweepAdvanceToToi(PxReal dt, bool clipTrajectoryToToi);
/**
\brief Updates the transforms of the shapes involved in this pair.
*/
void updateShapes();
};
/**
\brief Block array of CCD bodies
*/
typedef PxsCCDBlockArray<PxsCCDBody, 128> PxsCCDBodyArray;
/**
\brief Block array of CCD pairs
*/
typedef PxsCCDBlockArray<PxsCCDPair, 128> PxsCCDPairArray;
/**
\brief Block array of CCD overlaps
*/
typedef PxsCCDBlockArray<PxsCCDOverlap, 128> PxsCCDOverlapArray;
/**
\brief Block array of CCD shapes
*/
typedef PxsCCDBlockArray<PxsCCDShape, 128> PxsCCDShapeArray;
/**
\brief Pair structure to be able to look-up a rigid body-shape pair in a map
*/
typedef PxPair<const PxsRigidCore*, const PxsShapeCore*> PxsRigidShapePair;
/**
\brief CCD context object.
*/
class PxsCCDContext : public PxUserAllocated
{
public:
/**
\brief Constructor for PxsCCDContext
\param[in] context The PxsContext that is associated with this PxsCCDContext.
*/
PxsCCDContext(PxsContext* context, Dy::ThresholdStream& thresholdStream, PxvNphaseImplementationContext& nPhaseContext, PxReal ccdThreshold);
/**
\brief Destructor for PxsCCDContext
*/
~PxsCCDContext();
/**
\brief Returns the CCD contact modification callback
\return The CCD contact modification callback
*/
PX_FORCE_INLINE PxCCDContactModifyCallback* getCCDContactModifyCallback() const { return mCCDContactModifyCallback; }
/**
\brief Sets the CCD contact modification callback
\param[in] c The CCD contact modification callback
*/
PX_FORCE_INLINE void setCCDContactModifyCallback(PxCCDContactModifyCallback* c) { mCCDContactModifyCallback = c; }
/**
\brief Returns the maximum number of CCD passes
\return The maximum number of CCD passes
*/
PX_FORCE_INLINE PxU32 getCCDMaxPasses() const { return mCCDMaxPasses; }
/**
\brief Sets the maximum number of CCD passes
\param[in] ccdMaxPasses The maximum number of CCD passes
*/
PX_FORCE_INLINE void setCCDMaxPasses(PxU32 ccdMaxPasses) { mCCDMaxPasses = ccdMaxPasses; }
/**
\brief Returns the current CCD pass
\return The current CCD pass
*/
PX_FORCE_INLINE PxU32 getCurrentCCDPass() const { return miCCDPass; }
/**
\brief Returns The number of swept hits reported
\return The number of swept hits reported
*/
PX_FORCE_INLINE PxI32 getNumSweepHits() const { return mSweepTotalHits; }
/**
\brief Returns The number of updated bodies
\return The number of updated bodies in this CCD pass
*/
PX_FORCE_INLINE PxU32 getNumUpdatedBodies() const { return mUpdatedCCDBodies.size(); }
/**
\brief Returns The update bodies array
\return The updated bodies array from this CCD pass
*/
PX_FORCE_INLINE PxsRigidBody*const* getUpdatedBodies() const { return mUpdatedCCDBodies.begin(); }
/**
\brief Returns Clears the updated bodies array
*/
PX_FORCE_INLINE void clearUpdatedBodies() { mUpdatedCCDBodies.forceSize_Unsafe(0); }
PX_FORCE_INLINE PxReal getCCDThreshold() const { return mCCDThreshold; }
PX_FORCE_INLINE void setCCDThreshold(PxReal t) { mCCDThreshold = t; }
/**
\brief Runs the CCD contact modification.
\param[in] contacts The list of modifiable contacts
\param[in] contactCount The number of contacts
\param[in] shapeCore0 The first shape core
\param[in] shapeCore1 The second shape core
\param[in] rigidCore0 The first rigid core
\param[in] rigidCore1 The second rigid core
\param[in] rigid0 The first rigid body
\param[in] rigid1 The second rigid body
*/
void runCCDModifiableContact(PxModifiableContact* PX_RESTRICT contacts, PxU32 contactCount, const PxsShapeCore* PX_RESTRICT shapeCore0,
const PxsShapeCore* PX_RESTRICT shapeCore1, const PxsRigidCore* PX_RESTRICT rigidCore0, const PxsRigidCore* PX_RESTRICT rigidCore1,
const PxsRigidBody* PX_RESTRICT rigid0, const PxsRigidBody* PX_RESTRICT rigid1);
/**
\brief Performs a single CCD update
This occurs after broad phase and is responsible for creating islands, finding the TOI of collisions, filtering contacts, issuing modification callbacks and responding to
collisions. At the end of this phase all bodies will have stepper to their first TOI if they were involved in a CCD collision this frame.
\param[in] dt The timestep to simulate
\param[in] continuation The continuation task
\param[in] islandSim The island manager
\param[in] disableResweep If this is true, we perform a reduced-fidelity CCD approach
*/
void updateCCD(PxReal dt, PxBaseTask* continuation, IG::IslandSim& islandSim, bool disableResweep, PxI32 numFastMovingShapes);
/**
\brief Signals the beginning of a CCD multi-pass update
*/
void updateCCDBegin();
/**
\brief Resets the CCD contact state in any contact managers that previously had a reported CCD touch. This must be called if CCD update is bypassed for a frame
*/
void resetContactManagers();
private:
/**
\brief Verifies the consistency of the CCD context at the beginning
*/
void verifyCCDBegin();
/**
\brief Cleans up after the CCD update has completed
*/
void updateCCDEnd();
/**
\brief Spawns the update island tasks after the initial sweep estimates have been performed
\param[in] continuation The continuation task
*/
void postCCDSweep(PxBaseTask* continuation);
/**
\brief Creates contact buffers for CCD contacts. These will be sent to the user in the contact notification.
\param[in] continuation The continuation task
*/
void postCCDAdvance(PxBaseTask* continuation);
/**
\brief The final phase of the CCD task chain. Cleans up after the parallel update/postCCDAdvance stages.
\param[in] continuation The continuation task
*/
void postCCDDepenetrate(PxBaseTask* continuation);
typedef Cm::DelegateTask<PxsCCDContext, &PxsCCDContext::postCCDSweep> PostCCDSweepTask;
typedef Cm::DelegateTask<PxsCCDContext, &PxsCCDContext::postCCDAdvance> PostCCDAdvanceTask;
typedef Cm::DelegateTask<PxsCCDContext, &PxsCCDContext::postCCDDepenetrate> PostCCDDepenetrateTask;
PostCCDSweepTask mPostCCDSweepTask;
PostCCDAdvanceTask mPostCCDAdvanceTask;
PostCCDDepenetrateTask mPostCCDDepenetrateTask;
PxCCDContactModifyCallback* mCCDContactModifyCallback;
// CCD global data
bool mDisableCCDResweep;
PxU32 miCCDPass;
PxI32 mSweepTotalHits;
// a fraction of objects will be CCD active so PxsCCDBody is dynamic, not a member of PxsRigidBody
PxsCCDBodyArray mCCDBodies;
PxsCCDOverlapArray mCCDOverlaps;
PxsCCDShapeArray mCCDShapes;
PxArray<PxsCCDBody*> mIslandBodies;
PxArray<PxU16> mIslandSizes;
PxArray<PxsRigidBody*> mUpdatedCCDBodies;
PxHashMap<PxsRigidShapePair, PxsCCDShape*> mMap;
// temporary array updated during CCD update
//Array<PxsCCDPair> mCCDPairs;
PxsCCDPairArray mCCDPairs;
PxArray<PxsCCDPair*> mCCDPtrPairs;
// number of pairs per island
PxArray<PxU32> mCCDIslandHistogram;
// thread context valid during CCD update
PxcNpThreadContext* mCCDThreadContext;
// number of pairs to process per thread
PxU32 mCCDPairsPerBatch;
PxU32 mCCDMaxPasses;
PxsContext* mContext;
Dy::ThresholdStream& mThresholdStream;
PxvNphaseImplementationContext& mNphaseContext;
PxMutex mMutex;
PxReal mCCDThreshold;
private:
PX_NOCOPY(PxsCCDContext)
};
}
#endif
| 19,923 | C | 32.826825 | 172 | 0.730613 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsKernelWrangler.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_KERNEL_WRANGLER_H
#define PXS_KERNEL_WRANGLER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
class PxCudaContextManager;
class KernelWrangler;
class PxErrorCallback;
class PxsKernelWranglerManager : public PxUserAllocated
{
public:
virtual ~PxsKernelWranglerManager(){}
virtual KernelWrangler* getKernelWrangler() = 0;
virtual PxCudaContextManager* getCudaContextManager() = 0;
};
}
#endif | 2,166 | C | 43.224489 | 74 | 0.771468 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsContactManagerState.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_CONTACT_MANAGER_STATE_H
#define PXS_CONTACT_MANAGER_STATE_H
#include "foundation/PxSimpleTypes.h"
namespace physx
{
struct PxsShapeCore;
/**
There is an implicit 1:1 mapping between PxgContactManagerInput and PxsContactManagerOutput. The structures are split because PxgNpContactManagerInput contains constant
data that is produced by the CPU code and PxgNpContactManagerOutput contains per-frame contact information produced by the NP.
There is also a 1:1 mapping between the PxgNpContactManager and PxsContactManager. This mapping is handled within the PxgNPhaseCore.
The previous contact states are implicitly cached in PxsContactManager and will be propagated to the solver. Friction correlation is also done implicitly using cached
information in PxsContactManager.
The NP will produce a list of pairs that found/lost patches for the solver along with updating the PxgNpContactManagerOutput for all pairs.
*/
struct PxsContactManagerStatusFlag
{
enum Enum
{
eHAS_NO_TOUCH = (1 << 0),
eHAS_TOUCH = (1 << 1),
//eHAS_SOLVER_CONSTRAINTS = (1 << 2),
eREQUEST_CONSTRAINTS = (1 << 3),
eHAS_CCD_RETOUCH = (1 << 4), // Marks pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// but we can not tell whether they lost contact in a pass before. We send them as pure eNOTIFY_TOUCH_CCD events to the
// contact report callback if requested.
eDIRTY_MANAGER = (1 << 5),
eTOUCH_KNOWN = eHAS_NO_TOUCH | eHAS_TOUCH, // The touch status is known (if narrowphase never ran for a pair then no flag will be set)
eSTATIC_OR_KINEMATIC = (1 << 6)
};
};
struct PX_ALIGN_PREFIX(16) PxsContactManagerOutput
{
PxU8* contactPatches; //Start index/ptr for contact patches
PxU8* contactPoints; //Start index/ptr for contact points
PxReal* contactForces; //Start index/ptr for contact forces
PxU8 allflagsStart; //padding for compatibility with existing code
PxU8 nbPatches; //Num patches
PxU8 statusFlag; //Status flag (has touch etc.)
PxU8 prevPatches; //Previous number of patches
PxU16 nbContacts; //Num contacts
PxU16 flags; //Not really part of outputs, but we have 4 bytes of padding, so why not?
PX_FORCE_INLINE PxU32* getInternalFaceIndice()
{
return reinterpret_cast<PxU32*>(contactForces + nbContacts);
}
}
PX_ALIGN_SUFFIX(16);
struct PX_ALIGN_PREFIX(4) PxsContactManagerOutputCounts
{
PxU8 nbPatches; //Num patches
PxU8 prevPatches; //Previous number of patches
PxU8 statusFlag; //Status flag;
PxU8 unused; //Unused
} PX_ALIGN_SUFFIX(4);
struct PX_ALIGN_PREFIX(8) PxsTorsionalFrictionData
{
PxReal mTorsionalPatchRadius;
PxReal mMinTorsionalRadius;
PxsTorsionalFrictionData() {}
PxsTorsionalFrictionData(const PxReal patchRadius, const PxReal minPatchRadius) :
mTorsionalPatchRadius(patchRadius), mMinTorsionalRadius(minPatchRadius) {}
} PX_ALIGN_SUFFIX(8);
}
#endif //PXG_CONTACT_MANAGER_H
| 4,761 | C | 43.092592 | 169 | 0.744802 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsNphaseCommon.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_NPHASE_COMMON_H
#define PXS_NPHASE_COMMON_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxAssert.h"
namespace physx
{
struct PxsContactManagerBase
{
static const PxU32 NEW_CONTACT_MANAGER_MASK = 0x80000000;
static const PxU32 MaxBucketBits = 7;
const PxU32 mBucketId;
PxsContactManagerBase(const PxU32 bucketId) : mBucketId(bucketId)
{
PX_ASSERT(bucketId < (1 << MaxBucketBits));
}
PX_FORCE_INLINE PxU32 computeId(const PxU32 index) const { PX_ASSERT(index < PxU32(1 << (32 - (MaxBucketBits - 1)))); return (index << MaxBucketBits) | (mBucketId); }
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 computeIndexFromId(const PxU32 id) { return id >> MaxBucketBits; }
static PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 computeBucketIndexFromId(const PxU32 id) { return id & ((1 << MaxBucketBits) - 1); }
private:
PX_NOCOPY(PxsContactManagerBase)
};
}
#endif
| 2,616 | C | 41.901639 | 168 | 0.751911 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsIslandSim.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_ISLAND_SIM_H
#define PXS_ISLAND_SIM_H
#include "foundation/PxAssert.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxArray.h"
#include "CmPriorityQueue.h"
#include "CmBlockArray.h"
#include "PxNodeIndex.h"
namespace physx
{
namespace Dy
{
struct Constraint;
class FeatherstoneArticulation;
#if PX_SUPPORT_GPU_PHYSX
class SoftBody;
class FEMCloth;
class ParticleSystem;
class HairSystem;
#endif
}
// PT: TODO: fw declaring an Sc class here is not good
namespace Sc
{
class ArticulationSim;
}
class PxsContactManager;
class PxsRigidBody;
struct PartitionEdge;
namespace IG
{
//This index is
#define IG_INVALID_ISLAND 0xFFFFFFFFu
#define IG_INVALID_EDGE 0xFFFFFFFFu
#define IG_INVALID_LINK 0xFFu
typedef PxU32 IslandId;
typedef PxU32 EdgeIndex;
typedef PxU32 EdgeInstanceIndex;
class IslandSim;
struct Edge
{
//Edge instances can be implicitly calculated based on this edge index, which is an offset into the array of edges.
//From that, the child edge index is simply the
//The constraint or contact referenced by this edge
enum EdgeType
{
eCONTACT_MANAGER,
eCONSTRAINT,
eSOFT_BODY_CONTACT,
eFEM_CLOTH_CONTACT,
ePARTICLE_SYSTEM_CONTACT,
eHAIR_SYSTEM_CONTACT,
eEDGE_TYPE_COUNT
};
enum EdgeState
{
eINSERTED =1<<0,
ePENDING_DESTROYED =1<<1,
eACTIVE =1<<2,
eIN_DIRTY_LIST =1<<3,
eDESTROYED =1<<4,
eREPORT_ONLY_DESTROY=1<<5,
eACTIVATING =1<<6
};
//NodeIndex mNode1, mNode2;
EdgeType mEdgeType;
PxU16 mEdgeState;
EdgeIndex mNextIslandEdge, mPrevIslandEdge;
PX_FORCE_INLINE void setInserted() { mEdgeState |= (eINSERTED); }
PX_FORCE_INLINE void clearInserted() { mEdgeState &= (~eINSERTED); }
PX_FORCE_INLINE void clearDestroyed() { mEdgeState &=(~eDESTROYED);}
PX_FORCE_INLINE void setPendingDestroyed() { mEdgeState |= ePENDING_DESTROYED; }
PX_FORCE_INLINE void clearPendingDestroyed() { mEdgeState &= (~ePENDING_DESTROYED); }
PX_FORCE_INLINE void activateEdge() { mEdgeState |= eACTIVE; }
PX_FORCE_INLINE void deactivateEdge() { mEdgeState &= (~eACTIVE); }
PX_FORCE_INLINE void markInDirtyList() { mEdgeState |= (eIN_DIRTY_LIST); }
PX_FORCE_INLINE void clearInDirtyList() { mEdgeState &= (~eIN_DIRTY_LIST); }
PX_FORCE_INLINE void setReportOnlyDestroy() { mEdgeState |= (eREPORT_ONLY_DESTROY); }
PX_FORCE_INLINE void clearReportOnlyDestroy() { mEdgeState &= (~eREPORT_ONLY_DESTROY); }
public:
Edge() : mEdgeType(Edge::eCONTACT_MANAGER), mEdgeState(eDESTROYED),
mNextIslandEdge(IG_INVALID_EDGE), mPrevIslandEdge(IG_INVALID_EDGE)
{
}
PX_FORCE_INLINE bool isInserted() const { return !!(mEdgeState & eINSERTED);}
PX_FORCE_INLINE bool isDestroyed() const { return !!(mEdgeState & eDESTROYED); }
PX_FORCE_INLINE bool isPendingDestroyed() const { return !!(mEdgeState & ePENDING_DESTROYED); }
PX_FORCE_INLINE bool isActive() const { return !!(mEdgeState & eACTIVE); }
PX_FORCE_INLINE bool isInDirtyList() const { return !!(mEdgeState & eIN_DIRTY_LIST); }
PX_FORCE_INLINE EdgeType getEdgeType() const { return mEdgeType; }
//PX_FORCE_INLINE const NodeIndex getIndex1() const { return mNode1; }
//PX_FORCE_INLINE const NodeIndex getIndex2() const { return mNode2; }
PX_FORCE_INLINE bool isReportOnlyDestroy() { return !!(mEdgeState & eREPORT_ONLY_DESTROY); }
};
struct EdgeInstance
{
EdgeInstanceIndex mNextEdge, mPrevEdge; //The next edge instance in this node's list of edge instances
EdgeInstance() : mNextEdge(IG_INVALID_EDGE), mPrevEdge(IG_INVALID_EDGE)
{
}
};
template<typename Handle>
class HandleManager
{
PxArray<Handle> mFreeHandles;
Handle mCurrentHandle;
public:
HandleManager() : mFreeHandles("FreeHandles"), mCurrentHandle(0)
{
}
~HandleManager(){}
Handle getHandle()
{
if(mFreeHandles.size())
{
Handle handle = mFreeHandles.popBack();
PX_ASSERT(isValidHandle(handle));
return handle;
}
return mCurrentHandle++;
}
bool isNotFreeHandle(Handle handle) const
{
for(PxU32 a = 0; a < mFreeHandles.size(); ++a)
{
if(mFreeHandles[a] == handle)
return false;
}
return true;
}
void freeHandle(Handle handle)
{
PX_ASSERT(isValidHandle(handle));
PX_ASSERT(isNotFreeHandle(handle));
if(handle == mCurrentHandle)
mCurrentHandle--;
else
mFreeHandles.pushBack(handle);
}
bool isValidHandle(Handle handle) const
{
return handle < mCurrentHandle;
}
PX_FORCE_INLINE PxU32 getTotalHandles() const { return mCurrentHandle; }
};
class Node
{
public:
enum NodeType
{
eRIGID_BODY_TYPE,
eARTICULATION_TYPE,
eSOFTBODY_TYPE,
eFEMCLOTH_TYPE,
ePARTICLESYSTEM_TYPE,
eHAIRSYSTEM_TYPE,
eTYPE_COUNT
};
enum State
{
eREADY_FOR_SLEEPING = 1u << 0, //! Ready to go to sleep
eACTIVE = 1u << 1, //! Active
eKINEMATIC = 1u << 2, //! Kinematic
eDELETED = 1u << 3, //! Is pending deletion
eDIRTY = 1u << 4, //! Is dirty (i.e. lost a connection)
eACTIVATING = 1u << 5, //! Is in the activating list
eDEACTIVATING = 1u << 6 //! It is being forced to deactivate this frame
};
EdgeInstanceIndex mFirstEdgeIndex;
PxU8 mFlags;
PxU8 mType;
PxU16 mStaticTouchCount;
//PxU32 mActiveNodeIndex; //! Look-up for this node in the active nodes list, activating list or deactivating list...
PxNodeIndex mNextNode, mPrevNode;
//A counter for the number of active references to this body. Whenever an edge is activated, this is incremented.
//Whenver an edge is deactivated, this is decremented. This is used for kinematic bodies to determine if they need
//to be in the active kinematics list
PxU32 mActiveRefCount;
//A node can correspond with either a rigid body or an articulation or softBody
union
{
PxsRigidBody* mRigidBody;
Dy::FeatherstoneArticulation* mLLArticulation;
#if PX_SUPPORT_GPU_PHYSX
Dy::SoftBody* mLLSoftBody;
Dy::FEMCloth* mLLFEMCloth;
Dy::ParticleSystem* mLLParticleSystem;
Dy::HairSystem* mLLHairSystem;
#endif
};
PX_FORCE_INLINE Node() : mFirstEdgeIndex(IG_INVALID_EDGE), mFlags(eDELETED), mType(eRIGID_BODY_TYPE),
mStaticTouchCount(0), mActiveRefCount(0), mRigidBody(NULL)
{
}
PX_FORCE_INLINE ~Node() {}
PX_FORCE_INLINE void reset()
{
mFirstEdgeIndex = IG_INVALID_EDGE;
mFlags = eDELETED;
mRigidBody = NULL;
mActiveRefCount = 0;
mStaticTouchCount = 0;
}
PX_FORCE_INLINE void setRigidBody(PxsRigidBody* body) { mRigidBody = body; }
PX_FORCE_INLINE PxsRigidBody* getRigidBody() const { return mRigidBody; }
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getArticulation() const { return mLLArticulation; }
#if PX_SUPPORT_GPU_PHYSX
PX_FORCE_INLINE Dy::SoftBody* getSoftBody() const { return mLLSoftBody; }
PX_FORCE_INLINE Dy::FEMCloth* getFEMCloth() const { return mLLFEMCloth; }
PX_FORCE_INLINE Dy::HairSystem* getHairSystem() const { return mLLHairSystem; }
#endif
PX_FORCE_INLINE void setActive() { mFlags |= eACTIVE; }
PX_FORCE_INLINE void clearActive() { mFlags &= ~eACTIVE; }
PX_FORCE_INLINE void setActivating() { mFlags |= eACTIVATING; }
PX_FORCE_INLINE void clearActivating() { mFlags &= ~eACTIVATING; }
PX_FORCE_INLINE void setDeactivating() { mFlags |= eDEACTIVATING; }
PX_FORCE_INLINE void clearDeactivating() { mFlags &= (~eDEACTIVATING); }
//Activates a body/node.
PX_FORCE_INLINE void setIsReadyForSleeping() { mFlags |= eREADY_FOR_SLEEPING; }
PX_FORCE_INLINE void clearIsReadyForSleeping() { mFlags &= (~eREADY_FOR_SLEEPING); }
PX_FORCE_INLINE void setIsDeleted() { mFlags |= eDELETED; }
PX_FORCE_INLINE void setKinematicFlag() { PX_ASSERT(!isKinematic()); mFlags |= eKINEMATIC; }
PX_FORCE_INLINE void clearKinematicFlag() { PX_ASSERT(isKinematic()); mFlags &= (~eKINEMATIC); }
PX_FORCE_INLINE void markDirty() { mFlags |= eDIRTY; }
PX_FORCE_INLINE void clearDirty() { mFlags &= (~eDIRTY); }
public:
PX_FORCE_INLINE bool isActive() const { return !!(mFlags & eACTIVE); }
PX_FORCE_INLINE bool isActiveOrActivating() const { return !!(mFlags & (eACTIVE | eACTIVATING)); }
PX_FORCE_INLINE bool isActivating() const { return !!(mFlags & eACTIVATING); }
PX_FORCE_INLINE bool isDeactivating() const { return !!(mFlags & eDEACTIVATING); }
PX_FORCE_INLINE bool isKinematic() const { return !!(mFlags & eKINEMATIC); }
PX_FORCE_INLINE bool isDeleted() const { return !!(mFlags & eDELETED); }
PX_FORCE_INLINE bool isDirty() const { return !!(mFlags & eDIRTY); }
PX_FORCE_INLINE bool isReadyForSleeping() const { return !!(mFlags & eREADY_FOR_SLEEPING); }
PX_FORCE_INLINE NodeType getNodeType() const { return NodeType(mType); }
friend class SimpleIslandManager;
};
struct Island
{
PxNodeIndex mRootNode;
PxNodeIndex mLastNode;
PxU32 mNodeCount[Node::eTYPE_COUNT];
PxU32 mActiveIndex;
EdgeIndex mFirstEdge[Edge::eEDGE_TYPE_COUNT], mLastEdge[Edge::eEDGE_TYPE_COUNT];
PxU32 mEdgeCount[Edge::eEDGE_TYPE_COUNT];
Island() : mActiveIndex(IG_INVALID_ISLAND)
{
for(PxU32 a = 0; a < Edge::eEDGE_TYPE_COUNT; ++a)
{
mFirstEdge[a] = IG_INVALID_EDGE;
mLastEdge[a] = IG_INVALID_EDGE;
mEdgeCount[a] = 0;
}
for(PxU32 a = 0; a < Node::eTYPE_COUNT; ++a)
{
mNodeCount[a] = 0;
}
}
};
struct TraversalState
{
PxNodeIndex mNodeIndex;
PxU32 mCurrentIndex;
PxU32 mPrevIndex;
PxU32 mDepth;
TraversalState()
{
}
TraversalState(PxNodeIndex nodeIndex, PxU32 currentIndex, PxU32 prevIndex, PxU32 depth) :
mNodeIndex(nodeIndex), mCurrentIndex(currentIndex), mPrevIndex(prevIndex), mDepth(depth)
{
}
};
struct QueueElement
{
TraversalState* mState;
PxU32 mHopCount;
QueueElement()
{
}
QueueElement(TraversalState* state, PxU32 hopCount) : mState(state), mHopCount(hopCount)
{
}
};
struct NodeComparator
{
NodeComparator()
{
}
bool operator() (const QueueElement& node0, const QueueElement& node1) const
{
return node0.mHopCount < node1.mHopCount;
}
private:
NodeComparator& operator = (const NodeComparator&);
};
class IslandSim
{
PX_NOCOPY(IslandSim)
HandleManager<IslandId> mIslandHandles; //! Handle manager for islands
PxArray<Node> mNodes; //! The nodes used in the constraint graph
PxArray<PxU32> mActiveNodeIndex; //! The active node index for each node
Cm::BlockArray<Edge> mEdges;
Cm::BlockArray<EdgeInstance> mEdgeInstances; //! Edges used to connect nodes in the constraint graph
PxArray<Island> mIslands; //! The array of islands
PxArray<PxU32> mIslandStaticTouchCount; //! Array of static touch counts per-island
PxArray<PxNodeIndex> mActiveNodes[Node::eTYPE_COUNT]; //! An array of active nodes
PxArray<PxNodeIndex> mActiveKinematicNodes; //! An array of active or referenced kinematic nodes
PxArray<EdgeIndex> mActivatedEdges[Edge::eEDGE_TYPE_COUNT]; //! An array of active edges
PxU32 mActiveEdgeCount[Edge::eEDGE_TYPE_COUNT];
PxArray<PxU32> mHopCounts; //! The observed number of "hops" from a given node to its root node. May be inaccurate but used to accelerate searches.
PxArray<PxNodeIndex> mFastRoute; //! The observed last route from a given node to the root node. We try the fast route (unless its broken) before trying others.
PxArray<IslandId> mIslandIds; //! The array of per-node island ids
PxBitMap mIslandAwake; //! Indicates whether an island is awake or not
PxBitMap mActiveContactEdges;
//An array of active islands
PxArray<IslandId> mActiveIslands;
PxU32 mInitialActiveNodeCount[Edge::eEDGE_TYPE_COUNT];
PxArray<PxNodeIndex> mNodesToPutToSleep[Node::eTYPE_COUNT];
//Input to this frame's island management (changed nodes/edges)
//Input list of changes observed this frame. If there no changes, no work to be done.
PxArray<EdgeIndex> mDirtyEdges[Edge::eEDGE_TYPE_COUNT];
//Dirty nodes. These nodes lost at least one connection so we need to recompute islands from these nodes
//PxArray<NodeIndex> mDirtyNodes;
PxBitMap mDirtyMap;
PxU32 mLastMapIndex;
//An array of nodes to activate
PxArray<PxNodeIndex> mActivatingNodes;
PxArray<EdgeIndex> mDestroyedEdges;
PxArray<IslandId> mTempIslandIds;
//Temporary, transient data used for traversals. TODO - move to PxsSimpleIslandManager. Or if we keep it here, we can
//process multiple island simulations in parallel
Cm::PriorityQueue<QueueElement, NodeComparator> mPriorityQueue; //! Priority queue used for graph traversal
PxArray<TraversalState> mVisitedNodes; //! The list of nodes visited in the current traversal
PxBitMap mVisitedState; //! Indicates whether a node has been visited
PxArray<EdgeIndex> mIslandSplitEdges[Edge::eEDGE_TYPE_COUNT];
PxArray<EdgeIndex> mDeactivatingEdges[Edge::eEDGE_TYPE_COUNT];
PxArray<PartitionEdge*>* mFirstPartitionEdges;
Cm::BlockArray<PxNodeIndex>& mEdgeNodeIndices;
PxArray<physx::PartitionEdge*>* mDestroyedPartitionEdges;
PxU32* mNpIndexPtr;
const PxU64 mContextId;
public:
IslandSim(PxArray<PartitionEdge*>* firstPartitionEdges, Cm::BlockArray<PxNodeIndex>& edgeNodeIndices, PxArray<PartitionEdge*>* destroyedPartitionEdges, PxU64 contextID);
~IslandSim() {}
//void resize(const PxU32 nbNodes, const PxU32 nbContactManagers, const PxU32 nbConstraints);
void addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive, PxNodeIndex nodeIndex);
void addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive, PxNodeIndex nodeIndex);
#if PX_SUPPORT_GPU_PHYSX
void addSoftBody(Dy::SoftBody* llArtic, bool isActive, PxNodeIndex nodeIndex);
void addFEMCloth(Dy::FEMCloth* llArtic, bool isActive, PxNodeIndex nodeIndex);
void addParticleSystem(Dy::ParticleSystem* llArtic, bool isActive, PxNodeIndex nodeIndex);
void addHairSystem(Dy::HairSystem* llHairSystem, bool isActive, PxNodeIndex nodeIndex);
#endif
//void addContactManager(PxsContactManager* manager, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle);
void addConstraint(Dy::Constraint* constraint, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, EdgeIndex handle);
void activateNode(PxNodeIndex index);
void deactivateNode(PxNodeIndex index);
void putNodeToSleep(PxNodeIndex index);
void removeConnection(EdgeIndex edgeIndex);
PX_FORCE_INLINE PxU32 getNbNodes() const { return mNodes.size(); }
PX_FORCE_INLINE PxU32 getNbActiveNodes(Node::NodeType type) const { return mActiveNodes[type].size(); }
PX_FORCE_INLINE const PxNodeIndex* getActiveNodes(Node::NodeType type) const { return mActiveNodes[type].begin(); }
PX_FORCE_INLINE PxU32 getNbActiveKinematics() const { return mActiveKinematicNodes.size(); }
PX_FORCE_INLINE const PxNodeIndex* getActiveKinematics() const { return mActiveKinematicNodes.begin(); }
PX_FORCE_INLINE PxU32 getNbNodesToActivate(Node::NodeType type) const { return mActiveNodes[type].size() - mInitialActiveNodeCount[type]; }
PX_FORCE_INLINE const PxNodeIndex* getNodesToActivate(Node::NodeType type) const { return mActiveNodes[type].begin() + mInitialActiveNodeCount[type]; }
PX_FORCE_INLINE PxU32 getNbNodesToDeactivate(Node::NodeType type) const { return mNodesToPutToSleep[type].size(); }
PX_FORCE_INLINE const PxNodeIndex* getNodesToDeactivate(Node::NodeType type) const { return mNodesToPutToSleep[type].begin(); }
PX_FORCE_INLINE PxU32 getNbActivatedEdges(Edge::EdgeType type) const { return mActivatedEdges[type].size(); }
PX_FORCE_INLINE const EdgeIndex* getActivatedEdges(Edge::EdgeType type) const { return mActivatedEdges[type].begin(); }
PX_FORCE_INLINE PxU32 getNbActiveEdges(Edge::EdgeType type) const { return mActiveEdgeCount[type]; }
PX_FORCE_INLINE PartitionEdge* getFirstPartitionEdge(IG::EdgeIndex edgeIndex) const { return (*mFirstPartitionEdges)[edgeIndex]; }
PX_FORCE_INLINE void setFirstPartitionEdge(IG::EdgeIndex edgeIndex, PartitionEdge* partitionEdge) { (*mFirstPartitionEdges)[edgeIndex] = partitionEdge; }
//PX_FORCE_INLINE const EdgeIndex* getActiveEdges(Edge::EdgeType type) const { return mActiveEdges[type].begin(); }
PX_FORCE_INLINE PxsRigidBody* getRigidBody(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eRIGID_BODY_TYPE);
return node.mRigidBody;
}
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getLLArticulation(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eARTICULATION_TYPE);
return node.mLLArticulation;
}
// PT: this one is questionable here
Sc::ArticulationSim* getArticulationSim(PxNodeIndex nodeIndex) const;
#if PX_SUPPORT_GPU_PHYSX
PX_FORCE_INLINE Dy::SoftBody* getLLSoftBody(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eSOFTBODY_TYPE);
return node.mLLSoftBody;
}
PX_FORCE_INLINE Dy::FEMCloth* getLLFEMCloth(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eFEMCLOTH_TYPE);
return node.mLLFEMCloth;
}
PX_FORCE_INLINE Dy::HairSystem* getLLHairSystem(PxNodeIndex nodeIndex) const
{
const Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.mType == Node::eHAIRSYSTEM_TYPE);
return node.mLLHairSystem;
}
#endif
PX_FORCE_INLINE void clearDeactivations()
{
for (PxU32 i = 0; i < Node::eTYPE_COUNT; ++i)
{
mNodesToPutToSleep[i].forceSize_Unsafe(0);
mDeactivatingEdges[i].forceSize_Unsafe(0);
}
}
PX_FORCE_INLINE const Island& getIsland(IG::IslandId islandIndex) const { return mIslands[islandIndex]; }
PX_FORCE_INLINE PxU32 getNbActiveIslands() const { return mActiveIslands.size(); }
PX_FORCE_INLINE const IslandId* getActiveIslands() const { return mActiveIslands.begin(); }
PX_FORCE_INLINE PxU32 getNbDeactivatingEdges(const IG::Edge::EdgeType edgeType) const { return mDeactivatingEdges[edgeType].size(); }
PX_FORCE_INLINE const EdgeIndex* getDeactivatingEdges(const IG::Edge::EdgeType edgeType) const { return mDeactivatingEdges[edgeType].begin(); }
PX_FORCE_INLINE PxU32 getNbDestroyedEdges() const { return mDestroyedEdges.size(); }
PX_FORCE_INLINE const EdgeIndex* getDestroyedEdges() const { return mDestroyedEdges.begin(); }
PX_FORCE_INLINE PxU32 getNbDestroyedPartitionEdges() const { return mDestroyedPartitionEdges->size(); }
PX_FORCE_INLINE const PartitionEdge*const * getDestroyedPartitionEdges() const { return mDestroyedPartitionEdges->begin(); }
PX_FORCE_INLINE PartitionEdge** getDestroyedPartitionEdges() { return mDestroyedPartitionEdges->begin(); }
PX_FORCE_INLINE PxU32 getNbDirtyEdges(IG::Edge::EdgeType type) const { return mDirtyEdges[type].size(); }
PX_FORCE_INLINE const EdgeIndex* getDirtyEdges(IG::Edge::EdgeType type) const { return mDirtyEdges[type].begin(); }
PX_FORCE_INLINE const Edge& getEdge(const EdgeIndex edgeIndex) const { return mEdges[edgeIndex]; }
PX_FORCE_INLINE Edge& getEdge(const EdgeIndex edgeIndex) { return mEdges[edgeIndex]; }
PX_FORCE_INLINE const Node& getNode(const PxNodeIndex& nodeIndex) const { return mNodes[nodeIndex.index()]; }
PX_FORCE_INLINE const Island& getIsland(const PxNodeIndex& nodeIndex) const { PX_ASSERT(mIslandIds[nodeIndex.index()] != IG_INVALID_ISLAND); return mIslands[mIslandIds[nodeIndex.index()]]; }
PX_FORCE_INLINE PxU32 getIslandStaticTouchCount(const PxNodeIndex& nodeIndex) const { PX_ASSERT(mIslandIds[nodeIndex.index()] != IG_INVALID_ISLAND); return mIslandStaticTouchCount[mIslandIds[nodeIndex.index()]]; }
PX_FORCE_INLINE const PxBitMap& getActiveContactManagerBitmap() const { return mActiveContactEdges; }
PX_FORCE_INLINE PxU32 getActiveNodeIndex(const PxNodeIndex& nodeIndex) const { PxU32 activeNodeIndex = mActiveNodeIndex[nodeIndex.index()]; return activeNodeIndex;}
PX_FORCE_INLINE const PxU32* getActiveNodeIndex() const { return mActiveNodeIndex.begin(); }
PX_FORCE_INLINE PxU32 getNbActiveNodeIndex() const { return mActiveNodeIndex.size(); }
void setKinematic(PxNodeIndex nodeIndex);
void setDynamic(PxNodeIndex nodeIndex);
PX_FORCE_INLINE PxNodeIndex getNodeIndex1(IG::EdgeIndex index) const { return mEdgeNodeIndices[2 * index]; }
PX_FORCE_INLINE PxNodeIndex getNodeIndex2(IG::EdgeIndex index) const { return mEdgeNodeIndices[2 * index + 1]; }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextId; }
PxU32 getNbIslands() const { return mIslandStaticTouchCount.size(); }
const PxU32* getIslandStaticTouchCount() const { return mIslandStaticTouchCount.begin(); }
const PxU32* getIslandIds() const { return mIslandIds.begin(); }
bool checkInternalConsistency() const;
PX_INLINE void activateNode_ForGPUSolver(PxNodeIndex index)
{
IG::Node& node = mNodes[index.index()];
node.clearIsReadyForSleeping(); //Clear the "isReadyForSleeping" flag. Just in case it was set
node.clearDeactivating();
}
PX_INLINE void deactivateNode_ForGPUSolver(PxNodeIndex index)
{
IG::Node& node = mNodes[index.index()];
node.setIsReadyForSleeping();
}
// PT: these ones are strange, used to store an unrelated ptr from the outside, and only for GPU
// Why do we store that here? What happens on the CPU ?
PX_FORCE_INLINE void setEdgeNodeIndexPtr(PxU32* ptr) { mNpIndexPtr = ptr; }
PX_FORCE_INLINE PxU32* getEdgeNodeIndexPtr() const { return mNpIndexPtr; }
private:
void insertNewEdges();
void removeDestroyedEdges();
void wakeIslands();
void wakeIslands2();
void processNewEdges();
void processLostEdges(PxArray<PxNodeIndex>& destroyedNodes, bool allowDeactivation, bool permitKinematicDeactivation, PxU32 dirtyNodeLimit);
void removeConnectionInternal(EdgeIndex edgeIndex);
void addConnection(PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Edge::EdgeType edgeType, EdgeIndex handle);
void addConnectionToGraph(EdgeIndex index);
void removeConnectionFromGraph(EdgeIndex edgeIndex);
void connectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& source, PxNodeIndex destination);
void disconnectEdge(EdgeInstance& instance, EdgeInstanceIndex edgeIndex, Node& node);
//Merges 2 islands together. The returned id is the id of the merged island
IslandId mergeIslands(IslandId island0, IslandId island1, PxNodeIndex node0, PxNodeIndex node1);
void mergeIslandsInternal(Island& island0, Island& island1, IslandId islandId0, IslandId islandId1, PxNodeIndex node0, PxNodeIndex node1);
void unwindRoute(PxU32 traversalIndex, PxNodeIndex lastNode, PxU32 hopCount, IslandId id);
void activateIsland(IslandId island);
void deactivateIsland(IslandId island);
bool canFindRoot(PxNodeIndex startNode, PxNodeIndex targetNode, PxArray<PxNodeIndex>* visitedNodes);
bool tryFastPath(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId);
bool findRoute(PxNodeIndex startNode, PxNodeIndex targetNode, IslandId islandId);
bool isPathTo(PxNodeIndex startNode, PxNodeIndex targetNode) const;
void addNode(bool isActive, bool isKinematic, Node::NodeType type, PxNodeIndex nodeIndex);
void activateNodeInternal(PxNodeIndex index);
void deactivateNodeInternal(PxNodeIndex index);
/* PX_FORCE_INLINE void notifyReadyForSleeping(const PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
//PX_ASSERT(node.isActive());
node.setIsReadyForSleeping();
}
PX_FORCE_INLINE void notifyNotReadyForSleeping(const PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
PX_ASSERT(node.isActive() || node.isActivating());
node.clearIsReadyForSleeping();
}*/
PX_FORCE_INLINE void markIslandActive(IslandId islandId)
{
Island& island = mIslands[islandId];
PX_ASSERT(!mIslandAwake.test(islandId));
PX_ASSERT(island.mActiveIndex == IG_INVALID_ISLAND);
mIslandAwake.set(islandId);
island.mActiveIndex = mActiveIslands.size();
mActiveIslands.pushBack(islandId);
}
PX_FORCE_INLINE void markIslandInactive(IslandId islandId)
{
Island& island = mIslands[islandId];
PX_ASSERT(mIslandAwake.test(islandId));
PX_ASSERT(island.mActiveIndex != IG_INVALID_ISLAND);
PX_ASSERT(mActiveIslands[island.mActiveIndex] == islandId);
IslandId replaceId = mActiveIslands[mActiveIslands.size()-1];
PX_ASSERT(mIslandAwake.test(replaceId));
Island& replaceIsland = mIslands[replaceId];
replaceIsland.mActiveIndex = island.mActiveIndex;
mActiveIslands[island.mActiveIndex] = replaceId;
mActiveIslands.forceSize_Unsafe(mActiveIslands.size()-1);
island.mActiveIndex = IG_INVALID_ISLAND;
mIslandAwake.reset(islandId);
}
PX_FORCE_INLINE void markKinematicActive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(node.isKinematic());
if(node.mActiveRefCount == 0 && mActiveNodeIndex[index.index()] == PX_INVALID_NODE)
{
//PX_ASSERT(mActiveNodeIndex[index.index()] == PX_INVALID_NODE);
//node.mActiveNodeIndex = mActiveKinematicNodes.size();
mActiveNodeIndex[index.index()] = mActiveKinematicNodes.size();
PxNodeIndex nodeIndex;
nodeIndex = index;
mActiveKinematicNodes.pushBack(nodeIndex);
}
}
PX_FORCE_INLINE void markKinematicInactive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] != PX_INVALID_NODE);
PX_ASSERT(mActiveKinematicNodes[mActiveNodeIndex[index.index()]].index() == index.index());
if(node.mActiveRefCount == 0)
{
//Only remove from active kinematic list if it has no active contacts referencing it *and* it is asleep
if(mActiveNodeIndex[index.index()] != PX_INVALID_NODE)
{
//Need to verify active node index because there is an edge case where a node could be woken, then put to
//sleep in the same frame. This would mean that it would not have an active index at this stage.
PxNodeIndex replaceIndex = mActiveKinematicNodes.back();
PX_ASSERT(mActiveNodeIndex[replaceIndex.index()] == mActiveKinematicNodes.size()-1);
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[index.index()];
mActiveKinematicNodes[mActiveNodeIndex[index.index()]] = replaceIndex;
mActiveKinematicNodes.forceSize_Unsafe(mActiveKinematicNodes.size()-1);
mActiveNodeIndex[index.index()] = PX_INVALID_NODE;
}
}
}
PX_FORCE_INLINE void markActive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(!node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] == PX_INVALID_NODE);
mActiveNodeIndex[index.index()] = mActiveNodes[node.mType].size();
PxNodeIndex nodeIndex;
nodeIndex = index;
mActiveNodes[node.mType].pushBack(nodeIndex);
}
PX_FORCE_INLINE void markInactive(PxNodeIndex index)
{
Node& node = mNodes[index.index()];
PX_ASSERT(!node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] != PX_INVALID_NODE);
PxArray<PxNodeIndex>& activeNodes = mActiveNodes[node.mType];
PX_ASSERT(activeNodes[mActiveNodeIndex[index.index()]].index() == index.index());
const PxU32 initialActiveNodeCount = mInitialActiveNodeCount[node.mType];
if(mActiveNodeIndex[index.index()] < initialActiveNodeCount)
{
//It's in the initial active node set. We retain a list of active nodes, where the existing active nodes
//are at the beginning of the array and the newly activated nodes are at the end of the array...
//The solution is to move the node to the end of the initial active node list in this case
PxU32 activeNodeIndex = mActiveNodeIndex[index.index()];
PxNodeIndex replaceIndex = activeNodes[initialActiveNodeCount-1];
PX_ASSERT(mActiveNodeIndex[replaceIndex.index()] == initialActiveNodeCount-1);
mActiveNodeIndex[index.index()] = mActiveNodeIndex[replaceIndex.index()];
mActiveNodeIndex[replaceIndex.index()] = activeNodeIndex;
activeNodes[activeNodeIndex] = replaceIndex;
activeNodes[mActiveNodeIndex[index.index()]] = index;
mInitialActiveNodeCount[node.mType]--;
}
PX_ASSERT(!node.isKinematic());
PX_ASSERT(mActiveNodeIndex[index.index()] != PX_INVALID_NODE);
PX_ASSERT(activeNodes[mActiveNodeIndex[index.index()]].index() == index.index());
PxNodeIndex replaceIndex = activeNodes.back();
PX_ASSERT(mActiveNodeIndex[replaceIndex.index()] == activeNodes.size()-1);
mActiveNodeIndex[replaceIndex.index()] = mActiveNodeIndex[index.index()];
activeNodes[mActiveNodeIndex[index.index()]] = replaceIndex;
activeNodes.forceSize_Unsafe(activeNodes.size()-1);
mActiveNodeIndex[index.index()] = PX_INVALID_NODE;
}
PX_FORCE_INLINE void markEdgeActive(EdgeIndex index)
{
Edge& edge = mEdges[index];
PX_ASSERT((edge.mEdgeState & Edge::eACTIVATING) == 0);
edge.mEdgeState |= Edge::eACTIVATING;
mActivatedEdges[edge.mEdgeType].pushBack(index);
mActiveEdgeCount[edge.mEdgeType]++;
//Set the active bit...
if(edge.mEdgeType == Edge::eCONTACT_MANAGER)
mActiveContactEdges.set(index);
PxNodeIndex nodeIndex1 = mEdgeNodeIndices[2 * index];
PxNodeIndex nodeIndex2 = mEdgeNodeIndices[2 * index + 1];
if (nodeIndex1.index() != PX_INVALID_NODE && nodeIndex2.index() != PX_INVALID_NODE)
{
PX_ASSERT((!mNodes[nodeIndex1.index()].isKinematic()) || (!mNodes[nodeIndex2.index()].isKinematic()) || edge.getEdgeType() == IG::Edge::eCONTACT_MANAGER);
{
Node& node = mNodes[nodeIndex1.index()];
if(node.mActiveRefCount == 0 && node.isKinematic() && !(node.isActive() || node.isActivating()))
{
//Add to active kinematic list
markKinematicActive(nodeIndex1);
}
node.mActiveRefCount++;
}
{
Node& node = mNodes[nodeIndex2.index()];
if(node.mActiveRefCount == 0 && node.isKinematic() && !(node.isActive() || node.isActivating()))
{
//Add to active kinematic list
markKinematicActive(nodeIndex2);
}
node.mActiveRefCount++;
}
}
}
void removeEdgeFromActivatingList(EdgeIndex index);
PX_FORCE_INLINE void removeEdgeFromIsland(Island& island, EdgeIndex edgeIndex)
{
Edge& edge = mEdges[edgeIndex];
if(edge.mNextIslandEdge != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[edge.mNextIslandEdge].mPrevIslandEdge == edgeIndex);
mEdges[edge.mNextIslandEdge].mPrevIslandEdge = edge.mPrevIslandEdge;
}
else
{
PX_ASSERT(island.mLastEdge[edge.mEdgeType] == edgeIndex);
island.mLastEdge[edge.mEdgeType] = edge.mPrevIslandEdge;
}
if(edge.mPrevIslandEdge != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[edge.mPrevIslandEdge].mNextIslandEdge == edgeIndex);
mEdges[edge.mPrevIslandEdge].mNextIslandEdge = edge.mNextIslandEdge;
}
else
{
PX_ASSERT(island.mFirstEdge[edge.mEdgeType] == edgeIndex);
island.mFirstEdge[edge.mEdgeType] = edge.mNextIslandEdge;
}
island.mEdgeCount[edge.mEdgeType]--;
edge.mNextIslandEdge = edge.mPrevIslandEdge = IG_INVALID_EDGE;
}
PX_FORCE_INLINE void addEdgeToIsland(Island& island, EdgeIndex edgeIndex)
{
Edge& edge = mEdges[edgeIndex];
PX_ASSERT(edge.mNextIslandEdge == IG_INVALID_EDGE && edge.mPrevIslandEdge == IG_INVALID_EDGE);
if(island.mLastEdge[edge.mEdgeType] != IG_INVALID_EDGE)
{
PX_ASSERT(mEdges[island.mLastEdge[edge.mEdgeType]].mNextIslandEdge == IG_INVALID_EDGE);
mEdges[island.mLastEdge[edge.mEdgeType]].mNextIslandEdge = edgeIndex;
}
else
{
PX_ASSERT(island.mFirstEdge[edge.mEdgeType] == IG_INVALID_EDGE);
island.mFirstEdge[edge.mEdgeType] = edgeIndex;
}
edge.mPrevIslandEdge = island.mLastEdge[edge.mEdgeType];
island.mLastEdge[edge.mEdgeType] = edgeIndex;
island.mEdgeCount[edge.mEdgeType]++;
}
PX_FORCE_INLINE void removeNodeFromIsland(Island& island, PxNodeIndex nodeIndex)
{
Node& node = mNodes[nodeIndex.index()];
if(node.mNextNode.isValid())
{
PX_ASSERT(mNodes[node.mNextNode.index()].mPrevNode.index() == nodeIndex.index());
mNodes[node.mNextNode.index()].mPrevNode = node.mPrevNode;
}
else
{
PX_ASSERT(island.mLastNode.index() == nodeIndex.index());
island.mLastNode = node.mPrevNode;
}
if(node.mPrevNode.isValid())
{
PX_ASSERT(mNodes[node.mPrevNode.index()].mNextNode.index() == nodeIndex.index());
mNodes[node.mPrevNode.index()].mNextNode = node.mNextNode;
}
else
{
PX_ASSERT(island.mRootNode.index() == nodeIndex.index());
island.mRootNode = node.mNextNode;
}
island.mNodeCount[node.mType]--;
node.mNextNode = PxNodeIndex(); node.mPrevNode = PxNodeIndex();
}
//void setEdgeConnectedInternal(EdgeIndex edgeIndex);
//void setEdgeDisconnectedInternal(EdgeIndex edgeIndex);
friend class SimpleIslandManager;
friend class ThirdPassTask;
};
}
struct PartitionIndexData
{
PxU16 mPartitionIndex; //! The current partition this edge is in. Used to find the edge efficiently. PxU8 is probably too small (256 partitions max) but PxU16 should be more than enough
PxU8 mPatchIndex; //! The patch index for this partition edge. There may be multiple entries for a given edge if there are multiple patches.
PxU8 mCType; //! The type of constraint this is
PxU32 mPartitionEntryIndex; //! index of partition edges for this partition
};
struct PartitionNodeData
{
PxNodeIndex mNodeIndex0;
PxNodeIndex mNodeIndex1;
PxU32 mNextIndex0;
PxU32 mNextIndex1;
};
#define INVALID_PARTITION_INDEX 0xFFFF
struct PartitionEdge
{
IG::EdgeIndex mEdgeIndex; //! The edge index into the island manager. Used to identify the contact manager/constraint
PxNodeIndex mNode0; //! The node index for node 0. Can be obtained from the edge index alternatively
PxNodeIndex mNode1; //! The node idnex for node 1. Can be obtained from the edge index alternatively
bool mInfiniteMass0; //! Whether body 0 is kinematic
bool mArticulation0; //! Whether body 0 is an articulation link
bool mInfiniteMass1; //! Whether body 1 is kinematic
bool mArticulation1; //! Whether body 1 is an articulation link
PartitionEdge* mNextPatch; //! for the contact manager has more than 1 patch, we have next patch's edge and previous patch's edge to connect to this edge
PxU32 mUniqueIndex; //! a unique ID for this edge
//KS - This constructor explicitly does not set mUniqueIndex. It is filled in by the pool allocator and this constructor
//is called afterwards. We do not want to stomp the uniqueIndex value
PartitionEdge() : mEdgeIndex(IG_INVALID_EDGE), mInfiniteMass0(false), mArticulation0(false),
mInfiniteMass1(false), mArticulation1(false), mNextPatch(NULL)//, mUniqueIndex(IG_INVALID_EDGE)
{
}
};
}
#endif
| 36,023 | C | 35.684318 | 214 | 0.739278 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsSimulationController.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_SIMULATION_CONTROLLER_H
#define PXS_SIMULATION_CONTROLLER_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxPreprocessor.h"
#include "foundation/PxTransform.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxPinnedArray.h"
#include "foundation/PxUserAllocated.h"
#include "PxScene.h"
#include "PxParticleSystem.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFLIPParticleSystem.h"
#include "PxMPMParticleSystem.h"
// if these assert fail adjust the type here and in the forward declaration of the #else section just below
PX_COMPILE_TIME_ASSERT(sizeof(physx::PxMPMParticleDataFlag::Enum) == sizeof(physx::PxU32));
PX_COMPILE_TIME_ASSERT(sizeof(physx::PxSparseGridDataFlag::Enum) == sizeof(physx::PxU32));
#else
namespace PxMPMParticleDataFlag { enum Enum : physx::PxU32; }
namespace PxSparseGridDataFlag { enum Enum : physx::PxU32; }
#endif
#include "PxParticleSolverType.h"
namespace physx
{
namespace Dy
{
class Context;
struct Constraint;
class FeatherstoneArticulation;
struct ArticulationJointCore;
class ParticleSystemCore;
class ParticleSystem;
#if PX_SUPPORT_GPU_PHYSX
class SoftBody;
class FEMCloth;
class HairSystem;
#endif
}
namespace Bp
{
class BoundsArray;
class BroadPhase;
class AABBManagerBase;
}
namespace IG
{
class SimpleIslandManager;
class IslandSim;
}
namespace Sc
{
class BodySim;
}
class PxNodeIndex;
class PxsTransformCache;
class PxvNphaseImplementationContext;
class PxBaseTask;
class PxsContext;
struct PxsShapeSim;
class PxsRigidBody;
class PxsKernelWranglerManager;
class PxsHeapMemoryAllocatorManager;
class PxgParticleSystemCore;
struct PxConeLimitedConstraint;
struct PxsShapeCore;
class PxPhysXGpu;
struct PxgSolverConstraintManagerConstants;
class PxsSimulationControllerCallback : public PxUserAllocated
{
public:
virtual void updateScBodyAndShapeSim(PxBaseTask* continuation) = 0;
virtual PxU32 getNbCcdBodies() = 0;
virtual ~PxsSimulationControllerCallback() {}
};
class PxsSimulationController : public PxUserAllocated
{
public:
PxsSimulationController(PxsSimulationControllerCallback* callback, PxIntBool gpu) : mCallback(callback), mGPU(gpu) {}
virtual ~PxsSimulationController(){}
virtual void addJoint(const PxU32 /*edgeIndex*/, Dy::Constraint* /*constraint*/, IG::IslandSim& /*islandSim*/, PxArray<PxU32>& /*jointIndices*/,
PxPinnedArray<PxgSolverConstraintManagerConstants>& /*managerIter*/, PxU32 /*uniqueId*/){}
virtual void removeJoint(const PxU32 /*edgeIndex*/, Dy::Constraint* /*constraint*/, PxArray<PxU32>& /*jointIndices*/, IG::IslandSim& /*islandSim*/){}
virtual void addShape(PxsShapeSim* /*shapeSim*/, const PxU32 /*index*/){}
virtual void reinsertShape(PxsShapeSim* /*shapeSim*/, const PxU32 /*index*/) {}
virtual void updateShape(PxsShapeSim& /*shapeSim*/, const PxNodeIndex& /*index*/) {}
virtual void removeShape(const PxU32 /*index*/){}
virtual void addDynamic(PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*nodeIndex*/){}
virtual void addDynamics(PxsRigidBody** /*rigidBody*/, const PxU32* /*nodeIndex*/, PxU32 /*nbBodies*/) {}
virtual void addArticulation(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseArticulation(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseDeferredArticulationIds() {}
#if PX_SUPPORT_GPU_PHYSX
virtual void addSoftBody(Dy::SoftBody* /*softBody*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseSoftBody(Dy::SoftBody* /*softBody*/) {}
virtual void releaseDeferredSoftBodyIds() {}
virtual void activateSoftbody(Dy::SoftBody*) {}
virtual void deactivateSoftbody(Dy::SoftBody*) {}
virtual void activateSoftbodySelfCollision(Dy::SoftBody*) {}
virtual void deactivateSoftbodySelfCollision(Dy::SoftBody*) {}
virtual void setSoftBodyWakeCounter(Dy::SoftBody*) {}
virtual void addParticleFilter(Dy::SoftBody* /*softBodySystem*/, Dy::ParticleSystem* /*particleSystem*/,
PxU32 /*particleId*/, PxU32 /*userBufferId*/, PxU32 /*tetId*/) {}
virtual void removeParticleFilter(Dy::SoftBody* /*softBodySystem*/,
const Dy::ParticleSystem* /*particleSystem*/, PxU32 /*particleId*/, PxU32 /*userBufferId*/, PxU32 /*tetId*/) {}
virtual PxU32 addParticleAttachment(Dy::SoftBody* /*softBodySystem*/, const Dy::ParticleSystem* /*particleSystem*/,
PxU32 /*particleId*/, PxU32 /*userBufferId*/, PxU32 /*tetId*/, const PxVec4& /*barycentrics*/, const bool /*isActive*/) { return 0; }
virtual void removeParticleAttachment(Dy::SoftBody* /*softBody*/, PxU32 /*handle*/) {}
virtual void addRigidFilter(Dy::SoftBody* /*softBodySystem*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/) {}
virtual void removeRigidFilter(Dy::SoftBody* /*softBodySystem*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/) {}
virtual PxU32 addRigidAttachment(Dy::SoftBody* /*softBodySystem*/, const PxNodeIndex& /*softBodyNodeIndex*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/, const PxVec3& /*actorSpacePose*/,
PxConeLimitedConstraint* /*constraint*/, const bool /*isActive*/) { return 0; }
virtual void removeRigidAttachment(Dy::SoftBody* /*softBody*/, PxU32 /*handle*/) {}
virtual void addTetRigidFilter(Dy::SoftBody* /*softBodySystem*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*tetId*/) {}
virtual PxU32 addTetRigidAttachment(Dy::SoftBody* /*softBodySystem*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*tetIdx*/,
const PxVec4& /*barycentrics*/, const PxVec3& /*actorSpacePose*/, PxConeLimitedConstraint* /*constraint*/,
const bool /*isActive*/) { return 0; }
virtual void removeTetRigidFilter(Dy::SoftBody* /*softBody*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*tetId*/) {}
virtual void addSoftBodyFilter(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32 /*tetIdx0*/,
PxU32 /*tetIdx1*/) {}
virtual void removeSoftBodyFilter(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32 /*tetIdx0*/,
PxU32 /*tetId1*/) {}
virtual void addSoftBodyFilters(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32* /*tetIndices0*/, PxU32* /*tetIndices1*/,
PxU32 /*tetIndicesSize*/) {}
virtual void removeSoftBodyFilters(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32* /*tetIndices0*/, PxU32* /*tetIndices1*/,
PxU32 /*tetIndicesSize*/) {}
virtual PxU32 addSoftBodyAttachment(Dy::SoftBody* /*softBody0*/, Dy::SoftBody* /*softBody1*/, PxU32 /*tetIdx0*/, PxU32 /*tetIdx1*/,
const PxVec4& /*tetBarycentric0*/, const PxVec4& /*tetBarycentric1*/,
PxConeLimitedConstraint* /*constraint*/, PxReal /*constraintOffset*/, const bool /*isActive*/) { return 0; }
virtual void removeSoftBodyAttachment(Dy::SoftBody* /*softBody0*/, PxU32 /*handle*/) {}
virtual void addClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*triIdx*/, PxU32 /*tetIdx*/) {}
virtual void removeClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*triIdx*/, PxU32 /*tetIdx*/) {}
virtual void addVertClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*vertIdx*/, PxU32 /*tetIdx*/) {}
virtual void removeVertClothFilter(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*vertIdx*/, PxU32 /*tetIdx*/) {}
virtual PxU32 addClothAttachment(Dy::SoftBody* /*softBody*/, Dy::FEMCloth* /*cloth*/, PxU32 /*triIdx*/,
const PxVec4& /*triBarycentric*/, PxU32 /*tetIdx*/, const PxVec4& /*tetBarycentric*/,
PxConeLimitedConstraint* /*constraint*/, PxReal /*constraintOffset*/,
const bool /*isActive*/) { return 0; }
virtual void removeClothAttachment(Dy::SoftBody* /*softBody*/,PxU32 /*handle*/) {}
virtual void addFEMCloth(Dy::FEMCloth* /*femCloth*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseFEMCloth(Dy::FEMCloth* /*femCloth*/) {}
virtual void releaseDeferredFEMClothIds() {}
virtual void activateCloth(Dy::FEMCloth* /*femCloth*/) {}
virtual void deactivateCloth(Dy::FEMCloth* /*femCloth*/) {}
virtual void setClothWakeCounter(Dy::FEMCloth*) {}
virtual void addRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertId*/) {}
virtual void removeRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertId*/) {}
virtual PxU32 addRigidAttachment(Dy::FEMCloth* /*cloth*/, const PxNodeIndex& /*clothNodeIndex*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*vertIndex*/, const PxVec3& /*actorSpacePose*/,
PxConeLimitedConstraint* /*constraint*/, const bool /*isActive*/) { return 0; }
virtual void removeRigidAttachment(Dy::FEMCloth* /*cloth*/, PxU32 /*handle*/) {}
virtual void addTriRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*triIdx*/) {}
virtual void removeTriRigidFilter(Dy::FEMCloth* /*cloth*/,
const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*triIdx*/) {}
virtual PxU32 addTriRigidAttachment(Dy::FEMCloth* /*cloth*/,
PxsRigidBody* /*rigidBody*/, const PxNodeIndex& /*rigidNodeIndex*/, PxU32 /*triIdx*/, const PxVec4& /*barycentrics*/,
const PxVec3& /*actorSpacePose*/, PxConeLimitedConstraint* /*constraint*/,
const bool /*isActive*/) { return 0; }
virtual void removeTriRigidAttachment(Dy::FEMCloth* /*cloth*/, PxU32 /*handle*/) {}
virtual void addClothFilter(Dy::FEMCloth* /*cloth0*/, Dy::FEMCloth* /*cloth1*/, PxU32 /*triIdx0*/, PxU32 /*triIdx1*/) {}
virtual void removeClothFilter(Dy::FEMCloth* /*cloth0*/, Dy::FEMCloth* /*cloth1*/, PxU32 /*triIdx0*/, PxU32 /*triIdx1*/) {}
virtual PxU32 addTriClothAttachment(Dy::FEMCloth* /*cloth0*/, Dy::FEMCloth* /*cloth1*/, PxU32 /*triIdx0*/, PxU32 /*triIdx1*/,
const PxVec4& /*triBarycentric0*/, const PxVec4& /*triBarycentric1*/, const bool /*addToActive*/) { return 0; }
virtual void removeTriClothAttachment(Dy::FEMCloth* /*cloth*/, PxU32 /*handle*/) {}
virtual void addParticleSystem(Dy::ParticleSystem* /*particleSystem*/, const PxNodeIndex& /*nodeIndex*/, PxParticleSolverType::Enum /*type*/) {}
virtual void releaseParticleSystem(Dy::ParticleSystem* /*particleSystem*/, PxParticleSolverType::Enum /*type*/) {}
virtual void releaseDeferredParticleSystemIds() {}
virtual void addHairSystem(Dy::HairSystem* /*hairSystem*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void releaseHairSystem(Dy::HairSystem* /*hairSystem*/) {}
virtual void releaseDeferredHairSystemIds() {}
virtual void activateHairSystem(Dy::HairSystem*) {}
virtual void deactivateHairSystem(Dy::HairSystem*) {}
virtual void setHairSystemWakeCounter(Dy::HairSystem*) {}
#endif
virtual void flush() {}
virtual void updateDynamic(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateJoint(const PxU32 /*edgeIndex*/, Dy::Constraint* /*constraint*/){}
virtual void updateBodies(PxsRigidBody** /*rigidBodies*/, PxU32* /*nodeIndices*/, const PxU32 /*nbBodies*/) {}
// virtual void updateBody(PxsRigidBody* /*rigidBody*/, const PxU32 /*nodeIndex*/) {}
virtual void updateBodies(PxBaseTask* /*continuation*/){}
virtual void updateShapes(PxBaseTask* /*continuation*/) {}
virtual void preIntegrateAndUpdateBound(PxBaseTask* /*continuation*/, const PxVec3 /*gravity*/, const PxReal /*dt*/){}
virtual void updateParticleSystemsAndSoftBodies(){}
virtual void sortContacts(){}
virtual void update(PxBitMapPinned& /*changedHandleMap*/){}
virtual void updateArticulation(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateArticulationJoint(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
// virtual void updateArticulationTendon(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateArticulationExtAccel(Dy::FeatherstoneArticulation* /*articulation*/, const PxNodeIndex& /*nodeIndex*/) {}
virtual void updateArticulationAfterIntegration(PxsContext* /*llContext*/, Bp::AABBManagerBase* /*aabbManager*/,
PxArray<Sc::BodySim*>& /*ccdBodies*/, PxBaseTask* /*continuation*/, IG::IslandSim& /*islandSim*/, float /*dt*/) {}
virtual void mergeChangedAABBMgHandle() {}
virtual void gpuDmabackData(PxsTransformCache& /*cache*/, Bp::BoundsArray& /*boundArray*/, PxBitMapPinned& /*changedAABBMgrHandles*/, bool /*enableDirectGPUAPI*/){}
virtual void updateScBodyAndShapeSim(PxsTransformCache& cache, Bp::BoundsArray& boundArray, PxBaseTask* continuation) = 0;
virtual PxU32* getActiveBodies() { return NULL; }
virtual PxU32* getDeactiveBodies() { return NULL; }
virtual void** getRigidBodies() { return NULL; }
virtual PxU32 getNbBodies() { return 0; }
virtual PxU32* getUnfrozenShapes() { return NULL; }
virtual PxU32* getFrozenShapes() { return NULL; }
virtual PxsShapeSim** getShapeSims() { return NULL; }
virtual PxU32 getNbFrozenShapes() { return 0; }
virtual PxU32 getNbUnfrozenShapes() { return 0; }
virtual PxU32 getNbShapes() { return 0; }
virtual void clear() { }
virtual void setBounds(Bp::BoundsArray* /*boundArray*/){}
virtual void reserve(const PxU32 /*nbBodies*/) {}
virtual PxU32 getArticulationRemapIndex(const PxU32 /*nodeIndex*/) { return PX_INVALID_U32;}
//virtual void setParticleSystemManager(PxgParticleSystemCore* psCore) = 0;
virtual void copyArticulationData(void* /*jointData*/, void* /*index*/, PxArticulationGpuDataType::Enum /*dataType*/, const PxU32 /*nbUpdatedArticulations*/, CUevent /*copyEvent*/) {}
virtual void applyArticulationData(void* /*data*/, void* /*index*/, PxArticulationGpuDataType::Enum /*dataType*/, const PxU32 /*nbUpdatedArticulations*/, CUevent /*waitEvent*/, CUevent /*signalEvent*/) {}
virtual void updateArticulationsKinematic(CUevent /*signalEvent*/) {}
//KS - the methods below here should probably be wrapped in if PX_SUPPORT_GPU_PHYSX
// PT: isn't the whole class only needed for GPU anyway?
virtual void copySoftBodyData(void** /*data*/, void* /*dataSizes*/, void* /*softBodyIndices*/, PxSoftBodyGpuDataFlag::Enum /*flag*/, const PxU32 /*nbCopySoftBodies*/, const PxU32 /*maxSize*/, CUevent /*copyEvent*/) {}
virtual void applySoftBodyData(void** /*data*/, void* /*dataSizes*/, void* /*softBodyIndices*/, PxSoftBodyGpuDataFlag::Enum /*flag*/, const PxU32 /*nbUpdatedSoftBodies*/, const PxU32 /*maxSize*/, CUevent /*applyEvent*/, CUevent /*signalEvent*/) {}
virtual void copyContactData(Dy::Context* /*dyContext*/, void* /*data*/, const PxU32 /*maxContactPairs*/, void* /*numContactPairs*/, CUevent /*copyEvent*/) {}
virtual void copyBodyData(PxGpuBodyData* /*data*/, PxGpuActorPair* /*index*/, const PxU32 /*nbCopyActors*/, CUevent /*copyEvent*/){}
virtual void applyActorData(void* /*data*/, PxGpuActorPair* /*index*/, PxActorCacheFlag::Enum /*flag*/, const PxU32 /*nbUpdatedActors*/, CUevent /*waitEvent*/, CUevent /*signalEvent*/) {}
virtual void evaluateSDFDistances(const PxU32* /*sdfShapeIds*/, const PxU32 /*nbShapes*/, const PxVec4* /*samplePointsConcatenated*/,
const PxU32* /*samplePointCountPerShape*/, const PxU32 /*maxPointCount*/, PxVec4* /*localGradientAndSDFConcatenated*/, CUevent /*event*/) {}
virtual PxU32 getInternalShapeIndex(const PxsShapeCore& /*shapeCore*/) { return PX_INVALID_U32; }
virtual void syncParticleData() {}
virtual void updateBoundsAndShapes(Bp::AABBManagerBase& /*aabbManager*/, bool /*useDirectApi*/){}
virtual void computeDenseJacobians(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, CUevent /*computeEvent*/){}
virtual void computeGeneralizedMassMatrices(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, CUevent /*computeEvent*/){}
virtual void computeGeneralizedGravityForces(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, const PxVec3& /*gravity*/, CUevent /*computeEvent*/){}
virtual void computeCoriolisAndCentrifugalForces(const PxIndexDataPair* /*indices*/, PxU32 /*nbIndices*/, CUevent /*computeEvent*/) {}
virtual void applyParticleBufferData(const PxU32* /*indices*/, const PxGpuParticleBufferIndexPair* /*indexPairs*/, const PxParticleBufferFlags* /*flags*/, PxU32 /*nbUpdatedBuffers*/, CUevent /*waitEvent*/, CUevent /*signalEvent*/) {}
#if PX_SUPPORT_GPU_PHYSX
virtual PxU32 getNbDeactivatedFEMCloth() const { return 0; }
virtual PxU32 getNbActivatedFEMCloth() const { return 0; }
virtual Dy::FEMCloth** getDeactivatedFEMCloths() const { return NULL; }
virtual Dy::FEMCloth** getActivatedFEMCloths() const { return NULL; }
virtual PxU32 getNbDeactivatedSoftbodies() const { return 0; }
virtual PxU32 getNbActivatedSoftbodies() const { return 0; }
virtual const PxReal* getSoftBodyWakeCounters() const { return NULL; }
virtual const PxReal* getHairSystemWakeCounters() const { return NULL; }
virtual Dy::SoftBody** getDeactivatedSoftbodies() const { return NULL; }
virtual Dy::SoftBody** getActivatedSoftbodies() const { return NULL; }
virtual bool hasFEMCloth() const { return false; }
virtual bool hasSoftBodies() const { return false; }
virtual PxU32 getNbDeactivatedHairSystems() const { return 0; }
virtual PxU32 getNbActivatedHairSystems() const { return 0; }
virtual Dy::HairSystem** getDeactivatedHairSystems() const { return NULL; }
virtual Dy::HairSystem** getActivatedHairSystems() const { return NULL; }
virtual bool hasHairSystems() const { return false; }
#endif
virtual void* getMPMDataPointer(const Dy::ParticleSystem& /*psLL*/, PxMPMParticleDataFlag::Enum /*flags*/) { return NULL; }
virtual void* getSparseGridDataPointer(const Dy::ParticleSystem& /*psLL*/, PxSparseGridDataFlag::Enum /*flags*/, PxParticleSolverType::Enum /*type*/) { return NULL; }
protected:
PxsSimulationControllerCallback* mCallback;
public:
const PxIntBool mGPU; // PT: true for GPU version, used to quickly skip calls for CPU version
};
}
#endif
| 19,873 | C | 53.900552 | 249 | 0.729583 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsHeapMemoryAllocator.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_HEAP_MEMORY_ALLOCATOR_H
#define PXS_HEAP_MEMORY_ALLOCATOR_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
struct PxsHeapStats
{
enum Enum
{
eOTHER = 0,
eBROADPHASE,
eNARROWPHASE,
eSOLVER,
eARTICULATION,
eSIMULATION,
eSIMULATION_ARTICULATION,
eSIMULATION_PARTICLES,
eSIMULATION_SOFTBODY,
eSIMULATION_FEMCLOTH,
eSIMULATION_HAIRSYSTEM,
eSHARED_PARTICLES,
eSHARED_SOFTBODY,
eSHARED_FEMCLOTH,
eSHARED_HAIRSYSTEM,
eHEAPSTATS_COUNT
};
PxU64 stats[eHEAPSTATS_COUNT];
PxsHeapStats()
{
for (PxU32 i = 0; i < eHEAPSTATS_COUNT; i++)
{
stats[i] = 0;
}
}
};
// PT: TODO: consider dropping this class
class PxsHeapMemoryAllocator : public PxVirtualAllocatorCallback, public PxUserAllocated
{
public:
virtual ~PxsHeapMemoryAllocator(){}
// PxVirtualAllocatorCallback
//virtual void* allocate(const size_t size, const int group, const char* file, const int line) = 0;
//virtual void deallocate(void* ptr) = 0;
//~PxVirtualAllocatorCallback
};
class PxsHeapMemoryAllocatorManager : public PxUserAllocated
{
public:
virtual ~PxsHeapMemoryAllocatorManager() {}
virtual PxU64 getDeviceMemorySize() const = 0;
virtual PxsHeapStats getDeviceHeapStats() const = 0;
PxsHeapMemoryAllocator* mMappedMemoryAllocators;
};
}
#endif
| 3,077 | C | 31.4 | 101 | 0.747806 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsNphaseImplementationContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_NPHASE_IMPLEMENTATION_CONTEXT_H
#define PXS_NPHASE_IMPLEMENTATION_CONTEXT_H
#include "PxvNphaseImplementationContext.h"
#include "PxsContactManagerState.h"
#include "PxcNpCache.h"
#include "foundation/PxPinnedArray.h"
class PxsCMDiscreteUpdateTask;
namespace physx
{
struct PxsContactManagers : PxsContactManagerBase
{
PxArray<PxsContactManagerOutput> mOutputContactManagers;
PxArray<PxsContactManager*> mContactManagerMapping;
PxArray<Gu::Cache> mCaches;
PxPinnedArray<Sc::ShapeInteraction*> mShapeInteractions;
PxFloatArrayPinned mRestDistances;
PxPinnedArray<PxsTorsionalFrictionData> mTorsionalProperties;
PxsContactManagers(const PxU32 bucketId, PxVirtualAllocatorCallback* callback) : PxsContactManagerBase(bucketId),
mOutputContactManagers ("mOutputContactManagers"),
mContactManagerMapping ("mContactManagerMapping"),
mCaches ("mCaches"),
mShapeInteractions (PxVirtualAllocator(callback)),
mRestDistances (callback),
mTorsionalProperties (callback)
{
}
void clear()
{
mOutputContactManagers.forceSize_Unsafe(0);
mContactManagerMapping.forceSize_Unsafe(0);
mCaches.forceSize_Unsafe(0);
mShapeInteractions.forceSize_Unsafe(0);
mRestDistances.forceSize_Unsafe(0);
mTorsionalProperties.forceSize_Unsafe(0);
}
private:
PX_NOCOPY(PxsContactManagers)
};
class PxsNphaseImplementationContext : public PxvNphaseImplementationContextUsableAsFallback
{
public:
PxsNphaseImplementationContext(PxsContext& context, IG::IslandSim* islandSim, PxVirtualAllocatorCallback* callback, PxU32 index, bool gpu) :
PxvNphaseImplementationContextUsableAsFallback (context),
mNarrowPhasePairs (index, callback),
mNewNarrowPhasePairs (index, callback),
mModifyCallback (NULL),
mIslandSim (islandSim),
mGPU (gpu)
{}
// PxvNphaseImplementationContext
virtual void destroy() PX_OVERRIDE;
virtual void updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation,
PxBaseTask* firstPassContinuation, Cm::FanoutTask* updateBoundAndShape) PX_OVERRIDE;
virtual void postBroadPhaseUpdateContactManager(PxBaseTask*) PX_OVERRIDE {}
virtual void secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation) PX_OVERRIDE;
virtual void fetchUpdateContactManager() PX_OVERRIDE {}
virtual void registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* shapeInteraction, PxI32 touching, PxU32 numPatches) PX_OVERRIDE;
// virtual void registerContactManagers(PxsContactManager** cm, Sc::ShapeInteraction** shapeInteractions, PxU32 nbContactManagers, PxU32 maxContactManagerId);
virtual void unregisterContactManager(PxsContactManager* cm) PX_OVERRIDE;
virtual void refreshContactManager(PxsContactManager* cm) PX_OVERRIDE;
virtual void registerShape(const PxNodeIndex& /*nodeIndex*/, const PxsShapeCore& /*shapeCore*/, const PxU32 /*transformCacheID*/, PxActor* /*actor*/, const bool /*isFemCloth*/) PX_OVERRIDE {}
virtual void unregisterShape(const PxsShapeCore& /*shapeCore*/, const PxU32 /*transformCacheID*/, const bool /*isFemCloth*/) PX_OVERRIDE {}
virtual void registerAggregate(const PxU32 /*transformCacheID*/) PX_OVERRIDE {}
virtual void registerMaterial(const PxsMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsFEMSoftBodyMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsFEMSoftBodyMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsFEMSoftBodyMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsFEMClothMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsFEMClothMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsFEMClothMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsPBDMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsPBDMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsPBDMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsFLIPMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsFLIPMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsFLIPMaterialCore&) PX_OVERRIDE {}
virtual void registerMaterial(const PxsMPMMaterialCore&) PX_OVERRIDE {}
virtual void updateMaterial(const PxsMPMMaterialCore&) PX_OVERRIDE {}
virtual void unregisterMaterial(const PxsMPMMaterialCore&) PX_OVERRIDE {}
virtual void updateShapeMaterial(const PxsShapeCore&) PX_OVERRIDE {}
virtual void startNarrowPhaseTasks() PX_OVERRIDE {}
virtual void appendContactManagers() PX_OVERRIDE;
virtual PxsContactManagerOutput& getNewContactManagerOutput(PxU32 npIndex) PX_OVERRIDE;
virtual PxsContactManagerOutputIterator getContactManagerOutputs() PX_OVERRIDE;
virtual void setContactModifyCallback(PxContactModifyCallback* callback) PX_OVERRIDE { mModifyCallback = callback; }
virtual void acquireContext() PX_OVERRIDE {}
virtual void releaseContext() PX_OVERRIDE {}
virtual void preallocateNewBuffers(PxU32 /*nbNewPairs*/, PxU32 /*maxIndex*/) PX_OVERRIDE { /*TODO - implement if it's useful to do so*/}
virtual void lock() PX_OVERRIDE { mContactManagerMutex.lock(); }
virtual void unlock() PX_OVERRIDE { mContactManagerMutex.unlock(); }
virtual PxsContactManagerOutputCounts* getFoundPatchOutputCounts() PX_OVERRIDE { return mCmFoundLostOutputCounts.begin(); }
virtual PxsContactManager** getFoundPatchManagers() PX_OVERRIDE { return mCmFoundLost.begin(); }
virtual PxU32 getNbFoundPatchManagers() PX_OVERRIDE { return mCmFoundLost.size(); }
virtual PxsContactManagerOutput* getGPUContactManagerOutputBase() PX_OVERRIDE { return NULL; }
virtual PxReal* getGPURestDistances() PX_OVERRIDE { return NULL; }
virtual Sc::ShapeInteraction** getGPUShapeInteractions() PX_OVERRIDE { return NULL; }
virtual PxsTorsionalFrictionData* getGPUTorsionalData() PX_OVERRIDE { return NULL; }
//~PxvNphaseImplementationContext
// PxvNphaseImplementationFallback
virtual void processContactManager(PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation) PX_OVERRIDE;
virtual void processContactManagerSecondPass(PxReal dt, PxBaseTask* continuation) PX_OVERRIDE;
virtual void unregisterContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual void refreshContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual void appendContactManagersFallback(PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual void removeContactManagersFallback(PxsContactManagerOutput* cmOutputs) PX_OVERRIDE;
virtual Sc::ShapeInteraction** getShapeInteractions() PX_OVERRIDE { return mNarrowPhasePairs.mShapeInteractions.begin(); }
virtual PxReal* getRestDistances() PX_OVERRIDE { return mNarrowPhasePairs.mRestDistances.begin(); }
virtual PxsTorsionalFrictionData* getTorsionalData() PX_OVERRIDE { return mNarrowPhasePairs.mTorsionalProperties.begin(); }
//~PxvNphaseImplementationFallback
PxArray<PxU32> mRemovedContactManagers;
PxsContactManagers mNarrowPhasePairs;
PxsContactManagers mNewNarrowPhasePairs;
PxContactModifyCallback* mModifyCallback;
IG::IslandSim* mIslandSim;
PxMutex mContactManagerMutex;
PxArray<PxsCMDiscreteUpdateTask*> mCmTasks;
PxArray<PxsContactManagerOutputCounts> mCmFoundLostOutputCounts;
PxArray<PxsContactManager*> mCmFoundLost;
const bool mGPU;
private:
void unregisterContactManagerInternal(PxU32 npIndex, PxsContactManagers& managers, PxsContactManagerOutput* cmOutputs);
PX_FORCE_INLINE void unregisterAndForceSize(PxsContactManagers& cms, PxU32 index)
{
unregisterContactManagerInternal(index, cms, cms.mOutputContactManagers.begin());
cms.mOutputContactManagers.forceSize_Unsafe(cms.mOutputContactManagers.size()-1);
}
void appendNewLostPairs();
PX_NOCOPY(PxsNphaseImplementationContext)
};
}
#endif
| 10,239 | C | 49.945273 | 198 | 0.762867 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsIslandManagerTypes.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_ISLAND_MANAGER_TYPES_H
#define PXS_ISLAND_MANAGER_TYPES_H
namespace physx
{
class PxsContactManager;
namespace Dy
{
struct Constraint;
}
typedef PxU32 NodeType;
typedef PxU32 EdgeType;
typedef PxU32 IslandType;
#define INVALID_NODE 0xffffffff
#define INVALID_EDGE 0xffffffff
#define INVALID_ISLAND 0xffffffff
class PxsIslandIndices
{
public:
PxsIslandIndices() {}
~PxsIslandIndices() {}
NodeType bodies;
NodeType articulations;
EdgeType contactManagers;
EdgeType constraints;
};
typedef PxU64 PxsNodeType;
/**
\brief Each contact manager or constraint references two separate bodies, where
a body can be a dynamic rigid body, a kinematic rigid body, an articulation or a static.
The struct PxsIndexedInteraction describes the bodies that make up the pair.
*/
struct PxsIndexedInteraction
{
/**
\brief An enumerated list of all possible body types.
A body type is stored for each body in the pair.
*/
enum Enum
{
eBODY = 0,
eKINEMATIC = 1,
eARTICULATION = 2,
eWORLD = 3
};
/**
\brief An index describing how to access body0
\note If body0 is a dynamic (eBODY) rigid body then solverBody0 is an index into PxsIslandObjects::bodies.
\note If body0 is a kinematic (eKINEMATIC) rigid body then solverBody0 is an index into PxsIslandManager::getActiveKinematics.
\note If body0 is a static (eWORLD) then solverBody0 is PX_MAX_U32 or PX_MAX_U64, depending on the platform being 32- or 64-bit.
\note If body0 is an articulation then the articulation is found directly from Dy::getArticulation(articulation0)
\note If body0 is an soft body then the soft body is found directly from Dy::getSoftBody(softBody0)
*/
union
{
PxsNodeType solverBody0;
PxsNodeType articulation0;
};
/**
\brief An index describing how to access body1
\note If body1 is a dynamic (eBODY) rigid body then solverBody1 is an index into PxsIslandObjects::bodies.
\note If body1 is a kinematic (eKINEMATIC) rigid body then solverBody1 is an index into PxsIslandManager::getActiveKinematics.
\note If body1 is a static (eWORLD) then solverBody1 is PX_MAX_U32 or PX_MAX_U64, depending on the platform being 32- or 64-bit.
\note If body1 is an articulation then the articulation is found directly from Dy::getArticulation(articulation1)
\note If body0 is an soft body then the soft body is found directly from Dy::getSoftBody(softBody1)
*/
union
{
PxsNodeType solverBody1;
PxsNodeType articulation1;
};
/**
\brief The type (eBODY, eKINEMATIC etc) of body0
*/
PxU8 indexType0;
/**
\brief The type (eBODY, eKINEMATIC etc) of body1
*/
PxU8 indexType1;
PxU8 pad[2];
};
/**
@see PxsIslandObjects, PxsIndexedInteraction
*/
struct PxsIndexedContactManager : public PxsIndexedInteraction
{
/**
\brief The contact manager corresponds to the value set in PxsIslandManager::setEdgeRigidCM
*/
PxsContactManager* contactManager;
PxsIndexedContactManager(PxsContactManager* cm) : contactManager(cm) {}
};
#if !PX_X64
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxsIndexedContactManager) & 0x0f));
#endif
/**
@see PxsIslandObjects, PxsIndexedInteraction
*/
struct PxsIndexedConstraint : public PxsIndexedInteraction
{
/**
\brief The constraint corresponds to the value set in PxsIslandManager::setEdgeConstraint
*/
Dy::Constraint* constraint;
PxsIndexedConstraint(Dy::Constraint* c) : constraint(c) {}
};
#if !PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(0==(sizeof(PxsIndexedConstraint) & 0x0f));
#endif
} //namespace physx
#endif
| 5,169 | C | 30.333333 | 129 | 0.762623 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsShapeSim.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_SHAPE_SIM_H
#define PXS_SHAPE_SIM_H
#include "PxsRigidBody.h"
#include "PxNodeIndex.h"
namespace physx
{
struct PxsShapeCore;
struct PxsShapeSim
{
PxsShapeSim() : mShapeCore(NULL), mElementIndex_GPU(PX_INVALID_U32)
{
}
PxsShapeCore* mShapeCore; // 4 or 8
// NodeIndex used to look up BodySim in island manager
PxNodeIndex mBodySimIndex_GPU; // 8 or 12 unique identified for body
// ElementID - copy of ElementSim's getElementID()
PxU32 mElementIndex_GPU; // 12 or 16 transform cache and bound index
};
}//physx
#endif
| 2,249 | C | 37.793103 | 74 | 0.75767 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsMaterialCombiner.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIAL_COMBINER_H
#define PXS_MATERIAL_COMBINER_H
#include "PxsMaterialCore.h"
namespace physx
{
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal combineScalars(PxReal a, PxReal b, PxI32 combineMode)
{
switch (combineMode)
{
case PxCombineMode::eAVERAGE:
return 0.5f * (a + b);
case PxCombineMode::eMIN:
return PxMin(a,b);
case PxCombineMode::eMULTIPLY:
return a * b;
case PxCombineMode::eMAX:
return PxMax(a,b);
default:
return PxReal(0);
}
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal PxsCombineRestitution(const PxsMaterialData& mat0, const PxsMaterialData& mat1)
{
return combineScalars(mat0.restitution, mat1.restitution, ((mat0.flags | mat1.flags) & PxMaterialFlag::eCOMPLIANT_CONTACT) ?
PxCombineMode::eMIN : PxMax(mat0.getRestitutionCombineMode(), mat1.getRestitutionCombineMode()));
}
//ML:: move this function to header file to avoid LHS in Xbox
//PT: also called by CUDA code now
PX_CUDA_CALLABLE PX_FORCE_INLINE void PxsCombineIsotropicFriction(const PxsMaterialData& mat0, const PxsMaterialData& mat1, PxReal& dynamicFriction, PxReal& staticFriction, PxU32& flags)
{
const PxU32 combineFlags = (mat0.flags | mat1.flags); //& (PxMaterialFlag::eDISABLE_STRONG_FRICTION|PxMaterialFlag::eDISABLE_FRICTION); //eventually set DisStrongFric flag, lower all others.
if (!(combineFlags & PxMaterialFlag::eDISABLE_FRICTION))
{
const PxI32 fictionCombineMode = PxMax(mat0.getFrictionCombineMode(), mat1.getFrictionCombineMode());
PxReal dynFriction = 0.0f;
PxReal staFriction = 0.0f;
switch (fictionCombineMode)
{
case PxCombineMode::eAVERAGE:
dynFriction = 0.5f * (mat0.dynamicFriction + mat1.dynamicFriction);
staFriction = 0.5f * (mat0.staticFriction + mat1.staticFriction);
break;
case PxCombineMode::eMIN:
dynFriction = PxMin(mat0.dynamicFriction, mat1.dynamicFriction);
staFriction = PxMin(mat0.staticFriction, mat1.staticFriction);
break;
case PxCombineMode::eMULTIPLY:
dynFriction = (mat0.dynamicFriction * mat1.dynamicFriction);
staFriction = (mat0.staticFriction * mat1.staticFriction);
break;
case PxCombineMode::eMAX:
dynFriction = PxMax(mat0.dynamicFriction, mat1.dynamicFriction);
staFriction = PxMax(mat0.staticFriction, mat1.staticFriction);
break;
}
//isotropic case
const PxReal fDynFriction = PxMax(dynFriction, 0.0f);
// PT: TODO: the two branches aren't actually doing the same thing:
// - one is ">", the other is ">="
// - one uses a clamped dynFriction, the other not
#ifdef __CUDACC__
const PxReal fStaFriction = (staFriction - fDynFriction) > 0 ? staFriction : dynFriction;
#else
const PxReal fStaFriction = physx::intrinsics::fsel(staFriction - fDynFriction, staFriction, fDynFriction);
#endif
dynamicFriction = fDynFriction;
staticFriction = fStaFriction;
flags = combineFlags;
}
else
{
flags = combineFlags | PxMaterialFlag::eDISABLE_STRONG_FRICTION;
dynamicFriction = 0.0f;
staticFriction = 0.0f;
}
}
}
#endif
| 4,746 | C | 39.922413 | 192 | 0.741256 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsTransformCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_TRANSFORM_CACHE_H
#define PXS_TRANSFORM_CACHE_H
#include "CmIDPool.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxPinnedArray.h"
#define PX_DEFAULT_CACHE_SIZE 512
namespace physx
{
struct PxsTransformFlag
{
enum Flags
{
eFROZEN = (1 << 0)
};
};
struct PX_ALIGN_PREFIX(16) PxsCachedTransform
{
PxTransform transform;
PxU32 flags;
PX_FORCE_INLINE PxU32 isFrozen() const { return flags & PxsTransformFlag::eFROZEN; }
}
PX_ALIGN_SUFFIX(16);
class PxsTransformCache : public PxUserAllocated
{
typedef PxU32 RefCountType;
public:
PxsTransformCache(PxVirtualAllocatorCallback& allocatorCallback) : mTransformCache(PxVirtualAllocator(&allocatorCallback)), mHasAnythingChanged(true)
{
/*mTransformCache.reserve(PX_DEFAULT_CACHE_SIZE);
mTransformCache.forceSize_Unsafe(PX_DEFAULT_CACHE_SIZE);*/
mUsedSize = 0;
}
void initEntry(PxU32 index)
{
PxU32 oldCapacity = mTransformCache.capacity();
if (index >= oldCapacity)
{
PxU32 newCapacity = PxNextPowerOfTwo(index);
mTransformCache.reserve(newCapacity);
mTransformCache.forceSize_Unsafe(newCapacity);
}
mUsedSize = PxMax(mUsedSize, index + 1u);
}
PX_FORCE_INLINE void setTransformCache(const PxTransform& transform, const PxU32 flags, const PxU32 index)
{
mTransformCache[index].transform = transform;
mTransformCache[index].flags = flags;
mHasAnythingChanged = true;
}
PX_FORCE_INLINE const PxsCachedTransform& getTransformCache(const PxU32 index) const
{
return mTransformCache[index];
}
PX_FORCE_INLINE PxsCachedTransform& getTransformCache(const PxU32 index)
{
return mTransformCache[index];
}
PX_FORCE_INLINE void shiftTransforms(const PxVec3& shift)
{
for (PxU32 i = 0; i < mTransformCache.capacity(); i++)
{
mTransformCache[i].transform.p += shift;
}
mHasAnythingChanged = true;
}
PX_FORCE_INLINE PxU32 getTotalSize() const
{
return mUsedSize;
}
PX_FORCE_INLINE const PxsCachedTransform* getTransforms() const
{
return mTransformCache.begin();
}
PX_FORCE_INLINE PxsCachedTransform* getTransforms()
{
return mTransformCache.begin();
}
PX_FORCE_INLINE PxPinnedArray<PxsCachedTransform>* getCachedTransformArray()
{
return &mTransformCache;
}
PX_FORCE_INLINE void resetChangedState() { mHasAnythingChanged = false; }
PX_FORCE_INLINE void setChangedState() { mHasAnythingChanged = true; }
PX_FORCE_INLINE bool hasChanged() const { return mHasAnythingChanged; }
private:
PxPinnedArray<PxsCachedTransform> mTransformCache;
PxU32 mUsedSize;
bool mHasAnythingChanged;
};
}
#endif
| 4,428 | C | 30.411347 | 151 | 0.74458 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsSimpleIslandManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_SIMPLE_ISLAND_GEN_H
#define PXS_SIMPLE_ISLAND_GEN_H
#include "foundation/PxUserAllocated.h"
#include "PxsIslandSim.h"
#include "CmTask.h"
namespace physx
{
// PT: TODO: fw declaring an Sc class here is not good
namespace Sc
{
class Interaction;
}
namespace IG
{
class SimpleIslandManager;
class ThirdPassTask : public Cm::Task
{
SimpleIslandManager& mIslandManager;
IslandSim& mIslandSim;
public:
ThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager, IslandSim& islandSim);
virtual void runInternal();
virtual const char* getName() const
{
return "ThirdPassIslandGenTask";
}
private:
PX_NOCOPY(ThirdPassTask)
};
class PostThirdPassTask : public Cm::Task
{
SimpleIslandManager& mIslandManager;
public:
PostThirdPassTask(PxU64 contextID, SimpleIslandManager& islandManager);
virtual void runInternal();
virtual const char* getName() const
{
return "PostThirdPassTask";
}
private:
PX_NOCOPY(PostThirdPassTask)
};
class SimpleIslandManager : public PxUserAllocated
{
HandleManager<PxU32> mNodeHandles; //! Handle manager for nodes
HandleManager<EdgeIndex> mEdgeHandles; //! Handle manager for edges
//An array of destroyed nodes
PxArray<PxNodeIndex> mDestroyedNodes;
Cm::BlockArray<Sc::Interaction*> mInteractions;
//Edges destroyed this frame
PxArray<EdgeIndex> mDestroyedEdges;
PxArray<PartitionEdge*> mFirstPartitionEdges;
PxArray<PartitionEdge*> mDestroyedPartitionEdges;
//KS - stores node indices for a given edge. Node index 0 is at 2* edgeId and NodeIndex1 is at 2*edgeId + 1
//can also be used for edgeInstance indexing so there's no need to figure out outboundNode ID either!
Cm::BlockArray<PxNodeIndex> mEdgeNodeIndices;
Cm::BlockArray<void*> mConstraintOrCm; //! Pointers to either the constraint or Cm for this pair
PxBitMap mConnectedMap;
IslandSim mIslandManager;
IslandSim mSpeculativeIslandManager;
ThirdPassTask mSpeculativeThirdPassTask;
ThirdPassTask mAccurateThirdPassTask;
PostThirdPassTask mPostThirdPassTask;
PxU32 mMaxDirtyNodesPerFrame;
PxU64 mContextID;
public:
SimpleIslandManager(bool useEnhancedDeterminism, PxU64 contextID);
~SimpleIslandManager();
PxNodeIndex addRigidBody(PxsRigidBody* body, bool isKinematic, bool isActive);
void removeNode(const PxNodeIndex index);
PxNodeIndex addArticulation(Dy::FeatherstoneArticulation* llArtic, bool isActive);
#if PX_SUPPORT_GPU_PHYSX
PxNodeIndex addSoftBody(Dy::SoftBody* llSoftBody, bool isActive);
PxNodeIndex addFEMCloth(Dy::FEMCloth* llFEMCloth, bool isActive);
PxNodeIndex addParticleSystem(Dy::ParticleSystem* llParticleSystem, bool isActive);
PxNodeIndex addHairSystem(Dy::HairSystem* llHairSystem, bool isActive);
#endif
EdgeIndex addContactManager(PxsContactManager* manager, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction,
Edge::EdgeType edgeType);
EdgeIndex addConstraint(Dy::Constraint* constraint, PxNodeIndex nodeHandle1, PxNodeIndex nodeHandle2, Sc::Interaction* interaction);
bool isConnected(EdgeIndex edgeIndex) const { return !!mConnectedMap.test(edgeIndex); }
PX_FORCE_INLINE PxNodeIndex getEdgeIndex(EdgeInstanceIndex edgeIndex) const { return mEdgeNodeIndices[edgeIndex]; }
void activateNode(PxNodeIndex index);
void deactivateNode(PxNodeIndex index);
void putNodeToSleep(PxNodeIndex index);
void removeConnection(EdgeIndex edgeIndex);
void firstPassIslandGen();
void additionalSpeculativeActivation();
void secondPassIslandGen();
void thirdPassIslandGen(PxBaseTask* continuation);
PX_INLINE void clearDestroyedEdges()
{
mDestroyedPartitionEdges.forceSize_Unsafe(0);
}
void setEdgeConnected(EdgeIndex edgeIndex, Edge::EdgeType edgeType);
void setEdgeDisconnected(EdgeIndex edgeIndex);
bool getIsEdgeConnected(EdgeIndex edgeIndex);
void setEdgeRigidCM(const EdgeIndex edgeIndex, PxsContactManager* cm);
void clearEdgeRigidCM(const EdgeIndex edgeIndex);
void setKinematic(PxNodeIndex nodeIndex);
void setDynamic(PxNodeIndex nodeIndex);
const IslandSim& getSpeculativeIslandSim() const { return mSpeculativeIslandManager; }
const IslandSim& getAccurateIslandSim() const { return mIslandManager; }
IslandSim& getAccurateIslandSim() { return mIslandManager; }
IslandSim& getSpeculativeIslandSim() { return mSpeculativeIslandManager; }
PX_FORCE_INLINE PxU32 getNbEdgeHandles() const { return mEdgeHandles.getTotalHandles(); }
PX_FORCE_INLINE PxU32 getNbNodeHandles() const { return mNodeHandles.getTotalHandles(); }
void deactivateEdge(const EdgeIndex edge);
PX_FORCE_INLINE PxsContactManager* getContactManager(IG::EdgeIndex edgeId) const { return reinterpret_cast<PxsContactManager*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE PxsContactManager* getContactManagerUnsafe(IG::EdgeIndex edgeId) const { return reinterpret_cast<PxsContactManager*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE Dy::Constraint* getConstraint(IG::EdgeIndex edgeId) const { return reinterpret_cast<Dy::Constraint*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE Dy::Constraint* getConstraintUnsafe(IG::EdgeIndex edgeId) const { return reinterpret_cast<Dy::Constraint*>(mConstraintOrCm[edgeId]); }
PX_FORCE_INLINE Sc::Interaction* getInteraction(IG::EdgeIndex edgeId) const { return mInteractions[edgeId]; }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
bool checkInternalConsistency();
private:
friend class ThirdPassTask;
friend class PostThirdPassTask;
bool validateDeactivations() const;
PX_NOCOPY(SimpleIslandManager)
};
}
}
#endif
| 7,239 | C | 32.99061 | 161 | 0.790026 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsContactManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_CONTACT_MANAGER_H
#define PXS_CONTACT_MANAGER_H
#include "PxvConfig.h"
#include "PxcNpWorkUnit.h"
namespace physx
{
class PxsContext;
class PxsRigidBody;
namespace Dy
{
class DynamicsContext;
}
namespace Sc
{
class ShapeInteraction;
}
/**
\brief Additional header structure for CCD contact data stream.
*/
struct PxsCCDContactHeader
{
/**
\brief Stream for next collision. The same pair can collide multiple times during multiple CCD passes.
*/
PxsCCDContactHeader* nextStream; //4 //8
/**
\brief Size (in bytes) of the CCD contact stream (not including force buffer)
*/
PxU16 contactStreamSize; //6 //10
/**
\brief Defines whether the stream is from a previous pass.
It could happen that the stream can not get allocated because we run out of memory. In that case the current event should not use the stream
from an event of the previous pass.
*/
PxU16 isFromPreviousPass; //8 //12
PxU8 pad[12 - sizeof(PxsCCDContactHeader*)]; //16
};
PX_COMPILE_TIME_ASSERT((sizeof(PxsCCDContactHeader) & 0xF) == 0);
class PxsContactManager
{
public:
PxsContactManager(PxsContext* context, PxU32 index);
~PxsContactManager();
PX_FORCE_INLINE void setDisableStrongFriction(PxU32 d) { (!d) ? mNpUnit.flags &= ~PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION
: mNpUnit.flags |= PxcNpWorkUnitFlag::eDISABLE_STRONG_FRICTION; }
PX_FORCE_INLINE PxReal getRestDistance() const { return mNpUnit.restDistance; }
PX_FORCE_INLINE void setRestDistance(PxReal v) { mNpUnit.restDistance = v; }
PX_FORCE_INLINE PxU8 getDominance0() const { return mNpUnit.dominance0; }
PX_FORCE_INLINE void setDominance0(PxU8 v) { mNpUnit.dominance0 = v; }
PX_FORCE_INLINE PxU8 getDominance1() const { return mNpUnit.dominance1; }
PX_FORCE_INLINE void setDominance1(PxU8 v) { mNpUnit.dominance1 = v; }
PX_FORCE_INLINE PxU16 getTouchStatus() const { return PxU16(mNpUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_TOUCH); }
PX_FORCE_INLINE PxU16 touchStatusKnown() const { return PxU16(mNpUnit.statusFlags & PxcNpWorkUnitStatusFlag::eTOUCH_KNOWN); }
PX_FORCE_INLINE PxI32 getTouchIdx() const { return (mNpUnit.statusFlags& PxcNpWorkUnitStatusFlag::eHAS_TOUCH) ? 1 : (mNpUnit.statusFlags& PxcNpWorkUnitStatusFlag::eHAS_NO_TOUCH ? -1 : 0); }
PX_FORCE_INLINE PxU32 getIndex() const { return mNpUnit.index; }
PX_FORCE_INLINE PxU16 getHasCCDRetouch() const { return PxU16(mNpUnit.statusFlags & PxcNpWorkUnitStatusFlag::eHAS_CCD_RETOUCH); }
PX_FORCE_INLINE void clearCCDRetouch() { mNpUnit.statusFlags &= ~PxcNpWorkUnitStatusFlag::eHAS_CCD_RETOUCH; }
PX_FORCE_INLINE void raiseCCDRetouch() { mNpUnit.statusFlags |= PxcNpWorkUnitStatusFlag::eHAS_CCD_RETOUCH; }
// flags stuff - needs to be refactored
PX_FORCE_INLINE PxIntBool isChangeable() const { return PxIntBool(mFlags & PXS_CM_CHANGEABLE); }
PX_FORCE_INLINE PxIntBool getCCD() const { return PxIntBool((mFlags & PXS_CM_CCD_LINEAR) && (mNpUnit.flags & PxcNpWorkUnitFlag::eDETECT_CCD_CONTACTS)); }
PX_FORCE_INLINE PxIntBool getHadCCDContact() const { return PxIntBool(mFlags & PXS_CM_CCD_CONTACT); }
PX_FORCE_INLINE void setHadCCDContact() { mFlags |= PXS_CM_CCD_CONTACT; }
void setCCD(bool enable);
PX_FORCE_INLINE void clearCCDContactInfo() { mFlags &= ~PXS_CM_CCD_CONTACT; mNpUnit.ccdContacts = NULL; }
PX_FORCE_INLINE PxcNpWorkUnit& getWorkUnit() { return mNpUnit; }
PX_FORCE_INLINE const PxcNpWorkUnit& getWorkUnit() const { return mNpUnit; }
PX_FORCE_INLINE Sc::ShapeInteraction* getShapeInteraction() const { return mShapeInteraction; }
// Setup solver-constraints
PX_FORCE_INLINE void resetCachedState()
{
// happens when the body transform or shape relative transform changes.
mNpUnit.clearCachedState();
}
private:
//KS - moving this up - we want to get at flags
PxsRigidBody* mRigidBody0; //4 //8
PxsRigidBody* mRigidBody1; //8 //16
PxU32 mFlags; //20 //36
Sc::ShapeInteraction* mShapeInteraction; //16 //32
friend class PxsContext;
// everything required for narrow phase to run
PxcNpWorkUnit mNpUnit;
enum
{
PXS_CM_CHANGEABLE = (1<<0),
PXS_CM_CCD_LINEAR = (1<<1),
PXS_CM_CCD_CONTACT = (1 << 2)
};
friend class Dy::DynamicsContext;
friend struct PxsCCDPair;
friend class PxsCCDContext;
friend class Sc::ShapeInteraction;
};
}
#endif
| 6,276 | C | 40.569536 | 197 | 0.715105 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxvNphaseImplementationContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_NPHASE_IMPLEMENTATION_CONTEXT_H
#define PXV_NPHASE_IMPLEMENTATION_CONTEXT_H
#include "PxSceneDesc.h"
#include "PxsContactManagerState.h"
#include "foundation/PxArray.h"
#include "PxsNphaseCommon.h"
// PT: TODO: forward decl don't work easily with templates, to revisit
#include "PxsMaterialCore.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "PxsPBDMaterialCore.h"
namespace physx
{
namespace IG
{
class IslandSim;
typedef PxU32 EdgeIndex;
}
namespace Cm
{
class FanoutTask;
}
namespace Sc
{
class ShapeInteraction;
}
class PxNodeIndex;
class PxBaseTask;
class PxsContext;
struct PxsShapeCore;
class PxsContactManager;
struct PxsContactManagerOutput;
struct PxsTorsionalFrictionData;
class PxsContactManagerOutputIterator
{
PxU32 mOffsets[1<<PxsContactManagerBase::MaxBucketBits];
PxsContactManagerOutput* mOutputs;
public:
PxsContactManagerOutputIterator() : mOutputs(NULL)
{
}
PxsContactManagerOutputIterator(PxU32* offsets, PxU32 nbOffsets, PxsContactManagerOutput* outputs) : mOutputs(outputs)
{
PX_ASSERT(nbOffsets <= (1<<PxsContactManagerBase::MaxBucketBits));
for(PxU32 a = 0; a < nbOffsets; ++a)
{
mOffsets[a] = offsets[a];
}
}
PX_FORCE_INLINE PxsContactManagerOutput& getContactManager(PxU32 id)
{
PX_ASSERT((id & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK) == 0);
PxU32 bucketId = PxsContactManagerBase::computeBucketIndexFromId(id);
PxU32 cmOutId = PxsContactManagerBase::computeIndexFromId(id);
return mOutputs[mOffsets[bucketId] + cmOutId];
}
PxU32 getIndex(PxU32 id)
{
PX_ASSERT((id & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK) == 0);
PxU32 bucketId = PxsContactManagerBase::computeBucketIndexFromId(id);
PxU32 cmOutId = PxsContactManagerBase::computeIndexFromId(id);
return mOffsets[bucketId] + cmOutId;
}
};
class PxvNphaseImplementationContext
{
private:
PX_NOCOPY(PxvNphaseImplementationContext)
public:
PxvNphaseImplementationContext(PxsContext& context): mContext(context) {}
virtual ~PxvNphaseImplementationContext() {}
virtual void destroy() = 0;
virtual void updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation, PxBaseTask* firstPassContinuation, Cm::FanoutTask* updateBoundAndShapeTask) = 0;
virtual void postBroadPhaseUpdateContactManager(PxBaseTask* continuation) = 0;
virtual void secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation) = 0;
virtual void fetchUpdateContactManager() = 0;
virtual void registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* interaction, PxI32 touching, PxU32 patchCount) = 0;
// virtual void registerContactManagers(PxsContactManager** cm, Sc::ShapeInteraction** shapeInteractions, PxU32 nbContactManagers, PxU32 maxContactManagerId) = 0;
virtual void unregisterContactManager(PxsContactManager* cm) = 0;
virtual void refreshContactManager(PxsContactManager* cm) = 0;
virtual void registerShape(const PxNodeIndex& nodeIndex, const PxsShapeCore& shapeCore, const PxU32 transformCacheID, PxActor* actor, const bool isFemCloth = false) = 0;
virtual void unregisterShape(const PxsShapeCore& shapeCore, const PxU32 transformCacheID, const bool isFemCloth = false) = 0;
virtual void registerAggregate(const PxU32 transformCacheID) = 0;
virtual void registerMaterial(const PxsMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsFEMSoftBodyMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsFEMSoftBodyMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsFEMSoftBodyMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsFEMClothMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsFEMClothMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsFEMClothMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsPBDMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsPBDMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsPBDMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsFLIPMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsFLIPMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsFLIPMaterialCore& materialCore) = 0;
virtual void registerMaterial(const PxsMPMMaterialCore& materialCore) = 0;
virtual void updateMaterial(const PxsMPMMaterialCore& materialCore) = 0;
virtual void unregisterMaterial(const PxsMPMMaterialCore& materialCore) = 0;
virtual void updateShapeMaterial(const PxsShapeCore& shapeCore) = 0;
virtual void startNarrowPhaseTasks() = 0;
virtual void appendContactManagers() = 0;
virtual PxsContactManagerOutput& getNewContactManagerOutput(PxU32 index) = 0;
virtual PxsContactManagerOutputIterator getContactManagerOutputs() = 0;
virtual void setContactModifyCallback(PxContactModifyCallback* callback) = 0;
virtual void acquireContext() = 0;
virtual void releaseContext() = 0;
virtual void preallocateNewBuffers(PxU32 nbNewPairs, PxU32 maxIndex) = 0;
virtual void lock() = 0;
virtual void unlock() = 0;
virtual PxsContactManagerOutputCounts* getFoundPatchOutputCounts() = 0;
virtual PxsContactManager** getFoundPatchManagers() = 0;
virtual PxU32 getNbFoundPatchManagers() = 0;
//GPU-specific buffers. Return null for CPU narrow phase
virtual PxsContactManagerOutput* getGPUContactManagerOutputBase() = 0;
virtual PxReal* getGPURestDistances() = 0;
virtual Sc::ShapeInteraction** getGPUShapeInteractions() = 0;
virtual PxsTorsionalFrictionData* getGPUTorsionalData() = 0;
protected:
PxsContext& mContext;
};
class PxvNphaseImplementationFallback
{
private:
PX_NOCOPY(PxvNphaseImplementationFallback)
public:
PxvNphaseImplementationFallback() {}
virtual ~PxvNphaseImplementationFallback() {}
virtual void processContactManager(PxReal dt, PxsContactManagerOutput* cmOutputs, PxBaseTask* continuation) = 0;
virtual void processContactManagerSecondPass(PxReal dt, PxBaseTask* continuation) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?! Should be "registerContactManagerFallback"...
virtual void registerContactManager(PxsContactManager* cm, Sc::ShapeInteraction* shapeInteraction, PxI32 touching, PxU32 numPatches) = 0;
virtual void unregisterContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) = 0;
virtual void refreshContactManagerFallback(PxsContactManager* cm, PxsContactManagerOutput* cmOutputs) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual PxsContactManagerOutput& getNewContactManagerOutput(PxU32 npId) = 0;
virtual void appendContactManagersFallback(PxsContactManagerOutput* outputs) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual void setContactModifyCallback(PxContactModifyCallback* callback) = 0;
virtual void removeContactManagersFallback(PxsContactManagerOutput* cmOutputs) = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual void lock() = 0;
virtual void unlock() = 0;
// PT: TODO: this one is already defined in PxvNphaseImplementationContext ?!
virtual PxsContactManagerOutputCounts* getFoundPatchOutputCounts() = 0;
virtual PxsContactManager** getFoundPatchManagers() = 0;
virtual PxU32 getNbFoundPatchManagers() = 0;
virtual Sc::ShapeInteraction** getShapeInteractions() = 0;
virtual PxReal* getRestDistances() = 0;
virtual PxsTorsionalFrictionData* getTorsionalData() = 0;
};
class PxvNphaseImplementationContextUsableAsFallback: public PxvNphaseImplementationContext, public PxvNphaseImplementationFallback
{
private:
PX_NOCOPY(PxvNphaseImplementationContextUsableAsFallback)
public:
PxvNphaseImplementationContextUsableAsFallback(PxsContext& context) : PxvNphaseImplementationContext(context) {}
virtual ~PxvNphaseImplementationContextUsableAsFallback() {}
};
PxvNphaseImplementationContextUsableAsFallback* createNphaseImplementationContext(PxsContext& context, IG::IslandSim* islandSim, PxVirtualAllocatorCallback* allocator, bool gpuDynamics);
}
#endif
| 10,453 | C | 40.816 | 189 | 0.773271 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/software/include/PxsContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_CONTEXT_H
#define PXS_CONTEXT_H
#include "foundation/PxPinnedArray.h"
#include "PxVisualizationParameter.h"
#include "PxSceneDesc.h"
#include "common/PxRenderOutput.h"
#include "CmPool.h"
#include "PxvNphaseImplementationContext.h"
#include "PxvSimStats.h"
#include "PxsContactManager.h"
#include "PxcNpBatch.h"
#include "PxcConstraintBlockStream.h"
#include "PxcNpCacheStreamPair.h"
#include "PxcNpMemBlockPool.h"
#include "CmUtils.h"
#include "CmTask.h"
#include "PxContactModifyCallback.h"
#include "PxsTransformCache.h"
#include "GuPersistentContactManifold.h"
#if PX_SUPPORT_GPU_PHYSX
namespace physx
{
class PxCudaContextManager;
}
#endif
namespace physx
{
class PxsRigidBody;
struct PxcConstraintBlock;
class PxsMaterialManager;
class PxsCCDContext;
struct PxsContactManagerOutput;
struct PxvContactManagerTouchEvent;
namespace Cm
{
class FlushPool;
}
namespace IG
{
class SimpleIslandManager;
typedef PxU32 EdgeIndex;
}
enum PxsTouchEventCount
{
PXS_LOST_TOUCH_COUNT,
PXS_NEW_TOUCH_COUNT,
PXS_CCD_RETOUCH_COUNT, // pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// (but they could have lost touch in between)
PXS_TOUCH_EVENT_COUNT
};
class PxsContext : public PxUserAllocated, public PxcNpContext
{
PX_NOCOPY(PxsContext)
public:
PxsContext( const PxSceneDesc& desc, PxTaskManager*, Cm::FlushPool&, PxCudaContextManager*, PxU32 poolSlabSize, PxU64 contextID);
~PxsContext();
void createTransformCache(PxVirtualAllocatorCallback& allocatorCallback);
PxsContactManager* createContactManager(PxsContactManager* contactManager, bool useCCD);
void createCache(Gu::Cache& cache, PxGeometryType::Enum geomType0, PxGeometryType::Enum geomType1);
void destroyCache(Gu::Cache& cache);
void destroyContactManager(PxsContactManager* cm);
PX_FORCE_INLINE PxU64 getContextId() const { return mContextID; }
// Collision properties
PX_FORCE_INLINE PxContactModifyCallback* getContactModifyCallback() const { return mContactModifyCallback; }
PX_FORCE_INLINE void setContactModifyCallback(PxContactModifyCallback* c) { mContactModifyCallback = c; mNpImplementationContext->setContactModifyCallback(c);}
// resource-related
void setScratchBlock(void* addr, PxU32 size);
PX_FORCE_INLINE void setContactDistance(const PxFloatArrayPinned* contactDistances) { mContactDistances = contactDistances; }
// Task-related
void updateContactManager(PxReal dt, bool hasContactDistanceChanged, PxBaseTask* continuation,
PxBaseTask* firstPassContinuation, Cm::FanoutTask* updateBoundAndShapeTask);
void secondPassUpdateContactManager(PxReal dt, PxBaseTask* continuation);
void fetchUpdateContactManager();
void swapStreams();
void resetThreadContexts();
// Manager status change
bool getManagerTouchEventCount(int* newTouch, int* lostTouch, int* ccdTouch) const;
bool fillManagerTouchEvents(
PxvContactManagerTouchEvent* newTouch, PxI32& newTouchCount,
PxvContactManagerTouchEvent* lostTouch, PxI32& lostTouchCount,
PxvContactManagerTouchEvent* ccdTouch, PxI32& ccdTouchCount);
void beginUpdate();
// PX_ENABLE_SIM_STATS
PX_FORCE_INLINE PxvSimStats& getSimStats() { return mSimStats; }
PX_FORCE_INLINE const PxvSimStats& getSimStats() const { return mSimStats; }
PX_FORCE_INLINE Cm::FlushPool& getTaskPool() const { return mTaskPool; }
PX_FORCE_INLINE PxRenderBuffer& getRenderBuffer() { return mRenderBuffer; }
PX_FORCE_INLINE PxReal getRenderScale() const { return mVisualizationParams[PxVisualizationParameter::eSCALE]; }
PX_FORCE_INLINE PxReal getVisualizationParameter(PxVisualizationParameter::Enum param) const
{
PX_ASSERT(param < PxVisualizationParameter::eNUM_VALUES);
return mVisualizationParams[param];
}
PX_FORCE_INLINE void setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value)
{
PX_ASSERT(param < PxVisualizationParameter::eNUM_VALUES);
PX_ASSERT(value >= 0.0f);
mVisualizationParams[param] = value;
}
PX_FORCE_INLINE void setVisualizationCullingBox(const PxBounds3& box) { mVisualizationCullingBox = box; }
PX_FORCE_INLINE const PxBounds3& getVisualizationCullingBox() const { return mVisualizationCullingBox; }
PX_FORCE_INLINE bool getPCM() const { return mPCM; }
PX_FORCE_INLINE bool getContactCacheFlag() const { return mContactCache; }
PX_FORCE_INLINE bool getCreateAveragePoint() const { return mCreateAveragePoint; }
// general stuff
void shiftOrigin(const PxVec3& shift);
PX_FORCE_INLINE void setPCM(bool enabled) { mPCM = enabled; }
PX_FORCE_INLINE void setContactCache(bool enabled) { mContactCache = enabled; }
PX_FORCE_INLINE PxcScratchAllocator& getScratchAllocator() { return mScratchAllocator; }
PX_FORCE_INLINE PxsTransformCache& getTransformCache() { return *mTransformCache; }
PX_FORCE_INLINE const PxReal* getContactDistances() const { return mContactDistances->begin(); }
PX_FORCE_INLINE PxvNphaseImplementationContext* getNphaseImplementationContext() const { return mNpImplementationContext; }
PX_FORCE_INLINE void setNphaseImplementationContext(PxvNphaseImplementationContext* ctx) { mNpImplementationContext = ctx; }
PX_FORCE_INLINE PxvNphaseImplementationContext* getNphaseFallbackImplementationContext() const { return mNpFallbackImplementationContext; }
PX_FORCE_INLINE void setNphaseFallbackImplementationContext(PxvNphaseImplementationContext* ctx) { mNpFallbackImplementationContext = ctx; }
PxU32 getTotalCompressedContactSize() const { return mTotalCompressedCacheSize; }
PxU32 getMaxPatchCount() const { return mMaxPatches; }
PX_FORCE_INLINE PxcNpThreadContext* getNpThreadContext()
{
// We may want to conditional compile to exclude this on single threaded implementations
// if it is determined to be a performance hit.
return mNpThreadContextPool.get();
}
PX_FORCE_INLINE void putNpThreadContext(PxcNpThreadContext* threadContext)
{ mNpThreadContextPool.put(threadContext); }
PX_FORCE_INLINE PxMutex& getLock() { return mLock; }
PX_FORCE_INLINE PxTaskManager& getTaskManager()
{
PX_ASSERT(mTaskManager);
return *mTaskManager;
}
PX_FORCE_INLINE PxCudaContextManager* getCudaContextManager()
{
return mCudaContextManager;
}
PX_FORCE_INLINE void clearManagerTouchEvents();
PX_FORCE_INLINE Cm::PoolList<PxsContactManager, PxsContext>& getContactManagerPool()
{
return this->mContactManagerPool;
}
PX_FORCE_INLINE void setActiveContactManager(const PxsContactManager* manager, PxIntBool useCCD)
{
/*const PxU32 index = manager->getIndex();
if(index >= mActiveContactManager.size())
{
const PxU32 newSize = (2 * index + 256)&~255;
mActiveContactManager.resize(newSize);
}
mActiveContactManager.set(index);*/
//Record any pairs that have CCD enabled!
if(useCCD)
{
const PxU32 index = manager->getIndex();
if(index >= mActiveContactManagersWithCCD.size())
{
const PxU32 newSize = (2 * index + 256)&~255;
mActiveContactManagersWithCCD.resize(newSize);
}
mActiveContactManagersWithCCD.set(index);
}
}
private:
void mergeCMDiscreteUpdateResults(PxBaseTask* continuation);
PxU32 mIndex;
// Threading
PxcThreadCoherentCache<PxcNpThreadContext, PxcNpContext>
mNpThreadContextPool;
// Contact managers
Cm::PoolList<PxsContactManager, PxsContext> mContactManagerPool;
PxPool<Gu::LargePersistentContactManifold> mManifoldPool;
PxPool<Gu::SpherePersistentContactManifold> mSphereManifoldPool;
// PxBitMap mActiveContactManager;
PxBitMap mActiveContactManagersWithCCD; //KS - adding to filter any pairs that had a touch
PxBitMap mContactManagersWithCCDTouch; //KS - adding to filter any pairs that had a touch
PxBitMap mContactManagerTouchEvent;
//Cm::BitMap mContactManagerPatchChangeEvent;
PxU32 mCMTouchEventCount[PXS_TOUCH_EVENT_COUNT];
PxMutex mLock;
PxContactModifyCallback* mContactModifyCallback;
// narrowphase platform-dependent implementations support
PxvNphaseImplementationContext* mNpImplementationContext;
PxvNphaseImplementationContext* mNpFallbackImplementationContext;
// debug rendering (CS TODO: MS would like to have these wrapped into a class)
PxReal mVisualizationParams[PxVisualizationParameter::eNUM_VALUES];
PxBounds3 mVisualizationCullingBox;
PxTaskManager* mTaskManager;
Cm::FlushPool& mTaskPool;
PxCudaContextManager* mCudaContextManager;
// PxU32 mTouchesLost;
// PxU32 mTouchesFound;
// PX_ENABLE_SIM_STATS
PxvSimStats mSimStats;
bool mPCM;
bool mContactCache;
bool mCreateAveragePoint;
PxsTransformCache* mTransformCache;
const PxFloatArrayPinned* mContactDistances;
PxU32 mMaxPatches;
PxU32 mTotalCompressedCacheSize;
const PxU64 mContextID;
friend class PxsCCDContext;
friend class PxsNphaseImplementationContext;
friend class PxgNphaseImplementationContext; //FDTODO ideally it shouldn't be here..
};
PX_FORCE_INLINE void PxsContext::clearManagerTouchEvents()
{
mContactManagerTouchEvent.clear();
for(PxU32 i = 0; i < PXS_TOUCH_EVENT_COUNT; ++i)
{
mCMTouchEventCount[i] = 0;
}
}
}
#endif
| 11,660 | C | 36.616129 | 166 | 0.725386 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/src/px_globals.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxvGlobals.h"
#include "PxsContext.h"
#include "PxcContactMethodImpl.h"
#include "GuContactMethodImpl.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
static physx::PxPhysXGpu* gPxPhysXGpu = NULL;
#endif
namespace physx
{
PxvOffsetTable gPxvOffsetTable;
void PxvInit(const PxvOffsetTable& offsetTable)
{
#if PX_SUPPORT_GPU_PHYSX
gPxPhysXGpu = NULL;
#endif
gPxvOffsetTable = offsetTable;
}
void PxvTerm()
{
#if PX_SUPPORT_GPU_PHYSX
PX_RELEASE(gPxPhysXGpu);
#endif
}
}
#if PX_SUPPORT_GPU_PHYSX
namespace physx
{
//forward declare stuff from PxPhysXGpuModuleLoader.cpp
void PxLoadPhysxGPUModule(const char* appGUID);
void PxUnloadPhysxGPUModule();
typedef physx::PxPhysXGpu* (PxCreatePhysXGpu_FUNC)();
extern PxCreatePhysXGpu_FUNC* g_PxCreatePhysXGpu_Func;
PxPhysXGpu* PxvGetPhysXGpu(bool createIfNeeded)
{
if (!gPxPhysXGpu && createIfNeeded)
{
#ifdef PX_PHYSX_GPU_STATIC
gPxPhysXGpu = PxCreatePhysXGpu();
#else
PxLoadPhysxGPUModule(NULL);
if (g_PxCreatePhysXGpu_Func)
{
gPxPhysXGpu = g_PxCreatePhysXGpu_Func();
}
#endif
}
return gPxPhysXGpu;
}
// PT: added for the standalone GPU BP but we may want to revisit this
void PxvReleasePhysXGpu(PxPhysXGpu* gpu)
{
PX_ASSERT(gpu==gPxPhysXGpu);
PxUnloadPhysxGPUModule();
PX_RELEASE(gpu);
gPxPhysXGpu = NULL;
}
}
#endif
#include "common/PxMetaData.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "PxsPBDMaterialCore.h"
#include "PxsMaterialCore.h"
namespace physx
{
template<> void PxsMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxCombineMode::Enum, PxU32)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxMaterialFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, PxsMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, staticFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, restitution, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxMaterialFlags, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU8, fricCombineMode, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU8, restCombineMode, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFEMSoftBodyMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFEMSoftBodyMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, youngs, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, poissons, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, dampingScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, materialModel, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformLowLimitRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformHighLimitRatio, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxFEMSoftBodyMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFEMClothMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFEMClothMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, youngs, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, poissons, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, thickness, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxFEMClothMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsPBDMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsPBDMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxU32, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, viscosity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, vorticityConfinement, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, surfaceTension, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, cohesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, lift, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, drag, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, cflCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, particleFrictionScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, particleAdhesionScale, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxPBDMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFLIPMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFLIPMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, viscosity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, surfaceTension, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxFLIPMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsMPMMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsMPMMaterialCore)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxIntBool, PxU32)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxIntBool, isPlastic, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, youngsModulus, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, poissonsRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, hardening, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, criticalCompression, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, criticalStretch, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, tensileDamageSensitivity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, compressiveDamageSensitivity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, attractiveForceResidual, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxMPMMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
}
| 10,403 | C++ | 41.814815 | 118 | 0.783908 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvGeometry.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_GEOMETRY_H
#define PXV_GEOMETRY_H
#include "foundation/PxTransform.h"
#include "PxvConfig.h"
/*!
\file
Geometry interface
*/
/************************************************************************/
/* Shapes */
/************************************************************************/
#include "GuGeometryChecks.h"
#include "CmUtils.h"
namespace physx
{
//
// Summary of our material approach:
//
// On the API level, materials are accessed via pointer. Internally we store indices into the material table.
// The material table is stored in the SDK and the materials are shared among scenes. To make this threadsafe,
// we have the following approach:
//
// - Every scene has a copy of the SDK master material table
// - At the beginning of a simulation step, the scene material table gets synced to the master material table.
// - While the simulation is running, the scene table does not get touched.
// - Each shape stores the indices of its material(s). When the simulation is not running and a user requests the
// materials of the shape, the indices are used to fetch the material from the master material table. When the
// the simulation is running then the same indices are used internally to fetch the materials from the scene
// material table.
// - This whole scheme only works as long as the position of a material in the material table does not change
// when other materials get deleted/inserted. The data structure of the material table makes sure that is the case.
//
struct MaterialIndicesStruct
{
// PX_SERIALIZATION
MaterialIndicesStruct(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
MaterialIndicesStruct()
: indices(NULL)
, numIndices(0)
, pad(PX_PADDING_16)
{
}
~MaterialIndicesStruct()
{
}
void allocate(PxU16 size)
{
indices = PX_ALLOCATE(PxU16, size, "MaterialIndicesStruct::allocate");
numIndices = size;
}
void deallocate()
{
PX_FREE(indices);
numIndices = 0;
}
PxU16* indices; // the remap table for material index
PxU16 numIndices; // the size of the remap table
PxU16 pad; // pad for serialization
PxU32 gpuRemapId; // PT: using padding bytes on x64
};
struct PxConvexMeshGeometryLL: public PxConvexMeshGeometry
{
bool gpuCompatible; // PT: TODO: remove?
};
struct PxTriangleMeshGeometryLL: public PxTriangleMeshGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxParticleSystemGeometryLL : public PxParticleSystemGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxTetrahedronMeshGeometryLL : public PxTetrahedronMeshGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxHeightFieldGeometryLL : public PxHeightFieldGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxHairSystemGeometryLL : public PxHairSystemGeometry
{
PxU32 gpuRemapId;
};
template <> struct PxcGeometryTraits<PxParticleSystemGeometryLL> { enum { TypeID = PxGeometryType::ePARTICLESYSTEM}; };
template <> struct PxcGeometryTraits<PxConvexMeshGeometryLL> { enum { TypeID = PxGeometryType::eCONVEXMESH }; };
template <> struct PxcGeometryTraits<PxTriangleMeshGeometryLL> { enum { TypeID = PxGeometryType::eTRIANGLEMESH }; };
template <> struct PxcGeometryTraits<PxTetrahedronMeshGeometryLL> { enum { TypeID = PxGeometryType::eTETRAHEDRONMESH }; };
template <> struct PxcGeometryTraits<PxHeightFieldGeometryLL> { enum { TypeID = PxGeometryType::eHEIGHTFIELD }; };
template <> struct PxcGeometryTraits<PxHairSystemGeometryLL> { enum { TypeID = PxGeometryType::eHAIRSYSTEM }; };
class InvalidGeometry : public PxGeometry
{
public:
PX_CUDA_CALLABLE PX_FORCE_INLINE InvalidGeometry() : PxGeometry(PxGeometryType::eINVALID) {}
};
class GeometryUnion
{
public:
// PX_SERIALIZATION
GeometryUnion(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
PX_CUDA_CALLABLE PX_FORCE_INLINE GeometryUnion() { reinterpret_cast<InvalidGeometry&>(mGeometry) = InvalidGeometry(); }
PX_CUDA_CALLABLE PX_FORCE_INLINE GeometryUnion(const PxGeometry& g) { set(g); }
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxGeometry& getGeometry() const { return reinterpret_cast<const PxGeometry&>(mGeometry); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxGeometryType::Enum getType() const { return reinterpret_cast<const PxGeometry&>(mGeometry).getType(); }
PX_CUDA_CALLABLE void set(const PxGeometry& g);
template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE Geom& get()
{
checkType<Geom>(getGeometry());
return reinterpret_cast<Geom&>(mGeometry);
}
template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE const Geom& get() const
{
checkType<Geom>(getGeometry());
return reinterpret_cast<const Geom&>(mGeometry);
}
private:
union {
void* alignment; // PT: Makes sure the class is at least aligned to pointer size. See DE6803.
PxU8 box[sizeof(PxBoxGeometry)];
PxU8 sphere[sizeof(PxSphereGeometry)];
PxU8 capsule[sizeof(PxCapsuleGeometry)];
PxU8 plane[sizeof(PxPlaneGeometry)];
PxU8 convex[sizeof(PxConvexMeshGeometryLL)];
PxU8 particleSystem[sizeof(PxParticleSystemGeometryLL)];
PxU8 mesh[sizeof(PxTriangleMeshGeometryLL)];
PxU8 tetMesh[sizeof(PxTetrahedronMeshGeometryLL)];
PxU8 heightfield[sizeof(PxHeightFieldGeometryLL)];
PxU8 hairsystem[sizeof(PxHairSystemGeometryLL)];
PxU8 custom[sizeof(PxCustomGeometry)];
PxU8 invalid[sizeof(InvalidGeometry)];
} mGeometry;
};
struct PxShapeCoreFlag
{
enum Enum
{
eOWNS_MATERIAL_IDX_MEMORY = (1<<0), // PT: for de-serialization to avoid deallocating material index list. Moved there from Sc::ShapeCore (since one byte was free).
eIS_EXCLUSIVE = (1<<1), // PT: shape's exclusive flag
eIDT_TRANSFORM = (1<<2), // PT: true if PxsShapeCore::transform is identity
eSOFT_BODY_SHAPE = (1<<3), // True if this shape is a soft body shape
eCLOTH_SHAPE = (1<<4) // True if this shape is a cloth shape
};
};
typedef PxFlags<PxShapeCoreFlag::Enum,PxU8> PxShapeCoreFlags;
PX_FLAGS_OPERATORS(PxShapeCoreFlag::Enum,PxU8)
struct PxsShapeCore
{
PxsShapeCore()
{
setDensityForFluid(800.0f);
}
// PX_SERIALIZATION
PxsShapeCore(const PxEMPTY) : mShapeCoreFlags(PxEmpty), mGeometry(PxEmpty) {}
//~PX_SERIALIZATION
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
protected:
#endif
PX_ALIGN_PREFIX(16)
PxTransform mTransform PX_ALIGN_SUFFIX(16); // PT: Offset 0
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
public:
#endif
PX_FORCE_INLINE const PxTransform& getTransform() const
{
return mTransform;
}
PX_FORCE_INLINE void setTransform(const PxTransform& t)
{
mTransform = t;
if(t.p.isZero() && t.q.isIdentity())
mShapeCoreFlags.raise(PxShapeCoreFlag::eIDT_TRANSFORM);
else
mShapeCoreFlags.clear(PxShapeCoreFlag::eIDT_TRANSFORM);
}
PxReal mContactOffset; // PT: Offset 28
PxU8 mShapeFlags; // PT: Offset 32 !< API shape flags // PT: TODO: use PxShapeFlags here. Needs to move flags to separate file.
PxShapeCoreFlags mShapeCoreFlags; // PT: Offset 33
PxU16 mMaterialIndex; // PT: Offset 34
PxReal mRestOffset; // PT: Offset 36 - same as the API property of the same name - PT: moved from Sc::ShapeCore to fill padding bytes
GeometryUnion mGeometry; // PT: Offset 40
PxReal mTorsionalRadius; // PT: Offset 104 - PT: moved from Sc::ShapeCore to fill padding bytes
PxReal mMinTorsionalPatchRadius; // PT: Offset 108 - PT: moved from Sc::ShapeCore to fill padding bytes
PX_FORCE_INLINE float getDensityForFluid() const
{
return mGeometry.getGeometry().mTypePadding;
}
PX_FORCE_INLINE void setDensityForFluid(float density)
{
const_cast<PxGeometry&>(mGeometry.getGeometry()).mTypePadding = density;
}
};
PX_COMPILE_TIME_ASSERT( sizeof(GeometryUnion) <= 64); // PT: if you break this one I will not be happy
PX_COMPILE_TIME_ASSERT( (sizeof(PxsShapeCore)&0xf) == 0);
}
#endif
| 9,715 | C | 35.253731 | 167 | 0.732373 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsFEMSoftBodyMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_FEM_MATERIAL_CORE_H
#define PXS_FEM_MATERIAL_CORE_H
#include "PxFEMSoftBodyMaterial.h"
#include "PxsMaterialShared.h"
namespace physx
{
PX_FORCE_INLINE PX_CUDA_CALLABLE PxU16 toUniformU16(PxReal f)
{
f = PxClamp(f, 0.0f, 1.0f);
return PxU16(f * 65535.0f);
}
PX_FORCE_INLINE PX_CUDA_CALLABLE PxReal toUniformReal(PxU16 v)
{
return PxReal(v) * (1.0f / 65535.0f);
}
PX_ALIGN_PREFIX(16) struct PxsFEMSoftBodyMaterialData
{
PxReal youngs; //4
PxReal poissons; //8
PxReal dynamicFriction; //12
PxReal damping; //16
PxU16 dampingScale; //20, known to be in the range of 0...1. Mapped to integer range 0...65535
PxU16 materialModel; //22
PxReal deformThreshold; //24
PxReal deformLowLimitRatio; //28
PxReal deformHighLimitRatio; //32
PX_CUDA_CALLABLE PxsFEMSoftBodyMaterialData() :
youngs (1.e+6f),
poissons (0.45f),
dynamicFriction (0.0f),
damping (0.0f),
//dampingScale (0),
materialModel (PxFEMSoftBodyMaterialModel::eCO_ROTATIONAL),
deformThreshold (PX_MAX_F32),
deformLowLimitRatio (1.0f),
deformHighLimitRatio(1.0f)
{}
PxsFEMSoftBodyMaterialData(const PxEMPTY) {}
}PX_ALIGN_SUFFIX(16);
typedef MaterialCoreT<PxsFEMSoftBodyMaterialData, PxFEMSoftBodyMaterial> PxsFEMSoftBodyMaterialCore;
} //namespace phyxs
#endif
| 3,047 | C | 35.722891 | 101 | 0.737118 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIAL_MANAGER_H
#define PXS_MATERIAL_MANAGER_H
#include "PxsMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsPBDMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "foundation/PxAlignedMalloc.h"
namespace physx
{
struct PxsMaterialInfo
{
PxU16 mMaterialIndex0;
PxU16 mMaterialIndex1;
};
template<class MaterialCore>
class PxsMaterialManagerT
{
public:
PxsMaterialManagerT()
{
const PxU32 matCount = 128;
materials = reinterpret_cast<MaterialCore*>(physx::PxAlignedAllocator<16>().allocate(sizeof(MaterialCore)*matCount, PX_FL));
maxMaterials = matCount;
for(PxU32 i=0; i<matCount; ++i)
{
materials[i].mMaterialIndex = MATERIAL_INVALID_HANDLE;
}
}
~PxsMaterialManagerT()
{
physx::PxAlignedAllocator<16>().deallocate(materials);
}
void setMaterial(MaterialCore* mat)
{
const PxU16 materialIndex = mat->mMaterialIndex;
resize(PxU32(materialIndex) + 1);
materials[materialIndex] = *mat;
}
void updateMaterial(MaterialCore* mat)
{
materials[mat->mMaterialIndex] =*mat;
}
void removeMaterial(MaterialCore* mat)
{
mat->mMaterialIndex = MATERIAL_INVALID_HANDLE;
}
PX_FORCE_INLINE MaterialCore* getMaterial(const PxU32 index)const
{
PX_ASSERT(index < maxMaterials);
return &materials[index];
}
PxU32 getMaxSize()const
{
return maxMaterials;
}
void resize(PxU32 minValueForMax)
{
if(maxMaterials>=minValueForMax)
return;
const PxU32 numMaterials = maxMaterials;
maxMaterials = (minValueForMax+31)&~31;
MaterialCore* mat = reinterpret_cast<MaterialCore*>(physx::PxAlignedAllocator<16>().allocate(sizeof(MaterialCore)*maxMaterials, PX_FL));
for(PxU32 i=0; i<numMaterials; ++i)
mat[i] = materials[i];
for(PxU32 i = numMaterials; i < maxMaterials; ++i)
mat[i].mMaterialIndex = MATERIAL_INVALID_HANDLE;
physx::PxAlignedAllocator<16>().deallocate(materials);
materials = mat;
}
MaterialCore* materials;//make sure materials's start address is 16 bytes align
PxU32 maxMaterials;
PxU32 mPad;
#if !PX_P64_FAMILY
PxU32 mPad2;
#endif
};
//This class is used for forward declaration
class PxsMaterialManager : public PxsMaterialManagerT<PxsMaterialCore>
{
};
class PxsFEMMaterialManager : public PxsMaterialManagerT<PxsFEMSoftBodyMaterialCore>
{
};
class PxsFEMClothMaterialManager : public PxsMaterialManagerT<PxsFEMClothMaterialCore>
{
};
class PxsPBDMaterialManager : public PxsMaterialManagerT<PxsPBDMaterialCore>
{
};
class PxsFLIPMaterialManager : public PxsMaterialManagerT<PxsFLIPMaterialCore>
{
};
class PxsMPMMaterialManager : public PxsMaterialManagerT<PxsMPMMaterialCore>
{
};
template<class MaterialCore>
class PxsMaterialManagerIterator
{
public:
PxsMaterialManagerIterator(PxsMaterialManagerT<MaterialCore>& manager) : mManager(manager), mIndex(0)
{
}
bool getNextMaterial(MaterialCore*& materialCore)
{
const PxU32 maxSize = mManager.getMaxSize();
PxU32 index = mIndex;
while(index < maxSize && mManager.getMaterial(index)->mMaterialIndex == MATERIAL_INVALID_HANDLE)
index++;
materialCore = NULL;
if(index < maxSize)
materialCore = mManager.getMaterial(index++);
mIndex = index;
return materialCore!=NULL;
}
private:
PxsMaterialManagerIterator& operator=(const PxsMaterialManagerIterator&);
PxsMaterialManagerT<MaterialCore>& mManager;
PxU32 mIndex;
};
}
#endif
| 5,236 | C | 28.094444 | 140 | 0.744079 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvDynamics.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_DYNAMICS_H
#define PXV_DYNAMICS_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxIntrinsics.h"
#include "PxRigidDynamic.h"
namespace physx
{
/*!
\file
Dynamics interface.
*/
struct PxsRigidCore
{
PxsRigidCore() : mFlags(0), solverIterationCounts(0) {}
PxsRigidCore(const PxEMPTY) : mFlags(PxEmpty) {}
PX_ALIGN_PREFIX(16)
PxTransform body2World PX_ALIGN_SUFFIX(16);
PxRigidBodyFlags mFlags; // API body flags
PxU16 solverIterationCounts; // vel iters are in low word and pos iters in high word.
PX_FORCE_INLINE PxU32 isKinematic() const { return mFlags & PxRigidBodyFlag::eKINEMATIC; }
PX_FORCE_INLINE PxU32 hasCCD() const { return mFlags & PxRigidBodyFlag::eENABLE_CCD; }
PX_FORCE_INLINE PxU32 hasCCDFriction() const { return mFlags & PxRigidBodyFlag::eENABLE_CCD_FRICTION; }
PX_FORCE_INLINE PxU32 hasIdtBody2Actor() const { return mFlags & PxRigidBodyFlag::eRESERVED; }
};
PX_COMPILE_TIME_ASSERT(sizeof(PxsRigidCore) == 32);
#define PXV_CONTACT_REPORT_DISABLED PX_MAX_F32
struct PxsBodyCore : public PxsRigidCore
{
PxsBodyCore() : PxsRigidCore() { fixedBaseLink = PxU8(0); }
PxsBodyCore(const PxEMPTY) : PxsRigidCore(PxEmpty) {}
PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return body2Actor; }
PX_FORCE_INLINE void setBody2Actor(const PxTransform& t)
{
if(t.p.isZero() && t.q.isIdentity())
mFlags.raise(PxRigidBodyFlag::eRESERVED);
else
mFlags.clear(PxRigidBodyFlag::eRESERVED);
body2Actor = t;
}
protected:
PxTransform body2Actor;
public:
PxReal ccdAdvanceCoefficient; //64
PxVec3 linearVelocity;
PxReal maxPenBias;
PxVec3 angularVelocity;
PxReal contactReportThreshold; //96
PxReal maxAngularVelocitySq;
PxReal maxLinearVelocitySq;
PxReal linearDamping;
PxReal angularDamping; //112
PxVec3 inverseInertia;
PxReal inverseMass; //128
PxReal maxContactImpulse;
PxReal sleepThreshold;
union
{
PxReal freezeThreshold;
PxReal cfmScale;
};
PxReal wakeCounter; //144 this is authoritative wakeCounter
PxReal solverWakeCounter; //this is calculated by the solver when it performs sleepCheck. It is committed to wakeCounter in ScAfterIntegrationTask if the body is still awake.
PxU32 numCountedInteractions;
PxReal offsetSlop; //Slop value used to snap contact line of action back in-line with the COM
PxU8 isFastMoving; //This could be a single bit but it's a u8 at the moment for simplicity's sake
PxU8 disableGravity; //This could be a single bit but it's a u8 at the moment for simplicity's sake
PxRigidDynamicLockFlags lockFlags; //This is u8.
PxU8 fixedBaseLink; //160 This indicates whether the articulation link has PxArticulationFlag::eFIX_BASE. All fits into 16 byte alignment
// PT: moved from Sc::BodyCore ctor - we don't want to duplicate all this in immediate mode
PX_FORCE_INLINE void init( const PxTransform& bodyPose,
const PxVec3& inverseInertia_, PxReal inverseMass_,
PxReal wakeCounter_, PxReal scaleSpeed,
PxReal linearDamping_, PxReal angularDamping_,
PxReal maxLinearVelocitySq_, PxReal maxAngularVelocitySq_,
PxActorType::Enum type)
{
PX_ASSERT(bodyPose.p.isFinite());
PX_ASSERT(bodyPose.q.isFinite());
// PT: TODO: unify naming convention
// From PxsRigidCore
body2World = bodyPose;
mFlags = PxRigidBodyFlags();
solverIterationCounts = (1 << 8) | 4;
setBody2Actor(PxTransform(PxIdentity));
ccdAdvanceCoefficient = 0.15f;
linearVelocity = PxVec3(0.0f);
maxPenBias = -1e32f;//-PX_MAX_F32;
angularVelocity = PxVec3(0.0f);
contactReportThreshold = PXV_CONTACT_REPORT_DISABLED;
maxAngularVelocitySq = maxAngularVelocitySq_;
maxLinearVelocitySq = maxLinearVelocitySq_;
linearDamping = linearDamping_;
angularDamping = angularDamping_;
inverseInertia = inverseInertia_;
inverseMass = inverseMass_;
maxContactImpulse = 1e32f;// PX_MAX_F32;
sleepThreshold = 5e-5f * scaleSpeed * scaleSpeed;
if(type == PxActorType::eARTICULATION_LINK)
cfmScale = 0.025f;
else
freezeThreshold = 2.5e-5f * scaleSpeed * scaleSpeed;
wakeCounter = wakeCounter_;
offsetSlop = 0.f;
// PT: this one is not initialized?
//solverWakeCounter
// PT: these are initialized in BodySim ctor
//numCountedInteractions;
//numBodyInteractions;
isFastMoving = false;
disableGravity = false;
lockFlags = PxRigidDynamicLockFlags(0);
}
};
PX_COMPILE_TIME_ASSERT(sizeof(PxsBodyCore) == 160);
}
#endif
| 6,401 | C | 36.00578 | 180 | 0.732698 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsFLIPMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_FLIP_MATERIAL_CORE_H
#define PXS_FLIP_MATERIAL_CORE_H
#include "PxParticleGpu.h"
#include "PxsMaterialShared.h"
namespace physx
{
struct PxsFLIPMaterialData : public PxsParticleMaterialData
{
PxsFLIPMaterialData() {} // PT: TODO: ctor leaves things uninitialized, is that by design?
PxsFLIPMaterialData(const PxEMPTY) {}
PxReal viscosity; //24
PxReal surfaceTension; //28
};
typedef MaterialCoreT<PxsFLIPMaterialData, PxFLIPMaterial> PxsFLIPMaterialCore;
} //namespace phyxs
#endif
| 2,216 | C | 42.470587 | 95 | 0.765343 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialShared.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIAL_SHARED_H
#define PXS_MATERIAL_SHARED_H
#include "foundation/PxSimpleTypes.h"
namespace physx
{
#define MATERIAL_INVALID_HANDLE 0xffff
class PxOutputStream;
template<class MaterialDataT, class PxMaterialT>
class MaterialCoreT : public MaterialDataT
{
public:
MaterialCoreT(const MaterialDataT& desc) : MaterialDataT(desc), mMaterial(NULL), mMaterialIndex(MATERIAL_INVALID_HANDLE) {}
MaterialCoreT() : mMaterial(NULL), mMaterialIndex(MATERIAL_INVALID_HANDLE) {}
MaterialCoreT(const PxEMPTY) : MaterialDataT(PxEmpty) {}
~MaterialCoreT() {}
PxMaterialT* mMaterial; // PT: TODO: eventually this could just be a base PxBaseMaterial class instead of a templated param
PxU16 mMaterialIndex; //handle assign by the handle manager
static void getBinaryMetaData(PxOutputStream& stream);
};
} //namespace phyxs
#endif
| 2,599 | C | 43.067796 | 129 | 0.755675 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMPMMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MPM_MATERIAL_CORE_H
#define PXS_MPM_MATERIAL_CORE_H
#include "PxParticleGpu.h"
#include "PxsMaterialShared.h"
#include "PxMPMMaterial.h"
namespace physx
{
struct PxsMPMMaterialData : public PxsParticleMaterialData
{
PxsMPMMaterialData() {} // PT: TODO: ctor leaves things uninitialized, is that by design?
PxsMPMMaterialData(const PxEMPTY) {}
PxIntBool isPlastic; //24
PxReal youngsModulus; //28
PxReal poissonsRatio; //32
PxReal hardening; //snow //36
PxReal criticalCompression; //snow //40
PxReal criticalStretch; //snow //44
//Only used when damage tracking is activated in the cutting flags
PxReal tensileDamageSensitivity; //48
PxReal compressiveDamageSensitivity; //52
PxReal attractiveForceResidual; //56
PxReal sandFrictionAngle; //sand //60
PxReal yieldStress; //von Mises //64
PxMPMMaterialModel::Enum materialModel; //68
PxMPMCuttingFlags cuttingFlags; //72
PxReal density; //76;
PxReal stretchAndShearDamping; //80;
PxReal rotationalDamping; //84;
};
typedef MaterialCoreT<PxsMPMMaterialData, PxMPMMaterial> PxsMPMMaterialCore;
} //namespace phyxs
#endif
| 2,888 | C | 38.575342 | 94 | 0.74723 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIAL_CORE_H
#define PXS_MATERIAL_CORE_H
#include "PxMaterial.h"
#include "foundation/PxUtilities.h"
#include "PxsMaterialShared.h"
namespace physx
{
struct PxsMaterialData
{
PxReal dynamicFriction; //4
PxReal staticFriction; //8
PxReal restitution; //12
PxReal damping; //16
PxMaterialFlags flags; //18
PxU8 fricCombineMode; //19 PxCombineMode::Enum
PxU8 restCombineMode; //20 PxCombineMode::Enum
PxsMaterialData() :
dynamicFriction (0.0f),
staticFriction (0.0f),
restitution (0.0f),
damping (0.0f),
flags (PxMaterialFlag::eIMPROVED_PATCH_FRICTION),
fricCombineMode (PxCombineMode::eAVERAGE),
restCombineMode (PxCombineMode::eAVERAGE)
{}
PxsMaterialData(const PxEMPTY) {}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxCombineMode::Enum getFrictionCombineMode() const { return PxCombineMode::Enum(fricCombineMode); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxCombineMode::Enum getRestitutionCombineMode() const { return PxCombineMode::Enum(restCombineMode); }
PX_FORCE_INLINE void setFrictionCombineMode(PxCombineMode::Enum combineMode) { fricCombineMode = PxTo8(combineMode); }
PX_FORCE_INLINE void setRestitutionCombineMode(PxCombineMode::Enum combineMode) { restCombineMode = PxTo8(combineMode); }
};
typedef MaterialCoreT<PxsMaterialData, PxMaterial> PxsMaterialCore;
} //namespace phyxs
#endif
| 3,091 | C | 42.549295 | 137 | 0.757037 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvGlobals.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_GLOBALS_H
#define PXV_GLOBALS_H
#include "PxvConfig.h"
#include "foundation/PxBasicTemplates.h"
namespace physx
{
/*!
\file
PhysX Low-level, Memory management
*/
/************************************************************************/
/* Error Handling */
/************************************************************************/
enum PxvErrorCode
{
PXD_ERROR_NO_ERROR = 0,
PXD_ERROR_INVALID_PARAMETER,
PXD_ERROR_INVALID_PARAMETER_SIZE,
PXD_ERROR_INTERNAL_ERROR,
PXD_ERROR_NOT_IMPLEMENTED,
PXD_ERROR_NO_CONTEXT,
PXD_ERROR_NO_TASK_MANAGER,
PXD_ERROR_WARNING
};
class PxShape;
class PxRigidActor;
struct PxsShapeCore;
struct PxsRigidCore;
struct PxvOffsetTable
{
PX_FORCE_INLINE PxvOffsetTable() {}
PX_FORCE_INLINE const PxShape* convertPxsShape2Px(const PxsShapeCore* pxs) const
{
return PxPointerOffset<const PxShape*>(pxs, pxsShapeCore2PxShape);
}
PX_FORCE_INLINE const PxRigidActor* convertPxsRigidCore2PxRigidBody(const PxsRigidCore* pxs) const
{
return PxPointerOffset<const PxRigidActor*>(pxs, pxsRigidCore2PxRigidBody);
}
PX_FORCE_INLINE const PxRigidActor* convertPxsRigidCore2PxRigidStatic(const PxsRigidCore* pxs) const
{
return PxPointerOffset<const PxRigidActor*>(pxs, pxsRigidCore2PxRigidStatic);
}
ptrdiff_t pxsShapeCore2PxShape;
ptrdiff_t pxsRigidCore2PxRigidBody;
ptrdiff_t pxsRigidCore2PxRigidStatic;
};
extern PxvOffsetTable gPxvOffsetTable;
/*!
Initialize low-level implementation.
*/
void PxvInit(const PxvOffsetTable& offsetTable);
/*!
Shut down low-level implementation.
*/
void PxvTerm();
#if PX_SUPPORT_GPU_PHYSX
class PxPhysXGpu* PxvGetPhysXGpu(bool createIfNeeded);
void PxvReleasePhysXGpu(PxPhysXGpu*);
#endif
}
#endif
| 3,459 | C | 31.037037 | 101 | 0.728245 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvConfig.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_CONFIG_H
#define PXV_CONFIG_H
/*! \file internal top level include file for lowlevel. */
#include "PxPhysXConfig.h"
/************************************************************************/
/* Compiler workarounds */
/************************************************************************/
#if PX_VC
#pragma warning(disable: 4355 ) // "this" used in base member initializer list
#pragma warning(disable: 4146 ) // unary minus operator applied to unsigned type.
#endif
#endif
| 2,240 | C | 48.799999 | 81 | 0.693304 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvSimStats.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_SIM_STATS_H
#define PXV_SIM_STATS_H
#include "foundation/PxAssert.h"
#include "foundation/PxMemory.h"
#include "geometry/PxGeometry.h"
namespace physx
{
/*!
\file
Context handling
*/
/************************************************************************/
/* Context handling, types */
/************************************************************************/
/*!
Description: contains statistics for the simulation.
*/
struct PxvSimStats
{
PxvSimStats() { clearAll(); }
void clearAll() { PxMemZero(this, sizeof(PxvSimStats)); } // set counters to zero
PX_FORCE_INLINE void incCCDPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
mNbCCDPairs[g0][g1]++;
}
PX_FORCE_INLINE void decCCDPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
PX_ASSERT(mNbCCDPairs[g0][g1]);
mNbCCDPairs[g0][g1]--;
}
PX_FORCE_INLINE void incModifiedContactPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
mNbModifiedContactPairs[g0][g1]++;
}
PX_FORCE_INLINE void decModifiedContactPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
PX_ASSERT(mNbModifiedContactPairs[g0][g1]);
mNbModifiedContactPairs[g0][g1]--;
}
// PT: those guys are now persistent and shouldn't be cleared each frame
PxU32 mNbDiscreteContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbCCDPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbModifiedContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbDiscreteContactPairsTotal; // PT: sum of mNbDiscreteContactPairs, i.e. number of pairs reaching narrow phase
PxU32 mNbDiscreteContactPairsWithCacheHits;
PxU32 mNbDiscreteContactPairsWithContacts;
PxU32 mNbActiveConstraints;
PxU32 mNbActiveDynamicBodies;
PxU32 mNbActiveKinematicBodies;
PxU32 mNbAxisSolverConstraints;
PxU32 mTotalCompressedContactSize;
PxU32 mTotalConstraintSize;
PxU32 mPeakConstraintBlockAllocations;
PxU32 mNbNewPairs;
PxU32 mNbLostPairs;
PxU32 mNbNewTouches;
PxU32 mNbLostTouches;
PxU32 mNbPartitions;
};
}
#endif
| 4,082 | C | 35.455357 | 119 | 0.727095 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsPBDMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_PBD_MATERIAL_CORE_H
#define PXS_PBD_MATERIAL_CORE_H
#include "PxParticleGpu.h"
#include "PxsMaterialShared.h"
namespace physx
{
struct PxsPBDMaterialData : public PxsParticleMaterialData
{
PxsPBDMaterialData() {} // PT: TODO: ctor leaves things uninitialized, is that by design?
PxsPBDMaterialData(const PxEMPTY) {}
PxU32 flags; //24
PxReal viscosity; //28
PxReal vorticityConfinement; //32
PxReal surfaceTension; //36
PxReal cohesion; //40
PxReal lift; //44
PxReal drag; //48
PxReal cflCoefficient; //52
PxReal particleFrictionScale; //56
PxReal particleAdhesionScale; //60
};
typedef MaterialCoreT<PxsPBDMaterialData, PxPBDMaterial> PxsPBDMaterialCore;
} //namespace phyxs
#endif
| 2,462 | C | 40.745762 | 94 | 0.750609 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsFEMClothMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_FEM_CLOTH_MATERIAL_CORE_H
#define PXS_FEM_CLOTH_MATERIAL_CORE_H
#include "PxFEMClothMaterial.h"
#include "PxsMaterialShared.h"
namespace physx
{
PX_ALIGN_PREFIX(16) struct PxsFEMClothMaterialData
{
PxReal youngs; //4
PxReal poissons; //8
PxReal dynamicFriction; //12
PxReal thickness; //16
PX_CUDA_CALLABLE PxsFEMClothMaterialData()
: youngs(1.e+6f), poissons(0.45f), dynamicFriction(0.0f), thickness(0.0f)
{}
PxsFEMClothMaterialData(const PxEMPTY) {}
}PX_ALIGN_SUFFIX(16);
typedef MaterialCoreT<PxsFEMClothMaterialData, PxFEMClothMaterial> PxsFEMClothMaterialCore;
} //namespace phyxs
#endif
| 2,351 | C | 40.263157 | 92 | 0.757125 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_MANAGER_H
#define PXV_MANAGER_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMemory.h"
#include "PxvConfig.h"
#include "PxvGeometry.h"
namespace physx
{
/*!
\file
Manager interface
*/
/************************************************************************/
/* Managers */
/************************************************************************/
class PxsContactManager;
struct PxsRigidCore;
struct PxsShapeCore;
class PxsRigidBody;
/*!
Type of PXD_MANAGER_CCD_MODE property
*/
enum PxvContactManagerCCDMode
{
PXD_MANAGER_CCD_NONE,
PXD_MANAGER_CCD_LINEAR
};
/*!
Manager descriptor
*/
struct PxvManagerDescRigidRigid
{
/*!
Manager user data
\sa PXD_MANAGER_USER_DATA
*/
//void* userData;
/*!
Dominance setting for one way interactions.
A dominance of 0 means the corresp. body will
not be pushable by the other body in the constraint.
\sa PXD_MANAGER_DOMINANCE0
*/
PxU8 dominance0;
/*!
Dominance setting for one way interactions.
A dominance of 0 means the corresp. body will
not be pushable by the other body in the constraint.
\sa PXD_MANAGER_DOMINANCE1
*/
PxU8 dominance1;
/*!
PxsRigidBodies
*/
PxsRigidBody* rigidBody0;
PxsRigidBody* rigidBody1;
/*!
Shape Core structures
*/
const PxsShapeCore* shapeCore0;
const PxsShapeCore* shapeCore1;
/*!
Body Core structures
*/
PxsRigidCore* rigidCore0;
PxsRigidCore* rigidCore1;
/*!
Enable contact information reporting.
*/
int reportContactInfo;
/*!
Enable contact impulse threshold reporting.
*/
int hasForceThreshold;
/*!
Enable generated contacts to be changeable
*/
int contactChangeable;
/*!
Disable strong friction
*/
//int disableStrongFriction;
/*!
Contact resolution rest distance.
*/
PxReal restDistance;
/*!
Disable contact response
*/
int disableResponse;
/*!
Disable discrete contact generation
*/
int disableDiscreteContact;
/*!
Disable CCD contact generation
*/
int disableCCDContact;
/*!
Is connected to an articulation (1 - first body, 2 - second body)
*/
int hasArticulations;
/*!
is connected to a dynamic (1 - first body, 2 - second body)
*/
int hasDynamics;
/*!
Is the pair touching? Use when re-creating the manager with prior knowledge about touch status.
positive: pair is touching
0: touch state unknown (this is a new pair)
negative: pair is not touching
Default is 0
*/
int hasTouch;
/*!
Identifies whether body 1 is kinematic. We can treat kinematics as statics and embed velocity into constraint
because kinematic bodies' velocities will not change
*/
bool body1Kinematic;
/*
Index entries into the transform cache for shape 0
*/
PxU32 transformCache0;
/*
Index entries into the transform cache for shape 1
*/
PxU32 transformCache1;
PxvManagerDescRigidRigid()
{
PxMemSet(this, 0, sizeof(PxvManagerDescRigidRigid));
dominance0 = 1u;
dominance1 = 1u;
}
};
/*!
Report struct for contact manager touch reports
*/
struct PxvContactManagerTouchEvent
{
void* userData;
// PT: only useful to search for places where we get/set this specific user data
PX_FORCE_INLINE void setCMTouchEventUserData(void* ud) { userData = ud; }
PX_FORCE_INLINE void* getCMTouchEventUserData() const { return userData; }
};
}
#endif
| 5,101 | C | 22.730232 | 110 | 0.709273 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpMemBlockPool.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxMath.h"
#include "PxcNpMemBlockPool.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxInlineArray.h"
#include "PxcScratchAllocator.h"
using namespace physx;
PxcNpMemBlockPool::PxcNpMemBlockPool(PxcScratchAllocator& allocator) :
mConstraints("PxcNpMemBlockPool::mConstraints"),
mExceptionalConstraints("PxcNpMemBlockPool::mExceptionalConstraints"),
mNpCacheActiveStream(0),
mFrictionActiveStream(0),
mCCDCacheActiveStream(0),
mContactIndex(0),
mAllocatedBlocks(0),
mMaxBlocks(0),
mUsedBlocks(0),
mMaxUsedBlocks(0),
mScratchBlockAddr(0),
mNbScratchBlocks(0),
mScratchAllocator(allocator),
mPeakConstraintAllocations(0),
mConstraintAllocations(0)
{
}
void PxcNpMemBlockPool::init(PxU32 initialBlockCount, PxU32 maxBlocks)
{
mMaxBlocks = maxBlocks;
mInitialBlocks = initialBlockCount;
PxU32 reserve = PxMax<PxU32>(initialBlockCount, 64);
mConstraints.reserve(reserve);
mExceptionalConstraints.reserve(16);
mFriction[0].reserve(reserve);
mFriction[1].reserve(reserve);
mNpCache[0].reserve(reserve);
mNpCache[1].reserve(reserve);
mUnused.reserve(reserve);
setBlockCount(initialBlockCount);
}
PxU32 PxcNpMemBlockPool::getUsedBlockCount() const
{
return mUsedBlocks;
}
PxU32 PxcNpMemBlockPool::getMaxUsedBlockCount() const
{
return mMaxUsedBlocks;
}
PxU32 PxcNpMemBlockPool::getPeakConstraintBlockCount() const
{
return mPeakConstraintAllocations;
}
void PxcNpMemBlockPool::setBlockCount(PxU32 blockCount)
{
PxMutex::ScopedLock lock(mLock);
PxU32 current = getUsedBlockCount();
for(PxU32 i=current;i<blockCount;i++)
{
mUnused.pushBack(reinterpret_cast<PxcNpMemBlock *>(PX_ALLOC(PxcNpMemBlock::SIZE, "PxcNpMemBlock")));
mAllocatedBlocks++;
}
}
void PxcNpMemBlockPool::releaseUnusedBlocks()
{
PxMutex::ScopedLock lock(mLock);
while(mUnused.size())
{
PxcNpMemBlock* ptr = mUnused.popBack();
PX_FREE(ptr);
mAllocatedBlocks--;
}
}
PxcNpMemBlockPool::~PxcNpMemBlockPool()
{
// swapping twice guarantees all blocks are released from the stream pairs
swapFrictionStreams();
swapFrictionStreams();
swapNpCacheStreams();
swapNpCacheStreams();
releaseConstraintMemory();
releaseContacts();
releaseContacts();
PX_ASSERT(mUsedBlocks == 0);
flushUnused();
}
void PxcNpMemBlockPool::acquireConstraintMemory()
{
PxU32 size;
void* addr = mScratchAllocator.allocAll(size);
size = size&~(PxcNpMemBlock::SIZE-1);
PX_ASSERT(mScratchBlocks.size()==0);
mScratchBlockAddr = reinterpret_cast<PxcNpMemBlock*>(addr);
mNbScratchBlocks = size/PxcNpMemBlock::SIZE;
mScratchBlocks.resize(mNbScratchBlocks);
for(PxU32 i=0;i<mNbScratchBlocks;i++)
mScratchBlocks[i] = mScratchBlockAddr+i;
}
void PxcNpMemBlockPool::releaseConstraintMemory()
{
PxMutex::ScopedLock lock(mLock);
mPeakConstraintAllocations = mConstraintAllocations = 0;
while(mConstraints.size())
{
PxcNpMemBlock* block = mConstraints.popBack();
if(mScratchAllocator.isScratchAddr(block))
mScratchBlocks.pushBack(block);
else
{
mUnused.pushBack(block);
PX_ASSERT(mUsedBlocks>0);
mUsedBlocks--;
}
}
for(PxU32 i=0;i<mExceptionalConstraints.size();i++)
PX_FREE(mExceptionalConstraints[i]);
mExceptionalConstraints.clear();
PX_ASSERT(mScratchBlocks.size()==mNbScratchBlocks); // check we released them all
mScratchBlocks.clear();
if(mScratchBlockAddr)
{
mScratchAllocator.free(mScratchBlockAddr);
mScratchBlockAddr = 0;
mNbScratchBlocks = 0;
}
}
PxcNpMemBlock* PxcNpMemBlockPool::acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount, PxU32* peakAllocationCount, bool isScratchAllocation)
{
PxMutex::ScopedLock lock(mLock);
if(allocationCount && peakAllocationCount)
{
*peakAllocationCount = PxMax(*allocationCount + 1, *peakAllocationCount);
(*allocationCount)++;
}
// this is a bit of hack - the logic would be better placed in acquireConstraintBlock, but then we'd have to grab the mutex
// once there to check the scratch block array and once here if we fail - or, we'd need a larger refactor to separate out
// locking and acquisition.
if(isScratchAllocation && mScratchBlocks.size()>0)
{
PxcNpMemBlock* block = mScratchBlocks.popBack();
trackingArray.pushBack(block);
return block;
}
if(mUnused.size())
{
PxcNpMemBlock* block = mUnused.popBack();
trackingArray.pushBack(block);
mMaxUsedBlocks = PxMax<PxU32>(mUsedBlocks+1, mMaxUsedBlocks);
mUsedBlocks++;
return block;
}
if(mAllocatedBlocks == mMaxBlocks)
{
#if PX_CHECKED
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL,
"Reached maximum number of allocated blocks so 16k block allocation will fail!");
#endif
return NULL;
}
#if PX_CHECKED
if(mInitialBlocks)
{
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL,
"Number of required 16k memory blocks has exceeded the initial number of blocks. Allocator is being called. Consider increasing the number of pre-allocated 16k blocks.");
}
#endif
// increment here so that if we hit the limit in separate threads we won't overallocated
mAllocatedBlocks++;
PxcNpMemBlock* block = reinterpret_cast<PxcNpMemBlock*>(PX_ALLOC(sizeof(PxcNpMemBlock), "PxcNpMemBlock"));
if(block)
{
trackingArray.pushBack(block);
mMaxUsedBlocks = PxMax<PxU32>(mUsedBlocks+1, mMaxUsedBlocks);
mUsedBlocks++;
}
else
mAllocatedBlocks--;
return block;
}
PxU8* PxcNpMemBlockPool::acquireExceptionalConstraintMemory(PxU32 size)
{
PxU8* memory = reinterpret_cast<PxU8*>(PX_ALLOC(size, "PxcNpExceptionalMemory"));
if(memory)
{
PxMutex::ScopedLock lock(mLock);
mExceptionalConstraints.pushBack(memory);
}
return memory;
}
void PxcNpMemBlockPool::release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount)
{
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mUsedBlocks >= deadArray.size());
mUsedBlocks -= deadArray.size();
if(allocationCount)
{
*allocationCount -= deadArray.size();
}
while(deadArray.size())
{
PxcNpMemBlock* block = deadArray.popBack();
for(PxU32 a = 0; a < mUnused.size(); ++a)
{
PX_ASSERT(mUnused[a] != block);
}
mUnused.pushBack(block);
}
}
void PxcNpMemBlockPool::flushUnused()
{
while(mUnused.size())
{
PxcNpMemBlock* ptr = mUnused.popBack();
PX_FREE(ptr);
}
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireConstraintBlock()
{
// we track the scratch blocks in the constraint block array, because the code in acquireMultipleConstraintBlocks
// assumes that acquired blocks are listed there.
return acquire(mConstraints);
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireConstraintBlock(PxcNpMemBlockArray& memBlocks)
{
return acquire(memBlocks, &mConstraintAllocations, &mPeakConstraintAllocations, true);
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireContactBlock()
{
return acquire(mContacts[mContactIndex], NULL, NULL, true);
}
void PxcNpMemBlockPool::releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks)
{
PxMutex::ScopedLock lock(mLock);
while(memBlocks.size())
{
PxcNpMemBlock* block = memBlocks.popBack();
if(mScratchAllocator.isScratchAddr(block))
mScratchBlocks.pushBack(block);
else
{
mUnused.pushBack(block);
PX_ASSERT(mUsedBlocks>0);
mUsedBlocks--;
}
}
}
void PxcNpMemBlockPool::releaseContacts()
{
//releaseConstraintBlocks(mContacts);
release(mContacts[1-mContactIndex]);
mContactIndex = 1-mContactIndex;
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireFrictionBlock()
{
return acquire(mFriction[mFrictionActiveStream]);
}
void PxcNpMemBlockPool::swapFrictionStreams()
{
release(mFriction[1-mFrictionActiveStream]);
mFrictionActiveStream = 1-mFrictionActiveStream;
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireNpCacheBlock()
{
return acquire(mNpCache[mNpCacheActiveStream]);
}
void PxcNpMemBlockPool::swapNpCacheStreams()
{
release(mNpCache[1-mNpCacheActiveStream]);
mNpCacheActiveStream = 1-mNpCacheActiveStream;
}
| 9,542 | C++ | 26.501441 | 173 | 0.763991 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcContactCache.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcContactCache.h"
#include "PxsContactManager.h"
#include "foundation/PxUtilities.h"
#include "PxcNpCache.h"
#include "CmMatrix34.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
//#define ENABLE_CONTACT_CACHE_STATS
#ifdef ENABLE_CONTACT_CACHE_STATS
static PxU32 gNbCalls;
static PxU32 gNbHits;
#endif
void PxcClearContactCacheStats()
{
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbCalls = 0;
gNbHits = 0;
#endif
}
void PxcDisplayContactCacheStats()
{
#ifdef ENABLE_CONTACT_CACHE_STATS
pxPrintf("%d|%d (%f)\n", gNbHits, gNbCalls, gNbCalls ? float(gNbHits)/float(gNbCalls) : 0.0f);
#endif
}
namespace physx
{
const bool g_CanUseContactCache[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
false, //PxcContactSphereSphere
false, //PxcContactSpherePlane
true, //PxcContactSphereCapsule
false, //PxcContactSphereBox
true, //PxcContactSphereConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactSphereMesh
true, //PxcContactSphereHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::ePLANE
{
false, //-
false, //PxcInvalidContactPair
true, //PxcContactPlaneCapsule
true, //PxcContactPlaneBox
true, //PxcContactPlaneConvex
false, //ParticleSystem
true, //SoftBody
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eCAPSULE
{
false, //-
false, //-
true, //PxcContactCapsuleCapsule
true, //PxcContactCapsuleBox
true, //PxcContactCapsuleConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactCapsuleMesh
true, //PxcContactCapsuleHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eBOX
{
false, //-
false, //-
false, //-
true, //PxcContactBoxBox
true, //PxcContactBoxConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactBoxMesh
true, //PxcContactBoxHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eCONVEXMESH
{
false, //-
false, //-
false, //-
false, //-
true, //PxcContactConvexConvex
false, //-
true, //-
true, //PxcContactConvexMesh2
true, //PxcContactConvexHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::ePARTICLESYSTEM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eTETRAHEDRONMESH
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eTRIANGLEMESH
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eHEIGHTFIELD
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eHAIRSYSTEM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
},
//PxGeometryType::eCUSTOM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_CanUseContactCache) / sizeof(g_CanUseContactCache[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
static PX_FORCE_INLINE void updateContact( PxContactPoint& dst, const PxcLocalContactsCache& contactsData,
const PxMat34& world0, const PxMat34& world1,
const PxVec3& point, const PxVec3& normal, float separation)
{
const PxVec3 tmp0 = contactsData.mTransform0.transformInv(point);
const PxVec3 worldpt0 = world0.transform(tmp0);
const PxVec3 tmp1 = contactsData.mTransform1.transformInv(point);
const PxVec3 worldpt1 = world1.transform(tmp1);
const PxVec3 motion = worldpt0 - worldpt1;
dst.normal = normal;
dst.point = (worldpt0 + worldpt1)*0.5f;
//dst.point = point;
dst.separation = separation + motion.dot(normal);
}
static PX_FORCE_INLINE void prefetchData128(PxU8* PX_RESTRICT ptr, PxU32 size)
{
// PT: always prefetch the cache line containing our address (which unfortunately won't be aligned to 128 most of the time)
PxPrefetchLine(ptr, 0);
// PT: compute start offset of our data within its cache line
const PxU32 startOffset = PxU32(size_t(ptr)&127);
// PT: prefetch next cache line if needed
if(startOffset+size>128)
PxPrefetchLine(ptr+128, 0);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, const PxVec3& v)
{
*reinterpret_cast<PxVec3*>(bytes) = v;
return bytes + sizeof(PxVec3);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, PxReal v)
{
*reinterpret_cast<PxReal*>(bytes) = v;
return bytes + sizeof(PxReal);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, PxU32 v)
{
*reinterpret_cast<PxU32*>(bytes) = v;
return bytes + sizeof(PxU32);
}
//PxU32 gContactCache_NbCalls = 0;
//PxU32 gContactCache_NbHits = 0;
static PX_FORCE_INLINE PxReal maxComponentDeltaPos(const PxTransform& t0, const PxTransform& t1)
{
PxReal delta = PxAbs(t0.p.x - t1.p.x);
delta = PxMax(delta, PxAbs(t0.p.y - t1.p.y));
delta = PxMax(delta, PxAbs(t0.p.z - t1.p.z));
return delta;
}
static PX_FORCE_INLINE PxReal maxComponentDeltaRot(const PxTransform& t0, const PxTransform& t1)
{
PxReal delta = PxAbs(t0.q.x - t1.q.x);
delta = PxMax(delta, PxAbs(t0.q.y - t1.q.y));
delta = PxMax(delta, PxAbs(t0.q.z - t1.q.z));
delta = PxMax(delta, PxAbs(t0.q.w - t1.q.w));
return delta;
}
bool physx::PxcCacheLocalContacts( PxcNpThreadContext& context, Cache& pairContactCache,
const PxTransform32& tm0, const PxTransform32& tm1,
const PxcContactMethod conMethod,
const PxGeometry& shape0, const PxGeometry& shape1)
{
const NarrowPhaseParams& params = context.mNarrowPhaseParams;
// gContactCache_NbCalls++;
if(pairContactCache.mCachedData)
prefetchData128(pairContactCache.mCachedData, pairContactCache.mCachedSize);
PxContactBuffer& contactBuffer = context.mContactBuffer;
contactBuffer.reset();
PxcLocalContactsCache contactsData;
PxU32 nbCachedBytes;
const PxU8* cachedBytes = PxcNpCacheRead2(pairContactCache, contactsData, nbCachedBytes);
pairContactCache.mCachedData = NULL;
pairContactCache.mCachedSize = 0;
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbCalls++;
#endif
const PxU32 payloadSize = (sizeof(PxcLocalContactsCache)+3)&~3;
if(cachedBytes)
{
// PT: we used to store the relative TM but it's better to save memory and recompute it
const PxTransform t0to1 = tm1.transformInv(tm0);
const PxTransform relTM = contactsData.mTransform1.transformInv(contactsData.mTransform0);
const PxReal epsilon = 0.01f;
if( maxComponentDeltaPos(t0to1, relTM)<epsilon*params.mToleranceLength
&& maxComponentDeltaRot(t0to1, relTM)<epsilon)
{
// gContactCache_NbHits++;
const PxU32 nbContacts = contactsData.mNbCachedContacts;
PxU8* ls = PxcNpCacheWriteInitiate(context.mNpCacheStreamPair, pairContactCache, contactsData, nbCachedBytes);
prefetchData128(ls, (payloadSize + 4 + nbCachedBytes + 0xF)&~0xF);
contactBuffer.count = nbContacts;
if(nbContacts)
{
PxContactPoint* PX_RESTRICT dst = contactBuffer.contacts;
const Matrix34FromTransform world1(tm1);
const Matrix34FromTransform world0(tm0);
const bool sameNormal = contactsData.mSameNormal;
const PxU8* contacts = reinterpret_cast<const PxU8*>(cachedBytes);
const PxVec3* normal0 = NULL;
for(PxU32 i=0;i<nbContacts;i++)
{
if(i!=nbContacts-1)
PxPrefetchLine(contacts, 128);
const PxVec3* cachedNormal;
if(!i || !sameNormal)
{
cachedNormal = reinterpret_cast<const PxVec3*>(contacts); contacts += sizeof(PxVec3);
normal0 = cachedNormal;
}
else
{
cachedNormal = normal0;
}
const PxVec3* cachedPoint = reinterpret_cast<const PxVec3*>(contacts); contacts += sizeof(PxVec3);
const PxReal* cachedPD = reinterpret_cast<const PxReal*>(contacts); contacts += sizeof(PxReal);
updateContact(*dst, contactsData, world0, world1, *cachedPoint, *cachedNormal, *cachedPD);
if(contactsData.mUseFaceIndices)
{
const PxU32* cachedIndex1 = reinterpret_cast<const PxU32*>(contacts); contacts += sizeof(PxU32);
dst->internalFaceIndex1 = *cachedIndex1;
}
else
{
dst->internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX;
}
dst++;
}
}
if(ls)
PxcNpCacheWriteFinalize(ls, contactsData, nbCachedBytes, cachedBytes);
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbHits++;
#endif
return true;
}
else
{
// PT: if we reach this point we cached the contacts but we couldn't use them next frame
// => waste of time and memory
}
}
conMethod(shape0, shape1, tm0, tm1, params, pairContactCache, context.mContactBuffer, &context.mRenderOutput);
//if(contactBuffer.count)
{
contactsData.mTransform0 = tm0;
contactsData.mTransform1 = tm1;
PxU32 nbBytes = 0;
const PxU8* bytes = NULL;
const PxU32 count = contactBuffer.count;
if(count)
{
const bool useFaceIndices = contactBuffer.contacts[0].internalFaceIndex1!=PXC_CONTACT_NO_FACE_INDEX;
contactsData.mNbCachedContacts = PxTo16(count);
contactsData.mUseFaceIndices = useFaceIndices;
const PxContactPoint* PX_RESTRICT srcContacts = contactBuffer.contacts;
// PT: this loop should not be here. We should output the contacts directly compressed, as we used to.
bool sameNormal = true;
{
const PxVec3 normal0 = srcContacts->normal;
for(PxU32 i=1;i<count;i++)
{
if(srcContacts[i].normal!=normal0)
{
sameNormal = false;
break;
}
}
}
contactsData.mSameNormal = sameNormal;
if(!sameNormal)
{
const PxU32 sizeof_CachedContactPoint = sizeof(PxVec3) + sizeof(PxVec3) + sizeof(PxReal);
const PxU32 sizeof_CachedContactPointAndFaceIndices = sizeof_CachedContactPoint + sizeof(PxU32);
const PxU32 sizeOfItem = useFaceIndices ? sizeof_CachedContactPointAndFaceIndices : sizeof_CachedContactPoint;
nbBytes = count * sizeOfItem;
}
else
{
const PxU32 sizeof_CachedContactPoint = sizeof(PxVec3) + sizeof(PxReal);
const PxU32 sizeof_CachedContactPointAndFaceIndices = sizeof_CachedContactPoint + sizeof(PxU32);
const PxU32 sizeOfItem = useFaceIndices ? sizeof_CachedContactPointAndFaceIndices : sizeof_CachedContactPoint;
nbBytes = sizeof(PxVec3) + count * sizeOfItem;
}
PxU8* ls = PxcNpCacheWriteInitiate(context.mNpCacheStreamPair, pairContactCache, contactsData, nbBytes);
if(ls)
{
*reinterpret_cast<PxcLocalContactsCache*>(ls) = contactsData;
*reinterpret_cast<PxU32*>(ls+payloadSize) = nbBytes;
bytes = ls+payloadSize+sizeof(PxU32);
PxU8* dest = const_cast<PxU8*>(bytes);
for(PxU32 i=0;i<count;i++)
{
if(!i || !sameNormal)
dest = outputToCache(dest, srcContacts[i].normal);
dest = outputToCache(dest, srcContacts[i].point);
dest = outputToCache(dest, srcContacts[i].separation);
if(useFaceIndices)
{
dest = outputToCache(dest, srcContacts[i].internalFaceIndex1);
}
}
PX_ASSERT(size_t(dest) - size_t(bytes)==nbBytes);
}
else
{
contactsData.mNbCachedContacts = 0;
PxcNpCacheWrite(context.mNpCacheStreamPair, pairContactCache, contactsData, 0, bytes);
}
}
else
{
contactsData.mNbCachedContacts = 0;
contactsData.mUseFaceIndices = false;
PxcNpCacheWrite(context.mNpCacheStreamPair, pairContactCache, contactsData, nbBytes, bytes);
}
}
return false;
}
| 14,360 | C++ | 28.671488 | 124 | 0.700139 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcMaterialMethodImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcMaterialMethodImpl.h"
#include "PxvGeometry.h"
#include "PxcNpThreadContext.h"
#include "PxsMaterialManager.h"
#include "GuTriangleMesh.h"
#include "GuHeightField.h"
using namespace physx;
using namespace Gu;
// PT: moved these functions to same file for improving code locality and easily reusing code (calling smaller functions from larger ones, see below)
///////////////////////////////////////////////////////////////////////////////
static void PxcGetMaterialShape(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxU16 materialIndex = shape->mMaterialIndex;
const PxU32 count = context.mContactBuffer.count;
PX_ASSERT(index==0 || index==1);
for(PxU32 i=0; i<count; i++)
(&materialInfo[i].mMaterialIndex0)[index] = materialIndex;
}
static void PxcGetMaterialShapeShape(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxU16 materialIndex0 = shape0->mMaterialIndex;
const PxU16 materialIndex1 = shape1->mMaterialIndex;
const PxU32 count = context.mContactBuffer.count;
for(PxU32 i=0; i<count; i++)
{
materialInfo[i].mMaterialIndex0 = materialIndex0;
materialInfo[i].mMaterialIndex1 = materialIndex1;
}
}
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE const PxU16* getMaterialIndicesLL(const PxTriangleMeshGeometry& meshGeom)
{
return static_cast<const Gu::TriangleMesh*>(meshGeom.triangleMesh)->getMaterials();
}
static void PxcGetMaterialMesh(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 0 || index == 1);
const PxTriangleMeshGeometryLL& shapeMesh = shape->mGeometry.get<const PxTriangleMeshGeometryLL>();
if(shapeMesh.materialsLL.numIndices <= 1)
{
PxcGetMaterialShape(shape, index, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh);
const PxU16* indices = shapeMesh.materialsLL.indices;
for(PxU32 i=0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
(&materialInfo[i].mMaterialIndex0)[index] = indices[localMaterialIndex];
}
}
}
static void PxcGetMaterialShapeMesh(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxTriangleMeshGeometryLL& shapeMesh = shape1->mGeometry.get<const PxTriangleMeshGeometryLL>();
if(shapeMesh.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh);
const PxU16* indices = shapeMesh.materialsLL.indices;
const PxU16 materialIndex0 = shape0->mMaterialIndex;
for(PxU32 i=0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = materialIndex0;
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
materialInfo[i].mMaterialIndex1 = indices[localMaterialIndex];
}
}
}
static void PxcGetMaterialSoftBodyMesh(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
// PT: TODO: check this, it reads shape0 and labels it shapeMesh1? It's otherwise the same code as PxcGetMaterialShapeMesh ?
const PxTriangleMeshGeometryLL& shapeMesh1 = shape0->mGeometry.get<const PxTriangleMeshGeometryLL>();
if (shapeMesh1.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh1);
const PxU16* indices = shapeMesh1.materialsLL.indices;
const PxU16 materialIndex0 = shape0->mMaterialIndex;
for (PxU32 i = 0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = materialIndex0;
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
//contact.featureIndex1 = shapeMesh.materials.indices[localMaterialIndex];
materialInfo[i].mMaterialIndex1 = indices[localMaterialIndex];
}
}
}
///////////////////////////////////////////////////////////////////////////////
static PxU32 GetMaterialIndex(const Gu::HeightFieldData* hfData, PxU32 triangleIndex)
{
const PxU32 sampleIndex = triangleIndex >> 1;
const bool isFirstTriangle = (triangleIndex & 0x1) == 0;
//get sample
const PxHeightFieldSample* hf = &hfData->samples[sampleIndex];
return isFirstTriangle ? hf->materialIndex0 : hf->materialIndex1;
}
static void PxcGetMaterialHeightField(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 0 || index == 1);
const PxHeightFieldGeometryLL& hfGeom = shape->mGeometry.get<const PxHeightFieldGeometryLL>();
if(hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShape(shape, index, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
(&materialInfo[i].mMaterialIndex0)[index] = materialIndices[localMaterialIndex];
}
}
}
static void PxcGetMaterialShapeHeightField(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxHeightFieldGeometryLL& hfGeom = shape1->mGeometry.get<const PxHeightFieldGeometryLL>();
if(hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = shape0->mMaterialIndex;
//contact.featureIndex0 = shape0->materialIndex;
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
//contact.featureIndex1 = materialIndices[localMaterialIndex];
PX_ASSERT(localMaterialIndex<hfGeom.materialsLL.numIndices);
materialInfo[i].mMaterialIndex1 = materialIndices[localMaterialIndex];
}
}
}
static void PxcGetMaterialSoftBodyHeightField(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxHeightFieldGeometryLL& hfGeom = shape1->mGeometry.get<const PxHeightFieldGeometryLL>();
if (hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = shape0->mMaterialIndex;
//contact.featureIndex0 = shape0->materialIndex;
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
//contact.featureIndex1 = materialIndices[localMaterialIndex];
PX_ASSERT(localMaterialIndex<hfGeom.materialsLL.numIndices);
materialInfo[i].mMaterialIndex1 = materialIndices[localMaterialIndex];
}
}
}
///////////////////////////////////////////////////////////////////////////////
static void PxcGetMaterialSoftBody(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 1);
PX_UNUSED(index);
PxcGetMaterialShape(shape, index, context, materialInfo);
}
static void PxcGetMaterialShapeSoftBody(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
static void PxcGetMaterialSoftBodySoftBody(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
///////////////////////////////////////////////////////////////////////////////
namespace physx
{
PxcGetSingleMaterialMethod g_GetSingleMaterialMethodTable[] =
{
PxcGetMaterialShape, //PxGeometryType::eSPHERE
PxcGetMaterialShape, //PxGeometryType::ePLANE
PxcGetMaterialShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShape, //PxGeometryType::eBOX
PxcGetMaterialShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShape, //PxGeometryType::eCUSTOM
};
PX_COMPILE_TIME_ASSERT(sizeof(g_GetSingleMaterialMethodTable) / sizeof(g_GetSingleMaterialMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
//Table of contact methods for different shape-type combinations
PxcGetMaterialMethod g_GetMaterialMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcGetMaterialShapeShape, //PxGeometryType::eSPHERE
PxcGetMaterialShapeShape, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialSoftBodyMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialSoftBodyHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialSoftBodyMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialSoftBodyHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_GetMaterialMethodTable) / sizeof(g_GetMaterialMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
| 19,532 | C++ | 42.310421 | 180 | 0.746314 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcContactMethodImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxGeometry.h"
#include "PxcContactMethodImpl.h"
using namespace physx;
#define ARGS shape0, shape1, transform0, transform1, params, cache, contactBuffer, renderOutput
static bool PxcInvalidContactPair (GU_CONTACT_METHOD_ARGS_UNUSED) { return false; }
// PT: IMPORTANT: do NOT remove the indirection! Using the Gu functions directly in the table produces massive perf problems.
static bool PxcContactSphereSphere (GU_CONTACT_METHOD_ARGS) { return contactSphereSphere(ARGS); }
static bool PxcContactSphereCapsule (GU_CONTACT_METHOD_ARGS) { return contactSphereCapsule(ARGS); }
static bool PxcContactSphereBox (GU_CONTACT_METHOD_ARGS) { return contactSphereBox(ARGS); }
static bool PxcContactSpherePlane (GU_CONTACT_METHOD_ARGS) { return contactSpherePlane(ARGS); }
static bool PxcContactSphereConvex (GU_CONTACT_METHOD_ARGS) { return contactCapsuleConvex(ARGS); }
static bool PxcContactSphereMesh (GU_CONTACT_METHOD_ARGS) { return contactSphereMesh(ARGS); }
static bool PxcContactSphereHeightField (GU_CONTACT_METHOD_ARGS) { return contactSphereHeightfield(ARGS); }
static bool PxcContactPlaneBox (GU_CONTACT_METHOD_ARGS) { return contactPlaneBox(ARGS); }
static bool PxcContactPlaneCapsule (GU_CONTACT_METHOD_ARGS) { return contactPlaneCapsule(ARGS); }
static bool PxcContactPlaneConvex (GU_CONTACT_METHOD_ARGS) { return contactPlaneConvex(ARGS); }
static bool PxcContactCapsuleCapsule (GU_CONTACT_METHOD_ARGS) { return contactCapsuleCapsule(ARGS); }
static bool PxcContactCapsuleBox (GU_CONTACT_METHOD_ARGS) { return contactCapsuleBox(ARGS); }
static bool PxcContactCapsuleConvex (GU_CONTACT_METHOD_ARGS) { return contactCapsuleConvex(ARGS); }
static bool PxcContactCapsuleMesh (GU_CONTACT_METHOD_ARGS) { return contactCapsuleMesh(ARGS); }
static bool PxcContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS) { return contactCapsuleHeightfield(ARGS); }
static bool PxcContactBoxBox (GU_CONTACT_METHOD_ARGS) { return contactBoxBox(ARGS); }
static bool PxcContactBoxConvex (GU_CONTACT_METHOD_ARGS) { return contactBoxConvex(ARGS); }
static bool PxcContactBoxMesh (GU_CONTACT_METHOD_ARGS) { return contactBoxMesh(ARGS); }
static bool PxcContactBoxHeightField (GU_CONTACT_METHOD_ARGS) { return contactBoxHeightfield(ARGS); }
static bool PxcContactConvexConvex (GU_CONTACT_METHOD_ARGS) { return contactConvexConvex(ARGS); }
static bool PxcContactConvexMesh (GU_CONTACT_METHOD_ARGS) { return contactConvexMesh(ARGS); }
static bool PxcContactConvexHeightField (GU_CONTACT_METHOD_ARGS) { return contactConvexHeightfield(ARGS); }
static bool PxcContactGeometryCustomGeometry (GU_CONTACT_METHOD_ARGS) { return contactGeometryCustomGeometry(ARGS); }
static bool PxcPCMContactSphereSphere (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereSphere(ARGS); }
static bool PxcPCMContactSpherePlane (GU_CONTACT_METHOD_ARGS) { return pcmContactSpherePlane(ARGS); }
static bool PxcPCMContactSphereBox (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereBox(ARGS); }
static bool PxcPCMContactSphereCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereCapsule(ARGS); }
static bool PxcPCMContactSphereConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereConvex(ARGS); }
static bool PxcPCMContactSphereMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereMesh(ARGS); }
static bool PxcPCMContactSphereHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereHeightField(ARGS); }
static bool PxcPCMContactPlaneCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneCapsule(ARGS); }
static bool PxcPCMContactPlaneBox (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneBox(ARGS); }
static bool PxcPCMContactPlaneConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneConvex(ARGS); }
static bool PxcPCMContactCapsuleCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleCapsule(ARGS); }
static bool PxcPCMContactCapsuleBox (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleBox(ARGS); }
static bool PxcPCMContactCapsuleConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleConvex(ARGS); }
static bool PxcPCMContactCapsuleMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleMesh(ARGS); }
static bool PxcPCMContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleHeightField(ARGS); }
static bool PxcPCMContactBoxBox (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxBox(ARGS); }
static bool PxcPCMContactBoxConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxConvex(ARGS); }
static bool PxcPCMContactBoxMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxMesh(ARGS); }
static bool PxcPCMContactBoxHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxHeightField(ARGS); }
static bool PxcPCMContactConvexConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexConvex(ARGS); }
static bool PxcPCMContactConvexMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexMesh(ARGS); }
static bool PxcPCMContactConvexHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexHeightField(ARGS); }
static bool PxcPCMContactGeometryCustomGeometry (GU_CONTACT_METHOD_ARGS) { return pcmContactGeometryCustomGeometry(ARGS); }
#undef ARGS
namespace physx
{
//Table of contact methods for different shape-type combinations
PxcContactMethod g_ContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcContactSphereSphere, //PxGeometryType::eSPHERE
PxcContactSpherePlane, //PxGeometryType::ePLANE
PxcContactSphereCapsule, //PxGeometryType::eCAPSULE
PxcContactSphereBox, //PxGeometryType::eBOX
PxcContactSphereConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactSphereMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactSphereHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
PxcInvalidContactPair, //PxGeometryType::ePLANE
PxcContactPlaneCapsule, //PxGeometryType::eCAPSULE
PxcContactPlaneBox, //PxGeometryType::eBOX
PxcContactPlaneConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcContactCapsuleCapsule, //PxGeometryType::eCAPSULE
PxcContactCapsuleBox, //PxGeometryType::eBOX
PxcContactCapsuleConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactCapsuleMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactCapsuleHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcContactBoxBox, //PxGeometryType::eBOX
PxcContactBoxConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactBoxMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactBoxHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcContactConvexConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactConvexMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactConvexHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_ContactMethodTable) / sizeof(g_ContactMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
//Table of contact methods for different shape-type combinations
PxcContactMethod g_PCMContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcPCMContactSphereSphere, //PxGeometryType::eSPHERE
PxcPCMContactSpherePlane, //PxGeometryType::ePLANE
PxcPCMContactSphereCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactSphereBox, //PxGeometryType::eBOX
PxcPCMContactSphereConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactSphereMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactSphereHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
PxcInvalidContactPair, //PxGeometryType::ePLANE
PxcPCMContactPlaneCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactPlaneBox, //PxGeometryType::eBOX
PxcPCMContactPlaneConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcPCMContactCapsuleCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactCapsuleBox, //PxGeometryType::eBOX
PxcPCMContactCapsuleConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactCapsuleMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactCapsuleHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcPCMContactBoxBox, //PxGeometryType::eBOX
PxcPCMContactBoxConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactBoxMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactBoxHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcPCMContactConvexConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactConvexMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactConvexHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_PCMContactMethodTable) / sizeof(g_PCMContactMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
| 21,192 | C++ | 48.05787 | 128 | 0.74514 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpThreadContext.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcConstraintBlockStream.h"
#include "PxcNpThreadContext.h"
using namespace physx;
PxcNpThreadContext::PxcNpThreadContext(PxcNpContext* params) :
mRenderOutput (params->mRenderBuffer),
mContactBlockStream (params->mNpMemBlockPool),
mNpCacheStreamPair (params->mNpMemBlockPool),
mNarrowPhaseParams (0.0f, params->mMeshContactMargin, params->mToleranceLength),
mBodySimPool ("BodySimPool"),
mPCM (false),
mContactCache (false),
mCreateAveragePoint (false),
#if PX_ENABLE_SIM_STATS
mCompressedCacheSize (0),
mNbDiscreteContactPairsWithCacheHits(0),
mNbDiscreteContactPairsWithContacts (0),
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
mMaxPatches (0),
mTotalCompressedCacheSize (0),
mContactStreamPool (params->mContactStreamPool),
mPatchStreamPool (params->mPatchStreamPool),
mForceAndIndiceStreamPool (params->mForceAndIndiceStreamPool),
mMaterialManager (params->mMaterialManager),
mLocalNewTouchCount (0),
mLocalLostTouchCount (0)
{
#if PX_ENABLE_SIM_STATS
clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
PxcNpThreadContext::~PxcNpThreadContext()
{
}
#if PX_ENABLE_SIM_STATS
void PxcNpThreadContext::clearStats()
{
PxMemSet(mDiscreteContactPairs, 0, sizeof(mDiscreteContactPairs));
PxMemSet(mModifiedContactPairs, 0, sizeof(mModifiedContactPairs));
mCompressedCacheSize = 0;
mNbDiscreteContactPairsWithCacheHits = 0;
mNbDiscreteContactPairsWithContacts = 0;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
void PxcNpThreadContext::reset(PxU32 cmCount)
{
mContactBlockStream.reset();
mNpCacheStreamPair.reset();
mLocalChangeTouch.clear();
mLocalChangeTouch.resize(cmCount);
mLocalNewTouchCount = 0;
mLocalLostTouchCount = 0;
}
| 3,476 | C++ | 36.387096 | 85 | 0.767261 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpBatch.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxTriangleMesh.h"
#include "common/PxProfileZone.h"
#include "PxcNpBatch.h"
#include "PxcNpWorkUnit.h"
#include "PxcContactCache.h"
#include "PxcNpContactPrepShared.h"
#include "PxvGeometry.h"
#include "CmTask.h"
#include "PxsMaterialManager.h"
#include "PxsTransformCache.h"
#include "PxsContactManagerState.h"
// PT: use this define to enable detailed analysis of the NP functions.
//#define LOCAL_PROFILE_ZONE(x, y) PX_PROFILE_ZONE(x, y)
#define LOCAL_PROFILE_ZONE(x, y)
using namespace physx;
using namespace Gu;
PX_COMPILE_TIME_ASSERT(sizeof(PxsCachedTransform)==sizeof(PxTransform32));
static void startContacts(PxsContactManagerOutput& output, PxcNpThreadContext& context)
{
context.mContactBuffer.reset();
output.contactForces = NULL;
output.contactPatches = NULL;
output.contactPoints = NULL;
output.nbContacts = 0;
output.nbPatches = 0;
output.statusFlag = 0;
}
static void flipContacts(PxcNpThreadContext& threadContext, PxsMaterialInfo* PX_RESTRICT materialInfo)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
for(PxU32 i=0; i<buffer.count; ++i)
{
PxContactPoint& contactPoint = buffer.contacts[i];
contactPoint.normal = -contactPoint.normal;
PxSwap(materialInfo[i].mMaterialIndex0, materialInfo[i].mMaterialIndex1);
}
}
static PX_FORCE_INLINE void updateDiscreteContactStats(PxcNpThreadContext& context, PxGeometryType::Enum type0, PxGeometryType::Enum type1)
{
#if PX_ENABLE_SIM_STATS
PX_ASSERT(type0<=type1);
context.mDiscreteContactPairs[type0][type1]++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(context);
PX_UNUSED(type0);
PX_UNUSED(type1);
#endif
}
static bool copyBuffers(PxsContactManagerOutput& cmOutput, Gu::Cache& cache, PxcNpThreadContext& context, const bool useContactCache, const bool isMeshType)
{
bool ret = false;
//Copy the contact stream from previous buffer to current buffer...
PxU32 oldSize = sizeof(PxContact) * cmOutput.nbContacts + sizeof(PxContactPatch)*cmOutput.nbPatches;
if(oldSize)
{
ret = true;
PxU8* oldPatches = cmOutput.contactPatches;
PxU8* oldContacts = cmOutput.contactPoints;
PxReal* oldForces = cmOutput.contactForces;
PxU32 forceSize = cmOutput.nbContacts * sizeof(PxReal);
if(isMeshType)
forceSize += cmOutput.nbContacts * sizeof(PxU32);
PxU8* PX_RESTRICT contactPatches = NULL;
PxU8* PX_RESTRICT contactPoints = NULL;
PxReal* forceBuffer = NULL;
bool isOverflown = false;
//ML: if we are using contactStreamPool, which means we are running the GPU codepath
if(context.mContactStreamPool)
{
const PxU32 patchSize = cmOutput.nbPatches * sizeof(PxContactPatch);
const PxU32 contactSize = cmOutput.nbContacts * sizeof(PxContact);
PxU32 index = PxU32(PxAtomicAdd(&context.mContactStreamPool->mSharedDataIndex, PxI32(contactSize)));
if(context.mContactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactPoints = context.mContactStreamPool->mDataStream + context.mContactStreamPool->mDataStreamSize - index;
const PxU32 patchIndex = PxU32(PxAtomicAdd(&context.mPatchStreamPool->mSharedDataIndex, PxI32(patchSize)));
if(context.mPatchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactPatches = context.mPatchStreamPool->mDataStream + context.mPatchStreamPool->mDataStreamSize - patchIndex;
if(forceSize)
{
index = PxU32(PxAtomicAdd(&context.mForceAndIndiceStreamPool->mSharedDataIndex, PxI32(forceSize)));
if(context.mForceAndIndiceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
forceBuffer = reinterpret_cast<PxReal*>(context.mForceAndIndiceStreamPool->mDataStream + context.mForceAndIndiceStreamPool->mDataStreamSize - index);
}
if(isOverflown)
{
contactPatches = NULL;
contactPoints = NULL;
forceBuffer = NULL;
cmOutput.nbContacts = cmOutput.nbPatches = 0;
}
else
{
PxMemCopy(contactPatches, oldPatches, patchSize);
PxMemCopy(contactPoints, oldContacts, contactSize);
if(isMeshType)
PxMemCopy(forceBuffer + cmOutput.nbContacts, oldForces + cmOutput.nbContacts, sizeof(PxU32) * cmOutput.nbContacts);
}
}
else
{
const PxU32 alignedOldSize = (oldSize + 0xf) & 0xfffffff0;
PxU8* data = context.mContactBlockStream.reserve(alignedOldSize + forceSize);
if(forceSize)
forceBuffer = reinterpret_cast<PxReal*>(data + alignedOldSize);
contactPatches = data;
contactPoints = data + cmOutput.nbPatches * sizeof(PxContactPatch);
PxMemCopy(data, oldPatches, oldSize);
if(isMeshType)
PxMemCopy(forceBuffer + cmOutput.nbContacts, oldForces + cmOutput.nbContacts, sizeof(PxU32) * cmOutput.nbContacts);
}
if(forceSize)
PxMemZero(forceBuffer, forceSize);
cmOutput.contactPatches= contactPatches;
cmOutput.contactPoints = contactPoints;
cmOutput.contactForces = forceBuffer;
}
if(cache.mCachedSize)
{
if(cache.isMultiManifold())
{
PX_ASSERT((cache.mCachedSize & 0xF) == 0);
PxU8* newData = context.mNpCacheStreamPair.reserve(cache.mCachedSize);
PX_ASSERT((reinterpret_cast<uintptr_t>(newData)& 0xF) == 0);
PxMemCopy(newData, & cache.getMultipleManifold(), cache.mCachedSize);
cache.setMultiManifold(newData);
}
else if(useContactCache)
{
//Copy cache information as well...
const PxU8* cachedData = cache.mCachedData;
PxU8* newData = context.mNpCacheStreamPair.reserve(PxU32(cache.mCachedSize + 0xf) & 0xfff0);
PxMemCopy(newData, cachedData, cache.mCachedSize);
cache.mCachedData = newData;
}
}
return ret;
}
//ML: isMeshType is used in the GPU codepath. If the collision pair is mesh/heightfield vs primitives, we need to allocate enough memory for the mForceAndIndiceStreamPool in the threadContext.
static bool finishContacts(const PxcNpWorkUnit& input, PxsContactManagerOutput& npOutput, PxcNpThreadContext& threadContext, PxsMaterialInfo* PX_RESTRICT pMaterials, const bool isMeshType, PxU64 contextID)
{
PX_UNUSED(contextID);
LOCAL_PROFILE_ZONE("finishContacts", contextID);
PxContactBuffer& buffer = threadContext.mContactBuffer;
PX_ASSERT((npOutput.statusFlag & PxsContactManagerStatusFlag::eTOUCH_KNOWN) != PxsContactManagerStatusFlag::eTOUCH_KNOWN);
PxU8 statusFlags = PxU16(npOutput.statusFlag & (~PxsContactManagerStatusFlag::eTOUCH_KNOWN));
if(buffer.count)
statusFlags |= PxsContactManagerStatusFlag::eHAS_TOUCH;
else
statusFlags |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
npOutput.nbContacts = PxTo16(buffer.count);
if(!buffer.count)
{
npOutput.statusFlag = statusFlags;
npOutput.nbContacts = 0;
npOutput.nbPatches = 0;
return true;
}
PX_ASSERT(buffer.count);
#if PX_ENABLE_SIM_STATS
threadContext.mNbDiscreteContactPairsWithContacts++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
npOutput.statusFlag = statusFlags;
PxU32 contactForceByteSize = buffer.count * sizeof(PxReal);
//Regardless of the flags, we need to now record the compressed contact stream
PxU16 compressedContactSize;
const bool createReports =
input.flags & PxcNpWorkUnitFlag::eOUTPUT_CONTACTS
|| (input.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
if((!isMeshType && !createReports))
contactForceByteSize = 0;
bool res = (writeCompressedContact(buffer.contacts, buffer.count, &threadContext, npOutput.nbContacts, npOutput.contactPatches, npOutput.contactPoints, compressedContactSize,
reinterpret_cast<PxReal*&>(npOutput.contactForces), contactForceByteSize, threadContext.mMaterialManager, ((input.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT) != 0),
false, pMaterials, npOutput.nbPatches, 0, NULL, NULL, threadContext.mCreateAveragePoint, threadContext.mContactStreamPool,
threadContext.mPatchStreamPool, threadContext.mForceAndIndiceStreamPool, isMeshType) != 0);
//handle buffer overflow
if(!npOutput.nbContacts)
{
PxU8 thisStatusFlags = PxU16(npOutput.statusFlag & (~PxsContactManagerStatusFlag::eTOUCH_KNOWN));
thisStatusFlags |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
npOutput.statusFlag = thisStatusFlags;
npOutput.nbContacts = 0;
npOutput.nbPatches = 0;
#if PX_ENABLE_SIM_STATS
threadContext.mNbDiscreteContactPairsWithContacts--;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
return res;
}
template<bool useContactCacheT>
static PX_FORCE_INLINE bool checkContactsMustBeGenerated(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output,
const PxsCachedTransform* cachedTransform0, const PxsCachedTransform* cachedTransform1,
const bool flip, PxGeometryType::Enum type0, PxGeometryType::Enum type1)
{
PX_ASSERT(cachedTransform0->transform.isSane() && cachedTransform1->transform.isSane());
//ML : if user doesn't raise the eDETECT_DISCRETE_CONTACT, we should not generate contacts
if(!(input.flags & PxcNpWorkUnitFlag::eDETECT_DISCRETE_CONTACT))
return false;
if(!(output.statusFlag & PxcNpWorkUnitStatusFlag::eDIRTY_MANAGER) && !(input.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT))
{
const PxU32 body0Dynamic = PxU32(input.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0 | PxcNpWorkUnitFlag::eSOFT_BODY));
const PxU32 body1Dynamic = PxU32(input.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1 | PxcNpWorkUnitFlag::eSOFT_BODY));
const PxU32 active0 = PxU32(body0Dynamic && !cachedTransform0->isFrozen());
const PxU32 active1 = PxU32(body1Dynamic && !cachedTransform1->isFrozen());
if(!(active0 || active1))
{
if(flip)
PxSwap(type0, type1);
const bool useContactCache = useContactCacheT ? context.mContactCache && g_CanUseContactCache[type0][type1] : false;
#if PX_ENABLE_SIM_STATS
if(output.nbContacts)
context.mNbDiscreteContactPairsWithContacts++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
const bool isMeshType = type1 > PxGeometryType::eCONVEXMESH;
copyBuffers(output, cache, context, useContactCache, isMeshType);
return false;
}
}
output.statusFlag &= (~PxcNpWorkUnitStatusFlag::eDIRTY_MANAGER);
const PxReal contactDist0 = context.mContactDistances[input.mTransformCache0];
const PxReal contactDist1 = context.mContactDistances[input.mTransformCache1];
//context.mNarrowPhaseParams.mContactDistance = shape0->contactOffset + shape1->contactOffset;
context.mNarrowPhaseParams.mContactDistance = contactDist0 + contactDist1;
return true;
}
template<bool useLegacyCodepath>
static PX_FORCE_INLINE void discreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
PxGeometryType::Enum type0 = static_cast<PxGeometryType::Enum>(input.geomType0);
PxGeometryType::Enum type1 = static_cast<PxGeometryType::Enum>(input.geomType1);
const bool flip = (type1<type0);
const PxsCachedTransform* cachedTransform0 = &context.mTransformCache->getTransformCache(input.mTransformCache0);
const PxsCachedTransform* cachedTransform1 = &context.mTransformCache->getTransformCache(input.mTransformCache1);
if(!checkContactsMustBeGenerated<useLegacyCodepath>(context, input, cache, output, cachedTransform0, cachedTransform1, flip, type0, type1))
return;
PxsShapeCore* shape0 = const_cast<PxsShapeCore*>(input.shapeCore0);
PxsShapeCore* shape1 = const_cast<PxsShapeCore*>(input.shapeCore1);
if(flip)
{
PxSwap(type0, type1);
PxSwap(shape0, shape1);
PxSwap(cachedTransform0, cachedTransform1);
}
PxsMaterialInfo materialInfo[PxContactBuffer::MAX_CONTACTS];
Gu::MultiplePersistentContactManifold& manifold = context.mTempManifold;
bool isMultiManifold = false;
if(!useLegacyCodepath)
{
if(cache.isMultiManifold())
{
//We are using a multi-manifold. This is cached in a reduced npCache...
isMultiManifold = true;
uintptr_t address = uintptr_t(&cache.getMultipleManifold());
manifold.fromBuffer(reinterpret_cast<PxU8*>(address));
cache.setMultiManifold(&manifold);
}
else if(cache.isManifold())
{
void* address = reinterpret_cast<void*>(&cache.getManifold());
PxPrefetch(address);
PxPrefetch(address, 128);
PxPrefetch(address, 256);
}
}
updateDiscreteContactStats(context, type0, type1);
startContacts(output, context);
const PxTransform32* tm0 = reinterpret_cast<const PxTransform32*>(cachedTransform0);
const PxTransform32* tm1 = reinterpret_cast<const PxTransform32*>(cachedTransform1);
PX_ASSERT(tm0->isSane() && tm1->isSane());
const PxGeometry& contactShape0 = shape0->mGeometry.getGeometry();
const PxGeometry& contactShape1 = shape1->mGeometry.getGeometry();
if(useLegacyCodepath)
{
// PT: many cache misses here...
PxPrefetchLine(shape1, 0); // PT: at least get rid of L2s for shape1
const PxcContactMethod conMethod = g_ContactMethodTable[type0][type1];
PX_ASSERT(conMethod);
const bool useContactCache = context.mContactCache && g_CanUseContactCache[type0][type1];
if(useContactCache)
{
const bool status = PxcCacheLocalContacts(context, cache, *tm0, *tm1, conMethod, contactShape0, contactShape1);
#if PX_ENABLE_SIM_STATS
if(status)
context.mNbDiscreteContactPairsWithCacheHits++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(status);
#endif
}
else
{
LOCAL_PROFILE_ZONE("conMethod", contextID);
conMethod(contactShape0, contactShape1, *tm0, *tm1, context.mNarrowPhaseParams, cache, context.mContactBuffer, &context.mRenderOutput);
}
}
else
{
LOCAL_PROFILE_ZONE("conMethod", contextID);
const PxcContactMethod conMethod = g_PCMContactMethodTable[type0][type1];
PX_ASSERT(conMethod);
conMethod(contactShape0, contactShape1, *tm0, *tm1, context.mNarrowPhaseParams, cache, context.mContactBuffer, &context.mRenderOutput);
}
if(context.mContactBuffer.count)
{
const PxcGetMaterialMethod materialMethod = g_GetMaterialMethodTable[type0][type1];
if(materialMethod)
{
LOCAL_PROFILE_ZONE("materialMethod", contextID);
materialMethod(shape0, shape1, context, materialInfo);
}
if(flip)
{
LOCAL_PROFILE_ZONE("flipContacts", contextID);
flipContacts(context, materialInfo);
}
}
if(!useLegacyCodepath)
{
if(isMultiManifold)
{
//Store the manifold back...
const PxU32 size = (sizeof(MultiPersistentManifoldHeader) +
manifold.mNumManifolds * sizeof(SingleManifoldHeader) +
manifold.mNumTotalContacts * sizeof(Gu::CachedMeshPersistentContact));
PxU8* buffer = context.mNpCacheStreamPair.reserve(size);
PX_ASSERT((reinterpret_cast<uintptr_t>(buffer)& 0xf) == 0);
manifold.toBuffer(buffer);
cache.setMultiManifold(buffer);
cache.mCachedSize = PxTo16(size);
}
}
const bool isMeshType = type1 > PxGeometryType::eCONVEXMESH;
finishContacts(input, output, context, materialInfo, isMeshType, contextID);
}
void physx::PxcDiscreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
LOCAL_PROFILE_ZONE("PxcDiscreteNarrowPhase", contextID);
discreteNarrowPhase<true>(context, input, cache, output, contextID);
}
void physx::PxcDiscreteNarrowPhasePCM(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
LOCAL_PROFILE_ZONE("PxcDiscreteNarrowPhasePCM", contextID);
discreteNarrowPhase<false>(context, input, cache, output, contextID);
}
| 17,311 | C++ | 35.91258 | 205 | 0.763214 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpContactPrepShared.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "PxcNpWorkUnit.h"
#include "PxvDynamics.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "PxsMaterialCombiner.h"
#include "PxcNpContactPrepShared.h"
#include "foundation/PxAtomic.h"
#include "PxsContactManagerState.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxErrors.h"
using namespace physx;
using namespace aos;
static PX_FORCE_INLINE void copyContactPoint(PxContact* PX_RESTRICT point, const PxContactPoint* PX_RESTRICT cp)
{
// PT: TODO: consider moving "separation" right after "point" in both structures, to copy both at the same time.
// point->contact = cp->point;
const Vec4V contactV = V4LoadA(&cp->point.x); // PT: V4LoadA safe because 'point' is aligned.
V4StoreU(contactV, &point->contact.x);
point->separation = cp->separation;
}
void combineMaterials(const PxsMaterialManager* materialManager, PxU16 origMatIndex0, PxU16 origMatIndex1, PxReal& staticFriction, PxReal& dynamicFriction, PxReal& combinedRestitution, PxU32& materialFlags, PxReal& combinedDamping)
{
const PxsMaterialData& data0 = *materialManager->getMaterial(origMatIndex0);
const PxsMaterialData& data1 = *materialManager->getMaterial(origMatIndex1);
combinedRestitution = PxsCombineRestitution(data0, data1);
combinedDamping = PxMax(data0.damping, data1.damping);
PxsCombineIsotropicFriction(data0, data1, dynamicFriction, staticFriction, materialFlags);
}
struct StridePatch
{
PxU8 startIndex;
PxU8 endIndex;
PxU8 nextIndex;
PxU8 totalCount;
bool isRoot;
};
PxU32 physx::writeCompressedContact(const PxContactPoint* const PX_RESTRICT contactPoints, const PxU32 numContactPoints, PxcNpThreadContext* threadContext,
PxU16& writtenContactCount, PxU8*& outContactPatches, PxU8*& outContactPoints, PxU16& compressedContactSize, PxReal*& outContactForces, PxU32 contactForceByteSize,
const PxsMaterialManager* materialManager, bool hasModifiableContacts, bool forceNoResponse, const PxsMaterialInfo* PX_RESTRICT pMaterial, PxU8& numPatches,
PxU32 additionalHeaderSize, PxsConstraintBlockManager* manager, PxcConstraintBlockStream* blockStream, bool insertAveragePoint,
PxcDataStreamPool* contactStreamPool, PxcDataStreamPool* patchStreamPool, PxcDataStreamPool* forceStreamPool, const bool isMeshType)
{
if(numContactPoints == 0)
{
writtenContactCount = 0;
outContactPatches = NULL;
outContactPoints = NULL;
outContactForces = NULL;
compressedContactSize = 0;
numPatches = 0;
return 0;
}
//Calculate the size of the contact buffer...
PX_ALLOCA(strPatches, StridePatch, numContactPoints);
StridePatch* stridePatches = &strPatches[0];
PxU32 numStrideHeaders = 1;
PxU32 totalUniquePatches = 1;
PxU32 totalContactPoints = numContactPoints;
PxU32 strideStart = 0;
bool root = true;
StridePatch* parentRootPatch = NULL;
{
const PxReal closeNormalThresh = PXC_SAME_NORMAL;
//Go through and tag how many patches we have...
PxVec3 normal = contactPoints[0].normal;
PxU16 mat0 = pMaterial[0].mMaterialIndex0;
PxU16 mat1 = pMaterial[0].mMaterialIndex1;
for(PxU32 a = 1; a < numContactPoints; ++a)
{
if(normal.dot(contactPoints[a].normal) < closeNormalThresh ||
pMaterial[a].mMaterialIndex0 != mat0 || pMaterial[a].mMaterialIndex1 != mat1)
{
StridePatch& patch = stridePatches[numStrideHeaders-1];
patch.startIndex = PxU8(strideStart);
patch.endIndex = PxU8(a);
patch.nextIndex = 0xFF;
patch.totalCount = PxU8(a - strideStart);
patch.isRoot = root;
if(parentRootPatch)
parentRootPatch->totalCount += PxU8(a - strideStart);
root = true;
parentRootPatch = NULL;
for(PxU32 b = 1; b < numStrideHeaders; ++b)
{
StridePatch& thisPatch = stridePatches[b-1];
if(thisPatch.isRoot)
{
PxU32 ind = thisPatch.startIndex;
PxReal dp2 = contactPoints[a].normal.dot(contactPoints[ind].normal);
if(dp2 >= closeNormalThresh && pMaterial[a].mMaterialIndex0 == pMaterial[ind].mMaterialIndex0 &&
pMaterial[a].mMaterialIndex1 == pMaterial[ind].mMaterialIndex1)
{
PxU32 nextInd = b-1;
while(stridePatches[nextInd].nextIndex != 0xFF)
nextInd = stridePatches[nextInd].nextIndex;
stridePatches[nextInd].nextIndex = PxU8(numStrideHeaders);
root = false;
parentRootPatch = &stridePatches[b-1];
break;
}
}
}
normal = contactPoints[a].normal;
mat0 = pMaterial[a].mMaterialIndex0;
mat1 = pMaterial[a].mMaterialIndex1;
totalContactPoints = insertAveragePoint && (a - strideStart) > 1 ? totalContactPoints + 1 : totalContactPoints;
strideStart = a;
numStrideHeaders++;
if(root)
totalUniquePatches++;
}
}
totalContactPoints = insertAveragePoint &&(numContactPoints - strideStart) > 1 ? totalContactPoints + 1 : totalContactPoints;
contactForceByteSize = insertAveragePoint && contactForceByteSize != 0 ? contactForceByteSize + sizeof(PxF32) * (totalContactPoints - numContactPoints) : contactForceByteSize;
}
{
StridePatch& patch = stridePatches[numStrideHeaders-1];
patch.startIndex = PxU8(strideStart);
patch.endIndex = PxU8(numContactPoints);
patch.nextIndex = 0xFF;
patch.totalCount = PxU8(numContactPoints - strideStart);
patch.isRoot = root;
if(parentRootPatch)
parentRootPatch->totalCount += PxU8(numContactPoints - strideStart);
}
numPatches = PxU8(totalUniquePatches);
//Calculate the number of patches/points required
const bool isModifiable = !forceNoResponse && hasModifiableContacts;
const PxU32 patchHeaderSize = sizeof(PxContactPatch) * (isModifiable ? totalContactPoints : totalUniquePatches) + additionalHeaderSize;
const PxU32 pointSize = totalContactPoints * (isModifiable ? sizeof(PxModifiableContact) : sizeof(PxContact));
PxU32 requiredContactSize = pointSize;
PxU32 requiredPatchSize = patchHeaderSize;
PxU32 totalRequiredSize;
PxU8* PX_RESTRICT contactData = NULL;
PxU8* PX_RESTRICT patchData = NULL;
PxReal* PX_RESTRICT forceData = NULL;
PxU32* PX_RESTRICT triangleIndice = NULL;
if(contactStreamPool && !isModifiable && additionalHeaderSize == 0) //If the contacts are modifiable, we **DON'T** allocate them in GPU pinned memory. This will be handled later when they're modified
{
bool isOverflown = false;
PxU32 contactIndex = PxU32(PxAtomicAdd(&contactStreamPool->mSharedDataIndex, PxI32(requiredContactSize)));
if (contactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactData = contactStreamPool->mDataStream + contactStreamPool->mDataStreamSize - contactIndex;
PxU32 patchIndex = PxU32(PxAtomicAdd(&patchStreamPool->mSharedDataIndex, PxI32(requiredPatchSize)));
if (patchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
patchData = patchStreamPool->mDataStream + patchStreamPool->mDataStreamSize - patchIndex;
if(contactForceByteSize)
{
contactForceByteSize = isMeshType ? contactForceByteSize * 2 : contactForceByteSize;
contactIndex = PxU32(PxAtomicAdd(&forceStreamPool->mSharedDataIndex, PxI32(contactForceByteSize)));
if (forceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
forceData = reinterpret_cast<PxReal*>(forceStreamPool->mDataStream + forceStreamPool->mDataStreamSize - contactIndex);
if (isMeshType)
triangleIndice = reinterpret_cast<PxU32*>(forceData + numContactPoints);
}
totalRequiredSize = requiredContactSize + requiredPatchSize;
if (isOverflown)
{
patchData = NULL;
contactData = NULL;
forceData = NULL;
triangleIndice = NULL;
}
}
else
{
PxU32 alignedRequiredSize = (requiredContactSize + requiredPatchSize + 0xf) & 0xfffffff0;
contactForceByteSize = (isMeshType ? contactForceByteSize * 2 : contactForceByteSize);
PxU32 totalSize = alignedRequiredSize + contactForceByteSize;
PxU8* data = manager ? blockStream->reserve(totalSize, *manager) : threadContext->mContactBlockStream.reserve(totalSize);
patchData = data;
contactData = patchData + requiredPatchSize;
if(contactForceByteSize)
{
forceData = reinterpret_cast<PxReal*>((data + alignedRequiredSize));
if (isMeshType)
triangleIndice = reinterpret_cast<PxU32*>(forceData + numContactPoints);
if(data)
{
PxMemZero(forceData, contactForceByteSize);
}
}
totalRequiredSize = alignedRequiredSize;
}
PxPrefetchLine(patchData);
PxPrefetchLine(contactData);
if(patchData == NULL)
{
writtenContactCount = 0;
outContactPatches = NULL;
outContactPoints = NULL;
outContactForces = NULL;
compressedContactSize = 0;
numPatches = 0;
return 0;
}
#if PX_ENABLE_SIM_STATS
if(threadContext)
{
threadContext->mCompressedCacheSize += totalRequiredSize;
threadContext->mTotalCompressedCacheSize += totalRequiredSize;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
compressedContactSize = PxTo16(totalRequiredSize);
//PxU32 startIndex = 0;
//Extract first material
PxU16 origMatIndex0 = pMaterial[0].mMaterialIndex0;
PxU16 origMatIndex1 = pMaterial[0].mMaterialIndex1;
PxReal staticFriction, dynamicFriction, combinedRestitution, combinedDamping;
PxU32 materialFlags;
combineMaterials(materialManager, origMatIndex0, origMatIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
PxU8* PX_RESTRICT dataPlusOffset = patchData + additionalHeaderSize;
PxContactPatch* PX_RESTRICT patches = reinterpret_cast<PxContactPatch*>(dataPlusOffset);
PxU32* PX_RESTRICT faceIndice = triangleIndice;
outContactPatches = patchData;
outContactPoints = contactData;
outContactForces = forceData;
struct Local
{
static PX_FORCE_INLINE void fillPatch(PxContactPatch* PX_RESTRICT patch, const StridePatch& rootPatch, const PxVec3& normal,
PxU32 currentIndex, PxReal staticFriction_, PxReal dynamicFriction_, PxReal combinedRestitution_, PxReal combinedDamping_,
PxU32 materialFlags_, PxU32 flags, PxU16 matIndex0, PxU16 matIndex1
)
{
patch->mMassModification.linear0 = 1.0f;
patch->mMassModification.linear1 = 1.0f;
patch->mMassModification.angular0 = 1.0f;
patch->mMassModification.angular1 = 1.0f;
PX_ASSERT(PxAbs(normal.magnitude() - 1) < 1e-3f);
patch->normal = normal;
patch->restitution = combinedRestitution_;
patch->dynamicFriction = dynamicFriction_;
patch->staticFriction = staticFriction_;
patch->damping = combinedDamping_;
patch->startContactIndex = PxTo8(currentIndex);
//KS - we could probably compress this further into the header but the complexity might not be worth it
patch->nbContacts = rootPatch.totalCount;
patch->materialFlags = PxU8(materialFlags_);
patch->internalFlags = PxU8(flags);
patch->materialIndex0 = matIndex0;
patch->materialIndex1 = matIndex1;
}
};
if(isModifiable)
{
PxU32 flags = PxU32(isModifiable ? PxContactPatch::eMODIFIABLE : 0) |
(forceNoResponse ? PxContactPatch::eFORCE_NO_RESPONSE : 0) |
(isMeshType ? PxContactPatch::eHAS_FACE_INDICES : 0);
PxU32 currentIndex = 0;
PxModifiableContact* PX_RESTRICT point = reinterpret_cast<PxModifiableContact*>(contactData);
for(PxU32 a = 0; a < numStrideHeaders; ++a)
{
StridePatch& rootPatch = stridePatches[a];
if(rootPatch.isRoot)
{
const PxU32 startIndex = rootPatch.startIndex;
const PxU16 matIndex0 = pMaterial[startIndex].mMaterialIndex0;
const PxU16 matIndex1 = pMaterial[startIndex].mMaterialIndex1;
if(matIndex0 != origMatIndex0 || matIndex1 != origMatIndex1)
{
combineMaterials(materialManager, matIndex0, matIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
origMatIndex0 = matIndex0;
origMatIndex1 = matIndex1;
}
PxContactPatch* PX_RESTRICT patch = patches++;
Local::fillPatch(patch, rootPatch, contactPoints[startIndex].normal, currentIndex, staticFriction, dynamicFriction, combinedRestitution, combinedDamping, materialFlags, flags, matIndex0, matIndex1);
//const PxU32 endIndex = strideHeader[a];
const PxU32 totalCountThisPatch = rootPatch.totalCount;
if(insertAveragePoint && totalCountThisPatch > 1)
{
PxVec3 avgPt(0.0f);
PxF32 avgPen(0.0f);
PxF32 recipCount = 1.0f/(PxF32(rootPatch.totalCount));
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
avgPt += contactPoints[b].point;
avgPen += contactPoints[b].separation;
}
index = p.nextIndex;
}
if (faceIndice)
{
StridePatch& p = stridePatches[index];
*faceIndice = contactPoints[p.startIndex].internalFaceIndex1;
faceIndice++;
}
patch->nbContacts++;
point->contact = avgPt * recipCount;
point->separation = avgPen * recipCount;
point->normal = contactPoints[startIndex].normal;
point->maxImpulse = PX_MAX_REAL;
point->targetVelocity = PxVec3(0.0f);
point->staticFriction = staticFriction;
point->dynamicFriction = dynamicFriction;
point->restitution = combinedRestitution;
point->materialFlags = materialFlags;
point->materialIndex0 = matIndex0;
point->materialIndex1 = matIndex1;
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
copyContactPoint(point, &contactPoints[b]);
point->normal = contactPoints[b].normal;
point->maxImpulse = PX_MAX_REAL;
point->targetVelocity = PxVec3(0.0f);
point->staticFriction = staticFriction;
point->dynamicFriction = dynamicFriction;
point->restitution = combinedRestitution;
point->materialFlags = materialFlags;
point->materialIndex0 = matIndex0;
point->materialIndex1 = matIndex1;
if (faceIndice)
{
*faceIndice = contactPoints[b].internalFaceIndex1;
faceIndice++;
}
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
index = p.nextIndex;
}
}
}
}
else
{
PxU32 flags = PxU32(isMeshType ? PxContactPatch::eHAS_FACE_INDICES : 0);
PxContact* PX_RESTRICT point = reinterpret_cast<PxContact*>(contactData);
PxU32 currentIndex = 0;
{
for(PxU32 a = 0; a < numStrideHeaders; ++a)
{
StridePatch& rootPatch = stridePatches[a];
if(rootPatch.isRoot)
{
const PxU32 startIndex = rootPatch.startIndex;
const PxU16 matIndex0 = pMaterial[startIndex].mMaterialIndex0;
const PxU16 matIndex1 = pMaterial[startIndex].mMaterialIndex1;
if(matIndex0 != origMatIndex0 || matIndex1 != origMatIndex1)
{
combineMaterials(materialManager, matIndex0, matIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
origMatIndex0 = matIndex0;
origMatIndex1 = matIndex1;
}
PxContactPatch* PX_RESTRICT patch = patches++;
Local::fillPatch(patch, rootPatch, contactPoints[startIndex].normal, currentIndex, staticFriction, dynamicFriction, combinedRestitution, combinedDamping, materialFlags, flags, matIndex0, matIndex1);
if(insertAveragePoint && (rootPatch.totalCount) > 1)
{
patch->nbContacts++;
PxVec3 avgPt(0.0f);
PxF32 avgPen(0.0f);
PxF32 recipCount = 1.0f/(PxF32(rootPatch.totalCount));
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
avgPt += contactPoints[b].point;
avgPen += contactPoints[b].separation;
}
index = stridePatches[index].nextIndex;
}
if (faceIndice)
{
StridePatch& p = stridePatches[index];
*faceIndice = contactPoints[p.startIndex].internalFaceIndex1;
faceIndice++;
}
point->contact = avgPt * recipCount;
point->separation = avgPen * recipCount;
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
copyContactPoint(point, &contactPoints[b]);
if (faceIndice)
{
*faceIndice = contactPoints[b].internalFaceIndex1;
faceIndice++;
}
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
index = stridePatches[index].nextIndex;
}
}
}
}
}
writtenContactCount = PxTo16(totalContactPoints);
return totalRequiredSize;
}
| 18,676 | C++ | 33.91028 | 231 | 0.720979 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpCacheStreamPair.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcNpCacheStreamPair.h"
#include "foundation/PxUserAllocated.h"
#include "PxcNpMemBlockPool.h"
using namespace physx;
void PxcNpCacheStreamPair::reset()
{
mBlock = NULL;
mUsed = 0;
}
PxcNpCacheStreamPair::PxcNpCacheStreamPair(PxcNpMemBlockPool& blockPool):
mBlockPool(blockPool), mBlock(NULL), mUsed(0)
{
}
// reserve can fail and return null. Read should never fail
PxU8* PxcNpCacheStreamPair::reserve(PxU32 size)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
{
return reinterpret_cast<PxU8*>(-1);
}
if(mBlock == NULL || mUsed + size > PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireNpCacheBlock();
mUsed = 0;
}
PxU8* ptr;
if(mBlock == NULL)
ptr = 0;
else
{
ptr = mBlock->data+mUsed;
mUsed += size;
}
return ptr;
}
| 2,472 | C++ | 32.418918 | 74 | 0.744741 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcMaterialMethodImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_MATERIAL_METHOD_H
#define PXC_MATERIAL_METHOD_H
#include "geometry/PxGeometry.h"
namespace physx
{
struct PxsShapeCore;
struct PxsMaterialInfo;
class PxcNpThreadContext;
#define MATERIAL_METHOD_ARGS \
const PxsShapeCore* shape0, \
const PxsShapeCore* shape1, \
PxcNpThreadContext& pairContext, \
PxsMaterialInfo* materialInfo
#define SINGLE_MATERIAL_METHOD_ARGS \
const PxsShapeCore* shape, \
const PxU32 index, \
PxcNpThreadContext& pairContext, \
PxsMaterialInfo* materialInfo
/*!
Method prototype for fetch material routines
*/
typedef void (*PxcGetMaterialMethod) (MATERIAL_METHOD_ARGS);
typedef void (*PxcGetSingleMaterialMethod) (SINGLE_MATERIAL_METHOD_ARGS);
extern PxcGetMaterialMethod g_GetMaterialMethodTable[][PxGeometryType::eGEOMETRY_COUNT];
extern PxcGetSingleMaterialMethod g_GetSingleMaterialMethodTable[PxGeometryType::eGEOMETRY_COUNT];
}
#endif
| 2,609 | C | 37.382352 | 98 | 0.774243 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpWorkUnit.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_WORK_UNIT_H
#define PXC_NP_WORK_UNIT_H
#include "PxcNpThreadContext.h"
#include "PxcMaterialMethodImpl.h"
#include "PxcNpCache.h"
namespace physx
{
struct PxsRigidCore;
struct PxsShapeCore;
struct PxcNpWorkUnitFlag
{
enum Enum
{
eOUTPUT_CONTACTS = 1 << 0,
eOUTPUT_CONSTRAINTS = 1 << 1,
eDISABLE_STRONG_FRICTION = 1 << 2,
eARTICULATION_BODY0 = 1 << 3,
eARTICULATION_BODY1 = 1 << 4,
eDYNAMIC_BODY0 = 1 << 5,
eDYNAMIC_BODY1 = 1 << 6,
eSOFT_BODY = 1 << 7,
eMODIFIABLE_CONTACT = 1 << 8,
eFORCE_THRESHOLD = 1 << 9,
eDETECT_DISCRETE_CONTACT = 1 << 10,
eHAS_KINEMATIC_ACTOR = 1 << 11,
eDISABLE_RESPONSE = 1 << 12,
eDETECT_CCD_CONTACTS = 1 << 13,
};
};
struct PxcNpWorkUnitStatusFlag
{
enum Enum
{
eHAS_NO_TOUCH = (1 << 0),
eHAS_TOUCH = (1 << 1),
//eHAS_SOLVER_CONSTRAINTS = (1 << 2),
eREQUEST_CONSTRAINTS = (1 << 3),
eHAS_CCD_RETOUCH = (1 << 4), // Marks pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// but we can not tell whether they lost contact in a pass before. We send them as pure eNOTIFY_TOUCH_CCD events to the
// contact report callback if requested.
eDIRTY_MANAGER = (1 << 5),
eREFRESHED_WITH_TOUCH = (1 << 6),
eTOUCH_KNOWN = eHAS_NO_TOUCH | eHAS_TOUCH // The touch status is known (if narrowphase never ran for a pair then no flag will be set)
};
};
// PT: TODO: fix the inconsistent namings (mXXX) in this class
struct PxcNpWorkUnit
{
const PxsRigidCore* rigidCore0; // INPUT //4 //8
const PxsRigidCore* rigidCore1; // INPUT //8 //16
const PxsShapeCore* shapeCore0; // INPUT //12 //24
const PxsShapeCore* shapeCore1; // INPUT //16 //32
PxU8* ccdContacts; // OUTPUT //20 //40
PxU8* frictionDataPtr; // INOUT //24 //48
PxU16 flags; // INPUT //26 //50
PxU8 frictionPatchCount; // INOUT //27 //51
PxU8 statusFlags; // OUTPUT (see PxcNpWorkUnitStatusFlag) //28 //52
PxU8 dominance0; // INPUT //29 //53
PxU8 dominance1; // INPUT //30 //54
PxU8 geomType0; // INPUT //31 //55
PxU8 geomType1; // INPUT //32 //56
PxU32 index; // INPUT //36 //60
PxReal restDistance; // INPUT //40 //64
PxU32 mTransformCache0; // //44 //68
PxU32 mTransformCache1; // //48 //72
PxU32 mEdgeIndex; //inout the island gen edge index //52 //76
PxU32 mNpIndex; //INPUT //56 //80
PxReal mTorsionalPatchRadius; //60 //84
PxReal mMinTorsionalPatchRadius; //64 //88
PxReal mOffsetSlop; //68 //92
PX_FORCE_INLINE void clearCachedState()
{
frictionDataPtr = NULL;
frictionPatchCount = 0;
ccdContacts = NULL;
}
};
//#if !defined(PX_P64)
//PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxcNpWorkUnit) & 0x0f));
//#endif
#if !defined(PX_P64)
//PX_COMPILE_TIME_ASSERT(sizeof(PxcNpWorkUnit)==128);
#endif
}
#endif
| 4,799 | C | 35.090225 | 153 | 0.656178 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcContactCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_CONTACT_CACHE_H
#define PXC_CONTACT_CACHE_H
#include "foundation/PxTransform.h"
#include "PxvConfig.h"
#include "PxcContactMethodImpl.h"
namespace physx
{
class PxcNpThreadContext;
bool PxcCacheLocalContacts( PxcNpThreadContext& context, Gu::Cache& pairContactCache,
const PxTransform32& tm0, const PxTransform32& tm1,
const PxcContactMethod conMethod,
const PxGeometry& shape0, const PxGeometry& shape1);
struct PxcLocalContactsCache
{
PxTransform mTransform0;
PxTransform mTransform1;
PxU16 mNbCachedContacts;
bool mUseFaceIndices;
bool mSameNormal;
PX_FORCE_INLINE void operator = (const PxcLocalContactsCache& other)
{
mTransform0 = other.mTransform0;
mTransform1 = other.mTransform1;
mNbCachedContacts = other.mNbCachedContacts;
mUseFaceIndices = other.mUseFaceIndices;
mSameNormal = other.mSameNormal;
}
};
}
#endif // PXC_CONTACT_CACHE_H
| 2,633 | C | 38.90909 | 86 | 0.760349 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpMemBlockPool.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_MEM_BLOCK_POOL_H
#define PXC_NP_MEM_BLOCK_POOL_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
namespace physx
{
class PxcScratchAllocator;
struct PxcNpMemBlock
{
enum
{
SIZE = 16384
};
PxU8 data[SIZE];
};
typedef PxArray<PxcNpMemBlock*> PxcNpMemBlockArray;
class PxcNpMemBlockPool
{
PX_NOCOPY(PxcNpMemBlockPool)
public:
PxcNpMemBlockPool(PxcScratchAllocator& allocator);
~PxcNpMemBlockPool();
void init(PxU32 initial16KDataBlocks, PxU32 maxBlocks);
void flush();
void setBlockCount(PxU32 count);
PxU32 getUsedBlockCount() const;
PxU32 getMaxUsedBlockCount() const;
PxU32 getPeakConstraintBlockCount() const;
void releaseUnusedBlocks();
PxcNpMemBlock* acquireConstraintBlock();
PxcNpMemBlock* acquireConstraintBlock(PxcNpMemBlockArray& memBlocks);
PxcNpMemBlock* acquireContactBlock();
PxcNpMemBlock* acquireFrictionBlock();
PxcNpMemBlock* acquireNpCacheBlock();
PxU8* acquireExceptionalConstraintMemory(PxU32 size);
void acquireConstraintMemory();
void releaseConstraintMemory();
void releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks);
void releaseContacts();
void swapFrictionStreams();
void swapNpCacheStreams();
void flushUnused();
private:
PxMutex mLock;
PxcNpMemBlockArray mConstraints;
PxcNpMemBlockArray mContacts[2];
PxcNpMemBlockArray mFriction[2];
PxcNpMemBlockArray mNpCache[2];
PxcNpMemBlockArray mScratchBlocks;
PxArray<PxU8*> mExceptionalConstraints;
PxcNpMemBlockArray mUnused;
PxU32 mNpCacheActiveStream;
PxU32 mFrictionActiveStream;
PxU32 mCCDCacheActiveStream;
PxU32 mContactIndex;
PxU32 mAllocatedBlocks;
PxU32 mMaxBlocks;
PxU32 mInitialBlocks;
PxU32 mUsedBlocks;
PxU32 mMaxUsedBlocks;
PxcNpMemBlock* mScratchBlockAddr;
PxU32 mNbScratchBlocks;
PxcScratchAllocator& mScratchAllocator;
PxU32 mPeakConstraintAllocations;
PxU32 mConstraintAllocations;
PxcNpMemBlock* acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount = NULL, PxU32* peakAllocationCount = NULL, bool isScratchAllocation = false);
void release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount = NULL);
};
}
#endif
| 3,940 | C | 32.398305 | 159 | 0.770812 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpCacheStreamPair.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_CACHE_STREAM_PAIR_H
#define PXC_NP_CACHE_STREAM_PAIR_H
#include "foundation/PxSimpleTypes.h"
#include "PxvConfig.h"
#include "PxcNpMemBlockPool.h"
namespace physx
{
static const PxU32 PXC_NPCACHE_BLOCK_SIZE = 16384;
struct PxcNpCacheStreamPair
{
public:
PxcNpCacheStreamPair(PxcNpMemBlockPool& blockPool);
// reserve can fail and return null.
PxU8* reserve(PxU32 byteCount);
void reset();
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock;
PxU32 mUsed;
private:
PxcNpCacheStreamPair& operator=(const PxcNpCacheStreamPair&);
};
}
#endif
| 2,289 | C | 36.540983 | 74 | 0.764089 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpContactPrepShared.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_CONTACT_PREP_SHARED_H
#define PXC_NP_CONTACT_PREP_SHARED_H
namespace physx
{
class PxcNpThreadContext;
struct PxsMaterialInfo;
class PxsMaterialManager;
class PxsConstraintBlockManager;
class PxcConstraintBlockStream;
struct PxsContactManagerOutput;
namespace Gu
{
struct ContactPoint;
}
static const PxReal PXC_SAME_NORMAL = 0.999f; //Around 6 degrees
PxU32 writeCompressedContact(const PxContactPoint* const PX_RESTRICT contactPoints, const PxU32 numContactPoints, PxcNpThreadContext* threadContext,
PxU16& writtenContactCount, PxU8*& outContactPatches, PxU8*& outContactPoints, PxU16& compressedContactSize, PxReal*& contactForces, PxU32 contactForceByteSize,
const PxsMaterialManager* materialManager, bool hasModifiableContacts, bool forceNoResponse, const PxsMaterialInfo* PX_RESTRICT pMaterial, PxU8& numPatches,
PxU32 additionalHeaderSize = 0, PxsConstraintBlockManager* manager = NULL, PxcConstraintBlockStream* blockStream = NULL, bool insertAveragePoint = false,
PxcDataStreamPool* pool = NULL, PxcDataStreamPool* patchStreamPool = NULL, PxcDataStreamPool* forcePool = NULL, const bool isMeshType = false);
}
#endif
| 2,879 | C | 49.526315 | 168 | 0.783258 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcConstraintBlockStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_CONSTRAINT_BLOCK_POOL_H
#define PXC_CONSTRAINT_BLOCK_POOL_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
#include "PxcNpMemBlockPool.h"
namespace physx
{
class PxsConstraintBlockManager
{
public:
PxsConstraintBlockManager(PxcNpMemBlockPool & blockPool):
mBlockPool(blockPool)
{
}
PX_FORCE_INLINE void reset()
{
mBlockPool.releaseConstraintBlocks(mTrackingArray);
}
PxcNpMemBlockArray mTrackingArray;
PxcNpMemBlockPool& mBlockPool;
private:
PxsConstraintBlockManager& operator=(const PxsConstraintBlockManager&);
};
class PxcConstraintBlockStream
{
PX_NOCOPY(PxcConstraintBlockStream)
public:
PxcConstraintBlockStream(PxcNpMemBlockPool & blockPool) :
mBlockPool (blockPool),
mBlock (NULL),
mUsed (0)
{
}
PX_FORCE_INLINE PxU8* reserve(PxU32 size, PxsConstraintBlockManager& manager)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
return mBlockPool.acquireExceptionalConstraintMemory(size);
if(mBlock == NULL || size+mUsed>PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireConstraintBlock(manager.mTrackingArray);
PX_ASSERT(0==mBlock || mBlock->data == reinterpret_cast<PxU8*>(mBlock));
mUsed = size;
return reinterpret_cast<PxU8*>(mBlock);
}
PX_ASSERT(mBlock && mBlock->data == reinterpret_cast<PxU8*>(mBlock));
PxU8* PX_RESTRICT result = mBlock->data+mUsed;
mUsed += size;
return result;
}
PX_FORCE_INLINE void reset()
{
mBlock = NULL;
mUsed = 0;
}
PX_FORCE_INLINE PxcNpMemBlockPool& getMemBlockPool() { return mBlockPool; }
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock; // current constraint block
PxU32 mUsed; // number of bytes used in constraint block
//Tracking peak allocations
PxU32 mPeakUsed;
};
class PxcContactBlockStream
{
PX_NOCOPY(PxcContactBlockStream)
public:
PxcContactBlockStream(PxcNpMemBlockPool & blockPool):
mBlockPool(blockPool),
mBlock(NULL),
mUsed(0)
{
}
PX_FORCE_INLINE PxU8* reserve(PxU32 size)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
return mBlockPool.acquireExceptionalConstraintMemory(size);
PX_ASSERT(size <= PxcNpMemBlock::SIZE);
if(mBlock == NULL || size+mUsed>PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireContactBlock();
PX_ASSERT(0==mBlock || mBlock->data == reinterpret_cast<PxU8*>(mBlock));
mUsed = size;
return reinterpret_cast<PxU8*>(mBlock);
}
PX_ASSERT(mBlock && mBlock->data == reinterpret_cast<PxU8*>(mBlock));
PxU8* PX_RESTRICT result = mBlock->data+mUsed;
mUsed += size;
return result;
}
PX_FORCE_INLINE void reset()
{
mBlock = NULL;
mUsed = 0;
}
PX_FORCE_INLINE PxcNpMemBlockPool& getMemBlockPool() { return mBlockPool; }
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock; // current constraint block
PxU32 mUsed; // number of bytes used in constraint block
};
}
#endif
| 4,995 | C | 31.232258 | 84 | 0.682082 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpBatch.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_BATCH_H
#define PXC_NP_BATCH_H
#include "PxvConfig.h"
namespace physx
{
struct PxcNpWorkUnit;
class PxcNpThreadContext;
struct PxsContactManagerOutput;
namespace Gu
{
struct Cache;
}
void PxcDiscreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& cmInput, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID);
void PxcDiscreteNarrowPhasePCM(PxcNpThreadContext& context, const PxcNpWorkUnit& cmInput, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID);
}
#endif
| 2,235 | C | 43.719999 | 159 | 0.773602 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_CACHE_H
#define PXC_NP_CACHE_H
#include "foundation/PxMemory.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxPool.h"
#include "foundation/PxUtilities.h"
#include "PxcNpCacheStreamPair.h"
#include "GuContactMethodImpl.h"
namespace physx
{
template <typename T>
void PxcNpCacheWrite(PxcNpCacheStreamPair& streams,
Gu::Cache& cache,
const T& payload,
PxU32 bytes,
const PxU8* data)
{
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
cache.mCachedSize = PxTo16((payloadSize + 4 + bytes + 0xF)&~0xF);
PxU8* ls = streams.reserve(cache.mCachedSize);
cache.mCachedData = ls;
if(ls==NULL || (reinterpret_cast<PxU8*>(-1))==ls)
{
if(ls==NULL)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for narrow phase. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
return;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in narrowphase. "
"Either accept dropped contacts or simplify collision geometry.");
cache.mCachedData = NULL;
ls = NULL;
return;
}
}
*reinterpret_cast<T*>(ls) = payload;
*reinterpret_cast<PxU32*>(ls+payloadSize) = bytes;
if(data)
PxMemCopy(ls+payloadSize+sizeof(PxU32), data, bytes);
}
template <typename T>
PxU8* PxcNpCacheWriteInitiate(PxcNpCacheStreamPair& streams, Gu::Cache& cache, const T& payload, PxU32 bytes)
{
PX_UNUSED(payload);
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
cache.mCachedSize = PxTo16((payloadSize + 4 + bytes + 0xF)&~0xF);
PxU8* ls = streams.reserve(cache.mCachedSize);
cache.mCachedData = ls;
if(NULL==ls || reinterpret_cast<PxU8*>(-1)==ls)
{
if(NULL==ls)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for narrow phase. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in narrowphase. "
"Either accept dropped contacts or simplify collision geometry.");
cache.mCachedData = NULL;
ls = NULL;
}
}
return ls;
}
template <typename T>
PX_FORCE_INLINE void PxcNpCacheWriteFinalize(PxU8* ls, const T& payload, PxU32 bytes, const PxU8* data)
{
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
*reinterpret_cast<T*>(ls) = payload;
*reinterpret_cast<PxU32*>(ls+payloadSize) = bytes;
if(data)
PxMemCopy(ls+payloadSize+sizeof(PxU32), data, bytes);
}
template <typename T>
PX_FORCE_INLINE PxU8* PxcNpCacheRead(Gu::Cache& cache, T*& payload)
{
PxU8* ls = cache.mCachedData;
payload = reinterpret_cast<T*>(ls);
const PxU32 payloadSize = (sizeof(T)+3)&~3;
return reinterpret_cast<PxU8*>(ls+payloadSize+sizeof(PxU32));
}
template <typename T>
const PxU8* PxcNpCacheRead2(Gu::Cache& cache, T& payload, PxU32& bytes)
{
const PxU8* ls = cache.mCachedData;
if(ls==NULL)
{
bytes = 0;
return NULL;
}
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
payload = *reinterpret_cast<const T*>(ls);
bytes = *reinterpret_cast<const PxU32*>(ls+payloadSize);
PX_ASSERT(cache.mCachedSize == ((payloadSize + 4 + bytes+0xF)&~0xF));
return reinterpret_cast<const PxU8*>(ls+payloadSize+sizeof(PxU32));
}
}
#endif
| 5,161 | C | 32.738562 | 140 | 0.728347 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpThreadContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_THREAD_CONTEXT_H
#define PXC_NP_THREAD_CONTEXT_H
#include "geometry/PxGeometry.h"
#include "geomutils/PxContactBuffer.h"
#include "common/PxRenderOutput.h"
#include "CmRenderBuffer.h"
#include "PxvConfig.h"
#include "CmScaling.h"
#include "PxcNpCacheStreamPair.h"
#include "PxcConstraintBlockStream.h"
#include "PxcThreadCoherentCache.h"
#include "PxcScratchAllocator.h"
#include "foundation/PxBitMap.h"
#include "../pcm/GuPersistentContactManifold.h"
#include "../contact/GuContactMethodImpl.h"
namespace physx
{
class PxsTransformCache;
class PxsMaterialManager;
namespace Sc
{
class BodySim;
}
/*!
Per-thread context used by contact generation routines.
*/
struct PxcDataStreamPool
{
PxU8* mDataStream;
PxI32 mSharedDataIndex;
PxU32 mDataStreamSize;
PxU32 mSharedDataIndexGPU;
bool isOverflown() const
{
//FD: my expectaton is that reading those variables is atomic, shared indices are non-decreasing,
//so we can only get a false overflow alert because of concurrency issues, which is not a big deal as it means
//it did overflow a bit later
return (mSharedDataIndex + mSharedDataIndexGPU) > mDataStreamSize;
}
};
struct PxcNpContext
{
private:
PX_NOCOPY(PxcNpContext)
public:
PxcNpContext() :
mNpMemBlockPool (mScratchAllocator),
mMeshContactMargin (0.0f),
mToleranceLength (0.0f),
mContactStreamPool (NULL),
mPatchStreamPool (NULL),
mForceAndIndiceStreamPool(NULL),
mMaterialManager (NULL)
{
}
PxcScratchAllocator mScratchAllocator;
PxcNpMemBlockPool mNpMemBlockPool;
PxReal mMeshContactMargin;
PxReal mToleranceLength;
Cm::RenderBuffer mRenderBuffer;
PxcDataStreamPool* mContactStreamPool;
PxcDataStreamPool* mPatchStreamPool;
PxcDataStreamPool* mForceAndIndiceStreamPool;
PxcDataStreamPool* mConstraintWriteBackStreamPool;
PxsMaterialManager* mMaterialManager;
PX_FORCE_INLINE PxReal getToleranceLength() const { return mToleranceLength; }
PX_FORCE_INLINE void setToleranceLength(PxReal x) { mToleranceLength = x; }
PX_FORCE_INLINE PxReal getMeshContactMargin() const { return mMeshContactMargin; }
PX_FORCE_INLINE void setMeshContactMargin(PxReal x) { mMeshContactMargin = x; }
PX_FORCE_INLINE PxcNpMemBlockPool& getNpMemBlockPool() { return mNpMemBlockPool; }
PX_FORCE_INLINE const PxcNpMemBlockPool& getNpMemBlockPool() const { return mNpMemBlockPool; }
PX_FORCE_INLINE void setMaterialManager(PxsMaterialManager* m){ mMaterialManager = m; }
PX_FORCE_INLINE PxsMaterialManager* getMaterialManager() const { return mMaterialManager; }
};
class PxcNpThreadContext : public PxcThreadCoherentCache<PxcNpThreadContext, PxcNpContext>::EntryBase
{
PX_NOCOPY(PxcNpThreadContext)
public:
PxcNpThreadContext(PxcNpContext* params);
~PxcNpThreadContext();
#if PX_ENABLE_SIM_STATS
void clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PX_FORCE_INLINE void addLocalNewTouchCount(PxU32 newTouchCMCount) { mLocalNewTouchCount += newTouchCMCount; }
PX_FORCE_INLINE void addLocalLostTouchCount(PxU32 lostTouchCMCount) { mLocalLostTouchCount += lostTouchCMCount; }
PX_FORCE_INLINE PxU32 getLocalNewTouchCount() const { return mLocalNewTouchCount; }
PX_FORCE_INLINE PxU32 getLocalLostTouchCount() const { return mLocalLostTouchCount; }
PX_FORCE_INLINE PxBitMap& getLocalChangeTouch() { return mLocalChangeTouch; }
void reset(PxU32 cmCount);
// debugging
PxRenderOutput mRenderOutput;
// dsequeira: Need to think about this block pool allocation a bit more. Ideally we'd be
// taking blocks from a single pool, except that we want to be able to selectively reclaim
// blocks if the user needs to defragment, depending on which artifacts they're willing
// to tolerate, such that the blocks we don't reclaim are contiguous.
#if PX_ENABLE_SIM_STATS
PxU32 mDiscreteContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mModifiedContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxcContactBlockStream mContactBlockStream; // constraint block pool
PxcNpCacheStreamPair mNpCacheStreamPair; // narrow phase pairwise data cache
// Everything below here is scratch state. Most of it can even overlap.
// temporary contact buffer
PxContactBuffer mContactBuffer;
PX_ALIGN(16, Gu::MultiplePersistentContactManifold mTempManifold);
Gu::NarrowPhaseParams mNarrowPhaseParams;
// DS: this stuff got moved here from the PxcNpPairContext. As Pierre says:
////////// PT: those members shouldn't be there in the end, it's not necessary
PxArray<Sc::BodySim*> mBodySimPool;
PxsTransformCache* mTransformCache;
const PxReal* mContactDistances;
bool mPCM;
bool mContactCache;
bool mCreateAveragePoint; // flag to enforce whether we create average points
#if PX_ENABLE_SIM_STATS
PxU32 mCompressedCacheSize;
PxU32 mNbDiscreteContactPairsWithCacheHits;
PxU32 mNbDiscreteContactPairsWithContacts;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxReal mDt; // AP: still needed for ccd
PxU32 mCCDPass;
PxU32 mCCDFaceIndex;
PxU32 mMaxPatches;
//PxU32 mTotalContactCount;
PxU32 mTotalCompressedCacheSize;
//PxU32 mTotalPatchCount;
PxcDataStreamPool* mContactStreamPool;
PxcDataStreamPool* mPatchStreamPool;
PxcDataStreamPool* mForceAndIndiceStreamPool; //this stream is used to store the force buffer and triangle index if we are performing mesh/heightfield contact gen
PxcDataStreamPool* mConstraintWriteBackStreamPool;
PxsMaterialManager* mMaterialManager;
private:
// change touch handling.
PxBitMap mLocalChangeTouch;
PxU32 mLocalNewTouchCount;
PxU32 mLocalLostTouchCount;
};
}
#endif
| 7,962 | C | 38.034314 | 169 | 0.72846 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/collision/PxcContactMethodImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_CONTACT_METHOD_IMPL_H
#define PXC_CONTACT_METHOD_IMPL_H
#include "GuContactMethodImpl.h"
namespace physx
{
/*!
Method prototype for contact generation routines
*/
typedef bool (*PxcContactMethod) (GU_CONTACT_METHOD_ARGS);
// Matrix of types
extern PxcContactMethod g_ContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT];
extern const bool g_CanUseContactCache[][PxGeometryType::eGEOMETRY_COUNT];
extern PxcContactMethod g_PCMContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT];
extern bool gEnablePCMCaching[][PxGeometryType::eGEOMETRY_COUNT];
}
#endif
| 2,272 | C | 43.568627 | 83 | 0.775088 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/utils/PxcScratchAllocator.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_SCRATCH_ALLOCATOR_H
#define PXC_SCRATCH_ALLOCATOR_H
#include "foundation/PxAssert.h"
#include "PxvConfig.h"
#include "foundation/PxMutex.h"
#include "foundation/PxArray.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
class PxcScratchAllocator : public PxUserAllocated
{
PX_NOCOPY(PxcScratchAllocator)
public:
PxcScratchAllocator() : mStack("PxcScratchAllocator"), mStart(NULL), mSize(0)
{
mStack.reserve(64);
mStack.pushBack(0);
}
void setBlock(void* addr, PxU32 size)
{
PX_ASSERT(!(size&15));
// if the stack is not empty then some scratch memory was not freed on the previous frame. That's
// likely indicative of a problem, because when the scratch block is too small the memory will have
// come from the heap
PX_ASSERT(mStack.size()==1);
mStack.popBack();
mStart = reinterpret_cast<PxU8*>(addr);
mSize = size;
mStack.pushBack(mStart + size);
}
void* allocAll(PxU32& size)
{
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>0);
size = PxU32(mStack.back()-mStart);
if(size==0)
return NULL;
mStack.pushBack(mStart);
return mStart;
}
void* alloc(PxU32 requestedSize, bool fallBackToHeap = false)
{
requestedSize = (requestedSize+15)&~15;
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>=1);
PxU8* top = mStack.back();
if(top - mStart >= ptrdiff_t(requestedSize))
{
PxU8* addr = top - requestedSize;
mStack.pushBack(addr);
return addr;
}
if(!fallBackToHeap)
return NULL;
return PX_ALLOC(requestedSize, "Scratch Block Fallback");
}
void free(void* addr)
{
PX_ASSERT(addr!=NULL);
if(!isScratchAddr(addr))
{
PX_FREE(addr);
return;
}
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>1);
PxU32 i=mStack.size()-1;
while(mStack[i]<addr)
i--;
PX_ASSERT(mStack[i]==addr);
mStack.remove(i);
}
bool isScratchAddr(void* addr) const
{
PxU8* a = reinterpret_cast<PxU8*>(addr);
return a>= mStart && a<mStart+mSize;
}
private:
PxMutex mLock;
PxArray<PxU8*> mStack;
PxU8* mStart;
PxU32 mSize;
};
}
#endif
| 3,831 | C | 26.768116 | 101 | 0.719394 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/utils/PxcThreadCoherentCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_THREAD_COHERENT_CACHE_H
#define PXC_THREAD_COHERENT_CACHE_H
#include "foundation/PxMutex.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxSList.h"
namespace physx
{
class PxsContext;
/*!
Controls a pool of large objects which must be thread safe.
Tries to return the object most recently used by the thread(for better cache coherancy).
Assumes the object has a default contructor.
(Note the semantics are different to a pool because we dont want to construct/destroy each time
an object is requested, which may be expensive).
TODO: add thread coherancy.
*/
template<class T, class Params>
class PxcThreadCoherentCache : public PxAlignedAllocator<16, PxReflectionAllocator<T> >
{
typedef PxAlignedAllocator<16, PxReflectionAllocator<T> > Allocator;
PX_NOCOPY(PxcThreadCoherentCache)
public:
typedef PxSListEntry EntryBase;
PX_INLINE PxcThreadCoherentCache(Params* params, const Allocator& alloc = Allocator()) : Allocator(alloc), mParams(params)
{
}
PX_INLINE ~PxcThreadCoherentCache()
{
T* np = static_cast<T*>(root.pop());
while(np!=NULL)
{
np->~T();
Allocator::deallocate(np);
np = static_cast<T*>(root.pop());
}
}
PX_INLINE T* get()
{
T* rv = static_cast<T*>(root.pop());
if(rv==NULL)
{
rv = reinterpret_cast<T*>(Allocator::allocate(sizeof(T), PX_FL));
PX_PLACEMENT_NEW(rv, T(mParams));
}
return rv;
}
PX_INLINE void put(T* item)
{
root.push(*item);
}
private:
PxSList root;
Params* mParams;
template<class T2, class P2>
friend class PxcThreadCoherentCacheIterator;
};
/*!
Used to iterate over all objects controlled by the cache.
Note: The iterator flushes the cache(extracts all items on construction and adds them back on
destruction so we can iterate the list in a safe manner).
*/
template<class T, class Params>
class PxcThreadCoherentCacheIterator
{
public:
PxcThreadCoherentCacheIterator(PxcThreadCoherentCache<T, Params>& cache) : mCache(cache)
{
mNext = cache.root.flush();
mFirst = mNext;
}
~PxcThreadCoherentCacheIterator()
{
PxSListEntry* np = mFirst;
while(np != NULL)
{
PxSListEntry* npNext = np->next();
mCache.root.push(*np);
np = npNext;
}
}
PX_INLINE T* getNext()
{
if(mNext == NULL)
return NULL;
T* rv = static_cast<T*>(mNext);
mNext = mNext->next();
return rv;
}
private:
PxcThreadCoherentCacheIterator<T, Params>& operator=(const PxcThreadCoherentCacheIterator<T, Params>&);
PxcThreadCoherentCache<T, Params> &mCache;
PxSListEntry* mNext;
PxSListEntry* mFirst;
};
}
#endif
| 4,247 | C | 27.510067 | 123 | 0.73652 |
NVIDIA-Omniverse/PhysX/physx/include/PxSimulationEventCallback.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SIMULATION_EVENT_CALLBACK_H
#define PX_SIMULATION_EVENT_CALLBACK_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMemory.h"
#include "PxPhysXConfig.h"
#include "PxFiltering.h"
#include "PxContact.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxActor;
class PxRigidActor;
class PxRigidBody;
class PxConstraint;
/**
\brief Extra data item types for contact pairs.
@see PxContactPairExtraDataItem.type
*/
struct PxContactPairExtraDataType
{
enum Enum
{
ePRE_SOLVER_VELOCITY, //!< see #PxContactPairVelocity
ePOST_SOLVER_VELOCITY, //!< see #PxContactPairVelocity
eCONTACT_EVENT_POSE, //!< see #PxContactPairPose
eCONTACT_PAIR_INDEX //!< see #PxContactPairIndex
};
};
/**
\brief Base class for items in the extra data stream of contact pairs
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairExtraDataItem() {}
/**
\brief The type of the extra data stream item
*/
PxU8 type;
};
/**
\brief Velocities of the contact pair rigid bodies
This struct is shared by multiple types of extra data items. The #type field allows to distinguish between them:
\li PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY: see #PxPairFlag::ePRE_SOLVER_VELOCITY
\li PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY: see #PxPairFlag::ePOST_SOLVER_VELOCITY
\note For static rigid bodies, the velocities will be set to zero.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairVelocity : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairVelocity() {}
/**
\brief The linear velocity of the rigid bodies
*/
PxVec3 linearVelocity[2];
/**
\brief The angular velocity of the rigid bodies
*/
PxVec3 angularVelocity[2];
};
/**
\brief World space actor poses of the contact pair rigid bodies
@see PxContactPairHeader.extraDataStream PxPairFlag::eCONTACT_EVENT_POSE
*/
struct PxContactPairPose : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairPose() {}
/**
\brief The world space pose of the rigid bodies
*/
PxTransform globalPose[2];
};
/**
\brief Marker for the beginning of a new item set in the extra data stream.
If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same
object multiple times. Also, different shapes of the same actor might gain and lose contact with an other
object over multiple passes. This marker allows to separate the extra data items for each collision case, as well as
distinguish the shape pair reports of different CCD passes.
Example:
Let us assume that an actor a0 with shapes s0_0 and s0_1 hits another actor a1 with shape s1.
First s0_0 will hit s1, then a0 will slightly rotate and s0_1 will hit s1 while s0_0 will lose contact with s1.
Furthermore, let us say that contact event pose information is requested as extra data.
The extra data stream will look like this:
PxContactPairIndexA | PxContactPairPoseA | PxContactPairIndexB | PxContactPairPoseB
The corresponding array of PxContactPair events (see #PxSimulationEventCallback.onContact()) will look like this:
PxContactPair(touch_found: s0_0, s1) | PxContactPair(touch_lost: s0_0, s1) | PxContactPair(touch_found: s0_1, s1)
The #index of PxContactPairIndexA will point to the first entry in the PxContactPair array, for PxContactPairIndexB,
#index will point to the third entry.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairIndex : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairIndex() {}
/**
\brief The next item set in the extra data stream refers to the contact pairs starting at #index in the reported PxContactPair array.
*/
PxU16 index;
};
/**
\brief A class to iterate over a contact pair extra data stream.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairExtraDataIterator
{
/**
\brief Constructor
\param[in] stream Pointer to the start of the stream.
\param[in] size Size of the stream in bytes.
*/
PX_FORCE_INLINE PxContactPairExtraDataIterator(const PxU8* stream, PxU32 size)
: currPtr(stream), endPtr(stream + size), contactPairIndex(0)
{
clearDataPtrs();
}
/**
\brief Advances the iterator to next set of extra data items.
The contact pair extra data stream contains sets of items as requested by the corresponding #PxPairFlag flags
#PxPairFlag::ePRE_SOLVER_VELOCITY, #PxPairFlag::ePOST_SOLVER_VELOCITY, #PxPairFlag::eCONTACT_EVENT_POSE. A set can contain one
item of each plus the PxContactPairIndex item. This method parses the stream and points the iterator
member variables to the corresponding items of the current set, if they are available. If CCD is not enabled,
you should only get one set of items. If CCD with multiple passes is enabled, you might get more than one item
set.
\note Even though contact pair extra data is requested per shape pair, you will not get an item set per shape pair
but one per actor pair. If, for example, an actor has two shapes and both collide with another actor, then
there will only be one item set (since it applies to both shape pairs).
\return True if there was another set of extra data items in the stream, else false.
@see PxContactPairVelocity PxContactPairPose PxContactPairIndex
*/
PX_INLINE bool nextItemSet()
{
clearDataPtrs();
bool foundEntry = false;
bool endOfItemSet = false;
while ((currPtr < endPtr) && (!endOfItemSet))
{
const PxContactPairExtraDataItem* edItem = reinterpret_cast<const PxContactPairExtraDataItem*>(currPtr);
PxU8 type = edItem->type;
switch(type)
{
case PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY:
{
PX_ASSERT(!preSolverVelocity);
preSolverVelocity = static_cast<const PxContactPairVelocity*>(edItem);
currPtr += sizeof(PxContactPairVelocity);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY:
{
postSolverVelocity = static_cast<const PxContactPairVelocity*>(edItem);
currPtr += sizeof(PxContactPairVelocity);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::eCONTACT_EVENT_POSE:
{
eventPose = static_cast<const PxContactPairPose*>(edItem);
currPtr += sizeof(PxContactPairPose);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::eCONTACT_PAIR_INDEX:
{
if (!foundEntry)
{
contactPairIndex = static_cast<const PxContactPairIndex*>(edItem)->index;
currPtr += sizeof(PxContactPairIndex);
foundEntry = true;
}
else
endOfItemSet = true;
}
break;
default:
return foundEntry;
}
}
return foundEntry;
}
private:
/**
\brief Internal helper
*/
PX_FORCE_INLINE void clearDataPtrs()
{
preSolverVelocity = NULL;
postSolverVelocity = NULL;
eventPose = NULL;
}
public:
/**
\brief Current pointer in the stream.
*/
const PxU8* currPtr;
/**
\brief Pointer to the end of the stream.
*/
const PxU8* endPtr;
/**
\brief Pointer to the current pre solver velocity item in the stream. NULL if there is none.
@see PxContactPairVelocity
*/
const PxContactPairVelocity* preSolverVelocity;
/**
\brief Pointer to the current post solver velocity item in the stream. NULL if there is none.
@see PxContactPairVelocity
*/
const PxContactPairVelocity* postSolverVelocity;
/**
\brief Pointer to the current contact event pose item in the stream. NULL if there is none.
@see PxContactPairPose
*/
const PxContactPairPose* eventPose;
/**
\brief The contact pair index of the current item set in the stream.
@see PxContactPairIndex
*/
PxU32 contactPairIndex;
};
/**
\brief Collection of flags providing information on contact report pairs.
@see PxContactPairHeader
*/
struct PxContactPairHeaderFlag
{
enum Enum
{
eREMOVED_ACTOR_0 = (1<<0), //!< The actor with index 0 has been removed from the scene.
eREMOVED_ACTOR_1 = (1<<1) //!< The actor with index 1 has been removed from the scene.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxContactPairHeaderFlag.
@see PxContactPairHeaderFlag
*/
typedef PxFlags<PxContactPairHeaderFlag::Enum, PxU16> PxContactPairHeaderFlags;
PX_FLAGS_OPERATORS(PxContactPairHeaderFlag::Enum, PxU16)
/**
\brief An Instance of this class is passed to PxSimulationEventCallback.onContact().
@see PxSimulationEventCallback.onContact()
*/
struct PxContactPairHeader
{
public:
PX_INLINE PxContactPairHeader() {}
/**
\brief The two actors of the notification shape pairs.
\note The actor pointers might reference deleted actors. This will be the case if PxPairFlag::eNOTIFY_TOUCH_LOST
or PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved actors
gets deleted or removed from the scene. Check the #flags member to see whether that is the case.
Do not dereference a pointer to a deleted actor. The pointer to a deleted actor is only provided
such that user data structures which might depend on the pointer value can be updated.
@see PxActor
*/
PxActor* actors[2];
/**
\brief Stream containing extra data as requested in the PxPairFlag flags of the simulation filter.
This pointer is only valid if any kind of extra data information has been requested for the contact report pair (see #PxPairFlag::ePOST_SOLVER_VELOCITY etc.),
else it will be NULL.
@see PxPairFlag
*/
const PxU8* extraDataStream;
/**
\brief Size of the extra data stream [bytes]
*/
PxU16 extraDataStreamSize;
/**
\brief Additional information on the contact report pair.
@see PxContactPairHeaderFlag
*/
PxContactPairHeaderFlags flags;
/**
\brief pointer to the contact pairs
*/
const struct PxContactPair* pairs;
/**
\brief number of contact pairs
*/
PxU32 nbPairs;
};
/**
\brief Collection of flags providing information on contact report pairs.
@see PxContactPair
*/
struct PxContactPairFlag
{
enum Enum
{
/**
\brief The shape with index 0 has been removed from the actor/scene.
*/
eREMOVED_SHAPE_0 = (1<<0),
/**
\brief The shape with index 1 has been removed from the actor/scene.
*/
eREMOVED_SHAPE_1 = (1<<1),
/**
\brief First actor pair contact.
The provided shape pair marks the first contact between the two actors, no other shape pair has been touching prior to the current simulation frame.
\note: This info is only available if #PxPairFlag::eNOTIFY_TOUCH_FOUND has been declared for the pair.
*/
eACTOR_PAIR_HAS_FIRST_TOUCH = (1<<2),
/**
\brief All contact between the actor pair was lost.
All contact between the two actors has been lost, no shape pairs remain touching after the current simulation frame.
*/
eACTOR_PAIR_LOST_TOUCH = (1<<3),
/**
\brief Internal flag, used by #PxContactPair.extractContacts()
The applied contact impulses are provided for every contact point.
This is the case if #PxPairFlag::eSOLVE_CONTACT has been set for the pair.
*/
eINTERNAL_HAS_IMPULSES = (1<<4),
/**
\brief Internal flag, used by #PxContactPair.extractContacts()
The provided contact point information is flipped with regards to the shapes of the contact pair. This mainly concerns the order of the internal triangle indices.
*/
eINTERNAL_CONTACTS_ARE_FLIPPED = (1<<5)
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxContactPairFlag.
@see PxContactPairFlag
*/
typedef PxFlags<PxContactPairFlag::Enum, PxU16> PxContactPairFlags;
PX_FLAGS_OPERATORS(PxContactPairFlag::Enum, PxU16)
/**
\brief A contact point as used by contact notification
*/
struct PxContactPairPoint
{
/**
\brief The position of the contact point between the shapes, in world space.
*/
PxVec3 position;
/**
\brief The separation of the shapes at the contact point. A negative separation denotes a penetration.
*/
PxReal separation;
/**
\brief The normal of the contacting surfaces at the contact point. The normal direction points from the second shape to the first shape.
*/
PxVec3 normal;
/**
\brief The surface index of shape 0 at the contact point. This is used to identify the surface material.
*/
PxU32 internalFaceIndex0;
/**
\brief The impulse applied at the contact point, in world space. Divide by the simulation time step to get a force value.
*/
PxVec3 impulse;
/**
\brief The surface index of shape 1 at the contact point. This is used to identify the surface material.
*/
PxU32 internalFaceIndex1;
};
/**
\brief Contact report pair information.
Instances of this class are passed to PxSimulationEventCallback.onContact(). If contact reports have been requested for a pair of shapes (see #PxPairFlag),
then the corresponding contact information will be provided through this structure.
@see PxSimulationEventCallback.onContact()
*/
struct PxContactPair
{
public:
PX_INLINE PxContactPair() {}
/**
\brief The two shapes that make up the pair.
\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST
or #PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved shapes
gets deleted. Check the #flags member to see whether that is the case. Do not dereference a pointer to a
deleted shape. The pointer to a deleted shape is only provided such that user data structures which might
depend on the pointer value can be updated.
@see PxShape
*/
PxShape* shapes[2];
/**
\brief Pointer to first patch header in contact stream containing contact patch data
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxU8* contactPatches;
/**
\brief Pointer to first contact point in contact stream containing contact data
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxU8* contactPoints;
/**
\brief Buffer containing applied impulse data.
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxReal* contactImpulses;
/**
\brief Size of the contact stream [bytes] including force buffer
*/
PxU32 requiredBufferSize;
/**
\brief Number of contact points stored in the contact stream
*/
PxU8 contactCount;
/**
\brief Number of contact patches stored in the contact stream
*/
PxU8 patchCount;
/**
\brief Size of the contact stream [bytes] not including force buffer
*/
PxU16 contactStreamSize;
/**
\brief Additional information on the contact report pair.
@see PxContactPairFlag
*/
PxContactPairFlags flags;
/**
\brief Flags raised due to the contact.
The events field is a combination of:
<ul>
<li>PxPairFlag::eNOTIFY_TOUCH_FOUND,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_PERSISTS,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_LOST,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_CCD,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST</li>
</ul>
See the documentation of #PxPairFlag for an explanation of each.
\note eNOTIFY_TOUCH_CCD can get raised even if the pair did not request this event. However, in such a case it will only get
raised in combination with one of the other flags to point out that the other event occured during a CCD pass.
@see PxPairFlag
*/
PxPairFlags events;
PxU32 internalData[2]; // For internal use only
/**
\brief Extracts the contact points from the stream and stores them in a convenient format.
\param[out] userBuffer Array of PxContactPairPoint structures to extract the contact points to. The number of contacts for a pair is defined by #contactCount
\param[in] bufferSize Number of PxContactPairPoint structures the provided buffer can store.
\return Number of contact points written to the buffer.
@see PxContactPairPoint
*/
PX_INLINE PxU32 extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const;
/**
\brief Helper method to clone the contact pair and copy the contact data stream into a user buffer.
The contact data stream is only accessible during the contact report callback. This helper function provides copy functionality
to buffer the contact stream information such that it can get accessed at a later stage.
\param[out] newPair The contact pair info will get copied to this instance. The contact data stream pointer of the copy will be redirected to the provided user buffer. Use NULL to skip the contact pair copy operation.
\param[out] bufferMemory Memory block to store the contact data stream to. At most #requiredBufferSize bytes will get written to the buffer.
*/
PX_INLINE void bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const;
PX_INLINE const PxU32* getInternalFaceIndices() const;
};
PX_INLINE PxU32 PxContactPair::extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const
{
PxU32 nbContacts = 0;
if(contactCount && bufferSize)
{
PxContactStreamIterator iter(contactPatches, contactPoints, getInternalFaceIndices(), patchCount, contactCount);
const PxReal* impulses = contactImpulses;
const PxU32 flippedContacts = (flags & PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED);
const PxU32 hasImpulses = (flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
while(iter.hasNextPatch())
{
iter.nextPatch();
while(iter.hasNextContact())
{
iter.nextContact();
PxContactPairPoint& dst = userBuffer[nbContacts];
dst.position = iter.getContactPoint();
dst.separation = iter.getSeparation();
dst.normal = iter.getContactNormal();
if(!flippedContacts)
{
dst.internalFaceIndex0 = iter.getFaceIndex0();
dst.internalFaceIndex1 = iter.getFaceIndex1();
}
else
{
dst.internalFaceIndex0 = iter.getFaceIndex1();
dst.internalFaceIndex1 = iter.getFaceIndex0();
}
if(hasImpulses)
{
const PxReal impulse = impulses[nbContacts];
dst.impulse = dst.normal * impulse;
}
else
dst.impulse = PxVec3(0.0f);
++nbContacts;
if(nbContacts == bufferSize)
return nbContacts;
}
}
}
return nbContacts;
}
PX_INLINE void PxContactPair::bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const
{
PxU8* patches = bufferMemory;
PxU8* contacts = NULL;
if(patches)
{
contacts = bufferMemory + patchCount * sizeof(PxContactPatch);
PxMemCopy(patches, contactPatches, sizeof(PxContactPatch)*patchCount);
PxMemCopy(contacts, contactPoints, contactStreamSize - (sizeof(PxContactPatch)*patchCount));
}
if(contactImpulses)
{
PxMemCopy(bufferMemory + ((contactStreamSize + 15) & (~15)), contactImpulses, sizeof(PxReal) * contactCount);
}
if (newPair)
{
*newPair = *this;
newPair->contactPatches = patches;
newPair->contactPoints = contacts;
}
}
PX_INLINE const PxU32* PxContactPair::getInternalFaceIndices() const
{
return reinterpret_cast<const PxU32*>(contactImpulses + contactCount);
}
/**
\brief Collection of flags providing information on trigger report pairs.
@see PxTriggerPair
*/
struct PxTriggerPairFlag
{
enum Enum
{
eREMOVED_SHAPE_TRIGGER = (1<<0), //!< The trigger shape has been removed from the actor/scene.
eREMOVED_SHAPE_OTHER = (1<<1), //!< The shape causing the trigger event has been removed from the actor/scene.
eNEXT_FREE = (1<<2) //!< For internal use only.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxTriggerPairFlag.
@see PxTriggerPairFlag
*/
typedef PxFlags<PxTriggerPairFlag::Enum, PxU8> PxTriggerPairFlags;
PX_FLAGS_OPERATORS(PxTriggerPairFlag::Enum, PxU8)
/**
\brief Descriptor for a trigger pair.
An array of these structs gets passed to the PxSimulationEventCallback::onTrigger() report.
\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST
events were requested for the pair and one of the involved shapes gets deleted. Check the #flags member to see
whether that is the case. Do not dereference a pointer to a deleted shape. The pointer to a deleted shape is
only provided such that user data structures which might depend on the pointer value can be updated.
@see PxSimulationEventCallback.onTrigger()
*/
struct PxTriggerPair
{
PX_INLINE PxTriggerPair() {}
PxShape* triggerShape; //!< The shape that has been marked as a trigger.
PxActor* triggerActor; //!< The actor to which triggerShape is attached
PxShape* otherShape; //!< The shape causing the trigger event. \deprecated (see #PxSimulationEventCallback::onTrigger()) If collision between trigger shapes is enabled, then this member might point to a trigger shape as well.
PxActor* otherActor; //!< The actor to which otherShape is attached
PxPairFlag::Enum status; //!< Type of trigger event (eNOTIFY_TOUCH_FOUND or eNOTIFY_TOUCH_LOST). eNOTIFY_TOUCH_PERSISTS events are not supported.
PxTriggerPairFlags flags; //!< Additional information on the pair (see #PxTriggerPairFlag)
};
/**
\brief Descriptor for a broken constraint.
An array of these structs gets passed to the PxSimulationEventCallback::onConstraintBreak() report.
@see PxConstraint PxSimulationEventCallback.onConstraintBreak()
*/
struct PxConstraintInfo
{
PX_INLINE PxConstraintInfo() {}
PX_INLINE PxConstraintInfo(PxConstraint* c, void* extRef, PxU32 t) : constraint(c), externalReference(extRef), type(t) {}
PxConstraint* constraint; //!< The broken constraint.
void* externalReference; //!< The external object which owns the constraint (see #PxConstraintConnector::getExternalReference())
PxU32 type; //!< Unique type ID of the external object. Allows to cast the provided external reference to the appropriate type
};
/**
\brief An interface class that the user can implement in order to receive simulation events.
With the exception of onAdvance(), the events get sent during the call to either #PxScene::fetchResults() or
#PxScene::flushSimulation() with sendPendingReports=true. onAdvance() gets called while the simulation
is running (that is between PxScene::simulate() or PxScene::advance() and PxScene::fetchResults()).
\note SDK state should not be modified from within the callbacks. In particular objects should not
be created or destroyed. If state modification is needed then the changes should be stored to a buffer
and performed after the simulation step.
<b>Threading:</b> With the exception of onAdvance(), it is not necessary to make these callbacks thread safe as
they will only be called in the context of the user thread.
@see PxScene.setSimulationEventCallback() PxScene.getSimulationEventCallback()
*/
class PxSimulationEventCallback
{
public:
/**
\brief This is called when a breakable constraint breaks.
\note The user should not release the constraint shader inside this call!
\note No event will get reported if the constraint breaks but gets deleted while the time step is still being simulated.
\param[in] constraints - The constraints which have been broken.
\param[in] count - The number of constraints
@see PxConstraint PxConstraintDesc.linearBreakForce PxConstraintDesc.angularBreakForce
*/
virtual void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) = 0;
/**
\brief This is called with the actors which have just been woken up.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame
will get reported. For example, let us assume actor A is awake, then A->putToSleep() gets called, then later A->wakeUp() gets called.
At the next simulate/fetchResults() step only an onWake() event will get triggered because that was the last transition.
\note If an actor gets newly added to a scene with properties such that it is awake and the sleep state does not get changed by
the user or simulation, then an onWake() event will get sent at the next simulate/fetchResults() step.
\param[in] actors - The actors which just woke up.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
virtual void onWake(PxActor** actors, PxU32 count) = 0;
/**
\brief This is called with the actors which have just been put to sleep.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame
will get reported. For example, let us assume actor A is asleep, then A->wakeUp() gets called, then later A->putToSleep() gets called.
At the next simulate/fetchResults() step only an onSleep() event will get triggered because that was the last transition (assuming the simulation
does not wake the actor up).
\note If an actor gets newly added to a scene with properties such that it is asleep and the sleep state does not get changed by
the user or simulation, then an onSleep() event will get sent at the next simulate/fetchResults() step.
\param[in] actors - The actors which have just been put to sleep.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
virtual void onSleep(PxActor** actors, PxU32 count) = 0;
/**
\brief This is called when certain contact events occur.
The method will be called for a pair of actors if one of the colliding shape pairs requested contact notification.
You request which events are reported using the filter shader/callback mechanism (see #PxSimulationFilterShader,
#PxSimulationFilterCallback, #PxPairFlag).
Do not keep references to the passed objects, as they will be
invalid after this function returns.
\param[in] pairHeader Information on the two actors whose shapes triggered a contact report.
\param[in] pairs The contact pairs of two actors for which contact reports have been requested. See #PxContactPair.
\param[in] nbPairs The number of provided contact pairs.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxContactPair PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) = 0;
/**
\brief This is called with the current trigger pair events.
Shapes which have been marked as triggers using PxShapeFlag::eTRIGGER_SHAPE will send events
according to the pair flag specification in the filter shader (see #PxPairFlag, #PxSimulationFilterShader).
\note Trigger shapes will no longer send notification events for interactions with other trigger shapes.
\param[in] pairs - The trigger pair events.
\param[in] count - The number of trigger pair events.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxPairFlag PxSimulationFilterShader PxShapeFlag PxShape.setFlag()
*/
virtual void onTrigger(PxTriggerPair* pairs, PxU32 count) = 0;
/**
\brief Provides early access to the new pose of moving rigid bodies.
When this call occurs, rigid bodies having the #PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW
flag set, were moved by the simulation and their new poses can be accessed through the provided buffers.
\note The provided buffers are valid and can be read until the next call to #PxScene::simulate() or #PxScene::collide().
\note This callback gets triggered while the simulation is running. If the provided rigid body references are used to
read properties of the object, then the callback has to guarantee no other thread is writing to the same body at the same
time.
\note The code in this callback should be lightweight as it can block the simulation, that is, the
#PxScene::fetchResults() call.
\param[in] bodyBuffer The rigid bodies that moved and requested early pose reporting.
\param[in] poseBuffer The integrated rigid body poses of the bodies listed in bodyBuffer.
\param[in] count The number of entries in the provided buffers.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW
*/
virtual void onAdvance(const PxRigidBody*const* bodyBuffer, const PxTransform* poseBuffer, const PxU32 count) = 0;
virtual ~PxSimulationEventCallback() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,876 | C | 32.930769 | 230 | 0.754502 |
NVIDIA-Omniverse/PhysX/physx/include/PxContactModifyCallback.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_CONTACT_MODIFY_CALLBACK_H
#define PX_CONTACT_MODIFY_CALLBACK_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxShape.h"
#include "PxContact.h"
#include "foundation/PxTransform.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
/**
\brief An array of contact points, as passed to contact modification.
The word 'set' in the name does not imply that duplicates are filtered in any
way. This initial set of contacts does potentially get reduced to a smaller
set before being passed to the solver.
You can use the accessors to read and write contact properties. The number of
contacts is immutable, other than being able to disable contacts using ignore().
@see PxContactModifyCallback, PxModifiableContact
*/
class PxContactSet
{
public:
/**
\brief Get the position of a specific contact point in the set.
\param[in] i Index of the point in the set
\return Position to the requested point in world space
@see PxModifiableContact.point
*/
PX_FORCE_INLINE const PxVec3& getPoint(PxU32 i) const { return mContacts[i].contact; }
/**
\brief Alter the position of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] p The new position in world space
@see PxModifiableContact.point
*/
PX_FORCE_INLINE void setPoint(PxU32 i, const PxVec3& p) { mContacts[i].contact = p; }
/**
\brief Get the contact normal of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The requested normal in world space
@see PxModifiableContact.normal
*/
PX_FORCE_INLINE const PxVec3& getNormal(PxU32 i) const { return mContacts[i].normal; }
/**
\brief Alter the contact normal of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] n The new normal in world space
\note Changing the normal can cause contact points to be ignored.
@see PxModifiableContact.normal
*/
PX_FORCE_INLINE void setNormal(PxU32 i, const PxVec3& n)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].normal = n;
}
/**
\brief Get the separation distance of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The separation. Negative implies penetration.
@see PxModifiableContact.separation
*/
PX_FORCE_INLINE PxReal getSeparation(PxU32 i) const { return mContacts[i].separation; }
/**
\brief Alter the separation of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] s The new separation
@see PxModifiableContact.separation
*/
PX_FORCE_INLINE void setSeparation(PxU32 i, PxReal s) { mContacts[i].separation = s; }
/**
\brief Get the target velocity of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The target velocity in world frame
@see PxModifiableContact.targetVelocity
*/
PX_FORCE_INLINE const PxVec3& getTargetVelocity(PxU32 i) const { return mContacts[i].targetVelocity; }
/**
\brief Alter the target velocity of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] v The new velocity in world frame as seen from the second actor in the contact pair, i.e., the solver will try to achieve targetVel == (vel1 - vel2)
\note The sign of the velocity needs to be flipped depending on the order of the actors in the pair. There is no guarantee about the consistency of the order from frame to frame.
@see PxModifiableContact.targetVelocity
*/
PX_FORCE_INLINE void setTargetVelocity(PxU32 i, const PxVec3& v)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eHAS_TARGET_VELOCITY;
mContacts[i].targetVelocity = v;
}
/**
\brief Get the face index with respect to the first shape of the pair for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The face index of the first shape
\note At the moment, the first shape is never a tri-mesh, therefore this function always returns PXC_CONTACT_NO_FACE_INDEX
@see PxModifiableContact.internalFaceIndex0
*/
PX_FORCE_INLINE PxU32 getInternalFaceIndex0(PxU32 i) const { PX_UNUSED(i); return PXC_CONTACT_NO_FACE_INDEX; }
/**
\brief Get the face index with respect to the second shape of the pair for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The face index of the second shape
@see PxModifiableContact.internalFaceIndex1
*/
PX_FORCE_INLINE PxU32 getInternalFaceIndex1(PxU32 i) const
{
PxContactPatch* patch = getPatch();
if (patch->internalFlags & PxContactPatch::eHAS_FACE_INDICES)
{
return reinterpret_cast<PxU32*>(mContacts + mCount)[mCount + i];
}
return PXC_CONTACT_NO_FACE_INDEX;
}
/**
\brief Get the maximum impulse for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The maximum impulse
@see PxModifiableContact.maxImpulse
*/
PX_FORCE_INLINE PxReal getMaxImpulse(PxU32 i) const { return mContacts[i].maxImpulse; }
/**
\brief Alter the maximum impulse for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] s The new maximum impulse
\note Must be nonnegative. If set to zero, the contact point will be ignored
@see PxModifiableContact.maxImpulse, ignore()
*/
PX_FORCE_INLINE void setMaxImpulse(PxU32 i, PxReal s)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eHAS_MAX_IMPULSE;
mContacts[i].maxImpulse = s;
}
/**
\brief Get the restitution coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The restitution coefficient
@see PxModifiableContact.restitution
*/
PX_FORCE_INLINE PxReal getRestitution(PxU32 i) const { return mContacts[i].restitution; }
/**
\brief Alter the restitution coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] r The new restitution coefficient
\note Valid ranges [0,1]
@see PxModifiableContact.restitution
*/
PX_FORCE_INLINE void setRestitution(PxU32 i, PxReal r)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].restitution = r;
}
/**
\brief Get the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The friction coefficient (dimensionless)
@see PxModifiableContact.staticFriction
*/
PX_FORCE_INLINE PxReal getStaticFriction(PxU32 i) const { return mContacts[i].staticFriction; }
/**
\brief Alter the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] f The new friction coefficient (dimensionless), range [0, inf]
@see PxModifiableContact.staticFriction
*/
PX_FORCE_INLINE void setStaticFriction(PxU32 i, PxReal f)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].staticFriction = f;
}
/**
\brief Get the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The friction coefficient
@see PxModifiableContact.dynamicFriction
*/
PX_FORCE_INLINE PxReal getDynamicFriction(PxU32 i) const { return mContacts[i].dynamicFriction; }
/**
\brief Alter the static dynamic coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] f The new friction coefficient
@see PxModifiableContact.dynamicFriction
*/
PX_FORCE_INLINE void setDynamicFriction(PxU32 i, PxReal f)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].dynamicFriction = f;
}
/**
\brief Ignore the contact point.
\param[in] i Index of the point in the set
If a contact point is ignored then no force will get applied at this point. This can be used to disable collision in certain areas of a shape, for example.
*/
PX_FORCE_INLINE void ignore(PxU32 i) { setMaxImpulse(i, 0.0f); }
/**
\brief The number of contact points in the set.
*/
PX_FORCE_INLINE PxU32 size() const { return mCount; }
/**
\brief Returns the invMassScale of body 0
A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE PxReal getInvMassScale0() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.linear0;
}
/**
\brief Returns the invMassScale of body 1
A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE PxReal getInvMassScale1() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.linear1;
}
/**
\brief Returns the invInertiaScale of body 0
A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE PxReal getInvInertiaScale0() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.angular0;
}
/**
\brief Returns the invInertiaScale of body 1
A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE PxReal getInvInertiaScale1() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.angular1;
}
/**
\brief Sets the invMassScale of body 0
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE void setInvMassScale0(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.linear0 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invMassScale of body 1
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE void setInvMassScale1(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.linear1 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invInertiaScale of body 0
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE void setInvInertiaScale0(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.angular0 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invInertiaScale of body 1
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE void setInvInertiaScale1(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.angular1 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
protected:
PX_FORCE_INLINE PxContactPatch* getPatch() const
{
const size_t headerOffset = sizeof(PxContactPatch)*mCount;
return reinterpret_cast<PxContactPatch*>(reinterpret_cast<PxU8*>(mContacts) - headerOffset);
}
PxU32 mCount; //!< Number of contact points in the set
PxModifiableContact* mContacts; //!< The contact points of the set
};
/**
\brief An array of instances of this class is passed to PxContactModifyCallback::onContactModify().
@see PxContactModifyCallback
*/
class PxContactModifyPair
{
public:
/**
\brief The actors which make up the pair in contact.
Note that these are the actors as seen by the simulation, and may have been deleted since the simulation step started.
*/
const PxRigidActor* actor[2];
/**
\brief The shapes which make up the pair in contact.
Note that these are the shapes as seen by the simulation, and may have been deleted since the simulation step started.
*/
const PxShape* shape[2];
/**
\brief The shape to world transforms of the two shapes.
These are the transforms as the simulation engine sees them, and may have been modified by the application
since the simulation step started.
*/
PxTransform transform[2];
/**
\brief An array of contact points between these two shapes.
*/
PxContactSet contacts;
};
/**
\brief An interface class that the user can implement in order to modify contact constraints.
<b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the
simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded
parts of the physics engine.
You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in
the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects.
Please note:
+ Raising the contact modification flag will not wake the actors up automatically.
+ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the
filter shader/callback has to be used to clear the contact modification flag.
+ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping.
@see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
class PxContactModifyCallback
{
public:
/**
\brief Passes modifiable arrays of contacts to the application.
The initial contacts are regenerated from scratch each frame by collision detection.
The number of contacts can not be changed, so you cannot add your own contacts. You may however
disable contacts using PxContactSet::ignore().
\param[in,out] pairs The contact pairs that may be modified
\param[in] count Number of contact pairs
@see PxContactModifyPair
*/
virtual void onContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0;
protected:
virtual ~PxContactModifyCallback(){}
};
/**
\brief An interface class that the user can implement in order to modify CCD contact constraints.
<b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the
simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded
parts of the physics engine.
You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in
the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects.
Please note:
+ Raising the contact modification flag will not wake the actors up automatically.
+ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the
filter shader/callback has to be used to clear the contact modification flag.
+ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping.
@see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
class PxCCDContactModifyCallback
{
public:
/**
\brief Passes modifiable arrays of contacts to the application.
The initial contacts are regenerated from scratch each frame by collision detection.
The number of contacts can not be changed, so you cannot add your own contacts. You may however
disable contacts using PxContactSet::ignore().
\param[in,out] pairs The contact pairs that may be modified
\param[in] count Number of contact pairs
*/
virtual void onCCDContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0;
protected:
virtual ~PxCCDContactModifyCallback(){}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 18,893 | C | 34.784091 | 179 | 0.747473 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysicsAPI.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_API_H
#define PX_PHYSICS_API_H
/** \addtogroup physics
@{
*/
/**
This is the main include header for the Physics SDK, for users who
want to use a single #include file.
Alternatively, one can instead directly #include a subset of the below files.
*/
// Foundation SDK
#include "foundation/Px.h"
#include "foundation/PxAlignedMalloc.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxAllocatorCallback.h"
#include "foundation/PxArray.h"
#include "foundation/PxAssert.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxBitAndData.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxBroadcast.h"
#include "foundation/PxErrorCallback.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFlags.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxFoundationConfig.h"
#include "foundation/PxFPU.h"
#include "foundation/PxHash.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxHashSet.h"
#include "foundation/PxInlineAllocator.h"
#include "foundation/PxInlineArray.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxIO.h"
#include "foundation/PxMat33.h"
#include "foundation/PxMat44.h"
#include "foundation/PxMath.h"
#include "foundation/PxMathIntrinsics.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxMemory.h"
#include "foundation/PxMutex.h"
#include "foundation/PxPhysicsVersion.h"
#include "foundation/PxPlane.h"
#include "foundation/PxPool.h"
#include "foundation/PxPreprocessor.h"
#include "foundation/PxProfiler.h"
#include "foundation/PxQuat.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxSList.h"
#include "foundation/PxSocket.h"
#include "foundation/PxSort.h"
#include "foundation/PxStrideIterator.h"
#include "foundation/PxString.h"
#include "foundation/PxSync.h"
#include "foundation/PxTempAllocator.h"
#include "foundation/PxThread.h"
#include "foundation/PxTime.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUnionCast.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVec2.h"
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxVecQuat.h"
#include "foundation/PxVecTransform.h"
//Not physics specific utilities and common code
#include "common/PxCoreUtilityTypes.h"
#include "common/PxPhysXCommonConfig.h"
#include "common/PxRenderBuffer.h"
#include "common/PxBase.h"
#include "common/PxTolerancesScale.h"
#include "common/PxTypeInfo.h"
#include "common/PxStringTable.h"
#include "common/PxSerializer.h"
#include "common/PxMetaData.h"
#include "common/PxMetaDataFlags.h"
#include "common/PxSerialFramework.h"
#include "common/PxInsertionCallback.h"
//Task Manager
#include "task/PxTask.h"
// Cuda Mananger
#if PX_SUPPORT_GPU_PHYSX
#include "gpu/PxGpu.h"
#endif
//Geometry Library
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxBVH.h"
#include "geometry/PxBVHBuildStrategy.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxConvexMesh.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHelpers.h"
#include "geometry/PxGeometryQuery.h"
#include "geometry/PxHeightField.h"
#include "geometry/PxHeightFieldDesc.h"
#include "geometry/PxHeightFieldFlag.h"
#include "geometry/PxHeightFieldGeometry.h"
#include "geometry/PxHeightFieldSample.h"
#include "geometry/PxMeshQuery.h"
#include "geometry/PxMeshScale.h"
#include "geometry/PxPlaneGeometry.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxTriangle.h"
#include "geometry/PxTriangleMesh.h"
#include "geometry/PxTriangleMeshGeometry.h"
#include "geometry/PxTetrahedron.h"
#include "geometry/PxTetrahedronMesh.h"
#include "geometry/PxTetrahedronMeshGeometry.h"
// PhysX Core SDK
#include "PxActor.h"
#include "PxAggregate.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxArticulationJointReducedCoordinate.h"
#include "PxArticulationLink.h"
#include "PxClient.h"
#include "PxConeLimitedConstraint.h"
#include "PxConstraint.h"
#include "PxConstraintDesc.h"
#include "PxContact.h"
#include "PxContactModifyCallback.h"
#include "PxDeletionListener.h"
#include "PxFEMSoftBodyMaterial.h"
#include "PxFiltering.h"
#include "PxForceMode.h"
#include "PxLockedData.h"
#include "PxMaterial.h"
#include "PxParticleBuffer.h"
#include "PxParticleSystem.h"
#include "PxPBDParticleSystem.h"
#include "PxPBDMaterial.h"
#include "PxPhysics.h"
#include "PxPhysXConfig.h"
#include "PxQueryFiltering.h"
#include "PxQueryReport.h"
#include "PxRigidActor.h"
#include "PxRigidBody.h"
#include "PxRigidDynamic.h"
#include "PxRigidStatic.h"
#include "PxScene.h"
#include "PxSceneDesc.h"
#include "PxSceneLock.h"
#include "PxShape.h"
#include "PxSimulationEventCallback.h"
#include "PxSimulationStatistics.h"
#include "PxSoftBody.h"
#include "PxVisualizationParameter.h"
#include "PxPruningStructure.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#include "PxFEMClothMaterial.h"
#include "PxFLIPParticleSystem.h"
#include "PxFLIPMaterial.h"
#include "PxHairSystem.h"
#include "PxMPMMaterial.h"
#include "PxMPMParticleSystem.h"
#endif
//Character Controller
#include "characterkinematic/PxBoxController.h"
#include "characterkinematic/PxCapsuleController.h"
#include "characterkinematic/PxController.h"
#include "characterkinematic/PxControllerBehavior.h"
#include "characterkinematic/PxControllerManager.h"
#include "characterkinematic/PxControllerObstacles.h"
#include "characterkinematic/PxExtended.h"
//Cooking (data preprocessing)
#include "cooking/Pxc.h"
#include "cooking/PxConvexMeshDesc.h"
#include "cooking/PxCooking.h"
#include "cooking/PxTriangleMeshDesc.h"
#include "cooking/PxBVH33MidphaseDesc.h"
#include "cooking/PxBVH34MidphaseDesc.h"
#include "cooking/PxMidphaseDesc.h"
//Extensions to the SDK
#include "extensions/PxDefaultStreams.h"
#include "extensions/PxExtensionsAPI.h"
//Serialization
#include "extensions/PxSerialization.h"
#include "extensions/PxBinaryConverter.h"
#include "extensions/PxRepXSerializer.h"
//Vehicle Simulation
#include "vehicle2/PxVehicleAPI.h"
#include "vehicle/PxVehicleComponents.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleSDK.h"
#include "vehicle/PxVehicleShaders.h"
#include "vehicle/PxVehicleTireFriction.h"
#include "vehicle/PxVehicleUpdate.h"
#include "vehicle/PxVehicleUtil.h"
#include "vehicle/PxVehicleUtilControl.h"
#include "vehicle/PxVehicleUtilSetup.h"
#include "vehicle/PxVehicleUtilTelemetry.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleDriveNW.h"
//Connecting the SDK to Visual Debugger
#include "pvd/PxPvdSceneClient.h"
#include "pvd/PxPvd.h"
#include "pvd/PxPvdTransport.h"
/** @} */
#endif
| 8,680 | C | 33.312253 | 77 | 0.792742 |
NVIDIA-Omniverse/PhysX/physx/include/PxNodeIndex.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_NODEINDEX_H
#define PX_NODEINDEX_H
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#define PX_INVALID_NODE 0xFFFFFFFFu
/**
\brief PxNodeIndex
Node index is the unique index for each actor referenced by the island gen. It contains details like
if the actor is an articulation or rigid body. If it is an articulation, the node index also contains
the link index of the rigid body within the articulation. Also, it contains information to detect whether
the rigid body is static body or not
*/
class PxNodeIndex
{
protected:
PxU64 ind;
public:
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id, PxU32 articLinkId) : ind((PxU64(id) << 32) | (articLinkId << 1) | 1)
{
}
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id = PX_INVALID_NODE) : ind((PxU64(id) << 32))
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 index() const { return PxU32(ind >> 32); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 articulationLinkId() const { return PxU32((ind >> 1) & 0x7FFFFFFF); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 isArticulation() const { return PxU32(ind & 1); }
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isStaticBody() const { return PxU32(ind >> 32) == PX_INVALID_NODE; }
PX_CUDA_CALLABLE bool isValid() const { return PxU32(ind >> 32) != PX_INVALID_NODE; }
PX_CUDA_CALLABLE void setIndices(PxU32 index, PxU32 articLinkId) { ind = ((PxU64(index) << 32) | (articLinkId << 1) | 1); }
PX_CUDA_CALLABLE void setIndices(PxU32 index) { ind = ((PxU64(index) << 32)); }
PX_CUDA_CALLABLE bool operator < (const PxNodeIndex& other) const { return ind < other.ind; }
PX_CUDA_CALLABLE bool operator <= (const PxNodeIndex& other) const { return ind <= other.ind; }
PX_CUDA_CALLABLE bool operator == (const PxNodeIndex& other) const { return ind == other.ind; }
PX_CUDA_CALLABLE PxU64 getInd() const { return ind; }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,668 | C | 39.766666 | 134 | 0.73337 |
NVIDIA-Omniverse/PhysX/physx/include/PxQueryFiltering.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_QUERY_FILTERING_H
#define PX_QUERY_FILTERING_H
/** \addtogroup scenequery
@{
*/
#include "PxPhysXConfig.h"
#include "PxFiltering.h"
#include "PxQueryReport.h"
#include "PxClient.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxRigidActor;
struct PxQueryHit;
/**
\brief Filtering flags for scene queries.
@see PxQueryFilterData.flags
*/
struct PxQueryFlag
{
enum Enum
{
eSTATIC = (1<<0), //!< Traverse static shapes
eDYNAMIC = (1<<1), //!< Traverse dynamic shapes
ePREFILTER = (1<<2), //!< Run the pre-intersection-test filter (see #PxQueryFilterCallback::preFilter())
ePOSTFILTER = (1<<3), //!< Run the post-intersection-test filter (see #PxQueryFilterCallback::postFilter())
eANY_HIT = (1<<4), //!< Abort traversal as soon as any hit is found and return it via callback.block.
//!< Helps query performance. Both eTOUCH and eBLOCK hitTypes are considered hits with this flag.
eNO_BLOCK = (1<<5), //!< All hits are reported as touching. Overrides eBLOCK returned from user filters with eTOUCH.
//!< This is also an optimization hint that may improve query performance.
eBATCH_QUERY_LEGACY_BEHAVIOUR = (1<<6), //!< Run with legacy batch query filter behavior. Raising this flag ensures that
//!< the hardcoded filter equation is neglected. This guarantees that any provided PxQueryFilterCallback
//!< will be utilised, as specified by the ePREFILTER and ePOSTFILTER flags.
eDISABLE_HARDCODED_FILTER = (1<<6), //!< Same as eBATCH_QUERY_LEGACY_BEHAVIOUR, more explicit name making it clearer that this can also be used
//!< with regular/non-batched queries if needed.
eRESERVED = (1<<15) //!< Reserved for internal use
};
};
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eSTATIC==(1<<0));
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eDYNAMIC==(1<<1));
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR==PxQueryFlag::eDISABLE_HARDCODED_FILTER);
/**
\brief Flags typedef for the set of bits defined in PxQueryFlag.
*/
typedef PxFlags<PxQueryFlag::Enum,PxU16> PxQueryFlags;
PX_FLAGS_OPERATORS(PxQueryFlag::Enum,PxU16)
/**
\brief Classification of scene query hits (intersections).
- eNONE: Returning this hit type means that the hit should not be reported.
- eBLOCK: For all raycast, sweep and overlap queries the nearest eBLOCK type hit will always be returned in PxHitCallback::block member.
- eTOUCH: Whenever a raycast, sweep or overlap query was called with non-zero PxHitCallback::nbTouches and PxHitCallback::touches
parameters, eTOUCH type hits that are closer or same distance (touchDistance <= blockDistance condition)
as the globally nearest eBLOCK type hit, will be reported.
- For example, to record all hits from a raycast query, always return eTOUCH.
All hits in overlap() queries are treated as if the intersection distance were zero.
This means the hits are unsorted and all eTOUCH hits are recorded by the callback even if an eBLOCK overlap hit was encountered.
Even though all overlap() blocking hits have zero length, only one (arbitrary) eBLOCK overlap hit is recorded in PxHitCallback::block.
All overlap() eTOUCH type hits are reported (zero touchDistance <= zero blockDistance condition).
For raycast/sweep/overlap calls with zero touch buffer or PxHitCallback::nbTouches member,
only the closest hit of type eBLOCK is returned. All eTOUCH hits are discarded.
@see PxQueryFilterCallback.preFilter PxQueryFilterCallback.postFilter PxScene.raycast PxScene.sweep PxScene.overlap
*/
struct PxQueryHitType
{
enum Enum
{
eNONE = 0, //!< the query should ignore this shape
eTOUCH = 1, //!< a hit on the shape touches the intersection geometry of the query but does not block it
eBLOCK = 2 //!< a hit on the shape blocks the query (does not block overlap queries)
};
};
/**
\brief Scene query filtering data.
Whenever the scene query intersects a shape, filtering is performed in the following order:
\li For non-batched queries only:<br>If the data field is non-zero, and the bitwise-AND value of data AND the shape's
queryFilterData is zero, the shape is skipped
\li If filter callbacks are enabled in flags field (see #PxQueryFlags) they will get invoked accordingly.
\li If neither #PxQueryFlag::ePREFILTER or #PxQueryFlag::ePOSTFILTER is set, the hit defaults
to type #PxQueryHitType::eBLOCK when the value of PxHitCallback::nbTouches provided with the query is zero and to type
#PxQueryHitType::eTOUCH when PxHitCallback::nbTouches is positive.
@see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlag::eANY_HIT
*/
struct PxQueryFilterData
{
/** \brief default constructor */
explicit PX_INLINE PxQueryFilterData() : flags(PxQueryFlag::eDYNAMIC | PxQueryFlag::eSTATIC) {}
/** \brief constructor to set both filter data and filter flags */
explicit PX_INLINE PxQueryFilterData(const PxFilterData& fd, PxQueryFlags f) : data(fd), flags(f) {}
/** \brief constructor to set filter flags only */
explicit PX_INLINE PxQueryFilterData(PxQueryFlags f) : flags(f) {}
PxFilterData data; //!< Filter data associated with the scene query
PxQueryFlags flags; //!< Filter flags (see #PxQueryFlags)
};
/**
\brief Scene query filtering callbacks.
Custom filtering logic for scene query intersection candidates. If an intersection candidate object passes the data based filter
(see #PxQueryFilterData), filtering callbacks are executed if requested (see #PxQueryFilterData.flags)
\li If #PxQueryFlag::ePREFILTER is set, the preFilter function runs before exact intersection tests.
If this function returns #PxQueryHitType::eTOUCH or #PxQueryHitType::eBLOCK, exact testing is performed to
determine the intersection location.
The preFilter function may overwrite the copy of queryFlags it receives as an argument to specify any of #PxHitFlag::eMODIFIABLE_FLAGS
on a per-shape basis. Changes apply only to the shape being filtered, and changes to other flags are ignored.
\li If #PxQueryFlag::ePREFILTER is not set, precise intersection testing is performed using the original query's filterData.flags.
\li If #PxQueryFlag::ePOSTFILTER is set, the postFilter function is called for each intersection to determine the touch/block status.
This overrides any touch/block status previously returned from the preFilter function for this shape.
Filtering calls are not guaranteed to be sorted along the ray or sweep direction.
@see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlags PxHitFlags
*/
class PxQueryFilterCallback
{
public:
/**
\brief This filter callback is executed before the exact intersection test if PxQueryFlag::ePREFILTER flag was set.
\param[in] filterData custom filter data specified as the query's filterData.data parameter.
\param[in] shape A shape that has not yet passed the exact intersection test.
\param[in] actor The shape's actor.
\param[in,out] queryFlags scene query flags from the query's function call (only flags from PxHitFlag::eMODIFIABLE_FLAGS bitmask can be modified)
\return the updated type for this hit (see #PxQueryHitType)
*/
virtual PxQueryHitType::Enum preFilter(const PxFilterData& filterData, const PxShape* shape, const PxRigidActor* actor, PxHitFlags& queryFlags) = 0;
/**
\brief This filter callback is executed if the exact intersection test returned true and PxQueryFlag::ePOSTFILTER flag was set.
\param[in] filterData custom filter data of the query
\param[in] hit Scene query hit information. faceIndex member is not valid for overlap queries. For sweep and raycast queries the hit information can be cast to #PxSweepHit and #PxRaycastHit respectively.
\param[in] shape Hit shape
\param[in] actor Hit actor
\return the updated hit type for this hit (see #PxQueryHitType)
*/
virtual PxQueryHitType::Enum postFilter(const PxFilterData& filterData, const PxQueryHit& hit, const PxShape* shape, const PxRigidActor* actor) = 0;
/**
\brief virtual destructor
*/
virtual ~PxQueryFilterCallback() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,786 | C | 44.948357 | 206 | 0.759963 |
NVIDIA-Omniverse/PhysX/physx/include/PxSmoothing.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SMOOTHING_H
#define PX_SMOOTHING_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
class PxgKernelLauncher;
class PxParticleNeighborhoodProvider;
/**
\brief Ccomputes smoothed positions for a particle system to improve rendering quality
*/
class PxSmoothedPositionGenerator
{
public:
/**
\brief Schedules the compuation of smoothed positions on the specified cuda stream
\param[in] gpuParticleSystem A gpu pointer to access particle system data
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateSmoothedPositions(PxGpuParticleSystem* gpuParticleSystem, PxU32 numParticles, CUstream stream) = 0;
/**
\brief Schedules the compuation of smoothed positions on the specified cuda stream
\param[in] particlePositionsGpu A gpu pointer containing the particle positions
\param[in] neighborhoodProvider A neighborhood provider object that supports fast neighborhood queries
\param[in] numParticles The number of particles
\param[in] particleContactOffset The particle contact offset
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateSmoothedPositions(PxVec4* particlePositionsGpu, PxParticleNeighborhoodProvider& neighborhoodProvider, PxU32 numParticles, PxReal particleContactOffset, CUstream stream) = 0;
/**
\brief Set a host buffer that holds the smoothed position data after the timestep completed
\param[in] smoothedPositions A host buffer with memory for all particles already allocated
*/
virtual void setResultBufferHost(PxVec4* smoothedPositions) = 0;
/**
\brief Set a device buffer that holds the smoothed position data after the timestep completed
\param[in] smoothedPositions A device buffer with memory for all particles already allocated
*/
virtual void setResultBufferDevice(PxVec4* smoothedPositions) = 0;
/**
\brief Sets the intensity of the position smoothing effect
\param[in] smoothingStrenght The strength of the smoothing effect
*/
virtual void setSmoothing(float smoothingStrenght) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the device pointer for the smoothed positions. Only available after calling setResultBufferHost or setResultBufferDevice
\return The device pointer for the smoothed positions
*/
virtual PxVec4* getSmoothedPositionsDevicePointer() const = 0;
/**
\brief Enables or disables the smoothed position generator
\param[in] enabled The boolean to set the generator to enabled or disabled
*/
virtual void setEnabled(bool enabled) = 0;
/**
\brief Allows to query if the smoothed position generator is enabled
\return True if enabled, false otherwise
*/
virtual bool isEnabled() const = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxSmoothedPositionGenerator() {}
};
/**
\brief Default implementation of a particle system callback to trigger smoothed position calculations. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the post solve task completed.
*/
class PxSmoothedPositionCallback : public PxParticleSystemCallback
{
public:
/**
\brief Initializes the smoothing callback
\param[in] smoothedPositionGenerator The smoothed position generator
*/
void initialize(PxSmoothedPositionGenerator* smoothedPositionGenerator)
{
mSmoothedPositionGenerator = smoothedPositionGenerator;
}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream)
{
if (mSmoothedPositionGenerator)
{
mSmoothedPositionGenerator->generateSmoothedPositions(gpuParticleSystem.mDevicePtr, gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream);
}
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
private:
PxSmoothedPositionGenerator* mSmoothedPositionGenerator;
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,555 | C | 33.324607 | 196 | 0.769031 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleNeighborhoodProvider.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H
#define PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
/**
\brief Computes neighborhood information for a point cloud
*/
class PxParticleNeighborhoodProvider
{
public:
/**
\brief Schedules the compuation of neighborhood information on the specified cuda stream
\param[in] deviceParticlePos A gpu pointer containing the particle positions
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
\param[in] devicePhases An optional gpu pointer with particle phases
\param[in] validPhaseMask An optional phase mask to define which particles should be included into the neighborhood computation
\param[in] deviceActiveIndices An optional device pointer containing all indices of particles that are currently active
*/
virtual void buildNeighborhood(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* devicePhases = NULL,
PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid, const PxU32* deviceActiveIndices = NULL) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the maximal number of grid cells
\return The maximal number of grid cells
*/
virtual PxU32 getMaxGridCells() const = 0;
/**
\brief Gets the cell size
\return The cell size
*/
virtual PxReal getCellSize() const = 0;
/**
\brief Gets the number of grid cells in use
\return The number of grid cells in use
*/
virtual PxU32 getNumGridCellsInUse() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxGridCells The maximal number of grid cells
\param[in] cellSize The cell size. Should be equal to 2*contactOffset for PBD particle systems.
*/
virtual void setCellProperties(PxU32 maxGridCells, PxReal cellSize) = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxParticleNeighborhoodProvider() {}
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,383 | C | 31.474074 | 130 | 0.751312 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleSolverType.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_SOLVER_TYPE_H
#define PX_PARTICLE_SOLVER_TYPE_H
/** \addtogroup physics
@{ */
#include "foundation/PxPreprocessor.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
/**
\brief Identifies the solver to use for a particle system.
*/
struct PxParticleSolverType
{
enum Enum
{
ePBD = 1 << 0, //!< The position based dynamics solver that can handle fluid, granular material, cloth, inflatables etc. See #PxPBDParticleSystem.
eFLIP = 1 << 1, //!< The FLIP fluid solver. See #PxFLIPParticleSystem.
eMPM = 1 << 2 //!< The MPM (material point method) solver that can handle a variety of materials. See #PxMPMParticleSystem.
};
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,528 | C | 34.619718 | 150 | 0.743275 |
NVIDIA-Omniverse/PhysX/physx/include/PxAggregate.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_AGGREGATE_H
#define PX_AGGREGATE_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxActor;
class PxBVH;
class PxScene;
struct PxAggregateType
{
enum Enum
{
eGENERIC = 0, //!< Aggregate will contain various actors of unspecified types
eSTATIC = 1, //!< Aggregate will only contain static actors
eKINEMATIC = 2 //!< Aggregate will only contain kinematic actors
};
};
// PxAggregateFilterHint is used for more efficient filtering of aggregates outside of the broadphase.
// It is a combination of a PxAggregateType and a self-collision bit.
typedef PxU32 PxAggregateFilterHint;
PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateFilterHint PxGetAggregateFilterHint(PxAggregateType::Enum type, bool enableSelfCollision)
{
const PxU32 selfCollisionBit = enableSelfCollision ? 1 : 0;
return PxAggregateFilterHint((PxU32(type)<<1)|selfCollisionBit);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxGetAggregateSelfCollisionBit(PxAggregateFilterHint hint)
{
return hint & 1;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateType::Enum PxGetAggregateType(PxAggregateFilterHint hint)
{
return PxAggregateType::Enum(hint>>1);
}
/**
\brief Class to aggregate actors into a single broad-phase entry.
A PxAggregate object is a collection of PxActors, which will exist as a single entry in the
broad-phase structures. This has 3 main benefits:
1) it reduces "broad phase pollution" by allowing a collection of spatially coherent broad-phase
entries to be replaced by a single aggregated entry (e.g. a ragdoll or a single actor with a
large number of attached shapes).
2) it reduces broad-phase memory usage
3) filtering can be optimized a lot if self-collisions within an aggregate are not needed. For
example if you don't need collisions between ragdoll bones, it's faster to simply disable
filtering once and for all, for the aggregate containing the ragdoll, rather than filtering
out each bone-bone collision in the filter shader.
@see PxActor, PxPhysics.createAggregate
*/
class PxAggregate : public PxBase
{
public:
/**
\brief Deletes the aggregate object.
Deleting the PxAggregate object does not delete the aggregated actors. If the PxAggregate object
belongs to a scene, the aggregated actors are automatically re-inserted in that scene. If you intend
to delete both the PxAggregate and its actors, it is best to release the actors first, then release
the PxAggregate when it is empty.
*/
virtual void release() = 0;
/**
\brief Adds an actor to the aggregate object.
A warning is output if the total number of actors is reached, or if the incoming actor already belongs
to an aggregate.
If the aggregate belongs to a scene, adding an actor to the aggregate also adds the actor to that scene.
If the actor already belongs to a scene, a warning is output and the call is ignored. You need to remove
the actor from the scene first, before adding it to the aggregate.
\note When a BVH is provided the actor shapes are grouped together.
The scene query pruning structure inside PhysX SDK will store/update one
bound per actor. The scene queries against such an actor will query actor
bounds and then make a local space query against the provided BVH, which is in actor's local space.
\param [in] actor The actor that should be added to the aggregate
\param [in] bvh BVH for actor shapes.
return true if success
*/
virtual bool addActor(PxActor& actor, const PxBVH* bvh = NULL) = 0;
/**
\brief Removes an actor from the aggregate object.
A warning is output if the incoming actor does not belong to the aggregate. Otherwise the actor is
removed from the aggregate. If the aggregate belongs to a scene, the actor is reinserted in that
scene. If you intend to delete the actor, it is best to call #PxActor::release() directly. That way
the actor will be automatically removed from its aggregate (if any) and not reinserted in a scene.
\param [in] actor The actor that should be removed from the aggregate
return true if success
*/
virtual bool removeActor(PxActor& actor) = 0;
/**
\brief Adds an articulation to the aggregate object.
A warning is output if the total number of actors is reached (every articulation link counts as an actor),
or if the incoming articulation already belongs to an aggregate.
If the aggregate belongs to a scene, adding an articulation to the aggregate also adds the articulation to that scene.
If the articulation already belongs to a scene, a warning is output and the call is ignored. You need to remove
the articulation from the scene first, before adding it to the aggregate.
\param [in] articulation The articulation that should be added to the aggregate
return true if success
*/
virtual bool addArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Removes an articulation from the aggregate object.
A warning is output if the incoming articulation does not belong to the aggregate. Otherwise the articulation is
removed from the aggregate. If the aggregate belongs to a scene, the articulation is reinserted in that
scene. If you intend to delete the articulation, it is best to call #PxArticulationReducedCoordinate::release() directly. That way
the articulation will be automatically removed from its aggregate (if any) and not reinserted in a scene.
\param [in] articulation The articulation that should be removed from the aggregate
return true if success
*/
virtual bool removeArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Returns the number of actors contained in the aggregate.
You can use #getActors() to retrieve the actor pointers.
\return Number of actors contained in the aggregate.
@see PxActor getActors()
*/
virtual PxU32 getNbActors() const = 0;
/**
\brief Retrieves max amount of actors that can be contained in the aggregate.
\return Max actor size.
@see PxPhysics::createAggregate()
*/
virtual PxU32 getMaxNbActors() const = 0;
/**
\brief Retrieves max amount of shapes that can be contained in the aggregate.
\return Max shape size.
@see PxPhysics::createAggregate()
*/
virtual PxU32 getMaxNbShapes() const = 0;
/**
\brief Retrieve all actors contained in the aggregate.
You can retrieve the number of actor pointers by calling #getNbActors()
\param[out] userBuffer The buffer to store the actor pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of actor pointers written to the buffer.
@see PxShape getNbShapes()
*/
virtual PxU32 getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Retrieves the scene which this aggregate belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() = 0;
/**
\brief Retrieves aggregate's self-collision flag.
\return self-collision flag
*/
virtual bool getSelfCollision() const = 0;
virtual const char* getConcreteTypeName() const { return "PxAggregate"; }
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxAggregate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxAggregate(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxAggregate() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxAggregate", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,371 | C | 36.338645 | 134 | 0.762672 |
NVIDIA-Omniverse/PhysX/physx/include/PxSceneQuerySystem.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SCENE_QUERY_SYSTEM_H
#define PX_SCENE_QUERY_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxTransform.h"
#include "PxSceneQueryDesc.h"
#include "PxQueryReport.h"
#include "PxQueryFiltering.h"
#include "geometry/PxGeometryQueryFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
class PxRenderOutput;
class PxGeometry;
class PxRigidActor;
class PxShape;
class PxBVH;
class PxPruningStructure;
/**
\brief Built-in enum for default PxScene pruners
This is passed as a pruner index to various functions in the following APIs.
@see PxSceneQuerySystemBase::forceRebuildDynamicTree PxSceneQuerySystem::preallocate
@see PxSceneQuerySystem::visualize PxSceneQuerySystem::sync PxSceneQuerySystem::prepareSceneQueryBuildStep
*/
enum PxScenePrunerIndex
{
PX_SCENE_PRUNER_STATIC = 0,
PX_SCENE_PRUNER_DYNAMIC = 1,
PX_SCENE_COMPOUND_PRUNER = 0xffffffff
};
/**
\brief Base class for the scene-query system.
Methods defined here are common to both the traditional PxScene API and the PxSceneQuerySystem API.
@see PxScene PxSceneQuerySystem
*/
class PxSceneQuerySystemBase
{
protected:
PxSceneQuerySystemBase() {}
virtual ~PxSceneQuerySystemBase() {}
public:
/** @name Scene Query
*/
//@{
/**
\brief Sets the rebuild rate of the dynamic tree pruning structures.
\param[in] dynamicTreeRebuildRateHint Rebuild rate of the dynamic tree pruning structures.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint getDynamicTreeRebuildRateHint() forceRebuildDynamicTree()
*/
virtual void setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint) = 0;
/**
\brief Retrieves the rebuild rate of the dynamic tree pruning structures.
\return The rebuild rate of the dynamic tree pruning structures.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() forceRebuildDynamicTree()
*/
virtual PxU32 getDynamicTreeRebuildRateHint() const = 0;
/**
\brief Forces dynamic trees to be immediately rebuilt.
\param[in] prunerIndex Index of pruner containing the dynamic tree to rebuild
\note PxScene will call this function with the PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC value.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint()
*/
virtual void forceRebuildDynamicTree(PxU32 prunerIndex) = 0;
/**
\brief Sets scene query update mode
\param[in] updateMode Scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) = 0;
/**
\brief Gets scene query update mode
\return Current scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const = 0;
/**
\brief Retrieves the system's internal scene query timestamp, increased each time a change to the
static scene query structure is performed.
\return scene query static timestamp
*/
virtual PxU32 getStaticTimestamp() const = 0;
/**
\brief Flushes any changes to the scene query representation.
This method updates the state of the scene query representation to match changes in the scene state.
By default, these changes are buffered until the next query is submitted. Calling this function will not change
the results from scene queries, but can be used to ensure that a query will not perform update work in the course of
its execution.
A thread performing updates will hold a write lock on the query structure, and thus stall other querying threads. In multithread
scenarios it can be useful to explicitly schedule the period where this lock may be held for a significant period, so that
subsequent queries issued from multiple threads will not block.
*/
virtual void flushUpdates() = 0;
/**
\brief Performs a raycast against objects in the scene, returns results in a PxRaycastBuffer object
or via a custom user callback implementation inheriting from PxRaycastCallback.
\note Touching hits are not ordered.
\note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in user guide article SceneQuery. User can ignore such objects by employing one of the provided filter mechanisms.
\param[in] origin Origin of the ray.
\param[in] unitDir Normalized direction of the ray.
\param[in] distance Length of the ray. Has to be in the [0, inf) range.
\param[out] hitCall Raycast hit buffer or callback object used to report raycast hits.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] filterData Filtering data passed to the filter shader.
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking.
\param[in] cache Cached hit shape (optional). Ray is tested against cached shape first. If no hit is found the ray gets queried against the scene.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\param[in] queryFlags Optional flags controlling the query.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
@see PxRaycastCallback PxRaycastBuffer PxQueryFilterData PxQueryFilterCallback PxQueryCache PxRaycastHit PxQueryFlag PxQueryFlag::eANY_HIT PxGeometryQueryFlag
*/
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, const PxReal distance,
PxRaycastCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Performs a sweep test against objects in the scene, returns results in a PxSweepBuffer object
or via a custom user callback implementation inheriting from PxSweepCallback.
\note Touching hits are not ordered.
\note If a shape from the scene is already overlapping with the query shape in its starting position,
the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified.
\param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex).
\param[in] pose Pose of the sweep object.
\param[in] unitDir Normalized direction of the sweep.
\param[in] distance Sweep distance. Needs to be in [0, inf) range and >0 if eASSUME_NO_INITIAL_OVERLAP was specified. Will be clamped to PX_MAX_SWEEP_DISTANCE.
\param[out] hitCall Sweep hit buffer or callback object used to report sweep hits.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] filterData Filtering data and simple logic.
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking.
\param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first. If no hit is found the sweep gets queried against the scene.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal.
Note: ePRECISE_SWEEP doesn't support inflation. Therefore the sweep will be performed with zero inflation.
\param[in] queryFlags Optional flags controlling the query.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
@see PxSweepCallback PxSweepBuffer PxQueryFilterData PxQueryFilterCallback PxSweepHit PxQueryCache PxGeometryQueryFlag
*/
virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance,
PxSweepCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, const PxReal inflation = 0.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Performs an overlap test of a given geometry against objects in the scene, returns results in a PxOverlapBuffer object
or via a custom user callback implementation inheriting from PxOverlapCallback.
\note Filtering: returning eBLOCK from user filter for overlap queries will cause a warning (see #PxQueryHitType).
\param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex).
\param[in] pose Pose of the object.
\param[out] hitCall Overlap hit buffer or callback object used to report overlap hits.
\param[in] filterData Filtering data and simple logic. See #PxQueryFilterData #PxQueryFilterCallback
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to overlap.
\param[in] cache Cached hit shape (optional). Overlap is performed against cached shape first. If no hit is found the overlap gets queried against the scene.
\param[in] queryFlags Optional flags controlling the query.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
\note eBLOCK should not be returned from user filters for overlap(). Doing so will result in undefined behavior, and a warning will be issued.
\note If the PxQueryFlag::eNO_BLOCK flag is set, the eBLOCK will instead be automatically converted to an eTOUCH and the warning suppressed.
@see PxOverlapCallback PxOverlapBuffer PxHitFlags PxQueryFilterData PxQueryFilterCallback PxGeometryQueryFlag
*/
virtual bool overlap(const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hitCall,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
//@}
};
/**
\brief Traditional SQ system for PxScene.
Methods defined here are only available through the traditional PxScene API.
Thus PxSceneSQSystem effectively captures the scene-query related part of the PxScene API.
@see PxScene PxSceneQuerySystemBase
*/
class PxSceneSQSystem : public PxSceneQuerySystemBase
{
protected:
PxSceneSQSystem() {}
virtual ~PxSceneSQSystem() {}
public:
/** @name Scene Query
*/
//@{
/**
\brief Sets scene query update mode
\param[in] updateMode Scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
PX_FORCE_INLINE void setSceneQueryUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) { setUpdateMode(updateMode); }
/**
\brief Gets scene query update mode
\return Current scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
PX_FORCE_INLINE PxSceneQueryUpdateMode::Enum getSceneQueryUpdateMode() const { return getUpdateMode(); }
/**
\brief Retrieves the scene's internal scene query timestamp, increased each time a change to the
static scene query structure is performed.
\return scene query static timestamp
*/
PX_FORCE_INLINE PxU32 getSceneQueryStaticTimestamp() const { return getStaticTimestamp(); }
/**
\brief Flushes any changes to the scene query representation.
@see flushUpdates
*/
PX_FORCE_INLINE void flushQueryUpdates() { flushUpdates(); }
/**
\brief Forces dynamic trees to be immediately rebuilt.
\param[in] rebuildStaticStructure True to rebuild the dynamic tree containing static objects
\param[in] rebuildDynamicStructure True to rebuild the dynamic tree containing dynamic objects
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint()
*/
PX_FORCE_INLINE void forceDynamicTreeRebuild(bool rebuildStaticStructure, bool rebuildDynamicStructure)
{
if(rebuildStaticStructure)
forceRebuildDynamicTree(PX_SCENE_PRUNER_STATIC);
if(rebuildDynamicStructure)
forceRebuildDynamicTree(PX_SCENE_PRUNER_DYNAMIC);
}
/**
\brief Return the value of PxSceneQueryDesc::staticStructure that was set when creating the scene with PxPhysics::createScene
@see PxSceneQueryDesc::staticStructure, PxPhysics::createScene
*/
virtual PxPruningStructureType::Enum getStaticStructure() const = 0;
/**
\brief Return the value of PxSceneQueryDesc::dynamicStructure that was set when creating the scene with PxPhysics::createScene
@see PxSceneQueryDesc::dynamicStructure, PxPhysics::createScene
*/
virtual PxPruningStructureType::Enum getDynamicStructure() const = 0;
/**
\brief Executes scene queries update tasks.
This function will refit dirty shapes within the pruner and will execute a task to build a new AABB tree, which is
build on a different thread. The new AABB tree is built based on the dynamic tree rebuild hint rate. Once
the new tree is ready it will be commited in next fetchQueries call, which must be called after.
This function is equivalent to the following PxSceneQuerySystem calls:
Synchronous calls:
- PxSceneQuerySystemBase::flushUpdates()
- handle0 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_STATIC)
- handle1 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_DYNAMIC)
Asynchronous calls:
- PxSceneQuerySystem::sceneQueryBuildStep(handle0);
- PxSceneQuerySystem::sceneQueryBuildStep(handle1);
This function is part of the PxSceneSQSystem interface because it uses the PxScene task system under the hood. But
it calls PxSceneQuerySystem functions, which are independent from this system and could be called in a similar
fashion by a separate, possibly user-defined task manager.
\note If PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED is used, it is required to update the scene queries
using this function.
\param[in] completionTask if non-NULL, this task will have its refcount incremented in sceneQueryUpdate(), then
decremented when the scene is ready to have fetchQueries called. So the task will not run until the
application also calls removeReference().
\param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave
true unless the application is calling the PxTaskManager start/stopSimulation() methods itself.
@see PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED
*/
virtual void sceneQueriesUpdate(PxBaseTask* completionTask = NULL, bool controlSimulation = true) = 0;
/**
\brief This checks to see if the scene queries update has completed.
This does not cause the data available for reading to be updated with the results of the scene queries update, it is simply a status check.
The bool will allow it to either return immediately or block waiting for the condition to be met so that it can return true
\param[in] block When set to true will block until the condition is met.
\return True if the results are available.
@see sceneQueriesUpdate() fetchResults()
*/
virtual bool checkQueries(bool block = false) = 0;
/**
This method must be called after sceneQueriesUpdate. It will wait for the scene queries update to finish. If the user makes an illegal scene queries update call,
the SDK will issue an error message.
If a new AABB tree build finished, then during fetchQueries the current tree within the pruning structure is swapped with the new tree.
\param[in] block When set to true will block until the condition is met, which is tree built task must finish running.
*/
virtual bool fetchQueries(bool block = false) = 0;
//@}
};
typedef PxU32 PxSQCompoundHandle;
typedef PxU32 PxSQPrunerHandle;
typedef void* PxSQBuildStepHandle;
/**
\brief Scene-queries external sub-system for PxScene-based objects.
The default PxScene has hardcoded support for 2 regular pruners + 1 compound pruner, but these interfaces
should work with multiple pruners.
Regular shapes are traditional PhysX shapes that belong to an actor. That actor can be a compound, i.e. it has
more than one shape. *All of these go to the regular pruners*. This is important because it might be misleading:
by default all shapes go to one of the two regular pruners, even shapes that belong to compound actors.
For compound actors, adding all the actor's shapes individually to the SQ system can be costly, since all the
corresponding bounds will always move together and remain close together - that can put a lot of stress on the
code that updates the SQ spatial structures. In these cases it can be more efficient to add the compound's bounds
(i.e. the actor's bounds) to the system, as the first level of a bounds hierarchy. The scene queries would then
be performed against the actor's bounds first, and only visit the shapes' bounds second. This is only useful
for actors that have more than one shape, i.e. compound actors. Such actors added to the SQ system are thus
called "SQ compounds". These objects are managed by the "compound pruner", which is only used when an explicit
SQ compound is added to the SQ system via the addSQCompound call. So in the end one has to distinguish between:
- a "compound shape", which is added to regular pruners as its own individual entity.
- an "SQ compound shape", which is added to the compound pruner as a subpart of an SQ compound actor.
A compound shape has an invalid compound ID, since it does not belong to an SQ compound.
An SQ compound shape has a valid compound ID, that identifies its SQ compound owner.
@see PxScene PxSceneQuerySystemBase
*/
class PxSceneQuerySystem : public PxSceneQuerySystemBase
{
protected:
PxSceneQuerySystem() {}
virtual ~PxSceneQuerySystem() {}
public:
/**
\brief Decrements the reference count of the object and releases it if the new reference count is zero.
*/
virtual void release() = 0;
/**
\brief Acquires a counted reference to this object.
This method increases the reference count of the object by 1. Decrement the reference count by calling release()
*/
virtual void acquireReference() = 0;
/**
\brief Preallocates internal arrays to minimize the amount of reallocations.
The system does not prevent more allocations than given numbers. It is legal to not call this function at all,
or to add more shapes to the system than the preallocated amounts.
\param[in] prunerIndex Index of pruner to preallocate (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene).
\param[in] nbShapes Expected number of (regular) shapes
*/
virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) = 0;
/**
\brief Frees internal memory that may not be in-use anymore.
This is an entry point for reclaiming transient memory allocated at some point by the SQ system,
but which wasn't been immediately freed for performance reason. Calling this function might free
some memory, but it might also produce a new set of allocations in the next frame.
*/
virtual void flushMemory() = 0;
/**
\brief Adds a shape to the SQ system.
The same function is used to add either a regular shape, or a SQ compound shape.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[in] bounds Shape bounds, in world-space for regular shapes, in local-space for SQ compound shapes.
\param[in] transform Shape transform, in world-space for regular shapes, in local-space for SQ compound shapes.
\param[in] compoundHandle Handle of SQ compound owner, or NULL for regular shapes.
\param[in] hasPruningStructure True if the shape is part of a pruning structure. The structure will be merged later, adding the objects will not invalidate the pruner.
@see merge() PxPruningStructure
*/
virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds,
const PxTransform& transform, const PxSQCompoundHandle* compoundHandle=NULL, bool hasPruningStructure=false) = 0;
/**
\brief Removes a shape from the SQ system.
The same function is used to remove either a regular shape, or a SQ compound shape.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
*/
virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape) = 0;
/**
\brief Updates a shape in the SQ system.
The same function is used to update either a regular shape, or a SQ compound shape.
The transforms are eager-evaluated, but the bounds are lazy-evaluated. This means that
the updated transform has to be passed to the update function, while the bounds are automatically
recomputed by the system whenever needed.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[in] transform New shape transform, in world-space for regular shapes, in local-space for SQ compound shapes.
*/
virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) = 0;
/**
\brief Adds a compound to the SQ system.
\param[in] actor The compound actor
\param[in] shapes The compound actor's shapes
\param[in] bvh BVH structure containing the compound's shapes in local space
\param[in] transforms Shape transforms, in local-space
\return SQ compound handle
@see PxBVH PxCooking::createBVH
*/
virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms) = 0;
/**
\brief Removes a compound from the SQ system.
\param[in] compoundHandle SQ compound handle (returned by addSQCompound)
*/
virtual void removeSQCompound(PxSQCompoundHandle compoundHandle) = 0;
/**
\brief Updates a compound in the SQ system.
The compound structures are immediately updated when the call occurs.
\param[in] compoundHandle SQ compound handle (returned by addSQCompound)
\param[in] compoundTransform New actor/compound transform, in world-space
*/
virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) = 0;
/**
\brief Shift the data structures' origin by the specified vector.
Please refer to the notes of the similar function in PxScene.
\param[in] shift Translation vector to shift the origin by.
*/
virtual void shiftOrigin(const PxVec3& shift) = 0;
/**
\brief Visualizes the system's internal data-structures, for debugging purposes.
\param[in] prunerIndex Index of pruner to visualize (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene).
\param[out] out Filled with render output data
@see PxRenderOutput
*/
virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const = 0;
/**
\brief Merges a pruning structure with the SQ system's internal pruners.
\param[in] pruningStructure The pruning structure to merge
@see PxPruningStructure
*/
virtual void merge(const PxPruningStructure& pruningStructure) = 0;
/**
\brief Shape to SQ-pruner-handle mapping function.
This function finds and returns the SQ pruner handle associated with a given (actor/shape) couple
that was previously added to the system. This is needed for the sync function.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[out] prunerIndex Index of pruner the shape belongs to
\return Associated SQ pruner handle.
*/
virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const = 0;
/**
\brief Synchronizes the scene-query system with another system that references the same objects.
This function is used when the scene-query objects also exist in another system that can also update them. For example the scene-query objects
(used for raycast, overlap or sweep queries) might be driven by equivalent objects in an external rigid-body simulation engine. In this case
the rigid-body simulation engine computes the new poses and transforms, and passes them to the scene-query system using this function. It is
more efficient than calling updateSQShape on each object individually, since updateSQShape would end up recomputing the bounds already available
in the rigid-body engine.
\param[in] prunerIndex Index of pruner being synched (PX_SCENE_PRUNER_DYNAMIC for regular PhysX usage)
\param[in] handles Handles of updated objects
\param[in] indices Bounds & transforms indices of updated objects, i.e. object handles[i] has bounds[indices[i]] and transforms[indices[i]]
\param[in] bounds Array of bounds for all objects (not only updated bounds)
\param[in] transforms Array of transforms for all objects (not only updated transforms)
\param[in] count Number of updated objects
\param[in] ignoredIndices Optional bitmap of ignored indices, i.e. update is skipped if ignoredIndices[indices[i]] is set.
@see PxBounds3 PxTransform32 PxBitMap
*/
virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0;
/**
\brief Finalizes updates made to the SQ system.
This function should be called after updates have been made to the SQ system, to fully reflect the changes
inside the internal pruners. In particular it should be called:
- after calls to updateSQShape
- after calls to sync
This function:
- recomputes bounds of manually updated shapes (i.e. either regular or SQ compound shapes modified by updateSQShape)
- updates dynamic pruners (refit operations)
- incrementally rebuilds AABB-trees
The amount of work performed in this function depends on PxSceneQueryUpdateMode.
@see PxSceneQueryUpdateMode updateSQShape() sync()
*/
virtual void finalizeUpdates() = 0;
/**
\brief Prepares asynchronous build step.
This is directly called (synchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there.
This function is called to let the system execute any necessary synchronous operation before the
asynchronous sceneQueryBuildStep() function is called.
If there is any work to do for the specific pruner, the function returns a pruner-specific handle that
will be passed to the corresponding, asynchronous sceneQueryBuildStep function.
\return A pruner-specific handle that will be sent to sceneQueryBuildStep if there is any work to do, i.e. to execute the corresponding sceneQueryBuildStep() call.
\param[in] prunerIndex Index of pruner being built. (PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC when called by PxScene).
\return Null if there is no work to do, otherwise a pruner-specific handle.
@see PxSceneSQSystem::sceneQueriesUpdate sceneQueryBuildStep
*/
virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex) = 0;
/**
\brief Executes asynchronous build step.
This is directly called (asynchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there.
This function incrementally builds the internal trees/pruners. It is called asynchronously, i.e. this can be
called from different threads for building multiple trees at the same time.
\param[in] handle Pruner-specific handle previously returned by the prepareSceneQueryBuildStep function.
@see PxSceneSQSystem::sceneQueriesUpdate prepareSceneQueryBuildStep
*/
virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle) = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,407 | C | 45.283105 | 242 | 0.769625 |
NVIDIA-Omniverse/PhysX/physx/include/PxFEMParameter.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_FEM_PARAMETER_H
#define PX_PHYSICS_FEM_PARAMETER_H
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Set of parameters to control the sleeping and collision behavior of FEM based objects
*/
struct PxFEMParameters
{
public:
/**
\brief Velocity damping value. After every timestep the velocity is reduced while the magnitude of the reduction depends on velocityDamping
<b>Default:</b> 0.05
*/
PxReal velocityDamping;
/**
\brief Threshold that defines the maximal magnitude of the linear motion a fem body can move in one second before it becomes a candidate for sleeping
<b>Default:</b> 0.1
*/
PxReal settlingThreshold;
/**
\brief Threshold that defines the maximal magnitude of the linear motion a fem body can move in one second such that it can go to sleep in the next frame
<b>Default:</b> 0.05
*/
PxReal sleepThreshold;
/**
\brief Damping value that damps the motion of bodies that move slow enough to be candidates for sleeping (see settlingThreshold)
<b>Default:</b> 10
*/
PxReal sleepDamping;
/**
\brief Penetration value that needs to get exceeded before contacts for self collision are generated. Will only have an effect if self collisions are enabled.
<b>Default:</b> 0.1
*/
PxReal selfCollisionFilterDistance;
/**
\brief Stress threshold to deactivate collision contacts in case the tetrahedron's stress magnitude exceeds the threshold
<b>Default:</b> 0.9
*/
PxReal selfCollisionStressTolerance;
#ifndef __CUDACC__
PxFEMParameters()
{
velocityDamping = 0.05f;
settlingThreshold = 0.1f;
sleepThreshold = 0.05f;
sleepDamping = 10.f;
selfCollisionFilterDistance = 0.1f;
selfCollisionStressTolerance = 0.9f;
}
#endif
};
#if !PX_DOXYGEN
}
#endif
#endif
| 3,515 | C | 35.625 | 160 | 0.748222 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysXConfig.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_CONFIG_H
#define PX_PHYSICS_CONFIG_H
/** Configuration include file for PhysX SDK */
/** \addtogroup physics
@{
*/
#include "common/PxPhysXCommonConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 1,980 | C | 37.843137 | 74 | 0.755051 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationTendon.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_TENDON_H
#define PX_ARTICULATION_TENDON_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#include "solver/PxSolverDefs.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxArticulationSpatialTendon;
class PxArticulationFixedTendon;
class PxArticulationLink;
/**
\brief Defines the low/high limits of the length of a tendon.
*/
class PxArticulationTendonLimit
{
public:
PxReal lowLimit;
PxReal highLimit;
};
/**
\brief Defines a spatial tendon attachment point on a link.
*/
class PxArticulationAttachment : public PxBase
{
public:
virtual ~PxArticulationAttachment() {}
/**
\brief Sets the spring rest length for the sub-tendon from the root to this leaf attachment.
Setting this on non-leaf attachments has no effect.
\param[in] restLength The rest length of the spring.
<b>Default:</b> 0
@see getRestLength(), isLeaf()
*/
virtual void setRestLength(const PxReal restLength) = 0;
/**
\brief Gets the spring rest length for the sub-tendon from the root to this leaf attachment.
\return The rest length.
@see setRestLength()
*/
virtual PxReal getRestLength() const = 0;
/**
\brief Sets the low and high limit on the length of the sub-tendon from the root to this leaf attachment.
Setting this on non-leaf attachments has no effect.
\param[in] parameters Struct with the low and high limit.
<b>Default:</b> (PX_MAX_F32, -PX_MAX_F32) (i.e. an invalid configuration that can only work if stiffness is zero)
@see PxArticulationTendonLimit, getLimitParameters(), isLeaf()
*/
virtual void setLimitParameters(const PxArticulationTendonLimit& parameters) = 0;
/**
\brief Gets the low and high limit on the length of the sub-tendon from the root to this leaf attachment.
\return Struct with the low and high limit.
@see PxArticulationTendonLimit, setLimitParameters()
*/
virtual PxArticulationTendonLimit getLimitParameters() const = 0;
/**
\brief Sets the attachment's relative offset in the link actor frame.
\param[in] offset The relative offset in the link actor frame.
@see getRelativeOffset()
*/
virtual void setRelativeOffset(const PxVec3& offset) = 0;
/**
\brief Gets the attachment's relative offset in the link actor frame.
\return The relative offset in the link actor frame.
@see setRelativeOffset()
*/
virtual PxVec3 getRelativeOffset() const = 0;
/**
\brief Sets the attachment coefficient.
\param[in] coefficient The scale that the distance between this attachment and its parent is multiplied by when summing up the spatial tendon's length.
@see getCoefficient()
*/
virtual void setCoefficient(const PxReal coefficient) = 0;
/**
\brief Gets the attachment coefficient.
\return The scale that the distance between this attachment and its parent is multiplied by when summing up the spatial tendon's length.
@see setCoefficient()
*/
virtual PxReal getCoefficient() const = 0;
/**
\brief Gets the articulation link.
\return The articulation link that this attachment is attached to.
*/
virtual PxArticulationLink* getLink() const = 0;
/**
\brief Gets the parent attachment.
\return The parent attachment.
*/
virtual PxArticulationAttachment* getParent() const = 0;
/**
\brief Indicates that this attachment is a leaf, and thus defines a sub-tendon from the root to this attachment.
\return True: This attachment is a leaf and has zero children; False: Not a leaf.
*/
virtual bool isLeaf() const = 0;
/**
\brief Gets the spatial tendon that the attachment is a part of.
\return The tendon.
@see PxArticulationSpatialTendon
*/
virtual PxArticulationSpatialTendon* getTendon() const = 0;
/**
\brief Releases the attachment.
\note Releasing the attachment is not allowed while the articulation is in a scene. In order to
release the attachment, remove and then re-add the articulation to the scene.
@see PxArticulationSpatialTendon::createAttachment()
*/
virtual void release() = 0;
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationAttachment"; }
protected:
PX_INLINE PxArticulationAttachment(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationAttachment(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief Defines a fixed-tendon joint on an articulation joint degree of freedom.
*/
class PxArticulationTendonJoint : public PxBase
{
public:
virtual ~PxArticulationTendonJoint() {}
/**
\brief Sets the tendon joint coefficient.
\param[in] axis The degree of freedom that the tendon joint operates on (must correspond to a degree of freedom of the associated link's incoming joint).
\param[in] coefficient The scale that the axis' joint position is multiplied by when summing up the fixed tendon's length.
\param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint.
\note RecipCoefficient is commonly expected to be 1/coefficient, but it can be set to different values to tune behavior; for example, zero can be used to
have a joint axis only participate in the length computation of the tendon, but not have any tendon force applied to it.
@see getCoefficient()
*/
virtual void setCoefficient(const PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient) = 0;
/**
\brief Gets the tendon joint coefficient.
\param[out] axis The degree of freedom that the tendon joint operates on.
\param[out] coefficient The scale that the axis' joint position is multiplied by when summing up the fixed tendon's length.
\param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint.
@see setCoefficient()
*/
virtual void getCoefficient(PxArticulationAxis::Enum& axis, PxReal& coefficient, PxReal& recipCoefficient) const = 0;
/**
\brief Gets the articulation link.
\return The articulation link (and its incoming joint in particular) that this tendon joint is associated with.
*/
virtual PxArticulationLink* getLink() const = 0;
/**
\brief Gets the parent tendon joint.
\return The parent tendon joint.
*/
virtual PxArticulationTendonJoint* getParent() const = 0;
/**
\brief Gets the tendon that the joint is a part of.
\return The tendon.
@see PxArticulationFixedTendon
*/
virtual PxArticulationFixedTendon* getTendon() const = 0;
/**
\brief Releases a tendon joint.
\note Releasing a tendon joint is not allowed while the articulation is in a scene. In order to
release the joint, remove and then re-add the articulation to the scene.
@see PxArticulationFixedTendon::createTendonJoint()
*/
virtual void release() = 0;
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationTendonJoint"; }
protected:
PX_INLINE PxArticulationTendonJoint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationTendonJoint(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief Common API base class shared by PxArticulationSpatialTendon and PxArticulationFixedTendon.
*/
class PxArticulationTendon : public PxBase
{
public:
/**
\brief Sets the spring stiffness term acting on the tendon length.
\param[in] stiffness The spring stiffness.
<b>Default:</b> 0
@see getStiffness()
*/
virtual void setStiffness(const PxReal stiffness) = 0;
/**
\brief Gets the spring stiffness of the tendon.
\return The spring stiffness.
@see setStiffness()
*/
virtual PxReal getStiffness() const = 0;
/**
\brief Sets the damping term acting both on the tendon length and tendon-length limits.
\param[in] damping The damping term.
<b>Default:</b> 0
@see getDamping()
*/
virtual void setDamping(const PxReal damping) = 0;
/**
\brief Gets the damping term acting both on the tendon length and tendon-length limits.
\return The damping term.
@see setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Sets the limit stiffness term acting on the tendon's length limits.
For spatial tendons, this parameter applies to all its leaf attachments / sub-tendons.
\param[in] stiffness The limit stiffness term.
<b>Default:</b> 0
@see getLimitStiffness()
*/
virtual void setLimitStiffness(const PxReal stiffness) = 0;
/**
\brief Gets the limit stiffness term acting on the tendon's length limits.
For spatial tendons, this parameter applies to all its leaf attachments / sub-tendons.
\return The limit stiffness term.
@see setLimitStiffness()
*/
virtual PxReal getLimitStiffness() const = 0;
/**
\brief Sets the length offset term for the tendon.
An offset defines an amount to be added to the accumulated length computed for the tendon. It allows the
application to actuate the tendon by shortening or lengthening it.
\param[in] offset The offset term. <b>Default:</b> 0
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
@see getOffset()
*/
virtual void setOffset(const PxReal offset, bool autowake = true) = 0;
/**
\brief Gets the length offset term for the tendon.
\return The offset term.
@see setOffset()
*/
virtual PxReal getOffset() const = 0;
/**
\brief Gets the articulation that the tendon is a part of.
\return The articulation.
@see PxArticulationReducedCoordinate
*/
virtual PxArticulationReducedCoordinate* getArticulation() const = 0;
/**
\brief Releases a tendon to remove it from the articulation and free its associated memory.
When an articulation is released, its attached tendons are automatically released.
\note Releasing a tendon is not allowed while the articulation is in a scene. In order to
release the tendon, remove and then re-add the articulation to the scene.
*/
virtual void release() = 0;
virtual ~PxArticulationTendon() {}
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxArticulationTendon(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationTendon(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief A spatial tendon that attaches to an articulation.
A spatial tendon attaches to multiple links in an articulation using a set of PxArticulationAttachments.
The tendon is defined as a tree of attachment points, where each attachment can have an arbitrary number of children.
Each leaf of the attachment tree defines a subtendon between itself and the root attachment. The subtendon then
applies forces at the leaf, and an equal but opposing force at the root, in order to satisfy the spring-damper and limit
constraints that the user sets up. Attachments in between the root and leaf do not exert any force on the articulation,
but define the geometry of the tendon from which the length is computed together with the attachment coefficients.
*/
class PxArticulationSpatialTendon : public PxArticulationTendon
{
public:
/**
\brief Creates an articulation attachment and adds it to the list of children in the parent attachment.
Creating an attachment is not allowed while the articulation is in a scene. In order to
add the attachment, remove and then re-add the articulation to the scene.
\param[in] parent The parent attachment. Can be NULL for the root attachment of a tendon.
\param[in] coefficient A user-defined scale that the accumulated length is scaled by.
\param[in] relativeOffset An offset vector in the link's actor frame to the point where the tendon attachment is attached to the link.
\param[in] link The link that this attachment is associated with.
\return The newly-created attachment if creation was successful, otherwise a null pointer.
@see releaseAttachment()
*/
virtual PxArticulationAttachment* createAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link) = 0;
/**
\brief Fills a user-provided buffer of attachment pointers with the set of attachments.
\param[in] userBuffer The user-provided buffer.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to attachments,
only as many as can fit are written. Use getNbAttachments to size for all attachments.
\param[in] startIndex Index of first attachment pointer to be retrieved.
\return The number of attachments that were filled into the user buffer.
@see getNbAttachments
*/
virtual PxU32 getAttachments(PxArticulationAttachment** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of attachments in the tendon.
\return The number of attachments.
*/
virtual PxU32 getNbAttachments() const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationSpatialTendon"; }
virtual ~PxArticulationSpatialTendon() {}
protected:
PX_INLINE PxArticulationSpatialTendon(PxType concreteType, PxBaseFlags baseFlags) : PxArticulationTendon(concreteType, baseFlags) {}
PX_INLINE PxArticulationSpatialTendon(PxBaseFlags baseFlags) : PxArticulationTendon(baseFlags) {}
};
/**
\brief A fixed tendon that can be used to link multiple degrees of freedom of multiple articulation joints via length and limit constraints.
Fixed tendons allow the simulation of coupled relationships between joint degrees of freedom in an articulation. Fixed tendons do not allow
linking arbitrary joint axes of the articulation: The respective joints must all be directly connected to each other in the articulation structure,
i.e. each of the joints in the tendon must be connected by a single articulation link to another joint in the same tendon. This implies both that
1) fixed tendons can branch along a branching articulation; and 2) they cannot be used to create relationships between axes in a spherical joint with
more than one degree of freedom. Locked joint axes or fixed joints are currently not supported.
*/
class PxArticulationFixedTendon : public PxArticulationTendon
{
public:
/**
\brief Creates an articulation tendon joint and adds it to the list of children in the parent tendon joint.
Creating a tendon joint is not allowed while the articulation is in a scene. In order to
add the joint, remove and then re-add the articulation to the scene.
\param[in] parent The parent tendon joint. Can be NULL for the root tendon joint of a tendon.
\param[in] axis The degree of freedom that this tendon joint is associated with.
\param[in] coefficient A user-defined scale that the accumulated tendon length is scaled by.
\param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint.
\param[in] link The link (and the link's incoming joint in particular) that this tendon joint is associated with.
\return The newly-created tendon joint if creation was successful, otherwise a null pointer.
\note
- The axis motion must not be configured as PxArticulationMotion::eLOCKED.
- The axis cannot be part of a fixed joint, i.e. joint configured as PxArticulationJointType::eFIX.
@see PxArticulationTendonJoint PxArticulationAxis
*/
virtual PxArticulationTendonJoint* createTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) = 0;
/**
\brief Fills a user-provided buffer of tendon-joint pointers with the set of tendon joints.
\param[in] userBuffer The user-provided buffer.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendon joints,
only as many as can fit are written. Use getNbTendonJoints to size for all tendon joints.
\param[in] startIndex Index of first tendon joint pointer to be retrieved.
\return The number of tendon joints filled into the user buffer.
@see getNbTendonJoints
*/
virtual PxU32 getTendonJoints(PxArticulationTendonJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of tendon joints in the tendon.
\return The number of tendon joints.
*/
virtual PxU32 getNbTendonJoints() const = 0;
/**
\brief Sets the spring rest length of the tendon.
The accumulated "length" of a fixed tendon is a linear combination of the joint axis positions that the tendon is
associated with, scaled by the respective tendon joints' coefficients. As such, when the joint positions of all
joints are zero, the accumulated length of a fixed tendon is zero.
The spring of the tendon is not exerting any force on the articulation when the rest length is equal to the
tendon's accumulated length plus the tendon offset.
\param[in] restLength The spring rest length of the tendon.
@see getRestLength()
*/
virtual void setRestLength(const PxReal restLength) = 0;
/**
\brief Gets the spring rest length of the tendon.
\return The spring rest length of the tendon.
@see setRestLength()
*/
virtual PxReal getRestLength() const = 0;
/**
\brief Sets the low and high limit on the length of the tendon.
\param[in] parameter Struct with the low and high limit.
The limits, together with the damping and limit stiffness parameters, act on the accumulated length of the tendon.
@see PxArticulationTendonLimit getLimitParameters() setRestLength()
*/
virtual void setLimitParameters(const PxArticulationTendonLimit& parameter) = 0;
/**
\brief Gets the low and high limit on the length of the tendon.
\return Struct with the low and high limit.
@see PxArticulationTendonLimit setLimitParameters()
*/
virtual PxArticulationTendonLimit getLimitParameters() const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationFixedTendon"; }
virtual ~PxArticulationFixedTendon() {}
protected:
PX_INLINE PxArticulationFixedTendon(PxType concreteType, PxBaseFlags baseFlags) : PxArticulationTendon(concreteType, baseFlags) {}
PX_INLINE PxArticulationFixedTendon(PxBaseFlags baseFlags) : PxArticulationTendon(baseFlags) {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 21,144 | C | 34.838983 | 210 | 0.742575 |
NVIDIA-Omniverse/PhysX/physx/include/PxSparseGridParams.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SPARSE_GRID_PARAMS_H
#define PX_SPARSE_GRID_PARAMS_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxMath.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Parameters to define the sparse grid settings like grid spacing, maximal number of subgrids etc.
*/
struct PxSparseGridParams
{
/**
\brief Default constructor.
*/
PX_INLINE PxSparseGridParams()
{
maxNumSubgrids = 512;
subgridSizeX = 32;
subgridSizeY = 32;
subgridSizeZ = 32;
gridSpacing = 0.2f;
haloSize = 1;
}
/**
\brief Copy constructor.
*/
PX_CUDA_CALLABLE PX_INLINE PxSparseGridParams(const PxSparseGridParams& params)
{
maxNumSubgrids = params.maxNumSubgrids;
subgridSizeX = params.subgridSizeX;
subgridSizeY = params.subgridSizeY;
subgridSizeZ = params.subgridSizeZ;
gridSpacing = params.gridSpacing;
haloSize = params.haloSize;
}
PX_CUDA_CALLABLE PX_INLINE PxU32 getNumCellsPerSubgrid() const
{
return subgridSizeX * subgridSizeY * subgridSizeZ;
}
PX_CUDA_CALLABLE PX_INLINE PxReal getSqrt3dx() const
{
return PxSqrt(3.0f) * gridSpacing;
}
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault()
{
*this = PxSparseGridParams();
}
/**
\brief Assignment operator
*/
PX_INLINE void operator = (const PxSparseGridParams& params)
{
maxNumSubgrids = params.maxNumSubgrids;
subgridSizeX = params.subgridSizeX;
subgridSizeY = params.subgridSizeY;
subgridSizeZ = params.subgridSizeZ;
gridSpacing = params.gridSpacing;
haloSize = params.haloSize;
}
PxU32 maxNumSubgrids; //!< Maximum number of subgrids
PxReal gridSpacing; //!< Grid spacing for the grid
PxU16 subgridSizeX; //!< Subgrid resolution in x dimension (must be an even number)
PxU16 subgridSizeY; //!< Subgrid resolution in y dimension (must be an even number)
PxU16 subgridSizeZ; //!< Subgrid resolution in z dimension (must be an even number)
PxU16 haloSize; //!< Number of halo cell layers around every subgrid cell. Only 0 and 1 are valid values
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,881 | C | 31.35 | 109 | 0.730224 |
NVIDIA-Omniverse/PhysX/physx/include/PxMPMMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_MPM_MATERIAL_H
#define PX_MPM_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxParticleMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief MPM material models
*/
struct PxMPMMaterialModel
{
enum Enum
{
eATTACHED = 1 << 0, //!< Marker to indicate that all particles with an attached material should be treated as attached to whatever object they are located in
eNEO_HOOKEAN = 1 << 1, //!< A Neo-Hookean material model will be used
eELASTIC = 1 << 2, //!< A corotaional cauchy strain based material model will be used
eSNOW = 1 << 3, //!< A corotaional cauchy strain based material model with strain limiting and hardening will be used
eSAND = 1 << 4, //!< A Ducker-Prager elastoplasticity material model will be used
eVON_MISES = 1 << 5 //!< A von Mises material model will be used
};
};
/**
\brief MPM surface types that influence interaction between particles and obstacles
*/
struct PxMPMSurfaceType
{
enum Enum
{
eDEFAULT = 0, //!< Normal surface with friction in tangential direction
eSTICKY = 1 << 0, //!< Surface will always have friction in the tangential and the normal direction
eSLIPPERY = 1 << 1 //!< Surface will not cause any friction
};
};
/**
\brief Optional MPM modes that improve the quality of fracture and/or cutting
*/
struct PxMPMCuttingFlag
{
enum Enum
{
eNONE = 0, //!< No special processing to support cutting will be performed
eSUPPORT_THIN_BLADES = 1 << 0, //!< Special collision detection will be performed to improve support for blade like objects that are thinner than the mpm grid spacing
eENABLE_DAMAGE_TRACKING = 1 << 1 //!< A damage value will get updated on every particle to simulate material weakening to get more realistic crack propagation
};
};
typedef PxFlags<PxMPMCuttingFlag::Enum,PxU16> PxMPMCuttingFlags;
PX_FLAGS_OPERATORS(PxMPMCuttingFlag::Enum,PxU16)
class PxScene;
/**
\brief Material class to represent a set of MPM particle material properties.
@see PxPhysics.createMPMMaterial
*/
class PxMPMMaterial : public PxParticleMaterial
{
public:
/**
\brief Sets stretch and shear damping which dampens stretch and shear motion of MPM bodies. The effect is comparable to viscosity for fluids.
\param[in] stretchAndShearDamping The stretch and shear damping
@see getStretchAndShearDamping()
*/
virtual void setStretchAndShearDamping(PxReal stretchAndShearDamping) = 0;
/**
\brief Retrieves the stretch and shear damping.
\return The stretch and shear damping
@see setStretchAndShearDamping()
*/
virtual PxReal getStretchAndShearDamping() const = 0;
/**
\brief Sets the rotational damping which dampens rotations of mpm bodies
\param[in] rotationalDamping The rotational damping
@see getRotationalDamping()
*/
virtual void setRotationalDamping(PxReal rotationalDamping) = 0;
/**
\brief Retrieves the rotational damping.
\return The rotational damping
@see setRotationalDamping()
*/
virtual PxReal getRotationalDamping() const = 0;
/**
\brief Sets density which influences the body's weight
\param[in] density The material's density
@see getDensity()
*/
virtual void setDensity(PxReal density) = 0;
/**
\brief Retrieves the density value.
\return The density
@see setDensity()
*/
virtual PxReal getDensity() const = 0;
/**
\brief Sets the material model which influences interaction between MPM particles
\param[in] materialModel The material model
@see getMaterialModel()
*/
virtual void setMaterialModel(PxMPMMaterialModel::Enum materialModel) = 0;
/**
\brief Retrieves the material model.
\return The material model
@see setMaterialModel()
*/
virtual PxMPMMaterialModel::Enum getMaterialModel() const = 0;
/**
\brief Sets the cutting flags which can enable damage tracking or thin blade support
\param[in] cuttingFlags The cutting flags
@see getCuttingFlags()
*/
virtual void setCuttingFlags(PxMPMCuttingFlags cuttingFlags) = 0;
/**
\brief Retrieves the cutting flags.
\return The cutting flags
@see setCuttingFlags()
*/
virtual PxMPMCuttingFlags getCuttingFlags() const = 0;
/**
\brief Sets the sand friction angle, only applied if the material model is set to sand
\param[in] sandFrictionAngle The sand friction angle
@see getSandFrictionAngle()
*/
virtual void setSandFrictionAngle(PxReal sandFrictionAngle) = 0;
/**
\brief Retrieves the sand friction angle.
\return The sand friction angle
@see setSandFrictionAngle()
*/
virtual PxReal getSandFrictionAngle() const = 0;
/**
\brief Sets the yield stress, only applied if the material model is set to Von Mises
\param[in] yieldStress The yield stress
@see getYieldStress()
*/
virtual void setYieldStress(PxReal yieldStress) = 0;
/**
\brief Retrieves the yield stress.
\return The yield stress
@see setYieldStress()
*/
virtual PxReal getYieldStress() const = 0;
/**
\brief Set material to plastic
\param[in] isPlastic True if plastic
@see getIsPlastic()
*/
virtual void setIsPlastic(bool isPlastic) = 0;
/**
\brief Returns true if material is plastic
\return True if plastic
@see setIsPlastic()
*/
virtual bool getIsPlastic() const = 0;
/**
\brief Sets Young's modulus which defines the body's stiffness
\param[in] young Young's modulus. <b>Range:</b> [0, PX_MAX_F32)
@see getYoungsModulus()
*/
virtual void setYoungsModulus(PxReal young) = 0;
/**
\brief Retrieves the Young's modulus value.
\return The Young's modulus value.
@see setYoungsModulus()
*/
virtual PxReal getYoungsModulus() const = 0;
/**
\brief Sets Poisson's ratio defines the body's volume preservation. Completely incompressible materials have a Poisson ratio of 0.5 which will lead to numerical problems.
\param[in] poisson Poisson's ratio. <b>Range:</b> [0, 0.5)
@see getPoissons()
*/
virtual void setPoissons(PxReal poisson) = 0;
/**
\brief Retrieves the Poisson's ratio.
\return The Poisson's ratio.
@see setPoissons()
*/
virtual PxReal getPoissons() const = 0;
/**
\brief Sets material hardening coefficient
Tendency to get more rigid under compression. <b>Range:</b> [0, PX_MAX_F32)
\param[in] hardening Material hardening coefficient.
@see getHardening
*/
virtual void setHardening(PxReal hardening) = 0;
/**
\brief Retrieves the hardening coefficient.
\return The hardening coefficient.
@see setHardening()
*/
virtual PxReal getHardening() const = 0;
/**
\brief Sets material critical compression coefficient
Compression clamping threshold (higher means more compression is allowed before yield). <b>Range:</b> [0, 1)
\param[in] criticalCompression Material critical compression coefficient.
@see getCriticalCompression
*/
virtual void setCriticalCompression(PxReal criticalCompression) = 0;
/**
\brief Retrieves the critical compression coefficient.
\return The criticalCompression coefficient.
@see setCriticalCompression()
*/
virtual PxReal getCriticalCompression() const = 0;
/**
\brief Sets material critical stretch coefficient
Stretch clamping threshold (higher means more stretching is allowed before yield). <b>Range:</b> [0, 1]
\param[in] criticalStretch Material critical stretch coefficient.
@see getCriticalStretch
*/
virtual void setCriticalStretch(PxReal criticalStretch) = 0;
/**
\brief Retrieves the critical stretch coefficient.
\return The criticalStretch coefficient.
@see setCriticalStretch()
*/
virtual PxReal getCriticalStretch() const = 0;
/**
\brief Sets material tensile damage sensitivity coefficient
Sensitivity to tensile loads. The higher the sensitivity, the quicker damage will occur under tensile loads. <b>Range:</b> [0, PX_MAX_U32)
\param[in] tensileDamageSensitivity Material tensile damage sensitivity coefficient.
@see getTensileDamageSensitivity
*/
virtual void setTensileDamageSensitivity(PxReal tensileDamageSensitivity) = 0;
/**
\brief Retrieves the tensile damage sensitivity coefficient.
\return The tensileDamageSensitivity coefficient.
@see setTensileDamageSensitivity()
*/
virtual PxReal getTensileDamageSensitivity() const = 0;
/**
\brief Sets material compressive damage sensitivity coefficient
Sensitivity to compressive loads. The higher the sensitivity, the quicker damage will occur under compressive loads <b>Range:</b> [0, PX_MAX_U32)
\param[in] compressiveDamageSensitivity Material compressive damage sensitivity coefficient.
@see getCompressiveDamageSensitivity
*/
virtual void setCompressiveDamageSensitivity(PxReal compressiveDamageSensitivity) = 0;
/**
\brief Retrieves the compressive damage sensitivity coefficient.
\return The compressiveDamageSensitivity coefficient.
@see setCompressiveDamageSensitivity()
*/
virtual PxReal getCompressiveDamageSensitivity() const = 0;
/**
\brief Sets material attractive force residual coefficient
Relative amount of attractive force a fully damaged particle can exert on other particles compared to an undamaged one. <b>Range:</b> [0, 1]
\param[in] attractiveForceResidual Material attractive force residual coefficient.
@see getAttractiveForceResidual
*/
virtual void setAttractiveForceResidual(PxReal attractiveForceResidual) = 0;
/**
\brief Retrieves the attractive force residual coefficient.
\return The attractiveForceResidual coefficient.
@see setAttractiveForceResidual()
*/
virtual PxReal getAttractiveForceResidual() const = 0;
virtual const char* getConcreteTypeName() const { return "PxMPMMaterial"; }
protected:
PX_INLINE PxMPMMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxParticleMaterial(concreteType, baseFlags) {}
PX_INLINE PxMPMMaterial(PxBaseFlags baseFlags) : PxParticleMaterial(baseFlags) {}
virtual ~PxMPMMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxMPMMaterial", PxParticleMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 11,907 | C | 27.556355 | 172 | 0.73419 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationTendonData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_TENDON_DATA_H
#define PX_ARTICULATION_TENDON_DATA_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief PxGpuSpatialTendonData
This data structure is to be used by the direct GPU API for spatial tendon data updates.
@see PxArticulationSpatialTendon PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuSpatialTendonData
{
public:
PxReal stiffness;
PxReal damping;
PxReal limitStiffness;
PxReal offset;
}
PX_ALIGN_SUFFIX(16);
/**
\brief PxGpuFixedTendonData
This data structure is to be used by the direct GPU API for fixed tendon data updates.
@see PxArticulationFixedTendon PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuFixedTendonData : public PxGpuSpatialTendonData
{
public:
PxReal lowLimit;
PxReal highLimit;
PxReal restLength;
PxReal padding;
}
PX_ALIGN_SUFFIX(16);
/**
\brief PxGpuTendonJointCoefficientData
This data structure is to be used by the direct GPU API for fixed tendon joint data updates.
@see PxArticulationTendonJoint PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuTendonJointCoefficientData
{
public:
PxReal coefficient;
PxReal recipCoefficient;
PxU32 axis;
PxU32 pad;
}
PX_ALIGN_SUFFIX(16);
/**
\brief PxGpuTendonAttachmentData
This data structure is to be used by the direct GPU API for spatial tendon attachment data updates.
@see PxArticulationAttachment PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuTendonAttachmentData
{
public:
PxVec3 relativeOffset;
PxReal restLength;
PxReal coefficient;
PxReal lowLimit;
PxReal highLimit;
PxReal padding;
}
PX_ALIGN_SUFFIX(16);
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,590 | C | 28.677686 | 99 | 0.776602 |
NVIDIA-Omniverse/PhysX/physx/include/PxConeLimitedConstraint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_CONE_LIMITED_CONSTRAINT_H
#define PX_CONE_LIMITED_CONSTRAINT_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A constraint descriptor for limiting movement to a conical region.
*/
struct PxConeLimitedConstraint
{
PxConeLimitedConstraint()
{
setToDefault();
}
/**
\brief Set values such that constraint is disabled.
*/
PX_INLINE void setToDefault()
{
mAxis = PxVec3(0.f, 0.f, 0.f);
mAngle = -1.f;
mLowLimit = -1.f;
mHighLimit = -1.f;
}
/**
\brief Checks for valitity.
\return true if the constaint is valid
*/
PX_INLINE bool isValid() const
{
//disabled
if (mAngle < 0.f && mLowLimit < 0.f && mHighLimit < 0.f)
{
return true;
}
if (!mAxis.isNormalized())
{
return false;
}
//negative signifies that cone is disabled
if (mAngle >= PxPi)
{
return false;
}
//negative signifies that distance limits are disabled
if (mLowLimit > mHighLimit && mHighLimit >= 0.0f && mLowLimit >= 0.0f)
{
return false;
}
return true;
}
PxVec3 mAxis; //!< Axis of the cone in actor space
PxReal mAngle; //!< Opening angle in radians, negative indicates unlimited
PxReal mLowLimit; //!< Minimum distance, negative indicates unlimited
PxReal mHighLimit; //!< Maximum distance, negative indicates unlimited
};
/**
\brief Compressed form of cone limit parameters
@see PxConeLimitedConstraint
*/
PX_ALIGN_PREFIX(16)
struct PxConeLimitParams
{
PX_CUDA_CALLABLE PxConeLimitParams() {}
PX_CUDA_CALLABLE PxConeLimitParams(const PxConeLimitedConstraint& coneLimitedConstraint) :
lowHighLimits(coneLimitedConstraint.mLowLimit, coneLimitedConstraint.mHighLimit, 0.0f, 0.0f),
axisAngle(coneLimitedConstraint.mAxis, coneLimitedConstraint.mAngle)
{
}
PxVec4 lowHighLimits; // [lowLimit, highLimit, unused, unused]
PxVec4 axisAngle; // [axis.x, axis.y, axis.z, angle]
}PX_ALIGN_SUFFIX(16);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,717 | C | 27.821705 | 95 | 0.732311 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_MATERIAL_H
#define PX_PARTICLE_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "foundation/PxSimpleTypes.h"
#include "PxBaseMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Material class to represent a set of particle material properties.
@see #PxPhysics.createPBDMaterial, #PxPhysics.createFLIPMaterial, #PxPhysics.createMPMMaterial
*/
class PxParticleMaterial : public PxBaseMaterial
{
public:
/**
\brief Sets friction
\param[in] friction Friction. <b>Range:</b> [0, PX_MAX_F32)
@see #getFriction()
*/
virtual void setFriction(PxReal friction) = 0;
/**
\brief Retrieves the friction value.
\return The friction value.
@see #setFriction()
*/
virtual PxReal getFriction() const = 0;
/**
\brief Sets velocity damping term
\param[in] damping Velocity damping term. <b>Range:</b> [0, PX_MAX_F32)
@see #getDamping
*/
virtual void setDamping(PxReal damping) = 0;
/**
\brief Retrieves the velocity damping term
\return The velocity damping term.
@see #setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Sets adhesion term
\param[in] adhesion adhesion coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getAdhesion
*/
virtual void setAdhesion(PxReal adhesion) = 0;
/**
\brief Retrieves the adhesion term
\return The adhesion term.
@see #setAdhesion()
*/
virtual PxReal getAdhesion() const = 0;
/**
\brief Sets gravity scale term
\param[in] scale gravity scale coefficient. <b>Range:</b> (-PX_MAX_F32, PX_MAX_F32)
@see #getAdhesion
*/
virtual void setGravityScale(PxReal scale) = 0;
/**
\brief Retrieves the gravity scale term
\return The gravity scale term.
@see #setAdhesion()
*/
virtual PxReal getGravityScale() const = 0;
/**
\brief Sets material adhesion radius scale. This is multiplied by the particle rest offset to compute the fall-off distance
at which point adhesion ceases to operate.
\param[in] scale Material adhesion radius scale. <b>Range:</b> [0, PX_MAX_F32)
@see #getAdhesionRadiusScale
*/
virtual void setAdhesionRadiusScale(PxReal scale) = 0;
/**
\brief Retrieves the adhesion radius scale.
\return The adhesion radius scale.
@see #setAdhesionRadiusScale()
*/
virtual PxReal getAdhesionRadiusScale() const = 0;
protected:
PX_INLINE PxParticleMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {}
PX_INLINE PxParticleMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {}
virtual ~PxParticleMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxParticleMaterial", PxBaseMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,408 | C | 27.816993 | 124 | 0.736388 |
NVIDIA-Omniverse/PhysX/physx/include/PxRigidBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_RIGID_BODY_H
#define PX_RIGID_BODY_H
/** \addtogroup physics
@{
*/
#include "PxRigidActor.h"
#include "PxForceMode.h"
#include "PxNodeIndex.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Collection of flags describing the behavior of a rigid body.
@see PxRigidBody.setRigidBodyFlag(), PxRigidBody.getRigidBodyFlags()
*/
struct PxRigidBodyFlag
{
enum Enum
{
/**
\brief Enables kinematic mode for the actor.
Kinematic actors are special dynamic actors that are not
influenced by forces (such as gravity), and have no momentum. They are considered to have infinite
mass and can be moved around the world using the setKinematicTarget() method. They will push
regular dynamic actors out of the way. Kinematics will not collide with static or other kinematic objects.
Kinematic actors are great for moving platforms or characters, where direct motion control is desired.
You can not connect Reduced joints to kinematic actors. Lagrange joints work ok if the platform
is moving with a relatively low, uniform velocity.
<b>Sleeping:</b>
\li Setting this flag on a dynamic actor will put the actor to sleep and set the velocities to 0.
\li If this flag gets cleared, the current sleep state of the actor will be kept.
\note kinematic actors are incompatible with CCD so raising this flag will automatically clear eENABLE_CCD
@see PxRigidDynamic.setKinematicTarget()
*/
eKINEMATIC = (1<<0), //!< Enable kinematic mode for the body.
/**
\brief Use the kinematic target transform for scene queries.
If this flag is raised, then scene queries will treat the kinematic target transform as the current pose
of the body (instead of using the actual pose). Without this flag, the kinematic target will only take
effect with respect to scene queries after a simulation step.
@see PxRigidDynamic.setKinematicTarget()
*/
eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES = (1<<1),
/**
\brief Enables swept integration for the actor.
If this flag is raised and CCD is enabled on the scene, then this body will be simulated by the CCD system to ensure that collisions are not missed due to
high-speed motion. Note individual shape pairs still need to enable PxPairFlag::eDETECT_CCD_CONTACT in the collision filtering to enable the CCD to respond to
individual interactions.
\note kinematic actors are incompatible with CCD so this flag will be cleared automatically when raised on a kinematic actor
*/
eENABLE_CCD = (1<<2), //!< Enable CCD for the body.
/**
\brief Enabled CCD in swept integration for the actor.
If this flag is raised and CCD is enabled, CCD interactions will simulate friction. By default, friction is disabled in CCD interactions because
CCD friction has been observed to introduce some simulation artifacts. CCD friction was enabled in previous versions of the SDK. Raising this flag will result in behavior
that is a closer match for previous versions of the SDK.
\note This flag requires PxRigidBodyFlag::eENABLE_CCD to be raised to have any effect.
*/
eENABLE_CCD_FRICTION = (1<<3),
/**
\brief Register a rigid body to dynamically adjust contact offset based on velocity. This can be used to achieve a CCD effect.
If both eENABLE_CCD and eENABLE_SPECULATIVE_CCD are set on the same body, then angular motions are handled by speculative
contacts (eENABLE_SPECULATIVE_CCD) while linear motions are handled by sweeps (eENABLE_CCD).
*/
eENABLE_SPECULATIVE_CCD = (1<<4),
/**
\brief Register a rigid body for reporting pose changes by the simulation at an early stage.
Sometimes it might be advantageous to get access to the new pose of a rigid body as early as possible and
not wait until the call to fetchResults() returns. Setting this flag will schedule the rigid body to get reported
in #PxSimulationEventCallback::onAdvance(). Please refer to the documentation of that callback to understand
the behavior and limitations of this functionality.
@see PxSimulationEventCallback::onAdvance()
*/
eENABLE_POSE_INTEGRATION_PREVIEW = (1<<5),
/**
\brief Permit CCD to limit maxContactImpulse. This is useful for use-cases like a destruction system but can cause visual artefacts so is not enabled by default.
*/
eENABLE_CCD_MAX_CONTACT_IMPULSE = (1<<6),
/**
\brief Carries over forces/accelerations between frames, rather than clearing them
*/
eRETAIN_ACCELERATIONS = (1<<7),
/**
\brief Forces kinematic-kinematic pairs notifications for this actor.
This flag overrides the global scene-level PxPairFilteringMode setting for kinematic actors.
This is equivalent to having PxPairFilteringMode::eKEEP for pairs involving this actor.
A particular use case is when you have a large amount of kinematic actors, but you are only
interested in interactions between a few of them. In this case it is best to use
PxSceneDesc.kineKineFilteringMode = PxPairFilteringMode::eKILL, and then raise the
eFORCE_KINE_KINE_NOTIFICATIONS flag on the small set of kinematic actors that need
notifications.
\note This has no effect if PxRigidBodyFlag::eKINEMATIC is not set.
\warning Changing this flag at runtime will not have an effect until you remove and re-add the actor to the scene.
@see PxPairFilteringMode PxSceneDesc.kineKineFilteringMode
*/
eFORCE_KINE_KINE_NOTIFICATIONS = (1<<8),
/**
\brief Forces static-kinematic pairs notifications for this actor.
Similar to eFORCE_KINE_KINE_NOTIFICATIONS, but for static-kinematic interactions.
\note This has no effect if PxRigidBodyFlag::eKINEMATIC is not set.
\warning Changing this flag at runtime will not have an effect until you remove and re-add the actor to the scene.
@see PxPairFilteringMode PxSceneDesc.staticKineFilteringMode
*/
eFORCE_STATIC_KINE_NOTIFICATIONS = (1<<9),
/**
\brief Enables computation of gyroscopic forces on the rigid body.
*/
eENABLE_GYROSCOPIC_FORCES = (1<<10),
/**
\brief Reserved for internal usage
*/
eRESERVED = (1<<15)
};
};
/**
\brief collection of set bits defined in PxRigidBodyFlag.
@see PxRigidBodyFlag
*/
typedef PxFlags<PxRigidBodyFlag::Enum,PxU16> PxRigidBodyFlags;
PX_FLAGS_OPERATORS(PxRigidBodyFlag::Enum,PxU16)
/**
\brief PxRigidBody is a base class shared between dynamic rigid body objects.
@see PxRigidActor
*/
class PxRigidBody : public PxRigidActor
{
public:
// Runtime modifications
/************************************************************************************************/
/** @name Mass Manipulation
*/
/**
\brief Sets the pose of the center of mass relative to the actor.
\note Changing this transform will not move the actor in the world!
\note Setting an unrealistic center of mass which is a long way from the body can make it difficult for
the SDK to solve constraints. Perhaps leading to instability and jittering bodies.
\note Changing this transform will not update the linear velocity reported by getLinearVelocity() to account
for the shift in center of mass. If the shift should be accounted for, the user should update the velocity
using setLinearVelocity().
<b>Default:</b> the identity transform
\param[in] pose Mass frame offset transform relative to the actor frame. <b>Range:</b> rigid body transform.
@see getCMassLocalPose() getLinearVelocity()
*/
virtual void setCMassLocalPose(const PxTransform& pose) = 0;
/**
\brief Retrieves the center of mass pose relative to the actor frame.
\return The center of mass pose relative to the actor frame.
@see setCMassLocalPose()
*/
virtual PxTransform getCMassLocalPose() const = 0;
/**
\brief Sets the mass of a dynamic actor.
The mass must be non-negative.
setMass() does not update the inertial properties of the body, to change the inertia tensor
use setMassSpaceInertiaTensor() or the PhysX extensions method #PxRigidBodyExt::updateMassAndInertia().
\note A value of 0 is interpreted as infinite mass.
\note Values of 0 are not permitted for instances of PxArticulationLink but are permitted for instances of PxRigidDynamic.
<b>Default:</b> 1.0
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] mass New mass value for the actor. <b>Range:</b> [0, PX_MAX_F32)
@see getMass() setMassSpaceInertiaTensor()
*/
virtual void setMass(PxReal mass) = 0;
/**
\brief Retrieves the mass of the actor.
\note A value of 0 is interpreted as infinite mass.
\return The mass of this actor.
@see setMass() setMassSpaceInertiaTensor()
*/
virtual PxReal getMass() const = 0;
/**
\brief Retrieves the inverse mass of the actor.
\return The inverse mass of this actor.
@see setMass() setMassSpaceInertiaTensor()
*/
virtual PxReal getInvMass() const = 0;
/**
\brief Sets the inertia tensor, using a parameter specified in mass space coordinates.
Note that such matrices are diagonal -- the passed vector is the diagonal.
If you have a non diagonal world/actor space inertia tensor(3x3 matrix). Then you need to
diagonalize it and set an appropriate mass space transform. See #setCMassLocalPose().
The inertia tensor elements must be non-negative.
\note A value of 0 in an element is interpreted as infinite inertia along that axis.
\note Values of 0 are not permitted for instances of PxArticulationLink but are permitted for instances of PxRigidDynamic.
<b>Default:</b> (1.0, 1.0, 1.0)
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] m New mass space inertia tensor for the actor.
@see getMassSpaceInertia() setMass() setCMassLocalPose()
*/
virtual void setMassSpaceInertiaTensor(const PxVec3& m) = 0;
/**
\brief Retrieves the diagonal inertia tensor of the actor relative to the mass coordinate frame.
This method retrieves a mass frame inertia vector.
\return The mass space inertia tensor of this actor.
\note A value of 0 in an element is interpreted as infinite inertia along that axis.
@see setMassSpaceInertiaTensor() setMass() setCMassLocalPose()
*/
virtual PxVec3 getMassSpaceInertiaTensor() const = 0;
/**
\brief Retrieves the diagonal inverse inertia tensor of the actor relative to the mass coordinate frame.
This method retrieves a mass frame inverse inertia vector.
\note A value of 0 in an element is interpreted as infinite inertia along that axis.
\return The mass space inverse inertia tensor of this actor.
@see setMassSpaceInertiaTensor() setMass() setCMassLocalPose()
*/
virtual PxVec3 getMassSpaceInvInertiaTensor() const = 0;
/************************************************************************************************/
/** @name Damping
*/
/**
\brief Sets the linear damping coefficient.
Zero represents no damping. The damping coefficient must be nonnegative.
<b>Default:</b> 0.05 for PxArticulationLink, 0.0 for PxRigidDynamic
\param[in] linDamp Linear damping coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see getLinearDamping() setAngularDamping()
*/
virtual void setLinearDamping(PxReal linDamp) = 0;
/**
\brief Retrieves the linear damping coefficient.
\return The linear damping coefficient associated with this actor.
@see setLinearDamping() getAngularDamping()
*/
virtual PxReal getLinearDamping() const = 0;
/**
\brief Sets the angular damping coefficient.
Zero represents no damping.
The angular damping coefficient must be nonnegative.
<b>Default:</b> 0.05
\param[in] angDamp Angular damping coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see getAngularDamping() setLinearDamping()
*/
virtual void setAngularDamping(PxReal angDamp) = 0;
/**
\brief Retrieves the angular damping coefficient.
\return The angular damping coefficient associated with this actor.
@see setAngularDamping() getLinearDamping()
*/
virtual PxReal getAngularDamping() const = 0;
/************************************************************************************************/
/** @name Velocity
*/
/**
\brief Retrieves the linear velocity of an actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\note The linear velocity is reported with respect to the rigid body's center of mass and not the actor frame origin.
\return The linear velocity of the actor.
@see PxRigidDynamic.setLinearVelocity() getAngularVelocity()
*/
virtual PxVec3 getLinearVelocity() const = 0;
/**
\brief Retrieves the angular velocity of the actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\return The angular velocity of the actor.
@see PxRigidDynamic.setAngularVelocity() getLinearVelocity()
*/
virtual PxVec3 getAngularVelocity() const = 0;
/**
\brief Lets you set the maximum linear velocity permitted for this actor.
With this function, you can set the maximum linear velocity permitted for this rigid body.
Higher linear velocities are clamped to this value.
Note: The linear velocity is clamped to the set value <i>before</i> the solver, which means that
the limit may still be momentarily exceeded.
<b>Default:</b> 100*PxTolerancesScale::length for PxArticulationLink, 1e^16 for PxRigidDynamic
\param[in] maxLinVel Max allowable linear velocity for actor. <b>Range:</b> [0, 1e^16)
@see getMaxAngularVelocity()
*/
virtual void setMaxLinearVelocity(PxReal maxLinVel) = 0;
/**
\brief Retrieves the maximum angular velocity permitted for this actor.
\return The maximum allowed angular velocity for this actor.
@see setMaxLinearVelocity
*/
virtual PxReal getMaxLinearVelocity() const = 0;
/**
\brief Lets you set the maximum angular velocity permitted for this actor.
For various internal computations, very quickly rotating actors introduce error
into the simulation, which leads to undesired results.
With this function, you can set the maximum angular velocity permitted for this rigid body.
Higher angular velocities are clamped to this value.
Note: The angular velocity is clamped to the set value <i>before</i> the solver, which means that
the limit may still be momentarily exceeded.
<b>Default:</b> 50.0 for PxArticulationLink, 100.0 for PxRigidDynamic
<b>Range:</b> [0, 1e^16)
\param[in] maxAngVel Max allowable angular velocity for actor.
@see getMaxAngularVelocity()
*/
virtual void setMaxAngularVelocity(PxReal maxAngVel) = 0;
/**
\brief Retrieves the maximum angular velocity permitted for this actor.
\return The maximum allowed angular velocity for this actor.
@see setMaxAngularVelocity
*/
virtual PxReal getMaxAngularVelocity() const = 0;
/************************************************************************************************/
/** @name Forces
*/
/**
\brief Applies a force (or impulse) defined in the global coordinate frame to the actor at its center of mass.
<b>This will not induce a torque</b>.
::PxForceMode determines if the force is to be conventional or impulsive.
Each actor has an acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION
and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same
accumulators and are just short hand for multiplying the vector parameter by inverse mass and then using PxForceMode::eACCELERATION and
PxForceMode::eVELOCITY_CHANGE respectively.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note if this is called on an articulation link, only the link is updated, not the entire articulation.
\note see #PxRigidBodyExt::computeVelocityDeltaFromImpulse for details of how to compute the change in linear velocity that
will arise from the application of an impulsive force, where an impulsive force is applied force multiplied by a timestep.
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the force is non-zero.
\param[in] force Force/Impulse to apply defined in the global frame.
\param[in] mode The mode to use when applying the force/impulse(see #PxForceMode)
\param[in] autowake Specify if the call should wake up the actor if it is currently asleep. If true and the current wake counter value
is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see PxForceMode addTorque
*/
virtual void addForce(const PxVec3& force, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true) = 0;
/**
\brief Applies an impulsive torque defined in the global coordinate frame to the actor.
::PxForceMode determines if the torque is to be conventional or impulsive.
Each actor has an angular acceleration and an angular velocity change accumulator which are directly modified using the modes
PxForceMode::eACCELERATION and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE
also modify these same accumulators and are just short hand for multiplying the vector parameter by inverse inertia and then
using PxForceMode::eACCELERATION and PxForceMode::eVELOCITY_CHANGE respectively.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note if this called on an articulation link, only the link is updated, not the entire articulation.
\note see #PxRigidBodyExt::computeVelocityDeltaFromImpulse for details of how to compute the change in angular velocity that
will arise from the application of an impulsive torque, where an impulsive torque is an applied torque multiplied by a timestep.
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the torque is non-zero.
\param[in] torque Torque to apply defined in the global frame. <b>Range:</b> torque vector
\param[in] mode The mode to use when applying the force/impulse(see #PxForceMode).
\param[in] autowake Specify if the call should wake up the actor if it is currently asleep. If true and the current wake counter value
is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see PxForceMode addForce()
*/
virtual void addTorque(const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true) = 0;
/**
\brief Clears the accumulated forces (sets the accumulated force back to zero).
Each actor has an acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION
and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same
accumulators (see PxRigidBody::addForce() for details); therefore the effect of calling clearForce(PxForceMode::eFORCE) is equivalent to calling
clearForce(PxForceMode::eACCELERATION), and the effect of calling clearForce(PxForceMode::eIMPULSE) is equivalent to calling
clearForce(PxForceMode::eVELOCITY_CHANGE).
::PxForceMode determines if the cleared force is to be conventional or impulsive.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\param[in] mode The mode to use when clearing the force/impulse(see #PxForceMode)
@see PxForceMode addForce
*/
virtual void clearForce(PxForceMode::Enum mode = PxForceMode::eFORCE) = 0;
/**
\brief Clears the impulsive torque defined in the global coordinate frame to the actor.
::PxForceMode determines if the cleared torque is to be conventional or impulsive.
Each actor has an angular acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION
and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same
accumulators (see PxRigidBody::addTorque() for details); therefore the effect of calling clearTorque(PxForceMode::eFORCE) is equivalent to calling
clearTorque(PxForceMode::eACCELERATION), and the effect of calling clearTorque(PxForceMode::eIMPULSE) is equivalent to calling
clearTorque(PxForceMode::eVELOCITY_CHANGE).
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\param[in] mode The mode to use when clearing the force/impulse(see #PxForceMode).
@see PxForceMode addTorque
*/
virtual void clearTorque(PxForceMode::Enum mode = PxForceMode::eFORCE) = 0;
/**
\brief Sets the impulsive force and torque defined in the global coordinate frame to the actor.
::PxForceMode determines if the cleared torque is to be conventional or impulsive.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
@see PxForceMode addTorque
*/
virtual void setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE) = 0;
/**
\brief Raises or clears a particular rigid body flag.
See the list of flags #PxRigidBodyFlag
<b>Default:</b> no flags are set
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] flag The PxRigidBody flag to raise(set) or clear. See #PxRigidBodyFlag.
\param[in] value The new boolean value for the flag.
@see PxRigidBodyFlag getRigidBodyFlags()
*/
virtual void setRigidBodyFlag(PxRigidBodyFlag::Enum flag, bool value) = 0;
virtual void setRigidBodyFlags(PxRigidBodyFlags inFlags) = 0;
/**
\brief Reads the PxRigidBody flags.
See the list of flags #PxRigidBodyFlag
\return The values of the PxRigidBody flags.
@see PxRigidBodyFlag setRigidBodyFlag()
*/
virtual PxRigidBodyFlags getRigidBodyFlags() const = 0;
/**
\brief Sets the CCD minimum advance coefficient.
The CCD minimum advance coefficient is a value in the range [0, 1] that is used to control the minimum amount of time a body is integrated when
it has a CCD contact. The actual minimum amount of time that is integrated depends on various properties, including the relative speed and collision shapes
of the bodies involved in the contact. From these properties, a numeric value is calculated that determines the maximum distance (and therefore maximum time)
which these bodies could be integrated forwards that would ensure that these bodies did not pass through each-other. This value is then scaled by CCD minimum advance
coefficient to determine the amount of time that will be consumed in the CCD pass.
<b>Things to consider:</b>
A large value (approaching 1) ensures that the objects will always advance some time. However, larger values increase the chances of objects gently drifting through each-other in
scenes which the constraint solver can't converge, e.g. scenes where an object is being dragged through a wall with a constraint.
A value of 0 ensures that the pair of objects stop at the exact time-of-impact and will not gently drift through each-other. However, with very small/thin objects initially in
contact, this can lead to a large amount of time being dropped and increases the chances of jamming. Jamming occurs when the an object is persistently in contact with an object
such that the time-of-impact is 0, which results in no time being advanced for those objects in that CCD pass.
The chances of jamming can be reduced by increasing the number of CCD mass @see PxSceneDesc.ccdMaxPasses. However, increasing this number increases the CCD overhead.
\param[in] advanceCoefficient The CCD min advance coefficient. <b>Range:</b> [0, 1] <b>Default:</b> 0.15
*/
virtual void setMinCCDAdvanceCoefficient(PxReal advanceCoefficient) = 0;
/**
\brief Gets the CCD minimum advance coefficient.
\return The value of the CCD min advance coefficient.
@see setMinCCDAdvanceCoefficient
*/
virtual PxReal getMinCCDAdvanceCoefficient() const = 0;
/**
\brief Sets the maximum depenetration velocity permitted to be introduced by the solver.
This value controls how much velocity the solver can introduce to correct for penetrations in contacts.
\param[in] biasClamp The maximum velocity to de-penetrate by <b>Range:</b> (0, PX_MAX_F32].
*/
virtual void setMaxDepenetrationVelocity(PxReal biasClamp) = 0;
/**
\brief Returns the maximum depenetration velocity the solver is permitted to introduced.
This value controls how much velocity the solver can introduce to correct for penetrations in contacts.
\return The maximum penetration bias applied by the solver.
*/
virtual PxReal getMaxDepenetrationVelocity() const = 0;
/**
\brief Sets a limit on the impulse that may be applied at a contact. The maximum impulse at a contact between two dynamic or kinematic
bodies will be the minimum of the two limit values. For a collision between a static and a dynamic body, the impulse is limited
by the value for the dynamic body.
\param[in] maxImpulse the maximum contact impulse. <b>Range:</b> [0, PX_MAX_F32] <b>Default:</b> PX_MAX_F32
@see getMaxContactImpulse
*/
virtual void setMaxContactImpulse(PxReal maxImpulse) = 0;
/**
\brief Returns the maximum impulse that may be applied at a contact.
\return The maximum impulse that may be applied at a contact
@see setMaxContactImpulse
*/
virtual PxReal getMaxContactImpulse() const = 0;
/**
\brief Sets a distance scale whereby the angular influence of a contact on the normal constraint in a contact is
zeroed if normal.cross(offset) falls below this tolerance. Rather than acting as an absolute value, this tolerance
is scaled by the ratio rXn.dot(angVel)/normal.dot(linVel) such that contacts that have relatively larger angular velocity
than linear normal velocity (e.g. rolling wheels) achieve larger slop values as the angular velocity increases.
\param[in] slopCoefficient the Slop coefficient. <b>Range:</b> [0, PX_MAX_F32] <b>Default:</b> 0
@see getContactSlopCoefficient
*/
virtual void setContactSlopCoefficient(PxReal slopCoefficient) = 0;
/**
\brief Returns the contact slop coefficient.
\return The contact slop coefficient.
@see setContactSlopCoefficient
*/
virtual PxReal getContactSlopCoefficient() const = 0;
/**
\brief Returns the island node index
\return The island node index.
*/
virtual PxNodeIndex getInternalIslandNodeIndex() const = 0;
protected:
PX_INLINE PxRigidBody(PxType concreteType, PxBaseFlags baseFlags) : PxRigidActor(concreteType, baseFlags) {}
PX_INLINE PxRigidBody(PxBaseFlags baseFlags) : PxRigidActor(baseFlags) {}
virtual ~PxRigidBody() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidBody", PxRigidActor); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 29,286 | C | 39.732962 | 179 | 0.757188 |
NVIDIA-Omniverse/PhysX/physx/include/PxPBDParticleSystem.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PBD_PARTICLE_SYSTEM_H
#define PX_PBD_PARTICLE_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxParticleSystem.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
/**
\brief A particle system that uses the position based dynamics(PBD) solver.
The position based dynamics solver for particle systems supports behaviors like
fluid, cloth, inflatables etc.
*/
class PxPBDParticleSystem : public PxParticleSystem
{
public:
virtual ~PxPBDParticleSystem() {}
/**
\brief Set wind direction and intensity
\param[in] wind The wind direction and intensity
*/
virtual void setWind(const PxVec3& wind) = 0;
/**
\brief Retrieves the wind direction and intensity.
\return The wind direction and intensity
*/
virtual PxVec3 getWind() const = 0;
/**
\brief Set the fluid boundary density scale
Defines how strong of a contribution the boundary (typically a rigid surface) should have on a fluid particle's density.
\param[in] fluidBoundaryDensityScale <b>Range:</b> (0.0, 1.0)
*/
virtual void setFluidBoundaryDensityScale(PxReal fluidBoundaryDensityScale) = 0;
/**
\brief Return the fluid boundary density scale
\return the fluid boundary density scale
See #setFluidBoundaryDensityScale()
*/
virtual PxReal getFluidBoundaryDensityScale() const = 0;
/**
\brief Set the fluid rest offset
Two fluid particles will come to rest at a distance equal to twice the fluidRestOffset value.
\param[in] fluidRestOffset <b>Range:</b> (0, particleContactOffset)
*/
virtual void setFluidRestOffset(PxReal fluidRestOffset) = 0;
/**
\brief Return the fluid rest offset
\return the fluid rest offset
See #setFluidRestOffset()
*/
virtual PxReal getFluidRestOffset() const = 0;
/**
\brief Set the particle system grid size x dimension
\param[in] gridSizeX x dimension in the particle grid
*/
virtual void setGridSizeX(PxU32 gridSizeX) = 0;
/**
\brief Set the particle system grid size y dimension
\param[in] gridSizeY y dimension in the particle grid
*/
virtual void setGridSizeY(PxU32 gridSizeY) = 0;
/**
\brief Set the particle system grid size z dimension
\param[in] gridSizeZ z dimension in the particle grid
*/
virtual void setGridSizeZ(PxU32 gridSizeZ) = 0;
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxPBDParticleSystem"; }
protected:
PX_INLINE PxPBDParticleSystem(PxType concreteType, PxBaseFlags baseFlags) : PxParticleSystem(concreteType, baseFlags) {}
PX_INLINE PxPBDParticleSystem(PxBaseFlags baseFlags) : PxParticleSystem(baseFlags) {}
virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxPBDParticleSystem", PxParticleSystem); }
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,923 | C | 31.826666 | 147 | 0.705667 |
NVIDIA-Omniverse/PhysX/physx/include/PxFEMMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FEM_MATERIAL_H
#define PX_FEM_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxBaseMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxScene;
/**
\brief Material class to represent a set of FEM material properties.
@see PxPhysics.createFEMSoftBodyMaterial
*/
class PxFEMMaterial : public PxBaseMaterial
{
public:
/**
\brief Sets young's modulus which defines the body's stiffness
\param[in] young Young's modulus. <b>Range:</b> [0, PX_MAX_F32)
@see getYoungsModulus()
*/
virtual void setYoungsModulus(PxReal young) = 0;
/**
\brief Retrieves the young's modulus value.
\return The young's modulus value.
@see setYoungsModulus()
*/
virtual PxReal getYoungsModulus() const = 0;
/**
\brief Sets the Poisson's ratio which defines the body's volume preservation. Completely incompressible materials have a poisson ratio of 0.5. Its value should not be set to exactly 0.5 because this leads to numerical problems.
\param[in] poisson Poisson's ratio. <b>Range:</b> [0, 0.5)
@see getPoissons()
*/
virtual void setPoissons(PxReal poisson) = 0;
/**
\brief Retrieves the Poisson's ratio.
\return The Poisson's ratio.
@see setPoissons()
*/
virtual PxReal getPoissons() const = 0;
/**
\brief Sets the dynamic friction value which defines the strength of resistance when two objects slide relative to each other while in contact.
\param[in] dynamicFriction The dynamic friction value. <b>Range:</b> [0, PX_MAX_F32)
@see getDynamicFriction()
*/
virtual void setDynamicFriction(PxReal dynamicFriction) = 0;
/**
\brief Retrieves the dynamic friction value
\return The dynamic friction value
@see setDynamicFriction()
*/
virtual PxReal getDynamicFriction() const = 0;
protected:
PX_INLINE PxFEMMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {}
PX_INLINE PxFEMMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {}
virtual ~PxFEMMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxFEMMaterial", PxBaseMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,925 | C | 31.991596 | 229 | 0.736306 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationJointReducedCoordinate.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_JOINT_RC_H
#define PX_ARTICULATION_JOINT_RC_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#include "solver/PxSolverDefs.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A joint between two links in an articulation.
@see PxArticulationReducedCoordinate, PxArticulationLink
*/
class PxArticulationJointReducedCoordinate : public PxBase
{
public:
/**
\brief Gets the parent articulation link of this joint.
\return The parent link.
*/
virtual PxArticulationLink& getParentArticulationLink() const = 0;
/**
\brief Sets the joint pose in the parent link actor frame.
\param[in] pose The joint pose.
<b>Default:</b> The identity transform.
\note This call is not allowed while the simulation is running.
@see getParentPose
*/
virtual void setParentPose(const PxTransform& pose) = 0;
/**
\brief Gets the joint pose in the parent link actor frame.
\return The joint pose.
@see setParentPose
*/
virtual PxTransform getParentPose() const = 0;
/**
\brief Gets the child articulation link of this joint.
\return The child link.
*/
virtual PxArticulationLink& getChildArticulationLink() const = 0;
/**
\brief Sets the joint pose in the child link actor frame.
\param[in] pose The joint pose.
<b>Default:</b> The identity transform.
\note This call is not allowed while the simulation is running.
@see getChildPose
*/
virtual void setChildPose(const PxTransform& pose) = 0;
/**
\brief Gets the joint pose in the child link actor frame.
\return The joint pose.
@see setChildPose
*/
virtual PxTransform getChildPose() const = 0;
/**
\brief Sets the joint type (e.g. revolute).
\param[in] jointType The joint type to set.
\note Setting the joint type is not allowed while the articulation is in a scene.
In order to amend the joint type, remove and then re-add the articulation to the scene.
<b>Default:</b> PxArticulationJointType::eUNDEFINED
@see PxArticulationJointType, getJointType
*/
virtual void setJointType(PxArticulationJointType::Enum jointType) = 0;
/**
\brief Gets the joint type.
\return The joint type.
@see PxArticulationJointType, setJointType
*/
virtual PxArticulationJointType::Enum getJointType() const = 0;
/**
\brief Sets the joint motion for a given axis.
\param[in] axis The target axis.
\param[in] motion The motion type to set.
\note Setting the motion of joint axes is not allowed while the articulation is in a scene.
In order to set the motion, remove and then re-add the articulation to the scene.
<b>Default:</b> PxArticulationMotion::eLOCKED
@see PxArticulationAxis, PxArticulationMotion, getMotion
*/
virtual void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) = 0;
/**
\brief Returns the joint motion for the given axis.
\param[in] axis The target axis.
\return The joint motion of the given axis.
@see PxArticulationAxis, PxArticulationMotion, setMotion
*/
virtual PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint limits for a given axis.
- The motion of the corresponding axis should be set to PxArticulationMotion::eLIMITED in order for the limits to be enforced.
- The lower limit should be strictly smaller than the higher limit. If the limits should be equal, use PxArticulationMotion::eLOCKED
and an appropriate offset in the parent/child joint frames.
\param[in] axis The target axis.
\param[in] limit The joint limits.
\note This call is not allowed while the simulation is running.
\note For PxArticulationJointType::eSPHERICAL, limit.min and limit.max must both be in range [-Pi, Pi].
\note For PxArticulationJointType::eREVOLUTE, limit.min and limit.max must both be in range [-2*Pi, 2*Pi].
\note For PxArticulationJointType::eREVOLUTE_UNWRAPPED, limit.min and limit.max must both be in range [-PX_MAX_REAL, PX_MAX_REAL].
\note For PxArticulationJointType::ePRISMATIC, limit.min and limit.max must both be in range [-PX_MAX_REAL, PX_MAX_REAL].
<b>Default:</b> (0,0)
@see getLimitParams, PxArticulationAxis, PxArticulationLimit
*/
virtual void setLimitParams(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit) = 0;
/**
\brief Returns the joint limits for a given axis.
\param[in] axis The target axis.
\return The joint limits.
@see setLimitParams, PxArticulationAxis, PxArticulationLimit
*/
virtual PxArticulationLimit getLimitParams(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Configures a joint drive for the given axis.
See PxArticulationDrive for parameter details; and the manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular.
\param[in] axis The target axis.
\param[in] drive The drive parameters
\note This call is not allowed while the simulation is running.
@see getDriveParams, PxArticulationAxis, PxArticulationDrive
<b>Default:</b> PxArticulationDrive(0.0f, 0.0f, 0.0f, PxArticulationDriveType::eNONE)
*/
virtual void setDriveParams(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) = 0;
/**
\brief Gets the joint drive configuration for the given axis.
\param[in] axis The target axis.
\return The drive parameters.
@see setDriveParams, PxArticulationAxis, PxArticulationDrive
*/
virtual PxArticulationDrive getDriveParams(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint drive position target for the given axis.
The target units are linear units (equivalent to scene units) for a translational axis, or rad for a rotational axis.
\param[in] axis The target axis.
\param[in] target The target position.
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
\note This call is not allowed while the simulation is running.
\note For spherical joints, target must be in range [-Pi, Pi].
\note The target is specified in the parent frame of the joint. If Gp, Gc are the parent and child actor poses in the world frame and Lp, Lc are the parent and child joint frames expressed in the parent and child actor frames then the joint will drive the parent and child links to poses that obey Gp * Lp * J = Gc * Lc. For joints restricted to angular motion, J has the form PxTranfsorm(PxVec3(PxZero), PxExp(PxVec3(twistTarget, swing1Target, swing2Target))). For joints restricted to linear motion, J has the form PxTransform(PxVec3(XTarget, YTarget, ZTarget), PxQuat(PxIdentity)).
\note For spherical joints with more than 1 degree of freedom, the joint target angles taken together can collectively represent a rotation of greater than Pi around a vector. When this happens the rotation that matches the joint drive target is not the shortest path rotation. The joint pose J that is the outcome after driving to the target pose will always be the equivalent of the shortest path rotation.
@see PxArticulationAxis, getDriveTarget
<b>Default:</b> 0.0
*/
virtual void setDriveTarget(PxArticulationAxis::Enum axis, const PxReal target, bool autowake = true) = 0;
/**
\brief Returns the joint drive position target for the given axis.
\param[in] axis The target axis.
\return The target position.
@see PxArticulationAxis, setDriveTarget
*/
virtual PxReal getDriveTarget(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint drive velocity target for the given axis.
The target units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\param[in] axis The target axis.
\param[in] targetVel The target velocity.
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
\note This call is not allowed while the simulation is running.
@see PxArticulationAxis, getDriveVelocity
<b>Default:</b> 0.0
*/
virtual void setDriveVelocity(PxArticulationAxis::Enum axis, const PxReal targetVel, bool autowake = true) = 0;
/**
\brief Returns the joint drive velocity target for the given axis.
\param[in] axis The target axis.
\return The target velocity.
@see PxArticulationAxis, setDriveVelocity
*/
virtual PxReal getDriveVelocity(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint armature for the given axis.
- The armature is directly added to the joint-space spatial inertia of the corresponding axis.
- The armature is in mass units for a prismatic (i.e. linear) joint, and in mass units * (scene linear units)^2 for a rotational joint.
\param[in] axis The target axis.
\param[in] armature The joint axis armature.
\note This call is not allowed while the simulation is running.
@see PxArticulationAxis, getArmature
<b>Default:</b> 0.0
*/
virtual void setArmature(PxArticulationAxis::Enum axis, const PxReal armature) = 0;
/**
\brief Gets the joint armature for the given axis.
\param[in] axis The target axis.
\return The armature set on the given axis.
@see PxArticulationAxis, setArmature
*/
virtual PxReal getArmature(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint friction coefficient, which applies to all joint axes.
- The joint friction is unitless and relates the magnitude of the spatial force [F_trans, T_trans] transmitted from parent to child link to
the maximal friction force F_resist that may be applied by the solver to resist joint motion, per axis; i.e. |F_resist| <= coefficient * (|F_trans| + |T_trans|),
where F_resist may refer to a linear force or torque depending on the joint axis.
- The simulated friction effect is therefore similar to static and Coulomb friction. In order to simulate dynamic joint friction, use a joint drive with
zero stiffness and zero velocity target, and an appropriately dimensioned damping parameter.
\param[in] coefficient The joint friction coefficient.
\note This call is not allowed while the simulation is running.
@see getFrictionCoefficient
<b>Default:</b> 0.05
*/
virtual void setFrictionCoefficient(const PxReal coefficient) = 0;
/**
\brief Gets the joint friction coefficient.
\return The joint friction coefficient.
@see setFrictionCoefficient
*/
virtual PxReal getFrictionCoefficient() const = 0;
/**
\brief Sets the maximal joint velocity enforced for all axes.
- The solver will apply appropriate joint-space impulses in order to enforce the per-axis joint-velocity limit.
- The velocity units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\param[in] maxJointV The maximal per-axis joint velocity.
\note This call is not allowed while the simulation is running.
@see getMaxJointVelocity
<b>Default:</b> 100.0
*/
virtual void setMaxJointVelocity(const PxReal maxJointV) = 0;
/**
\brief Gets the maximal joint velocity enforced for all axes.
\return The maximal per-axis joint velocity.
@see setMaxJointVelocity
*/
virtual PxReal getMaxJointVelocity() const = 0;
/**
\brief Sets the joint position for the given axis.
- For performance, prefer PxArticulationCache::jointPosition to set joint positions in a batch articulation state update.
- Use PxArticulationReducedCoordinate::updateKinematic after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] axis The target axis.
\param[in] jointPos The joint position in linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis.
\note This call is not allowed while the simulation is running.
\note For PxArticulationJointType::eSPHERICAL, jointPos must be in range [-Pi, Pi].
\note For PxArticulationJointType::eREVOLUTE, jointPos must be in range [-2*Pi, 2*Pi].
\note For PxArticulationJointType::eREVOLUTE_UNWRAPPED, jointPos must be in range [-PX_MAX_REAL, PX_MAX_REAL].
\note For PxArticulationJointType::ePRISMATIC, jointPos must be in range [-PX_MAX_REAL, PX_MAX_REAL].
\note Joint position is specified in the parent frame of the joint. If Gp, Gc are the parent and child actor poses in the world frame and Lp, Lc are the parent and child joint frames expressed in the parent and child actor frames then the parent and child links will be given poses that obey Gp * Lp * J = Gc * Lc with J denoting the joint pose. For joints restricted to angular motion, J has the form PxTranfsorm(PxVec3(PxZero), PxExp(PxVec3(twistPos, swing1Pos, swing2Pos))). For joints restricted to linear motion, J has the form PxTransform(PxVec3(xPos, yPos, zPos), PxQuat(PxIdentity)).
\note For spherical joints with more than 1 degree of freedom, the input joint positions taken together can collectively represent a rotation of greater than Pi around a vector. When this happens the rotation that matches the joint positions is not the shortest path rotation. The joint pose J that is the outcome of setting and applying the joint positions will always be the equivalent of the shortest path rotation.
@see PxArticulationAxis, getJointPosition, PxArticulationCache::jointPosition, PxArticulationReducedCoordinate::updateKinematic
<b>Default:</b> 0.0
*/
virtual void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) = 0;
/**
\brief Gets the joint position for the given axis, i.e. joint degree of freedom (DOF).
For performance, prefer PxArticulationCache::jointPosition to get joint positions in a batch query.
\param[in] axis The target axis.
\return The joint position in linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
@see PxArticulationAxis, setJointPosition, PxArticulationCache::jointPosition
*/
virtual PxReal getJointPosition(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint velocity for the given axis.
- For performance, prefer PxArticulationCache::jointVelocity to set joint velocities in a batch articulation state update.
- Use PxArticulationReducedCoordinate::updateKinematic after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] axis The target axis.
\param[in] jointVel The joint velocity in linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\note This call is not allowed while the simulation is running.
@see PxArticulationAxis, getJointVelocity, PxArticulationCache::jointVelocity, PxArticulationReducedCoordinate::updateKinematic
<b>Default:</b> 0.0
*/
virtual void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) = 0;
/**
\brief Gets the joint velocity for the given axis.
For performance, prefer PxArticulationCache::jointVelocity to get joint velocities in a batch query.
\param[in] axis The target axis.
\return The joint velocity in linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
@see PxArticulationAxis, setJointVelocity, PxArticulationCache::jointVelocity
*/
virtual PxReal getJointVelocity(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationJointReducedCoordinate"; }
virtual ~PxArticulationJointReducedCoordinate() {}
//public variables:
void* userData; //!< The user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxArticulationJointReducedCoordinate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationJointReducedCoordinate(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationJointReducedCoordinate", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 18,865 | C | 39.7473 | 594 | 0.751179 |
NVIDIA-Omniverse/PhysX/physx/include/PxIsosurfaceExtraction.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ISOSURFACE_EXTRACTION_H
#define PX_ISOSURFACE_EXTRACTION_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "PxSparseGridParams.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
/**
\brief Identifies filter type to be applied on the isosurface grid.
*/
struct PxIsosurfaceGridFilteringType
{
enum Enum
{
eNONE = 0, //!< No filtering
eSMOOTH = 1, //!< Gaussian-blur-like filtering
eGROW = 2, //!< A dilate/erode operation will be applied that makes the fluid grow approximately one cell size
eSHRINK = 3 //!< A dilate/erode operation will be applied that makes the fluid shrink approximately one cell size
};
};
/**
\brief Parameters to define the isosurface extraction settings like isosurface level, filtering etc.
*/
struct PxIsosurfaceParams
{
/**
\brief Default constructor.
*/
PX_INLINE PxIsosurfaceParams()
{
particleCenterToIsosurfaceDistance = 0.2f;
numMeshSmoothingPasses = 4;
numMeshNormalSmoothingPasses = 4;
gridFilteringFlags = 0;
gridSmoothingRadius = 0.2f;
}
/**
\brief Clears the filtering operations
*/
PX_INLINE void clearFilteringPasses()
{
gridFilteringFlags = 0;
}
/**
\brief Adds a smoothing pass after the existing ones
At most 32 smoothing passes can be defined. Every pass can repeat itself up to 4 times.
\param[in] operation The smoothing operation to add
\return The index of the smoothing pass that was added
*/
PX_INLINE PxU64 addGridFilteringPass(PxIsosurfaceGridFilteringType::Enum operation)
{
for (PxU32 i = 0; i < 32; ++i)
{
PxIsosurfaceGridFilteringType::Enum o;
if (!getGridFilteringPass(i, o))
{
setGridFilteringPass(i, operation);
return i;
}
}
return 0xFFFFFFFFFFFFFFFF;
}
/**
\brief Sets the operation of a smoothing pass
\param[in] passIndex The index of the smoothing pass whose operation should be set <b>Range:</b> [0, 31]
\param[in] operation The operation the modified smoothing will perform
*/
PX_INLINE void setGridFilteringPass(PxU32 passIndex, PxIsosurfaceGridFilteringType::Enum operation)
{
PX_ASSERT(passIndex < 32u);
PxU32 shift = passIndex * 2;
gridFilteringFlags &= ~(PxU64(3) << shift);
gridFilteringFlags |= PxU64(operation) << shift;
}
/**
\brief Returns the operation of a smoothing pass
\param[in] passIndex The index of the smoothing pass whose operation is requested <b>Range:</b> [0, 31]
\param[out] operation The operation the requested smoothing pass will perform
\return true if the requested pass performs an operation
*/
PX_INLINE bool getGridFilteringPass(PxU32 passIndex, PxIsosurfaceGridFilteringType::Enum& operation) const
{
PxU32 shift = passIndex * 2;
PxU64 v = gridFilteringFlags >> shift;
v &= 3; //Extract last 2 bits
operation = PxIsosurfaceGridFilteringType::Enum(v);
return operation != PxIsosurfaceGridFilteringType::eNONE;
}
PxReal particleCenterToIsosurfaceDistance; //!< Distance form a particle center to the isosurface
PxU32 numMeshSmoothingPasses; //!< Number of Taubin mesh postprocessing smoothing passes. Using an even number of passes lead to less shrinking.
PxU32 numMeshNormalSmoothingPasses; //!< Number of mesh normal postprocessing smoothing passes.
PxU64 gridFilteringFlags; //!< Encodes the smoothing steps to apply on the sparse grid. Use setGridSmoothingPass method to set up.
PxReal gridSmoothingRadius; //!< Gaussian blur smoothing kernel radius used for smoothing operations on the grid
};
/**
\brief Base class for isosurface extractors. Allows to register the data arrays for the isosurface and to obtain the number vertices/triangles in use.
*/
class PxIsosurfaceExtractor
{
public:
/**
\brief Returns the isosurface parameters.
\return The isosurfacesettings used for the isosurface extraction
*/
virtual PxIsosurfaceParams getIsosurfaceParams() const = 0;
/**
\brief Set the isosurface extraction parameters
Allows to configure the isosurface extraction by controlling threshold value, smoothing options etc.
\param[in] params A collection of settings to control the isosurface extraction
*/
virtual void setIsosurfaceParams(const PxIsosurfaceParams& params) = 0;
/**
\brief Returns the number of vertices that the current isosurface triangle mesh uses
\return The number of vertices currently in use
*/
virtual PxU32 getNumVertices() const = 0;
/**
\brief Returns the number of triangles that the current isosurface triangle mesh uses
\return The number of triangles currently in use
*/
virtual PxU32 getNumTriangles() const = 0;
/**
\brief Returns the maximum number of vertices that the isosurface triangle mesh can contain
\return The maximum number of vertices that can be genrated
*/
virtual PxU32 getMaxVertices() const = 0;
/**
\brief Returns the maximum number of triangles that the isosurface triangle mesh can contain
\return The maximum number of triangles that can be generated
*/
virtual PxU32 getMaxTriangles() const = 0;
/**
\brief Resizes the internal triangle mesh buffers.
If the output buffers are device buffers, nothing will get resized but new output buffers can be set using setResultBufferDevice.
For host side output buffers, temporary buffers will get resized. The new host side result buffers with the same size must be set using setResultBufferHost.
\param[in] maxNumVertices The maximum number of vertices the output buffer can hold
\param[in] maxNumTriangles The maximum number of triangles the ouput buffer can hold
*/
virtual void setMaxVerticesAndTriangles(PxU32 maxNumVertices, PxU32 maxNumTriangles) = 0;
/**
\brief The maximal number of particles the isosurface extractor can process
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles the isosurface extractor can process
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Releases the isosurface extractor instance and its data
*/
virtual void release() = 0;
/**
\brief Triggers the compuation of a new isosurface based on the specified particle locations
\param[in] deviceParticlePos A gpu pointer pointing to the start of the particle array
\param[in] numParticles The number of particles
\param[in] stream The stream on which all the gpu work will be performed
\param[in] phases A phase value per particle
\param[in] validPhaseMask A mask that specifies which phases should contribute to the isosurface. If the binary and operation
between this mask and the particle phase is non zero, then the particle will contribute to the isosurface
\param[in] activeIndices Optional array with indices of all active particles
\param[in] anisotropy1 Optional anisotropy information, x axis direction (xyz) and scale in w component
\param[in] anisotropy2 Optional anisotropy information, y axis direction (xyz) and scale in w component
\param[in] anisotropy3 Optional anisotropy information, z axis direction (xyz) and scale in w component
\param[in] anisotropyFactor A factor to multiply with the anisotropy scale
*/
virtual void extractIsosurface(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* phases = NULL, PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid,
PxU32* activeIndices = NULL, PxVec4* anisotropy1 = NULL, PxVec4* anisotropy2 = NULL, PxVec4* anisotropy3 = NULL, PxReal anisotropyFactor = 1.0f) = 0;
/**
\brief Allows to register the host buffers into which the final isosurface triangle mesh will get stored
\param[in] vertices A host buffer to store the vertices of the isosurface mesh
\param[in] triIndices A host buffer to store the triangles of the isosurface mesh
\param[in] normals A host buffer to store the normals of the isosurface mesh
*/
virtual void setResultBufferHost(PxVec4* vertices, PxU32* triIndices, PxVec4* normals = NULL) = 0;
/**
\brief Allows to register the host buffers into which the final isosurface triangle mesh will get stored
\param[in] vertices A device buffer to store the vertices of the isosurface mesh
\param[in] triIndices A device buffer to store the triangles of the isosurface mesh
\param[in] normals A device buffer to store the normals of the isosurface mesh
*/
virtual void setResultBufferDevice(PxVec4* vertices, PxU32* triIndices, PxVec4* normals) = 0;
/**
\brief Enables or disables the isosurface extractor
\param[in] enabled The boolean to set the extractor to enabled or disabled
*/
virtual void setEnabled(bool enabled) = 0;
/**
\brief Allows to query if the isosurface extractor is enabled
\return True if enabled, false otherwise
*/
virtual bool isEnabled() const = 0;
/**
\brief Destructor
*/
virtual ~PxIsosurfaceExtractor() {}
};
/**
\brief Base class for sparse grid based isosurface extractors. Allows to register the data arrays for the isosurface and to obtain the number vertices/triangles in use.
*/
class PxSparseGridIsosurfaceExtractor : public PxIsosurfaceExtractor
{
/**
\brief Returns the sparse grid parameters.
\return The sparse grid settings used for the isosurface extraction
*/
virtual PxSparseGridParams getSparseGridParams() const = 0;
/**
\brief Set the sparse grid parameters
Allows to configure cell size, number of subgrids etc.
\param[in] params A collection of settings to control the isosurface grid
*/
virtual void setSparseGridParams(const PxSparseGridParams& params) = 0;
};
/**
\brief Default implementation of a particle system callback to trigger the isosurface extraction. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the post solve task completed.
*/
class PxIsosurfaceCallback : public PxParticleSystemCallback
{
public:
/**
\brief Initializes the isosurface callback
\param[in] isosurfaceExtractor The isosurface extractor
\param[in] validPhaseMask The valid phase mask marking the phase bits that particles must have set in order to contribute to the isosurface
*/
void initialize(PxIsosurfaceExtractor* isosurfaceExtractor, PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid)
{
mIsosurfaceExtractor = isosurfaceExtractor;
mValidPhaseMask = validPhaseMask;
}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream)
{
mIsosurfaceExtractor->extractIsosurface(reinterpret_cast<PxVec4*>(gpuParticleSystem.mHostPtr->mUnsortedPositions_InvMass),
gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream, gpuParticleSystem.mHostPtr->mUnsortedPhaseArray, mValidPhaseMask);
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
private:
PxIsosurfaceExtractor* mIsosurfaceExtractor;
PxU32 mValidPhaseMask;
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 13,251 | C | 36.541076 | 189 | 0.755037 |
NVIDIA-Omniverse/PhysX/physx/include/PxSceneLock.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SCENE_LOCK_H
#define PX_SCENE_LOCK_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxScene.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief RAII wrapper for the PxScene read lock.
Use this class as follows to lock the scene for reading by the current thread
for the duration of the enclosing scope:
PxSceneReadLock lock(sceneRef);
@see PxScene::lockRead(), PxScene::unlockRead(), PxSceneFlag::eREQUIRE_RW_LOCK
*/
class PxSceneReadLock
{
PxSceneReadLock(const PxSceneReadLock&);
PxSceneReadLock& operator=(const PxSceneReadLock&);
public:
/**
\brief Constructor
\param scene The scene to lock for reading
\param file Optional string for debugging purposes
\param line Optional line number for debugging purposes
*/
PxSceneReadLock(PxScene& scene, const char* file=NULL, PxU32 line=0)
: mScene(scene)
{
mScene.lockRead(file, line);
}
~PxSceneReadLock()
{
mScene.unlockRead();
}
private:
PxScene& mScene;
};
/**
\brief RAII wrapper for the PxScene write lock.
Use this class as follows to lock the scene for writing by the current thread
for the duration of the enclosing scope:
PxSceneWriteLock lock(sceneRef);
@see PxScene::lockWrite(), PxScene::unlockWrite(), PxSceneFlag::eREQUIRE_RW_LOCK
*/
class PxSceneWriteLock
{
PxSceneWriteLock(const PxSceneWriteLock&);
PxSceneWriteLock& operator=(const PxSceneWriteLock&);
public:
/**
\brief Constructor
\param scene The scene to lock for writing
\param file Optional string for debugging purposes
\param line Optional line number for debugging purposes
*/
PxSceneWriteLock(PxScene& scene, const char* file=NULL, PxU32 line=0)
: mScene(scene)
{
mScene.lockWrite(file, line);
}
~PxSceneWriteLock()
{
mScene.unlockWrite();
}
private:
PxScene& mScene;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,561 | C | 26.828125 | 80 | 0.750351 |
NVIDIA-Omniverse/PhysX/physx/include/PxFiltering.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FILTERING_H
#define PX_FILTERING_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxActor;
class PxShape;
/**
\brief Collection of flags describing the actions to take for a collision pair.
@see PxPairFlags PxSimulationFilterShader.filter() PxSimulationFilterCallback
*/
struct PxPairFlag
{
enum Enum
{
/**
\brief Process the contacts of this collision pair in the dynamics solver.
\note Only takes effect if the colliding actors are rigid bodies.
*/
eSOLVE_CONTACT = (1<<0),
/**
\brief Call contact modification callback for this collision pair
\note Only takes effect if the colliding actors are rigid bodies.
@see PxContactModifyCallback
*/
eMODIFY_CONTACTS = (1<<1),
/**
\brief Call contact report callback or trigger callback when this collision pair starts to be in contact.
If one of the two collision objects is a trigger shape (see #PxShapeFlag::eTRIGGER_SHAPE)
then the trigger callback will get called as soon as the other object enters the trigger volume.
If none of the two collision objects is a trigger shape then the contact report callback will get
called when the actors of this collision pair start to be in contact.
\note Only takes effect if the colliding actors are rigid bodies.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_FOUND = (1<<2),
/**
\brief Call contact report callback while this collision pair is in contact
If none of the two collision objects is a trigger shape then the contact report callback will get
called while the actors of this collision pair are in contact.
\note Triggers do not support this event. Persistent trigger contacts need to be tracked separately by observing eNOTIFY_TOUCH_FOUND/eNOTIFY_TOUCH_LOST events.
\note Only takes effect if the colliding actors are rigid bodies.
\note No report will get sent if the objects in contact are sleeping.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
\note If this flag gets enabled while a pair is in touch already, there will be no eNOTIFY_TOUCH_PERSISTS events until the pair loses and regains touch.
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_PERSISTS = (1<<3),
/**
\brief Call contact report callback or trigger callback when this collision pair stops to be in contact
If one of the two collision objects is a trigger shape (see #PxShapeFlag::eTRIGGER_SHAPE)
then the trigger callback will get called as soon as the other object leaves the trigger volume.
If none of the two collision objects is a trigger shape then the contact report callback will get
called when the actors of this collision pair stop to be in contact.
\note Only takes effect if the colliding actors are rigid bodies.
\note This event will also get triggered if one of the colliding objects gets deleted.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_LOST = (1<<4),
/**
\brief Call contact report callback when this collision pair is in contact during CCD passes.
If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same
object multiple times. Hence, the same pair might be in contact multiple times during a simulation step.
This flag will make sure that all the detected collision during CCD will get reported. For performance
reasons, the system can not always tell whether the contact pair lost touch in one of the previous CCD
passes and thus can also not always tell whether the contact is new or has persisted. eNOTIFY_TOUCH_CCD
just reports when the two collision objects were detected as being in contact during a CCD pass.
\note Only takes effect if the colliding actors are rigid bodies.
\note Trigger shapes are not supported.
\note Only takes effect if eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_CCD = (1<<5),
/**
\brief Call contact report callback when the contact force between the actors of this collision pair exceeds one of the actor-defined force thresholds.
\note Only takes effect if the colliding actors are rigid bodies.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact()
*/
eNOTIFY_THRESHOLD_FORCE_FOUND = (1<<6),
/**
\brief Call contact report callback when the contact force between the actors of this collision pair continues to exceed one of the actor-defined force thresholds.
\note Only takes effect if the colliding actors are rigid bodies.
\note If a pair gets re-filtered and this flag has previously been disabled, then the report will not get fired in the same frame even if the force threshold has been reached in the
previous one (unless #eNOTIFY_THRESHOLD_FORCE_FOUND has been set in the previous frame).
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact()
*/
eNOTIFY_THRESHOLD_FORCE_PERSISTS = (1<<7),
/**
\brief Call contact report callback when the contact force between the actors of this collision pair falls below one of the actor-defined force thresholds (includes the case where this collision pair stops being in contact).
\note Only takes effect if the colliding actors are rigid bodies.
\note If a pair gets re-filtered and this flag has previously been disabled, then the report will not get fired in the same frame even if the force threshold has been reached in the
previous one (unless #eNOTIFY_THRESHOLD_FORCE_FOUND or #eNOTIFY_THRESHOLD_FORCE_PERSISTS has been set in the previous frame).
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact()
*/
eNOTIFY_THRESHOLD_FORCE_LOST = (1<<8),
/**
\brief Provide contact points in contact reports for this collision pair.
\note Only takes effect if the colliding actors are rigid bodies and if used in combination with the flags eNOTIFY_TOUCH_... or eNOTIFY_THRESHOLD_FORCE_...
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxContactPair PxContactPair.extractContacts()
*/
eNOTIFY_CONTACT_POINTS = (1<<9),
/**
\brief This flag is used to indicate whether this pair generates discrete collision detection contacts.
\note Contacts are only responded to if eSOLVE_CONTACT is enabled.
*/
eDETECT_DISCRETE_CONTACT = (1<<10),
/**
\brief This flag is used to indicate whether this pair generates CCD contacts.
\note The contacts will only be responded to if eSOLVE_CONTACT is enabled on this pair.
\note The scene must have PxSceneFlag::eENABLE_CCD enabled to use this feature.
\note Non-static bodies of the pair should have PxRigidBodyFlag::eENABLE_CCD specified for this feature to work correctly.
\note This flag is not supported with trigger shapes. However, CCD trigger events can be emulated using non-trigger shapes
and requesting eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST and not raising eSOLVE_CONTACT on the pair.
@see PxRigidBodyFlag::eENABLE_CCD
@see PxSceneFlag::eENABLE_CCD
*/
eDETECT_CCD_CONTACT = (1<<11),
/**
\brief Provide pre solver velocities in contact reports for this collision pair.
If the collision pair has contact reports enabled, the velocities of the rigid bodies before contacts have been solved
will be provided in the contact report callback unless the pair lost touch in which case no data will be provided.
\note Usually it is not necessary to request these velocities as they will be available by querying the velocity from the provided
PxRigidActor object directly. However, it might be the case that the velocity of a rigid body gets set while the simulation is running
in which case the PxRigidActor would return this new velocity in the contact report callback and not the velocity the simulation used.
@see PxSimulationEventCallback.onContact(), PxContactPairVelocity, PxContactPairHeader.extraDataStream
*/
ePRE_SOLVER_VELOCITY = (1<<12),
/**
\brief Provide post solver velocities in contact reports for this collision pair.
If the collision pair has contact reports enabled, the velocities of the rigid bodies after contacts have been solved
will be provided in the contact report callback unless the pair lost touch in which case no data will be provided.
@see PxSimulationEventCallback.onContact(), PxContactPairVelocity, PxContactPairHeader.extraDataStream
*/
ePOST_SOLVER_VELOCITY = (1<<13),
/**
\brief Provide rigid body poses in contact reports for this collision pair.
If the collision pair has contact reports enabled, the rigid body poses at the contact event will be provided
in the contact report callback unless the pair lost touch in which case no data will be provided.
\note Usually it is not necessary to request these poses as they will be available by querying the pose from the provided
PxRigidActor object directly. However, it might be the case that the pose of a rigid body gets set while the simulation is running
in which case the PxRigidActor would return this new pose in the contact report callback and not the pose the simulation used.
Another use case is related to CCD with multiple passes enabled, A fast moving object might bounce on and off the same
object multiple times. This flag can be used to request the rigid body poses at the time of impact for each such collision event.
@see PxSimulationEventCallback.onContact(), PxContactPairPose, PxContactPairHeader.extraDataStream
*/
eCONTACT_EVENT_POSE = (1<<14),
eNEXT_FREE = (1<<15), //!< For internal use only.
/**
\brief Provided default flag to do simple contact processing for this collision pair.
*/
eCONTACT_DEFAULT = eSOLVE_CONTACT | eDETECT_DISCRETE_CONTACT,
/**
\brief Provided default flag to get commonly used trigger behavior for this collision pair.
*/
eTRIGGER_DEFAULT = eNOTIFY_TOUCH_FOUND | eNOTIFY_TOUCH_LOST | eDETECT_DISCRETE_CONTACT
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxPairFlag.
@see PxPairFlag
*/
typedef PxFlags<PxPairFlag::Enum, PxU16> PxPairFlags;
PX_FLAGS_OPERATORS(PxPairFlag::Enum, PxU16)
/**
\brief Collection of flags describing the filter actions to take for a collision pair.
@see PxFilterFlags PxSimulationFilterShader PxSimulationFilterCallback
*/
struct PxFilterFlag
{
enum Enum
{
/**
\brief Ignore the collision pair as long as the bounding volumes of the pair objects overlap.
Killed pairs will be ignored by the simulation and won't run through the filter again until one
of the following occurs:
\li The bounding volumes of the two objects overlap again (after being separated)
\li The user enforces a re-filtering (see #PxScene::resetFiltering())
@see PxScene::resetFiltering()
*/
eKILL = (1<<0),
/**
\brief Ignore the collision pair as long as the bounding volumes of the pair objects overlap or until filtering relevant data changes for one of the collision objects.
Suppressed pairs will be ignored by the simulation and won't make another filter request until one
of the following occurs:
\li Same conditions as for killed pairs (see #eKILL)
\li The filter data or the filter object attributes change for one of the collision objects
@see PxFilterData PxFilterObjectAttributes
*/
eSUPPRESS = (1<<1),
/**
\brief Invoke the filter callback (#PxSimulationFilterCallback::pairFound()) for this collision pair.
@see PxSimulationFilterCallback
*/
eCALLBACK = (1<<2),
/**
\brief Track this collision pair with the filter callback mechanism.
When the bounding volumes of the collision pair lose contact, the filter callback #PxSimulationFilterCallback::pairLost()
will be invoked. Furthermore, the filter status of the collision pair can be adjusted through #PxSimulationFilterCallback::statusChange()
once per frame (until a pairLost() notification occurs).
@see PxSimulationFilterCallback
*/
eNOTIFY = (1<<3) | eCALLBACK,
/**
\brief Provided default to get standard behavior:
The application configure the pair's collision properties once when bounding volume overlap is found and
doesn't get asked again about that pair until overlap status or filter properties changes, or re-filtering is requested.
No notification is provided when bounding volume overlap is lost
The pair will not be killed or suppressed, so collision detection will be processed
*/
eDEFAULT = 0
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxFilterFlag.
@see PxFilterFlag
*/
typedef PxFlags<PxFilterFlag::Enum, PxU16> PxFilterFlags;
PX_FLAGS_OPERATORS(PxFilterFlag::Enum, PxU16)
/**
\brief PxFilterData is user-definable data which gets passed into the collision filtering shader and/or callback.
@see PxShape.setSimulationFilterData() PxShape.getSimulationFilterData() PxSimulationFilterShader PxSimulationFilterCallback
*/
struct PxFilterData
{
PX_INLINE PxFilterData(const PxEMPTY)
{
}
/**
\brief Default constructor.
*/
PX_INLINE PxFilterData()
{
word0 = word1 = word2 = word3 = 0;
}
/**
\brief Copy constructor.
*/
PX_INLINE PxFilterData(const PxFilterData& fd) : word0(fd.word0), word1(fd.word1), word2(fd.word2), word3(fd.word3) {}
/**
\brief Constructor to set filter data initially.
*/
PX_INLINE PxFilterData(PxU32 w0, PxU32 w1, PxU32 w2, PxU32 w3) : word0(w0), word1(w1), word2(w2), word3(w3) {}
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault()
{
*this = PxFilterData();
}
/**
\brief Assignment operator
*/
PX_INLINE void operator = (const PxFilterData& fd)
{
word0 = fd.word0;
word1 = fd.word1;
word2 = fd.word2;
word3 = fd.word3;
}
/**
\brief Comparison operator to allow use in Array.
*/
PX_INLINE bool operator == (const PxFilterData& a) const
{
return a.word0 == word0 && a.word1 == word1 && a.word2 == word2 && a.word3 == word3;
}
/**
\brief Comparison operator to allow use in Array.
*/
PX_INLINE bool operator != (const PxFilterData& a) const
{
return !(a == *this);
}
PxU32 word0;
PxU32 word1;
PxU32 word2;
PxU32 word3;
};
/**
\brief Identifies each type of filter object.
@see PxGetFilterObjectType()
*/
struct PxFilterObjectType
{
enum Enum
{
/**
\brief A static rigid body
@see PxRigidStatic
*/
eRIGID_STATIC,
/**
\brief A dynamic rigid body
@see PxRigidDynamic
*/
eRIGID_DYNAMIC,
/**
\brief An articulation
@see PxArticulationReducedCoordinate
*/
eARTICULATION,
/**
\brief A particle system
@see PxParticleSystem
*/
ePARTICLESYSTEM,
/**
\brief A FEM-based soft body
@see PxSoftBody
*/
eSOFTBODY,
/**
\brief A FEM-based cloth
\note In development
@see PxFEMCloth
*/
eFEMCLOTH,
/**
\brief A hair system
\note In development
@see PxHairSystem
*/
eHAIRSYSTEM,
//! \brief internal use only!
eMAX_TYPE_COUNT = 16,
//! \brief internal use only!
eUNDEFINED = eMAX_TYPE_COUNT-1
};
};
// For internal use only
struct PxFilterObjectFlag
{
enum Enum
{
eKINEMATIC = (1<<4),
eTRIGGER = (1<<5),
eNEXT_FREE = (1<<6) // Used internally
};
};
/**
\brief Structure which gets passed into the collision filtering shader and/or callback providing additional information on objects of a collision pair
@see PxSimulationFilterShader PxSimulationFilterCallback getActorType() PxFilterObjectIsKinematic() PxFilterObjectIsTrigger()
*/
typedef PxU32 PxFilterObjectAttributes;
/**
\brief Extract filter object type from the filter attributes of a collision pair object
\param[in] attr The filter attribute of a collision pair object
\return The type of the collision pair object.
@see PxFilterObjectType
*/
PX_INLINE PxFilterObjectType::Enum PxGetFilterObjectType(PxFilterObjectAttributes attr)
{
return PxFilterObjectType::Enum(attr & (PxFilterObjectType::eMAX_TYPE_COUNT-1));
}
/**
\brief Specifies whether the collision object belongs to a kinematic rigid body
\param[in] attr The filter attribute of a collision pair object
\return True if the object belongs to a kinematic rigid body, else false
@see PxRigidBodyFlag::eKINEMATIC
*/
PX_INLINE bool PxFilterObjectIsKinematic(PxFilterObjectAttributes attr)
{
return (attr & PxFilterObjectFlag::eKINEMATIC) != 0;
}
/**
\brief Specifies whether the collision object is a trigger shape
\param[in] attr The filter attribute of a collision pair object
\return True if the object is a trigger shape, else false
@see PxShapeFlag::eTRIGGER_SHAPE
*/
PX_INLINE bool PxFilterObjectIsTrigger(PxFilterObjectAttributes attr)
{
return (attr & PxFilterObjectFlag::eTRIGGER) != 0;
}
/**
\brief Filter method to specify how a pair of potentially colliding objects should be processed.
Collision filtering is a mechanism to specify how a pair of potentially colliding objects should be processed by the
simulation. A pair of objects is potentially colliding if the bounding volumes of the two objects overlap.
In short, a collision filter decides whether a collision pair should get processed, temporarily ignored or discarded.
If a collision pair should get processed, the filter can additionally specify how it should get processed, for instance,
whether contacts should get resolved, which callbacks should get invoked or which reports should be sent etc.
The function returns the PxFilterFlag flags and sets the PxPairFlag flags to define what the simulation should do with the given collision pair.
\note A default implementation of a filter shader is provided in the PhysX extensions library, see #PxDefaultSimulationFilterShader.
This methods gets called when:
\li The bounding volumes of two objects start to overlap.
\li The bounding volumes of two objects overlap and the filter data or filter attributes of one of the objects changed
\li A re-filtering was forced through resetFiltering() (see #PxScene::resetFiltering())
\li Filtering is requested in scene queries
\note Certain pairs of objects are always ignored and this method does not get called. This is the case for the
following pairs:
\li Pair of static rigid actors
\li A static rigid actor and a kinematic actor (unless one is a trigger or if explicitly enabled through PxPairFilteringMode::eKEEP)
\li Two kinematic actors (unless one is a trigger or if explicitly enabled through PxPairFilteringMode::eKEEP)
\li Two jointed rigid bodies and the joint was defined to disable collision
\li Two articulation links if connected through an articulation joint
\note This is a performance critical method and should be stateless. You should neither access external objects
from within this method nor should you call external methods that are not inlined. If you need a more complex
logic to filter a collision pair then use the filter callback mechanism for this pair (see #PxSimulationFilterCallback,
#PxFilterFlag::eCALLBACK, #PxFilterFlag::eNOTIFY).
\param[in] attributes0 The filter attribute of the first object
\param[in] filterData0 The custom filter data of the first object
\param[in] attributes1 The filter attribute of the second object
\param[in] filterData1 The custom filter data of the second object
\param[out] pairFlags Flags giving additional information on how an accepted pair should get processed
\param[in] constantBlock The constant global filter data (see #PxSceneDesc.filterShaderData)
\param[in] constantBlockSize Size of the global filter data (see #PxSceneDesc.filterShaderDataSize)
\return Filter flags defining whether the pair should be discarded, temporarily ignored, processed and whether the
filter callback should get invoked for this pair.
@see PxSimulationFilterCallback PxFilterData PxFilterObjectAttributes PxFilterFlag PxFilterFlags PxPairFlag PxPairFlags PxSceneDesc.filterShader
*/
typedef PxFilterFlags (*PxSimulationFilterShader)
(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1,
PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize);
/**
\brief Filter callback to specify handling of collision pairs.
This class is provided to implement more complex and flexible collision pair filtering logic, for instance, taking
the state of the user application into account. Filter callbacks also give the user the opportunity to track collision
pairs and update their filter state.
You might want to check the documentation on #PxSimulationFilterShader as well since it includes more general information
on filtering.
\note SDK state should not be modified from within the callbacks. In particular objects should not
be created or destroyed. If state modification is needed then the changes should be stored to a buffer
and performed after the simulation step.
\note The callbacks may execute in user threads or simulation threads, possibly simultaneously. The corresponding objects
may have been deleted by the application earlier in the frame. It is the application's responsibility to prevent race conditions
arising from using the SDK API in the callback while an application thread is making write calls to the scene, and to ensure that
the callbacks are thread-safe. Return values which depend on when the callback is called during the frame will introduce nondeterminism
into the simulation.
@see PxSceneDesc.filterCallback PxSimulationFilterShader
*/
class PxSimulationFilterCallback
{
public:
/**
\brief Filter method to specify how a pair of potentially colliding objects should be processed.
This method gets called when the filter flags returned by the filter shader (see #PxSimulationFilterShader)
indicate that the filter callback should be invoked (#PxFilterFlag::eCALLBACK or #PxFilterFlag::eNOTIFY set).
Return the PxFilterFlag flags and set the PxPairFlag flags to define what the simulation should do with the given
collision pair.
\param[in] pairID Unique ID of the collision pair used to issue filter status changes for the pair (see #statusChange())
\param[in] attributes0 The filter attribute of the first object
\param[in] filterData0 The custom filter data of the first object
\param[in] a0 Actor pointer of the first object
\param[in] s0 Shape pointer of the first object (NULL if the object has no shapes)
\param[in] attributes1 The filter attribute of the second object
\param[in] filterData1 The custom filter data of the second object
\param[in] a1 Actor pointer of the second object
\param[in] s1 Shape pointer of the second object (NULL if the object has no shapes)
\param[in,out] pairFlags In: Pair flags returned by the filter shader. Out: Additional information on how an accepted pair should get processed
\return Filter flags defining whether the pair should be discarded, temporarily ignored or processed and whether the pair
should be tracked and send a report on pair deletion through the filter callback
@see PxSimulationFilterShader PxFilterData PxFilterObjectAttributes PxFilterFlag PxPairFlag
*/
virtual PxFilterFlags pairFound( PxU64 pairID,
PxFilterObjectAttributes attributes0, PxFilterData filterData0, const PxActor* a0, const PxShape* s0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1, const PxActor* a1, const PxShape* s1,
PxPairFlags& pairFlags) = 0;
/**
\brief Callback to inform that a tracked collision pair is gone.
This method gets called when a collision pair disappears or gets re-filtered. Only applies to
collision pairs which have been marked as filter callback pairs (#PxFilterFlag::eNOTIFY set in #pairFound()).
\param[in] pairID Unique ID of the collision pair that disappeared
\param[in] attributes0 The filter attribute of the first object
\param[in] filterData0 The custom filter data of the first object
\param[in] attributes1 The filter attribute of the second object
\param[in] filterData1 The custom filter data of the second object
\param[in] objectRemoved True if the pair was lost because one of the objects got removed from the scene
@see pairFound() PxSimulationFilterShader PxFilterData PxFilterObjectAttributes
*/
virtual void pairLost( PxU64 pairID,
PxFilterObjectAttributes attributes0, PxFilterData filterData0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1,
bool objectRemoved) = 0;
/**
\brief Callback to give the opportunity to change the filter state of a tracked collision pair.
This method gets called once per simulation step to let the application change the filter and pair
flags of a collision pair that has been reported in #pairFound() and requested callbacks by
setting #PxFilterFlag::eNOTIFY. To request a change of filter status, the target pair has to be
specified by its ID, the new filter and pair flags have to be provided and the method should return true.
\note If this method changes the filter status of a collision pair and the pair should keep being tracked
by the filter callbacks then #PxFilterFlag::eNOTIFY has to be set.
\note The application is responsible to ensure that this method does not get called for pairs that have been
reported as lost, see #pairLost().
\param[out] pairID ID of the collision pair for which the filter status should be changed
\param[out] pairFlags The new pairFlags to apply to the collision pair
\param[out] filterFlags The new filterFlags to apply to the collision pair
\return True if the changes should be applied. In this case the method will get called again. False if
no more status changes should be done in the current simulation step. In that case the provided flags will be discarded.
@see pairFound() pairLost() PxFilterFlag PxPairFlag
*/
virtual bool statusChange(PxU64& pairID, PxPairFlags& pairFlags, PxFilterFlags& filterFlags) = 0;
protected:
virtual ~PxSimulationFilterCallback() {}
};
struct PxPairFilteringMode
{
enum Enum
{
/**
\brief Output pair from BP, potentially send to user callbacks, create regular interaction object.
Enable contact pair filtering between kinematic/static or kinematic/kinematic rigid bodies.
By default contacts between these are suppressed (see #PxFilterFlag::eSUPPRESS) and don't get reported to the filter mechanism.
Use this mode if these pairs should go through the filtering pipeline nonetheless.
\note This mode is not mutable, and must be set in PxSceneDesc at scene creation.
*/
eKEEP,
/**
\brief Output pair from BP, create interaction marker. Can be later switched to regular interaction.
*/
eSUPPRESS,
/**
\brief Don't output pair from BP. Cannot be later switched to regular interaction, needs "resetFiltering" call.
*/
eKILL,
/**
\brief Default is eSUPPRESS for compatibility with previous PhysX versions.
*/
eDEFAULT = eSUPPRESS
};
};
/**
\brief Struct for storing a particle/vertex - rigid filter pair with comparison operators
*/
struct PxParticleRigidFilterPair
{
PX_CUDA_CALLABLE PxParticleRigidFilterPair() {}
PX_CUDA_CALLABLE PxParticleRigidFilterPair(const PxU64 id0, const PxU64 id1): mID0(id0), mID1(id1) {}
PxU64 mID0; //!< Rigid node index
PxU64 mID1; //!< Particle/vertex id
PX_CUDA_CALLABLE bool operator<(const PxParticleRigidFilterPair& other) const
{
if(mID0 < other.mID0)
return true;
if(mID0 == other.mID0 && mID1 < other.mID1)
return true;
return false;
}
PX_CUDA_CALLABLE bool operator>(const PxParticleRigidFilterPair& other) const
{
if(mID0 > other.mID0)
return true;
if(mID0 == other.mID0 && mID1 > other.mID1)
return true;
return false;
}
PX_CUDA_CALLABLE bool operator==(const PxParticleRigidFilterPair& other) const
{
return (mID0 == other.mID0 && mID1 == other.mID1);
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,117 | C | 37.56338 | 226 | 0.765647 |
NVIDIA-Omniverse/PhysX/physx/include/PxRigidDynamic.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_RIGID_DYNAMIC_H
#define PX_RIGID_DYNAMIC_H
/** \addtogroup physics
@{
*/
#include "PxRigidBody.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Collection of flags providing a mechanism to lock motion along/around a specific axis.
@see PxRigidDynamic.setRigidDynamicLockFlag(), PxRigidBody.getRigidDynamicLockFlags()
*/
struct PxRigidDynamicLockFlag
{
enum Enum
{
eLOCK_LINEAR_X = (1 << 0),
eLOCK_LINEAR_Y = (1 << 1),
eLOCK_LINEAR_Z = (1 << 2),
eLOCK_ANGULAR_X = (1 << 3),
eLOCK_ANGULAR_Y = (1 << 4),
eLOCK_ANGULAR_Z = (1 << 5)
};
};
typedef PxFlags<PxRigidDynamicLockFlag::Enum, PxU8> PxRigidDynamicLockFlags;
PX_FLAGS_OPERATORS(PxRigidDynamicLockFlag::Enum, PxU8)
/**
\brief PxRigidDynamic represents a dynamic rigid simulation object in the physics SDK.
<h3>Creation</h3>
Instances of this class are created by calling #PxPhysics::createRigidDynamic() and deleted with #release().
<h3>Visualizations</h3>
\li #PxVisualizationParameter::eACTOR_AXES
\li #PxVisualizationParameter::eBODY_AXES
\li #PxVisualizationParameter::eBODY_MASS_AXES
\li #PxVisualizationParameter::eBODY_LIN_VELOCITY
\li #PxVisualizationParameter::eBODY_ANG_VELOCITY
@see PxRigidBody PxPhysics.createRigidDynamic() release()
*/
class PxRigidDynamic : public PxRigidBody
{
public:
// Runtime modifications
/************************************************************************************************/
/** @name Kinematic Actors
*/
/**
\brief Moves kinematically controlled dynamic actors through the game world.
You set a dynamic actor to be kinematic using the PxRigidBodyFlag::eKINEMATIC flag
with setRigidBodyFlag().
The move command will result in a velocity that will move the body into
the desired pose. After the move is carried out during a single time step,
the velocity is returned to zero. Thus, you must continuously call
this in every time step for kinematic actors so that they move along a path.
This function simply stores the move destination until the next simulation
step is processed, so consecutive calls will simply overwrite the stored target variable.
The motion is always fully carried out.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
<b>Sleeping:</b> This call wakes the actor if it is sleeping and will set the wake counter to #PxSceneDesc::wakeCounterResetValue.
\param[in] destination The desired pose for the kinematic actor, in the global frame. <b>Range:</b> rigid body transform.
@see getKinematicTarget() PxRigidBodyFlag setRigidBodyFlag()
*/
virtual void setKinematicTarget(const PxTransform& destination) = 0;
/**
\brief Get target pose of a kinematically controlled dynamic actor.
\param[out] target Transform to write the target pose to. Only valid if the method returns true.
\return True if the actor is a kinematically controlled dynamic and the target has been set, else False.
@see setKinematicTarget() PxRigidBodyFlag setRigidBodyFlag()
*/
virtual bool getKinematicTarget(PxTransform& target) const = 0;
/************************************************************************************************/
/** @name Sleeping
*/
/**
\brief Returns true if this body is sleeping.
When an actor does not move for a period of time, it is no longer simulated in order to save time. This state
is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object,
or one of its properties is changed by the user, the entire sleep mechanism should be transparent to the user.
In general, a dynamic rigid actor is guaranteed to be awake if at least one of the following holds:
\li The wake counter is positive (see #setWakeCounter()).
\li The linear or angular velocity is non-zero.
\li A non-zero force or torque has been applied.
If a dynamic rigid actor is sleeping, the following state is guaranteed:
\li The wake counter is zero.
\li The linear and angular velocity is zero.
\li There is no force update pending.
When an actor gets inserted into a scene, it will be considered asleep if all the points above hold, else it will be treated as awake.
If an actor is asleep after the call to PxScene::fetchResults() returns, it is guaranteed that the pose of the actor
was not changed. You can use this information to avoid updating the transforms of associated objects.
\note A kinematic actor is asleep unless a target pose has been set (in which case it will stay awake until two consecutive
simulation steps without a target pose being set have passed). The wake counter will get set to zero or to the reset value
#PxSceneDesc::wakeCounterResetValue in the case where a target pose has been set to be consistent with the definitions above.
\note It is invalid to use this method if the actor has not been added to a scene already.
\note It is not allowed to use this method while the simulation is running.
\return True if the actor is sleeping.
@see isSleeping() wakeUp() putToSleep() getSleepThreshold()
*/
virtual bool isSleeping() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which an actor may go to sleep.
Actors whose kinetic energy divided by their mass is below this threshold will be candidates for sleeping.
<b>Default:</b> 5e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which an actor may go to sleep. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getSleepThreshold() wakeUp() putToSleep() PxTolerancesScale
*/
virtual void setSleepThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which an actor may go to sleep.
\return The energy threshold for sleeping.
@see isSleeping() wakeUp() putToSleep() setSleepThreshold()
*/
virtual PxReal getSleepThreshold() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which an actor may participate in stabilization.
Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
This value has no effect if PxSceneFlag::eENABLE_STABILIZATION was not enabled on the PxSceneDesc.
<b>Default:</b> 1e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which an actor may participate in stabilization. <b>Range:</b> [0,inf)
@see getStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual void setStabilizationThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which an actor may participate in stabilization.
Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
\return The energy threshold for participating in stabilization.
@see setStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual PxReal getStabilizationThreshold() const = 0;
/**
\brief Reads the PxRigidDynamic lock flags.
See the list of flags #PxRigidDynamicLockFlag
\return The values of the PxRigidDynamicLock flags.
@see PxRigidDynamicLockFlag setRigidDynamicLockFlag()
*/
virtual PxRigidDynamicLockFlags getRigidDynamicLockFlags() const = 0;
/**
\brief Raises or clears a particular rigid dynamic lock flag.
See the list of flags #PxRigidDynamicLockFlag
<b>Default:</b> no flags are set
\param[in] flag The PxRigidDynamicLockBody flag to raise(set) or clear. See #PxRigidBodyFlag.
\param[in] value The new boolean value for the flag.
@see PxRigidDynamicLockFlag getRigidDynamicLockFlags()
*/
virtual void setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) = 0;
virtual void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) = 0;
/**
\brief Retrieves the linear velocity of an actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\note The linear velocity is reported with respect to the rigid dynamic's center of mass and not the actor frame origin.
\return The linear velocity of the actor.
@see PxRigidDynamic.setLinearVelocity() getAngularVelocity()
*/
virtual PxVec3 getLinearVelocity() const = 0;
/**
\brief Sets the linear velocity of the actor.
Note that if you continuously set the velocity of an actor yourself,
forces such as gravity or friction will not be able to manifest themselves, because forces directly
influence only the velocity/momentum of an actor.
<b>Default:</b> (0.0, 0.0, 0.0)
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the
new velocity is non-zero.
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
\note The linear velocity is applied with respect to the rigid dynamic's center of mass and not the actor frame origin.
\param[in] linVel New linear velocity of actor. <b>Range:</b> velocity vector
\param[in] autowake Whether to wake the object up if it is asleep. If true and the current wake counter value is
smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see getLinearVelocity() setAngularVelocity()
*/
virtual void setLinearVelocity(const PxVec3& linVel, bool autowake = true) = 0;
/**
\brief Retrieves the angular velocity of the actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\return The angular velocity of the actor.
@see PxRigidDynamic.setAngularVelocity() getLinearVelocity()
*/
virtual PxVec3 getAngularVelocity() const = 0;
/**
\brief Sets the angular velocity of the actor.
Note that if you continuously set the angular velocity of an actor yourself,
forces such as friction will not be able to rotate the actor, because forces directly influence only the velocity/momentum.
<b>Default:</b> (0.0, 0.0, 0.0)
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the
new velocity is non-zero.
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
\param[in] angVel New angular velocity of actor. <b>Range:</b> angular velocity vector
\param[in] autowake Whether to wake the object up if it is asleep. If true and the current wake counter value is
smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see getAngularVelocity() setLinearVelocity()
*/
virtual void setAngularVelocity(const PxVec3& angVel, bool autowake = true) = 0;
/**
\brief Sets the wake counter for the actor.
The wake counter value determines the minimum amount of time until the body can be put to sleep. Please note
that a body will not be put to sleep if the energy is above the specified threshold (see #setSleepThreshold())
or if other awake bodies are touching it.
\note Passing in a positive value will wake the actor up automatically.
\note It is invalid to use this method for kinematic actors since the wake counter for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
<b>Default:</b> 0.4 (which corresponds to 20 frames for a time step of 0.02)
\param[in] wakeCounterValue Wake counter value. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getWakeCounter()
*/
virtual void setWakeCounter(PxReal wakeCounterValue) = 0;
/**
\brief Returns the wake counter of the actor.
\note It is not allowed to use this method while the simulation is running.
\return The wake counter of the actor.
@see isSleeping() setWakeCounter()
*/
virtual PxReal getWakeCounter() const = 0;
/**
\brief Wakes up the actor if it is sleeping.
The actor will get woken up and might cause other touching actors to wake up as well during the next simulation step.
\note This will set the wake counter of the actor to the value specified in #PxSceneDesc::wakeCounterResetValue.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
@see isSleeping() putToSleep()
*/
virtual void wakeUp() = 0;
/**
\brief Forces the actor to sleep.
The actor will stay asleep during the next simulation step if not touched by another non-sleeping actor.
\note Any applied force will be cleared and the velocity and the wake counter of the actor will be set to 0.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
@see isSleeping() wakeUp()
*/
virtual void putToSleep() = 0;
/************************************************************************************************/
/**
\brief Sets the solver iteration counts for the body.
The solver iteration count determines how accurately joints and contacts are resolved.
If you are having trouble with jointed bodies oscillating and behaving erratically, then
setting a higher position iteration count may improve their stability.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations. More velocity iterations will drive the relative exit velocity of the intersecting
objects closer to the correct value given the restitution.
<b>Default:</b> 4 position iterations, 1 velocity iteration
\param[in] minPositionIters Number of position iterations the solver should perform for this body. <b>Range:</b> [1,255]
\param[in] minVelocityIters Number of velocity iterations the solver should perform for this body. <b>Range:</b> [0,255]
@see getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Retrieves the solver iteration counts.
@see setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Retrieves the force threshold for contact reports.
The contact report threshold is a force threshold. If the force between
two actors exceeds this threshold for either of the two actors, a contact report
will be generated according to the contact report threshold flags provided by
the filter shader/callback.
See #PxPairFlag.
The threshold used for a collision between a dynamic actor and the static environment is
the threshold of the dynamic actor, and all contacts with static actors are summed to find
the total normal force.
<b>Default:</b> PX_MAX_F32
\return Force threshold for contact reports.
@see setContactReportThreshold PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual PxReal getContactReportThreshold() const = 0;
/**
\brief Sets the force threshold for contact reports.
See #getContactReportThreshold().
\param[in] threshold Force threshold for contact reports. <b>Range:</b> [0, PX_MAX_F32)
@see getContactReportThreshold PxPairFlag
*/
virtual void setContactReportThreshold(PxReal threshold) = 0;
virtual const char* getConcreteTypeName() const { return "PxRigidDynamic"; }
protected:
PX_INLINE PxRigidDynamic(PxType concreteType, PxBaseFlags baseFlags) : PxRigidBody(concreteType, baseFlags) { }
PX_INLINE PxRigidDynamic(PxBaseFlags baseFlags) : PxRigidBody(baseFlags) {}
virtual ~PxRigidDynamic() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidDynamic", PxRigidBody); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 17,957 | C | 38.124183 | 137 | 0.748789 |
NVIDIA-Omniverse/PhysX/physx/include/PxRigidStatic.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_RIGID_STATIC_H
#define PX_RIGID_STATIC_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxRigidActor.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief PxRigidStatic represents a static rigid body simulation object in the physics SDK.
PxRigidStatic objects are static rigid physics entities. They shall be used to define solid objects which are fixed in the world.
<h3>Creation</h3>
Instances of this class are created by calling #PxPhysics::createRigidStatic() and deleted with #release().
<h3>Visualizations</h3>
\li #PxVisualizationParameter::eACTOR_AXES
@see PxRigidActor PxPhysics.createRigidStatic() release()
*/
class PxRigidStatic : public PxRigidActor
{
public:
virtual const char* getConcreteTypeName() const { return "PxRigidStatic"; }
protected:
PX_INLINE PxRigidStatic(PxType concreteType, PxBaseFlags baseFlags) : PxRigidActor(concreteType, baseFlags) {}
PX_INLINE PxRigidStatic(PxBaseFlags baseFlags) : PxRigidActor(baseFlags){}
virtual ~PxRigidStatic() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidStatic", PxRigidActor); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,908 | C | 37.276315 | 129 | 0.758597 |
NVIDIA-Omniverse/PhysX/physx/include/PxBroadPhase.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_BROAD_PHASE_H
#define PX_BROAD_PHASE_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxBounds3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
class PxCudaContextManager;
/**
\brief Broad phase algorithm used in the simulation
eSAP is a good generic choice with great performance when many objects are sleeping. Performance
can degrade significantly though, when all objects are moving, or when large numbers of objects
are added to or removed from the broad phase. This algorithm does not need world bounds to be
defined in order to work.
eMBP is an alternative broad phase algorithm that does not suffer from the same performance
issues as eSAP when all objects are moving or when inserting large numbers of objects. However
its generic performance when many objects are sleeping might be inferior to eSAP, and it requires
users to define world bounds in order to work.
eABP is a revisited implementation of MBP, which automatically manages broad-phase regions.
It offers the convenience of eSAP (no need to define world bounds or regions) and the performance
of eMBP when a lot of objects are moving. While eSAP can remain faster when most objects are
sleeping and eMBP can remain faster when it uses a large number of properly-defined regions,
eABP often gives the best performance on average and the best memory usage.
ePABP is a parallel implementation of ABP. It can often be the fastest (CPU) broadphase, but it
can use more memory than ABP.
eGPU is a GPU implementation of the incremental sweep and prune approach. Additionally, it uses a ABP-style
initial pair generation approach to avoid large spikes when inserting shapes. It not only has the advantage
of traditional SAP approch which is good for when many objects are sleeping, but due to being fully parallel,
it also is great when lots of shapes are moving or for runtime pair insertion and removal. It can become a
performance bottleneck if there are a very large number of shapes roughly projecting to the same values
on a given axis. If the scene has a very large number of shapes in an actor, e.g. a humanoid, it is recommended
to use an aggregate to represent multi-shape or multi-body actors to minimize stress placed on the broad phase.
*/
struct PxBroadPhaseType
{
enum Enum
{
eSAP, //!< 3-axes sweep-and-prune
eMBP, //!< Multi box pruning
eABP, //!< Automatic box pruning
ePABP, //!< Parallel automatic box pruning
eGPU, //!< GPU broad phase
eLAST
};
};
/**
\brief "Region of interest" for the broad-phase.
This is currently only used for the PxBroadPhaseType::eMBP broad-phase, which requires zones or regions to be defined
when the simulation starts in order to work. Regions can overlap and be added or removed at runtime, but at least one
region needs to be defined when the scene is created.
If objects that do no overlap any region are inserted into the scene, they will not be added to the broad-phase and
thus collisions will be disabled for them. A PxBroadPhaseCallback out-of-bounds notification will be sent for each one
of those objects.
The total number of regions is limited by PxBroadPhaseCaps::mMaxNbRegions.
The number of regions has a direct impact on performance and memory usage, so it is recommended to experiment with
various settings to find the best combination for your game. A good default setup is to start with global bounds
around the whole world, and subdivide these bounds into 4*4 regions. The PxBroadPhaseExt::createRegionsFromWorldBounds
function can do that for you.
@see PxBroadPhaseCallback PxBroadPhaseExt.createRegionsFromWorldBounds
*/
struct PxBroadPhaseRegion
{
PxBounds3 mBounds; //!< Region's bounds
void* mUserData; //!< Region's user-provided data
};
/**
\brief Information & stats structure for a region
*/
struct PxBroadPhaseRegionInfo
{
PxBroadPhaseRegion mRegion; //!< User-provided region data
PxU32 mNbStaticObjects; //!< Number of static objects in the region
PxU32 mNbDynamicObjects; //!< Number of dynamic objects in the region
bool mActive; //!< True if region is currently used, i.e. it has not been removed
bool mOverlap; //!< True if region overlaps other regions (regions that are just touching are not considering overlapping)
};
/**
\brief Caps class for broad phase.
*/
struct PxBroadPhaseCaps
{
PxU32 mMaxNbRegions; //!< Max number of regions supported by the broad-phase (0 = explicit regions not needed)
};
/**
\brief Broadphase descriptor.
This structure is used to create a standalone broadphase. It captures all the parameters needed to
initialize a broadphase.
For the GPU broadphase (PxBroadPhaseType::eGPU) it is necessary to provide a CUDA context manager.
The kinematic filtering flags are currently not supported by the GPU broadphase. They are used to
dismiss pairs that involve kinematic objects directly within the broadphase.
\see PxCreateBroadPhase
*/
class PxBroadPhaseDesc
{
public:
PxBroadPhaseDesc(PxBroadPhaseType::Enum type = PxBroadPhaseType::eLAST) :
mType (type),
mContextID (0),
mContextManager (NULL),
mFoundLostPairsCapacity (256 * 1024),
mDiscardStaticVsKinematic (false),
mDiscardKinematicVsKinematic(false)
{}
PxBroadPhaseType::Enum mType; //!< Desired broadphase implementation
PxU64 mContextID; //!< Context ID for profiler. See PxProfilerCallback.
PxCudaContextManager* mContextManager; //!< (GPU) CUDA context manager, must be provided for PxBroadPhaseType::eGPU.
PxU32 mFoundLostPairsCapacity; //!< (GPU) Capacity of found and lost buffers allocated in GPU global memory. This is used for the found/lost pair reports in the BP.
bool mDiscardStaticVsKinematic; //!< Static-vs-kinematic filtering flag. Not supported by PxBroadPhaseType::eGPU.
bool mDiscardKinematicVsKinematic; //!< kinematic-vs-kinematic filtering flag. Not supported by PxBroadPhaseType::eGPU.
PX_INLINE bool isValid() const
{
if(PxU32(mType)>=PxBroadPhaseType::eLAST)
return false;
if(mType==PxBroadPhaseType::eGPU && !mContextManager)
return false;
return true;
}
};
typedef PxU32 PxBpIndex; //!< Broadphase index. Indexes bounds, groups and distance arrays.
typedef PxU32 PxBpFilterGroup; //!< Broadphase filter group.
#define PX_INVALID_BP_FILTER_GROUP 0xffffffff //!< Invalid broadphase filter group
/**
\brief Retrieves the filter group for static objects.
Mark static objects with this group when adding them to the broadphase.
Overlaps between static objects will not be detected. All static objects
should have the same group.
\return Filter group for static objects.
\see PxBpFilterGroup
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseStaticFilterGroup();
/**
\brief Retrieves a filter group for dynamic objects.
Mark dynamic objects with this group when adding them to the broadphase.
Each dynamic object must have an ID, and overlaps between dynamic objects that have
the same ID will not be detected. This is useful to dismiss overlaps between shapes
of the same (compound) actor directly within the broadphase.
\param id [in] ID/Index of dynamic object
\return Filter group for the object.
\see PxBpFilterGroup
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseDynamicFilterGroup(PxU32 id);
/**
\brief Retrieves a filter group for kinematic objects.
Mark kinematic objects with this group when adding them to the broadphase.
Each kinematic object must have an ID, and overlaps between kinematic objects that have
the same ID will not be detected.
\param id [in] ID/Index of kinematic object
\return Filter group for the object.
\see PxBpFilterGroup
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseKinematicFilterGroup(PxU32 id);
/**
\brief Broadphase data update structure.
This structure is used to update the low-level broadphase (PxBroadPhase). All added, updated and removed objects
must be batched and submitted at once to the broadphase.
Broadphase objects have bounds, a filtering group, and a distance. With the low-level broadphase the data must be
externally managed by the clients of the broadphase API, and passed to the update function.
The provided bounds are non-inflated "base" bounds that can be further extended by the broadphase using the passed
distance value. These can be contact offsets, or dynamically updated distance values for e.g. speculative contacts.
Either way they are optional and can be left to zero. The broadphase implementations efficiently combine the base
bounds with the per-object distance values at runtime.
The per-object filtering groups are used to discard some pairs directly within the broadphase, which is more
efficient than reporting the pairs and culling them in a second pass.
\see PxBpFilterGroup PxBpIndex PxBounds3 PxBroadPhase::update
*/
class PxBroadPhaseUpdateData
{
public:
PxBroadPhaseUpdateData( const PxBpIndex* created, PxU32 nbCreated,
const PxBpIndex* updated, PxU32 nbUpdated,
const PxBpIndex* removed, PxU32 nbRemoved,
const PxBounds3* bounds, const PxBpFilterGroup* groups, const float* distances,
PxU32 capacity) :
mCreated (created), mNbCreated (nbCreated),
mUpdated (updated), mNbUpdated (nbUpdated),
mRemoved (removed), mNbRemoved (nbRemoved),
mBounds (bounds), mGroups (groups), mDistances (distances),
mCapacity (capacity)
{
}
PxBroadPhaseUpdateData(const PxBroadPhaseUpdateData& other) :
mCreated (other.mCreated), mNbCreated (other.mNbCreated),
mUpdated (other.mUpdated), mNbUpdated (other.mNbUpdated),
mRemoved (other.mRemoved), mNbRemoved (other.mNbRemoved),
mBounds (other.mBounds), mGroups (other.mGroups), mDistances (other.mDistances),
mCapacity (other.mCapacity)
{
}
PxBroadPhaseUpdateData& operator=(const PxBroadPhaseUpdateData& other);
const PxBpIndex* mCreated; //!< Indices of created objects.
const PxU32 mNbCreated; //!< Number of created objects.
const PxBpIndex* mUpdated; //!< Indices of updated objects.
const PxU32 mNbUpdated; //!< Number of updated objects.
const PxBpIndex* mRemoved; //!< Indices of removed objects.
const PxU32 mNbRemoved; //!< Number of removed objects.
const PxBounds3* mBounds; //!< (Persistent) array of bounds.
const PxBpFilterGroup* mGroups; //!< (Persistent) array of groups.
const float* mDistances; //!< (Persistent) array of distances.
const PxU32 mCapacity; //!< Capacity of bounds / groups / distance buffers.
};
/**
\brief Broadphase pair.
A pair of indices returned by the broadphase for found or lost pairs.
\see PxBroadPhaseResults
*/
struct PxBroadPhasePair
{
PxBpIndex mID0; //!< Index of first object
PxBpIndex mID1; //!< Index of second object
};
/**
\brief Broadphase results.
Set of found and lost pairs after a broadphase update.
\see PxBroadPhasePair PxBroadPhase::fetchResults PxAABBManager::fetchResults
*/
struct PxBroadPhaseResults
{
PxBroadPhaseResults() : mNbCreatedPairs(0), mCreatedPairs(NULL), mNbDeletedPairs(0), mDeletedPairs(NULL) {}
PxU32 mNbCreatedPairs; //!< Number of new/found/created pairs.
const PxBroadPhasePair* mCreatedPairs; //!< Array of new/found/created pairs.
PxU32 mNbDeletedPairs; //!< Number of lost/deleted pairs.
const PxBroadPhasePair* mDeletedPairs; //!< Array of lost/deleted pairs.
};
/**
\brief Broadphase regions.
An API to manage broadphase regions. Only needed for the MBP broadphase (PxBroadPhaseType::eMBP).
\see PxBroadPhase::getRegions()
*/
class PxBroadPhaseRegions
{
protected:
PxBroadPhaseRegions() {}
virtual ~PxBroadPhaseRegions() {}
public:
/**
\brief Returns number of regions currently registered in the broad-phase.
\return Number of regions
*/
virtual PxU32 getNbRegions() const = 0;
/**
\brief Gets broad-phase regions.
\param userBuffer [out] Returned broad-phase regions
\param bufferSize [in] Size of provided userBuffer.
\param startIndex [in] Index of first desired region, in [0 ; getNbRegions()[
\return Number of written out regions.
\see PxBroadPhaseRegionInfo
*/
virtual PxU32 getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Adds a new broad-phase region.
The total number of regions is limited to PxBroadPhaseCaps::mMaxNbRegions. If that number is exceeded, the call is ignored.
The newly added region will be automatically populated with already existing objects that touch it, if the
'populateRegion' parameter is set to true. Otherwise the newly added region will be empty, and it will only be
populated with objects when those objects are added to the simulation, or updated if they already exist.
Using 'populateRegion=true' has a cost, so it is best to avoid it if possible. In particular it is more efficient
to create the empty regions first (with populateRegion=false) and then add the objects afterwards (rather than
the opposite).
Objects automatically move from one region to another during their lifetime. The system keeps tracks of what
regions a given object is in. It is legal for an object to be in an arbitrary number of regions. However if an
object leaves all regions, or is created outside of all regions, several things happen:
- collisions get disabled for this object
- the object appears in the getOutOfBoundsObjects() array
If an out-of-bounds object, whose collisions are disabled, re-enters a valid broadphase region, then collisions
are re-enabled for that object.
\param region [in] User-provided region data
\param populateRegion [in] True to automatically populate the newly added region with existing objects touching it
\param bounds [in] User-managed array of bounds
\param distances [in] User-managed array of distances
\return Handle for newly created region, or 0xffffffff in case of failure.
\see PxBroadPhaseRegion getOutOfBoundsObjects()
*/
virtual PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* bounds, const float* distances) = 0;
/**
\brief Removes a broad-phase region.
If the region still contains objects, and if those objects do not overlap any region any more, they are not
automatically removed from the simulation. Instead, the PxBroadPhaseCallback::onObjectOutOfBounds notification
is used for each object. Users are responsible for removing the objects from the simulation if this is the
desired behavior.
If the handle is invalid, or if a valid handle is removed twice, an error message is sent to the error stream.
\param handle [in] Region's handle, as returned by addRegion
\return True if success
*/
virtual bool removeRegion(PxU32 handle) = 0;
/*
\brief Return the number of objects that are not in any region.
*/
virtual PxU32 getNbOutOfBoundsObjects() const = 0;
/*
\brief Return an array of objects that are not in any region.
*/
virtual const PxU32* getOutOfBoundsObjects() const = 0;
};
/**
\brief Low-level broadphase API.
This low-level API only supports batched updates and leaves most of the data management to its clients.
This is useful if you want to use the broadphase with your own memory buffers. Note however that the GPU broadphase
works best with buffers allocated in CUDA memory. The getAllocator() function returns an allocator that is compatible
with the selected broadphase. It is recommended to allocate and deallocate the broadphase data (bounds, groups, distances)
using this allocator.
Important note: it must be safe to load 4 bytes past the end of the provided bounds array.
The high-level broadphase API (PxAABBManager) is an easier-to-use interface that automatically deals with these requirements.
\see PxCreateBroadPhase
*/
class PxBroadPhase
{
protected:
PxBroadPhase() {}
virtual ~PxBroadPhase() {}
public:
/*
\brief Releases the broadphase.
*/
virtual void release() = 0;
/**
\brief Gets the broadphase type.
\return Broadphase type.
\see PxBroadPhaseType::Enum
*/
virtual PxBroadPhaseType::Enum getType() const = 0;
/**
\brief Gets broad-phase caps.
\param caps [out] Broad-phase caps
\see PxBroadPhaseCaps
*/
virtual void getCaps(PxBroadPhaseCaps& caps) const = 0;
/**
\brief Retrieves the regions API if applicable.
For broadphases that do not use explicit user-defined regions, this call returns NULL.
\return Region API, or NULL.
\see PxBroadPhaseRegions
*/
virtual PxBroadPhaseRegions* getRegions() = 0;
/**
\brief Retrieves the broadphase allocator.
User-provided buffers should ideally be allocated with this allocator, for best performance.
This is especially true for the GPU broadphases, whose buffers need to be allocated in CUDA
host memory.
\return The broadphase allocator.
\see PxAllocatorCallback
*/
virtual PxAllocatorCallback* getAllocator() = 0;
/**
\brief Retrieves the profiler's context ID.
\return The context ID.
\see PxBroadPhaseDesc
*/
virtual PxU64 getContextID() const = 0;
/**
\brief Sets a scratch buffer
Some broadphases might take advantage of a scratch buffer to limit runtime allocations.
All broadphases still work without providing a scratch buffer, this is an optional function
that can potentially reduce runtime allocations.
\param scratchBlock [in] The scratch buffer
\param size [in] Size of the scratch buffer in bytes
*/
virtual void setScratchBlock(void* scratchBlock, PxU32 size) = 0;
/**
\brief Updates the broadphase and computes the lists of created/deleted pairs.
The provided update data describes changes to objects since the last broadphase update.
To benefit from potentially multithreaded implementations, it is necessary to provide a continuation
task to the function. It is legal to pass NULL there, but the underlying (CPU) implementations will
then run single-threaded.
\param updateData [in] The update data
\param continuation [in] Continuation task to enable multi-threaded implementations, or NULL.
\see PxBroadPhaseUpdateData PxBaseTask
*/
virtual void update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation=NULL) = 0;
/**
\brief Retrieves the broadphase results after an update.
This should be called once after each update call to retrieve the results of the broadphase. The
results are incremental, i.e. the system only returns new and lost pairs, not all current pairs.
\param results [out] The broadphase results
\see PxBroadPhaseResults
*/
virtual void fetchResults(PxBroadPhaseResults& results) = 0;
/**
\brief Helper for single-threaded updates.
This short helper function performs a single-theaded update and reports the results in a single call.
\param results [out] The broadphase results
\param updateData [in] The update data
\see PxBroadPhaseUpdateData PxBroadPhaseResults
*/
PX_FORCE_INLINE void update(PxBroadPhaseResults& results, const PxBroadPhaseUpdateData& updateData)
{
update(updateData);
fetchResults(results);
}
};
/**
\brief Broadphase factory function.
Use this function to create a new standalone broadphase.
\param desc [in] Broadphase descriptor
\return Newly created broadphase, or NULL
\see PxBroadPhase PxBroadPhaseDesc
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBroadPhase* PxCreateBroadPhase(const PxBroadPhaseDesc& desc);
/**
\brief High-level broadphase API.
The low-level broadphase API (PxBroadPhase) only supports batched updates and has a few non-trivial
requirements for managing the bounds data.
The high-level broadphase API (PxAABBManager) is an easier-to-use one-object-at-a-time API that
automatically deals with the quirks of the PxBroadPhase data management.
\see PxCreateAABBManager
*/
class PxAABBManager
{
protected:
PxAABBManager() {}
virtual ~PxAABBManager() {}
public:
/*
\brief Releases the AABB manager.
*/
virtual void release() = 0;
/**
\brief Retrieves the underlying broadphase.
\return The managed broadphase.
\see PxBroadPhase
*/
virtual PxBroadPhase& getBroadPhase() = 0;
/**
\brief Retrieves the managed bounds.
This is needed as input parameters to functions like PxBroadPhaseRegions::addRegion.
\return The managed object bounds.
\see PxBounds3
*/
virtual const PxBounds3* getBounds() const = 0;
/**
\brief Retrieves the managed distances.
This is needed as input parameters to functions like PxBroadPhaseRegions::addRegion.
\return The managed object distances.
*/
virtual const float* getDistances() const = 0;
/**
\brief Retrieves the managed filter groups.
\return The managed object groups.
*/
virtual const PxBpFilterGroup* getGroups() const = 0;
/**
\brief Retrieves the managed buffers' capacity.
Bounds, distances and groups buffers have the same capacity.
\return The managed buffers' capacity.
*/
virtual PxU32 getCapacity() const = 0;
/**
\brief Adds an object to the manager.
Objects' indices are externally managed, i.e. they must be provided by users (as opposed to handles
that could be returned by this manager). The design allows users to identify an object by a single ID,
and use the same ID in multiple sub-systems.
\param index [in] The object's index
\param bounds [in] The object's bounds
\param group [in] The object's filter group
\param distance [in] The object's distance (optional)
\see PxBpIndex PxBounds3 PxBpFilterGroup
*/
virtual void addObject(PxBpIndex index, const PxBounds3& bounds, PxBpFilterGroup group, float distance=0.0f) = 0;
/**
\brief Removes an object from the manager.
\param index [in] The object's index
\see PxBpIndex
*/
virtual void removeObject(PxBpIndex index) = 0;
/**
\brief Updates an object in the manager.
This call can update an object's bounds, distance, or both.
It is not possible to update an object's filter group.
\param index [in] The object's index
\param bounds [in] The object's updated bounds, or NULL
\param distance [in] The object's updated distance, or NULL
\see PxBpIndex PxBounds3
*/
virtual void updateObject(PxBpIndex index, const PxBounds3* bounds=NULL, const float* distance=NULL) = 0;
/**
\brief Updates the broadphase and computes the lists of created/deleted pairs.
The data necessary for updating the broadphase is internally computed by the AABB manager.
To benefit from potentially multithreaded implementations, it is necessary to provide a continuation
task to the function. It is legal to pass NULL there, but the underlying (CPU) implementations will
then run single-threaded.
\param continuation [in] Continuation task to enable multi-threaded implementations, or NULL.
\see PxBaseTask
*/
virtual void update(PxBaseTask* continuation=NULL) = 0;
/**
\brief Retrieves the broadphase results after an update.
This should be called once after each update call to retrieve the results of the broadphase. The
results are incremental, i.e. the system only returns new and lost pairs, not all current pairs.
\param results [out] The broadphase results
\see PxBroadPhaseResults
*/
virtual void fetchResults(PxBroadPhaseResults& results) = 0;
/**
\brief Helper for single-threaded updates.
This short helper function performs a single-theaded update and reports the results in a single call.
\param results [out] The broadphase results
\see PxBroadPhaseResults
*/
PX_FORCE_INLINE void update(PxBroadPhaseResults& results)
{
update();
fetchResults(results);
}
};
/**
\brief AABB manager factory function.
Use this function to create a new standalone high-level broadphase.
\param broadphase [in] The broadphase that will be managed by the AABB manager
\return Newly created AABB manager, or NULL
\see PxAABBManager PxBroadPhase
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxAABBManager* PxCreateAABBManager(PxBroadPhase& broadphase);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 25,948 | C | 35.754957 | 171 | 0.753931 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleGpu.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_GPU_PARTICLE_SYSTEM_H
#define PX_GPU_PARTICLE_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxParticleSystem.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
@brief Common material properties for particles. See #PxParticleMaterial.
Accessed by either integration or particle-rigid collisions
*/
struct PxsParticleMaterialData
{
PxReal friction; // 4
PxReal damping; // 8
PxReal adhesion; // 12
PxReal gravityScale; // 16
PxReal adhesionRadiusScale; // 20
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#if PX_SUPPORT_GPU_PHYSX
struct float4;
PX_CUDA_CALLABLE inline physx::PxU32 PxGetGroup(physx::PxU32 phase) { return phase & physx::PxParticlePhaseFlag::eParticlePhaseGroupMask; }
PX_CUDA_CALLABLE inline bool PxGetFluid(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseFluid) != 0; }
PX_CUDA_CALLABLE inline bool PxGetSelfCollide(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseSelfCollide) != 0; }
PX_CUDA_CALLABLE inline bool PxGetSelfCollideFilter(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseSelfCollideFilter) != 0; }
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
@brief An iterator class to iterate over the neighbors of a particle during particle system simulation.
*/
class PxNeighborhoodIterator
{
const PxU32* PX_RESTRICT mCollisionIndex; //!< Pointer to the current state of the iterator.
PxU32 mMaxParticles; //!< The maximum number of particles of the particle system this iterator is used on.
public:
PX_CUDA_CALLABLE PxNeighborhoodIterator(const PxU32* PX_RESTRICT collisionIndex, PxU32 maxParticles) :
mCollisionIndex(collisionIndex), mMaxParticles(maxParticles)
{
}
PX_CUDA_CALLABLE PxU32 getNextIndex()
{
PxU32 result = *mCollisionIndex;
mCollisionIndex += mMaxParticles;
return result;
}
PX_INLINE PxNeighborhoodIterator(const PxNeighborhoodIterator& params)
{
mCollisionIndex = params.mCollisionIndex;
mMaxParticles = params.mMaxParticles;
}
PX_INLINE void operator = (const PxNeighborhoodIterator& params)
{
mCollisionIndex = params.mCollisionIndex;
mMaxParticles = params.mMaxParticles;
}
};
/**
@brief Structure that holds simulation parameters of a #PxGpuParticleSystem.
*/
struct PxGpuParticleData
{
PxU32 mGridSizeX; //!< Size of the x-dimension of the background simulation grid. Translates to an absolute size of mGridSizeX * mParticleContactDistance.
PxU32 mGridSizeY; //!< Size of the y-dimension of the background simulation grid. Translates to an absolute size of mGridSizeY * mParticleContactDistance.
PxU32 mGridSizeZ; //!< Size of the z-dimension of the background simulation grid. Translates to an absolute size of mGridSizeZ * mParticleContactDistance.
PxReal mParticleContactDistance; //!< Two particles start interacting if their distance is lower than mParticleContactDistance.
PxReal mParticleContactDistanceInv; //!< 1.f / mParticleContactDistance.
PxReal mParticleContactDistanceSq; //!< mParticleContactDistance * mParticleContactDistance.
PxU32 mNumParticles; //!< The number of particles in this particle system.
PxU32 mMaxParticles; //!< The maximum number of particles that can be simulated in this particle system.
PxU32 mMaxNeighborhood; //!< The maximum number of particles considered when computing neighborhood based particle interactions.
PxU32 mMaxDiffuseParticles; //!< The maximum number of diffuse particles that can be simulated using this particle system.
PxU32 mNumParticleBuffers; //!< The number of particle buffers that are simulated in this particle system.
};
/**
@brief Container class for a GPU particle system. Used to communicate particle system parameters and simulation state
between the internal SDK simulation and the particle system callbacks.
See #PxParticleSystem, #PxParticleSystemCallback.
*/
class PxGpuParticleSystem
{
public:
/**
@brief Returns the number of cells of the background simulation grid.
@return PxU32 the number of cells.
*/
PX_FORCE_INLINE PxU32 getNumCells() { return mCommonData.mGridSizeX * mCommonData.mGridSizeY * mCommonData.mGridSizeZ; }
/* Unsorted particle state buffers */
float4* mUnsortedPositions_InvMass; //!< GPU pointer to unsorted particle positions and inverse masses.
float4* mUnsortedVelocities; //!< GPU pointer to unsorted particle velocities.
PxU32* mUnsortedPhaseArray; //!< GPU pointer to unsorted particle phase array. See #PxParticlePhase.
/* Sorted particle state buffers. Sorted by increasing hash value in background grid. */
float4* mSortedPositions_InvMass; //!< GPU pointer to sorted particle positions
float4* mSortedVelocities; //!< GPU pointer to sorted particle velocities
PxU32* mSortedPhaseArray; //!< GPU pointer to sorted particle phase array
/* Mappings to/from sorted particle states */
PxU32* mUnsortedToSortedMapping; //!< GPU pointer to the mapping from unsortedParticle ID to sorted particle ID
PxU32* mSortedToUnsortedMapping; //!< GPU pointer to the mapping from sorted particle ID to unsorted particle ID
/* Neighborhood information */
PxU32* mParticleSelfCollisionCount; //!< Per-particle neighborhood count
PxU32* mCollisionIndex; //!< Set of sorted particle indices per neighbor
PxsParticleMaterialData* mParticleMaterials; //!< GPU pointer to the particle materials used in this particle system.
PxGpuParticleData mCommonData; //!< Structure holding simulation parameters and state for this particle system. See #PxGpuParticleData.
/**
@brief Get a PxNeighborhoodIterator initialized for usage with this particle system.
@param particleId An initial particle index for the initialization of the iterator.
@return An initialized PxNeighborhoodIterator.
*/
PX_CUDA_CALLABLE PxNeighborhoodIterator getIterator(PxU32 particleId) const
{
return PxNeighborhoodIterator(mCollisionIndex + particleId, mCommonData.mMaxParticles);
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
/** @} */
#endif
| 8,283 | C | 42.371728 | 176 | 0.727756 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysicsSerialization.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_SERIALIZATION_H
#define PX_PHYSICS_SERIALIZATION_H
#include "common/PxSerialFramework.h"
#include "PxPhysXConfig.h"
#if !PX_DOXYGEN
/**
\brief Retrieves the PhysX SDK metadata.
\deprecated Binary conversion and binary meta data are deprecated.
This function is used to implement PxSerialization.dumpBinaryMetaData() and is not intended to be needed otherwise.
@see PxSerialization.dumpBinaryMetaData()
*/
PX_DEPRECATED PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxGetPhysicsBinaryMetaData(physx::PxOutputStream& stream);
/**
\brief Registers physics classes for serialization.
This function is used to implement PxSerialization.createSerializationRegistry() and is not intended to be needed otherwise.
@see PxSerializationRegistry
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxRegisterPhysicsSerializers(physx::PxSerializationRegistry& sr);
/**
\brief Unregisters physics classes for serialization.
This function is used in the release implementation of PxSerializationRegistry and in not intended to be used otherwise.
@see PxSerializationRegistry
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxUnregisterPhysicsSerializers(physx::PxSerializationRegistry& sr);
/**
\brief Adds collected objects to PxPhysics.
This function adds all objects contained in the input collection to the PxPhysics instance. This is used after deserializing
the collection, to populate the physics with inplace deserialized objects. This function is used in the implementation of
PxSerialization.createCollectionFromBinary and is not intended to be needed otherwise.
\param[in] collection Objects to add to the PxPhysics instance.
@see PxCollection, PxSerialization.createCollectionFromBinary
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxAddCollectionToPhysics(const physx::PxCollection& collection);
#endif // !PX_DOXYGEN
#endif
| 3,564 | C | 45.298701 | 124 | 0.792368 |
NVIDIA-Omniverse/PhysX/physx/include/PxSimulationStatistics.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SIMULATION_STATISTICS_H
#define PX_SIMULATION_STATISTICS_H
/** \addtogroup physics
@{
*/
#include "foundation/PxAssert.h"
#include "PxPhysXConfig.h"
#include "geometry/PxGeometry.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Class used to retrieve statistics for a simulation step.
@see PxScene::getSimulationStatistics()
*/
class PxSimulationStatistics
{
public:
/**
\brief Different types of rigid body collision pair statistics.
@see getRbPairStats
*/
enum RbPairStatsType
{
/**
\brief Shape pairs processed as discrete contact pairs for the current simulation step.
*/
eDISCRETE_CONTACT_PAIRS,
/**
\brief Shape pairs processed as swept integration pairs for the current simulation step.
\note Counts the pairs for which special CCD (continuous collision detection) work was actually done and NOT the number of pairs which were configured for CCD.
Furthermore, there can be multiple CCD passes and all processed pairs of all passes are summed up, hence the number can be larger than the amount of pairs which have been configured for CCD.
@see PxPairFlag::eDETECT_CCD_CONTACT,
*/
eCCD_PAIRS,
/**
\brief Shape pairs processed with user contact modification enabled for the current simulation step.
@see PxContactModifyCallback
*/
eMODIFIED_CONTACT_PAIRS,
/**
\brief Trigger shape pairs processed for the current simulation step.
@see PxShapeFlag::eTRIGGER_SHAPE
*/
eTRIGGER_PAIRS
};
//objects:
/**
\brief Number of active PxConstraint objects (joints etc.) for the current simulation step.
*/
PxU32 nbActiveConstraints;
/**
\brief Number of active dynamic bodies for the current simulation step.
\note Does not include active kinematic bodies
*/
PxU32 nbActiveDynamicBodies;
/**
\brief Number of active kinematic bodies for the current simulation step.
\note Kinematic deactivation occurs at the end of the frame after the last call to PxRigidDynamic::setKinematicTarget() was called so kinematics that are
deactivated in a given frame will be included by this counter.
*/
PxU32 nbActiveKinematicBodies;
/**
\brief Number of static bodies for the current simulation step.
*/
PxU32 nbStaticBodies;
/**
\brief Number of dynamic bodies for the current simulation step.
\note Includes inactive bodies and articulation links
\note Does not include kinematic bodies
*/
PxU32 nbDynamicBodies;
/**
\brief Number of kinematic bodies for the current simulation step.
\note Includes inactive bodies
*/
PxU32 nbKinematicBodies;
/**
\brief Number of shapes of each geometry type.
*/
PxU32 nbShapes[PxGeometryType::eGEOMETRY_COUNT];
/**
\brief Number of aggregates in the scene.
*/
PxU32 nbAggregates;
/**
\brief Number of articulations in the scene.
*/
PxU32 nbArticulations;
//solver:
/**
\brief The number of 1D axis constraints(joints+contact) present in the current simulation step.
*/
PxU32 nbAxisSolverConstraints;
/**
\brief The size (in bytes) of the compressed contact stream in the current simulation step
*/
PxU32 compressedContactSize;
/**
\brief The total required size (in bytes) of the contact constraints in the current simulation step
*/
PxU32 requiredContactConstraintMemory;
/**
\brief The peak amount of memory (in bytes) that was allocated for constraints (this includes joints) in the current simulation step
*/
PxU32 peakConstraintMemory;
//broadphase:
/**
\brief Get number of broadphase volumes added for the current simulation step.
\return Number of broadphase volumes added.
*/
PX_FORCE_INLINE PxU32 getNbBroadPhaseAdds() const
{
return nbBroadPhaseAdds;
}
/**
\brief Get number of broadphase volumes removed for the current simulation step.
\return Number of broadphase volumes removed.
*/
PX_FORCE_INLINE PxU32 getNbBroadPhaseRemoves() const
{
return nbBroadPhaseRemoves;
}
//collisions:
/**
\brief Get number of shape collision pairs of a certain type processed for the current simulation step.
There is an entry for each geometry pair type.
\note entry[i][j] = entry[j][i], hence, if you want the sum of all pair
types, you need to discard the symmetric entries
\param[in] pairType The type of pair for which to get information
\param[in] g0 The geometry type of one pair object
\param[in] g1 The geometry type of the other pair object
\return Number of processed pairs of the specified geometry types.
*/
PxU32 getRbPairStats(RbPairStatsType pairType, PxGeometryType::Enum g0, PxGeometryType::Enum g1) const
{
PX_ASSERT_WITH_MESSAGE( (pairType >= eDISCRETE_CONTACT_PAIRS) &&
(pairType <= eTRIGGER_PAIRS),
"Invalid pairType in PxSimulationStatistics::getRbPairStats");
if (g0 >= PxGeometryType::eGEOMETRY_COUNT || g1 >= PxGeometryType::eGEOMETRY_COUNT)
{
PX_ASSERT(false);
return 0;
}
PxU32 nbPairs = 0;
switch(pairType)
{
case eDISCRETE_CONTACT_PAIRS:
nbPairs = nbDiscreteContactPairs[g0][g1];
break;
case eCCD_PAIRS:
nbPairs = nbCCDPairs[g0][g1];
break;
case eMODIFIED_CONTACT_PAIRS:
nbPairs = nbModifiedContactPairs[g0][g1];
break;
case eTRIGGER_PAIRS:
nbPairs = nbTriggerPairs[g0][g1];
break;
}
return nbPairs;
}
/**
\brief Total number of (non CCD) pairs reaching narrow phase
*/
PxU32 nbDiscreteContactPairsTotal;
/**
\brief Total number of (non CCD) pairs for which contacts are successfully cached (<=nbDiscreteContactPairsTotal)
\note This includes pairs for which no contacts are generated, it still counts as a cache hit.
*/
PxU32 nbDiscreteContactPairsWithCacheHits;
/**
\brief Total number of (non CCD) pairs for which at least 1 contact was generated (<=nbDiscreteContactPairsTotal)
*/
PxU32 nbDiscreteContactPairsWithContacts;
/**
\brief Number of new pairs found by BP this frame
*/
PxU32 nbNewPairs;
/**
\brief Number of lost pairs from BP this frame
*/
PxU32 nbLostPairs;
/**
\brief Number of new touches found by NP this frame
*/
PxU32 nbNewTouches;
/**
\brief Number of lost touches from NP this frame
*/
PxU32 nbLostTouches;
/**
\brief Number of partitions used by the solver this frame
*/
PxU32 nbPartitions;
/**
\brief GPU device memory in bytes allocated for particle state accessible through API
*/
PxU64 gpuMemParticles;
/**
\brief GPU device memory in bytes allocated for FEM-based soft body state accessible through API
*/
PxU64 gpuMemSoftBodies;
/**
\brief GPU device memory in bytes allocated for FEM-based cloth state accessible through API
*/
PxU64 gpuMemFEMCloths;
/**
\brief GPU device memory in bytes allocated for hairsystem state accessible through API
*/
PxU64 gpuMemHairSystems;
/**
\brief GPU device memory in bytes allocated for internal heap allocation
*/
PxU64 gpuMemHeap;
/**
\brief GPU device heap memory used for broad phase in bytes
*/
PxU64 gpuMemHeapBroadPhase;
/**
\brief GPU device heap memory used for narrow phase in bytes
*/
PxU64 gpuMemHeapNarrowPhase;
/**
\brief GPU device heap memory used for solver in bytes
*/
PxU64 gpuMemHeapSolver;
/**
\brief GPU device heap memory used for articulations in bytes
*/
PxU64 gpuMemHeapArticulation;
/**
\brief GPU device heap memory used for simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulation;
/**
\brief GPU device heap memory used for articulations in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationArticulation;
/**
\brief GPU device heap memory used for particles in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationParticles;
/**
\brief GPU device heap memory used for soft bodies in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationSoftBody;
/**
\brief GPU device heap memory used for FEM-cloth in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationFEMCloth;
/**
\brief GPU device heap memory used for hairsystem in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationHairSystem;
/**
\brief GPU device heap memory used for shared buffers in the particles pipeline in bytes
*/
PxU64 gpuMemHeapParticles;
/**
\brief GPU device heap memory used for shared buffers in the FEM-based soft body pipeline in bytes
*/
PxU64 gpuMemHeapSoftBodies;
/**
\brief GPU device heap memory used for shared buffers in the FEM-based cloth pipeline in bytes
*/
PxU64 gpuMemHeapFEMCloths;
/**
\brief GPU device heap memory used for shared buffers in the hairsystem pipeline in bytes
*/
PxU64 gpuMemHeapHairSystems;
/**
\brief GPU device heap memory not covered by other stats in bytes
*/
PxU64 gpuMemHeapOther;
PxSimulationStatistics() :
nbActiveConstraints (0),
nbActiveDynamicBodies (0),
nbActiveKinematicBodies (0),
nbStaticBodies (0),
nbDynamicBodies (0),
nbKinematicBodies (0),
nbAggregates (0),
nbArticulations (0),
nbAxisSolverConstraints (0),
compressedContactSize (0),
requiredContactConstraintMemory (0),
peakConstraintMemory (0),
nbDiscreteContactPairsTotal (0),
nbDiscreteContactPairsWithCacheHits (0),
nbDiscreteContactPairsWithContacts (0),
nbNewPairs (0),
nbLostPairs (0),
nbNewTouches (0),
nbLostTouches (0),
nbPartitions (0),
gpuMemParticles (0),
gpuMemSoftBodies (0),
gpuMemFEMCloths (0),
gpuMemHairSystems (0),
gpuMemHeap (0),
gpuMemHeapBroadPhase (0),
gpuMemHeapNarrowPhase (0),
gpuMemHeapSolver (0),
gpuMemHeapArticulation (0),
gpuMemHeapSimulation (0),
gpuMemHeapSimulationArticulation (0),
gpuMemHeapSimulationParticles (0),
gpuMemHeapSimulationSoftBody (0),
gpuMemHeapSimulationFEMCloth (0),
gpuMemHeapSimulationHairSystem (0),
gpuMemHeapParticles (0),
gpuMemHeapSoftBodies (0),
gpuMemHeapFEMCloths (0),
gpuMemHeapHairSystems (0),
gpuMemHeapOther (0)
{
nbBroadPhaseAdds = 0;
nbBroadPhaseRemoves = 0;
for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++)
{
for(PxU32 j=0; j < PxGeometryType::eGEOMETRY_COUNT; j++)
{
nbDiscreteContactPairs[i][j] = 0;
nbModifiedContactPairs[i][j] = 0;
nbCCDPairs[i][j] = 0;
nbTriggerPairs[i][j] = 0;
}
}
for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++)
{
nbShapes[i] = 0;
}
}
//
// We advise to not access these members directly. Use the provided accessor methods instead.
//
//broadphase:
PxU32 nbBroadPhaseAdds;
PxU32 nbBroadPhaseRemoves;
//collisions:
PxU32 nbDiscreteContactPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 nbCCDPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 nbModifiedContactPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 nbTriggerPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 12,687 | C | 26.703057 | 192 | 0.733901 |
NVIDIA-Omniverse/PhysX/physx/include/PxBaseMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_BASE_MATERIAL_H
#define PX_BASE_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Base material class.
@see PxPhysics.createMaterial PxPhysics.createFEMClothMaterial PxPhysics.createFEMSoftBodyMaterial PxPhysics.createFLIPMaterial PxPhysics.createMPMMaterial PxPhysics.createPBDMaterial
*/
class PxBaseMaterial : public PxRefCounted
{
public:
PX_INLINE PxBaseMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxBaseMaterial(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxBaseMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBaseMaterial", PxRefCounted); }
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,698 | C | 40.523076 | 184 | 0.760193 |
NVIDIA-Omniverse/PhysX/physx/include/PxSDFBuilder.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SDF_BUILDER_H
#define PX_SDF_BUILDER_H
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "foundation/PxArray.h"
#include "cooking/PxSDFDesc.h"
#include "cudamanager/PxCudaTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Utility class to compute an SDF on the GPU
*/
class PxSDFBuilder
{
public:
/**
\brief Constructs a dense grid SDF for a triangle mesh using the GPU
\param[in] vertices The vertices of the triangle mesh
\param[in] numVertices The number of vertices
\param[in] indices The triangle indices
\param[in] numTriangleIndices The number of triangle indices
\param[in] width The number of samples along the x direction of the resulting SDF volume
\param[in] height The number of samples along the y direction of the resulting SDF volume
\param[in] depth The number of samples along the z direction of the resulting SDF volume
\param[in] minExtents The minimum corner location of the axis aligned box containing the SDF samples.
\param[in] maxExtents The maximum corner location of the axis aligned box containing the SDF samples.
\param[in] cellCenteredSamples Determines if the sample points are located at the center of a SDF cell or at the lower left (=min) corner of a cell.
\param[out] sdf The distance values. Must provide space for width*height*depth distance samples. Negative distance means the sample point is located inside of the triangle mesh.
\param[in] stream The cuda stream on which the conversion is processed. If the default stream (0) is used, a temporary stream will be created internally.
*/
virtual void buildSDF(const PxVec3* vertices, PxU32 numVertices, const PxU32* indices, PxU32 numTriangleIndices, PxU32 width, PxU32 height, PxU32 depth,
const PxVec3& minExtents, const PxVec3& maxExtents, bool cellCenteredSamples, PxReal* sdf, CUstream stream = 0) = 0;
/**
\brief Constructs a sparse grid SDF for a triangle mesh using the GPU
\param[in] vertices The vertices of the triangle mesh
\param[in] numVertices The number of vertices
\param[in] indices The triangle indices
\param[in] numTriangleIndices The number of triangle indices
\param[in] width The number of samples along the x direction of the resulting SDF volume
\param[in] height The number of samples along the y direction of the resulting SDF volume
\param[in] depth The number of samples along the z direction of the resulting SDF volume
\param[in] minExtents The minimum corner location of the axis aligned box containing the SDF samples.
\param[in] maxExtents The maximum corner location of the axis aligned box containing the SDF samples.
\param[in] narrowBandThickness The thickness of the narrow band.
\param[in] cellsPerSubgrid The number of cells in a sparse subgrid block (full block has mSubgridSize^3 cells and (mSubgridSize+1)^3 samples)
\param[in] bitsPerSubgridPixel Subgrid pixel compression
\param[out] subgridsMinSdfValue Used to store the minimum sdf value over all subgrids
\param[out] subgridsMaxSdfValue Used to store the maximum sdf value over all subgrids
\param[out] sdfSubgrids3DTexBlockDimX Used to store x dimension of the texture block that stores the subgrids
\param[out] sdfSubgrids3DTexBlockDimY Used to store y dimension of the texture block that stores the subgrids
\param[out] sdfSubgrids3DTexBlockDimZ Used to store z dimension of the texture block that stores the subgrids
\param[in] stream The cuda stream on which the conversion is processed. If the default stream (0) is used, a temporary stream will be created internally.
*/
virtual void buildSparseSDF(const PxVec3* vertices, PxU32 numVertices, const PxU32* indices, PxU32 numTriangleIndices, PxU32 width, PxU32 height, PxU32 depth,
const PxVec3& minExtents, const PxVec3& maxExtents, PxReal narrowBandThickness, PxU32 cellsPerSubgrid, PxSdfBitsPerSubgridPixel::Enum bitsPerSubgridPixel,
PxArray<PxReal>& sdfCoarse, PxArray<PxU32>& sdfSubgridsStartSlots, PxArray<PxU8>& sdfDataSubgrids,
PxReal& subgridsMinSdfValue, PxReal& subgridsMaxSdfValue,
PxU32& sdfSubgrids3DTexBlockDimX, PxU32& sdfSubgrids3DTexBlockDimY, PxU32& sdfSubgrids3DTexBlockDimZ, CUstream stream = 0) = 0;
/**
\brief Releases the memory including the this pointer
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxSDFBuilder() { }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 6,167 | C | 53.105263 | 178 | 0.781417 |
NVIDIA-Omniverse/PhysX/physx/include/PxLockedData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_LOCKED_DATA_H
#define PX_LOCKED_DATA_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxDataAccessFlag
{
enum Enum
{
eREADABLE = (1 << 0),
eWRITABLE = (1 << 1),
eDEVICE = (1 << 2)
};
};
/**
\brief collection of set bits defined in PxDataAccessFlag.
@see PxDataAccessFlag
*/
typedef PxFlags<PxDataAccessFlag::Enum,PxU8> PxDataAccessFlags;
PX_FLAGS_OPERATORS(PxDataAccessFlag::Enum,PxU8)
/**
\brief Parent class for bulk data that is shared between the SDK and the application.
*/
class PxLockedData
{
public:
/**
\brief Any combination of PxDataAccessFlag::eREADABLE and PxDataAccessFlag::eWRITABLE
@see PxDataAccessFlag
*/
virtual PxDataAccessFlags getDataAccessFlags() = 0;
/**
\brief Unlocks the bulk data.
*/
virtual void unlock() = 0;
/**
\brief virtual destructor
*/
virtual ~PxLockedData() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,706 | C | 28.423913 | 86 | 0.739468 |
NVIDIA-Omniverse/PhysX/physx/include/PxMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_MATERIAL_H
#define PX_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxBaseMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxScene;
/**
\brief Flags which control the behavior of a material.
@see PxMaterial
*/
struct PxMaterialFlag
{
enum Enum
{
/**
\brief If this flag is set, friction computations are always skipped between shapes with this material and any other shape.
*/
eDISABLE_FRICTION = 1 << 0,
/**
\brief Whether to use strong friction.
The difference between "normal" and "strong" friction is that the strong friction feature
remembers the "friction error" between simulation steps. The friction is a force trying to
hold objects in place (or slow them down) and this is handled in the solver. But since the
solver is only an approximation, the result of the friction calculation can include a small
"error" - e.g. a box resting on a slope should not move at all if the static friction is in
action, but could slowly glide down the slope because of a small friction error in each
simulation step. The strong friction counter-acts this by remembering the small error and
taking it to account during the next simulation step.
However, in some cases the strong friction could cause problems, and this is why it is
possible to disable the strong friction feature by setting this flag. One example is
raycast vehicles that are sliding fast across the surface, but still need a precise
steering behavior. It may be a good idea to reenable the strong friction when objects
are coming to a rest, to prevent them from slowly creeping down inclines.
Note: This flag only has an effect if the PxMaterialFlag::eDISABLE_FRICTION bit is 0.
*/
eDISABLE_STRONG_FRICTION = 1 << 1,
/**
\brief Whether to correct the friction force applied by the patch friction model to better match analytical models.
This flag only has an effect if the PxFrictionType::ePATCH friction model is used.
When using the patch friction model, up to two friction anchors are generated per patch. The normal force of all contacts
in the patch is accumulated and equally distributed among the anchors in order to compute friction forces. If this flag
is disabled, the legacy behavior is active which produces double the expected friction force in the case of two anchors,
since the full accumulated normal force is used in both anchors for the friction computation.
*/
eIMPROVED_PATCH_FRICTION = 1 << 2,
/**
\brief This flag has the effect of enabling an implicit spring model for the normal force computation.
@see PxMaterial.setRestitution, PxMaterial.setDamping
*/
eCOMPLIANT_CONTACT = 1 << 3
};
};
/**
\brief collection of set bits defined in PxMaterialFlag.
@see PxMaterialFlag
*/
typedef PxFlags<PxMaterialFlag::Enum,PxU16> PxMaterialFlags;
PX_FLAGS_OPERATORS(PxMaterialFlag::Enum,PxU16)
/**
\brief Enumeration that determines the way in which two material properties will be combined to yield a friction or restitution coefficient for a collision.
When two actors come in contact with each other, they each have materials with various coefficients, but we only need a single set of coefficients for the pair.
Physics doesn't have any inherent combinations because the coefficients are determined empirically on a case by case
basis. However, simulating this with a pairwise lookup table is often impractical.
For this reason the following combine behaviors are available:
eAVERAGE
eMIN
eMULTIPLY
eMAX
The effective combine mode for the pair is maximum(material0.combineMode, material1.combineMode).
@see PxMaterial.setFrictionCombineMode() PxMaterial.getFrictionCombineMode() PxMaterial.setRestitutionCombineMode() PxMaterial.getFrictionCombineMode()
*/
struct PxCombineMode
{
enum Enum
{
eAVERAGE = 0, //!< Average: (a + b)/2
eMIN = 1, //!< Minimum: minimum(a,b)
eMULTIPLY = 2, //!< Multiply: a*b
eMAX = 3, //!< Maximum: maximum(a,b)
eN_VALUES = 4, //!< This is not a valid combine mode, it is a sentinel to denote the number of possible values. We assert that the variable's value is smaller than this.
ePAD_32 = 0x7fffffff //!< This is not a valid combine mode, it is to assure that the size of the enum type is big enough.
};
};
/**
\brief Material class to represent a set of surface properties.
@see PxPhysics.createMaterial
*/
class PxMaterial : public PxBaseMaterial
{
public:
/**
\brief Sets the coefficient of dynamic friction.
The coefficient of dynamic friction should be in [0, PX_MAX_F32). If set to greater than staticFriction, the effective value of staticFriction will be increased to match.
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] coef Coefficient of dynamic friction. <b>Range:</b> [0, PX_MAX_F32)
@see getDynamicFriction()
*/
virtual void setDynamicFriction(PxReal coef) = 0;
/**
\brief Retrieves the DynamicFriction value.
\return The coefficient of dynamic friction.
@see setDynamicFriction
*/
virtual PxReal getDynamicFriction() const = 0;
/**
\brief Sets the coefficient of static friction
The coefficient of static friction should be in the range [0, PX_MAX_F32)
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] coef Coefficient of static friction. <b>Range:</b> [0, PX_MAX_F32)
@see getStaticFriction()
*/
virtual void setStaticFriction(PxReal coef) = 0;
/**
\brief Retrieves the coefficient of static friction.
\return The coefficient of static friction.
@see setStaticFriction
*/
virtual PxReal getStaticFriction() const = 0;
/**
\brief Sets the coefficient of restitution
A coefficient of 0 makes the object bounce as little as possible, higher values up to 1.0 result in more bounce.
This property is overloaded when PxMaterialFlag::eCOMPLIANT_CONTACT flag is enabled. This permits negative values for restitution to be provided.
The negative values are converted into spring stiffness terms for an implicit spring simulated at the contact site, with the spring positional error defined by
the contact separation value. Higher stiffness terms produce stiffer springs that behave more like a rigid contact.
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] rest Coefficient of restitution. <b>Range:</b> [-INF,1]
@see getRestitution()
*/
virtual void setRestitution(PxReal rest) = 0;
/**
\brief Retrieves the coefficient of restitution.
See #setRestitution.
\return The coefficient of restitution.
@see setRestitution()
*/
virtual PxReal getRestitution() const = 0;
/**
\brief Sets the coefficient of damping
This property only affects the simulation if PxMaterialFlag::eCOMPLIANT_CONTACT is raised.
Damping works together with spring stiffness (set through a negative restitution value). Spring stiffness corrects positional error while
damping resists relative velocity. Setting a high damping coefficient can produce spongy contacts.
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] damping Coefficient of damping. <b>Range:</b> [0,INF]
@see getDamping()
*/
virtual void setDamping(PxReal damping) = 0;
/**
\brief Retrieves the coefficient of damping.
See #setDamping.
\return The coefficient of damping.
@see setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Raises or clears a particular material flag.
See the list of flags #PxMaterialFlag
<b>Default:</b> eIMPROVED_PATCH_FRICTION
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] flag The PxMaterial flag to raise(set) or clear.
\param[in] b New state of the flag
@see getFlags() setFlags() PxMaterialFlag
*/
virtual void setFlag(PxMaterialFlag::Enum flag, bool b) = 0;
/**
\brief sets all the material flags.
See the list of flags #PxMaterialFlag
<b>Default:</b> eIMPROVED_PATCH_FRICTION
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] flags All PxMaterial flags
@see getFlags() setFlag() PxMaterialFlag
*/
virtual void setFlags(PxMaterialFlags flags) = 0;
/**
\brief Retrieves the flags. See #PxMaterialFlag.
\return The material flags.
@see PxMaterialFlag setFlags()
*/
virtual PxMaterialFlags getFlags() const = 0;
/**
\brief Sets the friction combine mode.
See the enum ::PxCombineMode .
<b>Default:</b> PxCombineMode::eAVERAGE
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] combMode Friction combine mode to set for this material. See #PxCombineMode.
@see PxCombineMode getFrictionCombineMode setStaticFriction() setDynamicFriction()
*/
virtual void setFrictionCombineMode(PxCombineMode::Enum combMode) = 0;
/**
\brief Retrieves the friction combine mode.
See #setFrictionCombineMode.
\return The friction combine mode for this material.
@see PxCombineMode setFrictionCombineMode()
*/
virtual PxCombineMode::Enum getFrictionCombineMode() const = 0;
/**
\brief Sets the restitution combine mode.
See the enum ::PxCombineMode .
<b>Default:</b> PxCombineMode::eAVERAGE
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] combMode Restitution combine mode for this material. See #PxCombineMode.
@see PxCombineMode getRestitutionCombineMode() setRestitution()
*/
virtual void setRestitutionCombineMode(PxCombineMode::Enum combMode) = 0;
/**
\brief Retrieves the restitution combine mode.
See #setRestitutionCombineMode.
\return The coefficient of restitution combine mode for this material.
@see PxCombineMode setRestitutionCombineMode getRestitution()
*/
virtual PxCombineMode::Enum getRestitutionCombineMode() const = 0;
// PxBase
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxMaterial"; }
//~PxBase
protected:
PX_INLINE PxMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {}
PX_INLINE PxMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {}
virtual ~PxMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxMaterial", PxBaseMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 11,967 | C | 32.80791 | 172 | 0.751734 |
NVIDIA-Omniverse/PhysX/physx/include/PxFEMClothFlags.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_FEM_CLOTH_FLAGS_H
#define PX_PHYSICS_FEM_CLOTH_FLAGS_H
#include "foundation/PxFlags.h"
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Identifies input and output buffers for PxFEMCloth.
*/
struct PxFEMClothDataFlag
{
enum Enum
{
eNONE = 0,
ePOSITION_INVMASS = 1 << 0,
eVELOCITY = 1 << 1,
eREST_POSITION = 1 << 2,
eALL = ePOSITION_INVMASS | eVELOCITY | eREST_POSITION
};
};
typedef PxFlags<PxFEMClothDataFlag::Enum, PxU32> PxFEMClothDataFlags;
struct PxFEMClothFlag
{
enum Enum
{
eDISABLE_SELF_COLLISION = 1 << 0,
eUSE_ANISOTROPIC_CLOTH = 1 << 1, // 0: use isotropic model, 1: use anistropic model
eENABLE_FLATTENING = 1 << 2 // 0: query rest bending angle from rest shape, 1: use zero rest bending angle
};
};
typedef PxFlags<PxFEMClothFlag::Enum, PxU32> PxFEMClothFlags;
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 2,624 | C | 34 | 112 | 0.744284 |
NVIDIA-Omniverse/PhysX/physx/include/PxHairSystemFlag.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_HAIR_SYSTEM_FLAG_H
#define PX_HAIR_SYSTEM_FLAG_H
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Identifies input and output buffers for PxHairSystem
*/
struct PxHairSystemData
{
enum Enum
{
eNONE = 0, //!< No data specified
ePOSITION_INVMASS = 1 << 0, //!< Specifies the position (first 3 floats) and inverse mass (last float) data (array of PxVec4 * max number of vertices)
eVELOCITY = 1 << 1, //!< Specifies the velocity (first 3 floats) data (array of PxVec4 * max number of vertices)
eALL = ePOSITION_INVMASS | eVELOCITY //!< Specifies everything
};
};
typedef PxFlags<PxHairSystemData::Enum, PxU32> PxHairSystemDataFlags;
/**
\brief Binary settings for hair system simulation
*/
struct PxHairSystemFlag
{
enum Enum
{
eDISABLE_SELF_COLLISION = 1 << 0, //!< Determines if self-collision between hair vertices is ignored
eDISABLE_EXTERNAL_COLLISION = 1 << 1, //!< Determines if collision between hair and external bodies is ignored
eDISABLE_TWOSIDED_ATTACHMENT = 1 << 2 //!< Determines if attachment constraint is also felt by body to which the hair is attached
};
};
typedef PxFlags<PxHairSystemFlag::Enum, PxU32> PxHairSystemFlags;
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,044 | C | 40.148648 | 160 | 0.737516 |
NVIDIA-Omniverse/PhysX/physx/include/PxClient.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_CLIENT_H
#define PX_CLIENT_H
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief An ID to identify different clients for multiclient support.
@see PxScene::createClient()
*/
typedef PxU8 PxClientID;
/**
\brief The predefined default PxClientID value.
@see PxClientID PxScene::createClient()
*/
static const PxClientID PX_DEFAULT_CLIENT = 0;
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 2,143 | C | 35.965517 | 74 | 0.760149 |
NVIDIA-Omniverse/PhysX/physx/include/PxActor.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ACTOR_H
#define PX_ACTOR_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxBounds3.h"
#include "PxClient.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxRigidActor;
class PxRigidBody;
class PxRigidStatic;
class PxRigidDynamic;
class PxArticulationLink;
class PxScene;
/**
\brief Group index which allows to specify 1- or 2-way interaction
*/
typedef PxU8 PxDominanceGroup; // Must be < 32, PxU8.
/**
\brief Flags which control the behavior of an actor.
@see PxActorFlags PxActor PxActor.setActorFlag() PxActor.getActorFlags()
*/
struct PxActorFlag
{
enum Enum
{
/**
\brief Enable debug renderer for this actor
@see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter
*/
eVISUALIZATION = (1<<0),
/**
\brief Disables scene gravity for this actor
*/
eDISABLE_GRAVITY = (1<<1),
/**
\brief Enables the sending of PxSimulationEventCallback::onWake() and PxSimulationEventCallback::onSleep() notify events
@see PxSimulationEventCallback::onWake() PxSimulationEventCallback::onSleep()
*/
eSEND_SLEEP_NOTIFIES = (1<<2),
/**
\brief Disables simulation for the actor.
\note This is only supported by PxRigidStatic and PxRigidDynamic actors and can be used to reduce the memory footprint when rigid actors are
used for scene queries only.
\note Setting this flag will remove all constraints attached to the actor from the scene.
\note If this flag is set, the following calls are forbidden:
\li PxRigidBody: setLinearVelocity(), setAngularVelocity(), addForce(), addTorque(), clearForce(), clearTorque(), setForceAndTorque()
\li PxRigidDynamic: setKinematicTarget(), setWakeCounter(), wakeUp(), putToSleep()
\par <b>Sleeping:</b>
Raising this flag will set all velocities and the wake counter to 0, clear all forces, clear the kinematic target, put the actor
to sleep and wake up all touching actors from the previous frame.
*/
eDISABLE_SIMULATION = (1<<3)
};
};
/**
\brief collection of set bits defined in PxActorFlag.
@see PxActorFlag
*/
typedef PxFlags<PxActorFlag::Enum,PxU8> PxActorFlags;
PX_FLAGS_OPERATORS(PxActorFlag::Enum,PxU8)
/**
\brief Identifies each type of actor.
@see PxActor
*/
struct PxActorType
{
enum Enum
{
/**
\brief A static rigid body
@see PxRigidStatic
*/
eRIGID_STATIC,
/**
\brief A dynamic rigid body
@see PxRigidDynamic
*/
eRIGID_DYNAMIC,
/**
\brief An articulation link
@see PxArticulationLink
*/
eARTICULATION_LINK,
/**
\brief A FEM-based soft body
@see PxSoftBody
*/
eSOFTBODY,
/**
\brief A FEM-based cloth
\note In development
@see PxFEMCloth
*/
eFEMCLOTH,
/**
\brief A PBD ParticleSystem
@see PxPBDParticleSystem
*/
ePBD_PARTICLESYSTEM,
/**
\brief A FLIP ParticleSystem
\note In development
@see PxFLIPParticleSystem
*/
eFLIP_PARTICLESYSTEM,
/**
\brief A MPM ParticleSystem
\note In development
@see PxMPMParticleSystem
*/
eMPM_PARTICLESYSTEM,
/**
\brief A HairSystem
\note In development
@see PxHairSystem
*/
eHAIRSYSTEM,
//! \brief internal use only!
eACTOR_COUNT,
//! \brief internal use only!
eACTOR_FORCE_DWORD = 0x7fffffff
};
};
/**
\brief PxActor is the base class for the main simulation objects in the physics SDK.
The actor is owned by and contained in a PxScene.
*/
class PxActor : public PxBase
{
public:
/**
\brief Deletes the actor.
Do not keep a reference to the deleted instance.
If the actor belongs to a #PxAggregate object, it is automatically removed from the aggregate.
@see PxBase.release(), PxAggregate
*/
virtual void release() = 0;
/**
\brief Retrieves the type of actor.
\return The actor type of the actor.
@see PxActorType
*/
virtual PxActorType::Enum getType() const = 0;
/**
\brief Retrieves the scene which this actor belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() const = 0;
// Runtime modifications
/**
\brief Sets a name string for the object that can be retrieved with getName().
This is for debugging and is not used by the SDK. The string is not copied by the SDK,
only the pointer is stored.
\param[in] name String to set the objects name to.
<b>Default:</b> NULL
@see getName()
*/
virtual void setName(const char* name) = 0;
/**
\brief Retrieves the name string set with setName().
\return Name string associated with object.
@see setName()
*/
virtual const char* getName() const = 0;
/**
\brief Retrieves the axis aligned bounding box enclosing the actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value.
\return The actor's bounding box.
@see PxBounds3
*/
virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0;
/**
\brief Raises or clears a particular actor flag.
See the list of flags #PxActorFlag
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] flag The PxActor flag to raise(set) or clear. See #PxActorFlag.
\param[in] value The boolean value to assign to the flag.
@see PxActorFlag getActorFlags()
*/
virtual void setActorFlag(PxActorFlag::Enum flag, bool value) = 0;
/**
\brief Sets the actor flags.
See the list of flags #PxActorFlag
@see PxActorFlag setActorFlag()
*/
virtual void setActorFlags( PxActorFlags inFlags ) = 0;
/**
\brief Reads the PxActor flags.
See the list of flags #PxActorFlag
\return The values of the PxActor flags.
@see PxActorFlag setActorFlag()
*/
virtual PxActorFlags getActorFlags() const = 0;
/**
\brief Assigns dynamic actors a dominance group identifier.
PxDominanceGroup is a 5 bit group identifier (legal range from 0 to 31).
The PxScene::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups.
By default every dynamic actor is created in group 0.
<b>Default:</b> 0
<b>Sleeping:</b> Changing the dominance group does <b>NOT</b> wake the actor up automatically.
\param[in] dominanceGroup The dominance group identifier. <b>Range:</b> [0..31]
@see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) = 0;
/**
\brief Retrieves the value set with setDominanceGroup().
\return The dominance group of this actor.
@see setDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
virtual PxDominanceGroup getDominanceGroup() const = 0;
/**
\brief Sets the owner client of an actor.
This cannot be done once the actor has been placed into a scene.
<b>Default:</b> PX_DEFAULT_CLIENT
@see PxClientID PxScene::createClient()
*/
virtual void setOwnerClient( PxClientID inClient ) = 0;
/**
\brief Returns the owner client that was specified at creation time.
This value cannot be changed once the object is placed into the scene.
@see PxClientID PxScene::createClient()
*/
virtual PxClientID getOwnerClient() const = 0;
/**
\brief Retrieves the aggregate the actor might be a part of.
\return The aggregate the actor is a part of, or NULL if the actor does not belong to an aggregate.
@see PxAggregate
*/
virtual PxAggregate* getAggregate() const = 0;
//public variables:
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxActor(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxActor(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxActor() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxActor", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,734 | C | 25.169355 | 142 | 0.725293 |
NVIDIA-Omniverse/PhysX/physx/include/PxSoftBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SOFT_BODY_H
#define PX_SOFT_BODY_H
/** \addtogroup physics
@{ */
#include "PxFEMParameter.h"
#include "PxActor.h"
#include "PxConeLimitedConstraint.h"
#include "PxSoftBodyFlag.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
class PxCudaContextManager;
class PxTetrahedronMesh;
class PxSoftBodyAuxData;
class PxFEMCloth;
class PxParticleBuffer;
/**
\brief The maximum tetrahedron index supported in the model.
*/
#define PX_MAX_TETID 0x000fffff
/**
\brief Flags to enable or disable special modes of a SoftBody
*/
struct PxSoftBodyFlag
{
enum Enum
{
eDISABLE_SELF_COLLISION = 1 << 0, //!< Determines if self collision will be detected and resolved
eCOMPUTE_STRESS_TENSOR = 1 << 1, //!< Enables computation of a Cauchy stress tensor for every tetrahedron in the simulation mesh. The tensors can be accessed through the softbody direct API
eENABLE_CCD = 1 << 2, //!< Enables support for continuous collision detection
eDISPLAY_SIM_MESH = 1 << 3, //!< Enable debug rendering to display the simulation mesh
eKINEMATIC = 1 << 4, //!< Enables support for kinematic motion of the collision and simulation mesh.
ePARTIALLY_KINEMATIC = 1 << 5 //!< Enables partially kinematic motion of the collision and simulation mesh.
};
};
typedef PxFlags<PxSoftBodyFlag::Enum, PxU32> PxSoftBodyFlags;
/**
\brief Represents a FEM softbody including everything to calculate its definition like geometry and material properties
*/
class PxSoftBody : public PxActor
{
public:
virtual ~PxSoftBody() {}
/**
\brief Set a single softbody flag
\param[in] flag The flag to set or clear
\param[in] val The new state of the flag
*/
virtual void setSoftBodyFlag(PxSoftBodyFlag::Enum flag, bool val) = 0;
/**
\brief Set the softbody flags
\param[in] flags The new softbody flags
*/
virtual void setSoftBodyFlags(PxSoftBodyFlags flags) = 0;
/**
\brief Get the softbody flags
\return The softbody flags
*/
virtual PxSoftBodyFlags getSoftBodyFlag() const = 0;
/**
\brief Set parameter for FEM internal solve
\param[in] parameters The FEM parameters
*/
virtual void setParameter(PxFEMParameters parameters) = 0;
/**
\brief Get parameter for FEM internal solve
\return The FEM parameters
*/
virtual PxFEMParameters getParameter() const = 0;
/**
\brief Get a pointer to a device buffer containing positions and inverse masses of the
collision mesh.
This function returns a pointer to device memory for the positions and inverse masses of
the soft body. This buffer is used to both initialize/update the collision mesh vertices
of the soft body and read the simulation results.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::ePOSITION_INVMASS
when updating data in this buffer.
The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary.
The first 3 floats specify the vertex position and the last float contains the inverse mass of the
vertex. The size of the buffer is the number of vertices of the collision mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a shape is attached to the
softbody. Calling PxSoftBody::detachShape() will deallocate the memory.
It is not allowed to write to this buffer from the start of the PxScene::simulate() call
until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks
have finished, reading the data during a completion task is explicitly allowed. The
simulation will read and write directly from/into this buffer.
It is the users' responsibility to initialize this buffer with the initial positions of
the vertices of the collision mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing positions and inverse masses of
the collision mesh.
*/
virtual PxVec4* getPositionInvMassBufferD() = 0;
/**
\brief Get a pointer to a device buffer containing rest positions of the collision mesh vertices.
This function returns a pointer to device memory for the rest positions of the softbody collision
mesh. This buffer is used to initialize the rest positions of the collision mesh vertices.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::eREST_POSITION when
updating data in this buffer.
The simulation expects 4 floats per vertex, aligned to a 16B boundary. The first 3 specify the
rest position. The last float is unused. The size of the buffer is the number of vertices in
the collision mesh * sizeof(PxVec4). @see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a shape is attached to the softbody.
Calling PxSoftBody::detachShape() will deallocate the memory.
It is not allowed to write data into this buffer from the start of PxScene::simulate() until
PxScene::fetchResults() returns.
It is the users' responsibility to initialize this buffer with the initial rest positions of the
vertices of the collision mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing the rest positions of the collision mesh.
*/
virtual PxVec4* getRestPositionBufferD() = 0;
/**
\brief Get a pointer to a device buffer containing the vertex positions of the simulation mesh.
This function returns a pointer to device memory for the positions and inverse masses of the softbody
simulation mesh. This buffer is used to both initialize/update the simulation mesh vertices
of the softbody and read the simulation results.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::eSIM_POSITION_INVMASS when
updating data in this buffer.
The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The
first 3 floats specify the positions and the last float specifies the inverse mass of the vertex.
The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a simulation mesh is attached to the
softbody. Calling PxSoftBody::detachSimulationMesh() will deallocate the memory.
It is not allowed to write to this buffer from the start of the PxScene::simulate() call
until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks
have finished, reading the data during a completion task is explicitly allowed. The
simulation will read and write directly from/into this buffer.
It is the users' responsibility to initialize this buffer with the initial positions of
the vertices of the simulation mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing the vertex positions of the simulation mesh.
*/
virtual PxVec4* getSimPositionInvMassBufferD() = 0;
/**
\brief Get a pointer to a device buffer containing the vertex velocities of the simulation mesh.
This function returns a pointer to device memory for the velocities of the softbody simulation mesh
vertices. This buffer is used to both initialize/update the simulation mesh vertex velocities
of the soft body and read the simulation results.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::eSIM_VELOCITY when
updating data in this buffer.
The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The
first 3 specify the velocities for each vertex. The final float is unused. The size of the
buffer is the number of vertices of the simulation mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a simulation mesh is attached to the
softbody. Calling PxSoftBody::detachSimulationMesh() will deallocate the memory.
It is not allowed to write to this buffer from the start of the PxScene::simulate() call
until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks
have finished, reading the data during a completion task is explicitly allowed. The
simulation will read and write directly from/into this buffer.
It is the users' responsibility to initialize this buffer with the initial velocities of
the vertices of the simulation mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing the vertex velocities of the simulation mesh.
*/
virtual PxVec4* getSimVelocityBufferD() = 0;
/**
\brief Marks per-vertex simulation state and configuration buffers dirty to signal to the simulation
that changes have been made.
Calling this function is mandatory to notify the simulation of changes made in the positionInvMass,
simPositionInvMass, simVelocity and rest position buffers.
This function can be called multiple times, and dirty flags are accumulated internally until
PxScene::simulate() is called.
@see getPositionInvMassBufferD, getSimVelocityBufferD, getRestPositionBufferD, getSimPositionInvMassBufferD
\param flags The buffers that have been updated.
*/
virtual void markDirty(PxSoftBodyDataFlags flags) = 0;
/**
\brief Set the device buffer containing the kinematic targets for this softbody.
This function sets the kinematic targets for a softbody to a user-provided device buffer. This buffer is
read by the simulation to obtain the target position for each vertex of the simulation mesh.
The simulation expects 4 consecutive float for each vertex, aligned to a 16B boundary. The first 3
floats specify the target positions. The last float determines (together with the flag argument)
if the target is active or not.
For a softbody with the flag PxSoftBodyFlag::eKINEMATIC raised, all target positions are considered
valid. In case a softbody has the PxSoftBodyFlag::ePARTIALLY_KINEMATIC raised, only target
positions whose corresponding last float has been set to 0.f are considered valid target positions.
@see PxConfigureSoftBodyKinematicTarget
The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
It is the users responsibility to manage the memory pointed to by the input to this function,
as well as guaranteeing the integrity of the input data. In particular, this means that it is
not allowed to write this data from from the start of PxScene::simulate() until PxScene::fetchResults()
returns. The memory is not allowed to be deallocated until PxScene::fetchResults() returns.
Calling this function with a null pointer for the positions will clear the input and resume normal
simulation. This will also clear both the PxSoftBodyFlag::eKINEMATIC and PxSoftBodyFlag::ePARTIALLY_KINEMATIC
flags of the softbody.
This call is persistent across calls to PxScene::simulate(). Once this function is called, the
simulation will look up the target positions from the same buffer for every call to PxScene::simulate().
The user is allowed to update the target positions without calling this function again, provided that
the synchronization requirements are adhered to (no changes between start of PxScene::simulate() until
PxScene::fetchResults() returns).
\param positions A pointer to a device buffer containing the kinematic targets for this softbody.
\param flags Flags specifying the type of kinematic softbody: this function ignores all flags except PxSoftBodyFlag::eKINEMATIC and PxSoftBodyFlag::ePARTIALLY_KINEMATIC.
*/
virtual void setKinematicTargetBufferD(const PxVec4* positions, PxSoftBodyFlags flags) = 0;
/**
\brief Return the cuda context manager
\return The cuda context manager
*/
virtual PxCudaContextManager* getCudaContextManager() const = 0;
/**
\brief Sets the wake counter for the soft body.
The wake counter value determines the minimum amount of time until the soft body can be put to sleep. Please note
that a soft body will not be put to sleep if any vertex velocity is above the specified threshold
or if other awake objects are touching it.
\note Passing in a positive value will wake the soft body up automatically.
<b>Default:</b> 0.4 (which corresponds to 20 frames for a time step of 0.02)
\param[in] wakeCounterValue Wake counter value. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getWakeCounter()
*/
virtual void setWakeCounter(PxReal wakeCounterValue) = 0;
/**
\brief Returns the wake counter of the soft body.
\return The wake counter of the soft body.
@see isSleeping() setWakeCounter()
*/
virtual PxReal getWakeCounter() const = 0;
/**
\brief Returns true if this soft body is sleeping.
When an actor does not move for a period of time, it is no longer simulated in order to save time. This state
is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object,
or a sleep-affecting property is changed by the user, the entire sleep mechanism should be transparent to the user.
A soft body can only go to sleep if all vertices are ready for sleeping. A soft body is guaranteed to be awake
if at least one of the following holds:
\li The wake counter is positive (@see setWakeCounter()).
\li The velocity of any vertex is above the sleep threshold.
If a soft body is sleeping, the following state is guaranteed:
\li The wake counter is zero.
\li The linear velocity of all vertices is zero.
When a soft body gets inserted into a scene, it will be considered asleep if all the points above hold, else it will
be treated as awake.
\note It is invalid to use this method if the soft body has not been added to a scene already.
\return True if the soft body is sleeping.
@see isSleeping()
*/
virtual bool isSleeping() const = 0;
/**
\brief Sets the solver iteration counts for the body.
The solver iteration count determines how accurately deformation and contacts are resolved.
If you are having trouble with softbodies that are not as stiff as they should be, then
setting a higher position iteration count may improve the behavior.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations.
<b>Default:</b> 4 position iterations, 1 velocity iteration
\param[in] minPositionIters Minimal number of position iterations the solver should perform for this body. <b>Range:</b> [1,255]
\param[in] minVelocityIters Minimal number of velocity iterations the solver should perform for this body. <b>Range:</b> [1,255]
@see getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Retrieves the solver iteration counts.
@see setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Retrieves the shape pointer belonging to the actor.
\return Pointer to the collision mesh's shape
@see PxShape getNbShapes() PxShape::release()
*/
virtual PxShape* getShape() = 0;
/**
\brief Retrieve the collision mesh pointer.
Allows to access the geometry of the tetrahedral mesh used to perform collision detection
\return Pointer to the collision mesh
*/
virtual PxTetrahedronMesh* getCollisionMesh() = 0;
//! \brief Const version of getCollisionMesh()
virtual const PxTetrahedronMesh* getCollisionMesh() const = 0;
/**
\brief Retrieves the simulation mesh pointer.
Allows to access the geometry of the tetrahedral mesh used to compute the object's deformation
\return Pointer to the simulation mesh
*/
virtual PxTetrahedronMesh* getSimulationMesh() = 0;
//! \brief Const version of getSimulationMesh()
virtual const PxTetrahedronMesh* getSimulationMesh() const = 0;
/**
\brief Retrieves the simulation state pointer.
Allows to access the additional data of the simulation mesh (inverse mass, rest state etc.).
The geometry part of the data is stored in the simulation mesh.
\return Pointer to the simulation state
*/
virtual PxSoftBodyAuxData* getSoftBodyAuxData() = 0;
//! \brief const version of getSoftBodyAuxData()
virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const = 0;
/**
\brief Attaches a shape
Attaches the shape to use for collision detection
\param[in] shape The shape to use for collisions
\return Returns true if the operation was successful
*/
virtual bool attachShape(PxShape& shape) = 0;
/**
\brief Attaches a simulation mesh
Attaches the simulation mesh (geometry) and a state containing inverse mass, rest pose
etc. required to compute the softbody deformation.
\param[in] simulationMesh The tetrahedral mesh used to compute the softbody's deformation
\param[in] softBodyAuxData A state that contain a mapping from simulation to collision mesh, volume information etc.
\return Returns true if the operation was successful
*/
virtual bool attachSimulationMesh(PxTetrahedronMesh& simulationMesh, PxSoftBodyAuxData& softBodyAuxData) = 0;
/**
\brief Detaches the shape
Detaches the shape used for collision detection.
@see void detachSimulationMesh()
*/
virtual void detachShape() = 0;
/**
\brief Detaches the simulation mesh
Detaches the simulation mesh and simulation state used to compute the softbody deformation.
@see void detachShape()
*/
virtual void detachSimulationMesh() = 0;
/**
\brief Releases the softbody
Releases the softbody and frees its resources.
*/
virtual void release() = 0;
/**
\brief Creates a collision filter between a particle and a tetrahedron in the soft body's collision mesh.
\param[in] particlesystem The particle system used for the collision filter
\param[in] buffer The PxParticleBuffer to which the particle belongs to.
\param[in] particleId The particle whose collisions with the tetrahedron in the soft body are filtered.
\param[in] tetId The tetradedron in the soft body that is filtered. If tetId is PX_MAX_TETID, this particle will filter against all tetrahedra in this soft body
*/
virtual void addParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) = 0;
/**
\brief Removes a collision filter between a particle and a tetrahedron in the soft body's collision mesh.
\param[in] particlesystem The particle system used for the collision filter
\param[in] buffer The PxParticleBuffer to which the particle belongs to.
\param[in] particleId The particle whose collisions with the tetrahedron in the soft body are filtered.
\param[in] tetId The tetrahedron in the soft body is filtered.
*/
virtual void removeParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) = 0;
/**
\brief Creates an attachment between a particle and a soft body.
Be aware that destroying the particle system before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the particle system does not.
\param[in] particlesystem The particle system used for the attachment
\param[in] buffer The PxParticleBuffer to which the particle belongs to.
\param[in] particleId The particle that is attached to a tetrahedron in the soft body's collision mesh.
\param[in] tetId The tetrahedron in the soft body's collision mesh to attach the particle to.
\param[in] barycentric The barycentric coordinates of the particle attachment position with respect to the tetrahedron specified with tetId.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addParticleAttachment(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId, const PxVec4& barycentric) = 0;
/**
\brief Removes an attachment between a particle and a soft body.
Be aware that destroying the particle system before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the particle system does not.
\param[in] particlesystem The particle system used for the attachment
\param[in] handle Index that identifies the attachment. This handle gets returned by the addParticleAttachment when the attachment is created
*/
virtual void removeParticleAttachment(PxPBDParticleSystem* particlesystem, PxU32 handle) = 0;
/**
\brief Creates a collision filter between a vertex in a soft body and a rigid body.
\param[in] actor The rigid body actor used for the collision filter
\param[in] vertId The index of a vertex in the softbody's collision mesh whose collisions with the rigid body are filtered.
*/
virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId) = 0;
/**
\brief Removes a collision filter between a vertex in a soft body and a rigid body.
\param[in] actor The rigid body actor used for the collision filter
\param[in] vertId The index of a vertex in the softbody's collision mesh whose collisions with the rigid body are filtered.
*/
virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId) = 0;
/**
\brief Creates a rigid attachment between a soft body and a rigid body.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the rigid body does not.
This method attaches a vertex on the soft body collision mesh to the rigid body.
\param[in] actor The rigid body actor used for the attachment
\param[in] vertId The index of a vertex in the softbody's collision mesh that gets attached to the rigid body.
\param[in] actorSpacePose The location of the attachment point expressed in the rigid body's coordinate system.
\param[in] constraint The user defined cone distance limit constraint to limit the movement between a vertex in the soft body and rigid body.
\return Returns a handle that identifies the attachment created. This handle can be used to relese the attachment later
*/
virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint = NULL) = 0;
/**
\brief Releases a rigid attachment between a soft body and a rigid body.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the rigid body does not.
This method removes a previously-created attachment between a vertex of the soft body collision mesh and the rigid body.
\param[in] actor The rigid body actor used for the attachment
\param[in] handle Index that identifies the attachment. This handle gets returned by the addRigidAttachment when the attachment is created
*/
virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a rigid body.
\param[in] actor The rigid body actor used for collision filter
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh whose collisions with the rigid body is filtered.
*/
virtual void addTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a rigid body.
\param[in] actor The rigid body actor used for collision filter
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh whose collisions with the rigid body is filtered.
*/
virtual void removeTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) = 0;
/**
\brief Creates a rigid attachment between a soft body and a rigid body.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the rigid body does not.
This method attaches a point inside a tetrahedron of the collision to the rigid body.
\param[in] actor The rigid body actor used for the attachment
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh that contains the point to be attached to the rigid body
\param[in] barycentric The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx
\param[in] actorSpacePose The location of the attachment point expressed in the rigid body's coordinate system.
\param[in] constraint The user defined cone distance limit constraint to limit the movement between a tet and rigid body.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addTetRigidAttachment(PxRigidActor* actor, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint = NULL) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a tetrahedron in another soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIdx The index of the tetrahedron in the other softbody's collision mesh to be filtered.
\param[in] tetIdx1 The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void addSoftBodyFilter(PxSoftBody* otherSoftBody, PxU32 otherTetIdx, PxU32 tetIdx1) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a tetrahedron in other soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIdx The index of the other tetrahedron in the other softbody's collision mesh whose collision with the tetrahedron with the soft body is filtered.
\param[in] tetIdx1 The index of the tetrahedron in the softbody's collision mesh whose collision with the other tetrahedron with the other soft body is filtered.
*/
virtual void removeSoftBodyFilter(PxSoftBody* otherSoftBody, PxU32 otherTetIdx, PxU32 tetIdx1) = 0;
/**
\brief Creates collision filters between a tetrahedron in a soft body with another soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIndices The indices of the tetrahedron in the other softbody's collision mesh to be filtered.
\param[in] tetIndices The indices of the tetrahedron of the softbody's collision mesh to be filtered.
\param[in] tetIndicesSize The size of tetIndices.
*/
virtual void addSoftBodyFilters(PxSoftBody* otherSoftBody, PxU32* otherTetIndices, PxU32* tetIndices, PxU32 tetIndicesSize) = 0;
/**
\brief Removes collision filters between a tetrahedron in a soft body with another soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIndices The indices of the tetrahedron in the other softbody's collision mesh to be filtered.
\param[in] tetIndices The indices of the tetrahedron of the softbody's collision mesh to be filtered.
\param[in] tetIndicesSize The size of tetIndices.
*/
virtual void removeSoftBodyFilters(PxSoftBody* otherSoftBody, PxU32* otherTetIndices, PxU32* tetIndices, PxU32 tetIndicesSize) = 0;
/**
\brief Creates an attachment between two soft bodies.
This method attaches a point inside a tetrahedron of the collision mesh to a point in another soft body's tetrahedron collision mesh.
\param[in] softbody0 The soft body actor used for the attachment
\param[in] tetIdx0 The index of a tetrahedron in the other soft body that contains the point to be attached to the soft body
\param[in] tetBarycentric0 The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx0
\param[in] tetIdx1 The index of a tetrahedron in the softbody's collision mesh that contains the point to be attached to the softbody0
\param[in] tetBarycentric1 The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx1
\param[in] constraint The user defined cone distance limit constraint to limit the movement between tets.
\param[in] constraintOffset Offsets the cone and distance limit constraint along its axis, in order to specify the location of the cone tip.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addSoftBodyAttachment(PxSoftBody* softbody0, PxU32 tetIdx0, const PxVec4& tetBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1,
PxConeLimitedConstraint* constraint = NULL, PxReal constraintOffset = 0.0f) = 0;
/**
\brief Releases an attachment between a soft body and the other soft body.
Be aware that destroying the soft body before destroying the attachment is illegal and may cause a crash.
This method removes a previously-created attachment between a point inside a tetrahedron of the collision mesh to a point in another soft body's tetrahedron collision mesh.
\param[in] softbody0 The softbody actor used for the attachment.
\param[in] handle Index that identifies the attachment. This handle gets returned by the addSoftBodyAttachment when the attachment is created.
*/
virtual void removeSoftBodyAttachment(PxSoftBody* softbody0, PxU32 handle) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a triangle in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] triIdx The index of the triangle in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void addClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a triangle in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] triIdx The index of the triangle in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void removeClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a vertex in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] vertIdx The index of the vertex in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void addVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a vertex in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] vertIdx The index of the vertex in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void removeVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx) = 0;
/**
\brief Creates an attachment between a soft body and a cloth.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the cloth does not.
This method attaches a point inside a tetrahedron of the collision mesh to a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for the attachment
\param[in] triIdx The index of a triangle in the cloth mesh that contains the point to be attached to the soft body
\param[in] triBarycentric The barycentric coordinates of the attachment point inside the triangle specified by triangleIdx
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh that contains the point to be attached to the cloth
\param[in] tetBarycentric The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx
\param[in] constraint The user defined cone distance limit constraint to limit the movement between a triangle in the fem cloth and a tet in the soft body.
\param[in] constraintOffset Offsets the cone and distance limit constraint along its axis, in order to specify the location of the cone tip.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addClothAttachment(PxFEMCloth* cloth, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric,
PxConeLimitedConstraint* constraint = NULL, PxReal constraintOffset = 0.0f) = 0;
/**
\brief Releases an attachment between a cloth and a soft body.
Be aware that destroying the cloth before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the cloth does not.
This method removes a previously-created attachment between a point inside a collision mesh tetrahedron and a point inside a cloth mesh.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for the attachment
\param[in] handle Index that identifies the attachment. This handle gets returned by the addClothAttachment when the attachment is created
*/
virtual void removeClothAttachment(PxFEMCloth* cloth, PxU32 handle) = 0;
/**
\brief Retrieves the axis aligned bounding box enclosing the soft body.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value.
\return The soft body's bounding box.
@see PxBounds3
*/
virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const = 0;
/**
\brief Returns the GPU soft body index.
\return The GPU index, or 0xFFFFFFFF if the soft body is not in a scene.
*/
virtual PxU32 getGpuSoftBodyIndex() = 0;
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxSoftBody"; }
protected:
PX_INLINE PxSoftBody(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {}
PX_INLINE PxSoftBody(PxBaseFlags baseFlags) : PxActor(baseFlags) {}
virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxSoftBody", PxActor); }
};
/**
\brief Adjusts a softbody kinematic target such that it is properly set as active or inactive. Inactive targets will not affect vertex position, they are ignored by the solver.
\param[in] target The kinematic target
\param[in] isActive A boolean indicating if the returned target should be marked as active or not
\return The target with adjusted w component
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureSoftBodyKinematicTarget(const PxVec4& target, bool isActive)
{
PxVec4 result = target;
if (isActive)
result.w = 0.0f;
else
{
//Any non-zero value will mark the target as inactive
if (result.w == 0.0f)
result.w = 1.0f;
}
return result;
}
/**
\brief Sets up a softbody kinematic target such that it is properly set as active or inactive. Inactive targets will not affect vertex position, they are ignored by the solver.
\param[in] target The kinematic target
\param[in] isActive A boolean indicating if the returned target should be marked as active or not
\return The target with configured w component
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureSoftBodyKinematicTarget(const PxVec3& target, bool isActive)
{
return PxConfigureSoftBodyKinematicTarget(PxVec4(target, 0.0f), isActive);
}
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 38,612 | C | 46.319853 | 193 | 0.763105 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.