file_path
stringlengths 21
224
| content
stringlengths 0
80.8M
|
---|---|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemShapeCore.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "foundation/PxErrorCallback.h"
#include "ScParticleSystemShapeCore.h"
#include "ScParticleSystemShapeSim.h"
#include "ScPhysics.h"
#include "PxvGlobals.h"
#include "PxPhysXGpu.h"
#include "cudamanager/PxCudaContextManager.h"
#include "CmVisualization.h"
using namespace physx;
using namespace Sc;
ParticleSystemShapeCore::ParticleSystemShapeCore()
: ShapeCore(PxEmpty)
, mGpuMemStat(0)
{
mSimulationFilterData = PxFilterData();
mCore = PxsShapeCore();
mCore.mShapeCoreFlags |= PxShapeCoreFlag::eOWNS_MATERIAL_IDX_MEMORY;
const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale();
mCore.setTransform(PxTransform(PxIdentity));
mCore.mContactOffset = 0.01f * scale.length;
mCore.mShapeFlags = 0;
mCore.mMaterialIndex = 0;
mCore.mMinTorsionalPatchRadius = 0.f;
mCore.mTorsionalRadius = 0.f;
mLLCore.sleepThreshold = 5e-5f * scale.speed * scale.speed;
mLLCore.wakeCounter = Physics::sWakeCounterOnCreation;
mLLCore.freezeThreshold = 5e-6f * scale.speed * scale.speed;
//TODO, make this dependend on scale?
//also set contact offset accordingly
mLLCore.restOffset = 0.1f;
const PxReal contactOffset = mLLCore.restOffset + 0.001f;
setContactOffset(contactOffset);
mLLCore.particleContactOffset = contactOffset;
mLLCore.solidRestOffset = mLLCore.restOffset;
mLLCore.fluidRestOffset = mLLCore.restOffset * 0.6f;
mLLCore.particleContactOffset_prev = FLT_MIN;
mLLCore.fluidRestOffset_prev = FLT_MIN;
mLLCore.fluidBoundaryDensityScale = 0.0f;
mLLCore.gridSizeX = 128;
mLLCore.gridSizeY = 128;
mLLCore.gridSizeZ = 128;
mLLCore.mFlags = PxParticleFlags(0);
mLLCore.solverIterationCounts = (1 << 8) | 4;
mLLCore.mWind = PxVec3(0.f);
//mLLCore.mNumUpdateSprings = 0;
mLLCore.solverType = PxParticleSolverType::ePBD;
// Sparse grid specific
mLLCore.sparseGridParams.setToDefault();
mLLCore.sparseGridParams.gridSpacing = 2.0f * mLLCore.particleContactOffset;
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
// FLIP specific
mLLCore.flipParams.setToDefault();
// MPM specific
mLLCore.mpmParams.setToDefault();
#endif
}
// PX_SERIALIZATION
ParticleSystemShapeCore::ParticleSystemShapeCore(const PxEMPTY)
: ShapeCore(PxEmpty)
{
}
ParticleSystemShapeCore::~ParticleSystemShapeCore()
{
}
void ParticleSystemShapeCore::addParticleBuffer(PxParticleBuffer* particleBuffer)
{
mLLCore.addParticleBuffer(particleBuffer);
}
void ParticleSystemShapeCore::removeParticleBuffer(PxParticleBuffer* particleBuffer)
{
mLLCore.removeParticleBuffer(particleBuffer);
}
void ParticleSystemShapeCore::initializeLLCoreData(PxU32 maxNeighborhood)
{
const PxTolerancesScale& scale = Sc::Physics::getInstance().getTolerancesScale();
mLLCore.mMaxNeighborhood = maxNeighborhood;
mLLCore.maxDepenetrationVelocity = 50.f * scale.length;
mLLCore.maxVelocity = 1e+6f;
}
#endif // PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScMetaData.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/PxIO.h"
#include "ScActorCore.h"
#include "ScActorSim.h"
#include "ScBodyCore.h"
#include "ScStaticCore.h"
#include "ScConstraintCore.h"
#include "ScShapeCore.h"
#include "ScArticulationCore.h"
#include "ScArticulationJointCore.h"
#include "ScArticulationSensor.h"
#include "ScArticulationTendonCore.h"
#include "ScArticulationAttachmentCore.h"
#include "ScArticulationTendonJointCore.h"
using namespace physx;
using namespace Cm;
using namespace Sc;
///////////////////////////////////////////////////////////////////////////////
template <typename T> class PxMetaDataArray : public physx::PxArray<T>
{
public:
static PX_FORCE_INLINE physx::PxU32 getDataOffset() { return PX_OFFSET_OF(PxMetaDataArray<T>, mData); }
static PX_FORCE_INLINE physx::PxU32 getDataSize() { return PX_SIZE_OF(PxMetaDataArray<T>, mData); }
static PX_FORCE_INLINE physx::PxU32 getSizeOffset() { return PX_OFFSET_OF(PxMetaDataArray<T>, mSize); }
static PX_FORCE_INLINE physx::PxU32 getSizeSize() { return PX_SIZE_OF(PxMetaDataArray<T>, mSize); }
static PX_FORCE_INLINE physx::PxU32 getCapacityOffset() { return PX_OFFSET_OF(PxMetaDataArray<T>, mCapacity); }
static PX_FORCE_INLINE physx::PxU32 getCapacitySize() { return PX_SIZE_OF(PxMetaDataArray<T>, mCapacity); }
};
void Sc::ActorCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxActorFlags, PxU8)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxDominanceGroup, PxU8)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxClientID, PxU8)
PX_DEF_BIN_METADATA_CLASS(stream, Sc::ActorCore)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, ActorSim, mSim, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxU32, mAggregateIDOwnerClient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxActorFlags, mActorFlags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxU8, mActorType, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::ActorCore, PxU8, mDominanceGroup, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_PxsRigidCore(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsRigidCore)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxTransform, body2World, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxRigidBodyFlags, mFlags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxU16, solverIterationCounts, 0)
}
namespace
{
class ShadowPxsBodyCore : public PxsBodyCore
{
public:
static void getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ShadowPxsBodyCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, ShadowPxsBodyCore, PxsRigidCore)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxTransform, body2Actor, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, ccdAdvanceCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxVec3, linearVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxPenBias, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxVec3, angularVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, contactReportThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxAngularVelocitySq, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxLinearVelocitySq, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, linearDamping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, angularDamping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxVec3, inverseInertia, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, inverseMass, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, maxContactImpulse, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, sleepThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, freezeThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, wakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, solverWakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU32, numCountedInteractions, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxReal, offsetSlop, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, isFastMoving, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, disableGravity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, lockFlags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsBodyCore, PxU8, fixedBaseLink, 0)
}
};
}
static void getBinaryMetaData_PxsBodyCore(PxOutputStream& stream)
{
getBinaryMetaData_PxsRigidCore(stream);
/* PX_DEF_BIN_METADATA_CLASS(stream, PxsBodyCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, PxsBodyCore, PxsRigidCore)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxTransform, body2Actor, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, ccdAdvanceCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxVec3, linearVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxPenBias, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxVec3, angularVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, contactReportThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxAngularVelocitySq, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxLinearVelocitySq, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, linearDamping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, angularDamping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxVec3, inverseInertia, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, inverseMass, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, maxContactImpulse, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, sleepThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, freezeThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, wakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxReal, solverWakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsBodyCore, PxU32, numCountedInteractions, 0)*/
ShadowPxsBodyCore::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxsBodyCore, ShadowPxsBodyCore)
}
/*
We need to fix the header deps by moving the API out of PhysXCore and into its own dir where other code can get to it.
[25.08.2010 18:34:57] Dilip Sequeira: In the meantime, I think it's Ok to include PxSDK.h, but you're right, we need to be very careful about include deps in that direction.
[25.08.2010 18:38:15] Dilip Sequeira: On the memory thing... PxsBodyCore has 28 bytes of padding at the end, for no reason. In addition, it has two words of padding after the velocity fields, to facilitate SIMD loads. But in fact, Vec3FromVec4 is fast enough such that unless you were using it in an inner loop (which we never are with PxsBodyCore) that padding isn't worth it.
[25.08.2010 18:38:58] Dilip Sequeira: So, we should drop the end-padding, and move the damping values to replace the velocity padding. This probably requires a bit of fixup in the places where we do SIMD writes to the velocity.
[25.08.2010 18:39:18] Dilip Sequeira: Then we're down to 92 bytes of data, and 4 bytes of padding I think.
[25.08.2010 18:50:41] Dilip Sequeira: The reason we don't want to put the sleep data there explicitly is that it isn't LL data so I'd rather not have it in an LL interface struct.
[25.08.2010 19:04:53] Gordon Yeoman nvidia: simd loads are faster when they are 16-byte aligned. I think the padding might be to ensure the second vector is also 16-byte aligned. We could drop the second 4-byte pad but dropping the 1st 4-byte pad will likely have performance implications.
[25.08.2010 19:06:22] Dilip Sequeira: We should still align the vec3s, as now - but we shouldn't use padding to do it, since there are a boatload of scalar data fields floating around in that struct too.
*/
void Sc::BodyCore::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_PxsBodyCore(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxRigidBodyFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, Sc::BodyCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Sc::BodyCore, Sc::RigidCore)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::BodyCore, PxsBodyCore, mCore, 0)
}
///////////////////////////////////////////////////////////////////////////////
void Sc::ConstraintCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxConstraintFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, ConstraintCore)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintFlags, mFlags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxU8, mIsDirty, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, ConstraintCore, PxU8, mPadding, PxMetaDataFlag::ePADDING)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxVec3, mAppliedForce, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxVec3, mAppliedTorque, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintConnector, mConnector, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintSolverPrep, mSolverPrep, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxConstraintVisualize, mVisualize, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxU32, mDataSize, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxReal, mLinearBreakForce, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxReal, mAngularBreakForce, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, PxReal, mMinResponseThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ConstraintCore, ConstraintSim, mSim, PxMetaDataFlag::ePTR)
}
///////////////////////////////////////////////////////////////////////////////
void Sc::RigidCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Sc::RigidCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Sc::RigidCore, Sc::ActorCore)
}
///////////////////////////////////////////////////////////////////////////////
void Sc::StaticCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Sc::StaticCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, Sc::StaticCore, Sc::RigidCore)
PX_DEF_BIN_METADATA_ITEM(stream, Sc::StaticCore, PxsRigidCore, mCore, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_PxFilterData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxFilterData)
PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word0, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word1, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word2, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxFilterData, PxU32, word3, 0)
}
namespace
{
class ShadowPxsShapeCore : public PxsShapeCore
{
public:
static void getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ShadowPxsShapeCore)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxTransform, mTransform, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, GeometryUnion, mGeometry, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mContactOffset, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxShapeFlags, mShapeFlags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxShapeCoreFlags, mShapeCoreFlags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mRestOffset, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mTorsionalRadius, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShadowPxsShapeCore, PxReal, mMinTorsionalPatchRadius, 0)
}
};
}
static void getBinaryMetaData_PxsShapeCore(PxOutputStream& stream)
{
ShadowPxsShapeCore::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxsShapeCore, ShadowPxsShapeCore)
}
void Sc::ShapeCore::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_PxFilterData(stream);
getBinaryMetaData_PxsShapeCore(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxShapeFlags, PxU8)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxShapeCoreFlags, PxU8)
PX_DEF_BIN_METADATA_CLASS(stream, ShapeCore)
PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, PxFilterData, mSimulationFilterData, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, PxsShapeCore, mCore, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, ShapeSim, mExclusiveSim, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ShapeCore, char, mName, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_EXTRA_NAME(stream, ShapeCore, mName, 0)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_ArticulationCore(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, Dy::ArticulationCore)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxArticulationFlags, PxU8)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxU16, solverIterationCounts, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxArticulationFlags, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, sleepThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, freezeThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, wakeCounter, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, gpuRemapIndex, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, maxLinearVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationCore, PxReal, maxAngularVelocity, 0)
}
void Sc::ArticulationCore::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_ArticulationCore(stream);
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationCore, ArticulationSim, mSim, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationCore, Dy::ArticulationCore, mCore, 0)
}
void Sc::ArticulationSensorCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationSensorCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSensorCore, ArticulationSensorSim, mSim, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSensorCore, PxTransform, mRelativePose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSensorCore, PxU16, mFlags, 0)
}
void Sc::ArticulationAttachmentCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationAttachmentCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxVec3, mRelativeOffset, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, ArticulationAttachmentCore, mParent, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mLowLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mHighLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mRestLength, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxReal, mCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxU32, mLLLinkIndex, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, PxU32, mAttachmentIndex, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationAttachmentCore, ArticulationSpatialTendonSim, mTendonSim, PxMetaDataFlag::ePTR)
}
void Sc::ArticulationTendonCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationTendonCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mStiffness, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mDamping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mOffset, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonCore, PxReal, mLimitStiffness, 0)
}
void Sc::ArticulationSpatialTendonCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationSpatialTendonCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, ArticulationSpatialTendonCore, ArticulationTendonCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationSpatialTendonCore, ArticulationSpatialTendonSim, mSim, PxMetaDataFlag::ePTR)
}
void Sc::ArticulationFixedTendonCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationFixedTendonCore)
PX_DEF_BIN_METADATA_BASE_CLASS(stream, ArticulationFixedTendonCore, ArticulationTendonCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, PxReal, mLowLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, PxReal, mHighLimit, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, PxReal, mRestLength, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationFixedTendonCore, ArticulationFixedTendonSim, mSim, PxMetaDataFlag::ePTR)
}
void Sc::ArticulationTendonJointCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxArticulationAxis, PxU32)
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationTendonJointCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxArticulationAxis, axis, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxReal, coefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxReal, recipCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxU32, mLLLinkIndex, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, ArticulationTendonJointCore, mParent, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, PxU32, mLLTendonJointIndex, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationTendonJointCore, ArticulationFixedTendonSim, mTendonSim, PxMetaDataFlag::ePTR)
}
///////////////////////////////////////////////////////////////////////////////
static void getBinaryMetaData_ArticulationLimit(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxArticulationLimit)
PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationLimit, PxReal, low, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationLimit, PxReal, high, 0)
}
static void getBinaryMetaData_ArticulationDrive(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxArticulationDriveType::Enum, PxU32)
PX_DEF_BIN_METADATA_CLASS(stream, PxArticulationDrive)
PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxReal, stiffness, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxReal, maxForce, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxArticulationDrive, PxArticulationDriveType::Enum, driveType, 0)
}
static void getBinaryMetaData_ArticulationJointCore(PxOutputStream& stream)
{
getBinaryMetaData_ArticulationLimit(stream);
getBinaryMetaData_ArticulationDrive(stream);
PX_DEF_BIN_METADATA_CLASS(stream, Dy::ArticulationJointCore)
PX_DEF_BIN_METADATA_TYPEDEF(stream, ArticulationJointCoreDirtyFlags, PxU8)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxTransform, parentPose, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxTransform, childPose, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxArticulationLimit, limits, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxArticulationDrive, drives, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, targetP, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, targetV, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, armature, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, jointPos, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxReal, jointVel, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxReal, frictionCoefficient, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxU8, dofIds, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxU8, motion, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream, Dy::ArticulationJointCore, PxU8, invDofIds, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxReal, maxJointVelocity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, ArticulationJointCoreDirtyFlags, jointDirtyFlag, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxU32, jointOffset, 0)
PX_DEF_BIN_METADATA_ITEM(stream, Dy::ArticulationJointCore, PxU8, jointType, 0)
}
//
//static void getBinaryMetaData_ArticulationJointCore(PxOutputStream& stream)
//{
// getBinaryMetaData_ArticulationJointCoreBase(stream);
// PX_DEF_BIN_METADATA_CLASS(stream, Dy::ArticulationJointCore)
// PX_DEF_BIN_METADATA_BASE_CLASS(stream, Dy::ArticulationJointCore, Dy::ArticulationJointCoreBase)
//}
void Sc::ArticulationJointCore::getBinaryMetaData(PxOutputStream& stream)
{
getBinaryMetaData_ArticulationJointCore(stream);
PX_DEF_BIN_METADATA_CLASS(stream, ArticulationJointCore)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, ArticulationJointSim, mSim, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, Dy::ArticulationJointCore, mCore, 0)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, Dy::ArticulationCore, mArticulation, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, PxArticulationJointReducedCoordinate, mRootType, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, ArticulationJointCore, PxU32, mLLLinkIndex, 0)
}
///////////////////////////////////////////////////////////////////////////////
/*
#define PX_DEF_BIN_METADATA_ARRAY(stream, Class, type, array) \
{ PxMetaDataEntry tmp = {"void", #array".mData", PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getDataOffset(), PxMetaDataArray<type>::getDataSize(), 1, 0, PxMetaDataFlag::ePTR, 0}; PX_STORE_METADATA(stream, tmp); } \
{ PxMetaDataEntry tmp = {"PxU32", #array".mSize", PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getSizeOffset(), PxMetaDataArray<type>::getSizeSize(), 1, 0, 0, 0}; PX_STORE_METADATA(stream, tmp); } \
{ PxMetaDataEntry tmp = {"PxU32", #array".mCapacity", PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getCapacityOffset(), PxMetaDataArray<type>::getCapacitySize(), 1, 0, PxMetaDataFlag::eCOUNT_MASK_MSB, 0}; PX_STORE_METADATA(stream, tmp); } \
{ PxMetaDataEntry tmp = {#type, 0, PxU32(PX_OFFSET_OF(Class, array)) + PxMetaDataArray<type>::getSizeOffset(), PxMetaDataArray<type>::getSizeSize(), 0, 0, PxMetaDataFlag::eEXTRA_DATA, 0}; PX_STORE_METADATA(stream, tmp); }
*/
///////////////////////////////////////////////////////////////////////////////
void MaterialIndicesStruct::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, MaterialIndicesStruct)
PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU16, indices, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU16, numIndices, 0)
PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU16, pad, PxMetaDataFlag::ePADDING)
PX_DEF_BIN_METADATA_ITEM(stream, MaterialIndicesStruct, PxU32, gpuRemapId, 0)
//------ Extra-data ------
// indices
PX_DEF_BIN_METADATA_EXTRA_ITEMS(stream, MaterialIndicesStruct, PxU16, indices, numIndices, PxMetaDataFlag::eHANDLE, PX_SERIAL_ALIGN)
}
///////////////////////////////////////////////////////////////////////////////
void GeometryUnion::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxGeometryType::Enum, PxU32)
// The various PxGeometry classes are all public, so I can't really put the meta-data function in there. And then
// I can't access their protected members. So we use the same trick as for the ShapeContainer
class ShadowConvexMeshGeometry : public PxConvexMeshGeometryLL
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream_, PxConvexMeshGeometryFlags, PxU8)
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowConvexMeshGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, float, mTypePadding, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxMeshScale, scale, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxConvexMesh, convexMesh, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, PxConvexMeshGeometryFlags, meshFlags, 0)
PX_DEF_BIN_METADATA_ITEMS(stream_, ShadowConvexMeshGeometry, PxU8, paddingFromFlags, PxMetaDataFlag::ePADDING, 3)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowConvexMeshGeometry, bool, gpuCompatible, 0)
}
};
ShadowConvexMeshGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxConvexMeshGeometryLL, ShadowConvexMeshGeometry)
/////////////////
class ShadowTriangleMeshGeometry : public PxTriangleMeshGeometryLL
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream_, PxMeshGeometryFlags, PxU8)
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowTriangleMeshGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, float, mTypePadding, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxMeshScale, scale, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxMeshGeometryFlags, meshFlags, 0)
PX_DEF_BIN_METADATA_ITEMS(stream_, ShadowTriangleMeshGeometry, PxU8, paddingFromFlags, PxMetaDataFlag::ePADDING, 3)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, PxTriangleMesh, triangleMesh, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowTriangleMeshGeometry, MaterialIndicesStruct, materialsLL, 0)
}
};
ShadowTriangleMeshGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream,PxTriangleMeshGeometryLL, ShadowTriangleMeshGeometry)
/////////////////
class ShadowHeightFieldGeometry : public PxHeightFieldGeometryLL
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowHeightFieldGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, float, mTypePadding, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxHeightField, heightField, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxReal, heightScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxReal, rowScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxReal, columnScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, PxMeshGeometryFlags, heightFieldFlags, 0)
PX_DEF_BIN_METADATA_ITEMS_AUTO(stream_, ShadowHeightFieldGeometry, PxU8, paddingFromFlags, PxMetaDataFlag::ePADDING)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowHeightFieldGeometry, MaterialIndicesStruct, materialsLL, 0)
}
};
ShadowHeightFieldGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream,PxHeightFieldGeometryLL, ShadowHeightFieldGeometry)
/////////////////
class ShadowPlaneGeometry : public PxPlaneGeometry
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowPlaneGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowPlaneGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowPlaneGeometry, float, mTypePadding, 0)
}
};
ShadowPlaneGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream,PxPlaneGeometry, ShadowPlaneGeometry)
/////////////////
class ShadowSphereGeometry : public PxSphereGeometry
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowSphereGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowSphereGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowSphereGeometry, float, mTypePadding, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowSphereGeometry, PxReal, radius, 0)
}
};
ShadowSphereGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxSphereGeometry, ShadowSphereGeometry)
/////////////////
class ShadowCapsuleGeometry : public PxCapsuleGeometry
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowCapsuleGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, float, mTypePadding, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, PxReal, radius, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowCapsuleGeometry, PxReal, halfHeight, 0)
}
};
ShadowCapsuleGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxCapsuleGeometry, ShadowCapsuleGeometry)
/////////////////
class ShadowBoxGeometry : public PxBoxGeometry
{
public:
static void getBinaryMetaData(PxOutputStream& stream_)
{
PX_DEF_BIN_METADATA_CLASS(stream_, ShadowBoxGeometry)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBoxGeometry, PxGeometryType::Enum, mType, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBoxGeometry, float, mTypePadding, 0)
PX_DEF_BIN_METADATA_ITEM(stream_, ShadowBoxGeometry, PxVec3, halfExtents, 0)
}
};
ShadowBoxGeometry::getBinaryMetaData(stream);
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxBoxGeometry, ShadowBoxGeometry)
/*
- geom union offset & size
- control type offset & size
- type-to-class mapping
*/
PX_DEF_BIN_METADATA_CLASS(stream, GeometryUnion)
PX_DEF_BIN_METADATA_UNION(stream, GeometryUnion, mGeometry)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxSphereGeometry, PxGeometryType::eSPHERE)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxPlaneGeometry, PxGeometryType::ePLANE)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxCapsuleGeometry, PxGeometryType::eCAPSULE)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxBoxGeometry, PxGeometryType::eBOX)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxConvexMeshGeometryLL, PxGeometryType::eCONVEXMESH)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxTriangleMeshGeometryLL,PxGeometryType::eTRIANGLEMESH)
PX_DEF_BIN_METADATA_UNION_TYPE(stream, GeometryUnion, PxHeightFieldGeometryLL, PxGeometryType::eHEIGHTFIELD)
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemSim.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.
#ifndef SC_PARTICLESYSTEM_SIM_H
#define SC_PARTICLESYSTEM_SIM_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "foundation/PxUserAllocated.h"
#include "ScActorSim.h"
#include "ScParticleSystemCore.h"
#include "ScParticleSystemShapeSim.h"
namespace physx
{
namespace Sc
{
class Scene;
class ParticleSystemSim : public ActorSim
{
PX_NOCOPY(ParticleSystemSim)
public:
ParticleSystemSim(ParticleSystemCore& core, Scene& scene);
~ParticleSystemSim();
PX_INLINE Dy::ParticleSystem* getLowLevelParticleSystem() const { return mLLParticleSystem; }
PX_INLINE ParticleSystemCore& getCore() const { return static_cast<ParticleSystemCore&>(mCore); }
virtual PxActor* getPxActor() const { return getCore().getPxActor(); }
void updateBounds();
void updateBoundsInAABBMgr();
PxBounds3 getBounds() const;
bool isSleeping() const;
bool isActive() const { return true; }
void sleepCheck(PxReal dt);
void setActive(bool active, bool asPartOfCreation=false);
const ParticleSystemShapeSim& getShapeSim() const { return mShapeSim; }
ParticleSystemShapeSim& getShapeSim() { return mShapeSim; }
private:
Dy::ParticleSystem* mLLParticleSystem;
ParticleSystemShapeSim mShapeSim;
// PT: as far as I can tell these are never actually called
// void activate();
// void deactivate();
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScRigidSim.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 SC_RIGID_SIM_H
#define SC_RIGID_SIM_H
#include "ScActorSim.h"
#include "ScRigidCore.h"
namespace physx
{
namespace Sc
{
class Scene;
class RigidSim : public ActorSim
{
public:
RigidSim(Scene&, RigidCore&);
virtual ~RigidSim();
PX_FORCE_INLINE RigidCore& getRigidCore() const { return static_cast<RigidCore&>(mCore); }
void notifyShapesOfTransformChange();
void setBodyNodeIndex(const PxNodeIndex nodeIndex);
virtual PxActor* getPxActor() const { return getRigidCore().getPxActor(); }
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScVisualize.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 "ScScene.h"
#include "ScNPhaseCore.h"
#include "ScShapeInteraction.h"
#include "ScConstraintSim.h"
#include "ScConstraintCore.h"
#include "CmVisualization.h"
using namespace physx;
using namespace Sc;
// PT: Sc-level visualization code has been moved to this dedicated file (like we did in NpDebugViz.cpp)
static void visualize(const ConstraintSim& sim, Cm::ConstraintImmediateVisualizer& viz, PxU32 flags, const PxTransform& idt)
{
ConstraintCore& core = sim.getCore();
if(!(core.getFlags() & PxConstraintFlag::eVISUALIZATION))
return;
const Dy::Constraint& llc = sim.getLowLevelConstraint();
PxsRigidBody* b0 = llc.body0;
PxsRigidBody* b1 = llc.body1;
const PxTransform& t0 = b0 ? b0->getPose() : idt;
const PxTransform& t1 = b1 ? b1->getPose() : idt;
core.getVisualize()(viz, llc.constantBlock, t0, t1, flags);
}
void Sc::ShapeInteraction::visualize(PxRenderOutput& out, PxsContactManagerOutputIterator& outputs,
float scale, float param_contactForce, float param_contactNormal, float param_contactError, float param_contactPoint)
{
if(mManager) // sleeping pairs have no contact points -> do not visualize
{
Sc::ActorSim* actorSim0 = &getShape0().getActor();
Sc::ActorSim* actorSim1 = &getShape1().getActor();
if(!actorSim0->isNonRigid() && !actorSim1->isNonRigid())
{
PxU32 offset;
PxU32 nextOffset = 0;
do
{
const void* contactPatches;
const void* contactPoints;
PxU32 contactDataSize;
PxU32 contactPointCount;
PxU32 contactPatchCount;
const PxReal* impulses;
offset = nextOffset;
nextOffset = getContactPointData(contactPatches, contactPoints, contactDataSize, contactPointCount, contactPatchCount, impulses, offset, outputs);
const PxU32* faceIndices = reinterpret_cast<const PxU32*>(impulses + contactPointCount);
PxContactStreamIterator iter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(contactPoints), faceIndices, contactPatchCount, contactPointCount);
PxU32 i = 0;
while(iter.hasNextPatch())
{
iter.nextPatch();
while(iter.hasNextContact())
{
iter.nextContact();
if((param_contactForce != 0.0f) && impulses)
{
out << PxU32(PxDebugColor::eARGB_RED);
out.outputSegment(iter.getContactPoint(), iter.getContactPoint() + iter.getContactNormal() * (scale * param_contactForce * impulses[i]));
}
else if(param_contactNormal != 0.0f)
{
out << PxU32(PxDebugColor::eARGB_BLUE);
out.outputSegment(iter.getContactPoint(), iter.getContactPoint() + iter.getContactNormal() * (scale * param_contactNormal));
}
else if(param_contactError != 0.0f)
{
out << PxU32(PxDebugColor::eARGB_YELLOW);
out.outputSegment(iter.getContactPoint(), iter.getContactPoint() + iter.getContactNormal() * PxAbs(scale * param_contactError * PxMin(0.f, iter.getSeparation())));
}
if(param_contactPoint != 0.0f)
{
const PxReal s = scale * 0.1f;
const PxVec3& point = iter.getContactPoint();
//if (0) //temp debug to see identical contacts
// point.x += scale * 0.01f * (contactPointCount - i + 1);
out << PxU32(PxDebugColor::eARGB_RED);
out.outputSegment(point + PxVec3(-s, 0, 0), point + PxVec3(s, 0, 0));
out.outputSegment(point + PxVec3(0, -s, 0), point + PxVec3(0, s, 0));
out.outputSegment(point + PxVec3(0, 0, -s), point + PxVec3(0, 0, s));
}
i++;
}
}
} while (nextOffset != offset);
}
}
}
// Render objects before simulation starts
void Sc::Scene::visualizeStartStep()
{
PX_PROFILE_ZONE("Sim.visualizeStartStep", mContextId);
// Update from visualization parameters
if(mVisualizationParameterChanged)
{
mVisualizationParameterChanged = false;
// Update SIPs if visualization is enabled
if( getVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT) || getVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL) ||
getVisualizationParameter(PxVisualizationParameter::eCONTACT_ERROR) || getVisualizationParameter(PxVisualizationParameter::eCONTACT_FORCE))
mInternalFlags |= SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_VISUALIZATION;
}
#if PX_ENABLE_DEBUG_VISUALIZATION
const PxReal scale = getVisualizationScale();
if(scale==0.0f)
{
// make sure visualization inside simulate was skipped
PX_ASSERT(getRenderBuffer().empty());
return; // early out if visualization scale is 0
}
PxRenderOutput out(getRenderBuffer());
if(getVisualizationParameter(PxVisualizationParameter::eCOLLISION_COMPOUNDS))
mAABBManager->visualize(out);
// Visualize joints
{
const float frameScale = scale * getVisualizationParameter(PxVisualizationParameter::eJOINT_LOCAL_FRAMES);
const float limitScale = scale * getVisualizationParameter(PxVisualizationParameter::eJOINT_LIMITS);
if(frameScale!=0.0f || limitScale!=0.0f)
{
Cm::ConstraintImmediateVisualizer viz(frameScale, limitScale, out);
PxU32 flags = 0;
if(frameScale!=0.0f)
flags |= PxConstraintVisualizationFlag::eLOCAL_FRAMES;
if(limitScale!=0.0f)
flags |= PxConstraintVisualizationFlag::eLIMITS;
const PxTransform idt(PxIdentity);
Sc::ConstraintCore*const * constraints = mConstraints.getEntries();
for(PxU32 i=0, size = mConstraints.size();i<size; i++)
{
ConstraintSim* sim = constraints[i]->getSim();
if(sim)
visualize(*sim, viz, flags, idt);
}
}
}
{
// PT: put common reads here to avoid doing them for each interaction
const PxReal param_contactForce = getVisualizationParameter(PxVisualizationParameter::eCONTACT_FORCE);
const PxReal param_contactNormal = getVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL);
const PxReal param_contactError = getVisualizationParameter(PxVisualizationParameter::eCONTACT_ERROR);
const PxReal param_contactPoint = getVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT);
if(param_contactForce!=0.0f || param_contactNormal!=0.0f || param_contactError!=0.0f || param_contactPoint!=0.0f)
{
PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs();
ElementSimInteraction** interactions = getActiveInteractions(InteractionType::eOVERLAP);
PxU32 nbActiveInteractions = getNbActiveInteractions(InteractionType::eOVERLAP);
while(nbActiveInteractions--)
static_cast<ShapeInteraction*>(*interactions++)->visualize( out, outputs,
scale, param_contactForce, param_contactNormal, param_contactError, param_contactPoint);
}
}
#else
PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION
#endif
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSim.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 "ScShapeSim.h"
using namespace physx;
using namespace Sc;
void resetElementID(Scene& scene, ShapeSimBase& shapeSim);
ShapeSim::ShapeSim(RigidSim& owner, ShapeCore& core) : ShapeSimBase(owner, &core)
{
initSubsystemsDependingOnElementID();
core.setExclusiveSim(this);
}
ShapeSim::~ShapeSim()
{
Sc::ShapeCore::getCore(*mLLShape.mShapeCore).setExclusiveSim(NULL);
Scene& scScene = getScene();
resetElementID(scScene, *this);
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintInteraction.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 "ScConstraintInteraction.h"
#include "ScConstraintSim.h"
#include "ScBodySim.h"
#include "ScScene.h"
#include "PxsRigidBody.h"
#include "PxsSimpleIslandManager.h"
using namespace physx;
using namespace Sc;
ConstraintInteraction::ConstraintInteraction(ConstraintSim* constraint, RigidSim& r0, RigidSim& r1) :
Interaction (r0, r1, InteractionType::eCONSTRAINTSHADER, InteractionFlag::eCONSTRAINT),
mConstraint (constraint)
{
{
onActivate(NULL);
registerInActors();
}
BodySim* b0 = mConstraint->getBody(0);
BodySim* b1 = mConstraint->getBody(1);
if(b0)
b0->onConstraintAttach();
if(b1)
b1->onConstraintAttach();
IG::SimpleIslandManager* simpleIslandManager = getScene().getSimpleIslandManager();
mEdgeIndex = simpleIslandManager->addConstraint(&mConstraint->getLowLevelConstraint(), b0 ? b0->getNodeIndex() : PxNodeIndex(), b1 ? b1->getNodeIndex() : PxNodeIndex(), this);
}
ConstraintInteraction::~ConstraintInteraction()
{
PX_ASSERT(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST));
PX_ASSERT(!getDirtyFlags());
PX_ASSERT(!mConstraint->readFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED));
}
static PX_FORCE_INLINE void removeFromActiveBreakableList(ConstraintSim* constraint, Scene& s)
{
if(constraint->readFlag(ConstraintSim::eBREAKABLE | ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED) == (ConstraintSim::eBREAKABLE | ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED))
s.removeActiveBreakableConstraint(constraint);
}
void ConstraintInteraction::destroy()
{
setClean(true); // removes the pair from the dirty interaction list etc.
Scene& scene = getScene();
removeFromActiveBreakableList(mConstraint, scene);
if(mEdgeIndex != IG_INVALID_EDGE)
scene.getSimpleIslandManager()->removeConnection(mEdgeIndex);
mEdgeIndex = IG_INVALID_EDGE;
unregisterFromActors();
BodySim* b0 = mConstraint->getBody(0);
BodySim* b1 = mConstraint->getBody(1);
if(b0)
b0->onConstraintDetach(); // Note: Has to be done AFTER the interaction has unregistered from the actors
if(b1)
b1->onConstraintDetach(); // Note: Has to be done AFTER the interaction has unregistered from the actors
clearInteractionFlag(InteractionFlag::eIS_ACTIVE); // ensures that broken constraints do not go into the list of active breakable constraints anymore
}
void ConstraintInteraction::updateState()
{
PX_ASSERT(!mConstraint->isBroken());
PX_ASSERT(getDirtyFlags() & InteractionDirtyFlag::eBODY_KINEMATIC); // at the moment this should be the only reason for this method being called
// at least one of the bodies got switched from kinematic to dynamic. This will not have changed the sleep state of the interactions, so the
// constraint interactions are just marked dirty and processed as part of the dirty interaction update system.
//
// -> need to check whether to activate the constraint and whether constraint break testing
// is now necessary
//
// the transition from dynamic to kinematic will always trigger an onDeactivate() (because the body gets deactivated)
// and thus there is no need to consider that case here.
//
onActivate(NULL); // note: this will not activate if the necessary conditions are not met, so it can be called even if the pair has been deactivated again before the
// simulation step started
}
bool ConstraintInteraction::onActivate(void*)
{
PX_ASSERT(!mConstraint->isBroken());
BodySim* b0 = mConstraint->getBody(0);
BodySim* b1 = mConstraint->getBody(1);
const bool b0Vote = !b0 || b0->isActive();
const bool b1Vote = !b1 || b1->isActive();
const bool b0Dynamic = b0 && (!b0->isKinematic());
const bool b1Dynamic = b1 && (!b1->isKinematic());
//
// note: constraints between kinematics and kinematics/statics are always inactive and must not be activated
//
if((b0Vote || b1Vote) && (b0Dynamic || b1Dynamic))
{
raiseInteractionFlag(InteractionFlag::eIS_ACTIVE);
if(mConstraint->readFlag(ConstraintSim::eBREAKABLE | ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED) == ConstraintSim::eBREAKABLE)
getScene().addActiveBreakableConstraint(mConstraint, this);
return true;
}
else
return false;
}
bool ConstraintInteraction::onDeactivate()
{
const BodySim* b0 = mConstraint->getBody(0);
const BodySim* b1 = mConstraint->getBody(1);
const bool b0Dynamic = b0 && (!b0->isKinematic());
const bool b1Dynamic = b1 && (!b1->isKinematic());
PX_ASSERT( (!b0 && b1 && !b1->isActive()) ||
(!b1 && b0 && !b0->isActive()) ||
((b0 && b1 && (!b0->isActive() || !b1->isActive()))) );
//
// note: constraints between kinematics and kinematics/statics should always get deactivated
//
if(((!b0 || !b0->isActive()) && (!b1 || !b1->isActive())) || (!b0Dynamic && !b1Dynamic))
{
removeFromActiveBreakableList(mConstraint, getScene());
clearInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
else
return false;
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorSim.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 SC_ACTOR_SIM_H
#define SC_ACTOR_SIM_H
#include "foundation/PxUserAllocated.h"
#include "CmPtrTable.h"
#include "CmUtils.h"
#include "PxActor.h"
#include "ScInteractionFlags.h"
#include "ScActorCore.h"
#include "PxsSimpleIslandManager.h"
#include "PxFiltering.h"
namespace physx
{
class PxActor;
namespace Sc
{
#define SC_NOT_IN_SCENE_INDEX 0xffffffff // the body is not in the scene yet
#define SC_NOT_IN_ACTIVE_LIST_INDEX 0xfffffffe // the body is in the scene but not in the active list
struct PxFilterObjectFlagEx : PxFilterObjectFlag
{
enum Enum
{
eRIGID_STATIC = eNEXT_FREE,
eRIGID_DYNAMIC = eNEXT_FREE<<1,
eNON_RIGID = eNEXT_FREE<<2,
eSOFTBODY = eNEXT_FREE<<3,
eFEMCLOTH = eNEXT_FREE<<4,
ePARTICLESYSTEM = eNEXT_FREE<<5,
eHAIRSYSTEM = eNEXT_FREE<<6,
eLAST = eHAIRSYSTEM
};
};
static const PxReal ScInternalWakeCounterResetValue = 20.0f*0.02f;
class Interaction;
class ElementSim;
class Scene;
class ShapeManager : public PxUserAllocated
{
public:
ShapeManager() {}
~ShapeManager() {}
PX_FORCE_INLINE PxU32 getNbElements() const
{
return mShapes.getCount();
}
PX_FORCE_INLINE ElementSim** getElements()
{
return reinterpret_cast<ElementSim**>(mShapes.getPtrs());
}
PX_FORCE_INLINE ElementSim*const* getElements() const
{
return reinterpret_cast<ElementSim*const*>(mShapes.getPtrs());
}
// void onElementAttach(ElementSim& element);
void onElementDetach(ElementSim& element);
Cm::PtrTable mShapes;
};
class ActorSim : public ShapeManager
{
friend class Scene; // the scene is allowed to set the scene array index
friend class Interaction;
PX_NOCOPY(ActorSim)
public:
enum InternalFlags
{
//BF_DISABLE_GRAVITY = 1 << 0, // Don't apply the scene's gravity
BF_HAS_STATIC_TOUCH = 1 << 1, // Set when a body is part of an island with static contacts. Needed to be able to recalculate adaptive force if this changes
BF_KINEMATIC_MOVED = 1 << 2, // Set when the kinematic was moved
BF_ON_DEATHROW = 1 << 3, // Set when the body is destroyed
BF_IS_IN_SLEEP_LIST = 1 << 4, // Set when the body is added to the list of bodies which were put to sleep
BF_IS_IN_WAKEUP_LIST = 1 << 5, // Set when the body is added to the list of bodies which were woken up
BF_SLEEP_NOTIFY = 1 << 6, // A sleep notification should be sent for this body (and not a wakeup event, even if the body is part of the woken list as well)
BF_WAKEUP_NOTIFY = 1 << 7, // A wake up notification should be sent for this body (and not a sleep event, even if the body is part of the sleep list as well)
BF_HAS_CONSTRAINTS = 1 << 8, // Set if the body has one or more constraints
BF_KINEMATIC_SETTLING = 1 << 9, // Set when the body was moved kinematically last frame
BF_KINEMATIC_SETTLING_2 = 1 << 10,
BF_KINEMATIC_MOVE_FLAGS = BF_KINEMATIC_MOVED | BF_KINEMATIC_SETTLING | BF_KINEMATIC_SETTLING_2, //Used to clear kinematic masks in 1 call
BF_KINEMATIC_SURFACE_VELOCITY = 1 << 11, //Set when the application calls setKinematicVelocity. Actor remains awake until application calls clearKinematicVelocity.
BF_IS_COMPOUND_RIGID = 1 << 12, // Set when the body is a compound actor, we dont want to set the sq bounds
// PT: WARNING: flags stored on 16-bits now.
};
ActorSim(Scene&, ActorCore&);
virtual ~ActorSim();
// Get the scene the actor resides in
PX_FORCE_INLINE Scene& getScene() const { return mScene; }
// Get the number of interactions connected to the actor
PX_FORCE_INLINE PxU32 getActorInteractionCount() const { return mInteractions.size(); }
// Get an iterator to the interactions connected to the actor
PX_FORCE_INLINE Interaction** getActorInteractions() const { return mInteractions.begin(); }
// Get the type ID of the actor
PX_FORCE_INLINE PxActorType::Enum getActorType() const { return mCore.getActorCoreType(); }
// Returns true if the actor is a dynamic rigid body (including articulation links)
PX_FORCE_INLINE PxU16 isDynamicRigid() const { return mFilterFlags & PxFilterObjectFlagEx::eRIGID_DYNAMIC; }
PX_FORCE_INLINE PxU16 isSoftBody() const { return mFilterFlags & PxFilterObjectFlagEx::eSOFTBODY; }
PX_FORCE_INLINE PxU16 isFEMCloth() const { return mFilterFlags & PxFilterObjectFlagEx::eFEMCLOTH; }
PX_FORCE_INLINE PxU16 isParticleSystem() const { return mFilterFlags & PxFilterObjectFlagEx::ePARTICLESYSTEM; }
PX_FORCE_INLINE PxU16 isHairSystem() const { return mFilterFlags & PxFilterObjectFlagEx::eHAIRSYSTEM; }
PX_FORCE_INLINE PxU16 isNonRigid() const { return mFilterFlags & PxFilterObjectFlagEx::eNON_RIGID; }
PX_FORCE_INLINE PxU16 isStaticRigid() const { return mFilterFlags & PxFilterObjectFlagEx::eRIGID_STATIC; }
virtual void postActorFlagChange(PxU32, PxU32) {}
void setActorsInteractionsDirty(InteractionDirtyFlag::Enum flag, const ActorSim* other, PxU8 interactionFlag);
PX_FORCE_INLINE ActorCore& getActorCore() const { return mCore; }
PX_FORCE_INLINE bool isActive() const { return (mActiveListIndex < SC_NOT_IN_ACTIVE_LIST_INDEX); }
PX_FORCE_INLINE PxU32 getActiveListIndex() const { return mActiveListIndex; } // if the body is active, the index is smaller than SC_NOT_IN_ACTIVE_LIST_INDEX
PX_FORCE_INLINE void setActiveListIndex(PxU32 index) { mActiveListIndex = index; }
PX_FORCE_INLINE PxU32 getActiveCompoundListIndex() const { return mActiveCompoundListIndex; } // if the body is active and is compound, the index is smaller than SC_NOT_IN_ACTIVE_LIST_INDEX
PX_FORCE_INLINE void setActiveCompoundListIndex(PxU32 index) { mActiveCompoundListIndex = index; }
PX_FORCE_INLINE PxNodeIndex getNodeIndex() const { return mNodeIndex; }
PX_FORCE_INLINE PxU32 getActorID() const { return mId; }
PX_FORCE_INLINE PxU16 getInternalFlag() const { return mInternalFlags; }
PX_FORCE_INLINE PxU16 readInternalFlag(InternalFlags flag) const { return PxU16(mInternalFlags & flag); }
PX_FORCE_INLINE void raiseInternalFlag(InternalFlags flag) { mInternalFlags |= flag; }
PX_FORCE_INLINE void clearInternalFlag(InternalFlags flag) { mInternalFlags &= ~flag; }
PX_FORCE_INLINE PxFilterObjectAttributes getFilterAttributes() const { return PxFilterObjectAttributes(mFilterFlags); }
virtual PxActor* getPxActor() const = 0;
//This can all be removed and functionality can be subsumed by the island system, removing the need for this
//virtual call and any associated work
virtual void registerCountedInteraction() {}
virtual void unregisterCountedInteraction() {}
virtual PxU32 getNumCountedInteractions() const { return 0; }
virtual void internalWakeUp(PxReal wakeCounterValue = ScInternalWakeCounterResetValue) { PX_UNUSED(wakeCounterValue); }
private:
//These are called from interaction creation/destruction
void registerInteractionInActor(Interaction* interaction);
void unregisterInteractionFromActor(Interaction* interaction);
void reallocInteractions(Sc::Interaction**& mem, PxU32& capacity, PxU32 size, PxU32 requiredMinCapacity);
protected:
// dsequeira: interaction arrays are a major cause of small allocations, so we don't want to delegate them to the heap allocator
// it's not clear this inline array is really needed, we should take it out and see whether the cache perf is worse
static const PxU32 INLINE_INTERACTION_CAPACITY = 4;
Interaction* mInlineInteractionMem[INLINE_INTERACTION_CAPACITY];
Cm::OwnedArray<Sc::Interaction*, Sc::ActorSim, PxU32, &Sc::ActorSim::reallocInteractions>
mInteractions;
Scene& mScene;
ActorCore& mCore;
// Sleeping
PxU32 mActiveListIndex; // Used by Scene to track active bodies
PxU32 mActiveCompoundListIndex; // Used by Scene to track active compound bodies
// Island manager
PxNodeIndex mNodeIndex;
PxU32 mId; // PT: ID provided by Sc::Scene::mActorIDTracker
PxU16 mInternalFlags;
PxU16 mFilterFlags; // PT: PxFilterObjectAttributes. Capturing the type information in local flags here is redundant
// but avoids reading the Core memory from the Sim object, and is also faster to test multiple types at once.
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeInteraction.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 SC_SHAPE_INTERACTION_H
#define SC_SHAPE_INTERACTION_H
#include "ScElementSimInteraction.h"
#include "ScShapeSim.h"
#include "ScActorPair.h"
#include "ScScene.h"
#include "ScBodySim.h"
#include "PxsContactManager.h"
#include "PxsContext.h"
#include "PxsSimpleIslandManager.h"
#define INVALID_REPORT_PAIR_ID 0xffffffff
namespace physx
{
static PX_FORCE_INLINE bool isParticleSystem(const PxActorType::Enum actorType)
{
return actorType == PxActorType::ePBD_PARTICLESYSTEM || actorType == PxActorType::eFLIP_PARTICLESYSTEM
|| actorType == PxActorType::eMPM_PARTICLESYSTEM;
}
class PxsContactManagerOutputIterator;
namespace Sc
{
class ContactReportAllocationManager;
/*
Description: A ShapeInteraction represents a pair of objects which _may_ have contacts. Created by the broadphase
and processed by the NPhaseCore.
*/
class ShapeInteraction : public ElementSimInteraction
{
friend class NPhaseCore;
ShapeInteraction& operator=(const ShapeInteraction&);
public:
enum SiFlag
{
PAIR_FLAGS_MASK = (PxPairFlag::eNEXT_FREE - 1), // Bits where the PxPairFlags get stored
NEXT_FREE = ((PAIR_FLAGS_MASK << 1) & ~PAIR_FLAGS_MASK),
HAS_TOUCH = (NEXT_FREE << 0), // Tracks the last know touch state
HAS_NO_TOUCH = (NEXT_FREE << 1), // Tracks the last know touch state
TOUCH_KNOWN = (HAS_TOUCH | HAS_NO_TOUCH), // If none of these flags is set, the touch state is not known (for example, this is true for pairs that never ran narrowphase
CONTACTS_COLLECT_POINTS = (NEXT_FREE << 2), // The user wants to get the contact points (includes debug rendering)
CONTACTS_RESPONSE_DISABLED = (NEXT_FREE << 3), // Collision response disabled (either by the user through PxPairFlag::eSOLVE_CONTACT or because the pair has two kinematics)
CONTACT_FORCE_THRESHOLD_PAIRS = PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST),
CONTACT_REPORT_EVENTS = PxU32(PxPairFlag::eNOTIFY_TOUCH_FOUND) | PxU32(PxPairFlag::eNOTIFY_TOUCH_PERSISTS) | PxU32(PxPairFlag::eNOTIFY_TOUCH_LOST) |
PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS) | PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST),
CONTACT_REPORT_EXTRA_DATA = PxU32(PxPairFlag::ePRE_SOLVER_VELOCITY) | PxU32(PxPairFlag::ePOST_SOLVER_VELOCITY) | PxU32(PxPairFlag::eCONTACT_EVENT_POSE),
FORCE_THRESHOLD_EXCEEDED_NOW = (NEXT_FREE << 4),
FORCE_THRESHOLD_EXCEEDED_BEFORE = (NEXT_FREE << 5),
FORCE_THRESHOLD_EXCEEDED_FLAGS = FORCE_THRESHOLD_EXCEEDED_NOW | FORCE_THRESHOLD_EXCEEDED_BEFORE,
IS_IN_PERSISTENT_EVENT_LIST = (NEXT_FREE << 6), // The pair is in the list of persistent contact events
WAS_IN_PERSISTENT_EVENT_LIST = (NEXT_FREE << 7), // The pair is inactive but used to be in the list of persistent contact events
IN_PERSISTENT_EVENT_LIST = IS_IN_PERSISTENT_EVENT_LIST | WAS_IN_PERSISTENT_EVENT_LIST,
IS_IN_FORCE_THRESHOLD_EVENT_LIST= (NEXT_FREE << 8), // The pair is in the list of force threshold contact events
IS_IN_CONTACT_EVENT_LIST = IS_IN_PERSISTENT_EVENT_LIST | IS_IN_FORCE_THRESHOLD_EVENT_LIST,
LL_MANAGER_RECREATE_EVENT = CONTACT_REPORT_EVENTS | CONTACTS_COLLECT_POINTS |
CONTACTS_RESPONSE_DISABLED | PxU32(PxPairFlag::eMODIFY_CONTACTS)
};
ShapeInteraction(ShapeSimBase& s1, ShapeSimBase& s2, PxPairFlags pairFlags, PxsContactManager* contactManager);
~ShapeInteraction();
// Submits to contact stream
void processUserNotification(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform,
PxsContactManagerOutputIterator& outputs); // ccdPass is 0 for discrete collision and then 1,2,... for the CCD passes
void processUserNotificationSync();
void processUserNotificationAsync(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform,
PxsContactManagerOutputIterator& outputs, ContactReportAllocationManager* alloc = NULL); // ccdPass is 0 for discrete collision and then 1,2,... for the CCD passes
void visualize( PxRenderOutput&, PxsContactManagerOutputIterator&,
float scale, float param_contactForce, float param_contactNormal, float param_contactError, float param_contactPoint
);
PxU32 getContactPointData(const void*& contactPatches, const void*& contactPoints, PxU32& contactDataSize, PxU32& contactPointCount, PxU32& patchCount, const PxReal*& impulses, PxU32 startOffset, PxsContactManagerOutputIterator& outputs);
bool managerLostTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs);
void managerNewTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs);
PX_FORCE_INLINE void adjustCountersOnLostTouch();
PX_FORCE_INLINE void adjustCountersOnNewTouch();
PX_FORCE_INLINE void sendCCDRetouch(PxU32 ccdPass, PxsContactManagerOutputIterator& outputs);
void setContactReportPostSolverVelocity(ContactStreamManager& cs);
PX_FORCE_INLINE void sendLostTouchReport(bool shapeVolumeRemoved, PxU32 ccdPass, PxsContactManagerOutputIterator& ouptuts);
void resetManagerCachedState() const;
PX_FORCE_INLINE ActorPair* getActorPair() const { return mActorPair; }
PX_FORCE_INLINE void setActorPair(ActorPair& aPair) { mActorPair = &aPair; }
PX_FORCE_INLINE void clearActorPair() { mActorPair = NULL; }
PX_FORCE_INLINE ActorPairReport& getActorPairReport() const { return ActorPairReport::cast(*mActorPair); }
PX_INLINE PxIntBool isReportPair() const { /*PX_ASSERT(!(PxIntBool(getPairFlags() & CONTACT_REPORT_EVENTS)) || mActorPair->isReportPair());*/ return PxIntBool(getPairFlags() & CONTACT_REPORT_EVENTS); }
PX_INLINE PxIntBool hasTouch() const { return readFlag(HAS_TOUCH); }
PX_INLINE PxIntBool hasCCDTouch() const { PX_ASSERT(mManager); return mManager->getHadCCDContact(); }
PX_INLINE void swapAndClearForceThresholdExceeded();
PX_FORCE_INLINE void raiseFlag(SiFlag flag) { mFlags |= flag; }
PX_FORCE_INLINE PxIntBool readFlag(SiFlag flag) const { return PxIntBool(mFlags & flag); }
PX_FORCE_INLINE PxU32 getPairFlags() const;
PX_FORCE_INLINE void removeFromReportPairList();
void onShapeChangeWhileSleeping(bool shapeOfDynamicChanged);
PX_FORCE_INLINE PxIntBool hasKnownTouchState() const;
bool onActivate(void* data);
bool onDeactivate();
void updateState(const PxU8 externalDirtyFlags);
const PxsContactManager* getContactManager() const { return mManager; }
void clearIslandGenData();
PX_FORCE_INLINE PxU32 getEdgeIndex() const { return mEdgeIndex; }
PX_FORCE_INLINE Sc::ShapeSimBase& getShape0() const { return static_cast<ShapeSimBase&>(getElement0()); }
PX_FORCE_INLINE Sc::ShapeSimBase& getShape1() const { return static_cast<ShapeSimBase&>(getElement1()); }
private:
ActorPair* mActorPair;
PxsContactManager* mManager;
PxU32 mContactReportStamp;
PxU32 mReportPairIndex; // Owned by NPhaseCore for its report pair list
PxU32 mEdgeIndex;
PxU16 mReportStreamIndex; // position of this pair in the contact report stream
void createManager(void* contactManager);
PX_INLINE bool updateManager(void* contactManager);
PX_INLINE void destroyManager();
PX_FORCE_INLINE bool activeManagerAllowed() const;
PX_FORCE_INLINE PxU32 getManagerContactState() const { return mFlags & LL_MANAGER_RECREATE_EVENT; }
PX_FORCE_INLINE void clearFlag(SiFlag flag) { mFlags &= ~flag; }
PX_INLINE void setFlag(SiFlag flag, bool value)
{
if (value)
raiseFlag(flag);
else
clearFlag(flag);
}
PX_FORCE_INLINE void setHasTouch() { clearFlag(HAS_NO_TOUCH); raiseFlag(HAS_TOUCH); }
PX_FORCE_INLINE void setHasNoTouch() { clearFlag(HAS_TOUCH); raiseFlag(HAS_NO_TOUCH); }
PX_FORCE_INLINE void setPairFlags(PxPairFlags flags);
PX_FORCE_INLINE void processReportPairOnActivate();
PX_FORCE_INLINE void processReportPairOnDeactivate();
// Certain SiFlag cache properties of the pair. If these properties change then the flags have to be updated.
// For example: is collision enabled for this pair? are contact points requested for this pair?
PX_FORCE_INLINE void updateFlags(const Sc::Scene&, const Sc::ActorSim&, const Sc::ActorSim&, const PxU32 pairFlags);
friend class Sc::Scene;
};
} // namespace Sc
// PT: TODO: is there a reason for force-inlining all that stuff?
PX_FORCE_INLINE void Sc::ShapeInteraction::sendLostTouchReport(bool shapeVolumeRemoved, PxU32 ccdPass, PxsContactManagerOutputIterator& outputs)
{
PX_ASSERT(hasTouch());
PX_ASSERT(isReportPair());
const PxU32 pairFlags = getPairFlags();
const PxU32 notifyTouchLost = pairFlags & PxU32(PxPairFlag::eNOTIFY_TOUCH_LOST);
const PxIntBool thresholdExceeded = readFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_NOW);
const PxU32 notifyThresholdLost = thresholdExceeded ? (pairFlags & PxU32(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST)) : 0;
if(!notifyTouchLost && !notifyThresholdLost)
return;
PxU16 infoFlag = 0;
if(mActorPair->getTouchCount() == 1) // this code assumes that the actor pair touch count does get decremented afterwards
infoFlag |= PxContactPairFlag::eACTOR_PAIR_LOST_TOUCH;
//Lost touch is processed after solver, so we should use the previous transform to update the pose for objects if user request eCONTACT_EVENT_POSE
const bool useCurrentTransform = false;
const PxU32 triggeredFlags = notifyTouchLost | notifyThresholdLost;
PX_ASSERT(triggeredFlags);
processUserNotification(triggeredFlags, infoFlag, true, ccdPass, useCurrentTransform, outputs);
if(shapeVolumeRemoved)
{
ActorPairReport& apr = getActorPairReport();
ContactStreamManager& cs = apr.getContactStreamManager();
cs.raiseFlags(ContactStreamManagerFlag::eTEST_FOR_REMOVED_SHAPES);
}
}
PX_FORCE_INLINE void Sc::ShapeInteraction::setPairFlags(PxPairFlags flags)
{
PX_ASSERT(PxU32(flags) < PxPairFlag::eNEXT_FREE); // to find out if a new PxPairFlag has been added after eLAST instead of in front
PxU32 newFlags = mFlags;
PxU32 fl = PxU32(flags) & PAIR_FLAGS_MASK;
newFlags &= (~PAIR_FLAGS_MASK); // clear old flags
newFlags |= fl;
mFlags = newFlags;
}
// PT: returning PxU32 instead of PxPairFlags to remove LHS. Please do not undo this.
PX_FORCE_INLINE PxU32 Sc::ShapeInteraction::getPairFlags() const
{
return (mFlags & PAIR_FLAGS_MASK);
}
PX_INLINE void Sc::ShapeInteraction::swapAndClearForceThresholdExceeded()
{
PxU32 flags = mFlags;
PX_COMPILE_TIME_ASSERT(FORCE_THRESHOLD_EXCEEDED_NOW == (FORCE_THRESHOLD_EXCEEDED_BEFORE >> 1));
PxU32 nowToBefore = (flags & FORCE_THRESHOLD_EXCEEDED_NOW) << 1;
flags &= ~(FORCE_THRESHOLD_EXCEEDED_NOW | FORCE_THRESHOLD_EXCEEDED_BEFORE);
flags |= nowToBefore;
mFlags = flags;
}
PX_FORCE_INLINE void Sc::ShapeInteraction::removeFromReportPairList()
{
// this method should only get called if the pair is in the list for
// persistent or force based contact reports
PX_ASSERT(mReportPairIndex != INVALID_REPORT_PAIR_ID);
PX_ASSERT(readFlag(IS_IN_CONTACT_EVENT_LIST));
Scene& scene = getScene();
if (readFlag(IS_IN_FORCE_THRESHOLD_EVENT_LIST))
scene.getNPhaseCore()->removeFromForceThresholdContactEventPairs(this);
else
{
PX_ASSERT(readFlag(IS_IN_PERSISTENT_EVENT_LIST));
scene.getNPhaseCore()->removeFromPersistentContactEventPairs(this);
}
}
PX_INLINE bool Sc::ShapeInteraction::updateManager(void* contactManager)
{
if (activeManagerAllowed())
{
if (mManager == 0)
createManager(contactManager);
return (mManager != NULL); // creation might fail (pool reached limit, mem allocation failed etc.)
}
else
return false;
}
PX_INLINE void Sc::ShapeInteraction::destroyManager()
{
PX_ASSERT(mManager);
Scene& scene = getScene();
PxvNphaseImplementationContext* nphaseImplementationContext = scene.getLowLevelContext()->getNphaseImplementationContext();
PX_ASSERT(nphaseImplementationContext);
nphaseImplementationContext->unregisterContactManager(mManager);
/*if (mEdgeIndex != IG_INVALID_EDGE)
scene.getSimpleIslandManager()->clearEdgeRigidCM(mEdgeIndex);*/
scene.getLowLevelContext()->destroyContactManager(mManager);
mManager = 0;
}
PX_FORCE_INLINE bool Sc::ShapeInteraction::activeManagerAllowed() const
{
ShapeSimBase& shape0 = getShape0();
ShapeSimBase& shape1 = getShape1();
ActorSim& bodySim0 = shape0.getActor();
ActorSim& bodySim1 = shape1.getActor();
// the first shape always belongs to a dynamic body or soft body
#if PX_SUPPORT_GPU_PHYSX
PX_ASSERT(bodySim0.isDynamicRigid() || bodySim0.isSoftBody() || bodySim0.isFEMCloth() || bodySim0.isParticleSystem() || bodySim0.isHairSystem());
#else
PX_ASSERT(bodySim0.isDynamicRigid());
#endif
// PT: try to prevent https://omniverse-jirasw.nvidia.com/browse/OM-103695
if(!bodySim0.getNodeIndex().isValid())
return false;
const IG::IslandSim& islandSim = getScene().getSimpleIslandManager()->getSpeculativeIslandSim();
//check whether active in the speculative sim!
return (islandSim.getNode(bodySim0.getNodeIndex()).isActive() ||
(!bodySim1.isStaticRigid() && islandSim.getNode(bodySim1.getNodeIndex()).isActive()));
}
PX_FORCE_INLINE void Sc::ShapeInteraction::sendCCDRetouch(PxU32 ccdPass, PxsContactManagerOutputIterator& outputs)
{
const PxU32 pairFlags = getPairFlags();
if (pairFlags & PxPairFlag::eNOTIFY_TOUCH_CCD)
processUserNotification(PxPairFlag::eNOTIFY_TOUCH_CCD, 0, false, ccdPass, false, outputs);
}
PX_FORCE_INLINE void Sc::ShapeInteraction::adjustCountersOnLostTouch()
{
PX_ASSERT(mActorPair->getTouchCount());
mActorPair->decTouchCount();
}
PX_FORCE_INLINE void Sc::ShapeInteraction::adjustCountersOnNewTouch()
{
mActorPair->incTouchCount();
}
PX_FORCE_INLINE PxIntBool Sc::ShapeInteraction::hasKnownTouchState() const
{
// For a pair where the bodies were added asleep, the touch state is not known until narrowphase runs on the pair for the first time.
// If such a pair looses AABB overlap before, the conservative approach is to wake the bodies up. This method provides an indicator that
// this is such a pair. Note: this might also wake up objects that do not touch but that's the price to pay (unless we want to run
// overlap tests on such pairs).
if (mManager)
return mManager->touchStatusKnown();
else
return readFlag(TOUCH_KNOWN);
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintCore.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 "ScConstraintCore.h"
#include "ScPhysics.h"
#include "ScConstraintSim.h"
using namespace physx;
Sc::ConstraintCore::ConstraintCore(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) :
mFlags (PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES),
mIsDirty (1),
mAppliedForce (PxVec3(0.0f)),
mAppliedTorque (PxVec3(0.0f)),
mConnector (&connector),
mSolverPrep (shaders.solverPrep),
mVisualize (shaders.visualize),
mDataSize (dataSize),
mLinearBreakForce (PX_MAX_F32),
mAngularBreakForce (PX_MAX_F32),
mMinResponseThreshold (0.0f),
mSim (NULL)
{
}
void Sc::ConstraintCore::setFlags(PxConstraintFlags flags)
{
PxConstraintFlags old = mFlags;
flags = flags | (old & PxConstraintFlag::eGPU_COMPATIBLE);
if(flags != old)
{
mFlags = flags;
if(mSim)
mSim->postFlagChange(old, flags);
}
}
void Sc::ConstraintCore::getForce(PxVec3& force, PxVec3& torque) const
{
if(!mSim)
{
force = PxVec3(0.0f);
torque = PxVec3(0.0f);
}
else
mSim->getForce(force, torque);
}
void Sc::ConstraintCore::setBodies(RigidCore* r0v, RigidCore* r1v)
{
if(mSim)
mSim->setBodies(r0v, r1v);
}
void Sc::ConstraintCore::setBreakForce(PxReal linear, PxReal angular)
{
mLinearBreakForce = linear;
mAngularBreakForce = angular;
if(mSim)
mSim->setBreakForceLL(linear, angular);
}
void Sc::ConstraintCore::setMinResponseThreshold(PxReal threshold)
{
mMinResponseThreshold = threshold;
if(mSim)
mSim->setMinResponseThresholdLL(threshold);
}
PxConstraint* Sc::ConstraintCore::getPxConstraint()
{
return gOffsetTable.convertScConstraint2Px(this);
}
const PxConstraint* Sc::ConstraintCore::getPxConstraint() const
{
return gOffsetTable.convertScConstraint2Px(this);
}
void Sc::ConstraintCore::breakApart()
{
// TODO: probably want to do something with the interaction here
// as well as remove the constraint from LL.
mFlags |= PxConstraintFlag::eBROKEN;
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationJointSim.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 SC_ARTICULATION_JOINT_SIM_H
#define SC_ARTICULATION_JOINT_SIM_H
#include "ScInteraction.h"
namespace physx
{
namespace Sc
{
class ArticulationJointCore;
class BodySim;
class ArticulationJointSim : public Interaction
{
PX_NOCOPY(ArticulationJointSim)
public:
ArticulationJointSim(ArticulationJointCore& joint, ActorSim& parent, ActorSim& child);
~ArticulationJointSim();
bool onActivate(void*);
bool onDeactivate();
PX_FORCE_INLINE ArticulationJointCore& getCore() const { return mCore; }
BodySim& getParent() const;
BodySim& getChild() const;
void setDirty();
private:
ArticulationJointCore& mCore;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBodyCore.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 "ScBodyCore.h"
#include "ScBodySim.h"
#include "ScPhysics.h"
#include "ScScene.h"
#include "PxsSimulationController.h"
#include "ScArticulationSim.h"
using namespace physx;
static void updateBodySim(Sc::BodyCore& bodyCore)
{
Sc::BodySim* bodySim = bodyCore.getSim();
if(bodySim)
bodySim->getScene().updateBodySim(*bodySim);
}
Sc::BodyCore::BodyCore(PxActorType::Enum type, const PxTransform& bodyPose) : RigidCore(type)
{
const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale();
const bool isDynamic = type == PxActorType::eRIGID_DYNAMIC;
const float linearDamping = isDynamic ? 0.0f : 0.05f;
const float maxLinearVelocitySq = isDynamic ? 1e32f /*PX_MAX_F32*/ : 100.f * 100.f * scale.length * scale.length;
const float maxAngularVelocitySq = isDynamic ? 100.0f * 100.0f : 50.0f * 50.0f;
mCore.init(bodyPose, PxVec3(1.0f), 1.0f, Sc::Physics::sWakeCounterOnCreation, scale.speed, linearDamping, 0.05f, maxLinearVelocitySq, maxAngularVelocitySq,
type);
}
Sc::BodyCore::~BodyCore()
{
PX_ASSERT(getSim() == 0);
}
Sc::BodySim* Sc::BodyCore::getSim() const
{
return static_cast<BodySim*>(Sc::ActorCore::getSim());
}
void Sc::BodyCore::restoreDynamicData()
{
BodySim* sim = getSim();
PX_ASSERT(sim);
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PxsBodyCore& core = getCore();
simStateRestoreBodyProperties(simStateData, core);
}
//--------------------------------------------------------------
//
// BodyCore interface implementation
//
//--------------------------------------------------------------
void Sc::BodyCore::setBody2World(const PxTransform& p)
{
mCore.body2World = p;
PX_ASSERT(p.p.isFinite());
PX_ASSERT(p.q.isFinite());
BodySim* sim = getSim();
if(sim)
{
sim->postBody2WorldChange();
sim->getScene().updateBodySim(*sim);
}
}
void Sc::BodyCore::setCMassLocalPose(const PxTransform& newBody2Actor)
{
const PxTransform oldActor2World = mCore.body2World * mCore.getBody2Actor().getInverse();
const PxTransform newBody2World = oldActor2World * newBody2Actor;
PX_ASSERT(newBody2World.p.isFinite());
PX_ASSERT(newBody2World.q.isFinite());
mCore.body2World = newBody2World;
setBody2Actor(newBody2Actor);
}
void Sc::BodyCore::setLinearVelocity(const PxVec3& v, bool skipBodySimUpdate)
{
mCore.linearVelocity = v;
PX_ASSERT(!skipBodySimUpdate || (getFlags() & PxRigidBodyFlag::eKINEMATIC));
if(!skipBodySimUpdate)
updateBodySim(*this);
}
void Sc::BodyCore::setAngularVelocity(const PxVec3& v, bool skipBodySimUpdate)
{
mCore.angularVelocity = v;
PX_ASSERT(!skipBodySimUpdate || (getFlags() & PxRigidBodyFlag::eKINEMATIC));
if(!skipBodySimUpdate)
updateBodySim(*this);
}
void Sc::BodyCore::setCfmScale(PxReal cfmScale)
{
mCore.cfmScale = cfmScale;
updateBodySim(*this);
}
void Sc::BodyCore::setBody2Actor(const PxTransform& p)
{
PX_ASSERT(p.p.isFinite());
PX_ASSERT(p.q.isFinite());
mCore.setBody2Actor(p);
updateBodySim(*this);
}
void Sc::BodyCore::addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc)
{
BodySim* sim = getSim();
PX_ASSERT(sim);
sim->addSpatialAcceleration(linAcc, angAcc);
}
void Sc::BodyCore::setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc)
{
BodySim* sim = getSim();
PX_ASSERT(sim);
sim->setSpatialAcceleration(linAcc, angAcc);
}
void Sc::BodyCore::clearSpatialAcceleration(bool force, bool torque)
{
PX_ASSERT(force || torque);
BodySim* sim = getSim();
PX_ASSERT(sim);
sim->clearSpatialAcceleration(force, torque);
}
void Sc::BodyCore::addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta)
{
BodySim* sim = getSim();
PX_ASSERT(sim);
sim->addSpatialVelocity(linVelDelta, angVelDelta);
}
void Sc::BodyCore::clearSpatialVelocity(bool force, bool torque)
{
PX_ASSERT(force || torque);
BodySim* sim = getSim();
PX_ASSERT(sim);
sim->clearSpatialVelocity(force, torque);
}
PxReal Sc::BodyCore::getInverseMass() const
{
BodySim* sim = getSim();
if(!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
return mCore.inverseMass;
}
else
{
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
return simStateData->getKinematicData()->backupInvMass;
}
}
void Sc::BodyCore::setInverseMass(PxReal m)
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
mCore.inverseMass = m;
updateBodySim(*this);
}
else
{
SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
simStateData->getKinematicData()->backupInvMass = m;
}
}
const PxVec3& Sc::BodyCore::getInverseInertia() const
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
return mCore.inverseInertia;
}
else
{
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
return (simStateData->getKinematicData()->backupInverseInertia);
}
}
void Sc::BodyCore::setInverseInertia(const PxVec3& i)
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
mCore.inverseInertia = i;
updateBodySim(*this);
}
else
{
SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
simStateData->getKinematicData()->backupInverseInertia = i;
}
}
PxReal Sc::BodyCore::getLinearDamping() const
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
return mCore.linearDamping;
}
else
{
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
return (simStateData->getKinematicData()->backupLinearDamping);
}
}
void Sc::BodyCore::setLinearDamping(PxReal d)
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
mCore.linearDamping = d;
updateBodySim(*this);
}
else
{
SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
simStateData->getKinematicData()->backupLinearDamping = d;
}
}
PxReal Sc::BodyCore::getAngularDamping() const
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
return mCore.angularDamping;
}
else
{
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
return (simStateData->getKinematicData()->backupAngularDamping);
}
}
void Sc::BodyCore::setAngularDamping(PxReal v)
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
mCore.angularDamping = v;
updateBodySim(*this);
}
else
{
SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
simStateData->getKinematicData()->backupAngularDamping = v;
}
}
PxReal Sc::BodyCore::getMaxAngVelSq() const
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
return mCore.maxAngularVelocitySq;
}
else
{
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
return (simStateData->getKinematicData()->backupMaxAngVelSq);
}
}
void Sc::BodyCore::setMaxAngVelSq(PxReal v)
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
mCore.maxAngularVelocitySq = v;
updateBodySim(*this);
}
else
{
SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
simStateData->getKinematicData()->backupMaxAngVelSq = v;
}
}
PxReal Sc::BodyCore::getMaxLinVelSq() const
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
return mCore.maxLinearVelocitySq;
}
else
{
const SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
return (simStateData->getKinematicData()->backupMaxLinVelSq);
}
}
void Sc::BodyCore::setMaxLinVelSq(PxReal v)
{
BodySim* sim = getSim();
if (!sim || (!(getFlags() & PxRigidBodyFlag::eKINEMATIC)))
{
mCore.maxLinearVelocitySq = v;
updateBodySim(*this);
}
else
{
SimStateData* simStateData = sim->getSimStateData(true);
PX_ASSERT(simStateData);
PX_ASSERT(simStateData->getKinematicData());
simStateData->getKinematicData()->backupMaxLinVelSq = v;
}
}
void Sc::BodyCore::setFlags(PxRigidBodyFlags f)
{
const PxRigidBodyFlags old = mCore.mFlags;
if(f != old)
{
const PxU32 wasKinematic = old & PxRigidBodyFlag::eKINEMATIC;
const PxU32 isKinematic = f & PxRigidBodyFlag::eKINEMATIC;
const bool switchToKinematic = ((!wasKinematic) && isKinematic);
const bool switchToDynamic = (wasKinematic && (!isKinematic));
mCore.mFlags = f;
BodySim* sim = getSim();
if (sim)
{
const PxU32 posePreviewFlag = f & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW;
if(PxU32(old & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW) != posePreviewFlag)
sim->postPosePreviewChange(posePreviewFlag);
// for those who might wonder about the complexity here:
// our current behavior is that you are not allowed to set a kinematic target unless the object is in a scene.
// Thus, the kinematic data should only be created/destroyed when we know for sure that we are in a scene.
if(switchToKinematic)
sim->switchToKinematic();
else if(switchToDynamic)
sim->switchToDynamic();
const PxU32 wasSpeculativeCCD = old & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD;
const PxU32 isSpeculativeCCD = f & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD;
if(wasSpeculativeCCD ^ isSpeculativeCCD)
{
if(wasSpeculativeCCD)
{
sim->removeFromSpeculativeCCDMap();
sim->getLowLevelBody().mInternalFlags &= (~PxsRigidBody::eSPECULATIVE_CCD);
}
else
{
//Kinematic body switch puts the body to sleep, so we do not mark the speculative CCD bitmap for this actor to true in this case.
if(!switchToKinematic)
sim->addToSpeculativeCCDMap();
sim->getLowLevelBody().mInternalFlags |= (PxsRigidBody::eSPECULATIVE_CCD);
}
}
const PxU32 wasIntegrateGyroscopic = old & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES;
const PxU32 isIntegrateGyroscopic = f & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES;
if (wasIntegrateGyroscopic ^ isIntegrateGyroscopic)
{
if(wasIntegrateGyroscopic)
sim->getLowLevelBody().mInternalFlags &= (PxsRigidBody::eENABLE_GYROSCOPIC);
else
sim->getLowLevelBody().mInternalFlags |= (PxsRigidBody::eENABLE_GYROSCOPIC);
}
const PxU32 wasRetainAccel = old & PxRigidBodyFlag::eRETAIN_ACCELERATIONS;
const PxU32 isRetainAccel = f & PxRigidBodyFlag::eRETAIN_ACCELERATIONS;
if (wasRetainAccel ^ isRetainAccel)
{
if (wasRetainAccel)
sim->getLowLevelBody().mInternalFlags &= (PxsRigidBody::eRETAIN_ACCELERATION);
else
sim->getLowLevelBody().mInternalFlags |= (PxsRigidBody::eRETAIN_ACCELERATION);
}
//Force flag change through...
sim->getScene().updateBodySim(*sim);
}
if(switchToKinematic)
putToSleep();
if(sim)
{
const PxRigidBodyFlags ktFlags(PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES | PxRigidBodyFlag::eKINEMATIC);
const bool hadKt = (old & ktFlags) == ktFlags;
const bool hasKt = (f & ktFlags) == ktFlags;
if(hasKt && !hadKt)
sim->destroySqBounds();
else if(hadKt && !hasKt)
sim->createSqBounds();
}
}
}
void Sc::BodyCore::setMaxContactImpulse(PxReal m)
{
mCore.maxContactImpulse = m;
updateBodySim(*this);
}
void Sc::BodyCore::setOffsetSlop(PxReal slop)
{
mCore.offsetSlop = slop;
updateBodySim(*this);
}
PxNodeIndex Sc::BodyCore::getInternalIslandNodeIndex() const
{
BodySim* sim = getSim();
return sim ? sim->getNodeIndex() : PxNodeIndex(PX_INVALID_NODE);
}
void Sc::BodyCore::setWakeCounter(PxReal wakeCounter, bool forceWakeUp)
{
mCore.wakeCounter = wakeCounter;
BodySim* sim = getSim();
if(sim)
{
//wake counter change, we need to trigger dma pxgbodysim data again
sim->getScene().updateBodySim(*sim);
if ((wakeCounter > 0.0f) || forceWakeUp)
sim->wakeUp();
sim->postSetWakeCounter(wakeCounter, forceWakeUp);
}
}
void Sc::BodyCore::setSleepThreshold(PxReal t)
{
mCore.sleepThreshold = t;
updateBodySim(*this);
}
void Sc::BodyCore::setFreezeThreshold(PxReal t)
{
mCore.freezeThreshold = t;
updateBodySim(*this);
}
bool Sc::BodyCore::isSleeping() const
{
BodySim* sim = getSim();
return sim ? !sim->isActive() : true;
}
void Sc::BodyCore::putToSleep()
{
mCore.linearVelocity = PxVec3(0.0f);
mCore.angularVelocity = PxVec3(0.0f);
// important to clear all values before setting the wake counter because the values decide
// whether an object is ready to go to sleep or not.
setWakeCounter(0.0f);
BodySim* sim = getSim();
if(sim)
sim->putToSleep();
}
void Sc::BodyCore::onOriginShift(const PxVec3& shift)
{
mCore.body2World.p -= shift;
BodySim* b = getSim();
if(b)
b->onOriginShift(shift, getFlags() & PxRigidBodyFlag::eKINEMATIC); // BodySim might not exist if actor has simulation disabled (PxActorFlag::eDISABLE_SIMULATION)
}
// PT: TODO: why do we test againt NULL everywhere but not in 'isFrozen' ?
PxIntBool Sc::BodyCore::isFrozen() const
{
return getSim()->isFrozen();
}
void Sc::BodyCore::setSolverIterationCounts(PxU16 c)
{
mCore.solverIterationCounts = c;
Sc::BodySim* sim = getSim();
if (sim)
{
sim->getLowLevelBody().solverIterationCounts = c;
sim->getScene().setDynamicsDirty();
}
}
///////////////////////////////////////////////////////////////////////////////
bool Sc::BodyCore::getKinematicTarget(PxTransform& p) const
{
PX_ASSERT(mCore.mFlags & PxRigidBodyFlag::eKINEMATIC);
const BodySim* sim = getSim();
return (sim && simStateGetKinematicTarget(sim->getSimStateData_Unchecked(), p));
}
bool Sc::BodyCore::getHasValidKinematicTarget() const
{
//The use pattern for this is that we should only look for kinematic data if we know it is kinematic.
//We might look for velmod data even if it is kinematic.
BodySim* sim = getSim();
return (sim && simStateGetHasValidKinematicTarget(sim->getSimStateData_Unchecked()));
}
void Sc::BodyCore::setKinematicTarget(const PxTransform& p, PxReal wakeCounter)
{
PX_ASSERT(mCore.mFlags & PxRigidBodyFlag::eKINEMATIC);
Sc::BodySim* sim = getSim();
PX_ASSERT(sim);
sim->setKinematicTarget(p);
wakeUp(wakeCounter);
}
void Sc::BodyCore::invalidateKinematicTarget()
{
Sc::BodySim* sim = getSim();
PX_ASSERT(sim);
simStateInvalidateKinematicTarget(sim->getSimStateData_Unchecked());
}
void Sc::BodyCore::setFixedBaseLink(bool value)
{
BodySim* sim = getSim();
if(sim)
sim->getLowLevelBody().mCore->fixedBaseLink = PxU8(value);
}
void Sc::BodyCore::onRemoveKinematicFromScene()
{
PX_ASSERT(mCore.mFlags & PxRigidBodyFlag::eKINEMATIC);
PX_ASSERT(getSim() && getSim()->checkSimStateKinematicStatus(true));
// make sure that a kinematic which is not part of a scene is in the expected state
mCore.wakeCounter = 0.0f;
mCore.linearVelocity = PxVec3(0.0f);
mCore.angularVelocity = PxVec3(0.0f);
}
///////////////////////////////////////////////////////////////////////////////
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSim.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 SC_ARTICULATION_SIM_H
#define SC_ARTICULATION_SIM_H
#include "foundation/PxUserAllocated.h"
#include "ScArticulationCore.h"
#include "PxsSimpleIslandManager.h"
#include "DyArticulationTendon.h"
namespace physx
{
namespace Bp
{
class BoundsArray;
}
namespace Sc
{
class BodySim;
class BodyCore;
class ArticulationJointSim;
class ArticulationSpatialTendonSim;
class ArticulationFixedTendonSim;
class ArticulationSensorSim;
class ArticulationCore;
class Scene;
class ConstraintSim;
struct ArticulationSimDirtyFlag
{
enum Enum
{
eNONE = 0,
eUPDATE = 1 << 0
};
};
typedef PxFlags<ArticulationSimDirtyFlag::Enum, PxU32> ArticulationSimDirtyFlags;
class ArticulationSim : public PxUserAllocated
{
PX_NOCOPY(ArticulationSim)
public:
ArticulationSim(ArticulationCore& core,
Scene& scene,
BodyCore& root);
~ArticulationSim();
PX_FORCE_INLINE Dy::FeatherstoneArticulation* getLowLevelArticulation() const { return mLLArticulation; }
PX_FORCE_INLINE ArticulationCore& getCore() const { return mCore; }
//we don't need removeBody method anymore because when the articulation is removed from the scene, the articulation sim will
//get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed
void addBody(BodySim& body,
BodySim* parent,
ArticulationJointSim* joint);
void removeBody(BodySim& body);
//we don't need removeTendon method anymore because when the articulation is removed from the scene, the articulation sim will
//get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed
void addTendon(ArticulationSpatialTendonSim*);
//we don't need removeTendon method anymore because when the articulation is removed from the scene, the articulation sim will
//get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed
void addTendon(ArticulationFixedTendonSim*);
//we don't need removeSensor method anymore because when the articulation is removed from the scene, the articulation sim will
//get completely distroy and when we re-add the articulation to the scene, all the data will get recomputed
void addSensor(ArticulationSensorSim* sensor, const PxU32 linkID);
void createLLStructure(); // resize LL memory if necessary
void initializeConfiguration();
void debugCheckWakeCounterOfLinks(PxReal wakeCounter) const;
void debugCheckSleepStateOfLinks(bool isSleeping) const;
bool isSleeping() const;
void internalWakeUp(PxReal wakeCounter); // called when sim sets sleep timer
void sleepCheck(PxReal dt);
void putToSleep();
void updateCCDLinks(PxArray<BodySim*>& sims);
void updateCached(PxBitMapPinned* shapehapeChangedMap);
void markShapesUpdated(PxBitMapPinned* shapeChangedMap);
void updateContactDistance(PxReal* contactDistance, PxReal dt, const Bp::BoundsArray& boundsArray);
void setActive(bool b, bool asPartOfCreation=false);
void updateForces(PxReal dt);
void saveLastCCDTransform();
void clearAcceleration(PxReal dt);
void setFixedBaseLink(bool value);
//external reduced coordinate implementation
PxU32 getDofs() const;
//This function return the dof of the inbound joint, which belong to a link with corresponding linkID
PxU32 getDof(const PxU32 linkID) const;
PxArticulationCache* createCache();
PxU32 getCacheDataSize() const;
void zeroCache(PxArticulationCache&) const;
bool applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag) const;
void copyInternalStateToCache
(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const;
void packJointData(const PxReal* maximum, PxReal* reduced) const;
void unpackJointData(const PxReal* reduced, PxReal* maximum) const;
void commonInit();
void computeGeneralizedGravityForce(PxArticulationCache& cache);
void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache);
void computeGeneralizedExternalForce(PxArticulationCache& cache);
void computeJointAcceleration(PxArticulationCache& cache);
void computeJointForce(PxArticulationCache& cache);
void computeKinematicJacobian(const PxU32 linkID, PxArticulationCache& cache);
void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols);
void computeCoefficientMatrix(PxArticulationCache& cache);
bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* jointTorque, const PxVec3 gravity, const PxU32 maxIter);
void computeGeneralizedMassMatrix(PxArticulationCache& cache);
PxU32 getCoefficientMatrixSize() const;
void setRootLinearVelocity(const PxVec3& velocity);
void setRootAngularVelocity(const PxVec3& velocity);
PxSpatialVelocity getLinkVelocity(const PxU32 linkId) const;
PxSpatialVelocity getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const;
//internal method implementation
PX_FORCE_INLINE PxNodeIndex getIslandNodeIndex() const { return mIslandNodeIndex; }
void setGlobalPose();
PxU32 findBodyIndex(BodySim &body) const;
void setJointDirty(Dy::ArticulationJointCore& jointCore);
void addLoopConstraint(ConstraintSim* constraint);
void removeLoopConstraint(ConstraintSim* constraint);
PX_FORCE_INLINE PxU32 getMaxDepth() { return mMaxDepth; }
void setArticulationDirty(PxU32 flag);
PX_FORCE_INLINE void setDirtyFlag(ArticulationSimDirtyFlag::Enum flag) { mDirtyFlags = flag; }
PX_FORCE_INLINE ArticulationSimDirtyFlags getDirtyFlag() const { return mDirtyFlags; }
PX_FORCE_INLINE const Dy::ArticulationLink& getLink(const PxU32 linkId) const { return mLinks[linkId]; }
PxU32 getRootActorIndex() const;
const PxSpatialForce& getSensorForce(const PxU32 lowLevelIndex) const;
void updateKinematic(PxArticulationKinematicFlags flags);
void copyJointStatus(const PxU32 linkIndex);
PX_FORCE_INLINE void getLLArticulationInitialized(bool val) { mIsLLArticulationInitialized = val; }
PX_FORCE_INLINE bool getLLArticulationInitialized() { return mIsLLArticulationInitialized; }
private:
Dy::FeatherstoneArticulation* mLLArticulation;
Scene& mScene;
ArticulationCore& mCore;
PxArray<Dy::ArticulationLink> mLinks;
PxArray<BodySim*> mBodies;
PxArray<ArticulationJointSim*> mJoints;
PxArray<Dy::ArticulationSpatialTendon*> mSpatialTendons;
PxArray<Dy::ArticulationFixedTendon*> mFixedTendons;
PxArray<Dy::ArticulationSensor*> mSensors;
PxArray<PxSpatialForce> mSensorForces;
PxNodeIndex mIslandNodeIndex;
PxArray <Dy::ArticulationLoopConstraint> mLoopConstraints;
PxU32 mMaxDepth;
bool mIsLLArticulationInitialized;
ArticulationSimDirtyFlags mDirtyFlags;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimStateData.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 SC_SIM_STATE_DATA_H
#define SC_SIM_STATE_DATA_H
#include "foundation/PxMemory.h"
#include "ScBodyCore.h"
namespace physx
{
namespace Sc
{
struct KinematicTransform
{
PxTransform targetPose; // The body will move to this pose over the superstep following this getting set.
PxU8 targetValid; // User set a kinematic target.
PxU8 pad[2];
PxU8 type;
};
struct Kinematic : public KinematicTransform
{
// The following members buffer the original body data to restore them when switching back to dynamic body
// (for kinematics the corresponding LowLevel properties are set to predefined values)
PxVec3 backupInverseInertia; // The inverse of the body space inertia tensor
PxReal backupInvMass; // The inverse of the body mass
PxReal backupLinearDamping; // The velocity is scaled by (1.0f - this * dt) inside integrateVelocity() every substep.
PxReal backupAngularDamping;
PxReal backupMaxAngVelSq; // The angular velocity's magnitude is clamped to this maximum value.
PxReal backupMaxLinVelSq; // The angular velocity's magnitude is clamped to this maximum value
};
PX_COMPILE_TIME_ASSERT(0 == (sizeof(Kinematic) & 0x0f));
enum VelocityModFlags
{
VMF_GRAVITY_DIRTY = (1 << 0),
VMF_ACC_DIRTY = (1 << 1),
VMF_VEL_DIRTY = (1 << 2)
};
// Important: Struct is reset in setForcesToDefaults.
struct VelocityMod
{
PxVec3 linearPerSec; // A request to change the linear velocity by this much each second. The velocity is changed by this * dt inside integrateVelocity().
PxU8 pad0[4];
PxVec3 angularPerSec;
PxU8 pad1[3];
PxU8 type;
PxVec3 linearPerStep; // A request to change the linear velocity by this much the next step. The velocity is changed inside updateForces().
PxU32 pad2;
PxVec3 angularPerStep;
PxU32 pad3;
PX_FORCE_INLINE void clear() { linearPerSec = angularPerSec = linearPerStep = angularPerStep = PxVec3(0.0f); }
PX_FORCE_INLINE void clearPerStep() { linearPerStep = angularPerStep = PxVec3(0.0f); }
PX_FORCE_INLINE const PxVec3& getLinearVelModPerSec() const { return linearPerSec; }
PX_FORCE_INLINE void accumulateLinearVelModPerSec(const PxVec3& v) { linearPerSec += v; }
PX_FORCE_INLINE void setLinearVelModPerSec(const PxVec3& v) { linearPerSec = v; }
PX_FORCE_INLINE void clearLinearVelModPerSec() { linearPerSec = PxVec3(0.0f); }
PX_FORCE_INLINE const PxVec3& getLinearVelModPerStep() const { return linearPerStep; }
PX_FORCE_INLINE void accumulateLinearVelModPerStep(const PxVec3& v) { linearPerStep += v; }
PX_FORCE_INLINE void clearLinearVelModPerStep() { linearPerStep = PxVec3(0.0f); }
PX_FORCE_INLINE const PxVec3& getAngularVelModPerSec() const { return angularPerSec; }
PX_FORCE_INLINE void accumulateAngularVelModPerSec(const PxVec3& v) { angularPerSec += v; }
PX_FORCE_INLINE void setAngularVelModPerSec(const PxVec3& v) { angularPerSec = v; }
PX_FORCE_INLINE void clearAngularVelModPerSec() { angularPerSec = PxVec3(0.0f); }
PX_FORCE_INLINE const PxVec3& getAngularVelModPerStep() const { return angularPerStep; }
PX_FORCE_INLINE void accumulateAngularVelModPerStep(const PxVec3& v) { angularPerStep += v; }
PX_FORCE_INLINE void clearAngularVelModPerStep() { angularPerStep = PxVec3(0.0f); }
};
PX_COMPILE_TIME_ASSERT(sizeof(VelocityMod) == sizeof(Kinematic));
// Structure to store data either for kinematics (target pose etc.) or for dynamics (vel and accel changes).
// note: we do not delete this object for kinematics even if no target is set.
struct SimStateData : public PxUserAllocated // TODO: may want to optimize the allocation of this further.
{
PxU8 data[sizeof(Kinematic)];
enum Enum
{
eVelMod=0,
eKine
};
SimStateData(){}
SimStateData(const PxU8 type)
{
PxMemZero(data, sizeof(Kinematic));
Kinematic* kine = reinterpret_cast<Kinematic*>(data);
kine->type = type;
}
PX_FORCE_INLINE PxU32 getType() const { const Kinematic* kine = reinterpret_cast<const Kinematic*>(data); return kine->type;}
PX_FORCE_INLINE bool isKine() const {return eKine == getType();}
PX_FORCE_INLINE bool isVelMod() const {return eVelMod == getType();}
PX_FORCE_INLINE Kinematic* getKinematicData() { Kinematic* kine = reinterpret_cast<Kinematic*>(data); PX_ASSERT(eKine == kine->type); return kine;}
PX_FORCE_INLINE VelocityMod* getVelocityModData() { VelocityMod* velmod = reinterpret_cast<VelocityMod*>(data); PX_ASSERT(eVelMod == velmod->type); return velmod;}
PX_FORCE_INLINE const Kinematic* getKinematicData() const { const Kinematic* kine = reinterpret_cast<const Kinematic*>(data); PX_ASSERT(eKine == kine->type); return kine;}
PX_FORCE_INLINE const VelocityMod* getVelocityModData() const { const VelocityMod* velmod = reinterpret_cast<const VelocityMod*>(data); PX_ASSERT(eVelMod == velmod->type); return velmod;}
};
PX_FORCE_INLINE void simStateBackupAndClearBodyProperties(SimStateData* simStateData, PxsBodyCore& core)
{
PX_ASSERT(simStateData && simStateData->isKine());
Kinematic* kine = simStateData->getKinematicData();
kine->backupLinearDamping = core.linearDamping;
kine->backupAngularDamping = core.angularDamping;
kine->backupInverseInertia = core.inverseInertia;
kine->backupInvMass = core.inverseMass;
kine->backupMaxAngVelSq = core.maxAngularVelocitySq;
kine->backupMaxLinVelSq = core.maxLinearVelocitySq;
core.inverseMass = 0.0f;
core.inverseInertia = PxVec3(0.0f);
core.linearDamping = 0.0f;
core.angularDamping = 0.0f;
core.maxAngularVelocitySq = PX_MAX_REAL;
core.maxLinearVelocitySq = PX_MAX_REAL;
}
PX_FORCE_INLINE void simStateRestoreBodyProperties(const SimStateData* simStateData, PxsBodyCore& core)
{
PX_ASSERT(simStateData && simStateData->isKine());
const Kinematic* kine = simStateData->getKinematicData();
core.inverseMass = kine->backupInvMass;
core.inverseInertia = kine->backupInverseInertia;
core.linearDamping = kine->backupLinearDamping;
core.angularDamping = kine->backupAngularDamping;
core.maxAngularVelocitySq = kine->backupMaxAngVelSq;
core.maxLinearVelocitySq = kine->backupMaxLinVelSq;
}
PX_FORCE_INLINE void simStateClearVelMod(SimStateData* simStateData)
{
if (simStateData && simStateData->isVelMod())
{
VelocityMod* velmod = simStateData->getVelocityModData();
velmod->clear();
}
}
PX_FORCE_INLINE bool simStateGetKinematicTarget(const SimStateData* simStateData, PxTransform& p)
{
if (simStateData && simStateData->isKine() && simStateData->getKinematicData()->targetValid)
{
p = simStateData->getKinematicData()->targetPose;
return true;
}
else
return false;
}
PX_FORCE_INLINE bool simStateGetHasValidKinematicTarget(const SimStateData* simStateData)
{
PX_ASSERT(!simStateData || simStateData->isKine());
return simStateData && simStateData->isKine() && simStateData->getKinematicData()->targetValid;
}
PX_FORCE_INLINE void simStateSetKinematicTarget(SimStateData* simStateData, const PxTransform& p)
{
PX_ASSERT(simStateData && simStateData->isKine());
// setting the kinematic target is only allowed if the body is part of a scene, at which point the
// mSimStateData buffer must exist
Kinematic* kine = simStateData->getKinematicData();
kine->targetPose = p;
kine->targetValid = 1;
}
PX_FORCE_INLINE void simStateInvalidateKinematicTarget(SimStateData* simStateData)
{
PX_ASSERT(simStateData && simStateData->isKine());
simStateData->getKinematicData()->targetValid = 0;
}
} // namespace Sc
} // namespace physx
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScIterators.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 "ScIterators.h"
#include "ScBodySim.h"
#include "ScShapeSim.h"
#include "ScShapeInteraction.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////
Sc::ContactIterator::Pair::Pair(const void*& contactPatches, const void*& contactPoints, PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches,
ShapeSimBase& shape0, ShapeSimBase& shape1, ActorSim* actor0, ActorSim* actor1)
: mIndex(0)
, mNumContacts(numContacts)
, mIter(reinterpret_cast<const PxU8*>(contactPatches), reinterpret_cast<const PxU8*>(contactPoints), reinterpret_cast<const PxU32*>(forces + numContacts), numPatches, numContacts)
, mForces(forces)
, mActor0(actor0->getPxActor())
, mActor1(actor1->getPxActor())
{
mCurrentContact.shape0 = shape0.getPxShape();
mCurrentContact.shape1 = shape1.getPxShape();
mCurrentContact.normalForceAvailable = (forces != NULL);
}
Sc::ContactIterator::Pair* Sc::ContactIterator::getNextPair()
{
PX_ASSERT(mCurrent || (mCurrent == mLast));
if(mCurrent < mLast)
{
ShapeInteraction* si = static_cast<ShapeInteraction*>(*mCurrent);
const void* contactPatches = NULL;
const void* contactPoints = NULL;
PxU32 contactDataSize = 0;
const PxReal* forces = NULL;
PxU32 numContacts = 0;
PxU32 numPatches = 0;
PxU32 nextOffset = si->getContactPointData(contactPatches, contactPoints, contactDataSize, numContacts, numPatches, forces, mOffset, *mOutputs);
if (nextOffset == mOffset)
++mCurrent;
else
mOffset = nextOffset;
mCurrentPair = Pair(contactPatches, contactPoints, contactDataSize, forces, numContacts, numPatches, si->getShape0(), si->getShape1(), &si->getActorSim0(), &si->getActorSim1());
return &mCurrentPair;
}
else
return NULL;
}
Sc::Contact* Sc::ContactIterator::Pair::getNextContact()
{
if(mIndex < mNumContacts)
{
if(!mIter.hasNextContact())
{
if(!mIter.hasNextPatch())
return NULL;
mIter.nextPatch();
}
PX_ASSERT(mIter.hasNextContact());
mIter.nextContact();
mCurrentContact.normal = mIter.getContactNormal();
mCurrentContact.point = mIter.getContactPoint();
mCurrentContact.separation = mIter.getSeparation();
mCurrentContact.normalForce = mForces ? mForces[mIndex] : 0;
mCurrentContact.faceIndex0 = mIter.getFaceIndex0();
mCurrentContact.faceIndex1 = mIter.getFaceIndex1();
mIndex++;
return &mCurrentContact;
}
return NULL;
}
///////////////////////////////////////////////////////////////////////////////
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodyCore.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"
#if PX_SUPPORT_GPU_PHYSX
#include "ScSoftBodyCore.h"
#include "ScFEMClothCore.h"
#include "ScPhysics.h"
#include "ScSoftBodySim.h"
#include "DySoftBody.h"
#include "GuTetrahedronMesh.h"
#include "GuBV4.h"
#include "geometry/PxTetrahedronMesh.h"
using namespace physx;
Sc::SoftBodyCore::SoftBodyCore() :
ActorCore(PxActorType::eSOFTBODY, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0),
mGpuMemStat(0)
{
const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale();
mCore.initialRotation = PxQuat(PxIdentity);
mCore.sleepThreshold = 5e-5f * scale.speed * scale.speed;
mCore.wakeCounter = Physics::sWakeCounterOnCreation;
mCore.freezeThreshold = 5e-6f * scale.speed * scale.speed;
mCore.maxPenBias = -1e32f;//-PX_MAX_F32;
mCore.solverIterationCounts = (1 << 8) | 4;
mCore.dirty = true;
mCore.mFlags = PxSoftBodyFlags(0);
mCore.mPositionInvMass = NULL;
mCore.mRestPosition = NULL;
mCore.mSimPositionInvMass = NULL;
mCore.mSimVelocity = NULL;
mCore.mKinematicTarget = NULL;
}
Sc::SoftBodyCore::~SoftBodyCore() { }
void Sc::SoftBodyCore::setMaterial(const PxU16 handle)
{
mCore.setMaterial(handle);
mCore.dirty = true;
}
void Sc::SoftBodyCore::clearMaterials()
{
mCore.clearMaterials();
mCore.dirty = true;
}
void Sc::SoftBodyCore::setFlags(PxSoftBodyFlags flags)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
{
const bool wasDisabledSelfCollision = mCore.mFlags & PxSoftBodyFlag::eDISABLE_SELF_COLLISION;
const bool isDisabledSelfCollision = flags & PxSoftBodyFlag::eDISABLE_SELF_COLLISION;
if (wasDisabledSelfCollision != isDisabledSelfCollision)
{
if (isDisabledSelfCollision)
sim->disableSelfCollision();
else
sim->enableSelfCollision();
}
}
mCore.mFlags = flags;
mCore.dirty = true;
}
template <typename I>
void computeRestPoses(PxVec4* pInvMasses, PxMat33* tetraRestPoses, const I* const indices, const PxU32 nbTetra)
{
for (PxU32 i = 0; i < nbTetra; ++i)
{
const PxU32 startIndex = i * 4;
// calculate rest pose
const PxVec3 x0 = pInvMasses[indices[startIndex + 0]].getXYZ();
const PxVec3 x1 = pInvMasses[indices[startIndex + 1]].getXYZ();
const PxVec3 x2 = pInvMasses[indices[startIndex + 2]].getXYZ();
const PxVec3 x3 = pInvMasses[indices[startIndex + 3]].getXYZ();
const PxVec3 u1 = x1 - x0;
const PxVec3 u2 = x2 - x0;
const PxVec3 u3 = x3 - x0;
PxMat33 Q = PxMat33(u1, u2, u3);
tetraRestPoses[i] = Q.getInverse();
#if PX_CHECKED
const float det = Q.getDeterminant();
if (fabsf(det) <= 1.e-9f)
{
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "computeRestPoses(): Degenerate or inverted tetrahedron\n");
}
#endif
}
}
PxFEMParameters Sc::SoftBodyCore::getParameter() const
{
return mCore.parameters;
}
void Sc::SoftBodyCore::setParameter(const PxFEMParameters parameter)
{
mCore.parameters = parameter;
mCore.dirty = true;
}
PxReal Sc::SoftBodyCore::getSleepThreshold() const
{
return mCore.sleepThreshold;
}
void Sc::SoftBodyCore::setSleepThreshold(const PxReal v)
{
mCore.sleepThreshold = v;
mCore.dirty = true;
}
PxReal Sc::SoftBodyCore::getFreezeThreshold() const
{
return mCore.freezeThreshold;
}
void Sc::SoftBodyCore::setFreezeThreshold(const PxReal v)
{
mCore.freezeThreshold = v;
mCore.dirty = true;
}
void Sc::SoftBodyCore::setSolverIterationCounts(const PxU16 c)
{
mCore.solverIterationCounts = c;
mCore.dirty = true;
}
PxReal Sc::SoftBodyCore::getWakeCounter() const
{
return mCore.wakeCounter;
}
void Sc::SoftBodyCore::setWakeCounter(const PxReal v)
{
mCore.wakeCounter = v;
mCore.dirty = true;
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->onSetWakeCounter();
}
}
void Sc::SoftBodyCore::setWakeCounterInternal(const PxReal v)
{
mCore.wakeCounter = v;
mCore.dirty = true;
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->onSetWakeCounter();
}
}
bool Sc::SoftBodyCore::isSleeping() const
{
Sc::SoftBodySim* sim = getSim();
return sim ? sim->isSleeping() : (mCore.wakeCounter == 0.0f);
}
void Sc::SoftBodyCore::wakeUp(PxReal wakeCounter)
{
mCore.wakeCounter = wakeCounter;
mCore.dirty = true;
}
void Sc::SoftBodyCore::putToSleep()
{
mCore.wakeCounter = 0.0f;
mCore.dirty = true;
}
PxActor* Sc::SoftBodyCore::getPxActor() const
{
return PxPointerOffset<PxActor*>(const_cast<SoftBodyCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]);
}
void Sc::SoftBodyCore::attachShapeCore(ShapeCore* shapeCore)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->attachShapeCore(shapeCore);
mCore.dirty = true;
}
}
void Sc::SoftBodyCore::attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->attachSimulationMesh(simulationMesh, simulationState);
mCore.dirty = true;
}
}
Sc::SoftBodySim* Sc::SoftBodyCore::getSim() const
{
return static_cast<Sc::SoftBodySim*>(ActorCore::getSim());
}
void Sc::SoftBodyCore::setSimulationFilterData(const PxFilterData& data)
{
mFilterData = data;
}
PxFilterData Sc::SoftBodyCore::getSimulationFilterData() const
{
return mFilterData;
}
void Sc::SoftBodyCore::addParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addParticleFilter(core, *sim, particleId, userBufferId, tetId);
}
void Sc::SoftBodyCore::removeParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().removeParticleFilter(core, *sim, particleId, userBufferId, tetId);
}
PxU32 Sc::SoftBodyCore::addParticleAttachment(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric)
{
Sc::SoftBodySim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
handle = sim->getScene().addParticleAttachment(core, *sim, particleId, userBufferId, tetId, barycentric);
return handle;
}
void Sc::SoftBodyCore::removeParticleAttachment(Sc::ParticleSystemCore* core, PxU32 handle)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->getScene().removeParticleAttachment(core, *sim, handle);
setWakeCounter(ScInternalWakeCounterResetValue);
}
}
void Sc::SoftBodyCore::addRigidFilter(Sc::BodyCore* core, PxU32 vertId)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addRigidFilter(core, *sim, vertId);
}
void Sc::SoftBodyCore::removeRigidFilter(Sc::BodyCore* core, PxU32 vertId)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().removeRigidFilter(core, *sim, vertId);
}
PxU32 Sc::SoftBodyCore::addRigidAttachment(Sc::BodyCore* core, PxU32 particleId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint)
{
Sc::SoftBodySim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if(sim)
handle = sim->getScene().addRigidAttachment(core, *sim, particleId, actorSpacePose, constraint);
return handle;
}
void Sc::SoftBodyCore::removeRigidAttachment(Sc::BodyCore* core, PxU32 handle)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->getScene().removeRigidAttachment(core, *sim, handle);
setWakeCounter(ScInternalWakeCounterResetValue);
}
}
void Sc::SoftBodyCore::addTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addTetRigidFilter(core, *sim, tetIdx);
}
void Sc::SoftBodyCore::removeTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
{
sim->getScene().removeTetRigidFilter(core, *sim, tetIdx);
}
}
PxU32 Sc::SoftBodyCore::addTetRigidAttachment(Sc::BodyCore* core, PxU32 tetIdx, const PxVec4& barycentric,
const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint)
{
Sc::SoftBodySim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
handle = sim->getScene().addTetRigidAttachment(core, *sim, tetIdx, barycentric, actorSpacePose, constraint);
return handle;
}
void Sc::SoftBodyCore::addSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addSoftBodyFilter(core, tetIdx0, *sim, tetIdx1);
}
void Sc::SoftBodyCore::removeSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().removeSoftBodyFilter(core, tetIdx0, *sim, tetIdx1);
}
void Sc::SoftBodyCore::addSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addSoftBodyFilters(core, *sim, tetIndices0, tetIndices1, tetIndicesSize);
}
void Sc::SoftBodyCore::removeSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().removeSoftBodyFilters(core, *sim, tetIndices0, tetIndices1, tetIndicesSize);
}
PxU32 Sc::SoftBodyCore::addSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1,
PxConeLimitedConstraint* constraint, PxReal constraintOffset)
{
Sc::SoftBodySim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
handle = sim->getScene().addSoftBodyAttachment(core, tetIdx0, triBarycentric0, *sim, tetIdx1, tetBarycentric1, constraint, constraintOffset);
return handle;
}
void Sc::SoftBodyCore::removeSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 handle)
{
Sc::SoftBodySim* sim = getSim();
setWakeCounterInternal(ScInternalWakeCounterResetValue);
core.setWakeCounterInternal(ScInternalWakeCounterResetValue);
if (sim)
sim->getScene().removeSoftBodyAttachment(core, *sim, handle);
}
void Sc::SoftBodyCore::addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addClothFilter(core, triIdx, *sim, tetIdx);
}
void Sc::SoftBodyCore::removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().removeClothFilter(core, triIdx, *sim, tetIdx);
}
void Sc::SoftBodyCore::addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().addVertClothFilter(core, vertIdx, *sim, tetIdx);
}
void Sc::SoftBodyCore::removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx)
{
Sc::SoftBodySim* sim = getSim();
if (sim)
sim->getScene().removeVertClothFilter(core, vertIdx, *sim, tetIdx);
}
PxU32 Sc::SoftBodyCore::addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric,
PxConeLimitedConstraint* constraint, PxReal constraintOffset)
{
Sc::SoftBodySim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
handle = sim->getScene().addClothAttachment(core, triIdx, triBarycentric, *sim, tetIdx, tetBarycentric, constraint, constraintOffset);
return handle;
}
void Sc::SoftBodyCore::removeClothAttachment(Sc::FEMClothCore& core, PxU32 handle)
{
Sc::SoftBodySim* sim = getSim();
setWakeCounter(ScInternalWakeCounterResetValue);
core.setWakeCounter(ScInternalWakeCounterResetValue);
if (sim)
sim->getScene().removeClothAttachment(core, *sim, handle);
}
PxU32 Sc::SoftBodyCore::getGpuSoftBodyIndex() const
{
const Sc::SoftBodySim* sim = getSim();
return sim ? sim->getGpuSoftBodyIndex() : 0xffffffff;
}
void Sc::SoftBodyCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags)
{
PX_UNUSED(shape);
SoftBodySim* sim = getSim();
if (!sim)
return;
SoftBodyShapeSim& s = sim->getShapeSim();
if (notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY)
s.onVolumeOrTransformChange();
if (notifyFlags & ShapeChangeNotifyFlag::eMATERIAL)
s.onMaterialChange();
if (notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING)
s.onResetFiltering();
if (notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY)
s.onVolumeOrTransformChange();
if (notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA)
s.onFilterDataChange();
if (notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET)
s.onContactOffsetChange();
if (notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET)
s.onRestOffsetChange();
}
void Sc::SoftBodyCore::setKinematicTargets(const PxVec4* positions, PxSoftBodyFlags flags)
{
mCore.mKinematicTarget = positions;
if (positions != NULL)
{
mCore.mFlags |= PxSoftBodyFlags(flags & PxSoftBodyFlags(PxSoftBodyFlag::eKINEMATIC | PxSoftBodyFlag::ePARTIALLY_KINEMATIC));
}
else
{
mCore.mFlags.clear(PxSoftBodyFlag::eKINEMATIC);
mCore.mFlags.clear(PxSoftBodyFlag::ePARTIALLY_KINEMATIC);
}
mCore.dirty = true;
}
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSim.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 "ScArticulationSim.h"
#include "ScArticulationCore.h"
#include "ScArticulationJointSim.h"
#include "ScArticulationJointCore.h"
#include "ScBodySim.h"
#include "ScConstraintSim.h"
#include "ScArticulationTendonSim.h"
#include "ScArticulationSensorSim.h"
#include "ScArticulationSensor.h"
#include "ScScene.h"
#include "DyConstraint.h"
#include "DyFeatherstoneArticulation.h"
#include "PxsContext.h"
#include "CmSpatialVector.h"
#include "foundation/PxVecMath.h"
#include "PxsSimpleIslandManager.h"
#include "ScShapeSim.h"
#include "PxsSimulationController.h"
using namespace physx;
using namespace physx::Dy;
Sc::ArticulationSim::ArticulationSim(ArticulationCore& core, Scene& scene, BodyCore& root) :
mLLArticulation (NULL),
mScene (scene),
mCore (core),
mLinks ("ScArticulationSim::links"),
mBodies ("ScArticulationSim::bodies"),
mJoints ("ScArticulationSim::joints"),
mMaxDepth (0),
mIsLLArticulationInitialized(false)
{
mLinks.reserve(16);
mJoints.reserve(16);
mBodies.reserve(16);
mLLArticulation = mScene.createLLArticulation(this);
mIslandNodeIndex = scene.getSimpleIslandManager()->addArticulation(mLLArticulation, false);
if(!mLLArticulation)
{
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "Articulation: could not allocate low-level resources.");
return;
}
PX_ASSERT(root.getSim());
addBody(*root.getSim(), NULL, NULL);
mCore.setSim(this);
mLLArticulation->setDyContext(mScene.getDynamicsContext());
mLLArticulation->getSolverDesc().initData(&core.getCore(), NULL);
//mLLArticulation->onUpdateSolverDesc();
}
Sc::ArticulationSim::~ArticulationSim()
{
if (!mLLArticulation)
return;
mScene.destroyLLArticulation(*mLLArticulation);
mScene.getSimpleIslandManager()->removeNode(mIslandNodeIndex);
mCore.setSim(NULL);
}
PxU32 Sc::ArticulationSim::findBodyIndex(BodySim& body) const
{
for(PxU32 i=0; i<mBodies.size(); i++)
{
if(mBodies[i]==&body)
return i;
}
PX_ASSERT(0);
return 0x80000000;
}
void Sc::ArticulationSim::addLoopConstraint(ConstraintSim* constraintSim)
{
const PxU32 size = mLoopConstraints.size();
if (size < mLoopConstraints.size())
mLoopConstraints.reserve(size*2 + 1);
BodySim* bodySim0 = constraintSim->getBody(0);
BodySim* bodySim1 = constraintSim->getBody(1);
ArticulationLoopConstraint lConstraint;
if (bodySim0)
lConstraint.linkIndex0 = findBodyIndex(*bodySim0);
else
lConstraint.linkIndex0 = 0x80000000;
if(bodySim1)
lConstraint.linkIndex1 = findBodyIndex(*bodySim1);
else
lConstraint.linkIndex1 = 0x80000000;
lConstraint.constraint = &constraintSim->getLowLevelConstraint();
mLoopConstraints.pushBack(lConstraint);
}
void Sc::ArticulationSim::removeLoopConstraint(ConstraintSim* constraintSim)
{
Dy::Constraint* constraint = &constraintSim->getLowLevelConstraint();
const PxU32 size = mLoopConstraints.size();
PxU32 index = 0;
while (index < size && mLoopConstraints[index].constraint != constraint)
++index;
if (index != size)
mLoopConstraints.replaceWithLast(index);
}
void Sc::ArticulationSim::updateCached(PxBitMapPinned* shapeChangedMap)
{
for(PxU32 i=0; i<mBodies.size(); i++)
mBodies[i]->updateCached(shapeChangedMap);
}
void Sc::ArticulationSim::markShapesUpdated(PxBitMapPinned* shapeChangedMap)
{
for (PxU32 a = 0; a < mBodies.size(); ++a)
{
PxU32 nbElems = mBodies[a]->getNbElements();
ElementSim** elems = mBodies[a]->getElements();
while (nbElems--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*elems++);
if (sim->isInBroadPhase())
shapeChangedMap->growAndSet(sim->getElementID());
}
}
}
void Sc::ArticulationSim::addBody(BodySim& body, BodySim* parent, ArticulationJointSim* joint)
{
mBodies.pushBack(&body);
mJoints.pushBack(joint);
mLLArticulation->addBody();
const PxU32 index = mLinks.size();
PX_ASSERT((((index==0) && (joint == 0)) && (parent == 0)) ||
(((index!=0) && joint) && (parent && (parent->getArticulation() == this))));
ArticulationLink& link = mLinks.insert();
link.bodyCore = &body.getBodyCore().getCore();
link.children = 0;
link.mPathToRootStartIndex = 0;
link.mPathToRootCount = 0;
link.mChildrenStartIndex = 0xffffffff;
link.mNumChildren = 0;
bool shouldSleep;
bool currentlyAsleep;
const bool bodyReadyForSleep = body.checkSleepReadinessBesidesWakeCounter();
const PxReal wakeCounter = getCore().getWakeCounter();
if(parent)
{
currentlyAsleep = !mBodies[0]->isActive();
shouldSleep = currentlyAsleep && bodyReadyForSleep;
PxU32 parentIndex = findBodyIndex(*parent);
link.parent = parentIndex;
ArticulationLink& parentLink = mLinks[parentIndex];
link.pathToRoot = parentLink.pathToRoot | ArticulationBitField(1)<<index;
link.inboundJoint = &joint->getCore().getCore();
parentLink.children |= ArticulationBitField(1)<<index;
if (parentLink.mChildrenStartIndex == 0xffffffff)
parentLink.mChildrenStartIndex = index;
parentLink.mNumChildren++;
}
else
{
currentlyAsleep = (wakeCounter == 0.0f);
shouldSleep = currentlyAsleep && bodyReadyForSleep;
link.parent = DY_ARTICULATION_LINK_NONE;
link.pathToRoot = 1;
link.inboundJoint = NULL;
}
if(currentlyAsleep && !shouldSleep)
{
for(PxU32 i=0; i < (mBodies.size() - 1); i++)
mBodies[i]->internalWakeUpArticulationLink(wakeCounter);
}
body.setArticulation(this, wakeCounter, shouldSleep, index);
}
void Sc::ArticulationSim::removeBody(BodySim& body)
{
for (PxU32 i = 0; i < mBodies.size(); ++i)
{
if (mBodies[i] == &body)
{
mBodies.replaceWithLast(i);
mJoints.replaceWithLast(i);
break;
}
}
}
void Sc::ArticulationSim::addTendon(ArticulationSpatialTendonSim* tendonSim)
{
tendonSim->mArtiSim = this;
const PxU32 index = mSpatialTendons.size();
Dy::ArticulationSpatialTendon& llTendon = tendonSim->mLLTendon;
llTendon.setTendonIndex(index);
mSpatialTendons.pushBack(&llTendon);
//mSpatialTendons.pushBack(&tendonSim->mLLTendon);
}
void Sc::ArticulationSim::addTendon(ArticulationFixedTendonSim* tendonSim)
{
tendonSim->mArtiSim = this;
const PxU32 index = mFixedTendons.size();
Dy::ArticulationFixedTendon& llTendon = tendonSim->mLLTendon;
llTendon.setTendonIndex(index);
mFixedTendons.pushBack(&llTendon);
}
void Sc::ArticulationSim::addSensor(ArticulationSensorSim* sensorSim, const PxU32 linkID)
{
const PxU32 index = mSensors.size();
sensorSim->setLowLevelIndex(index);
sensorSim->mArticulationSim = this;
Dy::ArticulationSensor& llSensor = sensorSim->getLLSensor();
llSensor.mLinkID = PxU16(linkID);
mSensors.pushBack(&llSensor);
mSensorForces.insert();
mSensorForces.back().force = PxVec3(0.f);
mSensorForces.back().torque = PxVec3(0.f);
}
void Sc::ArticulationSim::createLLStructure()
{
if(!mBodies.size())
return;
mLLArticulation->setupLinks(mLinks.size(), const_cast<Dy::ArticulationLink*>(mLinks.begin()));
mLLArticulation->assignTendons(mSpatialTendons.size(), const_cast<Dy::ArticulationSpatialTendon**>(mSpatialTendons.begin()));
mLLArticulation->assignTendons(mFixedTendons.size(), const_cast<Dy::ArticulationFixedTendon**>(mFixedTendons.begin()));
mLLArticulation->assignSensors(mSensors.size(), const_cast<Dy::ArticulationSensor**>(mSensors.begin()), const_cast<PxSpatialForce*>(mSensorForces.begin()));
mIsLLArticulationInitialized = true;
}
void Sc::ArticulationSim::initializeConfiguration()
{
Dy::ArticulationData& data = mLLArticulation->getArticulationData();
mLLArticulation->jcalc(data);
mLLArticulation->mJcalcDirty = false;
Dy::ArticulationLink* links = data.getLinks();
Dy::ArticulationJointCoreData* jointData = data.getJointData();
const PxU32 linkCount = data.getLinkCount();
PxReal* jointVelocites = data.getJointVelocities();
PxReal* jointPositions = data.getJointPositions();
PxReal* jointTargetPositions = data.getJointTargetPositions();
PxReal* jointTargetVelocities = data.getJointTargetVelocities();
for (PxU32 linkID = 1; linkID < linkCount; ++linkID)
{
Dy::ArticulationLink& link = links[linkID];
Dy::ArticulationJointCore* joint = link.inboundJoint;
Dy::ArticulationJointCoreData& jointDatum = jointData[linkID];
PxReal* jPositions = &jointPositions[jointDatum.jointOffset];
PxReal* jVelocites = &jointVelocites[jointDatum.jointOffset];
PxReal* jTargetPositions = &jointTargetPositions[jointDatum.jointOffset];
PxReal* jTargetVelocities = &jointTargetVelocities[jointDatum.jointOffset];
for (PxU8 i = 0; i < jointDatum.dof; ++i)
{
const PxU32 dofId = joint->dofIds[i];
jPositions[i] = joint->jointPos[dofId];
jVelocites[i] = joint->jointVel[dofId];
jTargetPositions[i] = joint->targetP[dofId];
jTargetVelocities[i] = joint->targetV[dofId];
}
}
PxU32 flags = (Dy::ArticulationDirtyFlag::eDIRTY_POSITIONS |
Dy::ArticulationDirtyFlag::eDIRTY_VELOCITIES |
Dy::ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_POS |
Dy::ArticulationDirtyFlag::eDIRTY_JOINT_TARGET_VEL);
mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::Enum(flags));
mLLArticulation->initPathToRoot();
}
void Sc::ArticulationSim::updateKinematic(PxArticulationKinematicFlags flags)
{
Dy::ArticulationData& data = mLLArticulation->getArticulationData();
if (mLLArticulation->mJcalcDirty)
{
mLLArticulation->jcalc(data);
mLLArticulation->mJcalcDirty = false;
}
if ((flags & PxArticulationKinematicFlag::ePOSITION))
{
mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_POSITIONS);
mLLArticulation->teleportLinks(data);
}
if ((flags & PxArticulationKinematicFlag::ePOSITION) ||
(flags & PxArticulationKinematicFlag::eVELOCITY))
{
mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITIES);
mLLArticulation->computeLinkVelocities(data);
}
}
void Sc::ArticulationSim::copyJointStatus(const PxU32 linkID)
{
Dy::ArticulationData& data = mLLArticulation->getArticulationData();
Dy::ArticulationLink* links = data.getLinks();
Dy::ArticulationJointCoreData* jointData = data.getJointData();
Dy::ArticulationLink& link = links[linkID];
Dy::ArticulationJointCore* joint = link.inboundJoint;
Dy::ArticulationJointCoreData& jointDatum = jointData[linkID];
PxReal* jointVelocites = data.getJointVelocities();
PxReal* jointPositions = data.getJointPositions();
PxReal* jVelocities = &jointVelocites[jointDatum.jointOffset];
PxReal* jPositions = &jointPositions[jointDatum.jointOffset];
for(PxU8 i = 0; i < jointDatum.dof; ++i)
{
const PxU32 dofId = joint->dofIds[i];
joint->jointPos[dofId] = jPositions[i];
joint->jointVel[dofId] = jVelocities[i];
}
}
void Sc::ArticulationSim::updateCCDLinks(PxArray<BodySim*>& sims)
{
for (PxU32 a = 0; a < mBodies.size(); ++a)
{
if (mBodies[a]->getLowLevelBody().getCore().mFlags & PxRigidBodyFlag::eENABLE_CCD)
{
sims.pushBack(mBodies[a]);
}
}
}
void Sc::ArticulationSim::putToSleep()
{
for (PxU32 i = 0; i < mLinks.size(); i++)
{
BodySim* bodySim = mBodies[i];
PxsRigidBody& rigid = bodySim->getLowLevelBody();
PxsBodyCore& bodyCore = bodySim->getBodyCore().getCore();
//rigid.setPose(rigid.getLastCCDTransform());
//KS - the IG deactivates bodies in parallel with the solver. It appears that under certain circumstances, the solver's integration (which performs
//sleep checks) could decide that the body is no longer a candidate for sleeping on the same frame that the island gen decides to deactivate the island
//that the body is contained in. This is a rare occurrence but the behavior we want to emulate is that of IG running before solver so we should therefore
//permit the IG to make the authoritative decision over whether the body should be active or inactive.
bodyCore.wakeCounter = 0.0f;
bodyCore.linearVelocity = PxVec3(0.0f);
bodyCore.angularVelocity = PxVec3(0.0f);
rigid.clearAllFrameFlags();
//Force update
}
mScene.getSimulationController()->updateArticulation(mLLArticulation, mIslandNodeIndex);
}
void Sc::ArticulationSim::sleepCheck(PxReal dt)
{
if(!mBodies.size())
return;
#if PX_CHECKED
{
PxReal maxTimer = 0.0f, minTimer = PX_MAX_F32;
bool allActive = true, noneActive = true;
PX_UNUSED(allActive);
PX_UNUSED(noneActive);
for(PxU32 i=0;i<mLinks.size();i++)
{
PxReal timer = mBodies[i]->getBodyCore().getWakeCounter();
maxTimer = PxMax(maxTimer, timer);
minTimer = PxMin(minTimer, timer);
bool active = mBodies[i]->isActive();
allActive &= active;
noneActive &= !active;
}
// either all links are asleep, or no links are asleep
PX_ASSERT(maxTimer==0 || minTimer!=0);
PX_ASSERT(allActive || noneActive);
}
#endif
if(!mBodies[0]->isActive())
return;
const PxReal sleepThreshold = getCore().getCore().sleepThreshold;
PxReal maxTimer = 0.0f , minTimer = PX_MAX_F32;
for(PxU32 i=0;i<mLinks.size();i++)
{
const Cm::SpatialVector& motionVelocity = mLLArticulation->getMotionVelocity(i);
PxReal timer = mBodies[i]->updateWakeCounter(dt, sleepThreshold, motionVelocity);
maxTimer = PxMax(maxTimer, timer);
minTimer = PxMin(minTimer, timer);
}
mCore.setWakeCounterInternal(maxTimer);
if(maxTimer != 0.0f)
{
if(minTimer == 0.0f)
{
// make sure nothing goes to sleep unless everything does
for(PxU32 i=0;i<mLinks.size();i++)
mBodies[i]->getBodyCore().setWakeCounterFromSim(PxMax(1e-6f, mBodies[i]->getBodyCore().getWakeCounter()));
}
return;
}
for(PxU32 i=0;i<mLinks.size();i++)
{
mBodies[i]->notifyReadyForSleeping();
mBodies[i]->getLowLevelBody().resetSleepFilter();
}
mScene.getSimpleIslandManager()->deactivateNode(mIslandNodeIndex);
}
bool Sc::ArticulationSim::isSleeping() const
{
return (mBodies.size() > 0) ? (!mBodies[0]->isActive()) : true;
}
void Sc::ArticulationSim::internalWakeUp(PxReal wakeCounter)
{
if(mCore.getWakeCounter() < wakeCounter)
{
mCore.setWakeCounterInternal(wakeCounter);
for(PxU32 i=0;i<mBodies.size();i++)
mBodies[i]->internalWakeUpArticulationLink(wakeCounter);
}
}
void Sc::ArticulationSim::updateForces(PxReal dt)
{
PxU32 count = 0;
bool anyForcesApplied = false;
for(PxU32 i=0;i<mBodies.size();i++)
{
if (i+1 < mBodies.size())
{
PxPrefetchLine(mBodies[i+1],128);
PxPrefetchLine(mBodies[i+1],256);
}
anyForcesApplied |= mBodies[i]->updateForces(dt, NULL, NULL, count, &mLLArticulation->getSolverDesc().acceleration[i]);
}
if(anyForcesApplied)
mLLArticulation->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_EXT_ACCEL);
}
void Sc::ArticulationSim::clearAcceleration(PxReal dt)
{
PxU32 count = 0;
bool anyBodyRetains = false;
for (PxU32 i = 0; i < mBodies.size(); i++)
{
if (i + 1 < mBodies.size())
{
PxPrefetchLine(mBodies[i + 1], 128);
PxPrefetchLine(mBodies[i + 1], 256);
}
const bool accDirty = mBodies[i]->readVelocityModFlag(VMF_ACC_DIRTY);
// the code restores the pre-impulse state:
// if we only applied an impulse and no acceleration, we clear the acceleration here.
// if we applied an acceleration, we re-apply the acceleration terms we have in the velMod.
// we cleared out the impulse here when we pushed the data at the start of the sim.
if (!accDirty)
{
mLLArticulation->getSolverDesc().acceleration[i].linear = PxVec3(0.f);
mLLArticulation->getSolverDesc().acceleration[i].angular = PxVec3(0.f);
}
else
{
mBodies[i]->updateForces(dt, NULL, NULL, count, &mLLArticulation->getSolverDesc().acceleration[i]);
}
// we need to raise the dirty flag if retain accelerations is on
// because in that case we need to restore the acceleration without impulses. We
// can only do that using the CPU->GPU codepath because we don't distinguish between
// acceleration and impulses on the GPU.
// The flag must be raised here because we don't know at the start of the next sim step
// that the data in velMod is actually valid and the articulation would not be added
// to the dirty list.
// without retain accelerations, the accelerations are cleared directly on the GPU.
if (mBodies[i]->getFlagsFast() & PxRigidBodyFlag::eRETAIN_ACCELERATIONS)
anyBodyRetains = true;
}
if (anyBodyRetains)
{
mScene.getSimulationController()->updateArticulationExtAccel(mLLArticulation, mIslandNodeIndex);
}
}
void Sc::ArticulationSim::saveLastCCDTransform()
{
for(PxU32 i=0;i<mBodies.size();i++)
{
if (i+1 < mBodies.size())
{
PxPrefetchLine(mBodies[i+1],128);
PxPrefetchLine(mBodies[i+1],256);
}
mBodies[i]->getLowLevelBody().saveLastCCDTransform();
}
}
void Sc::ArticulationSim::setFixedBaseLink(bool value)
{
const PxU32 linkCount = mLinks.size();
if(linkCount > 0)
mLinks[0].bodyCore->fixedBaseLink = PxU8(value);
}
PxU32 Sc::ArticulationSim::getDofs() const
{
return mLLArticulation->getDofs();
}
PxU32 Sc::ArticulationSim::getDof(const PxU32 linkID) const
{
return mLLArticulation->getDof(linkID);
}
PX_COMPILE_TIME_ASSERT(sizeof(Cm::SpatialVector)==sizeof(PxSpatialForce));
PxArticulationCache* Sc::ArticulationSim::createCache()
{
return FeatherstoneArticulation::createCache(getDofs(), mLinks.size(), mSensors.size());
}
PxU32 Sc::ArticulationSim::getCacheDataSize() const
{
return FeatherstoneArticulation::getCacheDataSize(getDofs(), mLinks.size(), mSensors.size());
}
void Sc::ArticulationSim::zeroCache(PxArticulationCache& cache) const
{
const PxU32 cacheDataSize = getCacheDataSize();
PxMemZero(cache.externalForces, cacheDataSize);
}
//copy external data to internal data
bool Sc::ArticulationSim::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag) const
{
//checkResize();
bool shouldWake = false;
if (mLLArticulation->applyCache(cache, flag, shouldWake))
{
mScene.getSimulationController()->updateArticulation(mLLArticulation, mIslandNodeIndex);
}
return shouldWake;
}
//copy internal data to external data
void Sc::ArticulationSim::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const
{
mLLArticulation->copyInternalStateToCache(cache, flag, isGpuSimEnabled);
}
void Sc::ArticulationSim::packJointData(const PxReal* maximum, PxReal* reduced) const
{
mLLArticulation->packJointData(maximum, reduced);
}
void Sc::ArticulationSim::unpackJointData(const PxReal* reduced, PxReal* maximum) const
{
mLLArticulation->unpackJointData(reduced, maximum);
}
void Sc::ArticulationSim::commonInit()
{
mLLArticulation->initializeCommonData();
}
void Sc::ArticulationSim::computeGeneralizedGravityForce(PxArticulationCache& cache)
{
mLLArticulation->getGeneralizedGravityForce(mScene.getGravity(), cache);
}
void Sc::ArticulationSim::computeCoriolisAndCentrifugalForce(PxArticulationCache& cache)
{
mLLArticulation->getCoriolisAndCentrifugalForce(cache);
}
void Sc::ArticulationSim::computeGeneralizedExternalForce(PxArticulationCache& cache)
{
mLLArticulation->getGeneralizedExternalForce(cache);
}
void Sc::ArticulationSim::computeJointAcceleration(PxArticulationCache& cache)
{
mLLArticulation->getJointAcceleration(mScene.getGravity(), cache);
}
void Sc::ArticulationSim::computeJointForce(PxArticulationCache& cache)
{
mLLArticulation->getJointForce(cache);
}
void Sc::ArticulationSim::computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols)
{
mLLArticulation->getDenseJacobian(cache, nRows, nCols);
}
void Sc::ArticulationSim::computeCoefficientMatrix(PxArticulationCache& cache)
{
mLLArticulation->getCoefficientMatrixWithLoopJoints(mLoopConstraints.begin(), mLoopConstraints.size(), cache);
}
bool Sc::ArticulationSim::computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState,
const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter)
{
const PxReal invLengthScale = 1.f / mScene.getLengthScale();
return mLLArticulation->getLambda(mLoopConstraints.begin(), mLoopConstraints.size(), cache, initialState, jointTorque, gravity, maxIter, invLengthScale);
}
void Sc::ArticulationSim::computeGeneralizedMassMatrix(PxArticulationCache& cache)
{
mLLArticulation->getGeneralizedMassMatrixCRB(cache);
/*const PxU32 totalDofs = mLLArticulation->getDofs();
PxReal* massMatrix = reinterpret_cast<PxReal*>(PX_ALLOC(sizeof(PxReal) * totalDofs * totalDofs, "MassMatrix"));
PxMemCopy(massMatrix, cache.massMatrix, sizeof(PxReal)*totalDofs * totalDofs);
mLLArticulation->getGeneralizedMassMatrix(cache);
PxReal* massMatrix1 = cache.massMatrix;
for (PxU32 i = 0; i < totalDofs; ++i)
{
PxReal* row = &massMatrix1[i * totalDofs];
for (PxU32 j = 0; j < totalDofs; ++j)
{
const PxReal dif = row[j] - massMatrix[j*totalDofs + i];
PX_ASSERT (PxAbs(dif) < 2e-4f)
}
}
PX_FREE(massMatrix);*/
}
PxU32 Sc::ArticulationSim::getCoefficientMatrixSize() const
{
const PxU32 size = mLoopConstraints.size();
const PxU32 totalDofs = mLLArticulation->getDofs();
return size * totalDofs;
}
void Sc::ArticulationSim::setRootLinearVelocity(const PxVec3& velocity)
{
mLLArticulation->setRootLinearVelocity(velocity);
}
void Sc::ArticulationSim::setRootAngularVelocity(const PxVec3& velocity)
{
mLLArticulation->setRootAngularVelocity(velocity);
}
PxSpatialVelocity Sc::ArticulationSim::getLinkVelocity(const PxU32 linkId) const
{
Cm::SpatialVector vel = mLLArticulation->getLinkScalarVelocity(linkId);
return reinterpret_cast<PxSpatialVelocity&>(vel);
}
PxSpatialVelocity Sc::ArticulationSim::getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const
{
Cm::SpatialVector accel = mLLArticulation->getMotionAcceleration(linkId, isGpuSimEnabled);
return reinterpret_cast<PxSpatialVelocity&>(accel);
}
// This method allows user teleport the root links and the articulation
//system update all other links pose
void Sc::ArticulationSim::setGlobalPose()
{
mLLArticulation->teleportRootLink();
}
void Sc::ArticulationSim::setJointDirty(Dy::ArticulationJointCore& jointCore)
{
PX_UNUSED(jointCore);
mScene.getSimulationController()->updateArticulationJoint(mLLArticulation, mIslandNodeIndex);
}
void Sc::ArticulationSim::setArticulationDirty(PxU32 flag)
{
Dy::FeatherstoneArticulation* featherstoneArtic = static_cast<Dy::FeatherstoneArticulation*>(mLLArticulation);
featherstoneArtic->raiseGPUDirtyFlag(Dy::ArticulationDirtyFlag::Enum(flag));
mScene.getSimulationController()->updateArticulation(mLLArticulation, mIslandNodeIndex);
}
void Sc::ArticulationSim::debugCheckWakeCounterOfLinks(PxReal wakeCounter) const
{
PX_UNUSED(wakeCounter);
#ifdef _DEBUG
// make sure the links are in sync with the articulation
for(PxU32 i=0; i < mBodies.size(); i++)
{
PX_ASSERT(mBodies[i]->getBodyCore().getWakeCounter() == wakeCounter);
}
#endif
}
void Sc::ArticulationSim::debugCheckSleepStateOfLinks(bool isSleeping) const
{
PX_UNUSED(isSleeping);
#ifdef _DEBUG
// make sure the links are in sync with the articulation
for(PxU32 i=0; i < mBodies.size(); i++)
{
if (isSleeping)
{
PX_ASSERT(!mBodies[i]->isActive());
PX_ASSERT(mBodies[i]->getBodyCore().getWakeCounter() == 0.0f);
PX_ASSERT(mBodies[i]->checkSleepReadinessBesidesWakeCounter());
}
else
PX_ASSERT(mBodies[i]->isActive());
}
#endif
}
PxU32 Sc::ArticulationSim::getRootActorIndex() const
{
return mBodies[0]->getActorID();
}
const PxSpatialForce& Sc::ArticulationSim::getSensorForce(const PxU32 lowLevelIndex) const
{
return mSensorForces[lowLevelIndex];
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationTendonJointCore.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 "ScArticulationTendonJointCore.h"
#include "ScArticulationTendonSim.h"
using namespace physx;
void Sc::ArticulationTendonJointCore::setCoefficient(PxArticulationAxis::Enum axis_, const PxReal coefficient_, const PxReal recipCoefficient_)
{
axis = axis_;
coefficient = coefficient_;
recipCoefficient = recipCoefficient_;
if (mTendonSim)
{
mTendonSim->setTendonJointCoefficient(*this, axis_, coefficient, recipCoefficient);
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorPair.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 SC_ACTOR_PAIR_H
#define SC_ACTOR_PAIR_H
#include "ScRigidSim.h"
#include "ScContactStream.h"
#include "ScNPhaseCore.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScSoftBodySim.h"
#endif
namespace physx
{
namespace Sc
{
class ActorPairContactReportData
{
public:
ActorPairContactReportData() :
mStrmResetStamp (0xffffffff),
mActorAID (0xffffffff),
mActorBID (0xffffffff),
mPxActorA (NULL),
mPxActorB (NULL)
{}
ContactStreamManager mContactStreamManager;
PxU32 mStrmResetStamp;
PxU32 mActorAID;
PxU32 mActorBID;
PxActor* mPxActorA;
PxActor* mPxActorB;
};
/**
\brief Class shared by all shape interactions for a pair of actors.
This base class is used if no shape pair of an actor pair has contact reports requested.
*/
class ActorPair
{
public:
enum ActorPairFlags
{
eIS_REPORT_PAIR = (1<<0),
eNEXT_FREE = (1<<1)
};
PX_FORCE_INLINE ActorPair() : mInternalFlags(0), mTouchCount(0), mRefCount(0) {}
PX_FORCE_INLINE ~ActorPair() {}
PX_FORCE_INLINE PxIntBool isReportPair() const { return (mInternalFlags & eIS_REPORT_PAIR); }
PX_FORCE_INLINE void incTouchCount() { mTouchCount++; PX_ASSERT(mTouchCount); }
PX_FORCE_INLINE void decTouchCount() { PX_ASSERT(mTouchCount); mTouchCount--; }
PX_FORCE_INLINE PxU32 getTouchCount() const { return mTouchCount; }
PX_FORCE_INLINE void incRefCount() { ++mRefCount; PX_ASSERT(mRefCount>0); }
PX_FORCE_INLINE PxU32 decRefCount() { PX_ASSERT(mRefCount>0); return --mRefCount; }
PX_FORCE_INLINE PxU32 getRefCount() const { return mRefCount; }
private:
ActorPair& operator=(const ActorPair&);
protected:
PxU16 mInternalFlags;
PxU16 mTouchCount;
PxU16 mRefCount;
PxU16 mPad; // instances of this class are stored in a pool which needs an item size of at least size_t
};
/**
\brief Class shared by all shape interactions for a pair of actors if contact reports are requested.
This class is used if at least one shape pair of an actor pair has contact reports requested.
\note If a pair of actors had contact reports requested for some of the shape interactions but all of them switch to not wanting contact reports
any longer, then the ActorPairReport instance is kept being used and won't get replaced by a simpler ActorPair instance.
*/
class ActorPairReport : public ActorPair
{
public:
enum ActorPairReportFlags
{
eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET = ActorPair::eNEXT_FREE // PT: whether the pair is already stored in the 'ContactReportActorPairSet' or not
};
PX_FORCE_INLINE ActorPairReport(ActorSim&, ActorSim&);
PX_FORCE_INLINE ~ActorPairReport();
PX_INLINE ContactStreamManager& createContactStreamManager(NPhaseCore&);
PX_FORCE_INLINE ContactStreamManager& getContactStreamManager() const { PX_ASSERT(mReportData); return mReportData->mContactStreamManager; }
PX_FORCE_INLINE ActorSim& getActorA() const { return mActorA; }
PX_FORCE_INLINE ActorSim& getActorB() const { return mActorB; }
PX_INLINE PxU32 getActorAID() const { PX_ASSERT(mReportData); return mReportData->mActorAID; }
PX_INLINE PxU32 getActorBID() const { PX_ASSERT(mReportData); return mReportData->mActorBID; }
PX_INLINE PxActor* getPxActorA() const { PX_ASSERT(mReportData); return mReportData->mPxActorA; }
PX_INLINE PxActor* getPxActorB() const { PX_ASSERT(mReportData); return mReportData->mPxActorB; }
PX_INLINE bool streamResetStamp(PxU32 cmpStamp);
PX_FORCE_INLINE PxU16 isInContactReportActorPairSet() const { return PxU16(mInternalFlags & eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET); }
PX_FORCE_INLINE void setInContactReportActorPairSet() { mInternalFlags |= eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET; }
PX_FORCE_INLINE void clearInContactReportActorPairSet() { mInternalFlags &= ~eIS_IN_CONTACT_REPORT_ACTOR_PAIR_SET; }
PX_FORCE_INLINE void createContactReportData(NPhaseCore&);
PX_FORCE_INLINE void releaseContactReportData(NPhaseCore&);
PX_FORCE_INLINE void convert(ActorPair& aPair) { PX_ASSERT(!aPair.isReportPair()); mTouchCount = PxU16(aPair.getTouchCount()); mRefCount = PxU16(aPair.getRefCount()); }
PX_FORCE_INLINE static ActorPairReport& cast(ActorPair& aPair) { PX_ASSERT(aPair.isReportPair()); return static_cast<ActorPairReport&>(aPair); }
private:
ActorPairReport& operator=(const ActorPairReport&);
ActorSim& mActorA;
ActorSim& mActorB;
ActorPairContactReportData* mReportData;
};
} // namespace Sc
PX_FORCE_INLINE Sc::ActorPairReport::ActorPairReport(ActorSim& actor0, ActorSim& actor1) : ActorPair(),
mActorA (actor0),
mActorB (actor1),
mReportData (NULL)
{
PX_ASSERT(mInternalFlags == 0);
mInternalFlags = ActorPair::eIS_REPORT_PAIR;
}
PX_FORCE_INLINE Sc::ActorPairReport::~ActorPairReport()
{
PX_ASSERT(mReportData == NULL);
}
PX_INLINE bool Sc::ActorPairReport::streamResetStamp(PxU32 cmpStamp)
{
PX_ASSERT(mReportData);
const bool ret = (cmpStamp != mReportData->mStrmResetStamp);
mReportData->mStrmResetStamp = cmpStamp;
return ret;
}
PX_INLINE Sc::ContactStreamManager& Sc::ActorPairReport::createContactStreamManager(NPhaseCore& npCore)
{
// Lazy create report data
if(!mReportData)
createContactReportData(npCore);
return mReportData->mContactStreamManager;
}
PX_FORCE_INLINE void Sc::ActorPairReport::createContactReportData(NPhaseCore& npCore)
{
PX_ASSERT(!mReportData);
Sc::ActorPairContactReportData* reportData = npCore.createActorPairContactReportData();
mReportData = reportData;
if(reportData)
{
const ActorCore& actorCoreA = mActorA.getActorCore();
const ActorCore& actorCoreB = mActorB.getActorCore();
reportData->mActorAID = mActorA.getActorID();
reportData->mActorBID = mActorB.getActorID();
#if PX_SUPPORT_GPU_PHYSX
if (mActorA.getActorType() == PxActorType::eSOFTBODY)
reportData->mPxActorA = static_cast<const SoftBodyCore&>(actorCoreA).getPxActor();
else
#endif
reportData->mPxActorA = static_cast<const RigidCore&>(actorCoreA).getPxActor();
#if PX_SUPPORT_GPU_PHYSX
if (mActorA.getActorType() == PxActorType::eSOFTBODY)
reportData->mPxActorB = static_cast<const SoftBodyCore&>(actorCoreB).getPxActor();
else
#endif
reportData->mPxActorB = static_cast<const RigidCore&>(actorCoreB).getPxActor();
}
}
PX_FORCE_INLINE void Sc::ActorPairReport::releaseContactReportData(NPhaseCore& npCore)
{
// Can't take the NPhaseCore (scene) reference from the actors since they're already gone on scene release
if(mReportData)
{
npCore.releaseActorPairContactReportData(mReportData);
mReportData = NULL;
}
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBodySim.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 "ScBodySim.h"
#include "ScShapeSim.h"
#include "ScScene.h"
#include "ScArticulationSim.h"
#include "PxsContext.h"
#include "PxsSimpleIslandManager.h"
#include "PxsSimulationController.h"
#include "ScSimStateData.h"
using namespace physx;
using namespace physx::Dy;
using namespace Sc;
#define PX_FREEZE_INTERVAL 1.5f
#define PX_FREE_EXIT_THRESHOLD 4.f
#define PX_FREEZE_TOLERANCE 0.25f
#define PX_SLEEP_DAMPING 0.5f
#define PX_FREEZE_SCALE 0.9f
static void updateBPGroup(ActorSim* sim)
{
PxU32 nbElems = sim->getNbElements();
ElementSim** elems = sim->getElements();
while (nbElems--)
{
ShapeSim* current = static_cast<ShapeSim*>(*elems++);
current->updateBPGroup();
}
}
BodySim::BodySim(Scene& scene, BodyCore& core, bool compound) :
RigidSim (scene, core),
mLLBody (&core.getCore(), PX_FREEZE_INTERVAL),
mSimStateData (NULL),
mVelModState (VMF_GRAVITY_DIRTY),
mArticulation (NULL)
{
core.getCore().numCountedInteractions = 0;
core.getCore().disableGravity = core.getActorFlags() & PxActorFlag::eDISABLE_GRAVITY;
if(core.getFlags() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD)
mLLBody.mInternalFlags |= PxsRigidBody::eSPECULATIVE_CCD;
if(core.getFlags() & PxRigidBodyFlag::eENABLE_GYROSCOPIC_FORCES)
mLLBody.mInternalFlags |= PxsRigidBody::eENABLE_GYROSCOPIC;
if(core.getFlags() & PxRigidBodyFlag::eRETAIN_ACCELERATIONS)
mLLBody.mInternalFlags |= PxsRigidBody::eRETAIN_ACCELERATION;
// PT: don't read the core ptr we just wrote, use input param
// PT: at time of writing we get a big L2 here because even though bodycore has been prefetched, the wake counter is 160 bytes away
const bool isAwake = (core.getWakeCounter() > 0) ||
(!core.getLinearVelocity().isZero()) ||
(!core.getAngularVelocity().isZero());
const bool isKine = isKinematic();
IG::SimpleIslandManager* simpleIslandManager = scene.getSimpleIslandManager();
if(!isArticulationLink())
{
mNodeIndex = simpleIslandManager->addRigidBody(&mLLBody, isKine, isAwake);
}
else
{
if(mArticulation)
{
const PxU32 linkIndex = mArticulation->findBodyIndex(*this);
const PxNodeIndex index = mArticulation->getIslandNodeIndex();
mNodeIndex.setIndices(index.index(), linkIndex);
}
}
PX_ASSERT(mActiveListIndex == SC_NOT_IN_SCENE_INDEX);
// A.B. need to set the compound rigid flag early enough, so that we add the rigid into
// active list and do not create the shape bounds
if(compound)
raiseInternalFlag(BF_IS_COMPOUND_RIGID);
setActive(isAwake, true);
if(isAwake)
{
scene.addToActiveList(*this);
PX_ASSERT(isActive());
}
else
{
mActiveListIndex = SC_NOT_IN_ACTIVE_LIST_INDEX;
mActiveCompoundListIndex = SC_NOT_IN_ACTIVE_LIST_INDEX;
PX_ASSERT(!isActive());
simpleIslandManager->deactivateNode(mNodeIndex);
}
if(isKine)
{
initKinematicStateBase(core, true);
setupSimStateData(true);
notifyPutToSleep(); // sleep state of kinematics is fully controlled by the simulation controller not the island manager
mFilterFlags |= PxFilterObjectFlag::eKINEMATIC;
}
}
BodySim::~BodySim()
{
Scene& scene = mScene;
const bool active = isActive();
tearDownSimStateData(isKinematic());
PX_ASSERT(!mSimStateData);
// PX-4603. AD: assuming that the articulation code cleans up the dirty state in case this is an articulation link.
if (!isArticulationLink())
scene.getVelocityModifyMap().boundedReset(mNodeIndex.index());
PX_ASSERT(!readInternalFlag(BF_ON_DEATHROW)); // Before 3.0 it could happen that destroy could get called twice. Assert to make sure this is fixed.
raiseInternalFlag(BF_ON_DEATHROW);
scene.removeBody(*this);
//Articulations are represented by a single node, so they must only be removed by the articulation and not the links!
if(mArticulation == NULL && mNodeIndex.articulationLinkId() == 0) //If it wasn't an articulation link, then we can remove it
scene.getSimpleIslandManager()->removeNode(mNodeIndex);
PX_ASSERT(mActiveListIndex != SC_NOT_IN_SCENE_INDEX);
if (active)
scene.removeFromActiveList(*this);
mActiveListIndex = SC_NOT_IN_SCENE_INDEX;
mActiveCompoundListIndex = SC_NOT_IN_SCENE_INDEX;
mCore.setSim(NULL);
}
void BodySim::updateCached(PxBitMapPinned* shapeChangedMap)
{
if(!(mLLBody.mInternalFlags & PxsRigidBody::eFROZEN))
{
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* current = static_cast<ShapeSim*>(*elems++);
current->updateCached(0, shapeChangedMap);
}
}
}
void BodySim::updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray)
{
PX_ASSERT(!(mLLBody.mInternalFlags & PxsRigidBody::eFROZEN)); // PT: should not be called otherwise
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* current = static_cast<ShapeSim*>(*elems++);
current->updateCached(transformCache, boundsArray);
}
}
bool BodySim::setupSimStateData(bool isKinematic)
{
SimStateData* data = mSimStateData;
if(!data)
{
data = mScene.getSimStateDataPool()->construct();
if(!data)
return false;
}
if(isKinematic)
{
PX_ASSERT(!mSimStateData || !mSimStateData->isKine());
PX_PLACEMENT_NEW(data, SimStateData(SimStateData::eKine));
Kinematic* kine = data->getKinematicData();
kine->targetValid = 0;
simStateBackupAndClearBodyProperties(data, getBodyCore().getCore());
}
else
{
PX_ASSERT(!mSimStateData || !mSimStateData->isVelMod());
PX_PLACEMENT_NEW(data, SimStateData(SimStateData::eVelMod));
VelocityMod* velmod = data->getVelocityModData();
velmod->clear();
}
mSimStateData = data;
return true;
}
void BodySim::tearDownSimStateData(bool isKinematic)
{
PX_ASSERT(!mSimStateData || mSimStateData->isKine() == isKinematic);
if (mSimStateData)
{
if (isKinematic)
simStateRestoreBodyProperties(mSimStateData, getBodyCore().getCore());
mScene.getSimStateDataPool()->destroy(mSimStateData);
mSimStateData = NULL;
}
}
void BodySim::switchToKinematic()
{
setupSimStateData(true);
{
initKinematicStateBase(getBodyCore(), false);
// - interactions need to get refiltered to make sure that kinematic-kinematic and kinematic-static pairs get suppressed
// - unlike postSwitchToDynamic(), constraint interactions are not marked dirty here because a transition to kinematic will put the object asleep which in turn
// triggers onDeactivate() on the constraint pairs that are active. If such pairs get deactivated, they will get removed from the list of active breakable
// constraints automatically.
setActorsInteractionsDirty(InteractionDirtyFlag::eBODY_KINEMATIC, NULL, InteractionFlag::eFILTERABLE);
mScene.getSimpleIslandManager()->setKinematic(mNodeIndex);
updateBPGroup(this);
}
mScene.setDynamicsDirty();
mFilterFlags |= PxFilterObjectFlag::eKINEMATIC;
}
void BodySim::switchToDynamic()
{
tearDownSimStateData(true);
{
mScene.getSimpleIslandManager()->setDynamic(mNodeIndex);
setForcesToDefaults(true);
// - interactions need to get refiltered to make sure that former kinematic-kinematic and kinematic-static pairs get enabled
// - switching from kinematic to dynamic does not change the sleep state of the body. The constraint interactions are marked dirty
// to check later whether they need to be activated plus potentially tracked for constraint break testing. This special treatment
// is necessary because constraints between two kinematic bodies are considered inactive, no matter whether one of the kinematics
// is active (has a target) or not.
setActorsInteractionsDirty(InteractionDirtyFlag::eBODY_KINEMATIC, NULL, InteractionFlag::eFILTERABLE | InteractionFlag::eCONSTRAINT);
clearInternalFlag(BF_KINEMATIC_MOVE_FLAGS);
if(isActive())
mScene.swapInActiveBodyList(*this);
//
updateBPGroup(this);
}
mScene.setDynamicsDirty();
mFilterFlags &= ~PxFilterObjectFlag::eKINEMATIC;
}
void BodySim::setKinematicTarget(const PxTransform& p)
{
PX_ASSERT(getSimStateData(true));
PX_ASSERT(getSimStateData(true)->isKine());
simStateSetKinematicTarget(getSimStateData_Unchecked(), p);
PX_ASSERT(getSimStateData(true)->getKinematicData()->targetValid);
raiseInternalFlag(BF_KINEMATIC_MOVED); // Important to set this here already because trigger interactions need to have this information when being activated.
clearInternalFlag(BF_KINEMATIC_SURFACE_VELOCITY);
}
void BodySim::addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc)
{
notifyAddSpatialAcceleration();
if (!mSimStateData || !mSimStateData->isVelMod())
setupSimStateData(false);
VelocityMod* velmod = mSimStateData->getVelocityModData();
if (linAcc) velmod->accumulateLinearVelModPerSec(*linAcc);
if (angAcc) velmod->accumulateAngularVelModPerSec(*angAcc);
}
void BodySim::setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc)
{
notifyAddSpatialAcceleration();
if (!mSimStateData || !mSimStateData->isVelMod())
setupSimStateData(false);
VelocityMod* velmod = mSimStateData->getVelocityModData();
if (linAcc) velmod->setLinearVelModPerSec(*linAcc);
if (angAcc) velmod->setAngularVelModPerSec(*angAcc);
}
void BodySim::clearSpatialAcceleration(bool force, bool torque)
{
PX_ASSERT(force || torque);
notifyClearSpatialAcceleration();
if (mSimStateData)
{
PX_ASSERT(mSimStateData->isVelMod());
VelocityMod* velmod = mSimStateData->getVelocityModData();
if (force)
velmod->clearLinearVelModPerSec();
if (torque)
velmod->clearAngularVelModPerSec();
}
}
void BodySim::addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta)
{
notifyAddSpatialVelocity();
if (!mSimStateData || !mSimStateData->isVelMod())
setupSimStateData(false);
VelocityMod* velmod = mSimStateData->getVelocityModData();
if (linVelDelta)
velmod->accumulateLinearVelModPerStep(*linVelDelta);
if (angVelDelta)
velmod->accumulateAngularVelModPerStep(*angVelDelta);
}
void BodySim::clearSpatialVelocity(bool force, bool torque)
{
PX_ASSERT(force || torque);
notifyClearSpatialVelocity();
if (mSimStateData)
{
PX_ASSERT(mSimStateData->isVelMod());
VelocityMod* velmod = mSimStateData->getVelocityModData();
if (force)
velmod->clearLinearVelModPerStep();
if (torque)
velmod->clearAngularVelModPerStep();
}
}
void BodySim::raiseVelocityModFlagAndNotify(VelocityModFlags flag)
{
//The dirty flag is stored separately in the BodySim so that we query the dirty flag before going to
//the expense of querying the simStateData for the velmod values.
raiseVelocityModFlag(flag);
if (!isArticulationLink())
mScene.getVelocityModifyMap().growAndSet(getNodeIndex().index());
else
mScene.addDirtyArticulationSim(getArticulation());
}
void BodySim::postActorFlagChange(PxU32 oldFlags, PxU32 newFlags)
{
// PT: don't convert to bool if not needed
const PxU32 wasWeightless = oldFlags & PxActorFlag::eDISABLE_GRAVITY;
const PxU32 isWeightless = newFlags & PxActorFlag::eDISABLE_GRAVITY;
if (isWeightless != wasWeightless)
{
if (mVelModState == 0)
raiseVelocityModFlag(VMF_GRAVITY_DIRTY);
getBodyCore().getCore().disableGravity = isWeightless!=0;
}
}
void BodySim::postBody2WorldChange()
{
mLLBody.saveLastCCDTransform();
notifyShapesOfTransformChange();
}
void BodySim::postSetWakeCounter(PxReal t, bool forceWakeUp)
{
if ((t > 0.0f) || forceWakeUp)
notifyNotReadyForSleeping();
else
{
const bool readyForSleep = checkSleepReadinessBesidesWakeCounter();
if (readyForSleep)
notifyReadyForSleeping();
}
}
void BodySim::postPosePreviewChange(PxU32 posePreviewFlag)
{
if (isActive())
{
if (posePreviewFlag & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW)
mScene.addToPosePreviewList(*this);
else
mScene.removeFromPosePreviewList(*this);
}
else
PX_ASSERT(!mScene.isInPosePreviewList(*this));
}
void BodySim::activate()
{
BodyCore& core = getBodyCore();
// Activate body
{
PX_ASSERT((!isKinematic()) || notInScene() || readInternalFlag(InternalFlags(BF_KINEMATIC_MOVED | BF_KINEMATIC_SURFACE_VELOCITY))); // kinematics should only get activated when a target is set.
// exception: object gets newly added, then the state change will happen later
if(!isArticulationLink())
{
mLLBody.mInternalFlags &= (~PxsRigidBody::eFROZEN);
// Put in list of activated bodies. The list gets cleared at the end of a sim step after the sleep callbacks have been fired.
mScene.onBodyWakeUp(this);
}
if(core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW)
{
PX_ASSERT(!mScene.isInPosePreviewList(*this));
mScene.addToPosePreviewList(*this);
}
createSqBounds();
}
activateInteractions(*this);
//set speculative CCD bit map if speculative CCD flag is on
if(core.getFlags() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD)
addToSpeculativeCCDMap();
}
void BodySim::deactivate()
{
deactivateInteractions(*this);
BodyCore& core = getBodyCore();
// Deactivate body
{
PX_ASSERT((!isKinematic()) || notInScene() || !readInternalFlag(BF_KINEMATIC_MOVED)); // kinematics should only get deactivated when no target is set.
// exception: object gets newly added, then the state change will happen later
if(!readInternalFlag(BF_ON_DEATHROW))
{
// Set velocity to 0.
// Note: this is also fine if the method gets called because the user puts something to sleep (this behavior is documented in the API)
PX_ASSERT(core.getWakeCounter() == 0.0f);
const PxVec3 zero(0.0f);
core.setLinearVelocityInternal(zero);
core.setAngularVelocityInternal(zero);
setForcesToDefaults(!core.getCore().disableGravity);
}
if(!isArticulationLink()) // Articulations have their own sleep logic.
mScene.onBodySleep(this);
if(core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW)
{
PX_ASSERT(mScene.isInPosePreviewList(*this));
mScene.removeFromPosePreviewList(*this);
}
destroySqBounds();
}
// reset speculative CCD bit map if speculative CCD flag is on
if(core.getFlags() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD)
removeFromSpeculativeCCDMap();
}
void BodySim::wakeUp()
{
setActive(true);
notifyWakeUp();
}
void BodySim::putToSleep()
{
PX_ASSERT(getBodyCore().getWakeCounter() == 0.0f);
PX_ASSERT(getBodyCore().getLinearVelocity().isZero());
PX_ASSERT(getBodyCore().getAngularVelocity().isZero());
notifyClearSpatialAcceleration();
notifyClearSpatialVelocity();
simStateClearVelMod(getSimStateData_Unchecked());
setActive(false);
notifyPutToSleep();
}
void BodySim::internalWakeUp(PxReal wakeCounterValue)
{
if(mArticulation)
mArticulation->internalWakeUp(wakeCounterValue);
else
internalWakeUpBase(wakeCounterValue);
}
void BodySim::internalWakeUpArticulationLink(PxReal wakeCounterValue)
{
PX_ASSERT(mArticulation);
internalWakeUpBase(wakeCounterValue);
}
void BodySim::internalWakeUpBase(PxReal wakeCounterValue) //this one can only increase the wake counter, not decrease it, so it can't be used to put things to sleep!
{
if ((!isKinematic()) && (getBodyCore().getWakeCounter() < wakeCounterValue))
{
PX_ASSERT(wakeCounterValue > 0.0f);
getBodyCore().setWakeCounterFromSim(wakeCounterValue);
//we need to update the gpu body sim because we reset the wake counter for the body core
mScene.updateBodySim(*this);
setActive(true);
notifyWakeUp();
if(0) // PT: commented-out for PX-2197
mLLBody.mInternalFlags &= (~PxsRigidBody::eFROZEN);
}
}
void BodySim::notifyReadyForSleeping()
{
if(mArticulation == NULL)
mScene.getSimpleIslandManager()->deactivateNode(mNodeIndex);
}
void BodySim::notifyNotReadyForSleeping()
{
mScene.getSimpleIslandManager()->activateNode(mNodeIndex);
}
void BodySim::notifyWakeUp()
{
mScene.getSimpleIslandManager()->activateNode(mNodeIndex);
}
void BodySim::notifyPutToSleep()
{
mScene.getSimpleIslandManager()->putNodeToSleep(mNodeIndex);
}
//This function will be called by CPU sleepCheck code
// PT: TODO: actually this seems to be only called by the articulation sim code, while regular rigid bodies use a copy of that code in LowLevelDynamics?
PxReal BodySim::updateWakeCounter(PxReal dt, PxReal energyThreshold, const Cm::SpatialVector& motionVelocity)
{
// update the body's sleep state and
BodyCore& core = getBodyCore();
const PxReal wakeCounterResetTime = ScInternalWakeCounterResetValue;
PxReal wc = core.getWakeCounter();
{
PxVec3 bcSleepLinVelAcc = mLLBody.sleepLinVelAcc;
PxVec3 bcSleepAngVelAcc = mLLBody.sleepAngVelAcc;
if(wc < wakeCounterResetTime * 0.5f || wc < dt)
{
const PxTransform& body2World = getBody2World();
// calculate normalized energy: kinetic energy divided by mass
const PxVec3 t = core.getInverseInertia();
const PxVec3 inertia(t.x > 0.0f ? 1.0f/t.x : 1.0f, t.y > 0.0f ? 1.0f/t.y : 1.0f, t.z > 0.0f ? 1.0f/t.z : 1.0f);
PxVec3 sleepLinVelAcc = motionVelocity.linear;
PxVec3 sleepAngVelAcc = body2World.q.rotateInv(motionVelocity.angular);
bcSleepLinVelAcc += sleepLinVelAcc;
bcSleepAngVelAcc += sleepAngVelAcc;
PxReal invMass = core.getInverseMass();
if(invMass == 0.0f)
invMass = 1.0f;
const PxReal angular = bcSleepAngVelAcc.multiply(bcSleepAngVelAcc).dot(inertia) * invMass;
const PxReal linear = bcSleepLinVelAcc.magnitudeSquared();
const PxReal normalizedEnergy = 0.5f * (angular + linear);
// scale threshold by cluster factor (more contacts => higher sleep threshold)
const PxReal clusterFactor = PxReal(1 + getNumCountedInteractions());
const PxReal threshold = clusterFactor*energyThreshold;
if (normalizedEnergy >= threshold)
{
PX_ASSERT(isActive());
mLLBody.resetSleepFilter();
const float factor = threshold == 0.0f ? 2.0f : PxMin(normalizedEnergy/threshold, 2.0f);
PxReal oldWc = wc;
wc = factor * 0.5f * wakeCounterResetTime + dt * (clusterFactor - 1.0f);
core.setWakeCounterFromSim(wc);
if (oldWc == 0.0f) // for the case where a sleeping body got activated by the system (not the user) AND got processed by the solver as well
notifyNotReadyForSleeping();
return wc;
}
}
mLLBody.sleepLinVelAcc = bcSleepLinVelAcc;
mLLBody.sleepAngVelAcc = bcSleepAngVelAcc;
}
wc = PxMax(wc-dt, 0.0f);
core.setWakeCounterFromSim(wc);
return wc;
}
PX_FORCE_INLINE void BodySim::initKinematicStateBase(BodyCore&, bool asPartOfCreation)
{
PX_ASSERT(!readInternalFlag(BF_KINEMATIC_MOVED));
if (!asPartOfCreation && isActive())
mScene.swapInActiveBodyList(*this);
//mLLBody.setAccelerationV(Cm::SpatialVector::zero());
// Need to be before setting setRigidBodyFlag::KINEMATIC
}
bool BodySim::updateForces(PxReal dt, PxsRigidBody** updatedBodySims, PxU32* updatedBodyNodeIndices, PxU32& index, Cm::SpatialVector* acceleration)
{
PxVec3 linVelDt(0.0f), angVelDt(0.0f);
const bool accDirty = readVelocityModFlag(VMF_ACC_DIRTY);
const bool velDirty = readVelocityModFlag(VMF_VEL_DIRTY);
SimStateData* simStateData = NULL;
bool forceChangeApplied = false;
//if we change the logic like this, which means we don't need to have two seperate variables in the pxgbodysim to represent linAcc and angAcc. However, this
//means angAcc will be always 0
if( (accDirty || velDirty) && ((simStateData = getSimStateData(false)) != NULL) )
{
VelocityMod* velmod = simStateData->getVelocityModData();
//we don't have support for articulation yet
if (updatedBodySims)
{
updatedBodySims[index] = &getLowLevelBody();
updatedBodyNodeIndices[index++] = getNodeIndex().index();
}
if(velDirty)
{
linVelDt = velmod->getLinearVelModPerStep();
angVelDt = velmod->getAngularVelModPerStep();
}
if (accDirty)
{
linVelDt += velmod->getLinearVelModPerSec()*dt;
angVelDt += velmod->getAngularVelModPerSec()*dt;
}
if (acceleration)
{
const PxReal invDt = 1.f / dt;
acceleration->linear = linVelDt * invDt;
acceleration->angular = angVelDt * invDt;
}
else
{
getBodyCore().updateVelocities(linVelDt, angVelDt);
}
forceChangeApplied = true;
}
setForcesToDefaults(readVelocityModFlag(VMF_ACC_DIRTY));
return forceChangeApplied;
}
void BodySim::onConstraintDetach()
{
PX_ASSERT(readInternalFlag(BF_HAS_CONSTRAINTS));
PxU32 size = getActorInteractionCount();
Interaction** interactions = getActorInteractions();
unregisterCountedInteraction();
while(size--)
{
const Interaction* interaction = *interactions++;
if(interaction->getType() == InteractionType::eCONSTRAINTSHADER)
return;
}
clearInternalFlag(BF_HAS_CONSTRAINTS); // There are no other constraint interactions left
}
void BodySim::setArticulation(ArticulationSim* a, PxReal wakeCounter, bool asleep, PxU32 bodyIndex)
{
mArticulation = a;
if(a)
{
PxNodeIndex index = mArticulation->getIslandNodeIndex();
mNodeIndex.setIndices(index.index(), bodyIndex);
getBodyCore().setWakeCounterFromSim(wakeCounter);
if (getFlagsFast() & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD)
mScene.setSpeculativeCCDArticulationLink(mNodeIndex.index());
//Articulations defer registering their shapes with the nphaseContext until the IG node index is known.
{
ElementSim** current = getElements();
PxU32 nbElements = getNbElements();
while (nbElements--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*current++);
mScene.getLowLevelContext()->getNphaseImplementationContext()->registerShape(mNodeIndex, sim->getCore().getCore(), sim->getElementID(), sim->getActor().getPxActor());
}
}
//Force node index into LL shapes
setBodyNodeIndex(mNodeIndex);
if (a->getCore().getArticulationFlags() & PxArticulationFlag::eDISABLE_SELF_COLLISION)
{
//We need to reset the group IDs for all shapes in this body...
ElementSim** current = getElements();
PxU32 nbElements = getNbElements();
Bp::AABBManagerBase* aabbMgr = mScene.getAABBManager();
Bp::FilterGroup::Enum rootGroup = Bp::getFilterGroup(false, a->getRootActorIndex(), false);
while (nbElements--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*current++);
aabbMgr->setBPGroup(sim->getElementID(), rootGroup);
}
}
if (!asleep)
{
setActive(true);
notifyWakeUp();
}
else
{
notifyReadyForSleeping();
notifyPutToSleep();
setActive(false);
}
}
else
{
//Setting a 1 in the articulation ID to avoid returning the node Index to the node index
//manager
mNodeIndex.setIndices(PX_INVALID_NODE, 1);
}
}
void BodySim::createSqBounds()
{
if(!isActive() || usingSqKinematicTarget() || readInternalFlag(BF_IS_COMPOUND_RIGID))
return;
PX_ASSERT(!isFrozen());
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* current = static_cast<ShapeSim*>(*elems++);
current->createSqBounds();
}
}
void BodySim::destroySqBounds()
{
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* current = static_cast<ShapeSim*>(*elems++);
current->destroySqBounds();
}
}
void BodySim::freezeTransforms(PxBitMapPinned* shapeChangedMap)
{
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*elems++);
sim->updateCached(PxsTransformFlag::eFROZEN, shapeChangedMap);
sim->destroySqBounds();
}
}
void BodySim::disableCompound()
{
if(isActive())
mScene.removeFromActiveCompoundBodyList(*this);
clearInternalFlag(BF_IS_COMPOUND_RIGID);
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothSim.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScFEMClothSim.h"
#include "ScFEMClothCore.h"
#include "ScScene.h"
#include "ScInteraction.h" // to be deleted
#include "PxsSimulationController.h"
using namespace physx;
using namespace physx::Dy;
Sc::FEMClothSim::FEMClothSim(FEMClothCore& core, Scene& scene) :
ActorSim(scene, core),
mShapeSim(*this)
{
mLLFEMCloth = scene.createLLFEMCloth(this);
mNodeIndex = scene.getSimpleIslandManager()->addFEMCloth(mLLFEMCloth, false);
scene.getSimpleIslandManager()->activateNode(mNodeIndex);
mLLFEMCloth->setElementId(mShapeSim.getElementID());
}
Sc::FEMClothSim::~FEMClothSim()
{
if (!mLLFEMCloth)
return;
mScene.destroyLLFEMCloth(*mLLFEMCloth);
mScene.getSimpleIslandManager()->removeNode(mNodeIndex);
mCore.setSim(NULL);
}
void Sc::FEMClothSim::updateBounds()
{
mShapeSim.updateBounds();
}
void Sc::FEMClothSim::updateBoundsInAABBMgr()
{
mShapeSim.updateBoundsInAABBMgr();
}
PxBounds3 Sc::FEMClothSim::getBounds() const
{
return mShapeSim.getBounds();
}
bool Sc::FEMClothSim::isSleeping() const
{
IG::IslandSim& sim = mScene.getSimpleIslandManager()->getAccurateIslandSim();
return sim.getActiveNodeIndex(mNodeIndex) == PX_INVALID_NODE;
}
void Sc::FEMClothSim::onSetWakeCounter()
{
getScene().getSimulationController()->setClothWakeCounter(mLLFEMCloth);
if (mLLFEMCloth->getCore().wakeCounter > 0.f)
getScene().getSimpleIslandManager()->activateNode(mNodeIndex);
else
getScene().getSimpleIslandManager()->deactivateNode(mNodeIndex);
}
void Sc::FEMClothSim::attachShapeCore(ShapeCore* core)
{
mShapeSim.attachShapeCore(core);
PxsShapeCore* shapeCore = const_cast<PxsShapeCore*>(&core->getCore());
mLLFEMCloth->setShapeCore(shapeCore);
}
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScRigidCore.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 "ScRigidCore.h"
#include "ScStaticCore.h"
#include "ScRigidSim.h"
#include "ScShapeSim.h"
#include "ScScene.h"
using namespace physx;
using namespace Sc;
static ShapeSim& getSimForShape(const ShapeCore& core, const ActorSim& actorSim)
{
if(core.getExclusiveSim())
{
return *core.getExclusiveSim();
}
//Must be a shared shape.
//Search backwards to emulate the behaviour of the previous linked list.
PxU32 nbElems = actorSim.getNbElements();
ElementSim*const* elems = actorSim.getElements() + (nbElems - 1);
while (nbElems--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*elems--);
if (&sim->getCore() == &core)
return *sim;
}
PX_ASSERT(0); // should never fail
return *reinterpret_cast<ShapeSim*>(1);
}
RigidCore::RigidCore(const PxActorType::Enum type) : ActorCore(type, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0)
{
}
RigidCore::~RigidCore()
{
}
void RigidCore::addShapeToScene(ShapeCore& shapeCore)
{
RigidSim* sim = getSim();
PX_ASSERT(sim);
if(!sim)
return;
sim->getScene().addShape_(*sim, shapeCore);
}
void RigidCore::removeShapeFromScene(ShapeCore& shapeCore, bool wakeOnLostTouch)
{
RigidSim* sim = getSim();
if(!sim)
return;
ShapeSim& s = getSimForShape(shapeCore, *sim);
sim->getScene().removeShape_(s, wakeOnLostTouch);
}
void RigidCore::unregisterShapeFromNphase(Sc::ShapeCore& shapeCore)
{
RigidSim* sim = getSim();
if (!sim)
return;
ShapeSim& s = getSimForShape(shapeCore, *sim);
s.getScene().unregisterShapeFromNphase(shapeCore, s.getElementID());
}
void RigidCore::registerShapeInNphase(Sc::ShapeCore& shapeCore)
{
RigidSim* sim = getSim();
if (!sim)
return;
ShapeSim& s = getSimForShape(shapeCore, *sim);
s.getScene().registerShapeInNphase(this, shapeCore, s.getElementID());
}
void RigidCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags)
{
RigidSim* sim = getSim();
if(!sim)
return;
ShapeSim& s = getSimForShape(shape, *sim);
if(notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY)
s.onVolumeOrTransformChange();
if(notifyFlags & ShapeChangeNotifyFlag::eMATERIAL)
s.onMaterialChange();
if(notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING)
s.onResetFiltering();
if(notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY)
s.onVolumeOrTransformChange();
if(notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA)
s.onFilterDataChange();
if(notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET)
s.onContactOffsetChange();
if(notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET)
s.onRestOffsetChange();
}
void RigidCore::onShapeFlagsChange(ShapeCore& shape, PxShapeFlags oldShapeFlags)
{
// DS: We pass flags to avoid searching multiple times or exposing RigidSim outside SC.
//If we start hitting this a lot we should do it
// a different way, but shape modification after insertion is rare.
RigidSim* sim = getSim();
if(!sim)
return;
ShapeSim& s = getSimForShape(shape, *sim);
s.onFlagChange(oldShapeFlags);
}
RigidSim* RigidCore::getSim() const
{
return static_cast<RigidSim*>(ActorCore::getSim());
}
PxU32 RigidCore::getRigidID() const
{
return static_cast<RigidSim*>(ActorCore::getSim())->getActorID();
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemSim.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.
#ifndef SC_HAIR_SYSTEM_SIM_H
#define SC_HAIR_SYSTEM_SIM_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "DyHairSystem.h"
#include "ScHairSystemCore.h"
#include "ScHairSystemShapeSim.h"
#include "ScActorSim.h"
namespace physx
{
namespace Sc
{
class Scene;
class HairSystemSim : public ActorSim
{
PX_NOCOPY(HairSystemSim)
public:
HairSystemSim(HairSystemCore& core, Scene& scene);
~HairSystemSim();
PX_INLINE Dy::HairSystem* getLowLevelHairSystem() const { return mLLHairSystem; }
PX_INLINE HairSystemCore& getCore() const { return static_cast<HairSystemCore&>(mCore); }
virtual PxActor* getPxActor() const { return getCore().getPxActor(); }
PxBounds3 getBounds() const;
void updateBounds();
void updateBoundsInAABBMgr();
bool isSleeping() const;
bool isActive() const { return !isSleeping(); }
void setActive(bool active, bool asPartOfCreation=false);
void onSetWakeCounter();
HairSystemShapeSim& getShapeSim() { return mShapeSim; }
private:
Dy::HairSystem* mLLHairSystem;
HairSystemShapeSim mShapeSim;
// PT: as far as I can tell these are never actually called
// void activate();
// void deactivate();
};
} // namespace Sc
} // namespace physx
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemSim.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScHairSystemSim.h"
#include "ScHairSystemCore.h"
#include "ScHairSystemShapeCore.h"
#include "ScScene.h"
#include "PxsSimulationController.h"
using namespace physx;
using namespace physx::Dy;
Sc::HairSystemSim::HairSystemSim(HairSystemCore& core, Scene& scene) :
ActorSim(scene, core),
mShapeSim(*this, &core.getShapeCore())
{
mLLHairSystem = scene.createLLHairSystem(this);
mNodeIndex = scene.getSimpleIslandManager()->addHairSystem(mLLHairSystem, false);
scene.getSimpleIslandManager()->activateNode(mNodeIndex);
mLLHairSystem->setElementId(mShapeSim.getElementID());
PxHairSystemGeometry geometry;
core.getShapeCore().setGeometry(geometry);
PxsShapeCore* shapeCore = const_cast<PxsShapeCore*>(&core.getShapeCore().getCore());
mLLHairSystem->setShapeCore(shapeCore);
}
Sc::HairSystemSim::~HairSystemSim()
{
if (!mLLHairSystem) {
return;
}
mScene.destroyLLHairSystem(*mLLHairSystem);
mScene.getSimpleIslandManager()->removeNode(mNodeIndex);
mCore.setSim(NULL);
}
void Sc::HairSystemSim::updateBounds()
{
mShapeSim.updateBounds();
}
void Sc::HairSystemSim::updateBoundsInAABBMgr()
{
mShapeSim.updateBoundsInAABBMgr();
}
PxBounds3 Sc::HairSystemSim::getBounds() const
{
return mShapeSim.getBounds();
}
bool Sc::HairSystemSim::isSleeping() const
{
IG::IslandSim& sim = mScene.getSimpleIslandManager()->getAccurateIslandSim();
return sim.getActiveNodeIndex(mNodeIndex) == PX_INVALID_NODE;
}
void Sc::HairSystemSim::onSetWakeCounter()
{
getScene().getSimulationController()->setHairSystemWakeCounter(mLLHairSystem);
if (mLLHairSystem->getCore().mWakeCounter > 0.0f) {
getScene().getSimpleIslandManager()->activateNode(mNodeIndex);
}
else
{
getScene().getSimpleIslandManager()->deactivateNode(mNodeIndex);
}
}
/*void Sc::HairSystemSim::activate()
{
activateInteractions(*this);
}
void Sc::HairSystemSim::deactivate()
{
deactivateInteractions(*this);
}*/
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemCore.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScHairSystemCore.h"
#include "ScHairSystemSim.h"
#include "ScPhysics.h"
namespace physx
{
namespace Sc
{
HairSystemCore::HairSystemCore()
: ActorCore(PxActorType::eHAIRSYSTEM, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0)
{
}
HairSystemCore::~HairSystemCore() {}
void HairSystemCore::setMaterial(const PxU16 handle) { mShapeCore.getLLCore().setMaterial(handle); }
void HairSystemCore::clearMaterials() { mShapeCore.getLLCore().clearMaterials(); }
void HairSystemCore::setSleepThreshold(const PxReal v)
{
mShapeCore.getLLCore().mSleepThreshold = v;
mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS;
}
void HairSystemCore::setSolverIterationCounts(const PxU16 c)
{
mShapeCore.getLLCore().mSolverIterationCounts = c;
mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS;
}
void HairSystemCore::setWakeCounter(const PxReal v)
{
mShapeCore.getLLCore().mWakeCounter = v;
mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS;
HairSystemSim* sim = getSim();
if(sim)
{
sim->onSetWakeCounter();
}
}
bool HairSystemCore::isSleeping() const
{
HairSystemSim* sim = getSim();
return sim ? sim->isSleeping() : (mShapeCore.getLLCore().mWakeCounter == 0.0f);
}
void HairSystemCore::wakeUp(PxReal wakeCounter)
{
mShapeCore.getLLCore().mWakeCounter = wakeCounter;
mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS;
}
void HairSystemCore::putToSleep()
{
mShapeCore.getLLCore().mWakeCounter = 0.0f;
mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS;
}
PxActor* HairSystemCore::getPxActor() const
{
return PxPointerOffset<PxActor*>(const_cast<HairSystemCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]);
}
HairSystemSim* HairSystemCore::getSim() const { return static_cast<HairSystemSim*>(ActorCore::getSim()); }
PxReal HairSystemCore::getContactOffset() const { return mShapeCore.getContactOffset(); }
void HairSystemCore::setContactOffset(PxReal v)
{
mShapeCore.setContactOffset(v);
HairSystemSim* sim = getSim();
if(sim)
{
sim->getScene().updateContactDistance(sim->getShapeSim().getElementID(), v);
}
}
void HairSystemCore::addAttachment(const BodySim& bodySim)
{
const HairSystemSim* sim = getSim();
if(sim)
{
sim->getScene().addAttachment(bodySim, *sim);
}
}
void HairSystemCore::removeAttachment(const BodySim& bodySim)
{
const HairSystemSim* sim = getSim();
if(sim)
{
sim->getScene().removeAttachment(bodySim, *sim);
}
}
void HairSystemCore::addAttachment(const SoftBodySim& sbSim)
{
const Sc::HairSystemSim* sim = getSim();
if(sim)
{
sim->getScene().addAttachment(sbSim, *sim);
}
}
void HairSystemCore::removeAttachment(const SoftBodySim& sbSim)
{
const Sc::HairSystemSim* sim = getSim();
if(sim)
{
sim->getScene().removeAttachment(sbSim, *sim);
}
}
void Sc::HairSystemCore::setFlags(PxHairSystemFlags flags)
{
mShapeCore.getLLCore().mParams.mFlags = flags;
mShapeCore.getLLCore().mDirtyFlags |= Dy::HairSystemDirtyFlag::ePARAMETERS;
}
} // namespace Sc
} // namespace physx
#endif // PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSleep.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 "ScScene.h"
#include "ScArticulationSim.h"
#include "ScBodySim.h"
#include "common/PxProfileZone.h"
#include "ScActorSim.h"
#include "ScArticulationSim.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScSoftBodySim.h"
#include "ScFEMClothSim.h"
#include "ScParticleSystemSim.h"
#include "ScHairSystemSim.h"
#endif
using namespace physx;
using namespace physx::Cm;
using namespace physx::Dy;
using namespace Sc;
// PT: "setActive()" moved from ActorSim to BodySim because GPU classes silently re-implement this in a very different way (see below),
// i.e. it defeats the purpose of the virtual activate()/deactivate() functions.
void Sc::BodySim::setActive(bool active, bool asPartOfCreation)
{
PX_ASSERT(!active || isDynamicRigid()); // Currently there should be no need to activate an actor that does not take part in island generation
if(asPartOfCreation || isActive() != active)
{
PX_ASSERT(!asPartOfCreation || (getActorInteractionCount() == 0)); // On creation or destruction there should be no interactions
if(active)
{
if(!asPartOfCreation)
getScene().addToActiveList(*this); // Inactive => Active
activate();
PX_ASSERT(asPartOfCreation || isActive());
}
else
{
if(!asPartOfCreation)
getScene().removeFromActiveList(*this); // Active => Inactive
deactivate();
PX_ASSERT(asPartOfCreation || (!isActive()));
}
}
}
void Sc::ArticulationSim::setActive(bool b, bool asPartOfCreation)
{
const PxReal wakeCounter = mCore.getWakeCounter();
const PxU32 nbBodies = mBodies.size();
for(PxU32 i=0;i<nbBodies;i++)
{
if(i+1 < nbBodies)
{
PxPrefetchLine(mBodies[i+1],0);
PxPrefetchLine(mBodies[i+1],128);
}
//KS - force in the wake counter from the articulation to its links. This is required because
//GPU articulation simulation does not DMA back wake counters for each link - it just brings back a global wake counter
mBodies[i]->getBodyCore().setWakeCounterFromSim(wakeCounter);
mBodies[i]->setActive(b, asPartOfCreation);
}
}
// PT: moving all the sleeping-related implementations to the same file clearly exposes the inconsistencies between them
#if PX_SUPPORT_GPU_PHYSX
void Sc::ParticleSystemSim::setActive(bool /*active*/, bool /*asPartOfCreation*/)
{
}
void Sc::FEMClothSim::activate()
{
mScene.getSimulationController()->activateCloth(mLLFEMCloth);
activateInteractions(*this);
}
void Sc::FEMClothSim::deactivate()
{
mScene.getSimulationController()->deactivateCloth(mLLFEMCloth);
deactivateInteractions(*this);
}
void Sc::FEMClothSim::setActive(bool active, bool /*asPartOfCreation*/)
{
if(active)
activate();
else
deactivate();
}
void Sc::SoftBodySim::setActive(bool active, bool /*asPartOfCreation*/)
{
if(active)
getScene().getSimulationController()->activateSoftbody(mLLSoftBody);
else
getScene().getSimulationController()->deactivateSoftbody(mLLSoftBody);
}
void Sc::HairSystemSim::setActive(bool active, bool /*asPartOfCreation*/)
{
if(active)
getScene().getSimulationController()->activateHairSystem(mLLHairSystem);
else
getScene().getSimulationController()->deactivateHairSystem(mLLHairSystem);
}
#endif
namespace
{
struct GetRigidSim { static PX_FORCE_INLINE BodySim* getSim(const IG::Node& node) { return reinterpret_cast<BodySim*>(reinterpret_cast<PxU8*>(node.mRigidBody) - BodySim::getRigidBodyOffset()); } };
struct GetArticSim { static PX_FORCE_INLINE ArticulationSim* getSim(const IG::Node& node) { return reinterpret_cast<ArticulationSim*>(node.mLLArticulation->getUserData()); } };
#if PX_SUPPORT_GPU_PHYSX
struct GetSoftBodySim { static PX_FORCE_INLINE SoftBodySim* getSim(const IG::Node& node) { return node.mLLSoftBody->getSoftBodySim(); } };
struct GetFEMClothSim { static PX_FORCE_INLINE FEMClothSim* getSim(const IG::Node& node) { return node.mLLFEMCloth->getFEMClothSim(); } };
struct GetHairSystemSim { static PX_FORCE_INLINE HairSystemSim* getSim(const IG::Node& node) { return node.mLLHairSystem->getHairSystemSim(); } };
#endif
}
template<class SimT, class SimAccessT, const bool active>
static void setActive(PxU32& nbModified, const IG::IslandSim& islandSim, IG::Node::NodeType type)
{
PxU32 nbToProcess = active ? islandSim.getNbNodesToActivate(type) : islandSim.getNbNodesToDeactivate(type);
const PxNodeIndex* indices = active ? islandSim.getNodesToActivate(type) : islandSim.getNodesToDeactivate(type);
while(nbToProcess--)
{
const IG::Node& node = islandSim.getNode(*indices++);
PX_ASSERT(node.mType == type);
if(node.isActive()==active)
{
SimT* sim = SimAccessT::getSim(node);
if(sim)
{
sim->setActive(active);
nbModified++;
}
}
}
}
#ifdef BATCHED
namespace
{
struct SetActiveRigidSim
{
template<const bool active>
static void setActive(Scene& /*scene*/, PxU32 nbObjects, BodySim** objects)
{
if(1)
{
while(nbObjects--)
{
(*objects)->setActive(active);
objects++;
}
}
else
{
if(active)
{
// scene.addToActiveList(*this);
// activate();
// PX_ASSERT(isActive());
}
else
{
// scene.removeFromActiveList(*this);
// deactivate();
// PX_ASSERT(!isActive());
}
}
}
};
}
template<class SimT, class SimAccessT, class SetActiveBatchedT, const bool active>
static void setActiveBatched(Scene& scene, PxU32& nbModified, const IG::IslandSim& islandSim, IG::Node::NodeType type)
{
PxU32 nbToProcess = active ? islandSim.getNbNodesToActivate(type) : islandSim.getNbNodesToDeactivate(type);
const PxNodeIndex* indices = active ? islandSim.getNodesToActivate(type) : islandSim.getNodesToDeactivate(type);
PX_ALLOCA(batch, SimT*, nbToProcess);
PxU32 nb = 0;
while(nbToProcess--)
{
const IG::Node& node = islandSim.getNode(*indices++);
PX_ASSERT(node.mType == type);
if(node.isActive()==active)
{
SimT* sim = SimAccessT::getSim(node);
if(sim && sim->isActive()!=active)
batch.mPointer[nb++] = sim;
}
}
SetActiveBatchedT::setActive<active>(scene, nb, batch.mPointer);
nbModified = nb;
}
/*
Batched version would be just:
a) addToActiveList(batched objects)
b) activate(batched objects)
void Sc::ActorSim::setActive(bool active)
{
PX_ASSERT(!active || isDynamicRigid()); // Currently there should be no need to activate an actor that does not take part in island generation
if(isActive() != active)
{
if(active)
{
// Inactive => Active
getScene().addToActiveList(*this);
activate();
PX_ASSERT(isActive());
}
else
{
// Active => Inactive
getScene().removeFromActiveList(*this);
deactivate();
PX_ASSERT(!isActive());
}
}
}
*/
#endif
void Sc::Scene::putObjectsToSleep()
{
PX_PROFILE_ZONE("Sc::Scene::putObjectsToSleep", mContextId);
//Set to sleep all bodies that were in awake islands that have just been put to sleep.
const IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim();
PxU32 nbBodiesDeactivated = 0;
//setActiveBatched<BodySim, GetRigidSim, SetActiveRigidSim, false>(*this, nbBodiesDeactivated, islandSim, IG::Node::eRIGID_BODY_TYPE);
setActive<BodySim, GetRigidSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eRIGID_BODY_TYPE);
setActive<ArticulationSim, GetArticSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eARTICULATION_TYPE);
#if PX_SUPPORT_GPU_PHYSX
setActive<SoftBodySim, GetSoftBodySim, false>(nbBodiesDeactivated, islandSim, IG::Node::eSOFTBODY_TYPE);
setActive<FEMClothSim, GetFEMClothSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eFEMCLOTH_TYPE);
setActive<HairSystemSim, GetHairSystemSim, false>(nbBodiesDeactivated, islandSim, IG::Node::eHAIRSYSTEM_TYPE);
#endif
if(nbBodiesDeactivated)
mDynamicsContext->setStateDirty(true);
}
void Sc::Scene::wakeObjectsUp()
{
PX_PROFILE_ZONE("Sc::Scene::wakeObjectsUp", mContextId);
//Wake up all bodies that were in sleeping islands that have just been hit by a moving object.
const IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim();
PxU32 nbBodiesWoken = 0;
setActive<BodySim, GetRigidSim, true>(nbBodiesWoken, islandSim, IG::Node::eRIGID_BODY_TYPE);
setActive<ArticulationSim, GetArticSim, true>(nbBodiesWoken, islandSim, IG::Node::eARTICULATION_TYPE);
#if PX_SUPPORT_GPU_PHYSX
setActive<SoftBodySim, GetSoftBodySim, true>(nbBodiesWoken, islandSim, IG::Node::eSOFTBODY_TYPE);
setActive<FEMClothSim, GetFEMClothSim, true>(nbBodiesWoken, islandSim, IG::Node::eFEMCLOTH_TYPE);
setActive<HairSystemSim, GetHairSystemSim, true>(nbBodiesWoken, islandSim, IG::Node::eHAIRSYSTEM_TYPE);
#endif
if(nbBodiesWoken)
mDynamicsContext->setStateDirty(true);
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSqBoundsManager.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 SC_SQ_BOUNDS_MANAGER_H
#define SC_SQ_BOUNDS_MANAGER_H
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxArray.h"
#include "ScSqBoundsSync.h"
namespace physx
{
class PxBounds3;
namespace Sc
{
struct SqBoundsSync;
struct SqRefFinder;
class ShapeSimBase;
class SqBoundsManager0 : public PxUserAllocated
{
PX_NOCOPY(SqBoundsManager0)
public:
SqBoundsManager0();
void addSyncShape(ShapeSimBase& shape);
void removeSyncShape(ShapeSimBase& shape);
void syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices);
private:
PxArray<ShapeSimBase*> mShapes; //
PxArray<ScPrunerHandle> mRefs; // SQ pruner references
PxArray<PxU32> mBoundsIndices; // indices into the Sc bounds array
PxArray<ShapeSimBase*> mRefless; // shapesims without references
};
class SqBoundsManagerEx : public PxUserAllocated
{
PX_NOCOPY(SqBoundsManagerEx)
public:
SqBoundsManagerEx();
~SqBoundsManagerEx();
void addSyncShape(ShapeSimBase& shape);
void removeSyncShape(ShapeSimBase& shape);
void syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices);
private:
PxArray<ShapeSimBase*> mWaitingRoom;
// PT: one of the many solutions discussed in https://confluence.nvidia.com/display/~pterdiman/The+new+SQ+system
// Just to get something working. This will most likely need revisiting later.
struct PrunerSyncData : public PxUserAllocated
{
PxArray<ShapeSimBase*> mShapes; //
// PT: layout dictated by the SqPruner API here. We could consider merging these two arrays.
PxArray<ScPrunerHandle> mRefs; // SQ pruner references
PxArray<PxU32> mBoundsIndices; // indices into the Sc bounds array
};
PrunerSyncData** mPrunerSyncData;
PxU32 mPrunerSyncDataSize;
void resize(PxU32 index);
};
//class SqBoundsManager : public SqBoundsManager0
class SqBoundsManager : public SqBoundsManagerEx
{
public:
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScParticleSystemCore.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScParticleSystemCore.h"
#include "ScPhysics.h"
#include "ScParticleSystemSim.h"
#include "DyParticleSystem.h"
#include "PxvGlobals.h"
#include "PxPhysXGpu.h"
using namespace physx;
Sc::ParticleSystemCore::ParticleSystemCore(PxActorType::Enum actorType) :
ActorCore(actorType, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0)
{
}
Sc::ParticleSystemCore::~ParticleSystemCore()
{
}
Sc::ParticleSystemSim* Sc::ParticleSystemCore::getSim() const
{
return static_cast<ParticleSystemSim*>(ActorCore::getSim());
}
PxReal Sc::ParticleSystemCore::getSleepThreshold() const
{
return mShapeCore.getLLCore().sleepThreshold;//mCore.sleepThreshold;
}
void Sc::ParticleSystemCore::setSleepThreshold(const PxReal v)
{
mShapeCore.getLLCore().sleepThreshold = v;
}
PxReal Sc::ParticleSystemCore::getRestOffset() const
{
return mShapeCore.getLLCore().restOffset;
}
void Sc::ParticleSystemCore::setRestOffset(const PxReal v)
{
mShapeCore.getLLCore().restOffset = v;
}
PxReal Sc::ParticleSystemCore::getContactOffset() const
{
return mShapeCore.getContactOffset();
}
void Sc::ParticleSystemCore::setContactOffset(const PxReal v)
{
mShapeCore.setContactOffset(v);
Sc::ParticleSystemSim* sim = getSim();
if (sim)
{
sim->getScene().updateContactDistance(sim->getShapeSim().getElementID(), v);
}
}
PxReal Sc::ParticleSystemCore::getParticleContactOffset() const
{
return mShapeCore.getLLCore().particleContactOffset;
}
void Sc::ParticleSystemCore::setParticleContactOffset(const PxReal v)
{
mShapeCore.getLLCore().particleContactOffset = v;
}
PxReal Sc::ParticleSystemCore::getSolidRestOffset() const
{
return mShapeCore.getLLCore().solidRestOffset;
}
void Sc::ParticleSystemCore::setSolidRestOffset(const PxReal v)
{
mShapeCore.getLLCore().solidRestOffset = v;
}
PxReal Sc::ParticleSystemCore::getFluidRestOffset() const
{
return mShapeCore.getLLCore().fluidRestOffset;
}
void Sc::ParticleSystemCore::setFluidRestOffset(const PxReal v)
{
mShapeCore.getLLCore().fluidRestOffset = v;
}
void Sc::ParticleSystemCore::setMaxDepenetrationVelocity(const PxReal v)
{
mShapeCore.getLLCore().maxDepenetrationVelocity = v;
}
PxReal Sc::ParticleSystemCore::getMaxDepenetrationVelocity() const
{
return mShapeCore.getLLCore().maxDepenetrationVelocity;
}
void Sc::ParticleSystemCore::setMaxVelocity(const PxReal v)
{
mShapeCore.getLLCore().maxVelocity = v;
}
PxReal Sc::ParticleSystemCore::getMaxVelocity() const
{
return mShapeCore.getLLCore().maxVelocity;
}
PxParticleSystemCallback* Sc::ParticleSystemCore::getParticleSystemCallback() const
{
return mShapeCore.getLLCore().mCallback;
}
void Sc::ParticleSystemCore::setParticleSystemCallback(PxParticleSystemCallback* callback)
{
mShapeCore.getLLCore().mCallback = callback;
}
PxReal Sc::ParticleSystemCore::getFluidBoundaryDensityScale() const
{
return mShapeCore.getLLCore().fluidBoundaryDensityScale;
}
void Sc::ParticleSystemCore::setFluidBoundaryDensityScale(const PxReal v)
{
mShapeCore.getLLCore().fluidBoundaryDensityScale = v;
}
PxU32 Sc::ParticleSystemCore::getGridSizeX() const
{
return mShapeCore.getLLCore().gridSizeX;
}
void Sc::ParticleSystemCore::setGridSizeX(const PxU32 v)
{
mShapeCore.getLLCore().gridSizeX = v;
}
PxU32 Sc::ParticleSystemCore::getGridSizeY() const
{
return mShapeCore.getLLCore().gridSizeY;
}
void Sc::ParticleSystemCore::setGridSizeY(const PxU32 v)
{
mShapeCore.getLLCore().gridSizeY = v;
}
PxU32 Sc::ParticleSystemCore::getGridSizeZ() const
{
return mShapeCore.getLLCore().gridSizeZ;
}
void Sc::ParticleSystemCore::setGridSizeZ(const PxU32 v)
{
mShapeCore.getLLCore().gridSizeZ = v;
}
void Sc::ParticleSystemCore::setSolverIterationCounts(PxU16 c)
{
mShapeCore.getLLCore().solverIterationCounts = c;
}
PxReal Sc::ParticleSystemCore::getWakeCounter() const
{
return mShapeCore.getLLCore().wakeCounter;
}
void Sc::ParticleSystemCore::setWakeCounter(const PxReal v)
{
mShapeCore.getLLCore().wakeCounter = v;
}
void Sc::ParticleSystemCore::setWakeCounterInternal(const PxReal v)
{
mShapeCore.getLLCore().wakeCounter = v;
}
bool Sc::ParticleSystemCore::isSleeping() const
{
Sc::ParticleSystemSim* sim = getSim();
return sim ? sim->isSleeping() : (mShapeCore.getLLCore().wakeCounter == 0.0f);
}
void Sc::ParticleSystemCore::wakeUp(PxReal wakeCounter)
{
mShapeCore.getLLCore().wakeCounter = wakeCounter;
}
void Sc::ParticleSystemCore::putToSleep()
{
mShapeCore.getLLCore().wakeCounter = 0.0f;
}
PxActor* Sc::ParticleSystemCore::getPxActor() const
{
return PxPointerOffset<PxActor*>(const_cast<ParticleSystemCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]);
}
// TOFIX
void Sc::ParticleSystemCore::enableCCD(const bool enable)
{
mShapeCore.getLLCore().enableCCD = enable;
}
void Sc::ParticleSystemCore::addRigidAttachment(Sc::BodyCore* core)
{
Sc::ParticleSystemSim* sim = getSim();
if(sim)
sim->getScene().addRigidAttachment(core, *sim);
}
void Sc::ParticleSystemCore::removeRigidAttachment(Sc::BodyCore* core)
{
Sc::ParticleSystemSim* sim = getSim();
if (sim)
sim->getScene().removeRigidAttachment(core, *sim);
}
void Sc::ParticleSystemCore::setFlags(PxParticleFlags flags)
{
Sc::ParticleSystemSim* sim = getSim();
PxParticleFlags oldFlags = mShapeCore.getLLCore().mFlags;
mShapeCore.getLLCore().mFlags = flags;
if (sim)
{
bool wasRigidCollisionDisabled = oldFlags & PxParticleFlag::eDISABLE_RIGID_COLLISION;
bool isRigidCollisionDisabled = flags & PxParticleFlag::eDISABLE_RIGID_COLLISION;
if (wasRigidCollisionDisabled ^ isRigidCollisionDisabled)
{
if (wasRigidCollisionDisabled)
sim->getShapeSim().createLowLevelVolume();
else
sim->getShapeSim().destroyLowLevelVolume();
}
}
}
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothCore.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"
#if PX_SUPPORT_GPU_PHYSX
#include "ScFEMClothCore.h"
#include "ScPhysics.h"
#include "ScFEMClothSim.h"
#include "DyFEMCloth.h"
#include "GuTetrahedronMesh.h"
#include "GuBV4.h"
#include "geometry/PxTetrahedronMesh.h"
#include "cudamanager/PxCudaContextManager.h"
using namespace physx;
Sc::FEMClothCore::FEMClothCore() :
ActorCore(PxActorType::eFEMCLOTH, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0),
mGpuMemStat(0)
{
mCore.solverIterationCounts = (1 << 8) | 4;
mCore.dirty = true;
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
mCore.mFlags = PxFEMClothFlags(0);
#endif
mCore.mPositionInvMass = NULL;
mCore.mVelocity = NULL;
mCore.mRestPosition = NULL;
mCore.wakeCounter = Physics::sWakeCounterOnCreation;
}
Sc::FEMClothCore::~FEMClothCore() { }
PxFEMParameters Sc::FEMClothCore::getParameter() const
{
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
return mCore.parameters;
#else
return PxFEMParameters();
#endif
}
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
void Sc::FEMClothCore::setParameter(const PxFEMParameters& parameter)
{
mCore.parameters = parameter;
mCore.dirty = true;
}
#else
void Sc::FEMClothCore::setParameter(const PxFEMParameters&)
{
mCore.dirty = true;
}
#endif
void Sc::FEMClothCore::addRigidFilter(Sc::BodyCore* core, PxU32 vertId)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->getScene().addRigidFilter(core, *sim, vertId);
}
void Sc::FEMClothCore::removeRigidFilter(Sc::BodyCore* core, PxU32 vertId)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->getScene().removeRigidFilter(core, *sim, vertId);
}
PxU32 Sc::FEMClothCore::addRigidAttachment(Sc::BodyCore* core, PxU32 particleId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* params)
{
Sc::FEMClothSim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
{
handle = sim->getScene().addRigidAttachment(core, *sim, particleId, actorSpacePose, params);
}
return handle;
}
void Sc::FEMClothCore::removeRigidAttachment(Sc::BodyCore* core, PxU32 handle)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
{
sim->getScene().removeRigidAttachment(core, *sim, handle);
setWakeCounter(ScInternalWakeCounterResetValue);
}
}
void Sc::FEMClothCore::addTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->getScene().addTriRigidFilter(core, *sim, triIdx);
}
void Sc::FEMClothCore::removeTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->getScene().removeTriRigidFilter(core, *sim, triIdx);
}
PxU32 Sc::FEMClothCore::addTriRigidAttachment(Sc::BodyCore* core, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint)
{
Sc::FEMClothSim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
handle = sim->getScene().addTriRigidAttachment(core, *sim, triIdx, barycentric, actorSpacePose, constraint);
return handle;
}
void Sc::FEMClothCore::removeTriRigidAttachment(Sc::BodyCore* core, PxU32 handle)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
{
sim->getScene().removeTriRigidAttachment(core, *sim, handle);
setWakeCounter(ScInternalWakeCounterResetValue);
}
}
void Sc::FEMClothCore::addClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, PxU32 triIdx)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->getScene().addClothFilter(*otherCore, otherTriIdx, *sim, triIdx);
}
void Sc::FEMClothCore::removeClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, PxU32 triIdx)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->getScene().removeClothFilter(*otherCore, otherTriIdx, *sim, triIdx);
}
PxU32 Sc::FEMClothCore::addClothAttachment(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric)
{
Sc::FEMClothSim* sim = getSim();
PxU32 handle = 0xFFFFFFFF;
if (sim)
handle = sim->getScene().addTriClothAttachment(*otherCore, otherTriIdx, otherTriBarycentric, *sim, triIdx, triBarycentric);
return handle;
}
void Sc::FEMClothCore::removeClothAttachment(Sc::FEMClothCore* otherCore, PxU32 handle)
{
Sc::FEMClothSim* sim = getSim();
setWakeCounter(ScInternalWakeCounterResetValue);
otherCore->setWakeCounter(ScInternalWakeCounterResetValue);
if (sim)
sim->getScene().removeTriClothAttachment(*otherCore, *sim, handle);
}
void Sc::FEMClothCore::setBendingScales(const PxReal* const bendingScales, PxU32 nbElements)
{
mCore.mBendingScales.assign(bendingScales, bendingScales + nbElements);
mCore.dirty = true;
}
const PxReal* Sc::FEMClothCore::getBendingScales() const
{
return mCore.mBendingScales.empty() ? NULL : mCore.mBendingScales.begin();
}
void Sc::FEMClothCore::setSolverIterationCounts(const PxU16 c)
{
mCore.solverIterationCounts = c;
mCore.dirty = true;
}
PxActor* Sc::FEMClothCore::getPxActor() const
{
return PxPointerOffset<PxActor*>(const_cast<FEMClothCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]);
}
void Sc::FEMClothCore::attachShapeCore(ShapeCore* shapeCore)
{
Sc::FEMClothSim* sim = getSim();
if (sim)
sim->attachShapeCore(shapeCore);
}
PxReal Sc::FEMClothCore::getWakeCounter() const
{
return mCore.wakeCounter;
}
void Sc::FEMClothCore::setWakeCounter(const PxReal v)
{
mCore.wakeCounter = v;
mCore.dirty = true;
Sc::FEMClothSim* sim = getSim();
if (sim)
{
sim->onSetWakeCounter();
}
}
void Sc::FEMClothCore::setWakeCounterInternal(const PxReal v)
{
mCore.wakeCounter = v;
mCore.dirty = true;
Sc::FEMClothSim* sim = getSim();
if (sim)
{
sim->onSetWakeCounter();
}
}
Sc::FEMClothSim* Sc::FEMClothCore::getSim() const
{
return static_cast<Sc::FEMClothSim*>(ActorCore::getSim());
}
void Sc::FEMClothCore::setSimulationFilterData(const PxFilterData& data)
{
mFilterData = data;
}
PxFilterData Sc::FEMClothCore::getSimulationFilterData() const
{
return mFilterData;
}
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
void Sc::FEMClothCore::setFlags(PxFEMClothFlags flags)
{
mCore.mFlags = flags;
mCore.dirty = true;
}
#endif
void Sc::FEMClothCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags)
{
PX_UNUSED(shape);
FEMClothSim* sim = getSim();
if (!sim)
return;
FEMClothShapeSim& s = sim->getShapeSim();
if (notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY)
s.onVolumeOrTransformChange();
if (notifyFlags & ShapeChangeNotifyFlag::eMATERIAL)
s.onMaterialChange();
if (notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING)
s.onResetFiltering();
if (notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY)
s.onVolumeOrTransformChange();
if (notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA)
s.onFilterDataChange();
if (notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET)
s.onContactOffsetChange();
if (notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET)
s.onRestOffsetChange();
}
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationJointSim.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 "ScArticulationJointSim.h"
#include "ScArticulationJointCore.h"
#include "ScBodySim.h"
#include "ScScene.h"
#include "PxsRigidBody.h"
#include "ScArticulationSim.h"
#include "PxsSimpleIslandManager.h"
using namespace physx;
Sc::ArticulationJointSim::ArticulationJointSim(ArticulationJointCore& joint, ActorSim& parent, ActorSim& child) :
Interaction (parent, child, InteractionType::eARTICULATION, 0),
mCore (joint)
{
{
onActivate(NULL);
registerInActors();
}
BodySim& childBody = static_cast<BodySim&>(child),
& parentBody = static_cast<BodySim&>(parent);
parentBody.getArticulation()->addBody(childBody, &parentBody, this);
mCore.setSim(this);
}
Sc::ArticulationJointSim::~ArticulationJointSim()
{
// articulation interactions do not make use of the dirty flags yet. If they did, a setClean(true) has to be introduced here.
PX_ASSERT(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST));
PX_ASSERT(!getDirtyFlags());
unregisterFromActors();
mCore.setSim(NULL);
}
Sc::BodySim& Sc::ArticulationJointSim::getParent() const
{
return static_cast<BodySim&>(getActorSim0());
}
Sc::BodySim& Sc::ArticulationJointSim::getChild() const
{
return static_cast<BodySim&>(getActorSim1());
}
bool Sc::ArticulationJointSim::onActivate(void*)
{
if(!(getParent().isActive() && getChild().isActive()))
return false;
raiseInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
bool Sc::ArticulationJointSim::onDeactivate()
{
clearInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
void Sc::ArticulationJointSim::setDirty()
{
Dy::ArticulationJointCore& llCore = mCore.getCore();
ArticulationSim* sim = mCore.getArticulation()->getSim();
sim->setJointDirty(llCore);
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScObjectIDTracker.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 SC_OBJECT_ID_TRACKER_H
#define SC_OBJECT_ID_TRACKER_H
#include "CmIDPool.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
namespace Sc
{
// PT: TODO: this has no direct dependency on "Sc". It should really be a "Cm" class.
class ObjectIDTracker : public PxUserAllocated
{
PX_NOCOPY(ObjectIDTracker)
public:
ObjectIDTracker() : mPendingReleasedIDs("objectIDTrackerIDs") {}
PX_INLINE PxU32 createID() { return mIDPool.getNewID(); }
PX_INLINE void releaseID(PxU32 id)
{
markIDAsDeleted(id);
mPendingReleasedIDs.pushBack(id);
}
PX_INLINE PxIntBool isDeletedID(PxU32 id) const { return mDeletedIDsMap.boundedTest(id); }
PX_FORCE_INLINE PxU32 getDeletedIDCount() const { return mPendingReleasedIDs.size(); }
PX_INLINE void clearDeletedIDMap() { mDeletedIDsMap.clear(); }
PX_INLINE void resizeDeletedIDMap(PxU32 id, PxU32 numIds)
{
mDeletedIDsMap.resize(id);
mPendingReleasedIDs.reserve(numIds);
}
PX_INLINE void processPendingReleases()
{
for(PxU32 i=0; i < mPendingReleasedIDs.size(); i++)
mIDPool.freeID(mPendingReleasedIDs[i]);
mPendingReleasedIDs.clear();
}
PX_INLINE void reset()
{
processPendingReleases();
mPendingReleasedIDs.reset();
// Don't free stuff in IDPool, we still need the list of free IDs
// And it does not seem worth freeing the memory of the bitmap
}
PX_INLINE PxU32 getMaxID() const
{
return mIDPool.getMaxID();
}
private:
PX_INLINE void markIDAsDeleted(PxU32 id)
{
PX_ASSERT(!isDeletedID(id));
mDeletedIDsMap.growAndSet(id);
}
Cm::IDPool mIDPool;
PxBitMap mDeletedIDsMap;
PxArray<PxU32> mPendingReleasedIDs; // Buffer for released IDs to make sure newly created objects do not re-use these IDs immediately
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementInteractionMarker.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 "ScElementInteractionMarker.h"
#include "ScNPhaseCore.h"
using namespace physx;
Sc::ElementInteractionMarker::~ElementInteractionMarker()
{
if(isRegistered())
getScene().unregisterInteraction(this);
unregisterFromActors();
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimulationController.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 "ScSimulationController.h"
#include "foundation/PxAllocator.h"
#include "CmTask.h"
#include "CmFlushPool.h"
#include "PxNodeIndex.h"
#include "ScArticulationSim.h"
#include "PxsContext.h"
#include "foundation/PxAllocator.h"
#include "BpAABBManager.h"
#include "DyVArticulation.h"
using namespace physx;
void Sc::SimulationController::updateScBodyAndShapeSim(PxsTransformCache& /*cache*/, Bp::BoundsArray& /*boundArray*/, PxBaseTask* continuation)
{
mCallback->updateScBodyAndShapeSim(continuation);
}
namespace
{
class UpdateArticulationAfterIntegrationTask : public Cm::Task
{
IG::IslandSim& mIslandSim;
const PxNodeIndex* const PX_RESTRICT mNodeIndices;
const PxU32 mNbArticulations;
const PxReal mDt;
PX_NOCOPY(UpdateArticulationAfterIntegrationTask)
public:
static const PxU32 NbArticulationsPerTask = 64;
UpdateArticulationAfterIntegrationTask(PxU64 contextId, PxU32 nbArticulations, PxReal dt, const PxNodeIndex* nodeIndices, IG::IslandSim& islandSim) :
Cm::Task(contextId),
mIslandSim(islandSim),
mNodeIndices(nodeIndices),
mNbArticulations(nbArticulations),
mDt(dt)
{
}
virtual void runInternal()
{
for (PxU32 i = 0; i < mNbArticulations; ++i)
{
PxNodeIndex nodeIndex = mNodeIndices[i];
//Sc::ArticulationSim* articSim = getArticulationSim(mIslandSim, nodeIndex);
Sc::ArticulationSim* articSim = mIslandSim.getArticulationSim(nodeIndex);
articSim->sleepCheck(mDt);
articSim->updateCached(NULL);
}
}
virtual const char* getName() const { return "UpdateArticulationAfterIntegrationTask"; }
};
}
//KS - TODO - parallelize this bit!!!!!
void Sc::SimulationController::updateArticulationAfterIntegration(
PxsContext* llContext,
Bp::AABBManagerBase* aabbManager,
PxArray<Sc::BodySim*>& ccdBodies,
PxBaseTask* continuation,
IG::IslandSim& islandSim,
float dt
)
{
const PxU32 nbActiveArticulations = islandSim.getNbActiveNodes(IG::Node::eARTICULATION_TYPE);
Cm::FlushPool& flushPool = llContext->getTaskPool();
const PxNodeIndex* activeArticulations = islandSim.getActiveNodes(IG::Node::eARTICULATION_TYPE);
for (PxU32 i = 0; i < nbActiveArticulations; i += UpdateArticulationAfterIntegrationTask::NbArticulationsPerTask)
{
UpdateArticulationAfterIntegrationTask* task =
PX_PLACEMENT_NEW(flushPool.allocate(sizeof(UpdateArticulationAfterIntegrationTask)), UpdateArticulationAfterIntegrationTask)(islandSim.getContextId(), PxMin(UpdateArticulationAfterIntegrationTask::NbArticulationsPerTask, PxU32(nbActiveArticulations - i)), dt,
activeArticulations + i, islandSim);
startTask(task, continuation);
}
llContext->getLock().lock();
//const IG::NodeIndex* activeArticulations = islandSim.getActiveNodes(IG::Node::eARTICULATION_TYPE);
PxBitMapPinned& changedAABBMgrActorHandles = aabbManager->getChangedAABBMgActorHandleMap();
for (PxU32 i = 0; i < nbActiveArticulations; i++)
{
Sc::ArticulationSim* articSim = islandSim.getArticulationSim(activeArticulations[i]);
//KS - check links for CCD flags and add to mCcdBodies list if required....
articSim->updateCCDLinks(ccdBodies);
articSim->markShapesUpdated(&changedAABBMgrActorHandles);
}
llContext->getLock().unlock();
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScInteractionFlags.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 SC_INTERACTION_FLAGS_H
#define SC_INTERACTION_FLAGS_H
#include "foundation/Px.h"
namespace physx
{
namespace Sc
{
struct InteractionFlag // PT: TODO: use PxFlags
{
enum Enum
{
eRB_ELEMENT = (1 << 0), // Interactions between rigid body shapes
eCONSTRAINT = (1 << 1),
eFILTERABLE = (1 << 2), // Interactions that go through the filter code
eIN_DIRTY_LIST = (1 << 3), // The interaction is in the dirty list
eIS_FILTER_PAIR = (1 << 4), // The interaction is tracked by the filter callback mechanism
eIS_ACTIVE = (1 << 5)
};
};
struct InteractionDirtyFlag
{
enum Enum
{
eFILTER_STATE = (1 << 0), // All changes filtering related
eMATERIAL = (1 << 1),
eBODY_KINEMATIC = (1 << 2) | eFILTER_STATE, // A transition between dynamic and kinematic (and vice versa) require a refiltering
eDOMINANCE = (1 << 3),
eREST_OFFSET = (1 << 4),
eVISUALIZATION = (1 << 5)
};
};
} // namespace Sc
} // namespace physx
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBroadphase.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 "ScBroadphase.h"
#include "BpAABBManagerBase.h"
#include "ScShapeSim.h"
using namespace physx;
using namespace Sc;
using namespace Bp;
///////////////////////////////////////////////////////////////////////////////
BroadphaseManager::BroadphaseManager() :
mBroadPhaseCallback (NULL),
mOutOfBoundsIDs ("sceneOutOfBoundsIds")
{
}
BroadphaseManager::~BroadphaseManager()
{
}
void BroadphaseManager::prepareOutOfBoundsCallbacks(AABBManagerBase* aabbManager)
{
AABBManagerBase::OutOfBoundsData data;
if(!aabbManager->getOutOfBoundsObjects(data))
return;
PxU32 nbOut = data.mNbOutOfBoundsObjects;
void** outObjects = data.mOutOfBoundsObjects;
mOutOfBoundsIDs.clear();
while(nbOut--)
{
const ElementSim* volume = reinterpret_cast<const ElementSim*>(*outObjects++);
const Sc::ShapeSim* sim = static_cast<const Sc::ShapeSim*>(volume);
mOutOfBoundsIDs.pushBack(sim->getElementID());
}
}
bool BroadphaseManager::fireOutOfBoundsCallbacks(Bp::AABBManagerBase* aabbManager, const ObjectIDTracker& tracker)
{
AABBManagerBase::OutOfBoundsData data;
if(!aabbManager->getOutOfBoundsObjects(data))
return false;
bool outputWarning = false;
PxBroadPhaseCallback* cb = mBroadPhaseCallback;
// Actors
{
PxU32 nbOut = data.mNbOutOfBoundsObjects;
void** outObjects = data.mOutOfBoundsObjects;
for(PxU32 i=0;i<nbOut;i++)
{
ElementSim* volume = reinterpret_cast<ElementSim*>(outObjects[i]);
Sc::ShapeSim* sim = static_cast<Sc::ShapeSim*>(volume);
// PT: TODO: I'm not sure the split between prepareOutOfBoundsCallbacks / fireOutOfBoundsCallbacks
// and the test for deletion is still needed after the removal of SCB
if(tracker.isDeletedID(mOutOfBoundsIDs[i]))
continue;
if(cb)
{
ActorSim& actor = volume->getActor();
RigidSim& rigidSim = static_cast<RigidSim&>(actor);
PxActor* pxActor = rigidSim.getPxActor();
PxShape* px = sim->getPxShape();
cb->onObjectOutOfBounds(*px, *pxActor);
}
else
outputWarning = true;
}
}
// Aggregates
{
PxU32 nbOut = data.mNbOutOfBoundsAggregates;
void** outAgg = data.mOutOfBoundsAggregates;
for(PxU32 i=0;i<nbOut;i++)
{
PxAggregate* px = reinterpret_cast<PxAggregate*>(outAgg[i]);
if(cb)
cb->onObjectOutOfBounds(*px);
else
outputWarning = true;
}
}
aabbManager->clearOutOfBoundsObjects();
return outputWarning;
}
void BroadphaseManager::flush(Bp::AABBManagerBase* /*aabbManager*/)
{
mOutOfBoundsIDs.reset();
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScKinematics.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 "ScScene.h"
#include "ScBodySim.h"
#include "ScShapeSim.h"
#include "PxsSimulationController.h"
#include "BpAABBManagerBase.h"
using namespace physx;
using namespace Sc;
//PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
// PT: TODO: consider using a non-member function for this one
void BodySim::calculateKinematicVelocity(PxReal oneOverDt)
{
PX_ASSERT(isKinematic());
/*------------------------------------------------\
| kinematic bodies are moved directly by the user and are not influenced by external forces
| we simply determine the distance moved since the last simulation frame and
| assign the appropriate delta to the velocity. This vel will be used to shove dynamic
| objects in the solver.
| We have to do this like so in a delayed way, because when the user sets the target pos the dt is not
| yet known.
\------------------------------------------------*/
PX_ASSERT(isActive());
BodyCore& core = getBodyCore();
if (readInternalFlag(BF_KINEMATIC_MOVED))
{
clearInternalFlag(InternalFlags(BF_KINEMATIC_SETTLING | BF_KINEMATIC_SETTLING_2));
const SimStateData* kData = getSimStateData(true);
PX_ASSERT(kData);
PX_ASSERT(kData->isKine());
PX_ASSERT(kData->getKinematicData()->targetValid);
PxVec3 linVelLL, angVelLL;
const PxTransform targetPose = kData->getKinematicData()->targetPose;
const PxTransform& currBody2World = getBody2World();
//the kinematic target pose is now the target of the body (CoM) and not the actor.
PxVec3 deltaPos = targetPose.p;
deltaPos -= currBody2World.p;
linVelLL = deltaPos * oneOverDt;
PxQuat q = targetPose.q * currBody2World.q.getConjugate();
if (q.w < 0) //shortest angle.
q = -q;
PxReal angle;
PxVec3 axis;
q.toRadiansAndUnitAxis(angle, axis);
angVelLL = axis * angle * oneOverDt;
core.getCore().linearVelocity = linVelLL;
core.getCore().angularVelocity = angVelLL;
// Moving a kinematic should trigger a wakeUp call on a higher level.
PX_ASSERT(core.getWakeCounter()>0);
PX_ASSERT(isActive());
}
else if (!readInternalFlag(BF_KINEMATIC_SURFACE_VELOCITY))
{
core.setLinearVelocity(PxVec3(0.0f), true);
core.setAngularVelocity(PxVec3(0.0f), true);
}
}
namespace
{
class ScKinematicUpdateTask : public Cm::Task
{
Sc::BodyCore*const* mKinematics;
const PxU32 mNbKinematics;
const PxReal mOneOverDt;
PX_NOCOPY(ScKinematicUpdateTask)
public:
static const PxU32 NbKinematicsPerTask = 1024;
ScKinematicUpdateTask(Sc::BodyCore*const* kinematics, PxU32 nbKinematics, PxReal oneOverDt, PxU64 contextID) :
Cm::Task(contextID), mKinematics(kinematics), mNbKinematics(nbKinematics), mOneOverDt(oneOverDt)
{
}
virtual void runInternal()
{
Sc::BodyCore*const* kinematics = mKinematics;
PxU32 nb = mNbKinematics;
const float oneOverDt = mOneOverDt;
while(nb--)
{
Sc::BodyCore* b = *kinematics++;
PX_ASSERT(b->getSim()->isKinematic());
PX_ASSERT(b->getSim()->isActive());
b->getSim()->calculateKinematicVelocity(oneOverDt);
}
}
virtual const char* getName() const
{
return "ScScene.KinematicUpdateTask";
}
};
}
void Sc::Scene::kinematicsSetup(PxBaseTask* continuation)
{
const PxU32 nbKinematics = getActiveKinematicBodiesCount();
if(!nbKinematics)
return;
BodyCore*const* kinematics = getActiveKinematicBodies();
// PT: create a copy of active bodies for the taks to operate on while the main array is
// potentially resized by operations running in parallel.
if(mActiveKinematicsCopyCapacity<nbKinematics)
{
PX_FREE(mActiveKinematicsCopy);
mActiveKinematicsCopy = PX_ALLOCATE(BodyCore*, nbKinematics, "Sc::Scene::mActiveKinematicsCopy");
mActiveKinematicsCopyCapacity = nbKinematics;
}
PxMemCopy(mActiveKinematicsCopy, kinematics, nbKinematics*sizeof(BodyCore*));
kinematics = mActiveKinematicsCopy;
Cm::FlushPool& flushPool = mLLContext->getTaskPool();
// PT: TASK-CREATION TAG
// PT: TODO: better load balancing? This will be single threaded for less than 1K kinematics
for(PxU32 i = 0; i < nbKinematics; i += ScKinematicUpdateTask::NbKinematicsPerTask)
{
ScKinematicUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicUpdateTask)), ScKinematicUpdateTask)
(kinematics + i, PxMin(ScKinematicUpdateTask::NbKinematicsPerTask, nbKinematics - i), mOneOverDt, mContextId);
task->setContinuation(continuation);
task->removeReference();
}
if((mPublicFlags & PxSceneFlag::eENABLE_GPU_DYNAMICS))
{
// PT: running this serially for now because it's unsafe: mNPhaseCore->updateDirtyInteractions() (called after this)
// can also call mSimulationController.updateDynamic() via BodySim::internalWakeUpBase
PxU32 nb = nbKinematics;
while(nb--)
{
Sc::BodyCore* b = *kinematics++;
Sc::BodySim* bodySim = b->getSim();
PX_ASSERT(!bodySim->getArticulation());
mSimulationController->updateDynamic(NULL, bodySim->getNodeIndex());
}
}
}
///////////////////////////////////////////////////////////////////////////////
// PT: TODO: consider using a non-member function for this one
void BodySim::updateKinematicPose()
{
/*------------------------------------------------\
| kinematic bodies are moved directly by the user and are not influenced by external forces
| we simply determine the distance moved since the last simulation frame and
| assign the appropriate delta to the velocity. This vel will be used to shove dynamic
| objects in the solver.
| We have to do this like so in a delayed way, because when the user sets the target pos the dt is not
| yet known.
\------------------------------------------------*/
PX_ASSERT(isKinematic());
PX_ASSERT(isActive());
if(readInternalFlag(BF_KINEMATIC_MOVED))
{
clearInternalFlag(InternalFlags(BF_KINEMATIC_SETTLING | BF_KINEMATIC_SETTLING_2));
const SimStateData* kData = getSimStateData(true);
PX_ASSERT(kData);
PX_ASSERT(kData->isKine());
PX_ASSERT(kData->getKinematicData()->targetValid);
const PxTransform targetPose = kData->getKinematicData()->targetPose;
getBodyCore().getCore().body2World = targetPose;
}
}
namespace
{
class ScKinematicPoseUpdateTask : public Cm::Task
{
Sc::BodyCore*const* mKinematics;
const PxU32 mNbKinematics;
PX_NOCOPY(ScKinematicPoseUpdateTask)
public:
static const PxU32 NbKinematicsPerTask = 1024;
ScKinematicPoseUpdateTask(Sc::BodyCore*const* kinematics, PxU32 nbKinematics, PxU64 contextID) :
Cm::Task(contextID), mKinematics(kinematics), mNbKinematics(nbKinematics)
{
}
virtual void runInternal()
{
const PxU32 nb = mNbKinematics;
for(PxU32 a=0; a<nb; ++a)
{
if ((a + 16) < nb)
{
PxPrefetchLine(static_cast<Sc::BodyCore* const>(mKinematics[a + 16]));
if ((a + 4) < nb)
{
PxPrefetchLine(static_cast<Sc::BodyCore* const>(mKinematics[a + 4])->getSim());
PxPrefetchLine(static_cast<Sc::BodyCore* const>(mKinematics[a + 4])->getSim()->getSimStateData_Unchecked());
}
}
Sc::BodyCore* b = static_cast<Sc::BodyCore* const>(mKinematics[a]);
PX_ASSERT(b->getSim()->isKinematic());
PX_ASSERT(b->getSim()->isActive());
b->getSim()->updateKinematicPose();
}
}
virtual const char* getName() const
{
return "ScScene.ScKinematicPoseUpdateTask";
}
};
}
void Sc::Scene::integrateKinematicPose()
{
PX_PROFILE_ZONE("Sim.integrateKinematicPose", mContextId);
const PxU32 nbKinematics = getActiveKinematicBodiesCount();
BodyCore*const* kinematics = getActiveKinematicBodies();
Cm::FlushPool& flushPool = mLLContext->getTaskPool();
// PT: TASK-CREATION TAG
for(PxU32 i=0; i<nbKinematics; i+= ScKinematicPoseUpdateTask::NbKinematicsPerTask)
{
ScKinematicPoseUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicPoseUpdateTask)), ScKinematicPoseUpdateTask)
(kinematics + i, PxMin(nbKinematics - i, ScKinematicPoseUpdateTask::NbKinematicsPerTask), mContextId);
task->setContinuation(&mAfterIntegration);
task->removeReference();
}
}
///////////////////////////////////////////////////////////////////////////////
namespace
{
class ScKinematicShapeUpdateTask : public Cm::Task
{
Sc::BodyCore*const* mKinematics;
const PxU32 mNbKinematics;
PxsTransformCache& mCache;
Bp::BoundsArray& mBoundsArray;
PX_NOCOPY(ScKinematicShapeUpdateTask)
public:
static const PxU32 NbKinematicsShapesPerTask = 1024;
ScKinematicShapeUpdateTask(Sc::BodyCore*const* kinematics, PxU32 nbKinematics, PxsTransformCache& cache, Bp::BoundsArray& boundsArray, PxU64 contextID) :
Cm::Task(contextID), mKinematics(kinematics), mNbKinematics(nbKinematics), mCache(cache), mBoundsArray(boundsArray)
{
}
virtual void runInternal()
{
const PxU32 nb = mNbKinematics;
for(PxU32 a=0; a<nb; ++a)
{
Sc::BodyCore* b = static_cast<Sc::BodyCore*>(mKinematics[a]);
PX_ASSERT(b->getSim()->isKinematic());
PX_ASSERT(b->getSim()->isActive());
b->getSim()->updateCached(mCache, mBoundsArray);
}
}
virtual const char* getName() const
{
return "ScScene.KinematicShapeUpdateTask";
}
};
}
void Sc::Scene::updateKinematicCached(PxBaseTask* continuation)
{
PX_PROFILE_ZONE("Sim.updateKinematicCached", mContextId);
const PxU32 nbKinematics = getActiveKinematicBodiesCount();
if(!nbKinematics)
return;
BodyCore*const* kinematics = getActiveKinematicBodies();
Cm::FlushPool& flushPool = mLLContext->getTaskPool();
PxU32 startIndex = 0;
PxU32 nbShapes = 0;
{
PX_PROFILE_ZONE("ShapeUpdate", mContextId);
// PT: TASK-CREATION TAG
for(PxU32 i=0; i<nbKinematics; i++)
{
Sc::BodySim* sim = static_cast<Sc::BodyCore*>(kinematics[i])->getSim();
PX_ASSERT(sim->isKinematic());
PX_ASSERT(sim->isActive());
nbShapes += sim->getNbShapes();
if (nbShapes >= ScKinematicShapeUpdateTask::NbKinematicsShapesPerTask)
{
ScKinematicShapeUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicShapeUpdateTask)), ScKinematicShapeUpdateTask)
(kinematics + startIndex, (i + 1) - startIndex, mLLContext->getTransformCache(), *mBoundsArray, mContextId);
task->setContinuation(continuation);
task->removeReference();
startIndex = i + 1;
nbShapes = 0;
}
}
if(nbShapes)
{
ScKinematicShapeUpdateTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScKinematicShapeUpdateTask)), ScKinematicShapeUpdateTask)
(kinematics + startIndex, nbKinematics - startIndex, mLLContext->getTransformCache(), *mBoundsArray, mContextId);
task->setContinuation(continuation);
task->removeReference();
}
}
{
PxBitMapPinned& changedAABBMap = mAABBManager->getChangedAABBMgActorHandleMap();
mLLContext->getTransformCache().setChangedState();
mBoundsArray->setChangedState();
for (PxU32 i = 0; i < nbKinematics; ++i)
{
Sc::BodySim* bodySim = static_cast<Sc::BodyCore*>(kinematics[i])->getSim();
if ((i+16) < nbKinematics)
{
PxPrefetchLine(kinematics[i + 16]);
if ((i + 8) < nbKinematics)
{
PxPrefetchLine(kinematics[i + 8]->getSim());
}
}
// PT: ### changedMap pattern #1
PxU32 nbElems = bodySim->getNbElements();
Sc::ElementSim** elems = bodySim->getElements();
while (nbElems--)
{
Sc::ShapeSim* sim = static_cast<Sc::ShapeSim*>(*elems++);
//KS - TODO - can we parallelize this? The problem with parallelizing is that it's a bit operation,
//so we would either need to use atomic operations or have some high-level concept that guarantees
//that threads don't write to the same word in the map simultaneously
if (sim->getFlags()&PxU32(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE))
changedAABBMap.set(sim->getElementID());
}
mSimulationController->updateDynamic(NULL, bodySim->getNodeIndex());
}
}
}
///////////////////////////////////////////////////////////////////////////////
// PT: TODO: consider using a non-member function for this one
bool BodySim::deactivateKinematic()
{
BodyCore& core = getBodyCore();
if(readInternalFlag(BF_KINEMATIC_SETTLING_2))
{
clearInternalFlag(BF_KINEMATIC_SETTLING_2);
core.setWakeCounterFromSim(0); // For sleeping objects the wake counter must be 0. This needs to hold for kinematics too.
notifyReadyForSleeping();
notifyPutToSleep();
setActive(false);
return true;
}
else if (readInternalFlag(BF_KINEMATIC_SETTLING))
{
clearInternalFlag(BF_KINEMATIC_SETTLING);
raiseInternalFlag(BF_KINEMATIC_SETTLING_2);
}
else if (!readInternalFlag(BF_KINEMATIC_SURFACE_VELOCITY))
{
clearInternalFlag(BF_KINEMATIC_MOVED);
raiseInternalFlag(BF_KINEMATIC_SETTLING);
}
return false;
}
// PT: called during fetchResults()
void Sc::Scene::postCallbacksPreSyncKinematics()
{
PX_PROFILE_ZONE("Sim.postCallbacksPreSyncKinematics", mContextId);
// Put/prepare kinematics to/for sleep and invalidate target pose
// note: this needs to get done after the contact callbacks because
// the target might get read there.
//
PxU32 nbKinematics = getActiveKinematicBodiesCount();
BodyCore*const* kinematics = getActiveKinematicBodies();
//KS - this method must run over the kinematic actors in reverse.
while(nbKinematics--)
{
if(nbKinematics > 16)
{
PxPrefetchLine(static_cast<BodyCore*>(kinematics[nbKinematics-16]));
}
if (nbKinematics > 4)
{
PxPrefetchLine((static_cast<BodyCore*>(kinematics[nbKinematics - 4]))->getSim());
PxPrefetchLine((static_cast<BodyCore*>(kinematics[nbKinematics - 4]))->getSim()->getSimStateData_Unchecked());
}
BodyCore* b = static_cast<BodyCore*>(kinematics[nbKinematics]);
//kinematics++;
PX_ASSERT(b->getSim()->isKinematic());
PX_ASSERT(b->getSim()->isActive());
b->invalidateKinematicTarget();
b->getSim()->deactivateKinematic();
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScScene.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 "ScPhysics.h"
#include "ScScene.h"
#include "BpBroadPhase.h"
#include "ScConstraintSim.h"
#include "ScConstraintCore.h"
#include "ScArticulationJointCore.h"
#include "ScArticulationTendonCore.h"
#include "ScArticulationSensor.h"
#include "ScArticulationSim.h"
#include "ScArticulationJointSim.h"
#include "ScArticulationTendonSim.h"
#include "ScArticulationSensorSim.h"
#include "ScConstraintInteraction.h"
#include "ScTriggerInteraction.h"
#include "ScSimStats.h"
#include "PxvGlobals.h"
#include "PxsCCD.h"
#include "ScSimulationController.h"
#include "ScSqBoundsManager.h"
#if defined(__APPLE__) && defined(__POWERPC__)
#include <ppc_intrinsics.h>
#endif
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
#include "PxsKernelWrangler.h"
#include "PxsHeapMemoryAllocator.h"
#include "cudamanager/PxCudaContextManager.h"
#endif
#include "PxsMemoryManager.h"
#include "ScShapeInteraction.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxSoftBody.h"
#include "ScSoftBodySim.h"
#include "DySoftBody.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#include "PxHairSystem.h"
#endif
#include "ScFEMClothSim.h"
#include "DyFEMCloth.h"
#include "ScParticleSystemSim.h"
#include "DyParticleSystem.h"
#include "ScHairSystemSim.h"
#include "DyHairSystem.h"
#endif
using namespace physx;
using namespace Cm;
using namespace Dy;
using namespace Sc;
PX_IMPLEMENT_OUTPUT_ERROR
namespace physx {
namespace Sc {
class LLArticulationRCPool : public PxPool<FeatherstoneArticulation, PxAlignedAllocator<64> >
{
public:
LLArticulationRCPool() {}
};
#if PX_SUPPORT_GPU_PHYSX
class LLSoftBodyPool : public PxPool<SoftBody, PxAlignedAllocator<64> >
{
public:
LLSoftBodyPool() {}
};
class LLFEMClothPool : public PxPool<FEMCloth, PxAlignedAllocator<64> >
{
public:
LLFEMClothPool() {}
};
class LLParticleSystemPool : public PxPool<ParticleSystem, PxAlignedAllocator<64> >
{
public:
LLParticleSystemPool() {}
};
class LLHairSystemPool : public PxPool<HairSystem, PxAlignedAllocator<64> >
{
public:
LLHairSystemPool() {}
};
#endif
static const char* sFilterShaderDataMemAllocId = "SceneDesc filterShaderData";
}}
void PxcDisplayContactCacheStats();
static const bool gUseNewTaskAllocationScheme = false;
namespace
{
class ScAfterIntegrationTask : public Cm::Task
{
public:
static const PxU32 MaxTasks = 256;
private:
const PxNodeIndex* const mIndices;
const PxU32 mNumBodies;
PxsContext* mContext;
Context* mDynamicsContext;
PxsTransformCache& mCache;
Sc::Scene& mScene;
public:
ScAfterIntegrationTask(const PxNodeIndex* const indices, PxU32 numBodies, PxsContext* context, Context* dynamicsContext, PxsTransformCache& cache, Sc::Scene& scene) :
Cm::Task (scene.getContextId()),
mIndices (indices),
mNumBodies (numBodies),
mContext (context),
mDynamicsContext(dynamicsContext),
mCache (cache),
mScene (scene)
{
}
virtual void runInternal()
{
const PxU32 rigidBodyOffset = Sc::BodySim::getRigidBodyOffset();
Sc::BodySim* bpUpdates[MaxTasks];
Sc::BodySim* ccdBodies[MaxTasks];
Sc::BodySim* activateBodies[MaxTasks];
Sc::BodySim* deactivateBodies[MaxTasks];
PxU32 nbBpUpdates = 0, nbCcdBodies = 0;
IG::SimpleIslandManager& manager = *mScene.getSimpleIslandManager();
const IG::IslandSim& islandSim = manager.getAccurateIslandSim();
Bp::BoundsArray& boundsArray = mScene.getBoundsArray();
Sc::BodySim* frozen[MaxTasks], * unfrozen[MaxTasks];
PxU32 nbFrozen = 0, nbUnfrozen = 0;
PxU32 nbActivated = 0, nbDeactivated = 0;
for(PxU32 i = 0; i < mNumBodies; i++)
{
PxsRigidBody* rigid = islandSim.getRigidBody(mIndices[i]);
Sc::BodySim* bodySim = reinterpret_cast<Sc::BodySim*>(reinterpret_cast<PxU8*>(rigid) - rigidBodyOffset);
//This move to PxgPostSolveWorkerTask for the gpu dynamic
//bodySim->sleepCheck(mDt, mOneOverDt, mEnableStabilization);
PxsBodyCore& bodyCore = bodySim->getBodyCore().getCore();
//If we got in this code, then this is an active object this frame. The solver computed the new wakeCounter and we
//commit it at this stage. We need to do it this way to avoid a race condition between the solver and the island gen, where
//the island gen may have deactivated a body while the solver decided to change its wake counter.
bodyCore.wakeCounter = bodyCore.solverWakeCounter;
PxsRigidBody& llBody = bodySim->getLowLevelBody();
const PxIntBool isFrozen = bodySim->isFrozen();
if(!isFrozen)
{
bpUpdates[nbBpUpdates++] = bodySim;
// PT: TODO: remove duplicate "isFrozen" test inside updateCached
// bodySim->updateCached(NULL);
bodySim->updateCached(mCache, boundsArray);
}
if(llBody.isFreezeThisFrame() && isFrozen)
frozen[nbFrozen++] = bodySim;
else if(llBody.isUnfreezeThisFrame())
unfrozen[nbUnfrozen++] = bodySim;
if(bodyCore.mFlags & PxRigidBodyFlag::eENABLE_CCD)
ccdBodies[nbCcdBodies++] = bodySim;
if(llBody.isActivateThisFrame())
{
PX_ASSERT(!llBody.isDeactivateThisFrame());
activateBodies[nbActivated++] = bodySim;
}
else if(llBody.isDeactivateThisFrame())
{
deactivateBodies[nbDeactivated++] = bodySim;
}
llBody.clearAllFrameFlags();
}
if(nbBpUpdates)
{
mCache.setChangedState();
boundsArray.setChangedState();
}
if(nbBpUpdates>0 || nbFrozen > 0 || nbCcdBodies>0 || nbActivated>0 || nbDeactivated>0)
{
//Write active bodies to changed actor map
mContext->getLock().lock();
PxBitMapPinned& changedAABBMgrHandles = mScene.getAABBManager()->getChangedAABBMgActorHandleMap();
for(PxU32 i = 0; i < nbBpUpdates; i++)
{
// PT: ### changedMap pattern #1
PxU32 nbElems = bpUpdates[i]->getNbElements();
Sc::ElementSim** elems = bpUpdates[i]->getElements();
while (nbElems--)
{
Sc::ShapeSim* sim = static_cast<Sc::ShapeSim*>(*elems++);
// PT: TODO: what's the difference between this test and "isInBroadphase" as used in bodySim->updateCached ?
// PT: Also, shouldn't it be "isInAABBManager" rather than BP ?
if (sim->getFlags()&PxU32(PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eTRIGGER_SHAPE)) // TODO: need trigger shape here?
changedAABBMgrHandles.growAndSet(sim->getElementID());
}
}
PxArray<Sc::BodySim*>& sceneCcdBodies = mScene.getCcdBodies();
for (PxU32 i = 0; i < nbCcdBodies; i++)
sceneCcdBodies.pushBack(ccdBodies[i]);
for(PxU32 i=0;i<nbFrozen;i++)
{
PX_ASSERT(frozen[i]->isFrozen());
frozen[i]->freezeTransforms(&changedAABBMgrHandles);
}
for(PxU32 i=0;i<nbUnfrozen;i++)
{
PX_ASSERT(!unfrozen[i]->isFrozen());
unfrozen[i]->createSqBounds();
}
for(PxU32 i = 0; i < nbActivated; ++i)
activateBodies[i]->notifyNotReadyForSleeping();
for(PxU32 i = 0; i < nbDeactivated; ++i)
deactivateBodies[i]->notifyReadyForSleeping();
mContext->getLock().unlock();
}
}
virtual const char* getName() const
{
return "ScScene.afterIntegrationTask";
}
private:
PX_NOCOPY(ScAfterIntegrationTask)
};
class ScSimulationControllerCallback : public PxsSimulationControllerCallback
{
Sc::Scene* mScene;
public:
ScSimulationControllerCallback(Sc::Scene* scene) : mScene(scene)
{
}
virtual void updateScBodyAndShapeSim(PxBaseTask* continuation)
{
PxsContext* contextLL = mScene->getLowLevelContext();
IG::SimpleIslandManager* islandManager = mScene->getSimpleIslandManager();
Dy::Context* dynamicContext = mScene->getDynamicsContext();
Cm::FlushPool& flushPool = contextLL->getTaskPool();
const PxU32 MaxBodiesPerTask = ScAfterIntegrationTask::MaxTasks;
PxsTransformCache& cache = contextLL->getTransformCache();
const IG::IslandSim& islandSim = islandManager->getAccurateIslandSim();
/*const*/ PxU32 numBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE);
const PxNodeIndex*const nodeIndices = islandSim.getActiveNodes(IG::Node::eRIGID_BODY_TYPE);
const PxU32 rigidBodyOffset = Sc::BodySim::getRigidBodyOffset();
// PT: TASK-CREATION TAG
if(!gUseNewTaskAllocationScheme)
{
PxU32 nbShapes = 0;
PxU32 startIdx = 0;
for (PxU32 i = 0; i < numBodies; i++)
{
if (nbShapes >= MaxBodiesPerTask)
{
ScAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScAfterIntegrationTask)), ScAfterIntegrationTask(nodeIndices + startIdx, i - startIdx,
contextLL, dynamicContext, cache, *mScene));
startTask(task, continuation);
startIdx = i;
nbShapes = 0;
}
PxsRigidBody* rigid = islandSim.getRigidBody(nodeIndices[i]);
Sc::BodySim* bodySim = reinterpret_cast<Sc::BodySim*>(reinterpret_cast<PxU8*>(rigid) - rigidBodyOffset);
nbShapes += PxMax(1u, bodySim->getNbShapes()); //Always add at least 1 shape in, even if the body has zero shapes because there is still some per-body overhead
}
if (nbShapes)
{
ScAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScAfterIntegrationTask)), ScAfterIntegrationTask(nodeIndices + startIdx, numBodies - startIdx,
contextLL, dynamicContext, cache, *mScene));
startTask(task, continuation);
}
}
else
{
// PT:
const PxU32 numCpuTasks = continuation->getTaskManager()->getCpuDispatcher()->getWorkerCount();
PxU32 nbPerTask;
if(numCpuTasks)
nbPerTask = numBodies > numCpuTasks ? numBodies / numCpuTasks : numBodies;
else
nbPerTask = numBodies;
// PT: we need to respect that limit even with a single thread, because of hardcoded buffer limits in ScAfterIntegrationTask.
if(nbPerTask>MaxBodiesPerTask)
nbPerTask = MaxBodiesPerTask;
PxU32 start = 0;
while(numBodies)
{
const PxU32 nb = numBodies < nbPerTask ? numBodies : nbPerTask;
ScAfterIntegrationTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(ScAfterIntegrationTask)), ScAfterIntegrationTask(nodeIndices+start, nb,
contextLL, dynamicContext, cache, *mScene));
start += nb;
numBodies -= nb;
startTask(task, continuation);
}
}
}
virtual PxU32 getNbCcdBodies()
{
return mScene->getCcdBodies().size();
}
};
// PT: TODO: what is this Pxg class doing here?
class PxgUpdateBodyAndShapeStatusTask : public Cm::Task
{
public:
static const PxU32 MaxTasks = 2048;
private:
const PxNodeIndex* const mNodeIndices;
const PxU32 mNumBodies;
Sc::Scene& mScene;
void** mRigidBodyLL;
PxU32* mActivatedBodies;
PxU32* mDeactivatedBodies;
PxI32& mCCDBodyWriteIndex;
public:
PxgUpdateBodyAndShapeStatusTask(const PxNodeIndex* const indices, PxU32 numBodies, void** rigidBodyLL, PxU32* activatedBodies, PxU32* deactivatedBodies, Sc::Scene& scene, PxI32& ccdBodyWriteIndex) :
Cm::Task (scene.getContextId()),
mNodeIndices (indices),
mNumBodies (numBodies),
mScene (scene),
mRigidBodyLL (rigidBodyLL),
mActivatedBodies (activatedBodies),
mDeactivatedBodies (deactivatedBodies),
mCCDBodyWriteIndex (ccdBodyWriteIndex)
{
}
virtual void runInternal()
{
IG::SimpleIslandManager& islandManager = *mScene.getSimpleIslandManager();
const IG::IslandSim& islandSim = islandManager.getAccurateIslandSim();
PxU32 nbCcdBodies = 0;
PxArray<Sc::BodySim*>& sceneCcdBodies = mScene.getCcdBodies();
Sc::BodySim* ccdBodies[MaxTasks];
const size_t bodyOffset = PX_OFFSET_OF_RT(Sc::BodySim, getLowLevelBody());
for(PxU32 i=0; i<mNumBodies; ++i)
{
const PxU32 nodeIndex = mNodeIndices[i].index();
PxsRigidBody* rigidLL = reinterpret_cast<PxsRigidBody*>(mRigidBodyLL[nodeIndex]);
PxsBodyCore* bodyCore = &rigidLL->getCore();
bodyCore->wakeCounter = bodyCore->solverWakeCounter;
//we can set the frozen/unfrozen flag in GPU, but we have copied the internalflags
//from the solverbodysleepdata to pxsbodycore, so we just need to clear the frozen flag in here
rigidLL->clearAllFrameFlags();
PX_ASSERT(mActivatedBodies[nodeIndex] <= 1);
PX_ASSERT(mDeactivatedBodies[nodeIndex] <= 1);
if(mActivatedBodies[nodeIndex])
{
PX_ASSERT(bodyCore->wakeCounter > 0.0f);
islandManager.activateNode(mNodeIndices[i]);
}
else if(mDeactivatedBodies[nodeIndex])
{
//KS - the CPU code can reset the wake counter due to lost touches in parallel with the solver, so we need to verify
//that the wakeCounter is still 0 before deactivating the node
if (bodyCore->wakeCounter == 0.0f)
{
islandManager.deactivateNode(mNodeIndices[i]);
}
}
if (bodyCore->mFlags & PxRigidBodyFlag::eENABLE_CCD)
{
PxsRigidBody* rigidBody = islandSim.getRigidBody(mNodeIndices[i]);
Sc::BodySim* bodySim = reinterpret_cast<Sc::BodySim*>(reinterpret_cast<PxU8*>(rigidBody) - bodyOffset);
ccdBodies[nbCcdBodies++] = bodySim;
}
}
if(nbCcdBodies > 0)
{
PxI32 startIndex = PxAtomicAdd(&mCCDBodyWriteIndex, PxI32(nbCcdBodies)) - PxI32(nbCcdBodies);
for(PxU32 a = 0; a < nbCcdBodies; ++a)
{
sceneCcdBodies[startIndex + a] = ccdBodies[a];
}
}
}
virtual const char* getName() const
{
return "ScScene.PxgUpdateBodyAndShapeStatusTask";
}
private:
PX_NOCOPY(PxgUpdateBodyAndShapeStatusTask)
};
#if PX_SUPPORT_GPU_PHYSX
// PT: TODO: what is this Pxg class doing here?
class PxgSimulationControllerCallback : public PxsSimulationControllerCallback
{
Sc::Scene* mScene;
PxI32 mCcdBodyWriteIndex;
public:
PxgSimulationControllerCallback(Sc::Scene* scene) : mScene(scene), mCcdBodyWriteIndex(0)
{
}
virtual void updateScBodyAndShapeSim(PxBaseTask* continuation)
{
IG::SimpleIslandManager* islandManager = mScene->getSimpleIslandManager();
PxsSimulationController* simulationController = mScene->getSimulationController();
PxsContext* contextLL = mScene->getLowLevelContext();
IG::IslandSim& islandSim = islandManager->getAccurateIslandSim();
const PxU32 numBodies = islandSim.getNbActiveNodes(IG::Node::eRIGID_BODY_TYPE);
const PxNodeIndex*const nodeIndices = islandSim.getActiveNodes(IG::Node::eRIGID_BODY_TYPE);
PxU32* activatedBodies = simulationController->getActiveBodies();
PxU32* deactivatedBodies = simulationController->getDeactiveBodies();
//PxsRigidBody** rigidBodyLL = simulationController->getRigidBodies();
void** rigidBodyLL = simulationController->getRigidBodies();
Cm::FlushPool& flushPool = contextLL->getTaskPool();
PxArray<Sc::BodySim*>& ccdBodies = mScene->getCcdBodies();
ccdBodies.forceSize_Unsafe(0);
ccdBodies.reserve(numBodies);
ccdBodies.forceSize_Unsafe(numBodies);
mCcdBodyWriteIndex = 0;
// PT: TASK-CREATION TAG
for(PxU32 i = 0; i < numBodies; i+=PxgUpdateBodyAndShapeStatusTask::MaxTasks)
{
PxgUpdateBodyAndShapeStatusTask* task = PX_PLACEMENT_NEW(flushPool.allocate(sizeof(PxgUpdateBodyAndShapeStatusTask)), PxgUpdateBodyAndShapeStatusTask(nodeIndices + i,
PxMin(PxgUpdateBodyAndShapeStatusTask::MaxTasks, numBodies - i), rigidBodyLL, activatedBodies, deactivatedBodies, *mScene, mCcdBodyWriteIndex));
task->setContinuation(continuation);
task->removeReference();
}
PxU32* unfrozenShapeIndices = simulationController->getUnfrozenShapes();
PxU32* frozenShapeIndices = simulationController->getFrozenShapes();
const PxU32 nbFrozenShapes = simulationController->getNbFrozenShapes();
const PxU32 nbUnfrozenShapes = simulationController->getNbUnfrozenShapes();
PxsShapeSim** shapeSimsLL = simulationController->getShapeSims();
const size_t shapeOffset = PX_OFFSET_OF_RT(Sc::ShapeSim, getLLShapeSim());
for(PxU32 i=0; i<nbFrozenShapes; ++i)
{
const PxU32 shapeIndex = frozenShapeIndices[i];
PxsShapeSim* shapeLL = shapeSimsLL[shapeIndex];
Sc::ShapeSim* shape = reinterpret_cast<Sc::ShapeSim*>(reinterpret_cast<PxU8*>(shapeLL) - shapeOffset);
shape->destroySqBounds();
}
for(PxU32 i=0; i<nbUnfrozenShapes; ++i)
{
const PxU32 shapeIndex = unfrozenShapeIndices[i];
PxsShapeSim* shapeLL = shapeSimsLL[shapeIndex];
Sc::ShapeSim* shape = reinterpret_cast<Sc::ShapeSim*>(reinterpret_cast<PxU8*>(shapeLL) - shapeOffset);
shape->createSqBounds();
}
if (simulationController->hasFEMCloth())
{
//KS - technically, there's a race condition calling activateNode/deactivateNode, but we know that it is
//safe because these deactivate/activate calls came from the solver. This means that we know that the
//actors are active currently, so at most we are just clearing/setting the ready for sleeping flag.
//None of the more complex logic that touching shared state will be executed.
const PxU32 nbActivatedCloth = simulationController->getNbActivatedFEMCloth();
Dy::FEMCloth** activatedCloths = simulationController->getActivatedFEMCloths();
for (PxU32 i = 0; i < nbActivatedCloth; ++i)
{
PxNodeIndex nodeIndex = activatedCloths[i]->getFEMClothSim()->getNodeIndex();
islandManager->activateNode(nodeIndex);
}
const PxU32 nbDeactivatedCloth = simulationController->getNbDeactivatedFEMCloth();
Dy::FEMCloth** deactivatedCloths = simulationController->getDeactivatedFEMCloths();
for (PxU32 i = 0; i < nbDeactivatedCloth; ++i)
{
PxNodeIndex nodeIndex = deactivatedCloths[i]->getFEMClothSim()->getNodeIndex();
islandManager->deactivateNode(nodeIndex);
}
}
if (simulationController->hasSoftBodies())
{
//KS - technically, there's a race condition calling activateNode/deactivateNode, but we know that it is
//safe because these deactivate/activate calls came from the solver. This means that we know that the
//actors are active currently, so at most we are just clearing/setting the ready for sleeping flag.
//None of the more complex logic that touching shared state will be executed.
const PxU32 nbDeactivatedSB = simulationController->getNbDeactivatedSoftbodies();
Dy::SoftBody** deactivatedSB = simulationController->getDeactivatedSoftbodies();
for (PxU32 i = 0; i < nbDeactivatedSB; ++i)
{
PxNodeIndex nodeIndex = deactivatedSB[i]->getSoftBodySim()->getNodeIndex();
islandManager->deactivateNode(nodeIndex);
}
const PxU32 nbActivatedSB = simulationController->getNbActivatedSoftbodies();
Dy::SoftBody** activatedSB = simulationController->getActivatedSoftbodies();
for (PxU32 i = 0; i < nbActivatedSB; ++i)
{
PxNodeIndex nodeIndex = activatedSB[i]->getSoftBodySim()->getNodeIndex();
islandManager->activateNode(nodeIndex);
}
}
if (simulationController->hasHairSystems())
{
// comment from KS regarding race condition applies here, too
const PxU32 nbDeactivatedHS = simulationController->getNbDeactivatedHairSystems();
Dy::HairSystem** deactivatedHS = simulationController->getDeactivatedHairSystems();
for (PxU32 i = 0; i < nbDeactivatedHS; ++i)
{
PxNodeIndex nodeIndex = deactivatedHS[i]->getHairSystemSim()->getNodeIndex();
islandManager->deactivateNode(nodeIndex);
}
const PxU32 nbActivatedHS = simulationController->getNbActivatedHairSystems();
Dy::HairSystem** activatedHS = simulationController->getActivatedHairSystems();
for (PxU32 i = 0; i < nbActivatedHS; ++i)
{
PxNodeIndex nodeIndex = activatedHS[i]->getHairSystemSim()->getNodeIndex();
islandManager->activateNode(nodeIndex);
}
}
}
virtual PxU32 getNbCcdBodies()
{
return PxU32(mCcdBodyWriteIndex);
}
};
#endif
}
static Bp::AABBManagerBase* createAABBManagerCPU(const PxSceneDesc& desc, Bp::BroadPhase* broadPhase, Bp::BoundsArray* boundsArray, PxFloatArrayPinned* contactDistances, PxVirtualAllocator& allocator, PxU64 contextID)
{
return PX_NEW(Bp::AABBManager)(*broadPhase, *boundsArray, *contactDistances,
desc.limits.maxNbAggregates, desc.limits.maxNbStaticShapes + desc.limits.maxNbDynamicShapes, allocator, contextID,
desc.kineKineFilteringMode, desc.staticKineFilteringMode);
}
#if PX_SUPPORT_GPU_PHYSX
static Bp::AABBManagerBase* createAABBManagerGPU(PxsKernelWranglerManager* kernelWrangler, PxCudaContextManager* cudaContextManager, PxsHeapMemoryAllocatorManager* heapMemoryAllocationManager,
const PxSceneDesc& desc, Bp::BroadPhase* broadPhase, Bp::BoundsArray* boundsArray, PxFloatArrayPinned* contactDistances, PxVirtualAllocator& allocator, PxU64 contextID)
{
return PxvGetPhysXGpu(true)->createGpuAABBManager(
kernelWrangler,
cudaContextManager,
desc.gpuComputeVersion,
desc.gpuDynamicsConfig,
heapMemoryAllocationManager,
*broadPhase, *boundsArray, *contactDistances,
desc.limits.maxNbAggregates, desc.limits.maxNbStaticShapes + desc.limits.maxNbDynamicShapes, allocator, contextID,
desc.kineKineFilteringMode, desc.staticKineFilteringMode);
}
#endif
Sc::Scene::Scene(const PxSceneDesc& desc, PxU64 contextID) :
mContextId (contextID),
mActiveBodies ("sceneActiveBodies"),
mActiveKinematicBodyCount (0),
mActiveDynamicBodyCount (0),
mActiveKinematicsCopy (NULL),
mActiveKinematicsCopyCapacity (0),
mPointerBlock8Pool ("scenePointerBlock8Pool"),
mPointerBlock16Pool ("scenePointerBlock16Pool"),
mPointerBlock32Pool ("scenePointerBlock32Pool"),
mLLContext (NULL),
mAABBManager (NULL),
mCCDContext (NULL),
mNumFastMovingShapes (0),
mCCDPass (0),
mSimpleIslandManager (NULL),
mDynamicsContext (NULL),
mMemoryManager (NULL),
#if PX_SUPPORT_GPU_PHYSX
mGpuWranglerManagers (NULL),
mHeapMemoryAllocationManager (NULL),
#endif
mSimulationController (NULL),
mSimulationControllerCallback (NULL),
mGravity (PxVec3(0.0f)),
mDt (0),
mOneOverDt (0),
mTimeStamp (1), // PT: has to start to 1 to fix determinism bug. I don't know why yet but it works.
mReportShapePairTimeStamp (0),
mTriggerBufferAPI ("sceneTriggerBufferAPI"),
mArticulations ("sceneArticulations"),
mBrokenConstraints ("sceneBrokenConstraints"),
mActiveBreakableConstraints ("sceneActiveBreakableConstraints"),
mMemBlock128Pool ("PxsContext ConstraintBlock128Pool"),
mMemBlock256Pool ("PxsContext ConstraintBlock256Pool"),
mMemBlock384Pool ("PxsContext ConstraintBlock384Pool"),
mNPhaseCore (NULL),
mKineKineFilteringMode (desc.kineKineFilteringMode),
mStaticKineFilteringMode (desc.staticKineFilteringMode),
mSleepBodies ("sceneSleepBodies"),
mWokeBodies ("sceneWokeBodies"),
mEnableStabilization (desc.flags & PxSceneFlag::eENABLE_STABILIZATION),
mActiveActors ("clientActiveActors"),
mFrozenActors ("clientFrozenActors"),
mClientPosePreviewBodies ("clientPosePreviewBodies"),
mClientPosePreviewBuffer ("clientPosePreviewBuffer"),
mSimulationEventCallback (NULL),
mInternalFlags (SceneInternalFlag::eSCENE_DEFAULT),
mPublicFlags (desc.flags),
mAnchorCore (PxTransform(PxIdentity)),
mStaticAnchor (NULL),
mBatchRemoveState (NULL),
mLostTouchPairs ("sceneLostTouchPairs"),
mVisualizationParameterChanged (false),
mMaxNbArticulationLinks (0),
mNbRigidStatics (0),
mNbRigidDynamics (0),
mNbRigidKinematic (0),
mSecondPassNarrowPhase (contextID, this, "ScScene.secondPassNarrowPhase"),
mPostNarrowPhase (contextID, this, "ScScene.postNarrowPhase"),
mFinalizationPhase (contextID, this, "ScScene.finalizationPhase"),
mUpdateCCDMultiPass (contextID, this, "ScScene.updateCCDMultiPass"),
mAfterIntegration (contextID, this, "ScScene.afterIntegration"),
mPostSolver (contextID, this, "ScScene.postSolver"),
mSolver (contextID, this, "ScScene.rigidBodySolver"),
mUpdateBodies (contextID, this, "ScScene.updateBodies"),
mUpdateShapes (contextID, this, "ScScene.updateShapes"),
mUpdateSimulationController (contextID, this, "ScScene.updateSimulationController"),
mUpdateDynamics (contextID, this, "ScScene.updateDynamics"),
mProcessLostContactsTask (contextID, this, "ScScene.processLostContact"),
mProcessLostContactsTask2 (contextID, this, "ScScene.processLostContact2"),
mProcessLostContactsTask3 (contextID, this, "ScScene.processLostContact3"),
mDestroyManagersTask (contextID, this, "ScScene.destroyManagers"),
mLostTouchReportsTask (contextID, this, "ScScene.lostTouchReports"),
mUnregisterInteractionsTask (contextID, this, "ScScene.unregisterInteractions"),
mProcessNarrowPhaseLostTouchTasks(contextID, this, "ScScene.processNpLostTouchTask"),
mProcessNPLostTouchEvents (contextID, this, "ScScene.processNPLostTouchEvents"),
mPostThirdPassIslandGenTask (contextID, this, "ScScene.postThirdPassIslandGenTask"),
mPostIslandGen (contextID, this, "ScScene.postIslandGen"),
mIslandGen (contextID, this, "ScScene.islandGen"),
mPreRigidBodyNarrowPhase (contextID, this, "ScScene.preRigidBodyNarrowPhase"),
mSetEdgesConnectedTask (contextID, this, "ScScene.setEdgesConnectedTask"),
mProcessLostPatchesTask (contextID, this, "ScScene.processLostSolverPatchesTask"),
mProcessFoundPatchesTask (contextID, this, "ScScene.processFoundSolverPatchesTask"),
mUpdateBoundAndShapeTask (contextID, this, "ScScene.updateBoundsAndShapesTask"),
mRigidBodyNarrowPhase (contextID, this, "ScScene.rigidBodyNarrowPhase"),
mRigidBodyNPhaseUnlock (contextID, this, "ScScene.unblockNarrowPhase"),
mPostBroadPhase (contextID, this, "ScScene.postBroadPhase"),
mPostBroadPhaseCont (contextID, this, "ScScene.postBroadPhaseCont"),
mPostBroadPhase2 (contextID, this, "ScScene.postBroadPhase2"),
mPostBroadPhase3 (contextID, this, "ScScene.postBroadPhase3"),
mPreallocateContactManagers (contextID, this, "ScScene.preallocateContactManagers"),
mIslandInsertion (contextID, this, "ScScene.islandInsertion"),
mRegisterContactManagers (contextID, this, "ScScene.registerContactManagers"),
mRegisterInteractions (contextID, this, "ScScene.registerInteractions"),
mRegisterSceneInteractions (contextID, this, "ScScene.registerSceneInteractions"),
mBroadPhase (contextID, this, "ScScene.broadPhase"),
mAdvanceStep (contextID, this, "ScScene.advanceStep"),
mCollideStep (contextID, this, "ScScene.collideStep"),
mBpFirstPass (contextID, this, "ScScene.broadPhaseFirstPass"),
mBpSecondPass (contextID, this, "ScScene.broadPhaseSecondPass"),
mBpUpdate (contextID, this, "ScScene.updateBroadPhase"),
mPreIntegrate (contextID, this, "ScScene.preIntegrate"),
mTaskPool (16384),
mTaskManager (NULL),
mCudaContextManager (desc.cudaContextManager),
mContactReportsNeedPostSolverVelocity(false),
mUseGpuDynamics(false),
mUseGpuBp (false),
mCCDBp (false),
mSimulationStage (SimulationStage::eCOMPLETE),
mPosePreviewBodies ("scenePosePreviewBodies"),
mOverlapFilterTaskHead (NULL),
mIsCollisionPhaseActive (false),
mIsDirectGPUAPIInitialized (false),
mOnSleepingStateChanged (NULL)
#if PX_SUPPORT_GPU_PHYSX
,mSoftBodies ("sceneSoftBodies"),
mFEMCloths ("sceneFEMCloths"),
mParticleSystems ("sceneParticleSystems"),
mHairSystems ("sceneHairSystems")
#endif
{
#if PX_SUPPORT_GPU_PHYSX
mLLSoftBodyPool = PX_NEW(LLSoftBodyPool);
mLLFEMClothPool = PX_NEW(LLFEMClothPool);
mLLParticleSystemPool = PX_NEW(LLParticleSystemPool);
mLLHairSystemPool = PX_NEW(LLHairSystemPool);
mWokeSoftBodyListValid = true;
mSleepSoftBodyListValid = true;
mWokeHairSystemListValid = true;
mSleepHairSystemListValid = true;
#endif
for(PxU32 type = 0; type < InteractionType::eTRACKED_IN_SCENE_COUNT; ++type)
mInteractions[type].reserve(64);
for (int i=0; i < InteractionType::eTRACKED_IN_SCENE_COUNT; ++i)
mActiveInteractionCount[i] = 0;
mStats = PX_NEW(SimStats);
mConstraintIDTracker = PX_NEW(ObjectIDTracker);
mActorIDTracker = PX_NEW(ObjectIDTracker);
mElementIDPool = PX_NEW(ObjectIDTracker);
mTriggerBufferExtraData = reinterpret_cast<TriggerBufferExtraData*>(PX_ALLOC(sizeof(TriggerBufferExtraData), "ScScene::TriggerBufferExtraData"));
PX_PLACEMENT_NEW(mTriggerBufferExtraData, TriggerBufferExtraData("ScScene::TriggerPairExtraData"));
mStaticSimPool = PX_NEW(PreallocatingPool<StaticSim>)(64, "StaticSim");
mBodySimPool = PX_NEW(PreallocatingPool<BodySim>)(64, "BodySim");
mShapeSimPool = PX_NEW(PreallocatingPool<ShapeSim>)(64, "ShapeSim");
mConstraintSimPool = PX_NEW(PxPool<ConstraintSim>)("ScScene::ConstraintSim");
mConstraintInteractionPool = PX_NEW(PxPool<ConstraintInteraction>)("ScScene::ConstraintInteraction");
mLLArticulationRCPool = PX_NEW(LLArticulationRCPool);
mSimStateDataPool = PX_NEW(PxPool<SimStateData>)("ScScene::SimStateData");
mSqBoundsManager = PX_NEW(SqBoundsManager);
mTaskManager = physx::PxTaskManager::createTaskManager(*PxGetErrorCallback(), desc.cpuDispatcher);
for(PxU32 i=0; i<PxGeometryType::eGEOMETRY_COUNT; i++)
mNbGeometries[i] = 0;
bool useGpuDynamics = false;
bool useGpuBroadphase = false;
#if PX_SUPPORT_GPU_PHYSX
if(desc.flags & PxSceneFlag::eENABLE_GPU_DYNAMICS)
{
if(!mCudaContextManager)
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "GPU solver pipeline failed, switching to software");
else if(mCudaContextManager->supportsArchSM30())
useGpuDynamics = true;
}
if(desc.broadPhaseType == PxBroadPhaseType::eGPU)
{
if(!mCudaContextManager)
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "GPU Bp pipeline failed, switching to software");
else if(mCudaContextManager->supportsArchSM30())
useGpuBroadphase = true;
}
#endif
mUseGpuDynamics = useGpuDynamics;
mUseGpuBp = useGpuBroadphase;
mLLContext = PX_NEW(PxsContext)(desc, mTaskManager, mTaskPool, mCudaContextManager, desc.contactPairSlabSize, contextID);
if (mLLContext == 0)
{
outputError<PxErrorCode::eINVALID_PARAMETER>(__LINE__, "Failed to create context!");
return;
}
mLLContext->setMaterialManager(&getMaterialManager());
#if PX_SUPPORT_GPU_PHYSX
if (useGpuBroadphase || useGpuDynamics)
{
PxPhysXGpu* physxGpu = PxvGetPhysXGpu(true);
// PT: this creates a PxgMemoryManager, whose host memory allocator is a PxgCudaHostMemoryAllocatorCallback
mMemoryManager = physxGpu->createGpuMemoryManager(mLLContext->getCudaContextManager());
mGpuWranglerManagers = physxGpu->getGpuKernelWranglerManager(mLLContext->getCudaContextManager());
// PT: this creates a PxgHeapMemoryAllocatorManager
mHeapMemoryAllocationManager = physxGpu->createGpuHeapMemoryAllocatorManager(desc.gpuDynamicsConfig.heapCapacity, mMemoryManager, desc.gpuComputeVersion);
}
else
#endif
{
// PT: this creates a PxsDefaultMemoryManager
mMemoryManager = createDefaultMemoryManager();
}
Bp::BroadPhase* broadPhase = NULL;
//Note: broadphase should be independent of AABBManager. MBP uses it to call getBPBounds but it has
//already been passed all bounds in BroadPhase::update() so should use that instead.
// PT: above comment is obsolete: MBP now doesn't call getBPBounds anymore (except in commented out code)
// and it is instead the GPU broadphase which is not independent from the GPU AABB manager.......
if(!useGpuBroadphase)
{
PxBroadPhaseType::Enum broadPhaseType = desc.broadPhaseType;
if (broadPhaseType == PxBroadPhaseType::eGPU)
broadPhaseType = PxBroadPhaseType::eABP;
broadPhase = Bp::BroadPhase::create(
broadPhaseType,
desc.limits.maxNbRegions,
desc.limits.maxNbBroadPhaseOverlaps,
desc.limits.maxNbStaticShapes,
desc.limits.maxNbDynamicShapes,
contextID);
}
#if PX_SUPPORT_GPU_PHYSX
else
{
broadPhase = PxvGetPhysXGpu(true)->createGpuBroadPhase( mGpuWranglerManagers, mLLContext->getCudaContextManager(),
desc.gpuComputeVersion, desc.gpuDynamicsConfig,
mHeapMemoryAllocationManager, contextID);
}
#endif
//create allocator
PxVirtualAllocatorCallback* allocatorCallback = mMemoryManager->getHostMemoryAllocator();
PxVirtualAllocator allocator(allocatorCallback);
mBoundsArray = PX_NEW(Bp::BoundsArray)(allocator);
mContactDistance = PX_PLACEMENT_NEW(PX_ALLOC(sizeof(PxFloatArrayPinned), "ContactDistance"), PxFloatArrayPinned)(allocator);
mHasContactDistanceChanged = false;
const bool useEnhancedDeterminism = mPublicFlags & PxSceneFlag::eENABLE_ENHANCED_DETERMINISM;
mSimpleIslandManager = PX_NEW(IG::SimpleIslandManager)(useEnhancedDeterminism, contextID);
PxvNphaseImplementationContextUsableAsFallback* cpuNphaseImplementation = createNphaseImplementationContext(*mLLContext, &mSimpleIslandManager->getAccurateIslandSim(), allocatorCallback, useGpuDynamics);
if (!useGpuDynamics)
{
if (desc.solverType == PxSolverType::ePGS)
{
mDynamicsContext = createDynamicsContext
(&mLLContext->getNpMemBlockPool(), mLLContext->getScratchAllocator(),
mLLContext->getTaskPool(), mLLContext->getSimStats(), &mLLContext->getTaskManager(), allocatorCallback, &getMaterialManager(),
mSimpleIslandManager, contextID, mEnableStabilization, useEnhancedDeterminism, desc.maxBiasCoefficient,
!!(desc.flags & PxSceneFlag::eENABLE_FRICTION_EVERY_ITERATION), desc.getTolerancesScale().length);
}
else
{
mDynamicsContext = createTGSDynamicsContext
(&mLLContext->getNpMemBlockPool(), mLLContext->getScratchAllocator(),
mLLContext->getTaskPool(), mLLContext->getSimStats(), &mLLContext->getTaskManager(), allocatorCallback, &getMaterialManager(),
mSimpleIslandManager, contextID, mEnableStabilization, useEnhancedDeterminism,
desc.getTolerancesScale().length);
}
mLLContext->setNphaseImplementationContext(cpuNphaseImplementation);
mSimulationControllerCallback = PX_NEW(ScSimulationControllerCallback)(this);
mSimulationController = PX_NEW(SimulationController)(mSimulationControllerCallback);
if (!useGpuBroadphase)
mAABBManager = createAABBManagerCPU(desc, broadPhase, mBoundsArray, mContactDistance, allocator, contextID);
#if PX_SUPPORT_GPU_PHYSX
else
mAABBManager = createAABBManagerGPU(mGpuWranglerManagers, mLLContext->getCudaContextManager(), mHeapMemoryAllocationManager, desc, broadPhase, mBoundsArray, mContactDistance, allocator, contextID);
#endif
}
else
{
#if PX_SUPPORT_GPU_PHYSX
bool directAPI = mPublicFlags & PxSceneFlag::eENABLE_DIRECT_GPU_API;
mDynamicsContext = PxvGetPhysXGpu(true)->createGpuDynamicsContext(mLLContext->getTaskPool(), mGpuWranglerManagers, mLLContext->getCudaContextManager(),
desc.gpuDynamicsConfig, mSimpleIslandManager, desc.gpuMaxNumPartitions, desc.gpuMaxNumStaticPartitions, mEnableStabilization, useEnhancedDeterminism, desc.maxBiasCoefficient, desc.gpuComputeVersion, mLLContext->getSimStats(),
mHeapMemoryAllocationManager, !!(desc.flags & PxSceneFlag::eENABLE_FRICTION_EVERY_ITERATION), desc.solverType, desc.getTolerancesScale().length, directAPI);
void* contactStreamBase = NULL;
void* patchStreamBase = NULL;
void* forceAndIndiceStreamBase = NULL;
mDynamicsContext->getDataStreamBase(contactStreamBase, patchStreamBase, forceAndIndiceStreamBase);
mLLContext->setNphaseFallbackImplementationContext(cpuNphaseImplementation);
PxvNphaseImplementationContext* gpuNphaseImplementation = PxvGetPhysXGpu(true)->createGpuNphaseImplementationContext(*mLLContext, mGpuWranglerManagers, cpuNphaseImplementation, desc.gpuDynamicsConfig, contactStreamBase, patchStreamBase,
forceAndIndiceStreamBase, getBoundsArray().getBounds(), &mSimpleIslandManager->getAccurateIslandSim(), mDynamicsContext, desc.gpuComputeVersion, mHeapMemoryAllocationManager, useGpuBroadphase);
mSimulationControllerCallback = PX_NEW(PxgSimulationControllerCallback)(this);
mSimulationController = PxvGetPhysXGpu(true)->createGpuSimulationController(mGpuWranglerManagers, mLLContext->getCudaContextManager(),
mDynamicsContext, gpuNphaseImplementation, broadPhase, useGpuBroadphase, mSimpleIslandManager, mSimulationControllerCallback, desc.gpuComputeVersion, mHeapMemoryAllocationManager,
desc.gpuDynamicsConfig.maxSoftBodyContacts, desc.gpuDynamicsConfig.maxFemClothContacts, desc.gpuDynamicsConfig.maxParticleContacts, desc.gpuDynamicsConfig.maxHairContacts);
mSimulationController->setBounds(mBoundsArray);
mDynamicsContext->setSimulationController(mSimulationController);
mLLContext->setNphaseImplementationContext(gpuNphaseImplementation);
mLLContext->mContactStreamPool = &mDynamicsContext->getContactStreamPool();
mLLContext->mPatchStreamPool = &mDynamicsContext->getPatchStreamPool();
mLLContext->mForceAndIndiceStreamPool = &mDynamicsContext->getForceStreamPool();
// PT: TODO: what's the difference between this allocator and "allocator" above?
PxVirtualAllocator tAllocator(mHeapMemoryAllocationManager->mMappedMemoryAllocators, PxsHeapStats::eBROADPHASE);
if (!useGpuBroadphase)
// PT: TODO: we're using a CUDA allocator in the CPU broadphase, and a different allocator for the bounds array?
mAABBManager = createAABBManagerCPU(desc, broadPhase, mBoundsArray, mContactDistance, tAllocator, contextID);
else
mAABBManager = createAABBManagerGPU(mGpuWranglerManagers, mLLContext->getCudaContextManager(), mHeapMemoryAllocationManager, desc, broadPhase, mBoundsArray, mContactDistance, tAllocator, contextID);
#endif
}
//Construct the bitmap of updated actors required as input to the broadphase update
if(desc.limits.maxNbBodies)
{
// PT: TODO: revisit this. Why do we handle the added/removed and updated bitmaps entirely differently, in different places? And what is this weird formula here?
mAABBManager->getChangedAABBMgActorHandleMap().resize((2*desc.limits.maxNbBodies + 256) & ~255);
}
//mLLContext->createTransformCache(mDynamicsContext->getAllocatorCallback());
mLLContext->createTransformCache(*allocatorCallback);
mLLContext->setContactDistance(mContactDistance);
mCCDContext = PX_NEW(PxsCCDContext)(mLLContext, mDynamicsContext->getThresholdStream(), *mLLContext->getNphaseImplementationContext(), desc.ccdThreshold);
setSolverBatchSize(desc.solverBatchSize);
setSolverArticBatchSize(desc.solverArticulationBatchSize);
mDynamicsContext->setFrictionOffsetThreshold(desc.frictionOffsetThreshold);
mDynamicsContext->setCCDSeparationThreshold(desc.ccdMaxSeparation);
mDynamicsContext->setCorrelationDistance(desc.frictionCorrelationDistance);
const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale();
mLLContext->setMeshContactMargin(0.01f * scale.length);
mLLContext->setToleranceLength(scale.length);
// the original descriptor uses
// bounce iff impact velocity > threshold
// but LL use
// bounce iff separation velocity < -threshold
// hence we negate here.
mDynamicsContext->setBounceThreshold(-desc.bounceThresholdVelocity);
mStaticAnchor = mStaticSimPool->construct(*this, mAnchorCore);
mNPhaseCore = PX_NEW(NPhaseCore)(*this, desc);
// Init dominance matrix
{
//init all dominance pairs such that:
//if g1 == g2, then (1.0f, 1.0f) is returned
//if g1 < g2, then (0.0f, 1.0f) is returned
//if g1 > g2, then (1.0f, 0.0f) is returned
PxU32 mask = ~PxU32(1);
for (unsigned i = 0; i < PX_MAX_DOMINANCE_GROUP; ++i, mask <<= 1)
mDominanceBitMatrix[i] = ~mask;
}
// DeterminismDebugger::begin();
mWokeBodyListValid = true;
mSleepBodyListValid = true;
//load from desc:
setLimits(desc.limits);
// Create broad phase
mBroadphaseManager.setBroadPhaseCallback(desc.broadPhaseCallback);
setGravity(desc.gravity);
setFrictionType(desc.frictionType);
setPCM(desc.flags & PxSceneFlag::eENABLE_PCM);
setContactCache(!(desc.flags & PxSceneFlag::eDISABLE_CONTACT_CACHE));
setSimulationEventCallback(desc.simulationEventCallback);
setContactModifyCallback(desc.contactModifyCallback);
setCCDContactModifyCallback(desc.ccdContactModifyCallback);
setCCDMaxPasses(desc.ccdMaxPasses);
PX_ASSERT(mNPhaseCore); // refactor paranoia
PX_ASSERT( ((desc.filterShaderData) && (desc.filterShaderDataSize > 0)) ||
(!(desc.filterShaderData) && (desc.filterShaderDataSize == 0)) );
if (desc.filterShaderData)
{
mFilterShaderData = PX_ALLOC(desc.filterShaderDataSize, sFilterShaderDataMemAllocId);
PxMemCopy(mFilterShaderData, desc.filterShaderData, desc.filterShaderDataSize);
mFilterShaderDataSize = desc.filterShaderDataSize;
mFilterShaderDataCapacity = desc.filterShaderDataSize;
}
else
{
mFilterShaderData = NULL;
mFilterShaderDataSize = 0;
mFilterShaderDataCapacity = 0;
}
mFilterShader = desc.filterShader;
mFilterCallback = desc.filterCallback;
}
void Sc::Scene::release()
{
// TODO: PT: check virtual stuff
mTimeStamp++;
//collisionSpace.purgeAllPairs();
//purgePairs();
//releaseTagData();
// We know release all the shapes before the collision space
//collisionSpace.deleteAllShapes();
//collisionSpace.release();
//DeterminismDebugger::end();
PX_FREE(mActiveKinematicsCopy);
PX_DELETE(mNPhaseCore);
PX_FREE(mFilterShaderData);
if(mStaticAnchor)
mStaticSimPool->destroy(mStaticAnchor);
// Free object IDs and the deleted object id map
postReportsCleanup();
//before the task manager
if (mLLContext)
{
if(mLLContext->getNphaseFallbackImplementationContext())
{
mLLContext->getNphaseFallbackImplementationContext()->destroy();
mLLContext->setNphaseFallbackImplementationContext(NULL);
}
if(mLLContext->getNphaseImplementationContext())
{
mLLContext->getNphaseImplementationContext()->destroy();
mLLContext->setNphaseImplementationContext(NULL);
}
}
PX_DELETE(mSqBoundsManager);
PX_DELETE(mBoundsArray);
PX_DELETE(mConstraintInteractionPool);
PX_DELETE(mConstraintSimPool);
PX_DELETE(mSimStateDataPool);
PX_DELETE(mStaticSimPool);
PX_DELETE(mShapeSimPool);
PX_DELETE(mBodySimPool);
PX_DELETE(mLLArticulationRCPool);
#if PX_SUPPORT_GPU_PHYSX
gpu_releasePools();
#endif
mTriggerBufferExtraData->~TriggerBufferExtraData();
PX_FREE(mTriggerBufferExtraData);
PX_DELETE(mElementIDPool);
PX_DELETE(mActorIDTracker);
PX_DELETE(mConstraintIDTracker);
PX_DELETE(mStats);
Bp::BroadPhase* broadPhase = mAABBManager->getBroadPhase();
mAABBManager->destroy();
PX_RELEASE(broadPhase);
PX_DELETE(mSimulationControllerCallback);
PX_DELETE(mSimulationController);
mDynamicsContext->destroy();
PX_DELETE(mCCDContext);
PX_DELETE(mSimpleIslandManager);
#if PX_SUPPORT_GPU_PHYSX
gpu_release();
#endif
PX_RELEASE(mTaskManager);
PX_DELETE(mLLContext);
mContactDistance->~PxArray();
PX_FREE(mContactDistance);
PX_DELETE(mMemoryManager);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::preAllocate(PxU32 nbStatics, PxU32 nbBodies, PxU32 nbStaticShapes, PxU32 nbDynamicShapes)
{
// PT: TODO: this is only used for my addActors benchmark for now. Pre-allocate more arrays here.
mActiveBodies.reserve(PxMax<PxU32>(64,nbBodies));
mStaticSimPool->preAllocate(nbStatics);
mBodySimPool->preAllocate(nbBodies);
mShapeSimPool->preAllocate(nbStaticShapes + nbDynamicShapes);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::addDirtyArticulationSim(Sc::ArticulationSim* artiSim)
{
artiSim->setDirtyFlag(ArticulationSimDirtyFlag::eUPDATE);
mDirtyArticulationSims.insert(artiSim);
}
void Sc::Scene::removeDirtyArticulationSim(Sc::ArticulationSim* artiSim)
{
artiSim->setDirtyFlag(ArticulationSimDirtyFlag::eNONE);
mDirtyArticulationSims.erase(artiSim);
}
void Sc::Scene::addToActiveList(ActorSim& actorSim)
{
PX_ASSERT(actorSim.getActiveListIndex() >= SC_NOT_IN_ACTIVE_LIST_INDEX);
ActorCore* appendedActorCore = &actorSim.getActorCore();
if (actorSim.isDynamicRigid())
{
// Sort: kinematic before dynamic
const PxU32 size = mActiveBodies.size();
PxU32 incomingBodyActiveListIndex = size; // PT: by default we append the incoming body at the end of the current array.
BodySim& bodySim = static_cast<BodySim&>(actorSim);
if (bodySim.isKinematic()) // PT: Except if incoming body is kinematic, in which case:
{
const PxU32 nbKinematics = mActiveKinematicBodyCount++; // PT: - we increase their number
if (nbKinematics != size) // PT: - if there's at least one dynamic in the array...
{
PX_ASSERT(appendedActorCore != mActiveBodies[nbKinematics]);
appendedActorCore = mActiveBodies[nbKinematics]; // PT: ...then we grab the first dynamic after the kinematics...
appendedActorCore->getSim()->setActiveListIndex(size); // PT: ...and we move that one back to the end of the array...
mActiveBodies[nbKinematics] = static_cast<BodyCore*>(&actorSim.getActorCore()); // PT: ...while the incoming kine replaces the dynamic we moved out.
incomingBodyActiveListIndex = nbKinematics; // PT: ...thus the incoming kine's index is the prev #kines.
}
}
// for active compound rigids add to separate array, so we dont have to traverse all active actors
if (bodySim.readInternalFlag(BodySim::BF_IS_COMPOUND_RIGID))
{
PX_ASSERT(actorSim.getActiveCompoundListIndex() >= SC_NOT_IN_ACTIVE_LIST_INDEX);
const PxU32 compoundIndex = mActiveCompoundBodies.size();
mActiveCompoundBodies.pushBack(static_cast<BodyCore*>(appendedActorCore));
actorSim.setActiveCompoundListIndex(compoundIndex);
}
actorSim.setActiveListIndex(incomingBodyActiveListIndex); // PT: will be 'size' or 'nbKinematics', 'dynamicIndex'
mActiveBodies.pushBack(static_cast<BodyCore*>(appendedActorCore)); // PT: will be the incoming object or the first dynamic we moved out.
}
#if PX_SUPPORT_GPU_PHYSX
else
gpu_addToActiveList(actorSim, appendedActorCore);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
static void removeFromActiveCompoundBodyList(Sc::ActorSim& actorSim, PxArray<Sc::BodyCore*>& activeCompoundBodies)
{
const PxU32 removedCompoundIndex = actorSim.getActiveCompoundListIndex();
PX_ASSERT(removedCompoundIndex < SC_NOT_IN_ACTIVE_LIST_INDEX);
actorSim.setActiveCompoundListIndex(SC_NOT_IN_ACTIVE_LIST_INDEX);
const PxU32 newCompoundSize = activeCompoundBodies.size() - 1;
if(removedCompoundIndex != newCompoundSize)
{
Sc::BodyCore* lastBody = activeCompoundBodies[newCompoundSize];
activeCompoundBodies[removedCompoundIndex] = lastBody;
lastBody->getSim()->setActiveCompoundListIndex(removedCompoundIndex);
}
activeCompoundBodies.forceSize_Unsafe(newCompoundSize);
}
void Sc::Scene::removeFromActiveCompoundBodyList(BodySim& body)
{
::removeFromActiveCompoundBodyList(body, mActiveCompoundBodies);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::removeFromActiveList(ActorSim& actorSim)
{
PxU32 removedActiveIndex = actorSim.getActiveListIndex();
PX_ASSERT(removedActiveIndex < SC_NOT_IN_ACTIVE_LIST_INDEX);
actorSim.setActiveListIndex(SC_NOT_IN_ACTIVE_LIST_INDEX);
if (actorSim.isDynamicRigid())
{
PX_ASSERT(mActiveBodies[removedActiveIndex] == &actorSim.getActorCore());
const PxU32 newSize = mActiveBodies.size() - 1;
BodySim& bodySim = static_cast<BodySim&>(actorSim);
// Sort: kinematic before dynamic,
if (removedActiveIndex < mActiveKinematicBodyCount) // PT: same as 'body.isKinematic()' but without accessing the Core data
{
PX_ASSERT(mActiveKinematicBodyCount);
PX_ASSERT(bodySim.isKinematic());
const PxU32 swapIndex = --mActiveKinematicBodyCount;
if (newSize != swapIndex // PT: equal if the array only contains kinematics
&& removedActiveIndex < swapIndex) // PT: i.e. "if we don't remove the last kinematic"
{
BodyCore* swapBody = mActiveBodies[swapIndex];
swapBody->getSim()->setActiveListIndex(removedActiveIndex);
mActiveBodies[removedActiveIndex] = swapBody;
removedActiveIndex = swapIndex;
}
}
// for active compound rigids add to separate array, so we dont have to traverse all active actors
// A.B. TODO we should handle kinematic switch, no need to hold kinematic rigids in compound list
if(bodySim.readInternalFlag(BodySim::BF_IS_COMPOUND_RIGID))
::removeFromActiveCompoundBodyList(actorSim, mActiveCompoundBodies);
if (removedActiveIndex != newSize)
{
Sc::BodyCore* lastBody = mActiveBodies[newSize];
mActiveBodies[removedActiveIndex] = lastBody;
lastBody->getSim()->setActiveListIndex(removedActiveIndex);
}
mActiveBodies.forceSize_Unsafe(newSize);
}
#if PX_SUPPORT_GPU_PHYSX
else
gpu_removeFromActiveList(actorSim, removedActiveIndex);
#endif
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::swapInActiveBodyList(BodySim& body)
{
PX_ASSERT(!body.isStaticRigid() && !body.isSoftBody() && !body.isFEMCloth() && !body.isParticleSystem() && !body.isHairSystem());
const PxU32 activeListIndex = body.getActiveListIndex();
PX_ASSERT(activeListIndex < SC_NOT_IN_ACTIVE_LIST_INDEX);
PxU32 swapIndex;
PxU32 newActiveKinematicBodyCount;
if(activeListIndex < mActiveKinematicBodyCount)
{
// kinematic -> dynamic
PX_ASSERT(!body.isKinematic()); // the corresponding flag gets switched before this call
PX_ASSERT(mActiveKinematicBodyCount > 0); // there has to be at least one kinematic body
swapIndex = mActiveKinematicBodyCount - 1;
newActiveKinematicBodyCount = swapIndex;
}
else
{
// dynamic -> kinematic
PX_ASSERT(body.isKinematic()); // the corresponding flag gets switched before this call
PX_ASSERT(mActiveKinematicBodyCount < mActiveBodies.size()); // there has to be at least one dynamic body
swapIndex = mActiveKinematicBodyCount;
newActiveKinematicBodyCount = swapIndex + 1;
}
BodyCore*& swapBodyRef = mActiveBodies[swapIndex];
body.setActiveListIndex(swapIndex);
BodyCore* swapBody = swapBodyRef;
swapBodyRef = &body.getBodyCore();
swapBody->getSim()->setActiveListIndex(activeListIndex);
mActiveBodies[activeListIndex] = swapBody;
mActiveKinematicBodyCount = newActiveKinematicBodyCount;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::registerInteraction(ElementSimInteraction* interaction, bool active)
{
const InteractionType::Enum type = interaction->getType();
const PxU32 sceneArrayIndex = mInteractions[type].size();
interaction->setInteractionId(sceneArrayIndex);
mInteractions[type].pushBack(interaction);
if (active)
{
if (sceneArrayIndex > mActiveInteractionCount[type])
swapInteractionArrayIndices(sceneArrayIndex, mActiveInteractionCount[type], type);
mActiveInteractionCount[type]++;
}
mNPhaseCore->registerInteraction(interaction);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::unregisterInteraction(ElementSimInteraction* interaction)
{
const InteractionType::Enum type = interaction->getType();
const PxU32 sceneArrayIndex = interaction->getInteractionId();
PX_ASSERT(sceneArrayIndex != PX_INVALID_INTERACTION_SCENE_ID);
// if(sceneArrayIndex==PX_INVALID_INTERACTION_SCENE_ID)
// return;
mInteractions[type].replaceWithLast(sceneArrayIndex);
interaction->setInteractionId(PX_INVALID_INTERACTION_SCENE_ID);
if (sceneArrayIndex<mInteractions[type].size()) // The removed interaction was the last one, do not reset its sceneArrayIndex
mInteractions[type][sceneArrayIndex]->setInteractionId(sceneArrayIndex);
if (sceneArrayIndex<mActiveInteractionCount[type])
{
mActiveInteractionCount[type]--;
if (mActiveInteractionCount[type]<mInteractions[type].size())
swapInteractionArrayIndices(sceneArrayIndex, mActiveInteractionCount[type], type);
}
mNPhaseCore->unregisterInteraction(interaction);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::swapInteractionArrayIndices(PxU32 id1, PxU32 id2, InteractionType::Enum type)
{
PxArray<ElementSimInteraction*>& interArray = mInteractions[type];
ElementSimInteraction* interaction1 = interArray[id1];
ElementSimInteraction* interaction2 = interArray[id2];
interArray[id1] = interaction2;
interArray[id2] = interaction1;
interaction1->setInteractionId(id2);
interaction2->setInteractionId(id1);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::notifyInteractionActivated(Interaction* interaction)
{
PX_ASSERT((interaction->getType() == InteractionType::eOVERLAP) || (interaction->getType() == InteractionType::eTRIGGER));
PX_ASSERT(interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE));
PX_ASSERT(interaction->getInteractionId() != PX_INVALID_INTERACTION_SCENE_ID);
const InteractionType::Enum type = interaction->getType();
PX_ASSERT(interaction->getInteractionId() >= mActiveInteractionCount[type]);
if (mActiveInteractionCount[type] < mInteractions[type].size())
swapInteractionArrayIndices(mActiveInteractionCount[type], interaction->getInteractionId(), type);
mActiveInteractionCount[type]++;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::notifyInteractionDeactivated(Interaction* interaction)
{
PX_ASSERT((interaction->getType() == InteractionType::eOVERLAP) || (interaction->getType() == InteractionType::eTRIGGER));
PX_ASSERT(!interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE));
PX_ASSERT(interaction->getInteractionId() != PX_INVALID_INTERACTION_SCENE_ID);
const InteractionType::Enum type = interaction->getType();
PX_ASSERT(interaction->getInteractionId() < mActiveInteractionCount[type]);
if (mActiveInteractionCount[type] > 1)
swapInteractionArrayIndices(mActiveInteractionCount[type]-1, interaction->getInteractionId(), type);
mActiveInteractionCount[type]--;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void** Sc::Scene::allocatePointerBlock(PxU32 size)
{
PX_ASSERT(size>32 || size == 32 || size == 16 || size == 8);
void* ptr;
if(size==8)
ptr = mPointerBlock8Pool.construct();
else if(size == 16)
ptr = mPointerBlock16Pool.construct();
else if(size == 32)
ptr = mPointerBlock32Pool.construct();
else
ptr = PX_ALLOC(size * sizeof(void*), "void*");
return reinterpret_cast<void**>(ptr);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::deallocatePointerBlock(void** block, PxU32 size)
{
PX_ASSERT(size>32 || size == 32 || size == 16 || size == 8);
if(size==8)
mPointerBlock8Pool.destroy(reinterpret_cast<PointerBlock8*>(block));
else if(size == 16)
mPointerBlock16Pool.destroy(reinterpret_cast<PointerBlock16*>(block));
else if(size == 32)
mPointerBlock32Pool.destroy(reinterpret_cast<PointerBlock32*>(block));
else
PX_FREE(block);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::setFilterShaderData(const void* data, PxU32 dataSize)
{
PX_UNUSED(sFilterShaderDataMemAllocId);
if (data)
{
PX_ASSERT(dataSize > 0);
void* buffer;
if (dataSize <= mFilterShaderDataCapacity)
buffer = mFilterShaderData;
else
{
buffer = PX_ALLOC(dataSize, sFilterShaderDataMemAllocId);
if (buffer)
{
mFilterShaderDataCapacity = dataSize;
PX_FREE(mFilterShaderData);
}
else
{
outputError<PxErrorCode::eOUT_OF_MEMORY>(__LINE__, "Failed to allocate memory for filter shader data!");
return;
}
}
PxMemCopy(buffer, data, dataSize);
mFilterShaderData = buffer;
mFilterShaderDataSize = dataSize;
}
else
{
PX_ASSERT(dataSize == 0);
PX_FREE(mFilterShaderData);
mFilterShaderDataSize = 0;
mFilterShaderDataCapacity = 0;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//stepSetup is called in solve, but not collide
void Sc::Scene::stepSetupSolve(PxBaseTask* continuation)
{
PX_PROFILE_ZONE("Sim.stepSetupSolve", mContextId);
kinematicsSetup(continuation);
}
void Sc::Scene::advance(PxReal timeStep, PxBaseTask* continuation)
{
if(timeStep != 0.0f)
{
setElapsedTime(timeStep);
mAdvanceStep.setContinuation(continuation);
stepSetupSolve(&mAdvanceStep);
mAdvanceStep.removeReference();
}
}
void Sc::Scene::collide(PxReal timeStep, PxBaseTask* continuation)
{
mDt = timeStep;
stepSetupCollide(continuation);
mLLContext->beginUpdate();
mCollideStep.setContinuation(continuation);
mCollideStep.removeReference();
}
void Sc::Scene::endSimulation()
{
// Handle user contact filtering
// Note: Do this before the contact callbacks get fired since the filter callback might
// trigger contact reports (touch lost due to re-filtering)
mBroadphaseManager.prepareOutOfBoundsCallbacks(mAABBManager);
PxsContactManagerOutputIterator outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs();
mNPhaseCore->fireCustomFilteringCallbacks(outputs);
mNPhaseCore->preparePersistentContactEventListForNextFrame();
mSimulationController->releaseDeferredArticulationIds();
#if PX_SUPPORT_GPU_PHYSX
mSimulationController->releaseDeferredSoftBodyIds();
mSimulationController->releaseDeferredFEMClothIds();
mSimulationController->releaseDeferredParticleSystemIds();
mSimulationController->releaseDeferredHairSystemIds();
mAABBManager->releaseDeferredAggregateIds();
#endif
// End step / update time stamps
{
mTimeStamp++;
// INVALID_SLEEP_COUNTER is 0xffffffff. Therefore the last bit is masked. Look at Body::isForcedToSleep() for example.
// if(timeStamp==PX_INVALID_U32) timeStamp = 0; // Reserve INVALID_ID for something else
mTimeStamp &= 0x7fffffff;
mReportShapePairTimeStamp++; // to make sure that deleted shapes/actors after fetchResults() create new report pairs
}
PxcDisplayContactCacheStats();
}
void Sc::Scene::flush(bool sendPendingReports)
{
if (sendPendingReports)
{
fireQueuedContactCallbacks();
mNPhaseCore->clearContactReportStream();
mNPhaseCore->clearContactReportActorPairs(true);
fireTriggerCallbacks();
}
else
{
mNPhaseCore->clearContactReportActorPairs(true); // To clear the actor pair set
}
postReportsCleanup();
mNPhaseCore->freeContactReportStreamMemory();
mTriggerBufferAPI.reset();
mTriggerBufferExtraData->reset();
mBrokenConstraints.reset();
mBroadphaseManager.flush(mAABBManager);
clearSleepWakeBodies(); //!!! If we send out these reports on flush then this would not be necessary
mActorIDTracker->reset();
mElementIDPool->reset();
processLostTouchPairs(); // Processes the lost touch bodies
PX_ASSERT(mLostTouchPairs.size() == 0);
mLostTouchPairs.reset();
// Does not seem worth deleting the bitmap for the lost touch pair list
mActiveBodies.shrink();
for(PxU32 i=0; i < InteractionType::eTRACKED_IN_SCENE_COUNT; i++)
{
mInteractions[i].shrink();
}
//!!! TODO: look into retrieving memory from the NPhaseCore & Broadphase class (all the pools in there etc.)
mLLContext->getNpMemBlockPool().releaseUnusedBlocks();
}
// User callbacks
void Sc::Scene::setSimulationEventCallback(PxSimulationEventCallback* callback)
{
if(!mSimulationEventCallback && callback)
{
// if there was no callback before, the sleeping bodies have to be prepared for potential notification events (no shortcut possible anymore)
BodyCore* const* sleepingBodies = mSleepBodies.getEntries();
for (PxU32 i = 0; i < mSleepBodies.size(); i++)
{
sleepingBodies[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY);
}
#if PX_SUPPORT_GPU_PHYSX
gpu_setSimulationEventCallback(callback);
#endif
}
mSimulationEventCallback = callback;
}
PxSimulationEventCallback* Sc::Scene::getSimulationEventCallback() const
{
return mSimulationEventCallback;
}
void Sc::Scene::removeBody(BodySim& body) //this also notifies any connected joints!
{
BodyCore& core = body.getBodyCore();
// Remove from sleepBodies array
mSleepBodies.erase(&core);
PX_ASSERT(!mSleepBodies.contains(&core));
// Remove from wokeBodies array
mWokeBodies.erase(&core);
PX_ASSERT(!mWokeBodies.contains(&core));
if (body.isActive() && (core.getFlags() & PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW))
removeFromPosePreviewList(body);
else
PX_ASSERT(!isInPosePreviewList(body));
markReleasedBodyIDForLostTouch(body.getActorID());
}
void Sc::Scene::addConstraint(ConstraintCore& constraint, RigidCore* body0, RigidCore* body1)
{
ConstraintSim* sim = mConstraintSimPool->construct(constraint, body0, body1, *this);
PX_UNUSED(sim);
PxNodeIndex nodeIndex0, nodeIndex1;
ActorSim* sim0 = NULL;
ActorSim* sim1 = NULL;
if (body0)
{
sim0 = body0->getSim();
nodeIndex0 = sim0->getNodeIndex();
}
if (body1)
{
sim1 = body1->getSim();
nodeIndex1 = sim1->getNodeIndex();
}
if (nodeIndex1 < nodeIndex0)
PxSwap(sim0, sim1);
mConstraintMap.insert(PxPair<const Sc::ActorSim*, const Sc::ActorSim*>(sim0, sim1), &constraint);
mConstraints.insert(&constraint);
}
void Sc::Scene::removeConstraint(ConstraintCore& constraint)
{
ConstraintSim* cSim = constraint.getSim();
if (cSim)
{
{
PxNodeIndex nodeIndex0, nodeIndex1;
const ConstraintInteraction* interaction = cSim->getInteraction();
Sc::ActorSim* bSim = &interaction->getActorSim0();
Sc::ActorSim* bSim1 = &interaction->getActorSim1();
if (bSim)
nodeIndex0 = bSim->getNodeIndex();
if (bSim1)
nodeIndex1 = bSim1->getNodeIndex();
if (nodeIndex1 < nodeIndex0)
PxSwap(bSim, bSim1);
mConstraintMap.erase(PxPair<const Sc::ActorSim*, const Sc::ActorSim*>(bSim, bSim1));
}
mConstraintSimPool->destroy(cSim);
}
mConstraints.erase(&constraint);
}
void Sc::Scene::addArticulation(ArticulationCore& articulation, BodyCore& root)
{
ArticulationSim* sim = PX_NEW(ArticulationSim)(articulation, *this, root);
if (sim && (sim->getLowLevelArticulation() == NULL))
{
PX_DELETE(sim);
return;
}
mArticulations.insert(&articulation);
addDirtyArticulationSim(sim);
}
void Sc::Scene::removeArticulation(ArticulationCore& articulation)
{
ArticulationSim* a = articulation.getSim();
Sc::ArticulationSimDirtyFlags dirtyFlags = a->getDirtyFlag();
const bool isDirty = (dirtyFlags & Sc::ArticulationSimDirtyFlag::eUPDATE);
if(isDirty)
removeDirtyArticulationSim(a);
PX_DELETE(a);
mArticulations.erase(&articulation);
}
void Sc::Scene::addArticulationJoint(ArticulationJointCore& joint, BodyCore& parent, BodyCore& child)
{
ArticulationJointSim* sim = PX_NEW(ArticulationJointSim)(joint, *parent.getSim(), *child.getSim());
PX_UNUSED(sim);
}
void Sc::Scene::removeArticulationJoint(ArticulationJointCore& joint)
{
ArticulationJointSim* sim = joint.getSim();
PX_DELETE(sim);
}
void Sc::Scene::addArticulationTendon(ArticulationSpatialTendonCore& tendon)
{
ArticulationSpatialTendonSim* sim = PX_NEW(ArticulationSpatialTendonSim)(tendon, *this);
PX_UNUSED(sim);
}
void Sc::Scene::removeArticulationTendon(ArticulationSpatialTendonCore& tendon)
{
ArticulationSpatialTendonSim* sim = tendon.getSim();
PX_DELETE(sim);
}
void Sc::Scene::addArticulationTendon(ArticulationFixedTendonCore& tendon)
{
ArticulationFixedTendonSim* sim = PX_NEW(ArticulationFixedTendonSim)(tendon, *this);
PX_UNUSED(sim);
}
void Sc::Scene::removeArticulationTendon(ArticulationFixedTendonCore& tendon)
{
ArticulationFixedTendonSim* sim = tendon.getSim();
PX_DELETE(sim);
}
void Sc::Scene::addArticulationSensor(ArticulationSensorCore& sensor)
{
ArticulationSensorSim* sim = PX_NEW(ArticulationSensorSim)(sensor, *this);
PX_UNUSED(sim);
}
void Sc::Scene::removeArticulationSensor(ArticulationSensorCore& sensor)
{
ArticulationSensorSim* sim = sensor.getSim();
PX_DELETE(sim);
}
void Sc::Scene::addArticulationSimControl(Sc::ArticulationCore& core)
{
Sc::ArticulationSim* sim = core.getSim();
if (sim)
mSimulationController->addArticulation(sim->getLowLevelArticulation(), sim->getIslandNodeIndex());
}
void Sc::Scene::removeArticulationSimControl(Sc::ArticulationCore& core)
{
Sc::ArticulationSim* sim = core.getSim();
if (sim)
mSimulationController->releaseArticulation(sim->getLowLevelArticulation(), sim->getIslandNodeIndex());
}
void* Sc::Scene::allocateConstraintBlock(PxU32 size)
{
if(size<=128)
return mMemBlock128Pool.construct();
else if(size<=256)
return mMemBlock256Pool.construct();
else if(size<=384)
return mMemBlock384Pool.construct();
else
return PX_ALLOC(size, "ConstraintBlock");
}
void Sc::Scene::deallocateConstraintBlock(void* ptr, PxU32 size)
{
if(size<=128)
mMemBlock128Pool.destroy(reinterpret_cast<MemBlock128*>(ptr));
else if(size<=256)
mMemBlock256Pool.destroy(reinterpret_cast<MemBlock256*>(ptr));
else if(size<=384)
mMemBlock384Pool.destroy(reinterpret_cast<MemBlock384*>(ptr));
else
PX_FREE(ptr);
}
void Sc::Scene::postReportsCleanup()
{
mElementIDPool->processPendingReleases();
mElementIDPool->clearDeletedIDMap();
mActorIDTracker->processPendingReleases();
mActorIDTracker->clearDeletedIDMap();
mConstraintIDTracker->processPendingReleases();
mConstraintIDTracker->clearDeletedIDMap();
mSimulationController->flush();
}
PX_COMPILE_TIME_ASSERT(sizeof(PxTransform32)==sizeof(PxsCachedTransform));
// PT: TODO: move this out of Sc? this is only called by Np
void Sc::Scene::syncSceneQueryBounds(SqBoundsSync& sync, SqRefFinder& finder)
{
const PxsTransformCache& cache = mLLContext->getTransformCache();
mSqBoundsManager->syncBounds(sync, finder, mBoundsArray->begin(), reinterpret_cast<const PxTransform32*>(cache.getTransforms()), mContextId, mDirtyShapeSimMap);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::Scene::resizeReleasedBodyIDMaps(PxU32 maxActors, PxU32 numActors)
{
mLostTouchPairsDeletedBodyIDs.resize(maxActors);
mActorIDTracker->resizeDeletedIDMap(maxActors,numActors);
mElementIDPool->resizeDeletedIDMap(maxActors,numActors);
}
void Sc::Scene::finalizeContactStreamAndCreateHeader(PxContactPairHeader& header, const ActorPairReport& aPair, ContactStreamManager& cs, PxU32 removedShapeTestMask)
{
PxU8* stream = mNPhaseCore->getContactReportPairData(cs.bufferIndex);
PxU32 streamManagerFlag = cs.getFlags();
ContactShapePair* contactPairs = cs.getShapePairs(stream);
const PxU16 nbShapePairs = cs.currentPairCount;
PX_ASSERT(nbShapePairs > 0);
if (streamManagerFlag & removedShapeTestMask)
{
// At least one shape of this actor pair has been deleted. Need to traverse the contact buffer,
// find the pairs which contain deleted shapes and set the flags accordingly.
ContactStreamManager::convertDeletedShapesInContactStream(contactPairs, nbShapePairs, getElementIDPool());
}
PX_ASSERT(contactPairs);
ObjectIDTracker& ActorIDTracker = getActorIDTracker();
header.actors[0] = aPair.getPxActorA();
header.actors[1] = aPair.getPxActorB();
PxU16 headerFlags = 0;
if (ActorIDTracker.isDeletedID(aPair.getActorAID()))
headerFlags |= PxContactPairHeaderFlag::eREMOVED_ACTOR_0;
if (ActorIDTracker.isDeletedID(aPair.getActorBID()))
headerFlags |= PxContactPairHeaderFlag::eREMOVED_ACTOR_1;
header.flags = PxContactPairHeaderFlags(headerFlags);
header.pairs = reinterpret_cast<PxContactPair*>(contactPairs);
header.nbPairs = nbShapePairs;
PxU16 extraDataSize = cs.extraDataSize;
if (!extraDataSize)
header.extraDataStream = NULL;
else
{
PX_ASSERT(extraDataSize >= sizeof(ContactStreamHeader));
extraDataSize -= sizeof(ContactStreamHeader);
header.extraDataStream = stream + sizeof(ContactStreamHeader);
if (streamManagerFlag & ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY)
{
PX_ASSERT(!(headerFlags & PxTo16(PxContactPairHeaderFlag::eREMOVED_ACTOR_0 | PxContactPairHeaderFlag::eREMOVED_ACTOR_1)));
cs.setContactReportPostSolverVelocity(stream, aPair.getActorA(), aPair.getActorB());
}
}
header.extraDataStreamSize = extraDataSize;
}
const PxArray<PxContactPairHeader>& Sc::Scene::getQueuedContactPairHeaders()
{
const PxU32 removedShapeTestMask = PxU32(ContactStreamManagerFlag::eTEST_FOR_REMOVED_SHAPES);
ActorPairReport*const* actorPairs = mNPhaseCore->getContactReportActorPairs();
PxU32 nbActorPairs = mNPhaseCore->getNbContactReportActorPairs();
mQueuedContactPairHeaders.reserve(nbActorPairs);
mQueuedContactPairHeaders.clear();
for (PxU32 i = 0; i < nbActorPairs; i++)
{
if (i < (nbActorPairs - 1))
PxPrefetchLine(actorPairs[i + 1]);
ActorPairReport* aPair = actorPairs[i];
ContactStreamManager& cs = aPair->getContactStreamManager();
if (cs.getFlags() & ContactStreamManagerFlag::eINVALID_STREAM)
continue;
if (i + 1 < nbActorPairs)
PxPrefetch(&(actorPairs[i + 1]->getContactStreamManager()));
PxContactPairHeader &pairHeader = mQueuedContactPairHeaders.insert();
finalizeContactStreamAndCreateHeader(pairHeader, *aPair, cs, removedShapeTestMask);
cs.maxPairCount = cs.currentPairCount;
cs.setMaxExtraDataSize(cs.extraDataSize);
}
return mQueuedContactPairHeaders;
}
/*
Threading: called in the context of the user thread, but only after the physics thread has finished its run
*/
void Sc::Scene::fireQueuedContactCallbacks()
{
if(mSimulationEventCallback)
{
const PxU32 removedShapeTestMask = PxU32(ContactStreamManagerFlag::eTEST_FOR_REMOVED_SHAPES);
ActorPairReport*const* actorPairs = mNPhaseCore->getContactReportActorPairs();
PxU32 nbActorPairs = mNPhaseCore->getNbContactReportActorPairs();
for(PxU32 i=0; i < nbActorPairs; i++)
{
if (i < (nbActorPairs - 1))
PxPrefetchLine(actorPairs[i+1]);
ActorPairReport* aPair = actorPairs[i];
ContactStreamManager* cs = &aPair->getContactStreamManager();
if (cs == NULL || cs->getFlags() & ContactStreamManagerFlag::eINVALID_STREAM)
continue;
if (i + 1 < nbActorPairs)
PxPrefetch(&(actorPairs[i+1]->getContactStreamManager()));
PxContactPairHeader pairHeader;
finalizeContactStreamAndCreateHeader(pairHeader, *aPair, *cs, removedShapeTestMask);
mSimulationEventCallback->onContact(pairHeader, pairHeader.pairs, pairHeader.nbPairs);
// estimates for next frame
cs->maxPairCount = cs->currentPairCount;
cs->setMaxExtraDataSize(cs->extraDataSize);
}
}
}
PX_FORCE_INLINE void markDeletedShapes(Sc::ObjectIDTracker& idTracker, Sc::TriggerPairExtraData& tped, PxTriggerPair& pair)
{
PxTriggerPairFlags::InternalType flags = 0;
if (idTracker.isDeletedID(tped.shape0ID))
flags |= PxTriggerPairFlag::eREMOVED_SHAPE_TRIGGER;
if (idTracker.isDeletedID(tped.shape1ID))
flags |= PxTriggerPairFlag::eREMOVED_SHAPE_OTHER;
pair.flags = PxTriggerPairFlags(flags);
}
void Sc::Scene::fireTriggerCallbacks()
{
// triggers
const PxU32 nbTriggerPairs = mTriggerBufferAPI.size();
PX_ASSERT(nbTriggerPairs == mTriggerBufferExtraData->size());
if(nbTriggerPairs)
{
// cases to take into account:
// - no simulation/trigger shape has been removed -> no need to test shape references for removed shapes
// - simulation/trigger shapes have been removed -> test the events that have
// a marker for removed shapes set
//
const bool hasRemovedShapes = mElementIDPool->getDeletedIDCount() > 0;
if(mSimulationEventCallback)
{
if (!hasRemovedShapes)
mSimulationEventCallback->onTrigger(mTriggerBufferAPI.begin(), nbTriggerPairs);
else
{
for(PxU32 i = 0; i < nbTriggerPairs; i++)
{
PxTriggerPair& triggerPair = mTriggerBufferAPI[i];
if ((PxTriggerPairFlags::InternalType(triggerPair.flags) & TriggerPairFlag::eTEST_FOR_REMOVED_SHAPES))
markDeletedShapes(*mElementIDPool, (*mTriggerBufferExtraData)[i], triggerPair);
}
mSimulationEventCallback->onTrigger(mTriggerBufferAPI.begin(), nbTriggerPairs);
}
}
}
// PT: clear the buffer **even when there's no simulationEventCallback**.
mTriggerBufferAPI.clear();
mTriggerBufferExtraData->clear();
}
/*
Threading: called in the context of the user thread, but only after the physics thread has finished its run
*/
void Sc::Scene::fireCallbacksPostSync()
{
//
// Fire sleep & woken callbacks
//
// A body should be either in the sleep or the woken list. If it is in both, remove it from the list it was
// least recently added to.
if(!mSleepBodyListValid)
cleanUpSleepBodies();
if(!mWokeBodyListValid)
cleanUpWokenBodies();
#if PX_SUPPORT_GPU_PHYSX
const PxU32 maxGpuSizeNeeded = gpu_cleanUpSleepAndWokenBodies();
#endif
if(mSimulationEventCallback || mOnSleepingStateChanged)
{
// allocate temporary data
const PxU32 nbSleep = mSleepBodies.size();
const PxU32 nbWoken = mWokeBodies.size();
#if PX_SUPPORT_GPU_PHYSX
const PxU32 arrSize = PxMax(PxMax(nbSleep, nbWoken), maxGpuSizeNeeded);
#else
const PxU32 arrSize = PxMax(nbSleep, nbWoken);
#endif
PxActor** actors = arrSize ? reinterpret_cast<PxActor**>(PX_ALLOC(arrSize*sizeof(PxActor*), "PxActor*")) : NULL;
if(actors)
{
if(nbSleep)
{
PxU32 destSlot = 0;
BodyCore* const* sleepingBodies = mSleepBodies.getEntries();
for(PxU32 i=0; i<nbSleep; i++)
{
BodyCore* body = sleepingBodies[i];
if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES)
actors[destSlot++] = body->getPxActor();
if (mOnSleepingStateChanged)
mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), true);
}
if(destSlot && mSimulationEventCallback)
mSimulationEventCallback->onSleep(actors, destSlot);
//if (PX_DBG_IS_CONNECTED())
//{
// for (PxU32 i = 0; i < nbSleep; ++i)
// {
// BodyCore* body = mSleepBodies[i];
// PX_ASSERT(body->getActorType() == PxActorType::eRIGID_DYNAMIC);
// }
//}
}
#if PX_SUPPORT_GPU_PHYSX
gpu_fireOnSleepCallback(actors);
#endif
// do the same thing for bodies that have just woken up
if(nbWoken)
{
PxU32 destSlot = 0;
BodyCore* const* wokenBodies = mWokeBodies.getEntries();
for(PxU32 i=0; i<nbWoken; i++)
{
BodyCore* body = wokenBodies[i];
if(body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES)
actors[destSlot++] = body->getPxActor();
if (mOnSleepingStateChanged)
mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), false);
}
if(destSlot && mSimulationEventCallback)
mSimulationEventCallback->onWake(actors, destSlot);
}
#if PX_SUPPORT_GPU_PHYSX
gpu_fireOnWakeCallback(actors);
#endif
PX_FREE(actors);
}
}
clearSleepWakeBodies();
}
void Sc::Scene::postCallbacksPreSync()
{
PX_PROFILE_ZONE("Sim.postCallbackPreSync", mContextId);
// clear contact stream data
mNPhaseCore->clearContactReportStream();
mNPhaseCore->clearContactReportActorPairs(false);
postCallbacksPreSyncKinematics();
releaseConstraints(true); //release constraint blocks at the end of the frame, so user can retrieve the blocks
}
void Sc::Scene::getStats(PxSimulationStatistics& s) const
{
mStats->readOut(s, mLLContext->getSimStats());
s.nbStaticBodies = mNbRigidStatics;
s.nbDynamicBodies = mNbRigidDynamics;
s.nbKinematicBodies = mNbRigidKinematic;
s.nbArticulations = mArticulations.size();
s.nbAggregates = mAABBManager->getNbActiveAggregates();
for(PxU32 i=0; i<PxGeometryType::eGEOMETRY_COUNT; i++)
s.nbShapes[i] = mNbGeometries[i];
#if PX_SUPPORT_GPU_PHYSX
if (mHeapMemoryAllocationManager)
{
s.gpuMemHeap = mHeapMemoryAllocationManager->getDeviceMemorySize();
const PxsHeapStats& deviceHeapStats = mHeapMemoryAllocationManager->getDeviceHeapStats();
s.gpuMemHeapBroadPhase = deviceHeapStats.stats[PxsHeapStats::eBROADPHASE];
s.gpuMemHeapNarrowPhase = deviceHeapStats.stats[PxsHeapStats::eNARROWPHASE];
s.gpuMemHeapSolver = deviceHeapStats.stats[PxsHeapStats::eSOLVER];
s.gpuMemHeapArticulation = deviceHeapStats.stats[PxsHeapStats::eARTICULATION];
s.gpuMemHeapSimulation = deviceHeapStats.stats[PxsHeapStats::eSIMULATION];
s.gpuMemHeapSimulationArticulation = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_ARTICULATION];
s.gpuMemHeapSimulationParticles = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_PARTICLES];
s.gpuMemHeapSimulationSoftBody = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_SOFTBODY];
s.gpuMemHeapSimulationFEMCloth = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_FEMCLOTH];
s.gpuMemHeapSimulationHairSystem = deviceHeapStats.stats[PxsHeapStats::eSIMULATION_HAIRSYSTEM];
s.gpuMemHeapParticles = deviceHeapStats.stats[PxsHeapStats::eSHARED_PARTICLES];
s.gpuMemHeapFEMCloths = deviceHeapStats.stats[PxsHeapStats::eSHARED_FEMCLOTH];
s.gpuMemHeapSoftBodies = deviceHeapStats.stats[PxsHeapStats::eSHARED_SOFTBODY];
s.gpuMemHeapHairSystems = deviceHeapStats.stats[PxsHeapStats::eSHARED_HAIRSYSTEM];
s.gpuMemHeapOther = deviceHeapStats.stats[PxsHeapStats::eOTHER];
}
else
#endif
{
s.gpuMemHeap = 0;
s.gpuMemParticles = 0;
s.gpuMemSoftBodies = 0;
s.gpuMemFEMCloths = 0;
s.gpuMemHairSystems = 0;
s.gpuMemHeapBroadPhase = 0;
s.gpuMemHeapNarrowPhase = 0;
s.gpuMemHeapSolver = 0;
s.gpuMemHeapArticulation = 0;
s.gpuMemHeapSimulation = 0;
s.gpuMemHeapSimulationArticulation = 0;
s.gpuMemHeapSimulationParticles = 0;
s.gpuMemHeapSimulationSoftBody = 0;
s.gpuMemHeapSimulationFEMCloth = 0;
s.gpuMemHeapSimulationHairSystem = 0;
s.gpuMemHeapParticles = 0;
s.gpuMemHeapSoftBodies = 0;
s.gpuMemHeapFEMCloths = 0;
s.gpuMemHeapHairSystems = 0;
s.gpuMemHeapOther = 0;
}
}
void Sc::Scene::addShapes(NpShape *const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& bodySim, PxBounds3* outBounds)
{
const PxNodeIndex nodeIndex = bodySim.getNodeIndex();
PxvNphaseImplementationContext* context = mLLContext->getNphaseImplementationContext();
for(PxU32 i=0;i<nbShapes;i++)
{
// PT: TODO: drop the offsets and let me include NpShape.h from here! This is just NpShape::getCore()....
ShapeCore& sc = *reinterpret_cast<ShapeCore*>(size_t(shapes[i])+ptrOffset);
//PxBounds3* target = uninflatedBounds ? uninflatedBounds + i : uninflatedBounds;
//mShapeSimPool->construct(sim, sc, llBody, target);
ShapeSim* shapeSim = mShapeSimPool->construct(bodySim, sc);
mNbGeometries[sc.getGeometryType()]++;
mSimulationController->addShape(&shapeSim->getLLShapeSim(), shapeSim->getElementID());
if (outBounds)
outBounds[i] = mBoundsArray->getBounds(shapeSim->getElementID());
//I register the shape if its either not an articulation link or if the nodeIndex has already been
//assigned. On insertion, the articulation will not have this nodeIndex correctly assigned at this stage
if (bodySim.getActorType() != PxActorType::eARTICULATION_LINK || !nodeIndex.isStaticBody())
context->registerShape(nodeIndex, sc.getCore(), shapeSim->getElementID(), bodySim.getPxActor());
}
}
void Sc::Scene::removeShapes(Sc::RigidSim& sim, PxInlineArray<Sc::ShapeSim*, 64>& shapesBuffer , PxInlineArray<const Sc::ShapeCore*,64>& removedShapes, bool wakeOnLostTouch)
{
PxU32 nbElems = sim.getNbElements();
Sc::ElementSim** elems = sim.getElements();
while (nbElems--)
{
Sc::ShapeSim* s = static_cast<Sc::ShapeSim*>(*elems++);
// can do two 2x the allocs in the worst case, but actors with >64 shapes are not common
shapesBuffer.pushBack(s);
removedShapes.pushBack(&s->getCore());
}
for(PxU32 i=0;i<shapesBuffer.size();i++)
removeShape_(*shapesBuffer[i], wakeOnLostTouch);
}
void Sc::Scene::addStatic(StaticCore& ro, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* uninflatedBounds)
{
PX_ASSERT(ro.getActorCoreType() == PxActorType::eRIGID_STATIC);
// sim objects do all the necessary work of adding themselves to broad phase,
// activation, registering with the interaction system, etc
StaticSim* sim = mStaticSimPool->construct(*this, ro);
mNbRigidStatics++;
addShapes(shapes, nbShapes, shapePtrOffset, *sim, uninflatedBounds);
}
void Sc::Scene::removeStatic(StaticCore& ro, PxInlineArray<const Sc::ShapeCore*,64>& removedShapes, bool wakeOnLostTouch)
{
PX_ASSERT(ro.getActorCoreType() == PxActorType::eRIGID_STATIC);
StaticSim* sim = ro.getSim();
if(sim)
{
if(mBatchRemoveState)
{
removeShapes(*sim, mBatchRemoveState->bufferedShapes ,removedShapes, wakeOnLostTouch);
}
else
{
PxInlineArray<Sc::ShapeSim*, 64> shapesBuffer;
removeShapes(*sim, shapesBuffer ,removedShapes, wakeOnLostTouch);
}
mStaticSimPool->destroy(static_cast<Sc::StaticSim*>(ro.getSim()));
mNbRigidStatics--;
}
}
void Sc::Scene::addBody(BodyCore& body, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* outBounds, bool compound)
{
// sim objects do all the necessary work of adding themselves to broad phase,
// activation, registering with the interaction system, etc
BodySim* sim = mBodySimPool->construct(*this, body, compound);
const bool isArticulationLink = sim->isArticulationLink();
if (sim->getLowLevelBody().mCore->mFlags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD && sim->isActive())
{
if (isArticulationLink)
{
if (sim->getNodeIndex().isValid())
mSpeculativeCDDArticulationBitMap.growAndSet(sim->getNodeIndex().index());
}
else
mSpeculativeCCDRigidBodyBitMap.growAndSet(sim->getNodeIndex().index());
}
//if rigid body is articulation link, the node index will be invalid. We should add the link to the scene after we add the
//articulation for gpu
if(sim->getNodeIndex().isValid())
mSimulationController->addDynamic(&sim->getLowLevelBody(), sim->getNodeIndex());
if(sim->getSimStateData(true) && sim->getSimStateData(true)->isKine())
mNbRigidKinematic++;
else
mNbRigidDynamics++;
addShapes(shapes, nbShapes, shapePtrOffset, *sim, outBounds);
mDynamicsContext->setStateDirty(true);
}
void Sc::Scene::removeBody(BodyCore& body, PxInlineArray<const Sc::ShapeCore*,64>& removedShapes, bool wakeOnLostTouch)
{
BodySim *sim = body.getSim();
if(sim)
{
if(mBatchRemoveState)
{
removeShapes(*sim, mBatchRemoveState->bufferedShapes, removedShapes, wakeOnLostTouch);
}
else
{
PxInlineArray<Sc::ShapeSim*, 64> shapesBuffer;
removeShapes(*sim,shapesBuffer, removedShapes, wakeOnLostTouch);
}
if(!sim->isArticulationLink())
{
//clear bit map
if(sim->getLowLevelBody().mCore->mFlags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD)
sim->getScene().resetSpeculativeCCDRigidBody(sim->getNodeIndex().index());
}
else
{
// PT: TODO: missing call to resetSpeculativeCCDArticulationLink ?
sim->getArticulation()->removeBody(*sim);
}
if(sim->getSimStateData(true) && sim->getSimStateData(true)->isKine())
{
body.onRemoveKinematicFromScene();
mNbRigidKinematic--;
}
else
mNbRigidDynamics--;
mBodySimPool->destroy(sim);
mDynamicsContext->setStateDirty(true);
}
}
// PT: TODO: refactor with addShapes
void Sc::Scene::addShape_(RigidSim& owner, ShapeCore& shapeCore)
{
ShapeSim* sim = mShapeSimPool->construct(owner, shapeCore);
mNbGeometries[shapeCore.getGeometryType()]++;
//register shape
mSimulationController->addShape(&sim->getLLShapeSim(), sim->getElementID());
registerShapeInNphase(&owner.getRigidCore(), shapeCore, sim->getElementID());
}
// PT: TODO: refactor with removeShapes
void Sc::Scene::removeShape_(ShapeSim& shape, bool wakeOnLostTouch)
{
//BodySim* body = shape.getBodySim();
//if(body)
// body->postShapeDetach();
unregisterShapeFromNphase(shape.getCore(), shape.getElementID());
mSimulationController->removeShape(shape.getElementID());
mNbGeometries[shape.getCore().getGeometryType()]--;
shape.removeFromBroadPhase(wakeOnLostTouch);
mShapeSimPool->destroy(&shape);
}
void Sc::Scene::registerShapeInNphase(Sc::RigidCore* rigidCore, const ShapeCore& shape, const PxU32 transformCacheID)
{
RigidSim* sim = rigidCore->getSim();
if(sim)
mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), shape.getCore(), transformCacheID, sim->getPxActor());
}
void Sc::Scene::unregisterShapeFromNphase(const ShapeCore& shape, const PxU32 transformCacheID)
{
mLLContext->getNphaseImplementationContext()->unregisterShape(shape.getCore(), transformCacheID);
}
void Sc::Scene::notifyNphaseOnUpdateShapeMaterial(const ShapeCore& shapeCore)
{
mLLContext->getNphaseImplementationContext()->updateShapeMaterial(shapeCore.getCore());
}
void Sc::Scene::startBatchInsertion(BatchInsertionState&state)
{
state.shapeSim = mShapeSimPool->allocateAndPrefetch();
state.staticSim = mStaticSimPool->allocateAndPrefetch();
state.bodySim = mBodySimPool->allocateAndPrefetch();
}
void Sc::Scene::addShapes(NpShape*const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& rigidSim, ShapeSim*& prefetchedShapeSim, PxBounds3* outBounds)
{
for(PxU32 i=0;i<nbShapes;i++)
{
if(i+1<nbShapes)
PxPrefetch(shapes[i+1], PxU32(ptrOffset+sizeof(Sc::ShapeCore)));
ShapeSim* nextShapeSim = mShapeSimPool->allocateAndPrefetch();
ShapeCore& sc = *PxPointerOffset<ShapeCore*>(shapes[i], ptrdiff_t(ptrOffset));
PX_PLACEMENT_NEW(prefetchedShapeSim, ShapeSim(rigidSim, sc));
const PxU32 elementID = prefetchedShapeSim->getElementID();
outBounds[i] = mBoundsArray->getBounds(elementID);
mSimulationController->addShape(&prefetchedShapeSim->getLLShapeSim(), elementID);
mLLContext->getNphaseImplementationContext()->registerShape(rigidSim.getNodeIndex(), sc.getCore(), elementID, rigidSim.getPxActor());
prefetchedShapeSim = nextShapeSim;
mNbGeometries[sc.getGeometryType()]++;
}
}
void Sc::Scene::addStatic(PxActor* actor, BatchInsertionState& s, PxBounds3* outBounds)
{
// static core has been prefetched by caller
Sc::StaticSim* sim = s.staticSim; // static core has been prefetched by the caller
const Cm::PtrTable* shapeTable = PxPointerOffset<const Cm::PtrTable*>(actor, s.staticShapeTableOffset);
void*const* shapes = shapeTable->getPtrs();
mStaticSimPool->construct(sim, *this, *PxPointerOffset<Sc::StaticCore*>(actor, s.staticActorOffset));
s.staticSim = mStaticSimPool->allocateAndPrefetch();
addShapes(reinterpret_cast<NpShape*const*>(shapes), shapeTable->getCount(), size_t(s.shapeOffset), *sim, s.shapeSim, outBounds);
mNbRigidStatics++;
}
void Sc::Scene::addBody(PxActor* actor, BatchInsertionState& s, PxBounds3* outBounds, bool compound)
{
Sc::BodySim* sim = s.bodySim; // body core has been prefetched by the caller
const Cm::PtrTable* shapeTable = PxPointerOffset<const Cm::PtrTable*>(actor, s.dynamicShapeTableOffset);
void*const* shapes = shapeTable->getPtrs();
Sc::BodyCore* bodyCore = PxPointerOffset<Sc::BodyCore*>(actor, s.dynamicActorOffset);
mBodySimPool->construct(sim, *this, *bodyCore, compound);
s.bodySim = mBodySimPool->allocateAndPrefetch();
if(sim->getLowLevelBody().mCore->mFlags & PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD)
{
if(sim->isArticulationLink())
mSpeculativeCDDArticulationBitMap.growAndSet(sim->getNodeIndex().index());
else
mSpeculativeCCDRigidBodyBitMap.growAndSet(sim->getNodeIndex().index());
}
if(sim->getNodeIndex().isValid())
mSimulationController->addDynamic(&sim->getLowLevelBody(), sim->getNodeIndex());
addShapes(reinterpret_cast<NpShape*const*>(shapes), shapeTable->getCount(), size_t(s.shapeOffset), *sim, s.shapeSim, outBounds);
const SimStateData* simStateData = bodyCore->getSim()->getSimStateData(true);
if(simStateData && simStateData->isKine())
mNbRigidKinematic++;
else
mNbRigidDynamics++;
mDynamicsContext->setStateDirty(true);
}
void Sc::Scene::finishBatchInsertion(BatchInsertionState& state)
{
// a little bit lazy - we could deal with the last one in the batch specially to avoid overallocating by one.
mStaticSimPool->releasePreallocated(static_cast<Sc::StaticSim*>(state.staticSim));
mBodySimPool->releasePreallocated(static_cast<Sc::BodySim*>(state.bodySim));
mShapeSimPool->releasePreallocated(state.shapeSim);
}
// PT: TODO: why is this in Sc?
void Sc::Scene::initContactsIterator(ContactIterator& contactIterator, PxsContactManagerOutputIterator& outputs)
{
outputs = mLLContext->getNphaseImplementationContext()->getContactManagerOutputs();
ElementSimInteraction** first = mInteractions[Sc::InteractionType::eOVERLAP].begin();
contactIterator = ContactIterator(first, first + mActiveInteractionCount[Sc::InteractionType::eOVERLAP], outputs);
}
void Sc::Scene::setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance)
{
struct {
void operator()(PxU32& bits, PxDominanceGroup shift, PxReal weight)
{
if(weight != PxReal(0))
bits |= (PxU32(1) << shift);
else
bits &= ~(PxU32(1) << shift);
}
} bitsetter;
bitsetter(mDominanceBitMatrix[group1], group2, dominance.dominance0);
bitsetter(mDominanceBitMatrix[group2], group1, dominance.dominance1);
mInternalFlags |= SceneInternalFlag::eSCENE_SIP_STATES_DIRTY_DOMINANCE; //force an update on all interactions on matrix change -- very expensive but we have no choice!!
}
PxDominanceGroupPair Sc::Scene::getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const
{
const PxU8 dom0 = PxU8((mDominanceBitMatrix[group1]>>group2) & 0x1 ? 1u : 0u);
const PxU8 dom1 = PxU8((mDominanceBitMatrix[group2]>>group1) & 0x1 ? 1u : 0u);
return PxDominanceGroupPair(dom0, dom1);
}
PxU32 Sc::Scene::getDefaultContactReportStreamBufferSize() const
{
return mNPhaseCore->getDefaultContactReportStreamBufferSize();
}
void Sc::Scene::buildActiveActors()
{
{
PxU32 numActiveBodies = 0;
BodyCore*const* PX_RESTRICT activeBodies;
if (!(getFlags() & PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS))
{
numActiveBodies = getNumActiveBodies();
activeBodies = getActiveBodiesArray();
}
else
{
numActiveBodies = getActiveDynamicBodiesCount();
activeBodies = getActiveDynamicBodies();
}
mActiveActors.clear();
for (PxU32 i = 0; i < numActiveBodies; i++)
{
if (!activeBodies[i]->isFrozen())
{
PxRigidActor* ra = static_cast<PxRigidActor*>(activeBodies[i]->getPxActor());
PX_ASSERT(ra);
mActiveActors.pushBack(ra);
}
}
}
#if PX_SUPPORT_GPU_PHYSX
gpu_buildActiveActors();
#endif
}
// PT: TODO: unify buildActiveActors & buildActiveAndFrozenActors
void Sc::Scene::buildActiveAndFrozenActors()
{
{
PxU32 numActiveBodies = 0;
BodyCore*const* PX_RESTRICT activeBodies;
if (!(getFlags() & PxSceneFlag::eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS))
{
numActiveBodies = getNumActiveBodies();
activeBodies = getActiveBodiesArray();
}
else
{
numActiveBodies = getActiveDynamicBodiesCount();
activeBodies = getActiveDynamicBodies();
}
mActiveActors.clear();
mFrozenActors.clear();
for (PxU32 i = 0; i < numActiveBodies; i++)
{
PxRigidActor* ra = static_cast<PxRigidActor*>(activeBodies[i]->getPxActor());
PX_ASSERT(ra);
if (!activeBodies[i]->isFrozen())
mActiveActors.pushBack(ra);
else
mFrozenActors.pushBack(ra);
}
}
#if PX_SUPPORT_GPU_PHYSX
gpu_buildActiveAndFrozenActors();
#endif
}
PxActor** Sc::Scene::getActiveActors(PxU32& nbActorsOut)
{
nbActorsOut = mActiveActors.size();
if(!nbActorsOut)
return NULL;
return mActiveActors.begin();
}
void Sc::Scene::setActiveActors(PxActor** actors, PxU32 nbActors)
{
mActiveActors.forceSize_Unsafe(0);
mActiveActors.resize(nbActors);
PxMemCopy(mActiveActors.begin(), actors, sizeof(PxActor*) * nbActors);
}
PxActor** Sc::Scene::getFrozenActors(PxU32& nbActorsOut)
{
nbActorsOut = mFrozenActors.size();
if(!nbActorsOut)
return NULL;
return mFrozenActors.begin();
}
void Sc::Scene::reserveTriggerReportBufferSpace(const PxU32 pairCount, PxTriggerPair*& triggerPairBuffer, TriggerPairExtraData*& triggerPairExtraBuffer)
{
const PxU32 oldSize = mTriggerBufferAPI.size();
const PxU32 newSize = oldSize + pairCount;
const PxU32 newCapacity = PxU32(newSize * 1.5f);
mTriggerBufferAPI.reserve(newCapacity);
mTriggerBufferAPI.forceSize_Unsafe(newSize);
triggerPairBuffer = mTriggerBufferAPI.begin() + oldSize;
PX_ASSERT(oldSize == mTriggerBufferExtraData->size());
mTriggerBufferExtraData->reserve(newCapacity);
mTriggerBufferExtraData->forceSize_Unsafe(newSize);
triggerPairExtraBuffer = mTriggerBufferExtraData->begin() + oldSize;
}
template<const bool sleepOrWoke, class T>
static void clearBodies(PxCoalescedHashSet<T*>& bodies)
{
T* const* sleepingOrWokenBodies = bodies.getEntries();
const PxU32 nb = bodies.size();
for(PxU32 i=0; i<nb; i++)
{
ActorSim* body = sleepingOrWokenBodies[i]->getSim();
if(sleepOrWoke)
{
PX_ASSERT(!body->readInternalFlag(ActorSim::BF_WAKEUP_NOTIFY));
body->clearInternalFlag(ActorSim::BF_SLEEP_NOTIFY);
}
else
{
PX_ASSERT(!body->readInternalFlag(ActorSim::BF_SLEEP_NOTIFY));
body->clearInternalFlag(ActorSim::BF_WAKEUP_NOTIFY);
}
// A body can be in both lists depending on the sequence of events
body->clearInternalFlag(ActorSim::BF_IS_IN_SLEEP_LIST);
body->clearInternalFlag(ActorSim::BF_IS_IN_WAKEUP_LIST);
}
bodies.clear();
}
void Sc::Scene::clearSleepWakeBodies()
{
// Clear sleep/woken marker flags
clearBodies<true>(mSleepBodies);
clearBodies<false>(mWokeBodies);
mSleepBodies.clear();
mWokeBodies.clear();
mWokeBodyListValid = true;
mSleepBodyListValid = true;
#if PX_SUPPORT_GPU_PHYSX
gpu_clearSleepWakeBodies();
#endif
}
void Sc::Scene::onBodySleep(BodySim* body)
{
if (!mSimulationEventCallback && !mOnSleepingStateChanged)
return;
if (body->readInternalFlag(ActorSim::BF_WAKEUP_NOTIFY))
{
PX_ASSERT(!body->readInternalFlag(ActorSim::BF_SLEEP_NOTIFY));
// Body is in the list of woken bodies, hence, mark this list as dirty such that it gets cleaned up before
// being sent to the user
body->clearInternalFlag(ActorSim::BF_WAKEUP_NOTIFY);
mWokeBodyListValid = false;
}
body->raiseInternalFlag(ActorSim::BF_SLEEP_NOTIFY);
// Avoid multiple insertion (the user can do multiple transitions between asleep and awake)
if (!body->readInternalFlag(ActorSim::BF_IS_IN_SLEEP_LIST))
{
PX_ASSERT(!mSleepBodies.contains(&body->getBodyCore()));
mSleepBodies.insert(&body->getBodyCore());
body->raiseInternalFlag(ActorSim::BF_IS_IN_SLEEP_LIST);
}
}
void Sc::Scene::onBodyWakeUp(BodySim* body)
{
if(!mSimulationEventCallback && !mOnSleepingStateChanged)
return;
if (body->readInternalFlag(BodySim::BF_SLEEP_NOTIFY))
{
PX_ASSERT(!body->readInternalFlag(BodySim::BF_WAKEUP_NOTIFY));
// Body is in the list of sleeping bodies, hence, mark this list as dirty such it gets cleaned up before
// being sent to the user
body->clearInternalFlag(BodySim::BF_SLEEP_NOTIFY);
mSleepBodyListValid = false;
}
body->raiseInternalFlag(BodySim::BF_WAKEUP_NOTIFY);
// Avoid multiple insertion (the user can do multiple transitions between asleep and awake)
if (!body->readInternalFlag(BodySim::BF_IS_IN_WAKEUP_LIST))
{
PX_ASSERT(!mWokeBodies.contains(&body->getBodyCore()));
mWokeBodies.insert(&body->getBodyCore());
body->raiseInternalFlag(BodySim::BF_IS_IN_WAKEUP_LIST);
}
}
PX_INLINE void Sc::Scene::cleanUpSleepBodies()
{
BodyCore* const* bodyArray = mSleepBodies.getEntries();
PxU32 bodyCount = mSleepBodies.size();
IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim();
while (bodyCount--)
{
ActorSim* actor = bodyArray[bodyCount]->getSim();
BodySim* body = static_cast<BodySim*>(actor);
if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_WAKEUP_NOTIFY)))
{
body->clearInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_IS_IN_WAKEUP_LIST));
mSleepBodies.erase(bodyArray[bodyCount]);
}
else if (islandSim.getNode(body->getNodeIndex()).isActive())
{
//This body is still active in the island simulation, so the request to deactivate the actor by the application must have failed. Recover by undoing this
mSleepBodies.erase(bodyArray[bodyCount]);
actor->internalWakeUp();
}
}
mSleepBodyListValid = true;
}
PX_INLINE void Sc::Scene::cleanUpWokenBodies()
{
cleanUpSleepOrWokenBodies(mWokeBodies, BodySim::BF_SLEEP_NOTIFY, mWokeBodyListValid);
}
PX_INLINE void Sc::Scene::cleanUpSleepOrWokenBodies(PxCoalescedHashSet<BodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker)
{
// With our current logic it can happen that a body is added to the sleep as well as the woken body list in the
// same frame.
//
// Examples:
// - Kinematic is created (added to woken list) but has not target (-> deactivation -> added to sleep list)
// - Dynamic is created (added to woken list) but is forced to sleep by user (-> deactivation -> added to sleep list)
//
// This code traverses the sleep/woken body list and removes bodies which have been initially added to the given
// list but do not belong to it anymore.
BodyCore* const* bodyArray = bodyList.getEntries();
PxU32 bodyCount = bodyList.size();
while (bodyCount--)
{
BodySim* body = bodyArray[bodyCount]->getSim();
if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(removeFlag)))
bodyList.erase(bodyArray[bodyCount]);
}
validMarker = true;
}
FeatherstoneArticulation* Sc::Scene::createLLArticulation(Sc::ArticulationSim* sim)
{
return mLLArticulationRCPool->construct(sim);
}
void Sc::Scene::destroyLLArticulation(FeatherstoneArticulation& articulation)
{
mLLArticulationRCPool->destroy(static_cast<Dy::FeatherstoneArticulation*>(&articulation));
}
PxU32 Sc::Scene::createAggregate(void* userData, PxU32 maxNumShapes, PxAggregateFilterHint filterHint)
{
const physx::Bp::BoundsIndex index = getElementIDPool().createID();
mBoundsArray->initEntry(index);
mLLContext->getNphaseImplementationContext()->registerAggregate(index);
#ifdef BP_USE_AGGREGATE_GROUP_TAIL
return mAABBManager->createAggregate(index, Bp::FilterGroup::eINVALID, userData, maxNumShapes, filterHint);
#else
// PT: TODO: ideally a static compound would have a static group
const PxU32 rigidId = getRigidIDTracker().createID();
const Bp::FilterGroup::Enum bpGroup = Bp::FilterGroup::Enum(rigidId + Bp::FilterGroup::eDYNAMICS_BASE);
return mAABBManager->createAggregate(index, bpGroup, userData, selfCollisions);
#endif
}
void Sc::Scene::deleteAggregate(PxU32 id)
{
Bp::BoundsIndex index;
Bp::FilterGroup::Enum bpGroup;
#ifdef BP_USE_AGGREGATE_GROUP_TAIL
if(mAABBManager->destroyAggregate(index, bpGroup, id))
{
getElementIDPool().releaseID(index);
}
#else
if(mAABBManager->destroyAggregate(index, bpGroup, id))
{
getElementIDPool().releaseID(index);
// PT: this is clumsy....
const PxU32 rigidId = PxU32(bpGroup) - Bp::FilterGroup::eDYNAMICS_BASE;
getRigidIDTracker().releaseID(rigidId);
}
#endif
}
void Sc::Scene::shiftOrigin(const PxVec3& shift)
{
// adjust low level context
mLLContext->shiftOrigin(shift);
// adjust bounds array
mBoundsArray->shiftOrigin(shift);
// adjust broadphase
mAABBManager->shiftOrigin(shift);
// adjust constraints
ConstraintCore*const * constraints = mConstraints.getEntries();
for(PxU32 i=0, size = mConstraints.size(); i < size; i++)
constraints[i]->getPxConnector()->onOriginShift(shift);
}
///////////////////////////////////////////////////////////////////////////////
// PT: onActivate() functions should be called when an interaction is activated or created, and return true if activation
// should proceed else return false (for example: joint interaction between two kinematics should not get activated)
bool Sc::activateInteraction(Sc::Interaction* interaction, void* data)
{
switch(interaction->getType())
{
case InteractionType::eOVERLAP:
return static_cast<Sc::ShapeInteraction*>(interaction)->onActivate(data);
case InteractionType::eTRIGGER:
return static_cast<Sc::TriggerInteraction*>(interaction)->onActivate(data);
case InteractionType::eMARKER:
// PT: ElementInteractionMarker::onActivate() always returns false (always inactive).
return false;
case InteractionType::eCONSTRAINTSHADER:
return static_cast<Sc::ConstraintInteraction*>(interaction)->onActivate(data);
case InteractionType::eARTICULATION:
return static_cast<Sc::ArticulationJointSim*>(interaction)->onActivate(data);
case InteractionType::eTRACKED_IN_SCENE_COUNT:
case InteractionType::eINVALID:
PX_ASSERT(0);
break;
}
return false;
}
// PT: onDeactivate() functions should be called when an interaction is deactivated, and return true if deactivation should proceed
// else return false (for example: joint interaction between two kinematics can ignore deactivation because it always is deactivated)
/*static*/ bool deactivateInteraction(Sc::Interaction* interaction, const Sc::InteractionType::Enum type)
{
switch(type)
{
case InteractionType::eOVERLAP:
return static_cast<Sc::ShapeInteraction*>(interaction)->onDeactivate();
case InteractionType::eTRIGGER:
return static_cast<Sc::TriggerInteraction*>(interaction)->onDeactivate();
case InteractionType::eMARKER:
// PT: ElementInteractionMarker::onDeactivate() always returns true.
return true;
case InteractionType::eCONSTRAINTSHADER:
return static_cast<Sc::ConstraintInteraction*>(interaction)->onDeactivate();
case InteractionType::eARTICULATION:
return static_cast<Sc::ArticulationJointSim*>(interaction)->onDeactivate();
case InteractionType::eTRACKED_IN_SCENE_COUNT:
case InteractionType::eINVALID:
PX_ASSERT(0);
break;
}
return false;
}
void Sc::activateInteractions(Sc::ActorSim& actorSim)
{
const PxU32 nbInteractions = actorSim.getActorInteractionCount();
if(!nbInteractions)
return;
Interaction** interactions = actorSim.getActorInteractions();
Scene& scene = actorSim.getScene();
for(PxU32 i=0; i<nbInteractions; ++i)
{
PxPrefetchLine(interactions[PxMin(i+1,nbInteractions-1)]);
Interaction* interaction = interactions[i];
if(!interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE))
{
const InteractionType::Enum type = interaction->getType();
const bool isNotIGControlled = type != InteractionType::eOVERLAP && type != InteractionType::eMARKER;
if(isNotIGControlled)
{
const bool proceed = activateInteraction(interaction, NULL);
if(proceed && (type < InteractionType::eTRACKED_IN_SCENE_COUNT))
scene.notifyInteractionActivated(interaction); // PT: we can reach this line for trigger interactions
}
}
}
}
void Sc::deactivateInteractions(Sc::ActorSim& actorSim)
{
const PxU32 nbInteractions = actorSim.getActorInteractionCount();
if(!nbInteractions)
return;
Interaction** interactions = actorSim.getActorInteractions();
Scene& scene = actorSim.getScene();
for(PxU32 i=0; i<nbInteractions; ++i)
{
PxPrefetchLine(interactions[PxMin(i+1,nbInteractions-1)]);
Interaction* interaction = interactions[i];
if(interaction->readInteractionFlag(InteractionFlag::eIS_ACTIVE))
{
const InteractionType::Enum type = interaction->getType();
const bool isNotIGControlled = type != InteractionType::eOVERLAP && type != InteractionType::eMARKER;
if(isNotIGControlled)
{
const bool proceed = deactivateInteraction(interaction, type);
if(proceed && (type < InteractionType::eTRACKED_IN_SCENE_COUNT))
scene.notifyInteractionDeactivated(interaction); // PT: we can reach this line for trigger interactions
}
}
}
}
Sc::ConstraintCore* Sc::Scene::findConstraintCore(const Sc::ActorSim* sim0, const Sc::ActorSim* sim1)
{
const PxNodeIndex ind0 = sim0->getNodeIndex();
const PxNodeIndex ind1 = sim1->getNodeIndex();
if(ind1 < ind0)
PxSwap(sim0, sim1);
const PxHashMap<PxPair<const Sc::ActorSim*, const Sc::ActorSim*>, Sc::ConstraintCore*>::Entry* entry = mConstraintMap.find(PxPair<const Sc::ActorSim*, const Sc::ActorSim*>(sim0, sim1));
return entry ? entry->second : NULL;
}
void Sc::Scene::updateBodySim(Sc::BodySim& bodySim)
{
Dy::FeatherstoneArticulation* arti = NULL;
Sc::ArticulationSim* artiSim = bodySim.getArticulation();
if (artiSim)
arti = artiSim->getLowLevelArticulation();
mSimulationController->updateDynamic(arti, bodySim.getNodeIndex());
}
// PT: start moving PX_SUPPORT_GPU_PHYSX bits to the end of the file. Ideally/eventually they would move to a separate class or file,
// to clearly decouple the CPU and GPU parts of the scene/pipeline.
#if PX_SUPPORT_GPU_PHYSX
void Sc::Scene::gpu_releasePools()
{
PX_DELETE(mLLSoftBodyPool);
PX_DELETE(mLLFEMClothPool);
PX_DELETE(mLLParticleSystemPool);
PX_DELETE(mLLHairSystemPool);
}
void Sc::Scene::gpu_release()
{
PX_DELETE(mHeapMemoryAllocationManager);
}
template<class T>
static void addToActiveArray(PxArray<T*>& activeArray, ActorSim& actorSim, ActorCore* core)
{
const PxU32 activeListIndex = activeArray.size();
actorSim.setActiveListIndex(activeListIndex);
activeArray.pushBack(static_cast<T*>(core));
}
void Sc::Scene::gpu_addToActiveList(ActorSim& actorSim, ActorCore* appendedActorCore)
{
if (actorSim.isSoftBody())
addToActiveArray(mActiveSoftBodies, actorSim, appendedActorCore);
else if (actorSim.isFEMCloth())
addToActiveArray(mActiveFEMCloths, actorSim, appendedActorCore);
else if (actorSim.isParticleSystem())
addToActiveArray(mActiveParticleSystems, actorSim, appendedActorCore);
else if (actorSim.isHairSystem())
addToActiveArray(mActiveHairSystems, actorSim, appendedActorCore);
}
template<class T>
static void removeFromActiveArray(PxArray<T*>& activeArray, PxU32 removedActiveIndex)
{
const PxU32 newSize = activeArray.size() - 1;
if(removedActiveIndex != newSize)
{
T* lastBody = activeArray[newSize];
activeArray[removedActiveIndex] = lastBody;
lastBody->getSim()->setActiveListIndex(removedActiveIndex);
}
activeArray.forceSize_Unsafe(newSize);
}
void Sc::Scene::gpu_removeFromActiveList(ActorSim& actorSim, PxU32 removedActiveIndex)
{
if(actorSim.isSoftBody())
removeFromActiveArray(mActiveSoftBodies, removedActiveIndex);
else if(actorSim.isFEMCloth())
removeFromActiveArray(mActiveFEMCloths, removedActiveIndex);
else if(actorSim.isParticleSystem())
removeFromActiveArray(mActiveParticleSystems, removedActiveIndex);
else if(actorSim.isHairSystem())
removeFromActiveArray(mActiveHairSystems, removedActiveIndex);
}
void Sc::Scene::gpu_clearSleepWakeBodies()
{
clearBodies<true>(mSleepSoftBodies);
clearBodies<true>(mSleepHairSystems);
clearBodies<false>(mWokeSoftBodies);
clearBodies<false>(mWokeHairSystems);
mWokeSoftBodyListValid = true;
mSleepSoftBodyListValid = true;
mWokeHairSystemListValid = true;
mSleepHairSystemListValid = true;
}
void Sc::Scene::gpu_buildActiveActors()
{
{
PxU32 numActiveSoftBodies = getNumActiveSoftBodies();
SoftBodyCore*const* PX_RESTRICT activeSoftBodies = getActiveSoftBodiesArray();
mActiveSoftBodyActors.clear();
for (PxU32 i = 0; i < numActiveSoftBodies; i++)
{
PxActor* ra = activeSoftBodies[i]->getPxActor();
mActiveSoftBodyActors.pushBack(ra);
}
}
{
PxU32 numActiveHairSystems = getNumActiveHairSystems();
HairSystemCore*const* PX_RESTRICT activeHairSystems = getActiveHairSystemsArray();
mActiveHairSystemActors.clear();
for (PxU32 i = 0; i < numActiveHairSystems; i++)
{
PxActor* ra = activeHairSystems[i]->getPxActor();
mActiveHairSystemActors.pushBack(ra);
}
}
}
void Sc::Scene::gpu_buildActiveAndFrozenActors()
{
{
PxU32 numActiveSoftBodies = getNumActiveSoftBodies();
SoftBodyCore*const* PX_RESTRICT activeSoftBodies = getActiveSoftBodiesArray();
mActiveSoftBodyActors.clear();
for (PxU32 i = 0; i < numActiveSoftBodies; i++)
{
PxActor* ra = activeSoftBodies[i]->getPxActor();
mActiveSoftBodyActors.pushBack(ra);
}
}
{
PxU32 numActiveHairSystems = getNumActiveHairSystems();
HairSystemCore*const* PX_RESTRICT activeHairSystems = getActiveHairSystemsArray();
mActiveHairSystemActors.clear();
for (PxU32 i = 0; i < numActiveHairSystems; i++)
{
PxActor* ra = activeHairSystems[i]->getPxActor();
mActiveHairSystemActors.pushBack(ra);
}
}
}
void Sc::Scene::gpu_setSimulationEventCallback(PxSimulationEventCallback* /*callback*/)
{
SoftBodyCore* const* sleepingSoftBodies = mSleepSoftBodies.getEntries();
for (PxU32 i = 0; i < mSleepSoftBodies.size(); i++)
{
sleepingSoftBodies[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY);
}
//FEMClothCore* const* sleepingFEMCloths = mSleepFEMCloths.getEntries();
//for (PxU32 i = 0; i < mSleepFEMCloths.size(); i++)
//{
// sleepingFEMCloths[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY);
//}
HairSystemCore* const* sleepingHairSystems = mSleepHairSystems.getEntries();
for (PxU32 i = 0; i < mSleepHairSystems.size(); i++)
{
sleepingHairSystems[i]->getSim()->raiseInternalFlag(BodySim::BF_SLEEP_NOTIFY);
}
}
PxU32 Sc::Scene::gpu_cleanUpSleepAndWokenBodies()
{
if (!mSleepSoftBodyListValid)
cleanUpSleepSoftBodies();
if (!mWokeBodyListValid)
cleanUpWokenSoftBodies();
if (!mSleepHairSystemListValid)
cleanUpSleepHairSystems();
if (!mWokeHairSystemListValid) // TODO(jcarius) should this be mWokeBodyListValid?
cleanUpWokenHairSystems();
const PxU32 nbHairSystemSleep = mSleepHairSystems.size();
const PxU32 nbHairSystemWoken = mWokeHairSystems.size();
const PxU32 nbSoftBodySleep = mSleepSoftBodies.size();
const PxU32 nbSoftBodyWoken = mWokeSoftBodies.size();
return PxMax(PxMax(nbSoftBodyWoken, nbHairSystemWoken), PxMax(nbSoftBodySleep, nbHairSystemSleep));
}
void Sc::Scene::gpu_fireOnSleepCallback(PxActor** actors)
{
//ML: need to create and API for the onSleep for softbody
const PxU32 nbSoftBodySleep = mSleepSoftBodies.size();
if (nbSoftBodySleep)
{
PxU32 destSlot = 0;
SoftBodyCore* const* sleepingSoftBodies = mSleepSoftBodies.getEntries();
for (PxU32 i = 0; i<nbSoftBodySleep; i++)
{
SoftBodyCore* body = sleepingSoftBodies[i];
if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES)
actors[destSlot++] = body->getPxActor();
if (mOnSleepingStateChanged)
mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), true);
}
if (destSlot && mSimulationEventCallback)
mSimulationEventCallback->onSleep(actors, destSlot);
}
const PxU32 nbHairSystemSleep = mSleepHairSystems.size();
if (nbHairSystemSleep)
{
PxU32 destSlot = 0;
HairSystemCore* const* sleepingHairSystems = mSleepHairSystems.getEntries();
for (PxU32 i = 0; i<nbHairSystemSleep; i++)
{
HairSystemCore* body = sleepingHairSystems[i];
if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES)
actors[destSlot++] = body->getPxActor();
if (mOnSleepingStateChanged)
mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), true);
}
if (destSlot && mSimulationEventCallback)
mSimulationEventCallback->onSleep(actors, destSlot);
}
}
void Sc::Scene::gpu_fireOnWakeCallback(PxActor** actors)
{
//ML: need to create an API for woken soft body
const PxU32 nbSoftBodyWoken = mWokeSoftBodies.size();
if (nbSoftBodyWoken)
{
PxU32 destSlot = 0;
SoftBodyCore* const* wokenSoftBodies = mWokeSoftBodies.getEntries();
for (PxU32 i = 0; i<nbSoftBodyWoken; i++)
{
SoftBodyCore* body = wokenSoftBodies[i];
if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES)
actors[destSlot++] = body->getPxActor();
if (mOnSleepingStateChanged)
mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), false);
}
if (destSlot && mSimulationEventCallback)
mSimulationEventCallback->onWake(actors, destSlot);
}
const PxU32 nbHairSystemWoken = mWokeHairSystems.size();
if (nbHairSystemWoken)
{
PxU32 destSlot = 0;
HairSystemCore* const* wokenHairSystems = mWokeHairSystems.getEntries();
for (PxU32 i = 0; i<nbHairSystemWoken; i++)
{
HairSystemCore* body = wokenHairSystems[i];
if (body->getActorFlags() & PxActorFlag::eSEND_SLEEP_NOTIFIES)
actors[destSlot++] = body->getPxActor();
if (mOnSleepingStateChanged)
mOnSleepingStateChanged(*static_cast<physx::PxRigidDynamic*>(body->getPxActor()), false);
}
if (destSlot && mSimulationEventCallback)
mSimulationEventCallback->onWake(actors, destSlot);
}
}
void Sc::Scene::gpu_updateBounds()
{
//update soft bodies world bound
Sc::SoftBodyCore* const* softBodies = mSoftBodies.getEntries();
PxU32 size = mSoftBodies.size();
if (mUseGpuBp)
{
for (PxU32 i = 0; i < size; ++i)
softBodies[i]->getSim()->updateBoundsInAABBMgr();
}
else
{
for (PxU32 i = 0; i < size; ++i)
softBodies[i]->getSim()->updateBounds();
}
// update FEM-cloth world bound
Sc::FEMClothCore* const* femCloths = mFEMCloths.getEntries();
size = mFEMCloths.size();
if (mUseGpuBp)
{
for (PxU32 i = 0; i < size; ++i)
femCloths[i]->getSim()->updateBoundsInAABBMgr();
}
else
{
for (PxU32 i = 0; i < size; ++i)
femCloths[i]->getSim()->updateBounds();
}
//upate the actor handle of particle system in AABB manager
Sc::ParticleSystemCore* const* particleSystems = mParticleSystems.getEntries();
size = mParticleSystems.size();
if (mUseGpuBp)
{
for (PxU32 i = 0; i < size; ++i)
particleSystems[i]->getSim()->updateBoundsInAABBMgr();
}
else
{
for (PxU32 i = 0; i < size; ++i)
particleSystems[i]->getSim()->updateBounds();
}
//update hair system world bound
Sc::HairSystemCore* const* hairSystems = mHairSystems.getEntries();
PxU32 nHairSystems = mHairSystems.size();
if (mUseGpuBp)
{
for (PxU32 i = 0; i < nHairSystems; ++i)
hairSystems[i]->getSim()->updateBoundsInAABBMgr();
}
else
{
for (PxU32 i = 0; i < nHairSystems; ++i)
hairSystems[i]->getSim()->updateBounds();
}
}
void Sc::Scene::addSoftBody(SoftBodyCore& softBody)
{
SoftBodySim* sim = PX_NEW(SoftBodySim)(softBody, *this);
if (sim && (sim->getLowLevelSoftBody() == NULL))
{
PX_DELETE(sim);
return;
}
mSoftBodies.insert(&softBody);
mStats->gpuMemSizeSoftBodies += softBody.getGpuMemStat();
}
void Sc::Scene::removeSoftBody(SoftBodyCore& softBody)
{
SoftBodySim* a = softBody.getSim();
PX_DELETE(a);
mSoftBodies.erase(&softBody);
mStats->gpuMemSizeSoftBodies -= softBody.getGpuMemStat();
}
void Sc::Scene::addFEMCloth(FEMClothCore& femCloth)
{
FEMClothSim* sim = PX_NEW(FEMClothSim)(femCloth, *this);
if (sim && (sim->getLowLevelFEMCloth() == NULL))
{
PX_DELETE(sim);
return;
}
mFEMCloths.insert(&femCloth);
mStats->gpuMemSizeFEMCloths += femCloth.getGpuMemStat();
}
void Sc::Scene::removeFEMCloth(FEMClothCore& femCloth)
{
FEMClothSim* a = femCloth.getSim();
PX_DELETE(a);
mFEMCloths.erase(&femCloth);
mStats->gpuMemSizeFEMCloths -= femCloth.getGpuMemStat();
}
void Sc::Scene::addParticleSystem(ParticleSystemCore& particleSystem)
{
ParticleSystemSim* sim = PX_NEW(ParticleSystemSim)(particleSystem, *this);
Dy::ParticleSystem* dyParticleSystem = sim->getLowLevelParticleSystem();
if (sim && (dyParticleSystem == NULL))
{
PX_DELETE(sim);
return;
}
mParticleSystems.insert(&particleSystem);
mStats->gpuMemSizeParticles += particleSystem.getShapeCore().getGpuMemStat();
}
void Sc::Scene::removeParticleSystem(ParticleSystemCore& particleSystem)
{
ParticleSystemSim* a = particleSystem.getSim();
PX_DELETE(a);
mParticleSystems.erase(&particleSystem);
mStats->gpuMemSizeParticles -= particleSystem.getShapeCore().getGpuMemStat();
}
void Sc::Scene::addHairSystem(HairSystemCore& hairSystem)
{
HairSystemSim* sim = PX_NEW(HairSystemSim)(hairSystem, *this);
if (sim && (sim->getLowLevelHairSystem() == NULL))
{
PX_DELETE(sim);
return;
}
mHairSystems.insert(&hairSystem);
mStats->gpuMemSizeHairSystems += hairSystem.getShapeCore().getGpuMemStat();
}
void Sc::Scene::removeHairSystem(HairSystemCore& hairSystem)
{
HairSystemSim* sim = hairSystem.getSim();
PX_DELETE(sim);
mHairSystems.erase(&hairSystem);
mStats->gpuMemSizeHairSystems -= hairSystem.getShapeCore().getGpuMemStat();
}
Dy::SoftBody* Sc::Scene::createLLSoftBody(Sc::SoftBodySim* sim)
{
return mLLSoftBodyPool->construct(sim, sim->getCore().getCore());
}
void Sc::Scene::destroyLLSoftBody(Dy::SoftBody& softBody)
{
mLLSoftBodyPool->destroy(&softBody);
}
Dy::FEMCloth* Sc::Scene::createLLFEMCloth(Sc::FEMClothSim* sim)
{
return mLLFEMClothPool->construct(sim, sim->getCore().getCore());
}
void Sc::Scene::destroyLLFEMCloth(Dy::FEMCloth& femCloth)
{
mLLFEMClothPool->destroy(&femCloth);
}
Dy::ParticleSystem* Sc::Scene::createLLParticleSystem(Sc::ParticleSystemSim* sim)
{
return mLLParticleSystemPool->construct(sim->getCore().getShapeCore().getLLCore());
}
void Sc::Scene::destroyLLParticleSystem(Dy::ParticleSystem& particleSystem)
{
return mLLParticleSystemPool->destroy(&particleSystem);
}
Dy::HairSystem* Sc::Scene::createLLHairSystem(Sc::HairSystemSim* sim)
{
return mLLHairSystemPool->construct(sim, sim->getCore().getShapeCore().getLLCore());
}
void Sc::Scene::destroyLLHairSystem(Dy::HairSystem& hairSystem)
{
mLLHairSystemPool->destroy(&hairSystem);
}
void Sc::Scene::cleanUpSleepHairSystems()
{
HairSystemCore* const* hairSystemArray = mSleepHairSystems.getEntries();
PxU32 bodyCount = mSleepBodies.size();
IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim();
while (bodyCount--)
{
HairSystemSim* hairSystem = hairSystemArray[bodyCount]->getSim();
if (hairSystem->readInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_WAKEUP_NOTIFY)))
{
hairSystem->clearInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_IS_IN_WAKEUP_LIST));
mSleepHairSystems.erase(hairSystemArray[bodyCount]);
}
else if (islandSim.getNode(hairSystem->getNodeIndex()).isActive())
{
//This hairSystem is still active in the island simulation, so the request to deactivate the actor by the application must have failed. Recover by undoing this
mSleepHairSystems.erase(hairSystemArray[bodyCount]);
hairSystem->internalWakeUp();
}
}
mSleepBodyListValid = true;
}
void Sc::Scene::cleanUpWokenHairSystems()
{
cleanUpSleepOrWokenHairSystems(mWokeHairSystems, BodySim::BF_SLEEP_NOTIFY, mWokeHairSystemListValid);
}
void Sc::Scene::cleanUpSleepOrWokenHairSystems(PxCoalescedHashSet<HairSystemCore*>& bodyList, PxU32 removeFlag, bool& validMarker)
{
HairSystemCore* const* hairSystemArray = bodyList.getEntries();
PxU32 bodyCount = bodyList.size();
while (bodyCount--)
{
HairSystemSim* hairSystem = hairSystemArray[bodyCount]->getSim();
if (hairSystem->readInternalFlag(static_cast<BodySim::InternalFlags>(removeFlag)))
bodyList.erase(hairSystemArray[bodyCount]);
}
validMarker = true;
}
PX_INLINE void Sc::Scene::cleanUpSleepSoftBodies()
{
SoftBodyCore* const* bodyArray = mSleepSoftBodies.getEntries();
PxU32 bodyCount = mSleepBodies.size();
IG::IslandSim& islandSim = mSimpleIslandManager->getAccurateIslandSim();
while (bodyCount--)
{
SoftBodySim* body = bodyArray[bodyCount]->getSim();
if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_WAKEUP_NOTIFY)))
{
body->clearInternalFlag(static_cast<BodySim::InternalFlags>(ActorSim::BF_IS_IN_WAKEUP_LIST));
mSleepSoftBodies.erase(bodyArray[bodyCount]);
}
else if (islandSim.getNode(body->getNodeIndex()).isActive())
{
//This body is still active in the island simulation, so the request to deactivate the actor by the application must have failed. Recover by undoing this
mSleepSoftBodies.erase(bodyArray[bodyCount]);
body->internalWakeUp();
}
}
mSleepBodyListValid = true;
}
PX_INLINE void Sc::Scene::cleanUpWokenSoftBodies()
{
cleanUpSleepOrWokenSoftBodies(mWokeSoftBodies, BodySim::BF_SLEEP_NOTIFY, mWokeSoftBodyListValid);
}
PX_INLINE void Sc::Scene::cleanUpSleepOrWokenSoftBodies(PxCoalescedHashSet<SoftBodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker)
{
// With our current logic it can happen that a body is added to the sleep as well as the woken body list in the
// same frame.
//
// Examples:
// - Kinematic is created (added to woken list) but has not target (-> deactivation -> added to sleep list)
// - Dynamic is created (added to woken list) but is forced to sleep by user (-> deactivation -> added to sleep list)
//
// This code traverses the sleep/woken body list and removes bodies which have been initially added to the given
// list but do not belong to it anymore.
SoftBodyCore* const* bodyArray = bodyList.getEntries();
PxU32 bodyCount = bodyList.size();
while (bodyCount--)
{
SoftBodySim* body = bodyArray[bodyCount]->getSim();
if (body->readInternalFlag(static_cast<BodySim::InternalFlags>(removeFlag)))
bodyList.erase(bodyArray[bodyCount]);
}
validMarker = true;
}
void Sc::Scene::addSoftBodySimControl(Sc::SoftBodyCore& core)
{
Sc::SoftBodySim* sim = core.getSim();
if (sim)
{
mSimulationController->addSoftBody(sim->getLowLevelSoftBody(), sim->getNodeIndex());
mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), sim->getPxActor());
}
}
void Sc::Scene::removeSoftBodySimControl(Sc::SoftBodyCore& core)
{
Sc::SoftBodySim* sim = core.getSim();
if (sim)
{
mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID());
mSimulationController->releaseSoftBody(sim->getLowLevelSoftBody());
}
}
void Sc::Scene::addFEMClothSimControl(Sc::FEMClothCore& core)
{
Sc::FEMClothSim* sim = core.getSim();
if (sim)
{
mSimulationController->addFEMCloth(sim->getLowLevelFEMCloth(), sim->getNodeIndex());
mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), sim->getPxActor(), true);
}
}
void Sc::Scene::removeFEMClothSimControl(Sc::FEMClothCore& core)
{
Sc::FEMClothSim* sim = core.getSim();
if (sim)
{
mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), true);
mSimulationController->releaseFEMCloth(sim->getLowLevelFEMCloth());
}
}
void Sc::Scene::addParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId)
{
mSimulationController->addParticleFilter(sim.getLowLevelSoftBody(), core->getSim()->getLowLevelParticleSystem(),
particleId, userBufferId, tetId);
}
void Sc::Scene::removeParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId)
{
mSimulationController->removeParticleFilter(sim.getLowLevelSoftBody(), core->getSim()->getLowLevelParticleSystem(), particleId, userBufferId, tetId);
}
PxU32 Sc::Scene::addParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric)
{
PxNodeIndex nodeIndex = core->getSim()->getNodeIndex();
PxU32 handle = mSimulationController->addParticleAttachment(sim.getLowLevelSoftBody(), core->getSim()->getLowLevelParticleSystem(),
particleId, userBufferId, tetId, barycentric, sim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eSOFT_BODY_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 handle)
{
PxNodeIndex nodeIndex = core->getSim()->getNodeIndex();
mSimulationController->removeParticleAttachment(sim.getLowLevelSoftBody(), handle);
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addAttachment(const Sc::SoftBodySim& sbSim, const Sc::HairSystemSim& hairSim)
{
const PxPair<PxU32, PxU32> pair(sbSim.getNodeIndex().index(), hairSim.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sbSim.getNodeIndex(), hairSim.getNodeIndex(), NULL, IG::Edge::eHAIR_SYSTEM_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eHAIR_SYSTEM_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
}
void Sc::Scene::removeAttachment(const Sc::SoftBodySim& sbSim, const Sc::HairSystemSim& hairSim)
{
const PxPair<PxU32, PxU32> pair(sbSim.getNodeIndex().index(), hairSim.getNodeIndex().index());
if(mParticleOrSoftBodyRigidInteractionMap.find(pair)) // find returns pointer to const so we cannot use it directly
{
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
PX_ASSERT(interaction.mCount > 0);
interaction.mCount--;
if(interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
}
void Sc::Scene::addRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 vertId)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->addRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, vertId);
}
void Sc::Scene::removeRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 vertId)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, vertId);
}
PxU32 Sc::Scene::addRigidAttachment(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 vertId, const PxVec3& actorSpacePose,
PxConeLimitedConstraint* constraint)
{
PxNodeIndex nodeIndex;
PxsRigidBody* body = NULL;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
body = &core->getSim()->getLowLevelBody();
}
PxU32 handle = mSimulationController->addRigidAttachment(sim.getLowLevelSoftBody(), sim.getNodeIndex(), body,
nodeIndex, vertId, actorSpacePose, constraint, sim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eSOFT_BODY_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeRigidAttachment(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 handle)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeRigidAttachment(sim.getLowLevelSoftBody(), handle);
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addTetRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 tetIdx)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->addTetRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, tetIdx);
}
void Sc::Scene::removeTetRigidFilter(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 tetIdx)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeTetRigidFilter(sim.getLowLevelSoftBody(), nodeIndex, tetIdx);
}
PxU32 Sc::Scene::addTetRigidAttachment(Sc::BodyCore* core, Sc::SoftBodySim& sim, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose,
PxConeLimitedConstraint* constraint)
{
PxNodeIndex nodeIndex;
PxsRigidBody* body = NULL;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
body = &core->getSim()->getLowLevelBody();
}
PxU32 handle = mSimulationController->addTetRigidAttachment(sim.getLowLevelSoftBody(), body, nodeIndex,
tetIdx, barycentric, actorSpacePose, constraint, sim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eSOFT_BODY_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::addSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1)
{
Sc::SoftBodySim& bSim = *core.getSim();
mSimulationController->addSoftBodyFilter(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIdx0, tetIdx1);
}
void Sc::Scene::removeSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1)
{
Sc::SoftBodySim& bSim = *core.getSim();
mSimulationController->removeSoftBodyFilter(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIdx0, tetIdx1);
}
void Sc::Scene::addSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize)
{
Sc::SoftBodySim& bSim = *core.getSim();
mSimulationController->addSoftBodyFilters(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIndices0, tetIndices1, tetIndicesSize);
}
void Sc::Scene::removeSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize)
{
Sc::SoftBodySim& bSim = *core.getSim();
mSimulationController->removeSoftBodyFilters(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIndices0, tetIndices1, tetIndicesSize);
}
PxU32 Sc::Scene::addSoftBodyAttachment(SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& tetBarycentric0, Sc::SoftBodySim& sim, PxU32 tetIdx1, const PxVec4& tetBarycentric1,
PxConeLimitedConstraint* constraint, PxReal constraintOffset)
{
Sc::SoftBodySim& bSim = *core.getSim();
PxU32 handle = mSimulationController->addSoftBodyAttachment(bSim.getLowLevelSoftBody(), sim.getLowLevelSoftBody(), tetIdx0, tetIdx1,
tetBarycentric0, tetBarycentric1, constraint, constraintOffset, sim.isActive() || bSim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), bSim.getNodeIndex(), NULL, IG::Edge::eSOFT_BODY_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eSOFT_BODY_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeSoftBodyAttachment(SoftBodyCore& core, Sc::SoftBodySim& sim, PxU32 handle)
{
Sc::SoftBodySim& bSim = *core.getSim();
mSimulationController->removeSoftBodyAttachment(bSim.getLowLevelSoftBody(), handle);
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx)
{
Sc::FEMClothSim& bSim = *core.getSim();
mSimulationController->addClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), triIdx,tetIdx);
}
void Sc::Scene::removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx)
{
Sc::FEMClothSim& bSim = *core.getSim();
mSimulationController->removeClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), triIdx, tetIdx);
}
void Sc::Scene::addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx)
{
Sc::FEMClothSim& bSim = *core.getSim();
mSimulationController->addVertClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), vertIdx, tetIdx);
}
void Sc::Scene::removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx)
{
Sc::FEMClothSim& bSim = *core.getSim();
mSimulationController->removeVertClothFilter(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), vertIdx, tetIdx);
}
PxU32 Sc::Scene::addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, Sc::SoftBodySim& sim, PxU32 tetIdx,
const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset)
{
Sc::FEMClothSim& bSim = *core.getSim();
PxU32 handle = mSimulationController->addClothAttachment(sim.getLowLevelSoftBody(), bSim.getLowLevelFEMCloth(), triIdx, triBarycentric,
tetIdx, tetBarycentric, constraint, constraintOffset, sim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), bSim.getNodeIndex(), NULL, IG::Edge::eFEM_CLOTH_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeClothAttachment(Sc::FEMClothCore& core, Sc::SoftBodySim& sim, PxU32 handle)
{
PX_UNUSED(core);
Sc::FEMClothSim& bSim = *core.getSim();
mSimulationController->removeClothAttachment(sim.getLowLevelSoftBody(), handle);
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), bSim.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 vertId)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->addRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, vertId);
}
void Sc::Scene::removeRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 vertId)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, vertId);
}
PxU32 Sc::Scene::addRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint)
{
PxNodeIndex nodeIndex;
PxsRigidBody* body = NULL;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
body = &core->getSim()->getLowLevelBody();
}
PxU32 handle = mSimulationController->addRigidAttachment(sim.getLowLevelFEMCloth(), sim.getNodeIndex(), body, nodeIndex,
vertId, actorSpacePose, constraint, sim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eFEM_CLOTH_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 handle)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeRigidAttachment(sim.getLowLevelFEMCloth(), handle);
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addTriRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 triIdx)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->addTriRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, triIdx);
}
void Sc::Scene::removeTriRigidFilter(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 triIdx)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeTriRigidFilter(sim.getLowLevelFEMCloth(), nodeIndex, triIdx);
}
PxU32 Sc::Scene::addTriRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint)
{
PxNodeIndex nodeIndex;
PxsRigidBody* body = NULL;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
body = &core->getSim()->getLowLevelBody();
}
PxU32 handle = mSimulationController->addTriRigidAttachment(sim.getLowLevelFEMCloth(), body, nodeIndex,
triIdx, barycentric, actorSpacePose, constraint, sim.isActive());
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eFEM_CLOTH_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeTriRigidAttachment(Sc::BodyCore* core, Sc::FEMClothSim& sim, PxU32 handle)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
mSimulationController->removeTriRigidAttachment(sim.getLowLevelFEMCloth(), handle);
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addClothFilter(FEMClothCore& core0, PxU32 triIdx0, Sc::FEMClothSim& sim1, PxU32 triIdx1)
{
Sc::FEMClothSim& sim0 = *core0.getSim();
mSimulationController->addClothFilter(sim0.getLowLevelFEMCloth(), sim1.getLowLevelFEMCloth(), triIdx0, triIdx1);
}
void Sc::Scene::removeClothFilter(FEMClothCore& core, PxU32 triIdx0, FEMClothSim& sim1, PxU32 triIdx1)
{
Sc::FEMClothSim& sim0 = *core.getSim();
mSimulationController->removeClothFilter(sim0.getLowLevelFEMCloth(), sim1.getLowLevelFEMCloth(), triIdx0, triIdx1);
}
PxU32 Sc::Scene::addTriClothAttachment(FEMClothCore& core, PxU32 triIdx0, const PxVec4& barycentric0, Sc::FEMClothSim& sim1, PxU32 triIdx1, const PxVec4& barycentric1)
{
Sc::FEMClothSim& sim0 = *core.getSim();
PxU32 handle = mSimulationController->addTriClothAttachment(sim0.getLowLevelFEMCloth(), sim1.getLowLevelFEMCloth(), triIdx0, triIdx1,
barycentric0, barycentric1, sim1.isActive() || sim0.isActive());
//return handle;
PxPair<PxU32, PxU32> pair(sim0.getNodeIndex().index(), sim1.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim0.getNodeIndex(), sim1.getNodeIndex(), NULL, IG::Edge::eFEM_CLOTH_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eFEM_CLOTH_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
return handle;
}
void Sc::Scene::removeTriClothAttachment(FEMClothCore& core, FEMClothSim& sim1, PxU32 handle)
{
Sc::FEMClothSim& sim0 = *core.getSim();
mSimulationController->removeTriClothAttachment(sim0.getLowLevelFEMCloth(), handle);
PxPair<PxU32, PxU32> pair(sim0.getNodeIndex().index(), sim1.getNodeIndex().index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addParticleSystemSimControl(Sc::ParticleSystemCore& core)
{
Sc::ParticleSystemSim* sim = core.getSim();
if (sim)
{
mSimulationController->addParticleSystem(sim->getLowLevelParticleSystem(), sim->getNodeIndex(), core.getSolverType());
mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getCore().getShapeCore().getCore(), sim->getLowLevelParticleSystem()->getElementId(), sim->getPxActor());
}
}
void Sc::Scene::removeParticleSystemSimControl(Sc::ParticleSystemCore& core)
{
Sc::ParticleSystemSim* sim = core.getSim();
if (sim)
{
mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getCore().getShapeCore().getCore(), sim->getShapeSim().getElementID());
mSimulationController->releaseParticleSystem(sim->getLowLevelParticleSystem(), core.getSolverType());
}
}
void Sc::Scene::addRigidAttachment(Sc::BodyCore* core, Sc::ParticleSystemSim& sim)
{
PxNodeIndex nodeIndex;
if (core)
{
nodeIndex = core->getSim()->getNodeIndex();
}
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, sim.getNodeIndex(), nodeIndex, NULL, IG::Edge::ePARTICLE_SYSTEM_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::ePARTICLE_SYSTEM_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
}
void Sc::Scene::removeRigidAttachment(Sc::BodyCore* core, Sc::ParticleSystemSim& sim)
{
PxNodeIndex nodeIndex;
if (core)
nodeIndex = core->getSim()->getNodeIndex();
PxPair<PxU32, PxU32> pair(sim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
interaction.mCount--;
if (interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
void Sc::Scene::addHairSystemSimControl(Sc::HairSystemCore& core)
{
Sc::HairSystemSim* sim = core.getSim();
if (sim)
{
mSimulationController->addHairSystem(sim->getLowLevelHairSystem(), sim->getNodeIndex());
mLLContext->getNphaseImplementationContext()->registerShape(sim->getNodeIndex(), sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID(), sim->getPxActor());
}
}
void Sc::Scene::removeHairSystemSimControl(Sc::HairSystemCore& core)
{
Sc::HairSystemSim* sim = core.getSim();
if (sim)
{
mLLContext->getNphaseImplementationContext()->unregisterShape(sim->getShapeSim().getCore().getCore(), sim->getShapeSim().getElementID());
mSimulationController->releaseHairSystem(sim->getLowLevelHairSystem());
}
}
void Sc::Scene::addAttachment(const Sc::BodySim& bodySim, const Sc::HairSystemSim& hairSim)
{
const PxNodeIndex nodeIndex = bodySim.getNodeIndex();
const PxPair<PxU32, PxU32> pair(hairSim.getNodeIndex().index(), nodeIndex.index());
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
if (interaction.mCount == 0)
{
IG::EdgeIndex edgeIdx = mSimpleIslandManager->addContactManager(NULL, hairSim.getNodeIndex(), nodeIndex, NULL, IG::Edge::eHAIR_SYSTEM_CONTACT);
mSimpleIslandManager->setEdgeConnected(edgeIdx, IG::Edge::eHAIR_SYSTEM_CONTACT);
interaction.mIndex = edgeIdx;
}
interaction.mCount++;
}
void Sc::Scene::removeAttachment(const Sc::BodySim& bodySim, const Sc::HairSystemSim& hairSim)
{
const PxNodeIndex nodeIndex = bodySim.getNodeIndex();
const PxPair<PxU32, PxU32> pair(hairSim.getNodeIndex().index(), nodeIndex.index());
if(mParticleOrSoftBodyRigidInteractionMap.find(pair)) // find returns pointer to const so we cannot use it directly
{
ParticleOrSoftBodyRigidInteraction& interaction = mParticleOrSoftBodyRigidInteractionMap[pair];
PX_ASSERT(interaction.mCount > 0);
interaction.mCount--;
if(interaction.mCount == 0)
{
mSimpleIslandManager->removeConnection(interaction.mIndex);
mParticleOrSoftBodyRigidInteractionMap.erase(pair);
}
}
}
PxActor** Sc::Scene::getActiveSoftBodyActors(PxU32& nbActorsOut)
{
nbActorsOut = mActiveSoftBodyActors.size();
if (!nbActorsOut)
return NULL;
return mActiveSoftBodyActors.begin();
}
void Sc::Scene::setActiveSoftBodyActors(PxActor** actors, PxU32 nbActors)
{
mActiveSoftBodyActors.forceSize_Unsafe(0);
mActiveSoftBodyActors.resize(nbActors);
PxMemCopy(mActiveSoftBodyActors.begin(), actors, sizeof(PxActor*) * nbActors);
}
//PxActor** Sc::Scene::getActiveFEMClothActors(PxU32& nbActorsOut)
//{
// nbActorsOut = mActiveFEMClothActors.size();
//
// if (!nbActorsOut)
// return NULL;
//
// return mActiveFEMClothActors.begin();
//}
//
//void Sc::Scene::setActiveFEMClothActors(PxActor** actors, PxU32 nbActors)
//{
// mActiveFEMClothActors.forceSize_Unsafe(0);
// mActiveFEMClothActors.resize(nbActors);
// PxMemCopy(mActiveFEMClothActors.begin(), actors, sizeof(PxActor*) * nbActors);
//}
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScBodySim.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 SC_BODYSIM_H
#define SC_BODYSIM_H
#include "foundation/PxUtilities.h"
#include "foundation/PxIntrinsics.h"
#include "ScRigidSim.h"
#include "PxvDynamics.h"
#include "ScBodyCore.h"
#include "ScSimStateData.h"
#include "PxRigidDynamic.h"
#include "PxsRigidBody.h"
namespace physx
{
namespace Bp
{
class BoundsArray;
}
class PxsTransformCache;
namespace Sc
{
class Scene;
class ArticulationSim;
#if PX_VC
#pragma warning(push)
#pragma warning( disable : 4324 ) // Padding was added at the end of a structure because of a __declspec(align) value.
#endif
class BodySim : public RigidSim
{
public:
BodySim(Scene&, BodyCore&, bool);
virtual ~BodySim();
void switchToKinematic();
void switchToDynamic();
PX_FORCE_INLINE const SimStateData* getSimStateData(bool isKinematic) const { return (mSimStateData && (checkSimStateKinematicStatus(isKinematic)) ? mSimStateData : NULL); }
PX_FORCE_INLINE SimStateData* getSimStateData(bool isKinematic) { return (mSimStateData && (checkSimStateKinematicStatus(isKinematic)) ? mSimStateData : NULL); }
PX_FORCE_INLINE SimStateData* getSimStateData_Unchecked() const { return mSimStateData; }
PX_FORCE_INLINE bool checkSimStateKinematicStatus(bool isKinematic) const
{
PX_ASSERT(mSimStateData);
return mSimStateData->isKine() == isKinematic;
}
void setKinematicTarget(const PxTransform& p);
void addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc);
void setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc);
void clearSpatialAcceleration(bool force, bool torque);
void addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta);
void clearSpatialVelocity(bool force, bool torque);
void updateCached(PxBitMapPinned* shapeChangedMap);
void updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray);
void updateContactDistance(PxReal* contactDistance, PxReal dt, const Bp::BoundsArray& boundsArray);
// hooks for actions in body core when it's attached to a sim object. Generally
// we get called after the attribute changed.
virtual void postActorFlagChange(PxU32 oldFlags, PxU32 newFlags) PX_OVERRIDE;
void postBody2WorldChange();
void postSetWakeCounter(PxReal t, bool forceWakeUp);
void postPosePreviewChange(PxU32 posePreviewFlag); // called when PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW changes
PX_FORCE_INLINE const PxTransform& getBody2World() const { return getBodyCore().getCore().body2World; }
PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return getBodyCore().getCore().getBody2Actor(); }
PX_FORCE_INLINE const PxsRigidBody& getLowLevelBody() const { return mLLBody; }
PX_FORCE_INLINE PxsRigidBody& getLowLevelBody() { return mLLBody; }
void setActive(bool active, bool asPartOfCreation=false);
void wakeUp(); // note: for user API call purposes only, i.e., use from BodyCore. For simulation internal purposes there is internalWakeUp().
void putToSleep();
void disableCompound();
static PxU32 getRigidBodyOffset() { return PxU32(PX_OFFSET_OF_RT(BodySim, mLLBody));}
void activate();
void deactivate();
// Kinematics
PX_FORCE_INLINE bool isKinematic() const { return getBodyCore().getFlags() & PxRigidBodyFlag::eKINEMATIC; }
PX_FORCE_INLINE bool isArticulationLink() const { return getActorType() == PxActorType::eARTICULATION_LINK; }
PX_FORCE_INLINE bool hasForcedKinematicNotif() const
{
return getBodyCore().getFlags() & (PxRigidBodyFlag::eFORCE_KINE_KINE_NOTIFICATIONS|PxRigidBodyFlag::eFORCE_STATIC_KINE_NOTIFICATIONS);
}
void calculateKinematicVelocity(PxReal oneOverDt);
void updateKinematicPose();
bool deactivateKinematic();
// Sleeping
virtual void internalWakeUp(PxReal wakeCounterValue) PX_OVERRIDE; // PT: TODO: does it need to be virtual?
void internalWakeUpArticulationLink(PxReal wakeCounterValue); // called by ArticulationSim to wake up this link
PxReal updateWakeCounter(PxReal dt, PxReal energyThreshold, const Cm::SpatialVector& motionVelocity);
void notifyReadyForSleeping(); // inform the sleep island generation system that the body is ready for sleeping
void notifyNotReadyForSleeping(); // inform the sleep island generation system that the body is not ready for sleeping
PX_FORCE_INLINE bool checkSleepReadinessBesidesWakeCounter(); // for API triggered changes to test sleep readiness
// PT: TODO: this is only used for the rigid bodies' sleep check, the implementations in derived classes look useless
virtual void registerCountedInteraction() PX_OVERRIDE { mLLBody.getCore().numCountedInteractions++; PX_ASSERT(mLLBody.getCore().numCountedInteractions); }
virtual void unregisterCountedInteraction() PX_OVERRIDE { PX_ASSERT(mLLBody.getCore().numCountedInteractions); mLLBody.getCore().numCountedInteractions--; }
// PT: TODO: this is only used for the rigid bodies' sleep check called from the articulation sim code
virtual PxU32 getNumCountedInteractions() const PX_OVERRIDE { return mLLBody.getCore().numCountedInteractions; }
PX_FORCE_INLINE PxIntBool isFrozen() const { return PxIntBool(mLLBody.mInternalFlags & PxsRigidBody::eFROZEN); }
// External velocity changes - returns true if any forces were applied to this body
bool updateForces(PxReal dt, PxsRigidBody** updatedBodySims, PxU32* updatedBodyNodeIndices, PxU32& index, Cm::SpatialVector* acceleration);
PX_FORCE_INLINE bool readVelocityModFlag(VelocityModFlags f) { return (mVelModState & f) != 0; }
// Miscellaneous
PX_FORCE_INLINE bool notInScene() const { return mActiveListIndex == SC_NOT_IN_SCENE_INDEX; }
PX_FORCE_INLINE PxU32 getNbShapes() const { return mShapes.getCount(); }
PX_FORCE_INLINE PxU32 getFlagsFast() const { return getBodyCore().getFlags(); }
PX_FORCE_INLINE BodyCore& getBodyCore() const { return static_cast<BodyCore&>(getRigidCore()); }
PX_FORCE_INLINE ArticulationSim* getArticulation() const { return mArticulation; }
void setArticulation(ArticulationSim* a, PxReal wakeCounter, bool asleep, PxU32 bodyIndex);
PX_FORCE_INLINE void onConstraintAttach() { raiseInternalFlag(BF_HAS_CONSTRAINTS); registerCountedInteraction(); }
void onConstraintDetach();
PX_FORCE_INLINE void onOriginShift(const PxVec3& shift, const bool isKinematic)
{
PX_ASSERT(!mSimStateData || checkSimStateKinematicStatus(isKinematic));
mLLBody.mLastTransform.p -= shift;
if (mSimStateData && isKinematic && mSimStateData->getKinematicData()->targetValid)
mSimStateData->getKinematicData()->targetPose.p -= shift;
}
PX_FORCE_INLINE bool usingSqKinematicTarget() const
{
const PxU32 ktFlags(PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES | PxRigidBodyFlag::eKINEMATIC);
return (getFlagsFast()&ktFlags) == ktFlags;
}
void createSqBounds();
void destroySqBounds();
void freezeTransforms(PxBitMapPinned* shapeChangedMap);
void addToSpeculativeCCDMap();
void removeFromSpeculativeCCDMap();
private:
// Base body
PxsRigidBody mLLBody;
// External velocity changes
// VelocityMod data allocated on the fly when the user applies velocity changes
// which need to be accumulated.
// VelMod dirty flags stored in BodySim so we can save ourselves the expense of looking at
// the separate velmod data if no forces have been set.
//PxU16 mInternalFlags;
SimStateData* mSimStateData;
PxU8 mVelModState;
// Articulation
ArticulationSim* mArticulation; // NULL if not in an articulation
// Joints & joint groups
bool setupSimStateData(bool isKinematic);
void tearDownSimStateData(bool isKinematic);
void raiseVelocityModFlagAndNotify(VelocityModFlags flag);
PX_FORCE_INLINE void notifyAddSpatialAcceleration() { raiseVelocityModFlagAndNotify(VMF_ACC_DIRTY); }
PX_FORCE_INLINE void notifyClearSpatialAcceleration() { raiseVelocityModFlagAndNotify(VMF_ACC_DIRTY); }
PX_FORCE_INLINE void notifyAddSpatialVelocity() { raiseVelocityModFlagAndNotify(VMF_VEL_DIRTY); }
PX_FORCE_INLINE void notifyClearSpatialVelocity() { raiseVelocityModFlagAndNotify(VMF_VEL_DIRTY); }
PX_FORCE_INLINE void initKinematicStateBase(BodyCore&, bool asPartOfCreation);
void notifyWakeUp(); // inform the sleep island generation system that the object got woken up
void notifyPutToSleep(); // inform the sleep island generation system that the object was put to sleep
void internalWakeUpBase(PxReal wakeCounterValue);
PX_FORCE_INLINE void raiseVelocityModFlag(VelocityModFlags f) { mVelModState |= f; }
PX_FORCE_INLINE void clearVelocityModFlag(VelocityModFlags f) { mVelModState &= ~f; }
PX_FORCE_INLINE void setForcesToDefaults(bool enableGravity);
};
#if PX_VC
#pragma warning(pop)
#endif
} // namespace Sc
PX_FORCE_INLINE void Sc::BodySim::setForcesToDefaults(bool enableGravity)
{
if (!(mLLBody.mCore->mFlags & PxRigidBodyFlag::eRETAIN_ACCELERATIONS))
{
SimStateData* simStateData = getSimStateData(false);
if(simStateData)
{
VelocityMod* velmod = simStateData->getVelocityModData();
velmod->clear();
}
if (enableGravity)
mVelModState = VMF_GRAVITY_DIRTY; // We want to keep the gravity flag to make sure the acceleration gets changed to gravity-only
// in the next step (unless the application adds new forces of course)
else
mVelModState = 0;
}
else
{
SimStateData* simStateData = getSimStateData(false);
if (simStateData)
{
VelocityMod* velmod = simStateData->getVelocityModData();
velmod->clearPerStep();
}
mVelModState &= (~(VMF_VEL_DIRTY));
}
}
PX_FORCE_INLINE bool Sc::BodySim::checkSleepReadinessBesidesWakeCounter()
{
const BodyCore& bodyCore = getBodyCore();
const SimStateData* simStateData = getSimStateData(false);
const VelocityMod* velmod = simStateData ? simStateData->getVelocityModData() : NULL;
bool readyForSleep = bodyCore.getLinearVelocity().isZero() && bodyCore.getAngularVelocity().isZero();
if (readVelocityModFlag(VMF_ACC_DIRTY))
{
readyForSleep = readyForSleep && (!velmod || velmod->getLinearVelModPerSec().isZero());
readyForSleep = readyForSleep && (!velmod || velmod->getAngularVelModPerSec().isZero());
}
if (readVelocityModFlag(VMF_VEL_DIRTY))
{
readyForSleep = readyForSleep && (!velmod || velmod->getLinearVelModPerStep().isZero());
readyForSleep = readyForSleep && (!velmod || velmod->getAngularVelModPerStep().isZero());
}
return readyForSleep;
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintBreakage.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 "ScScene.h"
#include "ScConstraintSim.h"
#include "ScConstraintCore.h"
#include "ScConstraintInteraction.h"
#include "common/PxProfileZone.h"
using namespace physx;
// PT: the breakable constraints are added to / removed from mActiveBreakableConstraints:
void Sc::Scene::addActiveBreakableConstraint(Sc::ConstraintSim* c, Sc::ConstraintInteraction* ci)
{
PX_ASSERT(ci && ci->readInteractionFlag(InteractionFlag::eIS_ACTIVE));
PX_UNUSED(ci);
PX_ASSERT(!mActiveBreakableConstraints.contains(c));
PX_ASSERT(!c->isBroken());
mActiveBreakableConstraints.insert(c);
c->setFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED);
}
void Sc::Scene::removeActiveBreakableConstraint(Sc::ConstraintSim* c)
{
const bool exists = mActiveBreakableConstraints.erase(c);
PX_ASSERT(exists);
PX_UNUSED(exists);
c->clearFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED);
}
// PT: then at runtime we parse mActiveBreakableConstraints, check for max force exceeded,
// and add broken constraints to mBrokenConstraints:
void Sc::Scene::checkConstraintBreakage()
{
PX_PROFILE_ZONE("Sim.checkConstraintBreakage", mContextId);
PxU32 count = mActiveBreakableConstraints.size();
if(!count)
return;
PxPinnedArray<Dy::ConstraintWriteback>& pool = mDynamicsContext->getConstraintWriteBackPool();
ConstraintSim* const* constraints = mActiveBreakableConstraints.getEntries();
while(count--)
{
ConstraintSim* sim = constraints[count]; // start from the back because broken constraints get removed from the list
PX_ASSERT(sim->readFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED));
const Dy::ConstraintWriteback& solverOutput = pool[sim->getLowLevelConstraint().index];
if(solverOutput.broken)
{
sim->setFlag(ConstraintSim::eBROKEN);
ConstraintCore& core = sim->getCore();
if(mSimulationEventCallback)
{
PX_ASSERT(mBrokenConstraints.find(&core) == mBrokenConstraints.end());
mBrokenConstraints.pushBack(&core);
}
core.breakApart();
ConstraintInteraction* interaction = const_cast<ConstraintInteraction*>(sim->getInteraction());
interaction->destroy(); // PT: this will call removeFromActiveBreakableList above
// update related SIPs
{
ActorSim& a0 = interaction->getActorSim0();
ActorSim& a1 = interaction->getActorSim1();
ActorSim& actor = (a0.getActorInteractionCount() < a1.getActorInteractionCount()) ? a0 : a1;
actor.setActorsInteractionsDirty(InteractionDirtyFlag::eFILTER_STATE, NULL, InteractionFlag::eRB_ELEMENT);
// because broken constraints can re-enable contact response between the two bodies
}
PX_ASSERT(!sim->readFlag(ConstraintSim::eCHECK_MAX_FORCE_EXCEEDED));
}
}
}
// PT: finally mBrokenConstraints is parsed and callbacks issued:
void Sc::Scene::fireBrokenConstraintCallbacks()
{
if(!mSimulationEventCallback)
return;
const PxU32 count = mBrokenConstraints.size();
for(PxU32 i=0;i<count;i++)
{
Sc::ConstraintCore* c = mBrokenConstraints[i];
PX_ASSERT(c->getSim());
PxU32 typeID = 0xffffffff;
void* externalRef = c->getPxConnector()->getExternalReference(typeID);
PX_CHECK_MSG(typeID != 0xffffffff, "onConstraintBreak: Invalid constraint type ID.");
PxConstraintInfo constraintInfo(c->getPxConstraint(), externalRef, typeID);
mSimulationEventCallback->onConstraintBreak(&constraintInfo, 1);
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorSim.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 "ScActorSim.h"
#include "ScActorCore.h"
#include "ScElementSim.h"
#include "ScScene.h"
#include "ScInteraction.h"
using namespace physx;
using namespace Sc;
static const PxFilterObjectType::Enum gFilterType[PxActorType::eACTOR_COUNT] =
{
PxFilterObjectType::eRIGID_STATIC, // PxActorType::eRIGID_STATIC
PxFilterObjectType::eRIGID_DYNAMIC, // PxActorType::eRIGID_DYNAMIC
PxFilterObjectType::eARTICULATION, // PxActorType::eARTICULATION_LINK
PxFilterObjectType::eSOFTBODY, // PxActorType::eSOFTBODY
PxFilterObjectType::eFEMCLOTH, // PxActorType::eFEMCLOTH
PxFilterObjectType::ePARTICLESYSTEM, // PxActorType::ePBD_PARTICLESYSTEM
PxFilterObjectType::ePARTICLESYSTEM, // PxActorType::eFLIP_PARTICLESYSTEM
PxFilterObjectType::ePARTICLESYSTEM, // PxActorType::eMPM_PARTICLESYSTEM
PxFilterObjectType::eHAIRSYSTEM, // PxActorType::eHAIRSYSTEM
};
static const PxU32 gFilterFlagEx[PxActorType::eACTOR_COUNT] =
{
PxFilterObjectFlagEx::eRIGID_STATIC, // PxActorType::eRIGID_STATIC
PxFilterObjectFlagEx::eRIGID_DYNAMIC, // PxActorType::eRIGID_DYNAMIC
PxFilterObjectFlagEx::eRIGID_DYNAMIC, // PxActorType::eARTICULATION_LINK
PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::eSOFTBODY, // PxActorType::eSOFTBODY
PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::eFEMCLOTH, // PxActorType::eFEMCLOTH
PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::ePARTICLESYSTEM, // PxActorType::ePBD_PARTICLESYSTEM
PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::ePARTICLESYSTEM, // PxActorType::eFLIP_PARTICLESYSTEM
PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::ePARTICLESYSTEM, // PxActorType::eMPM_PARTICLESYSTEM
PxFilterObjectFlagEx::eNON_RIGID|PxFilterObjectFlagEx::eHAIRSYSTEM, // PxActorType::eHAIRSYSTEM
};
// PT: if this breaks, you need to update the above table
PX_COMPILE_TIME_ASSERT(PxActorType::eACTOR_COUNT==9);
// PT: make sure that the highest flag fits into 16bit
PX_COMPILE_TIME_ASSERT(PxFilterObjectFlagEx::eLAST<=0xffff);
Sc::ActorSim::ActorSim(Scene& scene, ActorCore& core) :
mScene (scene),
mCore (core),
mActiveListIndex (SC_NOT_IN_SCENE_INDEX),
mActiveCompoundListIndex(SC_NOT_IN_SCENE_INDEX),
mNodeIndex (PX_INVALID_NODE),
mInternalFlags (0)
{
core.setSim(this);
mId = scene.getActorIDTracker().createID();
{
PX_ASSERT(gFilterType[PxActorType::eRIGID_STATIC] == PxFilterObjectType::eRIGID_STATIC);
PX_ASSERT(gFilterType[PxActorType::eRIGID_DYNAMIC] == PxFilterObjectType::eRIGID_DYNAMIC);
PX_ASSERT(gFilterType[PxActorType::eARTICULATION_LINK] == PxFilterObjectType::eARTICULATION);
PX_ASSERT(gFilterType[PxActorType::eSOFTBODY] == PxFilterObjectType::eSOFTBODY);
PX_ASSERT(gFilterType[PxActorType::eFEMCLOTH] == PxFilterObjectType::eFEMCLOTH);
PX_ASSERT(gFilterType[PxActorType::ePBD_PARTICLESYSTEM] == PxFilterObjectType::ePARTICLESYSTEM);
PX_ASSERT(gFilterType[PxActorType::eFLIP_PARTICLESYSTEM] == PxFilterObjectType::ePARTICLESYSTEM);
PX_ASSERT(gFilterType[PxActorType::eMPM_PARTICLESYSTEM] == PxFilterObjectType::ePARTICLESYSTEM);
PX_ASSERT(gFilterType[PxActorType::eHAIRSYSTEM] == PxFilterObjectType::eHAIRSYSTEM);
const PxActorType::Enum actorType = getActorType();
PxFilterObjectAttributes filterAttr = 0;
setFilterObjectAttributeType(filterAttr, gFilterType[actorType]);
filterAttr |= gFilterFlagEx[actorType];
mFilterFlags = PxTo16(filterAttr);
}
}
Sc::ActorSim::~ActorSim()
{
mInteractions.releaseMem(*this);
mScene.getActorIDTracker().releaseID(mId);
}
void Sc::ActorSim::registerInteractionInActor(Interaction* interaction)
{
const PxU32 id = mInteractions.size();
mInteractions.pushBack(interaction, *this);
interaction->setActorId(this, id);
}
void Sc::ActorSim::unregisterInteractionFromActor(Interaction* interaction)
{
const PxU32 i = interaction->getActorId(this);
PX_ASSERT(i < mInteractions.size());
mInteractions.replaceWithLast(i);
if (i<mInteractions.size())
mInteractions[i]->setActorId(this, i);
}
void Sc::ActorSim::reallocInteractions(Sc::Interaction**& mem, PxU32& capacity, PxU32 size, PxU32 requiredMinCapacity)
{
Interaction** newMem;
PxU32 newCapacity;
if(requiredMinCapacity==0)
{
newCapacity = 0;
newMem = 0;
}
else if(requiredMinCapacity<=INLINE_INTERACTION_CAPACITY)
{
newCapacity = INLINE_INTERACTION_CAPACITY;
newMem = mInlineInteractionMem;
}
else
{
newCapacity = PxNextPowerOfTwo(requiredMinCapacity-1);
newMem = reinterpret_cast<Interaction**>(mScene.allocatePointerBlock(newCapacity));
}
PX_ASSERT(newCapacity >= requiredMinCapacity && requiredMinCapacity>=size);
if(mem)
{
PxMemCopy(newMem, mem, size*sizeof(Interaction*));
if(mem!=mInlineInteractionMem)
mScene.deallocatePointerBlock(reinterpret_cast<void**>(mem), capacity);
}
capacity = newCapacity;
mem = newMem;
}
void Sc::ActorSim::setActorsInteractionsDirty(InteractionDirtyFlag::Enum flag, const ActorSim* other, PxU8 interactionFlag)
{
PxU32 size = getActorInteractionCount();
Interaction** interactions = getActorInteractions();
while(size--)
{
Interaction* interaction = *interactions++;
if((!other || other == &interaction->getActorSim0() || other == &interaction->getActorSim1()) && (interaction->readInteractionFlag(interactionFlag)))
interaction->setDirty(flag);
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeSim.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.
#ifndef SC_HAIRSYSTEM_SHAPE_SIM_H
#define SC_HAIRSYSTEM_SHAPE_SIM_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXConfig.h"
#include "ScElementSim.h"
#include "ScShapeSimBase.h"
namespace physx
{
namespace Sc
{
class HairSystemSim;
class HairSystemShapeCore;
/**
A collision detection primitive for the hair system.
*/
class HairSystemShapeSim : public ShapeSimBase
{
HairSystemShapeSim& operator=(const HairSystemShapeSim &);
public:
HairSystemShapeSim(HairSystemSim& hairSystem, const HairSystemShapeCore* core);
virtual ~HairSystemShapeSim();
// ElementSim implementation
virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const;
// ~ElementSim
HairSystemSim& getBodySim() const;
void updateBounds();
void updateBoundsInAABBMgr();
PxBounds3 getBounds() const;
void createLowLevelVolume();
void destroyLowLevelVolume();
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSimStats.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/PxMemory.h"
#include "ScSimStats.h"
#include "PxvSimStats.h"
#include "PxsHeapMemoryAllocator.h"
using namespace physx;
Sc::SimStats::SimStats()
{
numBroadPhaseAdds = numBroadPhaseRemoves = 0;
gpuMemSizeParticles = 0;
gpuMemSizeSoftBodies = 0;
clear();
}
void Sc::SimStats::clear()
{
#if PX_ENABLE_SIM_STATS
PxMemZero(const_cast<void*>(reinterpret_cast<volatile void*>(&numTriggerPairs)), sizeof(TriggerPairCounts));
numBroadPhaseAddsPending = numBroadPhaseRemovesPending = 0;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
void Sc::SimStats::simStart()
{
#if PX_ENABLE_SIM_STATS
// pending broadphase adds/removes are now the current ones
numBroadPhaseAdds = numBroadPhaseAddsPending;
numBroadPhaseRemoves = numBroadPhaseRemovesPending;
clear();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
void Sc::SimStats::readOut(PxSimulationStatistics& s, const PxvSimStats& simStats) const
{
#if PX_ENABLE_SIM_STATS
s = PxSimulationStatistics(); // clear stats
for(PxU32 i=0; i < PxGeometryType::eCONVEXMESH+1; i++)
{
for(PxU32 j=0; j < PxGeometryType::eGEOMETRY_COUNT; j++)
{
s.nbTriggerPairs[i][j] += PxU32(numTriggerPairs[i][j]);
if (i != j)
s.nbTriggerPairs[j][i] += PxU32(numTriggerPairs[i][j]);
}
}
s.nbBroadPhaseAdds = numBroadPhaseAdds;
s.nbBroadPhaseRemoves = numBroadPhaseRemoves;
for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++)
{
s.nbDiscreteContactPairs[i][i] = simStats.mNbDiscreteContactPairs[i][i];
s.nbModifiedContactPairs[i][i] = simStats.mNbModifiedContactPairs[i][i];
s.nbCCDPairs[i][i] = simStats.mNbCCDPairs[i][i];
for(PxU32 j=i+1; j < PxGeometryType::eGEOMETRY_COUNT; j++)
{
PxU32 c = simStats.mNbDiscreteContactPairs[i][j];
s.nbDiscreteContactPairs[i][j] = c;
s.nbDiscreteContactPairs[j][i] = c;
c = simStats.mNbModifiedContactPairs[i][j];
s.nbModifiedContactPairs[i][j] = c;
s.nbModifiedContactPairs[j][i] = c;
c = simStats.mNbCCDPairs[i][j];
s.nbCCDPairs[i][j] = c;
s.nbCCDPairs[j][i] = c;
}
#if PX_DEBUG
for(PxU32 j=0; j < i; j++)
{
// PxvSimStats should only use one half of the matrix
PX_ASSERT(simStats.mNbDiscreteContactPairs[i][j] == 0);
PX_ASSERT(simStats.mNbModifiedContactPairs[i][j] == 0);
PX_ASSERT(simStats.mNbCCDPairs[i][j] == 0);
}
#endif
}
s.nbDiscreteContactPairsTotal = simStats.mNbDiscreteContactPairsTotal;
s.nbDiscreteContactPairsWithCacheHits = simStats.mNbDiscreteContactPairsWithCacheHits;
s.nbDiscreteContactPairsWithContacts = simStats.mNbDiscreteContactPairsWithContacts;
s.nbActiveConstraints = simStats.mNbActiveConstraints;
s.nbActiveDynamicBodies = simStats.mNbActiveDynamicBodies;
s.nbActiveKinematicBodies = simStats.mNbActiveKinematicBodies;
s.nbAxisSolverConstraints = simStats.mNbAxisSolverConstraints;
s.peakConstraintMemory = simStats.mPeakConstraintBlockAllocations * 16 * 1024;
s.compressedContactSize = simStats.mTotalCompressedContactSize;
s.requiredContactConstraintMemory = simStats.mTotalConstraintSize;
s.nbNewPairs = simStats.mNbNewPairs;
s.nbLostPairs = simStats.mNbLostPairs;
s.nbNewTouches = simStats.mNbNewTouches;
s.nbLostTouches = simStats.mNbLostTouches;
s.nbPartitions = simStats.mNbPartitions;
s.gpuMemParticles = gpuMemSizeParticles;
s.gpuMemSoftBodies = gpuMemSizeSoftBodies;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(s);
PX_UNUSED(simStats);
#endif
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScElementInteractionMarker.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 SC_ELEMENT_INTERACTION_MARKER_H
#define SC_ELEMENT_INTERACTION_MARKER_H
#include "ScElementSimInteraction.h"
#include "ScNPhaseCore.h"
namespace physx
{
namespace Sc
{
class ElementInteractionMarker : public ElementSimInteraction
{
public:
PX_INLINE ElementInteractionMarker(ElementSim& element0, ElementSim& element1, bool createParallel/* = false*/);
~ElementInteractionMarker();
};
} // namespace Sc
PX_INLINE Sc::ElementInteractionMarker::ElementInteractionMarker(ElementSim& element0, ElementSim& element1, bool createParallel) :
ElementSimInteraction(element0, element1, InteractionType::eMARKER, InteractionFlag::eRB_ELEMENT|InteractionFlag::eFILTERABLE)
{
if(!createParallel)
{
// PT: no call to onActivate() here, interaction markers are always inactive
registerInActors();
Scene& scene = getScene();
scene.registerInteraction(this, false);
}
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScConstraintInteraction.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 SC_CONSTRAINT_INTERACTION_H
#define SC_CONSTRAINT_INTERACTION_H
#include "ScInteraction.h"
namespace physx
{
namespace Sc
{
class ConstraintSim;
class RigidSim;
class ConstraintInteraction : public Interaction
{
public:
ConstraintInteraction(ConstraintSim* shader, RigidSim& r0, RigidSim& r1);
~ConstraintInteraction();
bool onActivate(void* data);
bool onDeactivate();
void updateState();
void destroy(); // disables the interaction and unregisters from the system. Does NOT delete the object. This is used on destruction but also when a constraint breaks.
PX_FORCE_INLINE ConstraintSim* getConstraint() { return mConstraint; }
PX_FORCE_INLINE PxU32 getEdgeIndex() const { return mEdgeIndex; }
private:
ConstraintSim* mConstraint;
PxU32 mEdgeIndex;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSqBoundsManager.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 "GuPrunerTypedef.h"
#include "ScSqBoundsManager.h"
#include "ScBodySim.h"
#include "ScShapeSim.h"
#include "ScSqBoundsSync.h"
#include "common/PxProfileZone.h"
using namespace physx;
using namespace Sc;
#define INVALID_REF ScPrunerHandle(Gu::INVALID_PRUNERHANDLE)
SqBoundsManager0::SqBoundsManager0() :
mShapes ("SqBoundsManager::mShapes"),
mRefs ("SqBoundsManager::mRefs"),
mBoundsIndices ("SqBoundsManager::mBoundsIndices"),
mRefless ("SqBoundsManager::mRefless")
{
}
void SqBoundsManager0::addSyncShape(ShapeSimBase& shape)
{
PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE);
PX_ASSERT(!shape.getBodySim()->usingSqKinematicTarget());
PX_ASSERT(!shape.getBodySim()->isFrozen());
const PxU32 id = mShapes.size();
PX_ASSERT(id == mRefs.size());
PX_ASSERT(id == mBoundsIndices.size());
shape.setSqBoundsId(id);
// PT: mShapes / mRefs / mBoundsIndices are "parallel arrays". These arrays are persistent.
// mRefless is temporary/transient data to help populate mRefs each frame.
// mRefs / mBoundsIndices will be ultimately passed to updateObjects, whose API dictates the layout here.
// mShapes is not actually used for the sync, it's only here to be able to call setSqBoundsId in removeShape.
mShapes.pushBack(static_cast<Sc::ShapeSim*>(&shape));
mRefs.pushBack(INVALID_REF);
mBoundsIndices.pushBack(shape.getElementID());
mRefless.pushBack(static_cast<Sc::ShapeSim*>(&shape));
}
void SqBoundsManager0::removeSyncShape(ShapeSimBase& shape)
{
const PxU32 id = shape.getSqBoundsId();
PX_ASSERT(id!=PX_INVALID_U32);
shape.setSqBoundsId(PX_INVALID_U32);
mShapes[id] = mShapes.back();
mBoundsIndices[id] = mBoundsIndices.back();
mRefs[id] = mRefs.back();
if(id+1 != mShapes.size())
mShapes[id]->setSqBoundsId(id);
mShapes.popBack();
mRefs.popBack();
mBoundsIndices.popBack();
}
void SqBoundsManager0::syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices)
{
PX_PROFILE_ZONE("Sim.sceneQuerySyncBounds", contextID);
PX_UNUSED(contextID);
#if PX_DEBUG
for(PxU32 i=0;i<mShapes.size();i++)
{
const ShapeSimBase& shape = *mShapes[i];
PX_UNUSED(shape);
PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE);
PX_ASSERT(!shape.getBodySim()->usingSqKinematicTarget());
PX_ASSERT(!shape.getBodySim()->isFrozen());
}
#endif
ShapeSimBase*const * shapes = mRefless.begin();
for(PxU32 i=0, size = mRefless.size();i<size;i++)
{
const PxU32 id = shapes[i]->getSqBoundsId();
// PT:
//
// If id == PX_INVALID_U32, the shape has been removed and not re-added. Nothing to do in this case, we just ignore it.
// This case didn't previously exist since mRefless only contained valid (added) shapes. But now we left removed shapes in the
// structure, and these have an id == PX_INVALID_U32.
//
// Now if the id is valid but mRefs[id] == PX_INVALID_U32, this is a regular shape that has been added and not processed yet.
// So we process it.
//
// Finally, if both id and mRefs[id] are not PX_INVALID_U32, this is a shape that has been added, removed, and re-added. The
// array contains the same shape twice and we only need to process it once.
if(id!=PX_INVALID_U32)
{
if(mRefs[id] == INVALID_REF)
{
PxU32 prunerIndex = 0xffffffff;
mRefs[id] = finder.find(static_cast<PxRigidBody*>(shapes[i]->getBodySim()->getPxActor()), shapes[i]->getPxShape(), prunerIndex);
PX_ASSERT(prunerIndex==1);
}
}
}
mRefless.clear();
sync.sync(1, mRefs.begin(), mBoundsIndices.begin(), bounds, transforms, mShapes.size(), ignoredIndices);
}
// PT: we need to change the code so that the shape is added to the proper array during syncBounds, not during addSyncShape,
// because the pruner index is not known in addSyncShape. We could perhaps call the ref-finder directly in addSyncShape, but
// it would impose an order on the calls (the shape would need to be added to the pruners before addSyncShape is called. There's
// no such requirement with the initial code).
//
// Instead we do this:
// - in addSyncShape we just add the shape to a "waiting room", that's all.
// - adding the shape to the proper array is delayed until syncBounds. That way the prunerIndex will be available. Also we could
// then take advantage of batching, since all shapes are processed/added at the same time.
// - the only catch is that we need to ensure the previous edge-cases are still properly handled, i.e. when a shape is added then
// removed before sync is called, etc.
//
SqBoundsManagerEx::SqBoundsManagerEx() :
mWaitingRoom ("SqBoundsManagerEx::mWaitingRoom"),
mPrunerSyncData (NULL),
mPrunerSyncDataSize (0)
{
}
SqBoundsManagerEx::~SqBoundsManagerEx()
{
const PxU32 nbToGo = mPrunerSyncDataSize;
for(PxU32 i=0;i<nbToGo;i++)
{
PrunerSyncData* psd = mPrunerSyncData[i];
PX_DELETE(psd);
}
PX_FREE(mPrunerSyncData);
}
void SqBoundsManagerEx::resize(PxU32 index)
{
PxU32 size = mPrunerSyncDataSize ? mPrunerSyncDataSize*2 : 64;
const PxU32 minSize = index+1;
if(minSize>size)
size = minSize*2;
PrunerSyncData** items = PX_ALLOCATE(PrunerSyncData*, size, "PrunerSyncData");
if(mPrunerSyncData)
PxMemCopy(items, mPrunerSyncData, mPrunerSyncDataSize*sizeof(PrunerSyncData*));
PxMemZero(items+mPrunerSyncDataSize, (size-mPrunerSyncDataSize)*sizeof(PrunerSyncData*));
PX_FREE(mPrunerSyncData);
mPrunerSyncData = items;
mPrunerSyncDataSize = size;
}
void SqBoundsManagerEx::addSyncShape(ShapeSimBase& shape)
{
PX_ASSERT(shape.getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE);
PX_ASSERT(!shape.getBodySim()->usingSqKinematicTarget());
PX_ASSERT(!shape.getBodySim()->isFrozen());
PX_ASSERT(shape.getSqBoundsId()==PX_INVALID_U32);
PX_ASSERT(shape.getSqPrunerIndex()==PX_INVALID_U32);
const PxU32 id = mWaitingRoom.size();
mWaitingRoom.pushBack(&shape);
shape.setSqBoundsId(id);
shape.setSqPrunerIndex(PX_INVALID_U32);
}
void SqBoundsManagerEx::removeSyncShape(ShapeSimBase& shape)
{
const PxU32 id = shape.getSqBoundsId();
const PxU32 prunerIndex = shape.getSqPrunerIndex();
PX_ASSERT(id!=PX_INVALID_U32);
shape.setSqBoundsId(PX_INVALID_U32);
shape.setSqPrunerIndex(PX_INVALID_U32);
if(prunerIndex==PX_INVALID_U32)
{
// PT: this shape is still in the waiting room
PX_ASSERT(mWaitingRoom[id]==&shape);
mWaitingRoom[id] = mWaitingRoom.back();
if(id+1 != mWaitingRoom.size())
mWaitingRoom[id]->setSqBoundsId(id);
mWaitingRoom.popBack();
}
else
{
// PT: this shape is active
PX_ASSERT(prunerIndex<mPrunerSyncDataSize);
PrunerSyncData* psd = mPrunerSyncData[prunerIndex];
PX_ASSERT(psd);
PX_ASSERT(psd->mShapes[id]==&shape);
psd->mShapes[id] = psd->mShapes.back();
psd->mBoundsIndices[id] = psd->mBoundsIndices.back();
psd->mRefs[id] = psd->mRefs.back();
if(id+1 != psd->mShapes.size())
psd->mShapes[id]->setSqBoundsId(id);
psd->mShapes.popBack();
psd->mBoundsIndices.popBack();
psd->mRefs.popBack();
if(!psd->mShapes.size())
{
PX_DELETE(psd);
mPrunerSyncData[prunerIndex] = NULL;
}
}
}
void SqBoundsManagerEx::syncBounds(SqBoundsSync& sync, SqRefFinder& finder, const PxBounds3* bounds, const PxTransform32* transforms, PxU64 contextID, const PxBitMap& ignoredIndices)
{
PX_PROFILE_ZONE("Sim.sceneQuerySyncBounds", contextID);
PX_UNUSED(contextID);
/*
#if PX_DEBUG
for(PxU32 i=0;i<mShapeData.size();i++)
{
const ShapeSQData& shape = mShapeData[i];
PX_UNUSED(shape);
PX_ASSERT(shape.mSim->getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE);
PX_ASSERT(!shape.mSim->getBodySim()->usingSqKinematicTarget());
PX_ASSERT(!shape.mSim->getBodySim()->isFrozen());
}
#endif
*/
const PxU32 nbToGo = mWaitingRoom.size();
if(nbToGo)
{
for(PxU32 i=0;i<nbToGo;i++)
{
ShapeSimBase* sim = mWaitingRoom[i];
PX_ASSERT(i==sim->getSqBoundsId());
PX_ASSERT(PX_INVALID_U32==sim->getSqPrunerIndex());
PxU32 prunerIndex = 0xffffffff;
const ScPrunerHandle prunerHandle = finder.find(static_cast<PxRigidBody*>(sim->getBodySim()->getPxActor()), sim->getPxShape(), prunerIndex);
PX_ASSERT(prunerIndex!=0xffffffff);
if(prunerIndex>=mPrunerSyncDataSize)
resize(prunerIndex);
PrunerSyncData* psd = mPrunerSyncData[prunerIndex];
if(!psd)
{
psd = PX_NEW(PrunerSyncData);
mPrunerSyncData[prunerIndex] = psd;
}
PxArray<ShapeSimBase*>& shapes = psd->mShapes;
PxArray<ScPrunerHandle>& refs = psd->mRefs;
PxArray<PxU32>& boundsIndices = psd->mBoundsIndices;
const PxU32 id = shapes.size();
PX_ASSERT(id == refs.size());
PX_ASSERT(id == boundsIndices.size());
sim->setSqBoundsId(id);
sim->setSqPrunerIndex(prunerIndex);
// PT: mShapes / mRefs / mBoundsIndices are "parallel arrays". These arrays are persistent.
// mRefless is temporary/transient data to help populate mRefs each frame.
// mRefs / mBoundsIndices will be ultimately passed to updateObjects, whose API dictates the layout here.
// mShapes is not actually used for the sync, it's only here to be able to call setSqBoundsId in removeShape.
shapes.pushBack(sim);
refs.pushBack(prunerHandle);
boundsIndices.pushBack(sim->getElementID());
}
mWaitingRoom.clear(); // PT: TODO: optimize wasted memory here
}
// PT: TODO: optimize this
{
const PxU32 nb = mPrunerSyncDataSize;
for(PxU32 i=0;i<nb;i++)
{
PrunerSyncData* psd = mPrunerSyncData[i];
if(psd)
sync.sync(i, psd->mRefs.begin(), psd->mBoundsIndices.begin(), bounds, transforms, psd->mRefs.size(), ignoredIndices);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScPhysics.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/PxTolerancesScale.h"
#include "ScPhysics.h"
#include "ScScene.h"
#include "PxvGlobals.h"
using namespace physx;
Sc::Physics* Sc::Physics::mInstance = NULL;
const PxReal Sc::Physics::sWakeCounterOnCreation = 20.0f*0.02f;
namespace physx
{
namespace Sc
{
OffsetTable gOffsetTable;
}
}
Sc::Physics::Physics(const PxTolerancesScale& scale, const PxvOffsetTable& pxvOffsetTable) : mScale(scale)
{
mInstance = this;
PxvInit(pxvOffsetTable);
}
Sc::Physics::~Physics()
{
PxvTerm();
mInstance = NULL;
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothShapeSim.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.
#ifndef PX_PHYSICS_FEMCLOTH_SHAPE_SIM
#define PX_PHYSICS_FEMCLOTH_SHAPE_SIM
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXConfig.h"
#include "ScElementSim.h"
#include "ScShapeSimBase.h"
namespace physx
{
namespace Sc
{
class FEMClothSim;
class FEMClothShapeSim : public ShapeSimBase
{
PxTransform initialTransform;
PxReal initialScale;
FEMClothShapeSim& operator=(const FEMClothShapeSim &);
public:
FEMClothShapeSim(FEMClothSim& FEMCloth);
virtual ~FEMClothShapeSim();
PX_FORCE_INLINE void setInitialTransform(const PxTransform& transform, PxReal scale)
{
initialTransform = transform;
initialScale = scale;
//The base class constructor ensures that getElementID() points to a valid entry in the bounds array
getScene().getBoundsArray().setBounds(getWorldBounds(), getElementID());
}
void attachShapeCore(const ShapeCore* core);
// ElementSim implementation
virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const;
// ~ElementSim
PxBounds3 getWorldBounds() const;
//PX_FORCE_INLINE FEMClothSim& getBodySim() const { return static_cast<FEMClothSim&>(getActor()); }
FEMClothSim& getBodySim() const;
void updateBounds();
void updateBoundsInAABBMgr();
PxBounds3 getBounds() const;
void createLowLevelVolume();
void destroyLowLevelVolume();
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSim.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 SC_SHAPE_SIM_H
#define SC_SHAPE_SIM_H
#include "ScShapeSimBase.h"
namespace physx
{
/** Simulation object corresponding to a shape core object. This object is created when
a ShapeCore object is added to the simulation, and destroyed when it is removed
*/
namespace Sc
{
class RigidSim;
class ShapeCore;
class ShapeSim : public ShapeSimBase
{
PX_NOCOPY(ShapeSim)
public:
ShapeSim(RigidSim&, ShapeCore& core);
~ShapeSim();
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodySim.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.
#ifndef SC_SOFTBODY_SIM_H
#define SC_SOFTBODY_SIM_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "foundation/PxUserAllocated.h"
#include "DySoftBody.h"
#include "ScSoftBodyCore.h"
#include "ScSoftBodyShapeSim.h"
namespace physx
{
namespace Sc
{
class Scene;
class SoftBodySim : public ActorSim
{
PX_NOCOPY(SoftBodySim)
public:
SoftBodySim(SoftBodyCore& core, Scene& scene);
~SoftBodySim();
PX_INLINE Dy::SoftBody* getLowLevelSoftBody() const { return mLLSoftBody; }
PX_INLINE SoftBodyCore& getCore() const { return static_cast<SoftBodyCore&>(mCore); }
virtual PxActor* getPxActor() const { return getCore().getPxActor(); }
void updateBounds();
void updateBoundsInAABBMgr();
PxBounds3 getBounds() const;
bool isSleeping() const;
bool isActive() const { return !isSleeping(); }
void setActive(bool active, bool asPartOfCreation=false);
void enableSelfCollision();
void disableSelfCollision();
void onSetWakeCounter();
void attachShapeCore(ShapeCore* core);
void attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState);
PxTetrahedronMesh* getSimulationMesh();
PxSoftBodyAuxData* getSoftBodyAuxData();
PxTetrahedronMesh* getCollisionMesh();
PxU32 getGpuSoftBodyIndex() const;
SoftBodyShapeSim& getShapeSim() { return mShapeSim; }
private:
Dy::SoftBody* mLLSoftBody;
SoftBodyShapeSim mShapeSim;
PxU32 mIslandNodeIndex;
// PT: as far as I can tell these are never actually called
// void activate();
// void deactivate();
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScSoftBodyShapeSim.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.
#ifndef SC_SOFTBODY_SHAPE_SIM_H
#define SC_SOFTBODY_SHAPE_SIM_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXConfig.h"
#include "ScElementSim.h"
#include "ScShapeSimBase.h"
namespace physx
{
namespace Sc
{
class SoftBodySim;
/**
A collision detection primitive for soft body.
*/
class SoftBodyShapeSim : public ShapeSimBase
{
PxTransform initialTransform;
PxReal initialScale;
SoftBodyShapeSim& operator=(const SoftBodyShapeSim &);
public:
SoftBodyShapeSim(SoftBodySim& softbody);
virtual ~SoftBodyShapeSim();
PX_FORCE_INLINE void setInitialTransform(const PxTransform& transform, PxReal scale)
{
initialTransform = transform;
initialScale = scale;
//The base class constructor ensures that getElementID() points to a valid entry in the bounds array
getScene().getBoundsArray().setBounds(getWorldBounds(), getElementID());
}
void attachShapeCore(const ShapeCore* core);
// ElementSim implementation
virtual void getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const;
// ~ElementSim
PxBounds3 getWorldBounds() const;
//PX_FORCE_INLINE SoftBodySim& getBodySim() const { return static_cast<SoftBodySim&>(getActor()); }
SoftBodySim& getBodySim() const;
void updateBounds();
void updateBoundsInAABBMgr();
PxBounds3 getBounds() const;
void createLowLevelVolume();
void destroyLowLevelVolume();
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationSensorSim.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 SC_ARTICULATION_SENSOR_SIM_H
#define SC_ARTICULATION_SENSOR_SIM_H
#include "foundation/PxUserAllocated.h"
#include "PxArticulationReducedCoordinate.h"
#include "DyFeatherstoneArticulation.h"
namespace physx
{
namespace Sc
{
class Scene;
class ArticulationSensorCore;
class ArticulationCore;
class ArticulationSim;
class ArticulationSensorSim : public PxUserAllocated
{
PX_NOCOPY(ArticulationSensorSim)
public:
ArticulationSensorSim(Sc::ArticulationSensorCore& core, Sc::Scene& scene);
~ArticulationSensorSim();
const PxSpatialForce& getForces() const;
void setRelativePose(const PxTransform& relativePose);
void setFlag(PxU16 flag);
PX_FORCE_INLINE Sc::Scene& getScene() { return mScene; }
PX_FORCE_INLINE const Sc::Scene& getScene() const { return mScene; }
PX_FORCE_INLINE void setLowLevelIndex(const PxU32 llIndex) { mLLIndex = llIndex;}
PX_FORCE_INLINE PxU32 getLowLevelIndex() const { return mLLIndex; }
PX_FORCE_INLINE Sc::ArticulationSensorCore& getCore() { return mCore; }
PX_FORCE_INLINE const Sc::ArticulationSensorCore& getCore() const { return mCore; }
PX_FORCE_INLINE Dy::ArticulationSensor& getLLSensor() { return mLLSensor; }
Sc::Scene& mScene;
Sc::ArticulationSensorCore& mCore;
Sc::ArticulationSim* mArticulationSim;
Dy::ArticulationSensor mLLSensor;
PxU32 mLLIndex;
};
}
}
#endif //SC_ARTICULATION_SENSOR_SIM_H
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScInteraction.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 SC_INTERACTION_H
#define SC_INTERACTION_H
#include "foundation/Px.h"
#include "ScInteractionFlags.h"
#include "ScActorSim.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
namespace physx
{
#define PX_INVALID_INTERACTION_ACTOR_ID 0xffffffff
#define PX_INVALID_INTERACTION_SCENE_ID 0xffffffff
namespace Sc
{
struct InteractionType
{
enum Enum
{
eOVERLAP = 0, // corresponds to ShapeInteraction
eTRIGGER, // corresponds to TriggerInteraction
eMARKER, // corresponds to ElementInteractionMarker
eTRACKED_IN_SCENE_COUNT, // not a real type, interactions above this limit are tracked in the scene
eCONSTRAINTSHADER, // corresponds to ConstraintInteraction
eARTICULATION, // corresponds to ArticulationJointSim
eINVALID
};
};
// Interactions are used for connecting actors into activation groups. An interaction always connects exactly two actors.
// An interaction is implicitly active if at least one of the two actors it connects is active.
// PT: we need PxUserAllocated only for ArticulationJointSim, which for some reason doesn't follow the same design as the others.
// The others are allocated from pools in NphaseCore.
class Interaction : public PxUserAllocated
{
PX_NOCOPY(Interaction)
Interaction(ActorSim& actor0, ActorSim& actor1, InteractionType::Enum interactionType, PxU8 flags);
~Interaction() { PX_ASSERT(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST)); }
public:
// Interactions automatically register themselves in the actors here
PX_FORCE_INLINE void registerInActors();
// Interactions automatically unregister themselves from the actors here
PX_FORCE_INLINE void unregisterFromActors();
PX_FORCE_INLINE ActorSim& getActorSim0() const { return mActor0; }
PX_FORCE_INLINE ActorSim& getActorSim1() const { return mActor1; }
PX_FORCE_INLINE Scene& getScene() const { return mActor0.getScene(); }
PX_FORCE_INLINE InteractionType::Enum getType() const { return InteractionType::Enum(mInteractionType); }
PX_FORCE_INLINE PxU8 readInteractionFlag(PxU8 flag) const { return PxU8(mInteractionFlags & flag); }
PX_FORCE_INLINE void raiseInteractionFlag(InteractionFlag::Enum flag) { mInteractionFlags |= flag; }
PX_FORCE_INLINE void clearInteractionFlag(InteractionFlag::Enum flag) { mInteractionFlags &= ~flag; }
/**
\brief Mark the interaction as dirty. This will put the interaction into a list that is processed once per simulation step.
@see InteractionDirtyFlag
*/
PX_FORCE_INLINE void setDirty(PxU32 dirtyFlags);
/**
\brief Clear all flags that mark the interaction as dirty and optionally remove the interaction from the list of dirty interactions.
@see InteractionDirtyFlag
*/
/*PX_FORCE_INLINE*/ void setClean(bool removeFromList);
PX_FORCE_INLINE PxIntBool needsRefiltering() const { return (getDirtyFlags() & InteractionDirtyFlag::eFILTER_STATE); }
PX_FORCE_INLINE PxIntBool isElementInteraction() const;
PX_FORCE_INLINE void setInteractionId(PxU32 id) { mSceneId = id; }
PX_FORCE_INLINE PxU32 getInteractionId() const { return mSceneId; }
PX_FORCE_INLINE bool isRegistered() const { return mSceneId != PX_INVALID_INTERACTION_SCENE_ID; }
PX_FORCE_INLINE void setActorId(ActorSim* actor, PxU32 id);
PX_FORCE_INLINE PxU32 getActorId(const ActorSim* actor) const;
PX_FORCE_INLINE PxU8 getDirtyFlags() const { return mDirtyFlags; }
private:
void addToDirtyList();
void removeFromDirtyList();
ActorSim& mActor0;
ActorSim& mActor1;
// PT: TODO: merge the 6bits of the 3 PxU8s in the top bits of the 3 PxU32s
PxU32 mSceneId; // PT: TODO: merge this with mInteractionType
// PT: TODO: are those IDs even worth caching? Since the number of interactions per actor is (or should be) small,
// we could just do a linear search and save memory here...
PxU32 mActorId0; // PT: id of this interaction within mActor0's mInteractions array
PxU32 mActorId1; // PT: id of this interaction within mActor1's mInteractions array
protected:
const PxU8 mInteractionType; // PT: stored on a byte to save space, should be InteractionType enum, 5/6 bits needed here
PxU8 mInteractionFlags; // PT: 6 bits needed here, see InteractionFlag enum
PxU8 mDirtyFlags; // PT: 6 bits needed here, see InteractionDirtyFlag enum
PxU8 mPadding8;
};
} // namespace Sc
//////////////////////////////////////////////////////////////////////////
PX_FORCE_INLINE void Sc::Interaction::registerInActors()
{
mActor0.registerInteractionInActor(this);
mActor1.registerInteractionInActor(this);
}
PX_FORCE_INLINE void Sc::Interaction::unregisterFromActors()
{
mActor0.unregisterInteractionFromActor(this);
mActor1.unregisterInteractionFromActor(this);
}
PX_FORCE_INLINE void Sc::Interaction::setActorId(ActorSim* actor, PxU32 id)
{
PX_ASSERT(id != PX_INVALID_INTERACTION_ACTOR_ID);
PX_ASSERT(&mActor0 == actor || &mActor1 == actor);
if(&mActor0 == actor)
mActorId0 = id;
else
mActorId1 = id;
}
PX_FORCE_INLINE PxU32 Sc::Interaction::getActorId(const ActorSim* actor) const
{
PX_ASSERT(&mActor0 == actor || &mActor1 == actor);
return &mActor0 == actor ? mActorId0 : mActorId1;
}
PX_FORCE_INLINE PxIntBool Sc::Interaction::isElementInteraction() const
{
const PxIntBool res = readInteractionFlag(InteractionFlag::eRB_ELEMENT);
PX_ASSERT( (res &&
((getType() == InteractionType::eOVERLAP) ||
(getType() == InteractionType::eTRIGGER) ||
(getType() == InteractionType::eMARKER))) ||
(!res &&
((getType() == InteractionType::eCONSTRAINTSHADER) ||
(getType() == InteractionType::eARTICULATION))));
return res;
}
PX_FORCE_INLINE void Sc::Interaction::setDirty(PxU32 dirtyFlags)
{
PX_ASSERT(getType() != InteractionType::eARTICULATION);
mDirtyFlags |= PxTo8(dirtyFlags);
if(!readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST))
{
addToDirtyList();
raiseInteractionFlag(InteractionFlag::eIN_DIRTY_LIST);
}
}
//PX_FORCE_INLINE void Sc::Interaction::setClean(bool removeFromList)
//{
// if (readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST))
// {
// if (removeFromList) // if we process all dirty interactions anyway, then we can just clear the list at the end and save the work here.
// removeFromDirtyList();
// clearInteractionFlag(InteractionFlag::eIN_DIRTY_LIST);
// }
//
// mDirtyFlags = 0;
//}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScInteraction.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/Px.h"
#include "ScInteraction.h"
#include "ScNPhaseCore.h"
using namespace physx;
Sc::Interaction::Interaction(ActorSim& actor0, ActorSim& actor1, InteractionType::Enum type, PxU8 flags) :
mActor0 (actor0),
mActor1 (actor1),
mSceneId (PX_INVALID_INTERACTION_SCENE_ID),
mActorId0 (PX_INVALID_INTERACTION_ACTOR_ID),
mActorId1 (PX_INVALID_INTERACTION_ACTOR_ID),
mInteractionType (PxTo8(type)),
mInteractionFlags (flags),
mDirtyFlags (0)
{
PX_ASSERT_WITH_MESSAGE(&actor0.getScene() == &actor1.getScene(),"Cannot create an interaction between actors belonging to different scenes.");
PX_ASSERT(PxU32(type)<256); // PT: type is now stored on a byte
}
void Sc::Interaction::addToDirtyList()
{
getActorSim0().getScene().getNPhaseCore()->addToDirtyInteractionList(this);
}
void Sc::Interaction::removeFromDirtyList()
{
getActorSim0().getScene().getNPhaseCore()->removeFromDirtyInteractionList(this);
}
void Sc::Interaction::setClean(bool removeFromList)
{
if (readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST))
{
if (removeFromList) // if we process all dirty interactions anyway, then we can just clear the list at the end and save the work here.
removeFromDirtyList();
clearInteractionFlag(InteractionFlag::eIN_DIRTY_LIST);
}
mDirtyFlags = 0;
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScStaticSim.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 SC_STATIC_SIM_H
#define SC_STATIC_SIM_H
#include "ScRigidSim.h"
#include "ScStaticCore.h"
namespace physx
{
namespace Sc
{
class StaticSim : public RigidSim
{
//---------------------------------------------------------------------------------
// Construction, destruction & initialization
//---------------------------------------------------------------------------------
public:
StaticSim(Scene& scene, StaticCore& core) : RigidSim(scene, core) {}
~StaticSim() { getStaticCore().setSim(NULL); }
PX_FORCE_INLINE StaticCore& getStaticCore() const { return static_cast<StaticCore&>(getRigidCore()); }
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScContactStream.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 SC_CONTACT_STREAM_H
#define SC_CONTACT_STREAM_H
#include "foundation/Px.h"
#include "PxSimulationEventCallback.h"
#include "ScObjectIDTracker.h"
#include "ScRigidSim.h"
#include "ScStaticSim.h"
#include "ScBodySim.h"
namespace physx
{
class PxShape;
namespace Sc
{
class ActorPair;
// Internal counterpart of PxContactPair
struct ContactShapePair
{
public:
PxShape* shapes[2];
const PxU8* contactPatches;
const PxU8* contactPoints;
const PxReal* contactForces;
PxU32 requiredBufferSize;
PxU8 contactCount;
PxU8 patchCount;
PxU16 constraintStreamSize;
PxU16 flags;
PxU16 events;
PxU32 shapeID[2];
//26 (or 38 on 64bit)
};
PX_COMPILE_TIME_ASSERT(sizeof(ContactShapePair) == sizeof(PxContactPair));
struct ContactStreamManagerFlag
{
enum Enum
{
/**
\brief Need to test stream for shapes that were removed from the actor/scene
Usually this is the case when a shape gets removed from the scene, however, other operations that remove the
broadphase volume of a pair object have to be considered as well since the shape might get removed later after such an
operation. The scenarios to consider are:
\li shape gets removed (this includes raising PxActorFlag::eDISABLE_SIMULATION)
\li shape switches to eSCENE_QUERY_SHAPE only
\li shape switches to eTRIGGER_SHAPE
\li resetFiltering()
\li actor gets removed from an aggregate
*/
eTEST_FOR_REMOVED_SHAPES = (1<<0),
/**
\brief Invalid stream memory not allocated
*/
eINVALID_STREAM = (1<<1),
/**
\brief Incomplete stream will be reported
*/
eINCOMPLETE_STREAM = (1<<2),
/**
\brief The stream contains extra data with PxContactPairVelocity items where the post solver velocity needs to get written to.
Only valid for discrete collision (in CCD the post response velocity is available immediately).
*/
eNEEDS_POST_SOLVER_VELOCITY = (1<<3),
/**
\brief Marker for the next available free flag
*/
eNEXT_FREE_FLAG = (1<<4)
};
};
struct ContactStreamHeader
{
PxU16 contactPass; // marker for extra data to know when a new collison pass started (discrete collision -> CCD pass 1 -> CCD pass 2 -> ...)
PxU16 pad; // to keep the stream 4byte aligned
};
/**
\brief Contact report logic and data management.
The internal contact report stream has the following format:
ContactStreamHeader | PxContactPairIndex0 | (PxContactPairPose0, PxContactPairVelocity0) | ... | PxContactPairIndexN | (PxContactPairPoseN, PxContactPairVelocityN) | (unused memory up to maxExtraDataSize ) |
PxContactPair0 | ... | PxContactPairM | (unsued pairs up to maxPairCount)
*/
class ContactStreamManager
{
public:
PX_FORCE_INLINE ContactStreamManager() : maxPairCount(0), flags_and_maxExtraDataBlocks(0) {}
PX_FORCE_INLINE ~ContactStreamManager() {}
PX_FORCE_INLINE void reset();
PX_FORCE_INLINE PxU16 getFlags() const;
PX_FORCE_INLINE void raiseFlags(PxU16 flags);
PX_FORCE_INLINE void clearFlags(PxU16 flags);
PX_FORCE_INLINE PxU32 getMaxExtraDataSize() const;
PX_FORCE_INLINE void setMaxExtraDataSize(PxU32 size); // size in bytes (will translate into blocks internally)
PX_FORCE_INLINE Sc::ContactShapePair* getShapePairs(PxU8* contactReportPairData) const;
PX_FORCE_INLINE static void convertDeletedShapesInContactStream(ContactShapePair*, PxU32 pairCount, const ObjectIDTracker&);
PX_FORCE_INLINE static PxU32 computeExtraDataBlockCount(PxU32 extraDataSize);
PX_FORCE_INLINE static PxU32 computeExtraDataBlockSize(PxU32 extraDataSize);
PX_FORCE_INLINE static PxU16 computeContactReportExtraDataSize(PxU32 extraDataFlags, bool addHeader);
PX_FORCE_INLINE static void fillInContactReportExtraData(PxContactPairVelocity*, PxU32 index, const ActorSim&, bool isCCDPass);
PX_FORCE_INLINE static void fillInContactReportExtraData(PxContactPairPose*, PxU32 index, const ActorSim&, bool isCCDPass, const bool useCurrentTransform);
PX_FORCE_INLINE void fillInContactReportExtraData(PxU8* stream, PxU32 extraDataFlags, const ActorSim&, const ActorSim&, PxU32 ccdPass, const bool useCurrentTransform, PxU32 pairIndex, PxU32 sizeOffset);
PX_FORCE_INLINE void setContactReportPostSolverVelocity(PxU8* stream, const ActorSim&, const ActorSim&);
PxU32 bufferIndex; // marks the start of the shape pair stream of the actor pair (byte offset with respect to global contact buffer stream)
PxU16 maxPairCount; // used to reserve the same amount of memory as in the last frame (as an initial guess)
PxU16 currentPairCount; // number of shape pairs stored in the buffer
PxU16 extraDataSize; // size of the extra data section in the stream
private:
PxU16 flags_and_maxExtraDataBlocks; // used to reserve the same amount of memory as in the last frame (as an initial guess)
public:
static const PxU32 sExtraDataBlockSizePow2 = 4; // extra data gets allocated as a multiple of 2^sExtraDataBlockSizePow2 to keep memory low of this struct.
static const PxU32 sFlagMask = (ContactStreamManagerFlag::eNEXT_FREE_FLAG - 1);
static const PxU32 sMaxExtraDataShift = 4; // shift necessary to extract the maximum number of blocks allocated for extra data
PX_COMPILE_TIME_ASSERT(ContactStreamManagerFlag::eNEXT_FREE_FLAG == (1 << sMaxExtraDataShift));
};
} // namespace Sc
PX_FORCE_INLINE void Sc::ContactStreamManager::reset()
{
currentPairCount = 0;
extraDataSize = 0;
flags_and_maxExtraDataBlocks &= ~sFlagMask;
}
PX_FORCE_INLINE PxU16 Sc::ContactStreamManager::getFlags() const
{
return (flags_and_maxExtraDataBlocks & sFlagMask);
}
PX_FORCE_INLINE void Sc::ContactStreamManager::raiseFlags(PxU16 flags)
{
PX_ASSERT(flags < ContactStreamManagerFlag::eNEXT_FREE_FLAG);
flags_and_maxExtraDataBlocks |= flags;
}
PX_FORCE_INLINE void Sc::ContactStreamManager::clearFlags(PxU16 flags)
{
PX_ASSERT(flags < ContactStreamManagerFlag::eNEXT_FREE_FLAG);
PxU16 tmpFlags = getFlags();
tmpFlags &= ~flags;
flags_and_maxExtraDataBlocks &= ~sFlagMask;
raiseFlags(tmpFlags);
}
PX_FORCE_INLINE PxU32 Sc::ContactStreamManager::getMaxExtraDataSize() const
{
return PxU32((flags_and_maxExtraDataBlocks >> sMaxExtraDataShift) << sExtraDataBlockSizePow2);
}
PX_FORCE_INLINE void Sc::ContactStreamManager::setMaxExtraDataSize(PxU32 size)
{
PxU32 nbBlocks = computeExtraDataBlockCount(size);
flags_and_maxExtraDataBlocks = PxTo16((flags_and_maxExtraDataBlocks & sFlagMask) | (nbBlocks << sMaxExtraDataShift));
}
PX_FORCE_INLINE Sc::ContactShapePair* Sc::ContactStreamManager::getShapePairs(PxU8* contactReportPairData) const
{
return reinterpret_cast<Sc::ContactShapePair*>(contactReportPairData + getMaxExtraDataSize());
}
PX_FORCE_INLINE void Sc::ContactStreamManager::convertDeletedShapesInContactStream(ContactShapePair* shapePairs, PxU32 pairCount, const ObjectIDTracker& tracker)
{
for(PxU32 i=0; i < pairCount; i++)
{
ContactShapePair& csp = shapePairs[i];
PxU32 shape0ID = csp.shapeID[0];
PxU32 shape1ID = csp.shapeID[1];
PxU16 flags = csp.flags;
PX_COMPILE_TIME_ASSERT(sizeof(flags) == sizeof((reinterpret_cast<ContactShapePair*>(0))->flags));
if (tracker.isDeletedID(shape0ID))
flags |= PxContactPairFlag::eREMOVED_SHAPE_0;
if (tracker.isDeletedID(shape1ID))
flags |= PxContactPairFlag::eREMOVED_SHAPE_1;
csp.flags = flags;
}
}
PX_FORCE_INLINE PxU32 Sc::ContactStreamManager::computeExtraDataBlockCount(PxU32 extraDataSize_)
{
PxU32 nbBlocks;
if (extraDataSize_ & ((1 << sExtraDataBlockSizePow2) - 1)) // not a multiple of block size -> need one block more
nbBlocks = (extraDataSize_ >> sExtraDataBlockSizePow2) + 1;
else
nbBlocks = (extraDataSize_ >> sExtraDataBlockSizePow2);
return nbBlocks;
}
PX_FORCE_INLINE PxU32 Sc::ContactStreamManager::computeExtraDataBlockSize(PxU32 extraDataSize_)
{
return (computeExtraDataBlockCount(extraDataSize_) << sExtraDataBlockSizePow2);
}
PX_FORCE_INLINE PxU16 Sc::ContactStreamManager::computeContactReportExtraDataSize(PxU32 extraDataFlags, bool addHeader)
{
PX_ASSERT(extraDataFlags);
PxU16 extraDataSize_ = sizeof(PxContactPairIndex);
if (extraDataFlags & PxPairFlag::ePRE_SOLVER_VELOCITY)
extraDataSize_ += sizeof(PxContactPairVelocity);
if (extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY)
extraDataSize_ += sizeof(PxContactPairVelocity);
if (extraDataFlags & PxPairFlag::eCONTACT_EVENT_POSE)
extraDataSize_ += sizeof(PxContactPairPose);
if (addHeader)
extraDataSize_ += sizeof(ContactStreamHeader);
return extraDataSize_;
}
PX_FORCE_INLINE void Sc::ContactStreamManager::fillInContactReportExtraData(PxContactPairVelocity* cpVel, PxU32 index, const ActorSim& rs, bool isCCDPass)
{
if (rs.getActorType() != PxActorType::eRIGID_STATIC)
{
const BodySim& bs = static_cast<const BodySim&>(rs);
if ((!isCCDPass) || (cpVel->type == PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY))
{
const BodyCore& bc = bs.getBodyCore();
cpVel->linearVelocity[index] = bc.getLinearVelocity();
cpVel->angularVelocity[index] = bc.getAngularVelocity();
}
else
{
PX_ASSERT(cpVel->type == PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY);
const Cm::SpatialVector& vel = bs.getLowLevelBody().getPreSolverVelocities();
cpVel->linearVelocity[index] = vel.linear;
cpVel->angularVelocity[index] = vel.angular;
}
}
else
{
cpVel->linearVelocity[index] = PxVec3(0.0f);
cpVel->angularVelocity[index] = PxVec3(0.0f);
}
}
PX_FORCE_INLINE void Sc::ContactStreamManager::fillInContactReportExtraData(PxContactPairPose* cpPose, PxU32 index, const ActorSim& rs, bool isCCDPass, const bool useCurrentTransform)
{
if(rs.getActorType() != PxActorType::eRIGID_STATIC)
{
const BodySim& bs = static_cast<const BodySim&>(rs);
const BodyCore& bc = bs.getBodyCore();
const PxTransform& src = (!isCCDPass && useCurrentTransform) ? bc.getBody2World() : bs.getLowLevelBody().getLastCCDTransform();
// PT:: tag: scalar transform*transform
cpPose->globalPose[index] = src * bc.getBody2Actor().getInverse();
}
else
{
const StaticSim& ss = static_cast<const StaticSim&>(rs);
const StaticCore& sc = ss.getStaticCore();
cpPose->globalPose[index] = sc.getActor2World();
}
}
PX_FORCE_INLINE void Sc::ContactStreamManager::fillInContactReportExtraData(PxU8* stream, PxU32 extraDataFlags, const ActorSim& rs0, const ActorSim& rs1, PxU32 ccdPass, const bool useCurrentTransform,
PxU32 pairIndex, PxU32 sizeOffset)
{
ContactStreamHeader* strHeader = reinterpret_cast<ContactStreamHeader*>(stream);
strHeader->contactPass = PxTo16(ccdPass);
stream += sizeOffset;
PxU8* edStream = stream;
bool isCCDPass = (ccdPass != 0);
{
PxContactPairIndex* cpIndex = reinterpret_cast<PxContactPairIndex*>(edStream);
cpIndex->type = PxContactPairExtraDataType::eCONTACT_PAIR_INDEX;
cpIndex->index = PxTo16(pairIndex);
edStream += sizeof(PxContactPairIndex);
PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream)));
}
// Important: make sure this one is the first after the PxContactPairIndex item for discrete contacts as it needs to get filled in before the reports get sent
// (post solver velocity is not available when it gets created)
if (extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY)
{
PxContactPairVelocity* cpVel = reinterpret_cast<PxContactPairVelocity*>(edStream);
cpVel->type = PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY;
edStream += sizeof(PxContactPairVelocity);
if (!isCCDPass)
raiseFlags(ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY); // don't know the post solver velocity yet
else
{
ContactStreamManager::fillInContactReportExtraData(cpVel, 0, rs0, true);
ContactStreamManager::fillInContactReportExtraData(cpVel, 1, rs1, true);
}
PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream)));
}
if (extraDataFlags & PxPairFlag::ePRE_SOLVER_VELOCITY)
{
PxContactPairVelocity* cpVel = reinterpret_cast<PxContactPairVelocity*>(edStream);
cpVel->type = PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY;
ContactStreamManager::fillInContactReportExtraData(cpVel, 0, rs0, isCCDPass);
ContactStreamManager::fillInContactReportExtraData(cpVel, 1, rs1, isCCDPass);
edStream += sizeof(PxContactPairVelocity);
PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream)));
}
if (extraDataFlags & PxPairFlag::eCONTACT_EVENT_POSE)
{
PxContactPairPose* cpPose = reinterpret_cast<PxContactPairPose*>(edStream);
cpPose->type = PxContactPairExtraDataType::eCONTACT_EVENT_POSE;
ContactStreamManager::fillInContactReportExtraData(cpPose, 0, rs0, isCCDPass, useCurrentTransform);
ContactStreamManager::fillInContactReportExtraData(cpPose, 1, rs1, isCCDPass, useCurrentTransform);
edStream += sizeof(PxContactPairPose);
PX_ASSERT(edStream <= reinterpret_cast<PxU8*>(getShapePairs(stream)));
}
extraDataSize = PxTo16(sizeOffset + PxU32(edStream - stream));
}
PX_FORCE_INLINE void Sc::ContactStreamManager::setContactReportPostSolverVelocity(PxU8* stream, const ActorSim& rs0, const ActorSim& rs1)
{
PX_ASSERT(extraDataSize > (sizeof(ContactStreamHeader) + sizeof(PxContactPairIndex)));
PxContactPairVelocity* cpVel = reinterpret_cast<PxContactPairVelocity*>(stream + sizeof(ContactStreamHeader) + sizeof(PxContactPairIndex));
PX_ASSERT(cpVel->type == PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY);
fillInContactReportExtraData(cpVel, 0, rs0, false);
fillInContactReportExtraData(cpVel, 1, rs1, false);
clearFlags(ContactStreamManagerFlag::eNEEDS_POST_SOLVER_VELOCITY);
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScNPhaseCore.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 SC_NPHASE_CORE_H
#define SC_NPHASE_CORE_H
#include "foundation/PxHash.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxHashSet.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxMutex.h"
#include "foundation/PxAtomic.h"
#include "PxPhysXConfig.h"
#include "foundation/PxPool.h"
#include "PxSimulationEventCallback.h"
#include "ScTriggerPairs.h"
#include "ScScene.h"
#include "ScContactReportBuffer.h"
namespace physx
{
namespace Bp
{
struct AABBOverlap;
struct BroadPhasePair;
}
namespace Sc
{
class ActorSim;
class ElementSim;
class ShapeSimBase;
class Interaction;
class ElementSimInteraction;
class ElementInteractionMarker;
class TriggerInteraction;
class ShapeInteraction;
class ActorPair;
class ActorPairReport;
class ActorPairContactReportData;
struct ContactShapePair;
class NPhaseContext;
class ContactStreamManager;
struct FilterPair;
class FilterPairManager;
class ActorSim;
class TriggerContactTask;
struct PairReleaseFlag
{
enum Enum
{
eRUN_LOST_TOUCH_LOGIC = (1 << 0), // run the lost-touch-logic for a pair that gets removed.
eWAKE_ON_LOST_TOUCH = (1 << 1) // a pair that lost touch should check whether the actors should get woken up
};
};
/*
NPhaseCore encapsulates the near phase processing to allow multiple implementations(eg threading and non threaded).
The broadphase inserts shape pairs into the NPhaseCore, which are then processed into contact point streams.
Pairs can then be processed into AxisConstraints by the GroupSolveCore.
*/
struct BodyPairKey
{
PX_FORCE_INLINE BodyPairKey(PxU32 sim0, PxU32 sim1) : mSim0(sim0), mSim1(sim1) {}
const PxU32 mSim0;
const PxU32 mSim1;
PX_FORCE_INLINE bool operator == (const BodyPairKey& pair) const { return mSim0 == pair.mSim0 && mSim1 == pair.mSim1; }
};
PX_INLINE PxU32 PxComputeHash(const BodyPairKey& key)
{
const PxU32 add0 = key.mSim0;
const PxU32 add1 = key.mSim1;
const PxU32 base = PxU32((add0 & 0xFFFF) | (add1 << 16));
return physx::PxComputeHash(base);
}
struct ElementSimKey
{
PxU32 mID0;
PxU32 mID1;
ElementSimKey() : mID0(0xffffffff), mID1(0xffffffff)
{}
ElementSimKey(PxU32 id0, PxU32 id1)
{
if(id0 > id1)
PxSwap(id0, id1);
mID0 = id0;
mID1 = id1;
}
PX_FORCE_INLINE bool operator == (const ElementSimKey& pair) const { return mID0 == pair.mID0 && mID1 == pair.mID1; }
};
PX_INLINE PxU32 PxComputeHash(const ElementSimKey& key)
{
const PxU64 base = PxU64(key.mID0) | (PxU64(key.mID1) << 32);
return physx::PxComputeHash(base);
}
class ContactReportAllocationManager
{
PxU8* mBuffer;
PxU32 mBufferSize;
PxU32 mCurrentBufferIndex;
PxU32 mCurrentOffset;
ContactReportBuffer& mReportBuffer;
PxMutex& mMutex;
const PxU32 mBuferBlockSize;
PX_NOCOPY(ContactReportAllocationManager)
public:
ContactReportAllocationManager(ContactReportBuffer& buffer, PxMutex& mutex, const PxU32 bufferBlockSize = 16384) : mBuffer(NULL), mBufferSize(0), mCurrentBufferIndex(0),
mCurrentOffset(0), mReportBuffer(buffer), mMutex(mutex), mBuferBlockSize(bufferBlockSize)
{
}
PxU8* allocate(PxU32 size, PxU32& index, PxU32 alignment = 16u)
{
//(1) fix up offsets...
const PxU32 pad = ((mCurrentBufferIndex + alignment - 1)&~(alignment - 1)) - mCurrentBufferIndex;
PxU32 currOffset = mCurrentOffset + pad;
if ((currOffset + size) > mBufferSize)
{
const PxU32 allocSize = PxMax(size, mBuferBlockSize);
mMutex.lock();
mBuffer = mReportBuffer.allocateNotThreadSafe(allocSize, mCurrentBufferIndex, alignment);
mCurrentOffset = currOffset = 0;
mBufferSize = allocSize;
mMutex.unlock();
}
PxU8* ret = mBuffer + currOffset;
index = mCurrentBufferIndex + currOffset;
mCurrentOffset = currOffset + size;
return ret;
}
};
class TriggerProcessingContext
{
public:
TriggerProcessingContext()
: mTmpTriggerProcessingBlock(NULL)
, mTmpTriggerPairCount(0)
{
}
bool initialize(TriggerInteraction**, PxU32 pairCount, PxcScratchAllocator&);
void deinitialize(PxcScratchAllocator&);
PX_FORCE_INLINE TriggerInteraction* const* getTriggerInteractions() const
{
return reinterpret_cast<TriggerInteraction**>(mTmpTriggerProcessingBlock);
}
PX_FORCE_INLINE PxU32 getTriggerInteractionCount() const
{
return mTmpTriggerPairCount;
}
PX_FORCE_INLINE TriggerContactTask* getTriggerContactTasks()
{
const PxU32 offset = mTmpTriggerPairCount * sizeof(TriggerInteraction*);
return reinterpret_cast<TriggerContactTask*>(mTmpTriggerProcessingBlock + offset);
}
PX_FORCE_INLINE PxMutex& getTriggerWriteBackLock()
{
return mTriggerWriteBackLock;
}
private:
PxU8* mTmpTriggerProcessingBlock; // temporary memory block to process trigger pairs in parallel
// (see comment in Sc::Scene::postIslandGen too)
PxU32 mTmpTriggerPairCount;
PxMutex mTriggerWriteBackLock;
};
class NPhaseCore : public PxUserAllocated
{
PX_NOCOPY(NPhaseCore)
public:
NPhaseCore(Scene& scene, const PxSceneDesc& desc);
~NPhaseCore();
ElementSimInteraction* findInteraction(const ElementSim* element0, const ElementSim* element1);
void onTriggerOverlapCreated(const Bp::AABBOverlap* PX_RESTRICT pairs, PxU32 pairCount);
void runOverlapFilters( PxU32 nbToProcess, const Bp::AABBOverlap* PX_RESTRICT pairs, FilterInfo* PX_RESTRICT filterInfo,
PxU32& nbToKeep, PxU32& nbToSuppress, PxU32* PX_RESTRICT keepMap);
void onOverlapRemoved(ElementSim* volume0, ElementSim* volume1, PxU32 ccdPass, void* elemSim, PxsContactManagerOutputIterator& outputs);
void onVolumeRemoved(ElementSim* volume, PxU32 flags, PxsContactManagerOutputIterator& outputs);
void managerNewTouch(Sc::ShapeInteraction& interaction);
PxU32 getDefaultContactReportStreamBufferSize() const;
void fireCustomFilteringCallbacks(PxsContactManagerOutputIterator& outputs);
void addToDirtyInteractionList(Interaction* interaction);
void removeFromDirtyInteractionList(Interaction* interaction);
void updateDirtyInteractions(PxsContactManagerOutputIterator& outputs);
/**
\brief Allocate buffers for trigger overlap test.
See comment in Sc::Scene::postIslandGen for why this is split up into multiple parts.
\param[in] continuation The task to run after trigger processing.
\return The concluding trigger processing task if there is work to do, else NULL.
*/
PxBaseTask* prepareForTriggerInteractionProcessing(PxBaseTask* continuation);
// Perform trigger overlap tests.
void processTriggerInteractions(PxBaseTask& continuation);
// Deactivate trigger interactions if possible, free buffers from overlap tests and clean up.
// See comment in Sc::Scene::postIslandGen for why this is split up into multiple parts.
void concludeTriggerInteractionProcessing(PxBaseTask* continuation);
// Check candidates for persistent touch contact events and create those events if necessary.
void processPersistentContactEvents(PxsContactManagerOutputIterator& outputs);
PX_FORCE_INLINE void addToContactReportActorPairSet(ActorPairReport* pair) { mContactReportActorPairSet.pushBack(pair); }
void clearContactReportActorPairs(bool shrinkToZero);
PX_FORCE_INLINE PxU32 getNbContactReportActorPairs() const { return mContactReportActorPairSet.size(); }
PX_FORCE_INLINE ActorPairReport* const* getContactReportActorPairs() const { return mContactReportActorPairSet.begin(); }
void addToPersistentContactEventPairs(ShapeInteraction*);
void addToPersistentContactEventPairsDelayed(ShapeInteraction*);
void removeFromPersistentContactEventPairs(ShapeInteraction*);
PX_FORCE_INLINE PxU32 getCurrentPersistentContactEventPairCount() const { return mNextFramePersistentContactEventPairIndex; }
PX_FORCE_INLINE ShapeInteraction* const* getCurrentPersistentContactEventPairs() const { return mPersistentContactEventPairList.begin(); }
PX_FORCE_INLINE PxU32 getAllPersistentContactEventPairCount() const { return mPersistentContactEventPairList.size(); }
PX_FORCE_INLINE ShapeInteraction* const* getAllPersistentContactEventPairs() const { return mPersistentContactEventPairList.begin(); }
PX_FORCE_INLINE void preparePersistentContactEventListForNextFrame();
void addToForceThresholdContactEventPairs(ShapeInteraction*);
void removeFromForceThresholdContactEventPairs(ShapeInteraction*);
PX_FORCE_INLINE PxU32 getForceThresholdContactEventPairCount() const { return mForceThresholdContactEventPairList.size(); }
PX_FORCE_INLINE ShapeInteraction* const* getForceThresholdContactEventPairs() const { return mForceThresholdContactEventPairList.begin(); }
PX_FORCE_INLINE PxU8* getContactReportPairData(const PxU32& bufferIndex) const { return mContactReportBuffer.getData(bufferIndex); }
PxU8* reserveContactReportPairData(PxU32 pairCount, PxU32 extraDataSize, PxU32& bufferIndex, ContactReportAllocationManager* alloc = NULL);
PxU8* resizeContactReportPairData(PxU32 pairCount, PxU32 extraDataSize, Sc::ContactStreamManager& csm);
PX_FORCE_INLINE void clearContactReportStream() { mContactReportBuffer.reset(); } // Do not free memory at all
PX_FORCE_INLINE void freeContactReportStreamMemory() { mContactReportBuffer.flush(); }
ActorPairContactReportData* createActorPairContactReportData();
void releaseActorPairContactReportData(ActorPairContactReportData* data);
void registerInteraction(ElementSimInteraction* interaction);
void unregisterInteraction(ElementSimInteraction* interaction);
ElementSimInteraction* createRbElementInteraction(const FilterInfo& fInfo, ShapeSimBase& s0, ShapeSimBase& s1, PxsContactManager* contactManager, Sc::ShapeInteraction* shapeInteraction,
Sc::ElementInteractionMarker* interactionMarker, bool isTriggerPair);
void lockReports() { mReportAllocLock.lock(); }
void unlockReports() { mReportAllocLock.unlock(); }
private:
void callPairLost(const ShapeSimBase& s0, const ShapeSimBase& s1, bool objVolumeRemoved);
ElementSimInteraction* createTriggerElementInteraction(ShapeSimBase& s0, ShapeSimBase& s1);
// removedElement: points to the removed element (that is, the BP volume wrapper), if a pair gets removed or loses touch due to a removed element.
// NULL if not triggered by a removed element.
//
void releaseElementPair(ElementSimInteraction* pair, PxU32 flags, ElementSim* removedElement, PxU32 ccdPass, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs);
void lostTouchReports(ShapeInteraction* pair, PxU32 flags, ElementSim* removedElement, PxU32 ccdPass, PxsContactManagerOutputIterator& outputs);
ShapeInteraction* createShapeInteraction(ShapeSimBase& s0, ShapeSimBase& s1, PxPairFlags pairFlags, PxsContactManager* contactManager, Sc::ShapeInteraction* shapeInteraction);
TriggerInteraction* createTriggerInteraction(ShapeSimBase& s0, ShapeSimBase& s1, PxPairFlags triggerFlags);
ElementInteractionMarker* createElementInteractionMarker(ElementSim& e0, ElementSim& e1, ElementInteractionMarker* marker);
//------------- Filtering -------------
ElementSimInteraction* refilterInteraction(ElementSimInteraction* pair, const FilterInfo* filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs);
//-------------------------------------
ElementSimInteraction* convert(ElementSimInteraction* pair, InteractionType::Enum type, FilterInfo& filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs);
ActorPair* findActorPair(ShapeSimBase* s0, ShapeSimBase* s1, PxIntBool isReportPair);
PX_FORCE_INLINE void destroyActorPairReport(ActorPairReport&);
// Pooling
Scene& mOwnerScene;
PxArray<ActorPairReport*> mContactReportActorPairSet;
PxArray<ShapeInteraction*> mPersistentContactEventPairList; // Pairs which request events which do not get triggered by the sdk and thus need to be tested actively every frame.
// May also contain force threshold event pairs (see mForceThresholdContactEventPairList)
// This list is split in two, the elements in front are for the current frame, the elements at the
// back will get added next frame.
PxU32 mNextFramePersistentContactEventPairIndex; // start index of the pairs which need to get added to the persistent list for next frame
PxArray<ShapeInteraction*> mForceThresholdContactEventPairList; // Pairs which request force threshold contact events. A pair is only in this list if it does have contact.
// Note: If a pair additionally requests PxPairFlag::eNOTIFY_TOUCH_PERSISTS events, then it
// goes into mPersistentContactEventPairList instead. This allows to share the list index.
// data layout:
// ContactActorPair0_ExtraData, ContactShapePair0_0, ContactShapePair0_1, ... ContactShapePair0_N,
// ContactActorPair1_ExtraData, ContactShapePair1_0, ...
//
ContactReportBuffer mContactReportBuffer; // Shape pair information for contact reports
PxCoalescedHashSet<Interaction*> mDirtyInteractions;
// Pools
PxPool<ActorPair> mActorPairPool;
PxPool<ActorPairReport> mActorPairReportPool;
PxPool<ShapeInteraction> mShapeInteractionPool;
PxPool<TriggerInteraction> mTriggerInteractionPool;
PxPool<ActorPairContactReportData> mActorPairContactReportDataPool;
PxPool<ElementInteractionMarker> mInteractionMarkerPool;
Cm::DelegateTask<Sc::NPhaseCore, &Sc::NPhaseCore::concludeTriggerInteractionProcessing> mConcludeTriggerInteractionProcessingTask;
TriggerProcessingContext mTriggerProcessingContext;
PxHashMap<BodyPairKey, ActorPair*> mActorPairMap;
PxHashMap<ElementSimKey, ElementSimInteraction*> mElementSimMap;
PxMutex mBufferAllocLock;
PxMutex mReportAllocLock;
friend class Sc::Scene;
friend class Sc::ShapeInteraction;
};
struct FilteringContext
{
PX_NOCOPY(FilteringContext)
public:
FilteringContext(const Sc::Scene& scene) :
mFilterShader (scene.getFilterShaderFast()),
mFilterShaderData (scene.getFilterShaderDataFast()),
mFilterShaderDataSize (scene.getFilterShaderDataSizeFast()),
mFilterCallback (scene.getFilterCallbackFast()),
mKineKineFilteringMode (scene.getKineKineFilteringMode()),
mStaticKineFilteringMode(scene.getStaticKineFilteringMode())
{
}
PxSimulationFilterShader mFilterShader;
const void* mFilterShaderData;
PxU32 mFilterShaderDataSize;
PxSimulationFilterCallback* mFilterCallback;
const PxPairFilteringMode::Enum mKineKineFilteringMode;
const PxPairFilteringMode::Enum mStaticKineFilteringMode;
};
} // namespace Sc
PX_FORCE_INLINE void Sc::NPhaseCore::preparePersistentContactEventListForNextFrame()
{
// reports have been processed -> "activate" next frame candidates for persistent contact events
mNextFramePersistentContactEventPairIndex = mPersistentContactEventPairList.size();
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeInteraction.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 "ScShapeInteraction.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScParticleSystemSim.h"
#endif
using namespace physx;
Sc::ShapeInteraction::ShapeInteraction(ShapeSimBase& s1, ShapeSimBase& s2, PxPairFlags pairFlags, PxsContactManager* contactManager) :
ElementSimInteraction (s1, s2, InteractionType::eOVERLAP, InteractionFlag::eRB_ELEMENT|InteractionFlag::eFILTERABLE),
mActorPair (NULL),
mManager (NULL),
mContactReportStamp (PX_INVALID_U32),
mReportPairIndex (INVALID_REPORT_PAIR_ID),
mEdgeIndex (IG_INVALID_EDGE),
mReportStreamIndex (0)
{
mFlags = 0;
// The PxPairFlags get stored in the SipFlag, make sure any changes get noticed
PX_COMPILE_TIME_ASSERT(PxPairFlag::eSOLVE_CONTACT == (1<<0));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eMODIFY_CONTACTS == (1<<1));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_FOUND == (1<<2));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_PERSISTS == (1<<3));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_LOST == (1<<4));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_CCD == (1<<5));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND == (1<<6));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS == (1<<7));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST == (1<<8));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_CONTACT_POINTS == (1<<9));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eDETECT_DISCRETE_CONTACT == (1<<10));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eDETECT_CCD_CONTACT == (1<<11));
PX_COMPILE_TIME_ASSERT(PxPairFlag::ePRE_SOLVER_VELOCITY == (1<<12));
PX_COMPILE_TIME_ASSERT(PxPairFlag::ePOST_SOLVER_VELOCITY == (1<<13));
PX_COMPILE_TIME_ASSERT(PxPairFlag::eCONTACT_EVENT_POSE == (1<<14));
PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eSOLVE_CONTACT) == PxPairFlag::eSOLVE_CONTACT);
PX_COMPILE_TIME_ASSERT((PxPairFlag::eSOLVE_CONTACT | PAIR_FLAGS_MASK) == PAIR_FLAGS_MASK);
PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eCONTACT_EVENT_POSE) == PxPairFlag::eCONTACT_EVENT_POSE);
PX_COMPILE_TIME_ASSERT((PxPairFlag::eCONTACT_EVENT_POSE | PAIR_FLAGS_MASK) == PAIR_FLAGS_MASK);
setPairFlags(pairFlags);
//Add a fresh edge to the island manager.
Scene& scene = getScene();
//Sc::BodySim* bs0 = getShape0().getBodySim();
//Sc::BodySim* bs1 = getShape1().getBodySim();
Sc::ActorSim& bs0 = getShape0().getActor();
Sc::ActorSim& bs1 = getShape1().getActor();
updateFlags(scene, bs0, bs1, pairFlags);
if(contactManager == NULL)
{
PxNodeIndex indexA, indexB;
//if(bs0) // the first shape always belongs to a dynamic body (we assert for this above)
{
indexA = bs0.getNodeIndex();
bs0.registerCountedInteraction();
}
if(!bs1.isStaticRigid())
{
indexB = bs1.getNodeIndex();
bs1.registerCountedInteraction();
}
IG::SimpleIslandManager* simpleIslandManager = scene.getSimpleIslandManager();
const PxActorType::Enum actorTypeLargest = PxMax(bs0.getActorType(), bs1.getActorType());
IG::Edge::EdgeType type = IG::Edge::eCONTACT_MANAGER;
#if PX_SUPPORT_GPU_PHYSX
if (actorTypeLargest == PxActorType::eSOFTBODY)
type = IG::Edge::eSOFT_BODY_CONTACT;
if (actorTypeLargest == PxActorType::eFEMCLOTH)
type = IG::Edge::eFEM_CLOTH_CONTACT;
else if (isParticleSystem(actorTypeLargest))
type = IG::Edge::ePARTICLE_SYSTEM_CONTACT;
else if (actorTypeLargest == PxActorType::eHAIRSYSTEM)
type = IG::Edge::eHAIR_SYSTEM_CONTACT;
#endif
mEdgeIndex = simpleIslandManager->addContactManager(NULL, indexA, indexB, this, type);
{
const bool active = onActivate(contactManager);
registerInActors();
scene.registerInteraction(this, active);
}
//If it is a soft body or particle overlap, treat it as a contact for now (we can hook up touch found/lost events later maybe)
if (actorTypeLargest > PxActorType::eARTICULATION_LINK)
simpleIslandManager->setEdgeConnected(mEdgeIndex, type);
}
else
{
onActivate(contactManager);
}
}
Sc::ShapeInteraction::~ShapeInteraction()
{
Sc::ActorSim* body0 = &getShape0().getActor();
Sc::ActorSim* body1 = &getShape1().getActor();
body0->unregisterCountedInteraction();
if (body1)
body1->unregisterCountedInteraction();
if(mManager)
destroyManager();
if(mEdgeIndex != IG_INVALID_EDGE)
{
Scene& scene = getScene();
scene.getSimpleIslandManager()->removeConnection(mEdgeIndex);
mEdgeIndex = IG_INVALID_EDGE;
scene.unregisterInteraction(this);
}
// This will remove the interaction from the actors list, which will prevent
// update calls to this actor because of Body::wakeUp below.
unregisterFromActors();
if(mReportPairIndex != INVALID_REPORT_PAIR_ID)
removeFromReportPairList();
}
void Sc::ShapeInteraction::clearIslandGenData()
{
if(mEdgeIndex != IG_INVALID_EDGE)
{
Scene& scene = getScene();
scene.getSimpleIslandManager()->removeConnection(mEdgeIndex);
mEdgeIndex = IG_INVALID_EDGE;
}
}
PX_FORCE_INLINE void Sc::ShapeInteraction::processReportPairOnActivate()
{
PX_ASSERT(isReportPair());
PX_ASSERT(mReportPairIndex == INVALID_REPORT_PAIR_ID);
if(readFlag(WAS_IN_PERSISTENT_EVENT_LIST))
{
getScene().getNPhaseCore()->addToPersistentContactEventPairs(this);
mFlags &= ~WAS_IN_PERSISTENT_EVENT_LIST;
}
}
PX_FORCE_INLINE void Sc::ShapeInteraction::processReportPairOnDeactivate()
{
PX_ASSERT(isReportPair());
PX_ASSERT(mReportPairIndex != INVALID_REPORT_PAIR_ID);
PX_COMPILE_TIME_ASSERT(IS_IN_PERSISTENT_EVENT_LIST == (WAS_IN_PERSISTENT_EVENT_LIST >> 1));
PX_ASSERT(!(readFlag(WAS_IN_PERSISTENT_EVENT_LIST)));
const PxU32 wasInPersList = (mFlags & IS_IN_PERSISTENT_EVENT_LIST) << 1;
mFlags |= wasInPersList;
removeFromReportPairList();
}
void Sc::ShapeInteraction::setContactReportPostSolverVelocity(ContactStreamManager& cs)
{
Scene& scene = getScene();
NPhaseCore* npcore = scene.getNPhaseCore();
PxU8* stream = npcore->getContactReportPairData(cs.bufferIndex);
ActorPairReport& apr = getActorPairReport();
cs.setContactReportPostSolverVelocity(stream, apr.getActorA(), apr.getActorB());
}
void Sc::ShapeInteraction::resetManagerCachedState() const
{
if(mManager)
{
Sc::Scene& scene = getScene();
PxvNphaseImplementationContext* nphaseImplementationContext = scene.getLowLevelContext()->getNphaseImplementationContext();
PX_ASSERT(nphaseImplementationContext);
mManager->resetCachedState();
nphaseImplementationContext->refreshContactManager(mManager);
}
}
/*
This method can be called from various stages in the pipeline, some of which operate before the actor has advanced its pose and some after it has advanced its pose.
Discrete touch found events operate before the pose has been updated. This is because we are using the found event to active the bodies before solve so that we can just
solve the activated bodies.
Lost touch events occur after the pose has been updated.
*/
void Sc::ShapeInteraction::processUserNotificationSync()
{
PX_ASSERT(hasTouch());
if(mManager)
PxPrefetchLine(mManager);
// make sure shape A and shape B are the same way round as the actors (in compounds they may be swapped)
// TODO: make "unswapped" a SIP flag and set it in updateState()
if(!mActorPair)
return;
NPhaseCore* npcore = getScene().getNPhaseCore();
ActorPairReport& aPairReport = getActorPairReport();
if(!aPairReport.isInContactReportActorPairSet())
{
aPairReport.setInContactReportActorPairSet();
npcore->addToContactReportActorPairSet(&aPairReport);
aPairReport.incRefCount();
}
aPairReport.createContactStreamManager(*npcore);
}
void Sc::ShapeInteraction::processUserNotificationAsync(PxU32 contactEvent, PxU16 infoFlags, bool touchLost,
PxU32 ccdPass, bool useCurrentTransform, PxsContactManagerOutputIterator& outputs, ContactReportAllocationManager* alloc)
{
contactEvent = (!ccdPass) ? contactEvent : (contactEvent | PxPairFlag::eNOTIFY_TOUCH_CCD);
if(!mActorPair)
return;
ActorPairReport& aPairReport = getActorPairReport();
Scene& scene = getScene();
NPhaseCore* npcore = scene.getNPhaseCore();
ContactStreamManager& cs = aPairReport.createContactStreamManager(*npcore);
// Prepare user notification
const PxU32 timeStamp = scene.getTimeStamp();
const PxU32 shapePairTimeStamp = scene.getReportShapePairTimeStamp();
const PxU32 pairFlags = getPairFlags();
PX_ASSERT(pairFlags & contactEvent);
const PxU32 extraDataFlags = pairFlags & CONTACT_REPORT_EXTRA_DATA;
PxU8* stream = NULL;
ContactShapePair* pairStream = NULL;
const bool unswapped = &aPairReport.getActorA() == &getShape0().getActor();
const Sc::ShapeSimBase& shapeA = unswapped ? getShape0() : getShape1();
const Sc::ShapeSimBase& shapeB = unswapped ? getShape1() : getShape0();
if(aPairReport.streamResetStamp(timeStamp))
{
PX_ASSERT(mContactReportStamp != shapePairTimeStamp); // actor pair and shape pair timestamps must both be out of sync in this case
PxU16 maxCount;
if(cs.maxPairCount != 0)
maxCount = cs.maxPairCount; // use value from previous report
else
{
// TODO: Use some kind of heuristic
maxCount = 2;
cs.maxPairCount = maxCount;
}
PxU32 maxExtraDataSize;
if(!extraDataFlags || touchLost)
{
maxExtraDataSize = 0;
cs.setMaxExtraDataSize(maxExtraDataSize);
}
else
{
PxU32 currentMaxExtraDataSize = cs.getMaxExtraDataSize();
maxExtraDataSize = ContactStreamManager::computeContactReportExtraDataSize(extraDataFlags, true);
PX_ASSERT(maxExtraDataSize > 0);
if(maxExtraDataSize <= currentMaxExtraDataSize)
maxExtraDataSize = currentMaxExtraDataSize; // use value from previous report
else
cs.setMaxExtraDataSize(maxExtraDataSize);
}
stream = npcore->reserveContactReportPairData(maxCount, maxExtraDataSize, cs.bufferIndex, alloc);
if(!maxExtraDataSize) // this is the usual case, so set it first for branch prediction
cs.reset();
else if(stream)
{
cs.reset();
PX_ASSERT(extraDataFlags);
PX_ASSERT(!touchLost);
cs.fillInContactReportExtraData(stream, extraDataFlags, aPairReport.getActorA(), aPairReport.getActorB(), ccdPass, useCurrentTransform, 0, sizeof(ContactStreamHeader));
if((extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY) && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT))
scene.setPostSolverVelocityNeeded();
}
}
else
{
const PxU32 currentPairCount = cs.currentPairCount;
if(currentPairCount != 0)
{
PxU8* tmpStreamPtr = npcore->getContactReportPairData(cs.bufferIndex);
if(!extraDataFlags)
stream = tmpStreamPtr; // this is the usual case, so set it first for branch prediction
else
{
if(!touchLost)
{
// - the first few shape pair events might not request extra data
// - the events so far were due to touch lost
// - multiple reports due to CCD multiple passes
// Hence, the extra data has to be created/extended now.
//
const PxU16 oldExtraDataSize = cs.extraDataSize;
PxI32 lastContactPass;
if(oldExtraDataSize)
{
ContactStreamHeader* strHeader = reinterpret_cast<ContactStreamHeader*>(tmpStreamPtr);
lastContactPass = strHeader->contactPass;
}
else
lastContactPass = -1;
if(PxI32(ccdPass) > lastContactPass) // do not send extra data mulitple times for the same contact pass
{
const PxU16 extraDataSize = PxU16(oldExtraDataSize + ContactStreamManager::computeContactReportExtraDataSize(extraDataFlags, (oldExtraDataSize == 0)));
PxU8* strPtr;
if (extraDataSize <= cs.getMaxExtraDataSize())
strPtr = tmpStreamPtr;
else
strPtr = npcore->resizeContactReportPairData(currentPairCount < cs.maxPairCount ? cs.maxPairCount : PxU32(cs.maxPairCount+1), extraDataSize, cs);
// the check for max pair count is there to avoid another potential allocation further below
if(strPtr)
{
stream = strPtr;
PxU32 sizeOffset;
if(oldExtraDataSize)
sizeOffset = oldExtraDataSize;
else
sizeOffset = sizeof(ContactStreamHeader);
cs.fillInContactReportExtraData(strPtr, extraDataFlags, aPairReport.getActorA(), aPairReport.getActorB(), ccdPass, useCurrentTransform, currentPairCount, sizeOffset);
if((extraDataFlags & PxPairFlag::ePOST_SOLVER_VELOCITY) && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT))
scene.setPostSolverVelocityNeeded();
}
else
{
stream = tmpStreamPtr;
cs.raiseFlags(ContactStreamManagerFlag::eINCOMPLETE_STREAM);
}
}
else
stream = tmpStreamPtr;
}
else
stream = tmpStreamPtr;
}
}
}
if(stream)
pairStream = cs.getShapePairs(stream);
else
{
cs.raiseFlags(ContactStreamManagerFlag::eINVALID_STREAM);
return;
}
ContactShapePair* cp;
if(mContactReportStamp != shapePairTimeStamp)
{
// this shape pair is not in the contact notification stream yet
if(cs.currentPairCount < cs.maxPairCount)
cp = pairStream + cs.currentPairCount;
else
{
const PxU32 newSize = PxU32(cs.currentPairCount + (cs.currentPairCount >> 1) + 1);
stream = npcore->resizeContactReportPairData(newSize, cs.getMaxExtraDataSize(), cs);
if(stream)
{
pairStream = cs.getShapePairs(stream);
cp = pairStream + cs.currentPairCount;
}
else
{
cs.raiseFlags(ContactStreamManagerFlag::eINCOMPLETE_STREAM);
return;
}
}
//!!! why is alignment important here? Looks almost like some refactor nonsense
PX_ASSERT(0==(reinterpret_cast<uintptr_t>(stream) & 0x0f)); // check 16Byte alignment
mReportStreamIndex = cs.currentPairCount;
cp->shapes[0] = shapeA.getPxShape();
cp->shapes[1] = shapeB.getPxShape();
cp->contactPatches = NULL;
cp->contactPoints = NULL;
cp->contactForces = NULL;
cp->contactCount = 0;
cp->patchCount = 0;
cp->constraintStreamSize = 0;
cp->requiredBufferSize = 0;
cp->flags = infoFlags;
PX_ASSERT(contactEvent <= 0xffff);
cp->events = PxU16(contactEvent);
cp->shapeID[0] = shapeA.getElementID();
cp->shapeID[1] = shapeB.getElementID();
cs.currentPairCount++;
mContactReportStamp = shapePairTimeStamp;
}
else
{
// this shape pair is in the contact notification stream already but there is a second event (can happen with force threshold reports, for example).
PX_ASSERT(mReportStreamIndex < cs.currentPairCount);
cp = &pairStream[mReportStreamIndex];
cp->events |= contactEvent;
if(touchLost && cp->events & PxPairFlag::eNOTIFY_TOUCH_PERSISTS)
cp->events &= PxU16(~PxPairFlag::eNOTIFY_TOUCH_PERSISTS);
cp->flags |= infoFlags;
}
if((getPairFlags() & PxPairFlag::eNOTIFY_CONTACT_POINTS) && mManager && (!cp->contactPatches) && !(contactEvent & PxU32(PxPairFlag::eNOTIFY_TOUCH_LOST | PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST)))
{
const PxcNpWorkUnit& workUnit = mManager->getWorkUnit();
PxsContactManagerOutput* output = NULL;
if(workUnit.mNpIndex & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK)
output = &getScene().getLowLevelContext()->getNphaseImplementationContext()->getNewContactManagerOutput(workUnit.mNpIndex);
else
output = &outputs.getContactManager(workUnit.mNpIndex);
const PxsCCDContactHeader* ccdContactData = reinterpret_cast<const PxsCCDContactHeader*>(workUnit.ccdContacts);
const bool isCCDPass = (ccdPass != 0);
if((output->nbPatches && !isCCDPass) || (ccdContactData && (!ccdContactData->isFromPreviousPass) && isCCDPass))
{
const PxU8* contactPatchData;
const PxU8* contactPointData;
PxU32 cDataSize;
PxU32 alignedContactDataSize;
const PxReal* impulses;
PxU32 nbPoints = output->nbContacts;
PxU32 contactPatchCount = output->nbPatches;
if(!isCCDPass)
{
PX_ASSERT(0==(reinterpret_cast<const uintptr_t>(output->contactPatches) & 0x0f)); // check 16Byte alignment
contactPatchData = output->contactPatches;
contactPointData = output->contactPoints;
cDataSize = sizeof(PxContactPatch)*output->nbPatches + sizeof(PxContact)*output->nbContacts;
alignedContactDataSize = (cDataSize + 0xf) & 0xfffffff0;
impulses = output->contactForces;
}
else
{
PX_ASSERT(0==(reinterpret_cast<const uintptr_t>(ccdContactData) & 0x0f)); // check 16Byte alignment
contactPatchData = reinterpret_cast<const PxU8*>(ccdContactData) + sizeof(PxsCCDContactHeader);
contactPointData = contactPatchData + sizeof(PxContactPatch);
cDataSize = ccdContactData->contactStreamSize - sizeof(PxsCCDContactHeader);
PxU32 tmpAlignedSize = (ccdContactData->contactStreamSize + 0xf) & 0xfffffff0;
alignedContactDataSize = tmpAlignedSize - sizeof(PxsCCDContactHeader);
impulses = reinterpret_cast<const PxReal*>(contactPatchData + alignedContactDataSize);
nbPoints = 1;
contactPatchCount = 1;
}
infoFlags = cp->flags;
infoFlags |= unswapped ? 0 : PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED;
//PX_ASSERT(0==(reinterpret_cast<const uintptr_t>(impulses) & 0x0f));
const PxU32 impulseSize = impulses ? (nbPoints * sizeof(PxReal)) : 0;
if(impulseSize)
infoFlags |= PxContactPairFlag::eINTERNAL_HAS_IMPULSES;
cp->contactPatches = contactPatchData;
cp->contactPoints = contactPointData;
cp->contactCount = PxTo8(nbPoints);
cp->patchCount = PxTo8(contactPatchCount);
cp->constraintStreamSize = PxTo16(cDataSize);
cp->requiredBufferSize = alignedContactDataSize + impulseSize;
cp->contactForces = impulses;
cp->flags = infoFlags;
}
}
}
void Sc::ShapeInteraction::processUserNotification(PxU32 contactEvent, PxU16 infoFlags, bool touchLost, PxU32 ccdPass, bool useCurrentTransform, PxsContactManagerOutputIterator& outputs)
{
processUserNotificationSync();
processUserNotificationAsync(contactEvent, infoFlags, touchLost, ccdPass, useCurrentTransform, outputs);
}
PxU32 Sc::ShapeInteraction::getContactPointData(const void*& contactPatches, const void*& contactPoints, PxU32& contactDataSize, PxU32& contactPointCount, PxU32& numPatches, const PxReal*& impulses, PxU32 startOffset,
PxsContactManagerOutputIterator& outputs)
{
// Process LL generated contacts
if(mManager != NULL)
{
const PxcNpWorkUnit& workUnit = mManager->getWorkUnit();
PxsContactManagerOutput* output = NULL;
if(workUnit.mNpIndex & PxsContactManagerBase::NEW_CONTACT_MANAGER_MASK)
output = &getScene().getLowLevelContext()->getNphaseImplementationContext()->getNewContactManagerOutput(workUnit.mNpIndex);
else
output = &outputs.getContactManager(workUnit.mNpIndex);
/*const void* dcdContactPatches;
const void* dcdContactPoints;
PxU32 dcdContactPatchCount;
const PxReal* dcdImpulses;
const PxsCCDContactHeader* ccdContactStream;
PxU32 dcdContactCount = mManager->getContactPointData(dcdContactPatches, dcdContactPoints, dcdContactPatchCount, dcdImpulses, ccdContactStream);
PX_ASSERT(((dcdContactCount == 0) && (!ccdContactStream)) || ((dcdContactCount > 0) && hasTouch()) || (ccdContactStream && hasCCDTouch()));*/
const PxsCCDContactHeader* ccdContactStream = reinterpret_cast<const PxsCCDContactHeader*>(workUnit.ccdContacts);
PxU32 idx = 0;
if(output) // preventive measure for omnicrash OM-109664
{
if(output->nbContacts)
{
if(startOffset == 0)
{
contactPatches = output->contactPatches;
contactPoints = output->contactPoints;
contactDataSize = sizeof(PxContactPatch) * output->nbPatches + sizeof(PxContact) * output->nbContacts;
contactPointCount = output->nbContacts;
numPatches = output->nbPatches;
impulses = output->contactForces;
if(!ccdContactStream)
return startOffset;
else
return (startOffset + 1);
}
idx++;
}
while(ccdContactStream)
{
if(startOffset == idx)
{
const PxU8* stream = reinterpret_cast<const PxU8*>(ccdContactStream);
PxU16 streamSize = ccdContactStream->contactStreamSize;
contactPatches = stream + sizeof(PxsCCDContactHeader);
contactPoints = stream + sizeof(PxsCCDContactHeader) + sizeof(PxContactPatch);
contactDataSize = streamSize - sizeof(PxsCCDContactHeader);
contactPointCount = 1;
numPatches = 1;
impulses = reinterpret_cast<const PxReal*>(stream + ((streamSize + 0xf) & 0xfffffff0));
if(!ccdContactStream->nextStream)
return startOffset;
else
return (startOffset + 1);
}
idx++;
ccdContactStream = ccdContactStream->nextStream;
}
}
}
else
{
PxGetFoundation().error(PxErrorCode::eINTERNAL_ERROR, PX_FL, "PxsContactManagerOutput output is null!\n");
}
contactPatches = NULL;
contactPoints = NULL;
contactDataSize = 0;
contactPointCount = 0;
numPatches = 0;
impulses = NULL;
return startOffset;
}
// Note that LL will not send end touch events for managers that are destroyed while having contact
void Sc::ShapeInteraction::managerNewTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs)
{
if(readFlag(HAS_TOUCH))
return; // Do not count the touch twice (for instance when recreating a manager with touch)
// We have contact this frame
setHasTouch();
if(adjustCounters)
adjustCountersOnNewTouch();
if(!isReportPair())
return;
else
{
PX_ASSERT(hasTouch());
PX_ASSERT(!readFlag(IS_IN_PERSISTENT_EVENT_LIST));
PX_ASSERT(!readFlag(IS_IN_FORCE_THRESHOLD_EVENT_LIST));
const PxU32 pairFlags = getPairFlags();
if(pairFlags & PxPairFlag::eNOTIFY_TOUCH_FOUND)
{
PxU16 infoFlag = 0;
if(mActorPair->getTouchCount() == 1) // this code assumes that the actor pair touch count does get incremented beforehand
infoFlag = PxContactPairFlag::eACTOR_PAIR_HAS_FIRST_TOUCH;
processUserNotification(PxPairFlag::eNOTIFY_TOUCH_FOUND, infoFlag, false, ccdPass, true, outputs);
}
if(pairFlags & PxPairFlag::eNOTIFY_TOUCH_PERSISTS)
{
getScene().getNPhaseCore()->addToPersistentContactEventPairsDelayed(this); // to make sure that from now on, the pairs are tested for persistent contact events
}
else if(pairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS)
{
// new touch -> need to start checking for force threshold events
// Note: this code assumes that it runs before the pairs get tested for force threshold exceeded
getScene().getNPhaseCore()->addToForceThresholdContactEventPairs(this);
}
}
}
bool Sc::ShapeInteraction::managerLostTouch(PxU32 ccdPass, bool adjustCounters, PxsContactManagerOutputIterator& outputs)
{
if(!readFlag(HAS_TOUCH))
return false;
// We do not have LL contacts this frame and also we lost LL contact this frame
if(!isReportPair())
{
setHasNoTouch();
}
else
{
PX_ASSERT(hasTouch());
sendLostTouchReport(false, ccdPass, outputs);
if(readFlag(IS_IN_CONTACT_EVENT_LIST))
{
// don't need to worry about persistent/force-threshold contact events until next new touch
if(readFlag(IS_IN_FORCE_THRESHOLD_EVENT_LIST))
{
getScene().getNPhaseCore()->removeFromForceThresholdContactEventPairs(this);
}
else
{
PX_ASSERT(readFlag(IS_IN_PERSISTENT_EVENT_LIST));
getScene().getNPhaseCore()->removeFromPersistentContactEventPairs(this);
}
clearFlag(FORCE_THRESHOLD_EXCEEDED_FLAGS);
}
setHasNoTouch();
}
ActorSim& body0 = getShape0().getActor();
ActorSim& body1 = getShape1().getActor();
if(adjustCounters)
adjustCountersOnLostTouch();
if(body1.isStaticRigid())
{
body0.internalWakeUp();
return false;
}
return true;
}
PX_FORCE_INLINE void Sc::ShapeInteraction::updateFlags(const Sc::Scene& scene, const Sc::ActorSim& bs0, const Sc::ActorSim& bs1, const PxU32 pairFlags)
{
// the first shape always belongs to a dynamic body/ a soft body
bool enabled = true;
if (bs0.isDynamicRigid())
{
const Sc::BodySim& body0 = static_cast<const Sc::BodySim&>(bs0);
enabled = !body0.isKinematic();
}
if (bs1.isDynamicRigid())
{
const Sc::BodySim& body1 = static_cast<const Sc::BodySim&>(bs1);
enabled |= !body1.isKinematic();
}
// Check if collision response is disabled
enabled = enabled && (pairFlags & PxPairFlag::eSOLVE_CONTACT);
setFlag(CONTACTS_RESPONSE_DISABLED, !enabled);
// Check if contact points needed
setFlag(CONTACTS_COLLECT_POINTS, ( (pairFlags & PxPairFlag::eNOTIFY_CONTACT_POINTS) ||
(pairFlags & PxPairFlag::eMODIFY_CONTACTS) ||
scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_POINT) ||
scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_NORMAL) ||
scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_ERROR) ||
scene.getVisualizationParameter(PxVisualizationParameter::eCONTACT_FORCE)) );
}
PX_INLINE PxReal ScGetRestOffset(const Sc::ShapeSimBase& shapeSim)
{
#if PX_SUPPORT_GPU_PHYSX
if (shapeSim.getActor().isParticleSystem())
return static_cast<Sc::ParticleSystemSim&>(shapeSim.getActor()).getCore().getRestOffset();
#endif
return shapeSim.getRestOffset();
}
void Sc::ShapeInteraction::updateState(const PxU8 externalDirtyFlags)
{
const PxU32 oldContactState = getManagerContactState();
const PxU8 dirtyFlags = PxU8(getDirtyFlags() | externalDirtyFlags);
const PxU32 pairFlags = getPairFlags();
Scene& scene = getScene();
IG::SimpleIslandManager* islandManager = scene.getSimpleIslandManager();
if(dirtyFlags & (InteractionDirtyFlag::eFILTER_STATE | InteractionDirtyFlag::eVISUALIZATION))
{
Sc::ActorSim& bs0 = getShape0().getActor();
Sc::ActorSim& bs1 = getShape1().getActor();
PxIntBool wasDisabled = readFlag(CONTACTS_RESPONSE_DISABLED);
updateFlags(scene, bs0, bs1, pairFlags);
PxIntBool isDisabled = readFlag(CONTACTS_RESPONSE_DISABLED);
if(!wasDisabled && isDisabled)
{
islandManager->setEdgeDisconnected(mEdgeIndex);
}
else if(wasDisabled && !isDisabled)
{
if(readFlag(ShapeInteraction::HAS_TOUCH))
islandManager->setEdgeConnected(mEdgeIndex, IG::Edge::eCONTACT_MANAGER);
}
}
const PxU32 newContactState = getManagerContactState();
const bool recreateManager = (oldContactState != newContactState);
// No use in updating manager properties if the manager is going to be re-created or does not exist yet
if((!recreateManager) && (mManager != 0))
{
ShapeSimBase& shapeSim0 = getShape0();
ShapeSimBase& shapeSim1 = getShape1();
// Update dominance
if(dirtyFlags & InteractionDirtyFlag::eDOMINANCE)
{
Sc::ActorSim& bs0 = shapeSim0.getActor();
Sc::ActorSim& bs1 = shapeSim1.getActor();
// Static actors are in dominance group zero and must remain there
const PxDominanceGroup dom0 = bs0.getActorCore().getDominanceGroup();
const PxDominanceGroup dom1 = !bs1.isStaticRigid() ? bs1.getActorCore().getDominanceGroup() : PxDominanceGroup(0);
const PxDominanceGroupPair cdom = getScene().getDominanceGroupPair(dom0, dom1);
mManager->setDominance0(cdom.dominance0);
mManager->setDominance1(cdom.dominance1);
}
if (dirtyFlags & InteractionDirtyFlag::eBODY_KINEMATIC)
{
//Kinematic flags changed - clear flag for kinematic on the pair
Sc::ActorSim& bs1 = shapeSim1.getActor();
if (bs1.isDynamicRigid())
{
if (static_cast<BodySim&>(bs1).isKinematic())
mManager->getWorkUnit().flags |= PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR;
else
mManager->getWorkUnit().flags &= (~PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR);
}
}
// Update skin width
if(dirtyFlags & InteractionDirtyFlag::eREST_OFFSET)
mManager->setRestDistance(ScGetRestOffset(shapeSim0) + ScGetRestOffset(shapeSim1));
//we may want to only write these if they have changed, the set code is a bit painful for the integration flags because of bit unpacking + packing.
mManager->setCCD((getPairFlags() & PxPairFlag::eDETECT_CCD_CONTACT) != 0);
if(dirtyFlags)
resetManagerCachedState(); // this flushes changes through to the GPU
}
else if (readInteractionFlag(InteractionFlag::eIS_ACTIVE)) // only re-create the manager if the pair is active
{
PX_ASSERT(mManager); // if the pair is active, there has to be a manager
if (dirtyFlags & InteractionDirtyFlag::eBODY_KINEMATIC)
{
//Kinematic->dynamic transition
const IG::IslandSim& islandSim = getScene().getSimpleIslandManager()->getSpeculativeIslandSim();
//
//check whether active in the speculative sim!
const ActorSim& bodySim0 = getShape0().getActor();
const ActorSim& bodySim1 = getShape1().getActor();
if (!islandSim.getNode(bodySim0.getNodeIndex()).isActiveOrActivating() &&
(bodySim1.isStaticRigid() || !islandSim.getNode(bodySim1.getNodeIndex()).isActiveOrActivating()))
{
onDeactivate();
scene.notifyInteractionDeactivated(this);
}
else
{
//Else we are allowed to be active, so recreate
if (mEdgeIndex != IG_INVALID_EDGE)
islandManager->clearEdgeRigidCM(mEdgeIndex);
destroyManager();
createManager(NULL);
}
}
else
{
PX_ASSERT(activeManagerAllowed());
// A) This is a newly created pair
//
// B) The contact notification or processing state has changed.
// All existing managers need to be deleted and recreated with the correct flag set
// These flags can only be set at creation in LL
//KS - added this code here because it is no longer done in destroyManager() - a side-effect of the parallelization of the interaction management code
if (mEdgeIndex != IG_INVALID_EDGE)
islandManager->clearEdgeRigidCM(mEdgeIndex);
destroyManager();
createManager(NULL);
}
}
}
bool Sc::ShapeInteraction::onActivate(void* contactManager)
{
if(isReportPair())
{
// for pairs that go through a second island pass, there is the possibility that they get put to sleep again after the second pass.
// So we do not want to check for re-insertion into the persistent report pair list yet.
processReportPairOnActivate();
}
if(updateManager(contactManager))
{
raiseInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
else
return false;
}
bool Sc::ShapeInteraction::onDeactivate()
{
PX_ASSERT(!getShape0().getActor().isStaticRigid() || !getShape1().getActor().isStaticRigid());
const ActorSim& bodySim0 = getShape0().getActor();
const ActorSim& bodySim1 = getShape1().getActor();
PX_ASSERT( (bodySim0.isStaticRigid() && !bodySim1.isStaticRigid() && !bodySim1.isActive()) ||
(bodySim1.isStaticRigid() && !bodySim0.isStaticRigid() && !bodySim0.isActive()) ||
((!bodySim0.isStaticRigid() && !bodySim1.isStaticRigid() && (!bodySim0.isActive() || !bodySim1.isActive()))) );
if((!bodySim0.isActive()) && (bodySim1.isStaticRigid() || !bodySim1.isActive()))
{
if(mReportPairIndex != INVALID_REPORT_PAIR_ID)
processReportPairOnDeactivate();
PX_ASSERT((mManager->getTouchStatus() > 0) == (hasTouch() > 0));
Scene& scene = getScene();
IG::SimpleIslandManager* islandManager = scene.getSimpleIslandManager();
if(mManager)
{
if((!readFlag(TOUCH_KNOWN)) && mManager->touchStatusKnown() && (!mManager->getTouchStatus()))
{
// for pairs that are inserted asleep, we do not know the touch state. If they run through narrowphase and a touch is found,
// then a managerNewTouch() call will inform this object about the found touch. However, if narrowphase detects that there
// is no touch, this object will not be informed about it. The low level manager will always know though. Now, before destroying
// the pair manager, we need to record "does not have touch" state if available.
raiseFlag(HAS_NO_TOUCH);
}
destroyManager();
if(mEdgeIndex != IG_INVALID_EDGE)
islandManager->clearEdgeRigidCM(mEdgeIndex);
}
islandManager->deactivateEdge(mEdgeIndex);
//
// We distinguish two scenarios here:
//
// A) island generation deactivates objects:
// -> the deactivated body was active
// -> narrowphase ran on this pair
// -> the touch status is known
// -> touch: the objects of the pair are in the same island
// -> no touch: the objects of the pair are in different islands
//
// As a consequence, the edge state is not changed. The assumption is that anything that could break the touch status
// from here on will have to mark the edges connected (for example if the object gets moved).
//
// B) user deactivates objects:
// -> the touch status might not be known (for example, the pose gets integrated after the solver which might cause a change
// in touch status. If the object gets put to sleep after that, we have to be conservative and mark the edge connected.
// other example: an active object gets moved by the user and then deactivated).
//
clearInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
else
{
return false;
}
}
void Sc::ShapeInteraction::createManager(void* contactManager)
{
//PX_PROFILE_ZONE("ShapeInteraction.createManager", 0);
Sc::Scene& scene = getScene();
const PxU32 pairFlags = getPairFlags();
const int disableCCDContact = !(pairFlags & PxPairFlag::eDETECT_CCD_CONTACT);
PxsContactManager* manager = scene.getLowLevelContext()->createContactManager(reinterpret_cast<PxsContactManager*>(contactManager), !disableCCDContact);
PxcNpWorkUnit& mNpUnit = manager->getWorkUnit();
// Check if contact generation callback has been ordered on the pair
int contactChangeable = 0;
if(pairFlags & PxPairFlag::eMODIFY_CONTACTS)
contactChangeable = 1;
ShapeSimBase& shapeSim0 = getShape0();
ShapeSimBase& shapeSim1 = getShape1();
const PxActorType::Enum type0 = shapeSim0.getActor().getActorType();
const PxActorType::Enum type1 = shapeSim1.getActor().getActorType();
const int disableResponse = readFlag(CONTACTS_RESPONSE_DISABLED) ? 1 : 0;
const int disableDiscreteContact = !(pairFlags & PxPairFlag::eDETECT_DISCRETE_CONTACT);
const int reportContactInfo = readFlag(CONTACTS_COLLECT_POINTS);
const int hasForceThreshold = !disableResponse && (pairFlags & CONTACT_FORCE_THRESHOLD_PAIRS);
int touching;
if(readFlag(TOUCH_KNOWN))
touching = readFlag(HAS_TOUCH) ? 1 : -1;
else
touching = 0;
// Static actors are in dominance group zero and must remain there
Sc::ActorSim& bs0 = shapeSim0.getActor();
Sc::ActorSim& bs1 = shapeSim1.getActor();
const PxDominanceGroup dom0 = bs0.getActorCore().getDominanceGroup();
const PxDominanceGroup dom1 = bs1.isStaticRigid() ? PxDominanceGroup(0) : bs1.getActorCore().getDominanceGroup();
const bool kinematicActor = bs1.isDynamicRigid() ? static_cast<BodySim&>(bs1).isKinematic() : false;
const PxDominanceGroupPair cdom = scene.getDominanceGroupPair(dom0, dom1);
/*const PxI32 hasArticulations= (type0 == PxActorType::eARTICULATION_LINK) | (type1 == PxActorType::eARTICULATION_LINK)<<1;
const PxI32 hasDynamics = (type0 != PxActorType::eRIGID_STATIC) | (type1 != PxActorType::eRIGID_STATIC)<<1;*/
const PxsShapeCore* shapeCore0 = &shapeSim0.getCore().getCore();
const PxsShapeCore* shapeCore1 = &shapeSim1.getCore().getCore();
//Initialize the manager....
manager->mRigidBody0 = bs0.isDynamicRigid() ? &static_cast<BodySim&>(bs0).getLowLevelBody() : NULL;
manager->mRigidBody1 = bs1.isDynamicRigid() ? &static_cast<BodySim&>(bs1).getLowLevelBody() : NULL;
manager->mShapeInteraction = this;
mNpUnit.shapeCore0 = shapeCore0;
mNpUnit.shapeCore1 = shapeCore1;
PX_ASSERT(shapeCore0->getTransform().isValid() && shapeCore1->getTransform().isValid());
mNpUnit.rigidCore0 = !bs0.isNonRigid() ? &static_cast<ShapeSim&>(shapeSim0).getPxsRigidCore() : NULL;
mNpUnit.rigidCore1 = !bs1.isNonRigid() ? &static_cast<ShapeSim&>(shapeSim1).getPxsRigidCore() : NULL;
mNpUnit.restDistance = ScGetRestOffset(shapeSim0) + ScGetRestOffset(shapeSim1);
mNpUnit.dominance0 = cdom.dominance0;
mNpUnit.dominance1 = cdom.dominance1;
mNpUnit.geomType0 = PxU8(shapeCore0->mGeometry.getType());
mNpUnit.geomType1 = PxU8(shapeCore1->mGeometry.getType());
mNpUnit.mTransformCache0 = shapeSim0.getTransformCacheID();
mNpUnit.mTransformCache1 = shapeSim1.getTransformCacheID();
mNpUnit.mTorsionalPatchRadius = PxMax(shapeSim0.getTorsionalPatchRadius(),shapeSim1.getTorsionalPatchRadius());
mNpUnit.mMinTorsionalPatchRadius = PxMax(shapeSim0.getMinTorsionalPatchRadius(), shapeSim1.getMinTorsionalPatchRadius());
const PxReal slop0 = manager->mRigidBody0 ? manager->mRigidBody0->getCore().offsetSlop : 0.0f;
const PxReal slop1 = manager->mRigidBody1 ? manager->mRigidBody1->getCore().offsetSlop : 0.0f;
mNpUnit.mOffsetSlop = PxMax(slop0, slop1);
PxU16 wuflags = 0;
if(type0 == PxActorType::eARTICULATION_LINK)
wuflags |= PxcNpWorkUnitFlag::eARTICULATION_BODY0;
if(type1 == PxActorType::eARTICULATION_LINK)
wuflags |= PxcNpWorkUnitFlag::eARTICULATION_BODY1;
if(type0 == PxActorType::eRIGID_DYNAMIC)
wuflags |= PxcNpWorkUnitFlag::eDYNAMIC_BODY0;
if(type1 == PxActorType::eRIGID_DYNAMIC)
wuflags |= PxcNpWorkUnitFlag::eDYNAMIC_BODY1;
#if PX_SUPPORT_GPU_PHYSX
if (type0 == PxActorType::eSOFTBODY)
wuflags |= PxcNpWorkUnitFlag::eSOFT_BODY;
if (type1 == PxActorType::eSOFTBODY)
wuflags |= PxcNpWorkUnitFlag::eSOFT_BODY;
#endif
if(!disableResponse && !contactChangeable)
wuflags |= PxcNpWorkUnitFlag::eOUTPUT_CONSTRAINTS;
if(!disableDiscreteContact)
wuflags |= PxcNpWorkUnitFlag::eDETECT_DISCRETE_CONTACT;
if(kinematicActor)
wuflags |= PxcNpWorkUnitFlag::eHAS_KINEMATIC_ACTOR;
if(disableResponse)
wuflags |= PxcNpWorkUnitFlag::eDISABLE_RESPONSE;
if(!disableCCDContact)
wuflags |= PxcNpWorkUnitFlag::eDETECT_CCD_CONTACTS;
// this is just the user req: contact reports can also be generated by body thresholding
if(reportContactInfo || contactChangeable)
wuflags |= PxcNpWorkUnitFlag::eOUTPUT_CONTACTS;
if(hasForceThreshold)
wuflags |= PxcNpWorkUnitFlag::eFORCE_THRESHOLD;
if(contactChangeable)
wuflags |= PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT;
mNpUnit.flags = wuflags;
manager->mFlags = PxU32(contactChangeable ? PxsContactManager::PXS_CM_CHANGEABLE : 0) | PxU32(disableCCDContact ? 0 : PxsContactManager::PXS_CM_CCD_LINEAR);
//manager->mUserData = this;
mNpUnit.mNpIndex = 0xFFffFFff;
mManager = manager;
PxU8 statusFlags = 0;
if(touching > 0)
statusFlags |= PxcNpWorkUnitStatusFlag::eHAS_TOUCH;
else if (touching < 0)
statusFlags |= PxcNpWorkUnitStatusFlag::eHAS_NO_TOUCH;
mNpUnit.statusFlags = statusFlags;
//KS - do not register the CMs here if contactManager isn't null. This implies this is a newly-found pair so we'll do that addition outside in parallel
if(contactManager == NULL)
{
scene.getSimpleIslandManager()->setEdgeRigidCM(mEdgeIndex, mManager);
PxvNphaseImplementationContext* nphaseImplementationContext = scene.getLowLevelContext()->getNphaseImplementationContext();
PX_ASSERT(nphaseImplementationContext);
nphaseImplementationContext->registerContactManager(mManager, this, touching, 0);
}
}
void Sc::ShapeInteraction::onShapeChangeWhileSleeping(bool shapeOfDynamicChanged)
{
// if an operation that can break touch status occurs, all deactivated pairs need to set the sleep island edge
// to connected to make sure that potentially joined islands get detected once parts of the island wake up.
// Active interactions can be ignored because the edges of those will be marked connected on deactivation.
if(!mManager)
{
Scene& scene = getScene();
//soft body/dynamic before static
ActorSim& body0 = getShape0().getActor();
if(shapeOfDynamicChanged && !readFlag(TOUCH_KNOWN))
{
// conservative approach: if a pair was added asleep, and a body/shape gets moved, we want to check next frame
// whether the other body should get woken up. The motivation behind this is to get a similar behavior as in
// the case where the objects fell asleep rather than have been added asleep (in that case the object will be
// woken up with one frame delay).
ActorSim& body1 = getShape1().getActor();
if(body1.isDynamicRigid() && !readFlag(ShapeInteraction::CONTACTS_RESPONSE_DISABLED)) // the first shape always belongs to a dynamic body, hence no need to test body0
scene.addToLostTouchList(body0, body1); // note: this will cause duplicate entries if the pair loses AABB overlap the next frame
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeCore.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.
#ifndef SC_HAIRSYSTEM_SHAPECORE_H
#define SC_HAIRSYSTEM_SHAPECORE_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "foundation/PxUserAllocated.h"
#include "DyHairSystemCore.h"
#include "ScShapeCore.h"
#include "PxShape.h"
namespace physx
{
class PxCudaContextManager;
namespace Sc
{
class HairSystemShapeCore : public Sc::ShapeCore
{
public:
// PX_SERIALIZATION
HairSystemShapeCore(const PxEMPTY);
//~PX_SERIALIZATION
HairSystemShapeCore();
~HairSystemShapeCore();
PX_FORCE_INLINE const Dy::HairSystemCore& getLLCore() const { return mLLCore; }
PX_FORCE_INLINE Dy::HairSystemCore& getLLCore() { return mLLCore; }
void createBuffers(PxCudaContextManager* cudaContextManager);
void releaseBuffers();
PxU64& getGpuMemStat() { return mGpuMemStat; }
private:
Dy::HairSystemCore mLLCore;
PxU64 mGpuMemStat;
PxCudaContextManager* mCudaContextManager;
};
} // namespace Sc
} // namespace physx
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScTriggerInteraction.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 "ScTriggerInteraction.h"
#include "ScBodySim.h"
#include "ScNPhaseCore.h"
using namespace physx;
using namespace Sc;
TriggerInteraction::TriggerInteraction( ShapeSimBase& tShape, ShapeSimBase& oShape) :
ElementSimInteraction(tShape, oShape, InteractionType::eTRIGGER, InteractionFlag::eRB_ELEMENT | InteractionFlag::eFILTERABLE),
mLastFrameHadContacts(false)
{
mFlags = PROCESS_THIS_FRAME;
// The PxPairFlags eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST get stored and mixed up with internal flags. Make sure any breaking change gets noticed.
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_FOUND < PxPairFlag::eNOTIFY_TOUCH_LOST);
PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eNOTIFY_TOUCH_FOUND) == PxPairFlag::eNOTIFY_TOUCH_FOUND);
PX_COMPILE_TIME_ASSERT((PAIR_FLAGS_MASK & PxPairFlag::eNOTIFY_TOUCH_LOST) == PxPairFlag::eNOTIFY_TOUCH_LOST);
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_FOUND < 0xffff);
PX_COMPILE_TIME_ASSERT(PxPairFlag::eNOTIFY_TOUCH_LOST < 0xffff);
PX_COMPILE_TIME_ASSERT(LAST < 0xffff);
{
const bool active = onActivate(NULL);
registerInActors();
getScene().registerInteraction(this, active);
}
PX_ASSERT(getTriggerShape().getFlags() & PxShapeFlag::eTRIGGER_SHAPE);
mTriggerCache.state = Gu::TRIGGER_DISJOINT;
}
TriggerInteraction::~TriggerInteraction()
{
getScene().unregisterInteraction(this);
unregisterFromActors();
}
static bool isOneActorActive(TriggerInteraction* trigger)
{
const ActorSim& actorSim0 = trigger->getTriggerShape().getActor();
if(actorSim0.isActive() && actorSim0.isDynamicRigid())
{
const BodySim* bodySim0 = static_cast<const BodySim*>(&actorSim0);
PX_UNUSED(bodySim0);
PX_ASSERT(!bodySim0->isKinematic() || bodySim0->readInternalFlag(BodySim::BF_KINEMATIC_MOVED) ||
bodySim0->readInternalFlag(BodySim::InternalFlags(BodySim::BF_KINEMATIC_SETTLING | BodySim::BF_KINEMATIC_SETTLING_2)));
return true;
}
const ActorSim& actorSim1 = trigger->getOtherShape().getActor();
if(actorSim1.isActive() && actorSim1.isDynamicRigid())
{
const BodySim* bodySim1 = static_cast<const BodySim*>(&actorSim1);
PX_UNUSED(bodySim1);
PX_ASSERT(!bodySim1->isKinematic() || bodySim1->readInternalFlag(BodySim::BF_KINEMATIC_MOVED) ||
bodySim1->readInternalFlag(BodySim::InternalFlags(BodySim::BF_KINEMATIC_SETTLING | BodySim::BF_KINEMATIC_SETTLING_2)));
return true;
}
return false;
}
//
// Some general information about triggers and sleeping
//
// The goal is to avoid running overlap tests if both objects are sleeping.
// This is an optimization for eNOTIFY_TOUCH_LOST events since the overlap state
// can not change if both objects are sleeping. eNOTIFY_TOUCH_FOUND should be sent nonetheless.
// For this to work the following assumptions are made:
// - On creation or if the pose of an actor is set, the pair will always be checked.
// - If the scenario above does not apply, then a trigger pair can only be deactivated, if both actors are sleeping.
// - If an overlapping actor is activated/deactivated, the trigger interaction gets notified
//
bool TriggerInteraction::onActivate(void*)
{
// IMPORTANT: this method can get called concurrently from multiple threads -> make sure shared resources
// are protected (note: there are none at the moment but it might change)
if(!(readFlag(PROCESS_THIS_FRAME)))
{
if(isOneActorActive(this))
{
raiseInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
else
return false;
}
else
{
raiseInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true; // newly created trigger pairs should always test for overlap, no matter the sleep state
}
}
bool TriggerInteraction::onDeactivate()
{
if(!readFlag(PROCESS_THIS_FRAME))
{
if(!isOneActorActive(this))
{
clearInteractionFlag(InteractionFlag::eIS_ACTIVE);
return true;
}
else
return false;
}
else
return false;
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScShapeSimBase.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.
#include "ScShapeSimBase.h"
#include "ScSqBoundsManager.h"
#include "ScTriggerInteraction.h"
#include "ScSimulationController.h"
#include "CmTransformUtils.h"
#include "ScShapeInteraction.h"
using namespace physx;
using namespace Sc;
// PT: keep local functions in cpp, no need to pollute the header. Don't force conversions to bool if not necessary.
static PX_FORCE_INLINE PxU32 hasTriggerFlags(PxShapeFlags flags) { return PxU32(flags) & PxU32(PxShapeFlag::eTRIGGER_SHAPE); }
void resetElementID(Scene& scene, ShapeSimBase& shapeSim)
{
PX_ASSERT(!shapeSim.isInBroadPhase());
// scene.getDirtyShapeSimMap().reset(shapeSim.getElementID());
scene.getDirtyShapeSimMap().boundedReset(shapeSim.getElementID());
if (shapeSim.getSqBoundsId() != PX_INVALID_U32)
shapeSim.destroySqBounds();
}
PX_INLINE Bp::FilterGroup::Enum getBPGroup(const ShapeSimBase& shapeSim)
{
const BodySim* bs = shapeSim.getBodySim();
const RigidSim& rbSim = shapeSim.getRbSim();
bool isKinematic = bs ? bs->isKinematic() : false;
if (isKinematic && bs->hasForcedKinematicNotif())
isKinematic = false;
return Bp::getFilterGroup(rbSim.getActorType() == PxActorType::eRIGID_STATIC, rbSim.getActorID(), isKinematic);
}
static void setElementInteractionsDirty(Sc::ElementSim& elementSim, InteractionDirtyFlag::Enum flag, PxU8 interactionFlag)
{
ElementSim::ElementInteractionIterator iter = elementSim.getElemInteractions();
ElementSimInteraction* interaction = iter.getNext();
while(interaction)
{
if(interaction->readInteractionFlag(interactionFlag))
interaction->setDirty(flag);
interaction = iter.getNext();
}
}
void ShapeSimBase::onFilterDataChange()
{
setElementInteractionsDirty(*this, InteractionDirtyFlag::eFILTER_STATE, InteractionFlag::eFILTERABLE);
}
void ShapeSimBase::onResetFiltering()
{
if (isInBroadPhase())
reinsertBroadPhase();
}
void ShapeSimBase::onMaterialChange()
{
setElementInteractionsDirty(*this, InteractionDirtyFlag::eMATERIAL, InteractionFlag::eRB_ELEMENT);
}
void ShapeSimBase::onRestOffsetChange()
{
setElementInteractionsDirty(*this, InteractionDirtyFlag::eREST_OFFSET, InteractionFlag::eRB_ELEMENT);
}
void ShapeSimBase::onContactOffsetChange()
{
if (isInBroadPhase())
getScene().getAABBManager()->setContactDistance(getElementID(), getCore().getContactOffset());
}
void ShapeSimBase::removeFromBroadPhase(bool wakeOnLostTouch)
{
if (isInBroadPhase())
internalRemoveFromBroadPhase(wakeOnLostTouch);
}
void ShapeSimBase::reinsertBroadPhase()
{
bool wasPendingInsert = false;
if (isInBroadPhase())
{
wasPendingInsert = internalRemoveFromBroadPhase();
}
// internalAddToBroadPhase();
Scene& scene = getScene();
// Scene::removeShape
{
//unregisterShapeFromNphase(shape.getCore());
// PT: "getID" is const but the addShape call used LLShape, which uses elementID, so....
scene.getSimulationController()->removeShape(getElementID());
scene.unregisterShapeFromNphase(getCore(), getElementID());
}
// Call ShapeSim dtor
{
resetElementID(scene, *this);
}
// Call ElementSim dtor - only required if this shape was not pending insert (otherwise the elementID is fine to keep)
if (!wasPendingInsert)
{
{
releaseID();
}
// Call ElementSim ctor
{
initID();
}
}
// Call ShapeSim ctor
{
initSubsystemsDependingOnElementID();
}
// Scene::addShape
{
scene.getSimulationController()->addShape(&getLLShapeSim(), getElementID());
// PT: TODO: anything else needed here?
scene.registerShapeInNphase(&getRbSim().getRigidCore(), getCore(), getElementID());
}
}
PX_FORCE_INLINE void ShapeSimBase::internalAddToBroadPhase()
{
PX_ASSERT(!isInBroadPhase());
addToAABBMgr(getCore().getContactOffset(), getBPGroup(*this), (getCore().getCore().mShapeFlags & PxShapeFlag::eTRIGGER_SHAPE) ? Bp::ElementType::eTRIGGER : Bp::ElementType::eSHAPE);
}
PX_FORCE_INLINE bool ShapeSimBase::internalRemoveFromBroadPhase(bool wakeOnLostTouch)
{
PX_ASSERT(isInBroadPhase());
bool res = removeFromAABBMgr();
Scene& scene = getScene();
PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs();
scene.getNPhaseCore()->onVolumeRemoved(this, wakeOnLostTouch ? PxU32(PairReleaseFlag::eWAKE_ON_LOST_TOUCH) : 0, outputs);
return res;
}
void ShapeSimBase::initSubsystemsDependingOnElementID()
{
Scene& scScene = getScene();
Bp::BoundsArray& boundsArray = scScene.getBoundsArray();
const PxU32 index = getElementID();
PX_ALIGN(16, PxTransform absPos);
getAbsPoseAligned(&absPos);
PxsTransformCache& cache = scScene.getLowLevelContext()->getTransformCache();
cache.initEntry(index);
cache.setTransformCache(absPos, 0, index);
boundsArray.updateBounds(absPos, getCore().getGeometryUnion().getGeometry(), index);
{
PX_PROFILE_ZONE("API.simAddShapeToBroadPhase", scScene.getContextId());
if (isBroadPhase(getCore().getFlags()))
internalAddToBroadPhase();
else
scScene.getAABBManager()->reserveSpaceForBounds(index);
scScene.updateContactDistance(index, getContactOffset());
}
// if(scScene.getDirtyShapeSimMap().size() <= index)
// scScene.getDirtyShapeSimMap().resize(PxMax(index+1, (scScene.getDirtyShapeSimMap().size()+1) * 2u));
RigidSim& owner = getRbSim();
if (owner.isDynamicRigid() && static_cast<BodySim&>(owner).isActive())
createSqBounds();
// Init LL shape
{
mLLShape.mElementIndex_GPU = index;
mLLShape.mShapeCore = const_cast<PxsShapeCore*>(&getCore().getCore());
if (owner.getActorType() == PxActorType::eRIGID_STATIC)
{
mLLShape.mBodySimIndex_GPU = PxNodeIndex(PX_INVALID_NODE);
}
else
{
BodySim& bodySim = static_cast<BodySim&>(getActor());
mLLShape.mBodySimIndex_GPU = bodySim.getNodeIndex();
//mLLShape.mLocalBound = computeBounds(mCore.getGeometry(), PxTransform(PxIdentity));
}
}
}
void ShapeSimBase::getAbsPoseAligned(PxTransform* PX_RESTRICT globalPose) const
{
// PT: TODO: simplify dynamic case when shape2Actor = idt
const PxsShapeCore& shapeCore = getCore().getCore();
const PxTransform& shape2Actor = shapeCore.getTransform();
const PxTransform* actor2World = NULL;
if (getActor().getActorType() == PxActorType::eRIGID_STATIC)
{
PxsRigidCore& core = static_cast<StaticSim&>(getActor()).getStaticCore().getCore();
if (shapeCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eIDT_TRANSFORM))
{
PX_ASSERT(shape2Actor.p.isZero() && shape2Actor.q.isIdentity());
*globalPose = core.body2World;
return;
}
actor2World = &core.body2World;
}
else
{
PxsBodyCore& core = static_cast<BodySim&>(getActor()).getBodyCore().getCore();
if (!core.hasIdtBody2Actor())
{
Cm::getDynamicGlobalPoseAligned(core.body2World, shape2Actor, core.getBody2Actor(), *globalPose);
return;
}
actor2World = &core.body2World;
}
Cm::getStaticGlobalPoseAligned(*actor2World, shape2Actor, *globalPose);
}
void ShapeSimBase::onFlagChange(PxShapeFlags oldFlags)
{
const PxShapeFlags newFlags = getCore().getFlags();
const bool oldBp = isBroadPhase(oldFlags) != 0;
const bool newBp = isBroadPhase(newFlags) != 0;
// Change of collision shape flags requires removal/add to broadphase
if (oldBp != newBp)
{
if (!oldBp && newBp)
{
// A.B. if a trigger was removed and inserted within the same frame we need to reinsert
if (hasTriggerFlags(newFlags) && getScene().getAABBManager()->isMarkedForRemove(getElementID()))
reinsertBroadPhase();
else
internalAddToBroadPhase();
}
else
internalRemoveFromBroadPhase();
}
else
{
const bool wasTrigger = hasTriggerFlags(oldFlags) != 0;
const bool isTrigger = hasTriggerFlags(newFlags) != 0;
if (wasTrigger != isTrigger)
reinsertBroadPhase(); // re-insertion is necessary because trigger pairs get killed
}
const PxShapeFlags hadSq = oldFlags & PxShapeFlag::eSCENE_QUERY_SHAPE;
const PxShapeFlags hasSq = newFlags & PxShapeFlag::eSCENE_QUERY_SHAPE;
if (hasSq && !hadSq)
{
BodySim* body = getBodySim();
if (body && body->isActive())
createSqBounds();
}
else if (hadSq && !hasSq)
destroySqBounds();
getScene().getSimulationController()->reinsertShape(&getLLShapeSim(), getElementID());
}
BodySim* ShapeSimBase::getBodySim() const
{
ActorSim& a = getActor();
return a.isDynamicRigid() ? static_cast<BodySim*>(&a) : NULL;
}
PxsRigidCore& ShapeSimBase::getPxsRigidCore() const
{
ActorSim& a = getActor();
return a.isDynamicRigid() ? static_cast<BodySim&>(a).getBodyCore().getCore()
: static_cast<StaticSim&>(a).getStaticCore().getCore();
}
void ShapeSimBase::updateCached(PxU32 transformCacheFlags, PxBitMapPinned* shapeChangedMap)
{
PX_ALIGN(16, PxTransform absPose);
getAbsPoseAligned(&absPose);
Scene& scene = getScene();
const PxU32 index = getElementID();
scene.getLowLevelContext()->getTransformCache().setTransformCache(absPose, transformCacheFlags, index);
scene.getBoundsArray().updateBounds(absPose, getCore().getGeometryUnion().getGeometry(), index);
if (shapeChangedMap && isInBroadPhase())
shapeChangedMap->growAndSet(index);
}
void ShapeSimBase::updateCached(PxsTransformCache& transformCache, Bp::BoundsArray& boundsArray)
{
const PxU32 index = getElementID();
PxsCachedTransform& ct = transformCache.getTransformCache(index);
PxPrefetchLine(&ct);
getAbsPoseAligned(&ct.transform);
ct.flags = 0;
PxBounds3& b = boundsArray.begin()[index];
Gu::computeBounds(b, getCore().getGeometryUnion().getGeometry(), ct.transform, 0.0f, 1.0f);
}
void ShapeSimBase::updateBPGroup()
{
if (isInBroadPhase())
{
Sc::Scene& scene = getScene();
scene.getAABBManager()->setBPGroup(getElementID(), getBPGroup(*this));
reinsertBroadPhase();
// internalRemoveFromBroadPhase();
// internalAddToBroadPhase();
}
}
void ShapeSimBase::markBoundsForUpdate()
{
Scene& scene = getScene();
if (isInBroadPhase())
scene.getDirtyShapeSimMap().growAndSet(getElementID());
}
static PX_FORCE_INLINE void updateInteraction(Scene& scene, Interaction* i, const bool isDynamic, const bool isAsleep)
{
if (i->getType() == InteractionType::eOVERLAP)
{
ShapeInteraction* si = static_cast<ShapeInteraction*>(i);
si->resetManagerCachedState();
if (isAsleep)
si->onShapeChangeWhileSleeping(isDynamic);
}
else if (i->getType() == InteractionType::eTRIGGER)
(static_cast<TriggerInteraction*>(i))->forceProcessingThisFrame(scene); // trigger pairs need to be checked next frame
}
void ShapeSimBase::onVolumeOrTransformChange()
{
Scene& scene = getScene();
BodySim* body = getBodySim();
const bool isDynamic = (body != NULL);
const bool isAsleep = body ? !body->isActive() : true;
ElementSim::ElementInteractionIterator iter = getElemInteractions();
ElementSimInteraction* i = iter.getNext();
while (i)
{
updateInteraction(scene, i, isDynamic, isAsleep);
i = iter.getNext();
}
markBoundsForUpdate();
getScene().getSimulationController()->reinsertShape(&getLLShapeSim(), getElementID());
}
void notifyActorInteractionsOfTransformChange(ActorSim& actor)
{
bool isDynamic;
bool isAsleep;
if (actor.isDynamicRigid())
{
isDynamic = true;
isAsleep = !static_cast<BodySim&>(actor).isActive();
}
else
{
isDynamic = false;
isAsleep = true;
}
Scene& scene = actor.getScene();
PxU32 nbInteractions = actor.getActorInteractionCount();
Interaction** interactions = actor.getActorInteractions();
while (nbInteractions--)
updateInteraction(scene, *interactions++, isDynamic, isAsleep);
}
void ShapeSimBase::createSqBounds()
{
if (mSqBoundsId != PX_INVALID_U32)
return;
BodySim* bodySim = getBodySim();
PX_ASSERT(bodySim);
if (bodySim->usingSqKinematicTarget() || bodySim->isFrozen() || !bodySim->isActive() || bodySim->readInternalFlag(BodySim::BF_IS_COMPOUND_RIGID))
return;
if (getCore().getFlags() & PxShapeFlag::eSCENE_QUERY_SHAPE)
getScene().getSqBoundsManager().addSyncShape(*this);
}
void ShapeSimBase::destroySqBounds()
{
if (mSqBoundsId != PX_INVALID_U32)
getScene().getSqBoundsManager().removeSyncShape(*this);
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFEMClothShapeSim.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScFEMClothShapeSim.h"
#include "ScNPhaseCore.h"
#include "ScScene.h"
#include "ScFEMClothSim.h"
#include "PxsContext.h"
#include "BpAABBManager.h"
#include "ScSqBoundsManager.h"
#include "geometry/PxTetrahedronMesh.h"
#include "geometry/PxTriangleMesh.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sc::FEMClothShapeSim::FEMClothShapeSim(FEMClothSim& FEMCloth) :
ShapeSimBase(FEMCloth, NULL),
initialTransform(PxVec3(0, 0, 0)),
initialScale(1.0f)
{
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sc::FEMClothShapeSim::~FEMClothShapeSim()
{
if (isInBroadPhase())
destroyLowLevelVolume();
PX_ASSERT(!isInBroadPhase());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::FEMClothShapeSim::attachShapeCore(const Sc::ShapeCore* shapeCore)
{
setCore(shapeCore);
createLowLevelVolume();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::FEMClothShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const
{
filterAttr = 0;
setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eFEMCLOTH);
filterData = getBodySim().getCore().getSimulationFilterData();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::FEMClothShapeSim::updateBounds()
{
Scene& scene = getScene();
PxBounds3 worldBounds = getWorldBounds();
worldBounds.fattenSafe(getContactOffset()); // fatten for fast moving colliders
scene.getBoundsArray().setBounds(worldBounds, getElementID());
scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID());
}
void Sc::FEMClothShapeSim::updateBoundsInAABBMgr()
{
Scene& scene = getScene();
scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID());
scene.getAABBManager()->setGPUStateChanged();
}
PxBounds3 Sc::FEMClothShapeSim::getBounds() const
{
PxBounds3 bounds = getScene().getBoundsArray().getBounds(getElementID());
return bounds;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::FEMClothShapeSim::createLowLevelVolume()
{
PX_ASSERT(getWorldBounds().isFinite());
const PxU32 index = getElementID();
getScene().getBoundsArray().setBounds(getWorldBounds(), index);
{
const PxU32 group = Bp::FilterGroup::eDYNAMICS_BASE + getActor().getActorID();
const PxU32 type = Bp::FilterType::FEMCLOTH;
addToAABBMgr(getCore().getContactOffset(), Bp::FilterGroup::Enum((group << BP_FILTERING_TYPE_SHIFT_BIT) | type), Bp::ElementType::eSHAPE);
}
// PT: TODO: what's the difference between "getContactOffset()" and "getCore().getContactOffset()" above?
getScene().updateContactDistance(index, getContactOffset());
PxsTransformCache& cache = getScene().getLowLevelContext()->getTransformCache();
cache.initEntry(index);
PxTransform idt(PxIdentity);
cache.setTransformCache(idt, 0, index);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::FEMClothShapeSim::destroyLowLevelVolume()
{
if (!isInBroadPhase())
return;
Sc::Scene& scene = getScene();
PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs();
scene.getNPhaseCore()->onVolumeRemoved(this, 0, outputs);
removeFromAABBMgr();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxBounds3 Sc::FEMClothShapeSim::getWorldBounds() const
{
const PxTriangleMeshGeometry& triGeom = static_cast<const PxTriangleMeshGeometry&>(getCore().getGeometry());
PxTriangleMesh* triMesh = triGeom.triangleMesh;
// PT: are you sure you want to go through the Px API here?
PxBounds3 bounds = triMesh->getLocalBounds();
bounds.minimum *= initialScale;
bounds.maximum *= initialScale;
bounds = PxBounds3::transformFast(initialTransform, bounds);
return bounds;
}
Sc::FEMClothSim& Sc::FEMClothShapeSim::getBodySim() const
{
return static_cast<FEMClothSim&>(getActor());
}
#endif //PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScActorCore.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 "ScActorCore.h"
#include "ScActorSim.h"
#include "ScShapeCore.h"
#include "ScShapeSim.h"
#include "ScBodySim.h"
using namespace physx;
Sc::ActorCore::ActorCore(PxActorType::Enum actorType, PxU8 actorFlags, PxClientID owner, PxDominanceGroup dominanceGroup) :
mSim (NULL),
mAggregateIDOwnerClient ((PxU32(owner)<<24)|0x00ffffff),
mActorFlags (actorFlags),
mActorType (PxU8(actorType)),
mDominanceGroup (dominanceGroup)
{
PX_ASSERT((actorType & 0xff) == actorType);
}
Sc::ActorCore::~ActorCore()
{
}
void Sc::ActorCore::setActorFlags(PxActorFlags af)
{
const PxActorFlags old = mActorFlags;
if(af!=old)
{
mActorFlags = af;
if(mSim)
mSim->postActorFlagChange(old, af);
}
}
void Sc::ActorCore::setDominanceGroup(PxDominanceGroup g)
{
PX_ASSERT(g<128);
mDominanceGroup = g;
if(mSim)
{
//force all related interactions to refresh, so they fetch new dominance values.
mSim->setActorsInteractionsDirty(InteractionDirtyFlag::eDOMINANCE, NULL, InteractionFlag::eRB_ELEMENT);
}
}
void Sc::ActorCore::reinsertShapes()
{
PX_ASSERT(mSim);
if(!mSim)
return;
PxU32 nbElems = mSim->getNbElements();
ElementSim** elems = mSim->getElements();
while (nbElems--)
{
ShapeSim* current = static_cast<ShapeSim*>(*elems++);
current->reinsertBroadPhase();
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationCore.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 "ScArticulationCore.h"
#include "ScPhysics.h"
#include "ScBodyCore.h"
#include "ScBodySim.h"
#include "ScArticulationSim.h"
using namespace physx;
Sc::ArticulationCore::ArticulationCore() :
mSim(NULL)
{
const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale();
mCore.solverIterationCounts = 1<<8 | 4;
mCore.sleepThreshold = 5e-5f * scale.speed * scale.speed;
mCore.freezeThreshold = 5e-6f * scale.speed * scale.speed;
mCore.wakeCounter = Physics::sWakeCounterOnCreation;
mCore.gpuRemapIndex = 0xffffffff;
mCore.maxLinearVelocity = 1e+6f;
mCore.maxAngularVelocity = 1e+6f;
}
Sc::ArticulationCore::~ArticulationCore()
{
}
//--------------------------------------------------------------
//
// ArticulationCore interface implementation
//
//--------------------------------------------------------------
void Sc::ArticulationCore::setWakeCounter(const PxReal v)
{
mCore.wakeCounter = v;
if (mSim)
{
mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_WAKECOUNTER);
}
#ifdef _DEBUG
if(mSim)
mSim->debugCheckWakeCounterOfLinks(v);
#endif
}
void Sc::ArticulationCore::setMaxLinearVelocity(const PxReal v)
{
mCore.maxLinearVelocity = v;
if (mSim)
{
mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITY_LIMITS);
}
}
void Sc::ArticulationCore::setMaxAngularVelocity(const PxReal v)
{
mCore.maxAngularVelocity = v;
if (mSim)
{
mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_VELOCITY_LIMITS);
}
}
bool Sc::ArticulationCore::isSleeping() const
{
return mSim ? mSim->isSleeping() : (mCore.wakeCounter == 0.0f);
}
void Sc::ArticulationCore::wakeUp(PxReal wakeCounter)
{
mCore.wakeCounter = wakeCounter;
if (mSim)
{
Dy::FeatherstoneArticulation* arti = static_cast<Dy::FeatherstoneArticulation*>(mSim->getLowLevelArticulation());
arti->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_WAKECOUNTER);
}
#ifdef _DEBUG
if(mSim)
mSim->debugCheckSleepStateOfLinks(false);
#endif
}
void Sc::ArticulationCore::putToSleep()
{
mCore.wakeCounter = 0.0f;
if (mSim)
{
Dy::FeatherstoneArticulation* arti = static_cast<Dy::FeatherstoneArticulation*>(mSim->getLowLevelArticulation());
arti->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_WAKECOUNTER);
}
#ifdef _DEBUG
if(mSim)
mSim->debugCheckSleepStateOfLinks(true);
#endif
}
void Sc::ArticulationCore::setArticulationFlags(PxArticulationFlags flags)
{
mCore.flags = flags;
if(mSim)
{
mSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_USER_FLAGS);
const bool isFixedBaseLink = flags & PxArticulationFlag::eFIX_BASE;
mSim->setFixedBaseLink(isFixedBaseLink);
}
}
PxU32 Sc::ArticulationCore::getDofs() const
{
return mSim ? mSim->getDofs() : 0xFFFFFFFFu;
}
PxArticulationCache* Sc::ArticulationCore::createCache() const
{
return mSim ? mSim->createCache() : NULL;
}
PxU32 Sc::ArticulationCore::getCacheDataSize() const
{
return mSim ? mSim->getCacheDataSize() : 0xFFFFFFFFu;
}
void Sc::ArticulationCore::zeroCache(PxArticulationCache& cache) const
{
if(mSim)
mSim->zeroCache(cache);
}
bool Sc::ArticulationCore::applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag) const
{
if(mSim)
return mSim->applyCache(cache, flag);
return false;
}
void Sc::ArticulationCore::copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const
{
if(mSim)
mSim->copyInternalStateToCache(cache, flag, isGpuSimEnabled);
}
void Sc::ArticulationCore::packJointData(const PxReal* maximum, PxReal* reduced) const
{
if(mSim)
mSim->packJointData(maximum, reduced);
}
void Sc::ArticulationCore::unpackJointData(const PxReal* reduced, PxReal* maximum) const
{
if(mSim)
mSim->unpackJointData(reduced, maximum);
}
void Sc::ArticulationCore::commonInit() const
{
if(mSim)
mSim->commonInit();
}
void Sc::ArticulationCore::computeGeneralizedGravityForce(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeGeneralizedGravityForce(cache);
}
void Sc::ArticulationCore::computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeCoriolisAndCentrifugalForce(cache);
}
void Sc::ArticulationCore::computeGeneralizedExternalForce(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeGeneralizedExternalForce(cache);
}
void Sc::ArticulationCore::computeJointAcceleration(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeJointAcceleration(cache);
}
void Sc::ArticulationCore::computeJointForce(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeJointForce(cache);
}
void Sc::ArticulationCore::computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const
{
if(mSim)
mSim->computeDenseJacobian(cache, nRows, nCols);
}
void Sc::ArticulationCore::computeCoefficientMatrix(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeCoefficientMatrix(cache);
}
bool Sc::ArticulationCore::computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter) const
{
return mSim ? mSim->computeLambda(cache, initialState, jointTorque, gravity, maxIter) : false;
}
void Sc::ArticulationCore::computeGeneralizedMassMatrix(PxArticulationCache& cache) const
{
if(mSim)
mSim->computeGeneralizedMassMatrix(cache);
}
PxU32 Sc::ArticulationCore::getCoefficientMatrixSize() const
{
return mSim ? mSim->getCoefficientMatrixSize() : 0xFFFFFFFFu;
}
PxSpatialVelocity Sc::ArticulationCore::getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const
{
return mSim ? mSim->getLinkAcceleration(linkId, isGpuSimEnabled) : PxSpatialVelocity();
}
PxU32 Sc::ArticulationCore::getGpuArticulationIndex() const
{
return mSim ? mCore.gpuRemapIndex : 0xffffffff;
}
void Sc::ArticulationCore::updateKinematic(PxArticulationKinematicFlags flags)
{
PX_ASSERT(mSim);
if (mSim)
mSim->updateKinematic(flags);
}
PxNodeIndex Sc::ArticulationCore::getIslandNodeIndex() const
{
return mSim ? mSim->getIslandNodeIndex() : PxNodeIndex(PX_INVALID_NODE);
}
void Sc::ArticulationCore::setGlobalPose()
{
if(mSim)
mSim->setGlobalPose();
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScArticulationTendonSim.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 "ScArticulationTendonSim.h"
#include "ScArticulationTendonCore.h"
#include "ScArticulationAttachmentCore.h"
#include "ScArticulationTendonJointCore.h"
#include "ScArticulationJointCore.h"
#include "ScScene.h"
#include "DyArticulationTendon.h"
#include "ScArticulationSim.h"
using namespace physx;
Sc::ArticulationSpatialTendonSim::ArticulationSpatialTendonSim(ArticulationSpatialTendonCore& tendon, Scene& scene) :
mTendonCore(tendon), mScene(scene)
{
mTendonCore.setSim(this);
mLLTendon.mStiffness = tendon.mStiffness;
mLLTendon.mDamping = tendon.mDamping;
mLLTendon.mOffset = tendon.mOffset;
mLLTendon.mLimitStiffness = tendon.mLimitStiffness;
}
Sc::ArticulationSpatialTendonSim::~ArticulationSpatialTendonSim()
{
mTendonCore.setSim(NULL);
}
void Sc::ArticulationSpatialTendonSim::setStiffness(const PxReal stiffness)
{
mLLTendon.mStiffness = stiffness;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON);
}
PxReal Sc::ArticulationSpatialTendonSim::getStiffness() const
{
return mLLTendon.mStiffness;
}
void Sc::ArticulationSpatialTendonSim::setDamping(const PxReal damping)
{
mLLTendon.mDamping = damping;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON);
}
PxReal Sc::ArticulationSpatialTendonSim::getDamping() const
{
return mLLTendon.mDamping;
}
void Sc::ArticulationSpatialTendonSim::setLimitStiffness(const PxReal stiffness)
{
mLLTendon.mLimitStiffness = stiffness;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
PxReal Sc::ArticulationSpatialTendonSim::getLimitStiffness() const
{
return mLLTendon.mLimitStiffness;
}
void Sc::ArticulationSpatialTendonSim::setOffset(const PxReal offset)
{
mLLTendon.mOffset = offset;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON);
}
PxReal Sc::ArticulationSpatialTendonSim::getOffset() const
{
return mLLTendon.mOffset;
}
void Sc::ArticulationSpatialTendonSim::setAttachmentCoefficient(ArticulationAttachmentCore& core, const PxReal coefficient)
{
const PxU32 index = core.mAttachmentIndex;
Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index);
attachment.coefficient = coefficient;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT);
}
void Sc::ArticulationSpatialTendonSim::setAttachmentRelativeOffset(ArticulationAttachmentCore& core, const PxVec3& offset)
{
const PxU32 index = core.mAttachmentIndex;
Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index);
attachment.relativeOffset = offset;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT);
}
void Sc::ArticulationSpatialTendonSim::setAttachmentLimits(ArticulationAttachmentCore& core, const PxReal lowLimit, const PxReal highLimit)
{
const PxU32 index = core.mAttachmentIndex;
Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index);
attachment.lowLimit = lowLimit;
attachment.highLimit = highLimit;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT);
}
void Sc::ArticulationSpatialTendonSim::setAttachmentRestLength(ArticulationAttachmentCore& core, const PxReal restLength)
{
const PxU32 index = core.mAttachmentIndex;
Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index);
attachment.restLength = restLength;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_SPATIAL_TENDON_ATTACHMENT);
}
void Sc::ArticulationSpatialTendonSim::addAttachment(ArticulationAttachmentCore& core)
{
const PxU32 index = mLLTendon.getNewID();
Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index);
attachment.relativeOffset = core.mRelativeOffset;
attachment.linkInd = PxU16(core.mLLLinkIndex);
attachment.lowLimit = core.mLowLimit;
attachment.highLimit = core.mHighLimit;
attachment.coefficient = core.mCoefficient;
attachment.myInd = index;
attachment.children = 0;
attachment.childCount = 0;
attachment.restLength = core.mRestLength;
core.mAttachmentIndex = index;
core.mTendonSim = this;
if (core.mParent)
{
const PxU32 parentIndex = core.mParent->mAttachmentIndex;
attachment.parent = parentIndex;
mLLTendon.getAttachment(parentIndex).children |= Dy::ArticulationAttachmentBitField(1) << index;
mLLTendon.getAttachment(parentIndex).childCount++;
}
else
{
attachment.parent = DY_ARTICULATION_ATTACHMENT_NONE;
}
}
void Sc::ArticulationSpatialTendonSim::removeAttachment(ArticulationAttachmentCore& core)
{
const PxU32 index = core.mAttachmentIndex;
Dy::ArticulationAttachment& attachment = mLLTendon.getAttachment(index);
PX_ASSERT(attachment.childCount == 0);
if (attachment.parent != DY_ARTICULATION_ATTACHMENT_NONE)
{
Dy::ArticulationAttachment& parent = mLLTendon.getAttachment(attachment.parent);
parent.children &= ~(Dy::ArticulationAttachmentBitField(1) << index);
parent.childCount--;
}
mLLTendon.freeID(index);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
Sc::ArticulationFixedTendonSim::ArticulationFixedTendonSim(ArticulationFixedTendonCore& tendon, Scene& scene) :
mTendonCore(tendon), mScene(scene)
{
mTendonCore.setSim(this);
mLLTendon.mStiffness = tendon.mStiffness;
mLLTendon.mDamping = tendon.mDamping;
mLLTendon.mOffset = tendon.mOffset;
mLLTendon.mLimitStiffness = tendon.mLimitStiffness;
mLLTendon.mLowLimit = tendon.mLowLimit;
mLLTendon.mHighLimit = tendon.mHighLimit;
mLLTendon.mRestLength = tendon.mRestLength;
}
Sc::ArticulationFixedTendonSim::~ArticulationFixedTendonSim()
{
mTendonCore.setSim(NULL);
}
void Sc::ArticulationFixedTendonSim::setStiffness(const PxReal stiffness)
{
mLLTendon.mStiffness = stiffness;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
PxReal Sc::ArticulationFixedTendonSim::getStiffness() const
{
return mLLTendon.mStiffness;
}
void Sc::ArticulationFixedTendonSim::setDamping(const PxReal damping)
{
mLLTendon.mDamping = damping;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
PxReal Sc::ArticulationFixedTendonSim::getDamping() const
{
return mLLTendon.mDamping;
}
void Sc::ArticulationFixedTendonSim::setLimitStiffness(const PxReal stiffness)
{
mLLTendon.mLimitStiffness = stiffness;
Dy::FeatherstoneArticulation* llArticulation = static_cast<Dy::FeatherstoneArticulation*>(mArtiSim->getLowLevelArticulation());
llArticulation->setGpuDirtyFlag(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
PxReal Sc::ArticulationFixedTendonSim::getLimitStiffness() const
{
return mLLTendon.mLimitStiffness;
}
void Sc::ArticulationFixedTendonSim::setOffset(const PxReal offset)
{
mLLTendon.mOffset = offset;
mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
PxReal Sc::ArticulationFixedTendonSim::getOffset() const
{
return mLLTendon.mOffset;
}
void Sc::ArticulationFixedTendonSim::setSpringRestLength(const PxReal restLength)
{
mLLTendon.mRestLength = restLength;
mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
PxReal Sc::ArticulationFixedTendonSim::getSpringRestLength() const
{
return mLLTendon.mRestLength;
}
void Sc::ArticulationFixedTendonSim::setLimitRange(const PxReal lowLimit, const PxReal highLimit)
{
mLLTendon.mLowLimit = lowLimit;
mLLTendon.mHighLimit = highLimit;
mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON);
}
void Sc::ArticulationFixedTendonSim::getLimitRange(PxReal& lowLimit, PxReal& highLimit) const
{
lowLimit = mLLTendon.mLowLimit;
highLimit = mLLTendon.mHighLimit;
}
void Sc::ArticulationFixedTendonSim::addTendonJoint(ArticulationTendonJointCore& tendonJointCore)
{
const PxU32 jointIndex = mLLTendon.getNewID();
Dy::ArticulationTendonJoint& tendonJoint = mLLTendon.getTendonJoint(jointIndex);
tendonJoint.axis = PxU16(tendonJointCore.axis);
tendonJoint.coefficient = tendonJointCore.coefficient;
tendonJoint.recipCoefficient = tendonJointCore.recipCoefficient;
tendonJoint.linkInd = PxU16(tendonJointCore.mLLLinkIndex);
tendonJoint.children = 0;
tendonJoint.childCount = 0;
tendonJointCore.mLLTendonJointIndex = jointIndex;
//tendonJointCore.mLLTendonJoint = &tendonJoint;
tendonJointCore.mTendonSim = this;
if (tendonJointCore.mParent)
{
const PxU32 parentIndex = tendonJointCore.mParent->mLLTendonJointIndex;
tendonJoint.parent = parentIndex;
mLLTendon.getTendonJoint(parentIndex).children |= Dy::ArticulationAttachmentBitField(1) << jointIndex;
mLLTendon.getTendonJoint(parentIndex).childCount++;
}
else
{
tendonJoint.parent = DY_ARTICULATION_ATTACHMENT_NONE;
}
}
void Sc::ArticulationFixedTendonSim::removeTendonJoint(ArticulationTendonJointCore& core)
{
const PxU32 index = core.mLLTendonJointIndex;
Dy::ArticulationTendonJoint& tendonJoint = mLLTendon.getTendonJoint(index);
PX_ASSERT(tendonJoint.childCount == 0);
if (tendonJoint.parent != DY_ARTICULATION_ATTACHMENT_NONE)
{
Dy::ArticulationTendonJoint& parent = mLLTendon.getTendonJoint(tendonJoint.parent);
parent.children &= ~(Dy::ArticulationAttachmentBitField(1) << index);
parent.childCount--;
}
mLLTendon.freeID(index);
}
void Sc::ArticulationFixedTendonSim::setTendonJointCoefficient(ArticulationTendonJointCore& core, const PxArticulationAxis::Enum axis, const float coefficient, const float recipCoefficient)
{
const PxU32 index = core.mLLTendonJointIndex;
Dy::ArticulationTendonJoint& tendonJoint = mLLTendon.getTendonJoint(index);
tendonJoint.axis = PxU16(axis);
tendonJoint.coefficient = coefficient;
tendonJoint.recipCoefficient = recipCoefficient;
mArtiSim->setArticulationDirty(Dy::ArticulationDirtyFlag::eDIRTY_FIXED_TENDON_JOINT);
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeSim.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScHairSystemShapeSim.h"
#include "ScNPhaseCore.h"
#include "ScHairSystemSim.h"
#include "PxsContext.h"
using namespace physx;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sc::HairSystemShapeSim::HairSystemShapeSim(HairSystemSim& hairSystemSim, const HairSystemShapeCore* core) :
ShapeSimBase(hairSystemSim, core)
{
createLowLevelVolume();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sc::HairSystemShapeSim::~HairSystemShapeSim()
{
if (isInBroadPhase())
destroyLowLevelVolume();
PX_ASSERT(!isInBroadPhase());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::HairSystemShapeSim::getFilterInfo(PxFilterObjectAttributes& filterAttr, PxFilterData& filterData) const
{
filterAttr = 0;
setFilterObjectAttributeType(filterAttr, PxFilterObjectType::eHAIRSYSTEM);
filterData = getBodySim().getCore().getShapeCore().getSimulationFilterData();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::HairSystemShapeSim::updateBounds()
{
Scene& scene = getScene();
PxBounds3 worldBounds = PxBounds3(PxVec3(0.f), PxVec3(0.f));
const PxReal contactOffset = getBodySim().getCore().getContactOffset();
worldBounds.fattenSafe(contactOffset); // fatten for fast moving colliders
scene.getBoundsArray().setBounds(worldBounds, getElementID());
scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::HairSystemShapeSim::updateBoundsInAABBMgr()
{
//we are updating the bound in GPU so we just need to set the actor handle in CPU to make sure
//the GPU BP will process the vertices
Scene& scene = getScene();
scene.getAABBManager()->getChangedAABBMgActorHandleMap().growAndSet(getElementID());
scene.getAABBManager()->setGPUStateChanged();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PxBounds3 Sc::HairSystemShapeSim::getBounds() const
{
PxBounds3 bounds = getScene().getBoundsArray().getBounds(getElementID());
return bounds;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::HairSystemShapeSim::createLowLevelVolume()
{
// PX_ASSERT(getWorldBounds().isFinite());
const PxU32 index = getElementID();
getScene().getBoundsArray().setBounds(PxBounds3(PxVec3(0.f), PxVec3(0.f)), index);
{
const PxU32 group = Bp::FilterGroup::eDYNAMICS_BASE + getActor().getActorID();
const PxU32 type = Bp::FilterType::HAIRSYSTEM;
addToAABBMgr(getCore().getContactOffset(), Bp::FilterGroup::Enum((group << BP_FILTERING_TYPE_SHIFT_BIT) | type), Bp::ElementType::eSHAPE);
}
// PT: TODO: what's the difference between "getContactOffset()" and "getCore().getContactOffset()" above?
getScene().updateContactDistance(index, getContactOffset());
PxsTransformCache& cache = getScene().getLowLevelContext()->getTransformCache();
cache.initEntry(index);
PxTransform idt(PxIdentity);
cache.setTransformCache(idt, 0, index);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Sc::HairSystemShapeSim::destroyLowLevelVolume()
{
if (!isInBroadPhase())
return;
Sc::Scene& scene = getScene();
PxsContactManagerOutputIterator outputs = scene.getLowLevelContext()->getNphaseImplementationContext()->getContactManagerOutputs();
scene.getNPhaseCore()->onVolumeRemoved(this, 0, outputs);
removeFromAABBMgr();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sc::HairSystemSim& Sc::HairSystemShapeSim::getBodySim() const
{
return static_cast<HairSystemSim&>(getActor());
}
#endif // PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScTriggerPairs.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 SC_TRIGGER_PAIRS_H
#define SC_TRIGGER_PAIRS_H
#include "foundation/PxArray.h"
#include "PxFiltering.h"
#include "PxClient.h"
#include "PxSimulationEventCallback.h"
namespace physx
{
class PxShape;
namespace Sc
{
struct TriggerPairFlag
{
enum Enum
{
eTEST_FOR_REMOVED_SHAPES = PxTriggerPairFlag::eNEXT_FREE // for cases where the pair got deleted because one of the shape volumes got removed from broadphase.
// This covers scenarios like volume re-insertion into broadphase as well since the shape might get removed
// after such an operation. The scenarios to consider are:
//
// - shape gets removed (this includes raising PxActorFlag::eDISABLE_SIMULATION)
// - shape switches to eSCENE_QUERY_SHAPE only
// - shape switches to eSIMULATION_SHAPE
// - resetFiltering()
// - actor gets removed from an aggregate
};
};
PX_COMPILE_TIME_ASSERT((1 << (8*sizeof(PxTriggerPairFlags::InternalType))) > TriggerPairFlag::eTEST_FOR_REMOVED_SHAPES);
struct TriggerPairExtraData
{
PX_INLINE TriggerPairExtraData() :
shape0ID(0xffffffff),
shape1ID(0xffffffff),
client0ID(0xff),
client1ID(0xff)
{
}
PX_INLINE TriggerPairExtraData(PxU32 s0ID, PxU32 s1ID,
PxClientID cl0ID, PxClientID cl1ID) :
shape0ID(s0ID),
shape1ID(s1ID),
client0ID(cl0ID),
client1ID(cl1ID)
{
}
PxU32 shape0ID;
PxU32 shape1ID;
PxClientID client0ID;
PxClientID client1ID;
};
typedef PxArray<TriggerPairExtraData> TriggerBufferExtraData;
typedef PxArray<PxTriggerPair> TriggerBufferAPI;
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScFiltering.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 "ScFiltering.h"
#include "ScShapeInteraction.h"
#include "ScTriggerInteraction.h"
#include "ScConstraintCore.h"
#include "ScArticulationSim.h"
using namespace physx;
using namespace Sc;
///////////////////////////////////////////////////////////////////////////////
PX_IMPLEMENT_OUTPUT_ERROR
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE PxU64 getPairID(const ShapeSimBase& s0, const ShapeSimBase& s1)
{
PxU64 id0 = PxU64(s0.getElementID());
PxU64 id1 = PxU64(s1.getElementID());
if(id1<id0)
PxSwap(id0, id1);
const PxU64 pairID = (id0<<32)|id1;
return pairID;
}
///////////////////////////////////////////////////////////////////////////////
template<const bool supportTriggers>
static PxFilterObjectAttributes getFilterObjectAttributes(const ShapeSimBase& shape)
{
const ActorSim& actorSim = shape.getActor();
PxFilterObjectAttributes filterAttr = actorSim.getFilterAttributes();
if(supportTriggers && (shape.getCore().getFlags() & PxShapeFlag::eTRIGGER_SHAPE))
filterAttr |= PxFilterObjectFlag::eTRIGGER;
#if PX_DEBUG
BodySim* b = shape.getBodySim();
if(b)
{
if(!b->isArticulationLink())
{
if(b->isKinematic())
PX_ASSERT(filterAttr & PxFilterObjectFlag::eKINEMATIC);
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eRIGID_DYNAMIC);
}
else
{
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eARTICULATION);
}
}
else
{
#if PX_SUPPORT_GPU_PHYSX
// For softbody and particle system, the bodySim is set to null
if(actorSim.isSoftBody())
{
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eSOFTBODY);
}
else if(actorSim.isParticleSystem())
{
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::ePARTICLESYSTEM);
}
else if(actorSim.isFEMCloth())
{
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eFEMCLOTH);
}
else if(actorSim.isHairSystem())
{
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eHAIRSYSTEM);
}
else
#endif
{
PX_ASSERT(PxGetFilterObjectType(filterAttr)==PxFilterObjectType::eRIGID_STATIC);
}
}
#endif
return filterAttr;
}
///////////////////////////////////////////////////////////////////////////////
// PT: checks that the kill & suppress flags are not both set, disable kill flag if they are.
static PX_INLINE void checkFilterFlags(PxFilterFlags& filterFlags)
{
if((filterFlags & (PxFilterFlag::eKILL | PxFilterFlag::eSUPPRESS)) == (PxFilterFlag::eKILL | PxFilterFlag::eSUPPRESS))
{
#if PX_CHECKED
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: eKILL and eSUPPRESS must not be set simultaneously. eSUPPRESS will be used.");
#endif
filterFlags.clear(PxFilterFlag::eKILL);
}
}
///////////////////////////////////////////////////////////////////////////////
static PX_INLINE PxPairFlags checkRbPairFlags( const ShapeSimBase& s0, const ShapeSimBase& s1, bool isKinePair,
PxPairFlags pairFlags, PxFilterFlags filterFlags, bool isNonRigid)
{
if(filterFlags & (PxFilterFlag::eSUPPRESS | PxFilterFlag::eKILL))
return pairFlags;
if(isKinePair && (pairFlags & PxPairFlag::eSOLVE_CONTACT))
{
#if PX_CHECKED
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: Resolving contacts between two kinematic objects is invalid. Contacts will not get resolved.");
#endif
pairFlags.clear(PxPairFlag::eSOLVE_CONTACT);
}
if(isNonRigid && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT))
pairFlags.clear(PxPairFlag::eDETECT_CCD_CONTACT);
#if PX_CHECKED
// we want to avoid to run contact generation for pairs that should not get resolved or have no contact/trigger reports
if (!(PxU32(pairFlags) & (PxPairFlag::eSOLVE_CONTACT | ShapeInteraction::CONTACT_REPORT_EVENTS)))
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: Pair with no contact/trigger reports detected, nor is PxPairFlag::eSOLVE_CONTACT set. It is recommended to suppress/kill such pairs for performance reasons.");
else if(!(pairFlags & (PxPairFlag::eDETECT_DISCRETE_CONTACT | PxPairFlag::eDETECT_CCD_CONTACT)))
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: Pair did not request either eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT. It is recommended to suppress/kill such pairs for performance reasons.");
if(((s0.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)!=0 || (s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE)!=0) &&
(pairFlags & PxPairFlag::eTRIGGER_DEFAULT) && (pairFlags & PxPairFlag::eDETECT_CCD_CONTACT))
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: CCD isn't supported on Triggers yet");
#else
PX_UNUSED(s0);
PX_UNUSED(s1);
#endif
return pairFlags;
}
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE bool createFilterInfo(FilterInfo& filterInfo, const PxFilterFlags filterFlags)
{
filterInfo = FilterInfo(filterFlags);
return true;
}
static void filterRbCollisionPairSecondStage(FilterInfo& filterInfo, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1, bool isKinePair,
const PxFilterObjectAttributes fa0, const PxFilterObjectAttributes fa1, bool runCallbacks, bool isNonRigid)
{
// Run filter shader
const PxFilterData& fd0 = s0.getCore().getSimulationFilterData();
const PxFilterData& fd1 = s1.getCore().getSimulationFilterData();
filterInfo.filterFlags = context.mFilterShader(fa0, fd0, fa1, fd1, filterInfo.pairFlags, context.mFilterShaderData, context.mFilterShaderDataSize);
if(filterInfo.filterFlags & PxFilterFlag::eCALLBACK)
{
if(context.mFilterCallback)
{
if(!runCallbacks)
{
return;
}
else
{
// If a FilterPair is provided, then we use it, else we create a new one
// (A FilterPair is provided in the case for a pairLost()-pairFound() sequence after refiltering)
struct Local
{
static PX_FORCE_INLINE PxShape* fetchActorAndShape(const ShapeSimBase& sim, const PxFilterObjectAttributes fa, PxActor*& a)
{
a = sim.getActor().getPxActor();
#if PX_SUPPORT_GPU_PHYSX
if(PxGetFilterObjectType(fa)==PxFilterObjectType::ePARTICLESYSTEM)
return NULL; // Particle system does not have a valid shape so set it to null
#endif
PX_UNUSED(fa);
return sim.getPxShape();
}
};
PxActor* a0, *a1;
PxShape* shape0 = Local::fetchActorAndShape(s0, fa0, a0);
PxShape* shape1 = Local::fetchActorAndShape(s1, fa1, a1);
filterInfo.filterFlags = context.mFilterCallback->pairFound(getPairID(s0, s1), fa0, fd0, a0, shape0, fa1, fd1, a1, shape1, filterInfo.pairFlags);
filterInfo.hasPairID = true;
}
}
else
{
filterInfo.filterFlags.clear(PxFilterFlag::eNOTIFY);
outputError<PxErrorCode::eDEBUG_WARNING>(__LINE__, "Filtering: eCALLBACK set but no filter callback defined.");
}
}
checkFilterFlags(filterInfo.filterFlags);
const bool hasNotify = (filterInfo.filterFlags & PxFilterFlag::eNOTIFY) == PxFilterFlag::eNOTIFY;
const bool hasKill = filterInfo.filterFlags & PxFilterFlag::eKILL;
{
if(filterInfo.hasPairID && (hasKill || !hasNotify))
{
if(hasKill && hasNotify)
context.mFilterCallback->pairLost(getPairID(s0, s1), fa0, fd0, fa1, fd1, false);
if(!hasNotify)
{
// No notification, hence we don't need to treat it as a filter callback pair anymore.
// Make sure that eCALLBACK gets removed as well
filterInfo.filterFlags.clear(PxFilterFlag::eNOTIFY);
}
filterInfo.hasPairID = false;
}
}
// Sanity checks
PX_ASSERT((!hasKill) || (hasKill && (!filterInfo.hasPairID)));
PX_ASSERT((!hasNotify) || (hasNotify && filterInfo.hasPairID));
if(runCallbacks || (!(filterInfo.filterFlags & PxFilterFlag::eCALLBACK)))
filterInfo.pairFlags = checkRbPairFlags(s0, s1, isKinePair, filterInfo.pairFlags, filterInfo.filterFlags, isNonRigid);
}
static bool filterArticulationLinks(const BodySim* bs0, const BodySim* bs1)
{
//It's the same articulation, so we can filter based on flags...
const ArticulationSim* articulationSim0 = bs0->getArticulation();
const ArticulationSim* articulationSim1 = bs1->getArticulation();
if(articulationSim0 == articulationSim1)
{
if(articulationSim0->getCore().getArticulationFlags() & PxArticulationFlag::eDISABLE_SELF_COLLISION)
return true;
//check to see if one link is the parent of the other link, if so disable collision
const PxU32 linkId0 = bs0->getNodeIndex().articulationLinkId();
const PxU32 linkId1 = bs1->getNodeIndex().articulationLinkId();
if(linkId1 < linkId0)
return articulationSim0->getLink(linkId0).parent == linkId1;
else
return articulationSim1->getLink(linkId1).parent == linkId0;
}
return false;
}
static PX_FORCE_INLINE bool filterJointedBodies(const ActorSim& rbActor0, const ActorSim& rbActor1)
{
// If the bodies of the shape pair are connected by a joint, we need to check whether this connection disables the collision.
// Note: As an optimization, the dynamic bodies have a flag which specifies whether they have any constraints at all. That works
// because a constraint has at least one dynamic body and an interaction is tracked by both objects.
// PT: the BF_HAS_CONSTRAINTS flag is only raised on dynamic actors in the BodySim class, but it's not raised on static actors.
// Thus the only reliable way to use the flag (without casting to BodySim etc) is when both actors don't have the flag set, in
// which case we're sure we're not dealing with a jointed pair.
if(!rbActor0.readInternalFlag(ActorSim::BF_HAS_CONSTRAINTS) && !rbActor1.readInternalFlag(ActorSim::BF_HAS_CONSTRAINTS))
return false;
ConstraintCore* core = rbActor0.getScene().findConstraintCore(&rbActor0, &rbActor1);
return core ? !(core->getFlags() & PxConstraintFlag::eCOLLISION_ENABLED) : false;
}
static PX_FORCE_INLINE bool hasForceNotifEnabled(const BodySim* bs, PxRigidBodyFlag::Enum flag)
{
if(!bs)
return false;
const PxsRigidCore& core = bs->getBodyCore().getCore();
return core.mFlags.isSet(flag);
}
static PX_FORCE_INLINE bool validateSuppress(const BodySim* b0, const BodySim* b1, PxRigidBodyFlag::Enum flag)
{
if(hasForceNotifEnabled(b0, flag))
return false;
if(hasForceNotifEnabled(b1, flag))
return false;
return true;
}
static PX_FORCE_INLINE bool filterKinematics(const BodySim* b0, const BodySim* b1, bool kine0, bool kine1,
PxPairFilteringMode::Enum kineKineFilteringMode, PxPairFilteringMode::Enum staticKineFilteringMode)
{
const bool kinematicPair = kine0 | kine1;
if(kinematicPair)
{
if(staticKineFilteringMode != PxPairFilteringMode::eKEEP)
{
if(!b0 || !b1)
return validateSuppress(b0, b1, PxRigidBodyFlag::eFORCE_STATIC_KINE_NOTIFICATIONS);
}
if(kineKineFilteringMode != PxPairFilteringMode::eKEEP)
{
if(kine0 && kine1)
return validateSuppress(b0, b1, PxRigidBodyFlag::eFORCE_KINE_KINE_NOTIFICATIONS);
}
}
return false;
}
template<const bool runAllTests>
static bool filterRbCollisionPairShared( FilterInfo& filterInfo, bool& isNonRigid, bool& isKinePair,
const FilteringContext& context,
const ShapeSimBase& s0, const ShapeSimBase& s1,
const PxFilterObjectAttributes filterAttr0, const PxFilterObjectAttributes filterAttr1)
{
const bool kine0 = PxFilterObjectIsKinematic(filterAttr0);
const bool kine1 = PxFilterObjectIsKinematic(filterAttr1);
const ActorSim& rbActor0 = s0.getActor();
const BodySim* bs0 = NULL;
if(filterAttr0 & PxFilterObjectFlagEx::eRIGID_DYNAMIC)
bs0 = static_cast<const BodySim*>(&rbActor0);
else if(filterAttr0 & PxFilterObjectFlagEx::eNON_RIGID)
isNonRigid = true;
const ActorSim& rbActor1 = s1.getActor();
const BodySim* bs1 = NULL;
if(filterAttr1 & PxFilterObjectFlagEx::eRIGID_DYNAMIC)
bs1 = static_cast<const BodySim*>(&rbActor1);
else if(filterAttr1 & PxFilterObjectFlagEx::eNON_RIGID)
isNonRigid = true;
if(!isNonRigid && filterKinematics(bs0, bs1, kine0, kine1, context.mKineKineFilteringMode, context.mStaticKineFilteringMode))
return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS);
if(filterJointedBodies(rbActor0, rbActor1))
return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS);
const PxFilterObjectType::Enum filterType0 = PxGetFilterObjectType(filterAttr0);
const PxFilterObjectType::Enum filterType1 = PxGetFilterObjectType(filterAttr1);
// PT: For unknown reasons the filtering code was not the same for triggers/refiltered pairs and for regular "shape sim" pairs
// out of the BP. The tests on "runAllTests" below capture that. I did not change what the code
// was doing, although it might very well be wrong - we might want to run all these tests in both codepaths.
if(runAllTests)
{
#if PX_SUPPORT_GPU_PHYSX
if(filterType0==PxFilterObjectType::ePARTICLESYSTEM && filterType1==PxFilterObjectType::ePARTICLESYSTEM)
return createFilterInfo(filterInfo, PxFilterFlag::eKILL);
if(filterType0==PxFilterObjectType::eHAIRSYSTEM && filterType1==PxFilterObjectType::eHAIRSYSTEM )
return createFilterInfo(filterInfo, PxFilterFlag::eKILL);
#endif
}
const bool link0 = filterType0==PxFilterObjectType::eARTICULATION;
const bool link1 = filterType1==PxFilterObjectType::eARTICULATION;
if(runAllTests)
{
if(link0 ^ link1)
{
if(link0)
{
const PxU8 fixedBaseLink = bs0->getLowLevelBody().mCore->fixedBaseLink;
const bool isStaticOrKinematic = (filterType1 == PxFilterObjectType::eRIGID_STATIC) || kine1;
if(fixedBaseLink && isStaticOrKinematic)
return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS);
}
if(link1)
{
const PxU8 fixedBaseLink = bs1->getLowLevelBody().mCore->fixedBaseLink;
const bool isStaticOrKinematic = (filterType0 == PxFilterObjectType::eRIGID_STATIC) || kine0;
if(fixedBaseLink && isStaticOrKinematic)
return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS);
}
}
}
if(link0 && link1)
{
if(runAllTests)
{
const PxU8 fixedBaseLink0 = bs0->getLowLevelBody().mCore->fixedBaseLink;
const PxU8 fixedBaseLink1 = bs1->getLowLevelBody().mCore->fixedBaseLink;
if(fixedBaseLink0 && fixedBaseLink1)
return createFilterInfo(filterInfo, PxFilterFlag::eSUPPRESS);
}
if(filterArticulationLinks(bs0, bs1))
return createFilterInfo(filterInfo, PxFilterFlag::eKILL);
}
isKinePair = kine0 && kine1;
return false;
}
static void filterRbCollisionPair(FilterInfo& filterInfo, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1, bool& isTriggerPair, bool runCallbacks)
{
const PxFilterObjectAttributes filterAttr0 = getFilterObjectAttributes<true>(s0);
const PxFilterObjectAttributes filterAttr1 = getFilterObjectAttributes<true>(s1);
const bool trigger0 = PxFilterObjectIsTrigger(filterAttr0);
const bool trigger1 = PxFilterObjectIsTrigger(filterAttr1);
isTriggerPair = trigger0 || trigger1;
bool isNonRigid = false;
bool isKinePair = false;
if(isTriggerPair)
{
if(trigger0 && trigger1) // trigger-trigger pairs are not supported
{
createFilterInfo(filterInfo, PxFilterFlag::eKILL);
return;
}
// PT: I think we need to do this here to properly handle kinematic triggers.
const bool kine0 = PxFilterObjectIsKinematic(filterAttr0);
const bool kine1 = PxFilterObjectIsKinematic(filterAttr1);
isKinePair = kine0 && kine1;
}
else
{
if(filterRbCollisionPairShared<false>(filterInfo, isNonRigid, isKinePair, context, s0, s1, filterAttr0, filterAttr1))
return;
}
filterRbCollisionPairSecondStage(filterInfo, context, s0, s1, isKinePair, filterAttr0, filterAttr1, runCallbacks, isNonRigid);
}
static PX_FORCE_INLINE void filterRbCollisionPairAllTests(FilterInfo& filterInfo, const FilteringContext& context, const ShapeSimBase& s0, const ShapeSimBase& s1)
{
PX_ASSERT(!(s0.getFlags() & PxShapeFlag::eTRIGGER_SHAPE));
PX_ASSERT(!(s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE));
const PxFilterObjectAttributes filterAttr0 = getFilterObjectAttributes<false>(s0);
const PxFilterObjectAttributes filterAttr1 = getFilterObjectAttributes<false>(s1);
bool isNonRigid = false;
bool isKinePair = false;
if(filterRbCollisionPairShared<true>(filterInfo, isNonRigid, isKinePair, context, s0, s1, filterAttr0, filterAttr1))
return;
filterRbCollisionPairSecondStage(filterInfo, context, s0, s1, isKinePair, filterAttr0, filterAttr1, true, isNonRigid);
}
static PX_FORCE_INLINE bool testElementSimPointers(const ElementSim* e0, const ElementSim* e1)
{
PX_ASSERT(e0);
PX_ASSERT(e1);
// PT: a bit of defensive coding added for OM-74224. In theory this should not be needed, as the broadphase is not
// supposed to return null pointers here. But there seems to be an issue somewhere, most probably in the GPU BP kernels,
// and this is an attempt at preventing a crash. We could/should remove this eventually.
if(!e0 || !e1)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__, "NPhaseCore::runOverlapFilters: found null elements!");
return true;
}
static PX_FORCE_INLINE bool testShapeSimCorePointers(const ShapeSimBase* s0, const ShapeSimBase* s1)
{
bool isValid0 = s0->isPxsCoreValid();
bool isValid1 = s1->isPxsCoreValid();
PX_ASSERT(isValid0);
PX_ASSERT(isValid1);
// GW: further defensive coding added for OM-111249
// This is only a temporary / immediate solution to mitigate crashes
// Still need to root-cause what is causing null pointers here
if(!isValid0 || !isValid1)
return outputError<PxErrorCode::eINTERNAL_ERROR>(__LINE__,
"NPhaseCore::runOverlapFilters: found null PxsShapeCore pointers!");
return true;
}
// PT: called from OverlapFilterTask
void NPhaseCore::runOverlapFilters( PxU32 nbToProcess, const Bp::AABBOverlap* PX_RESTRICT pairs, FilterInfo* PX_RESTRICT filterInfo,
PxU32& nbToKeep_, PxU32& nbToSuppress_, PxU32* PX_RESTRICT keepMap
)
{
PxU32 nbToKeep = 0;
PxU32 nbToSuppress = 0;
const FilteringContext context(mOwnerScene);
for(PxU32 i=0; i<nbToProcess; i++)
{
const Bp::AABBOverlap& pair = pairs[i];
const ElementSim* e0 = reinterpret_cast<const ElementSim*>(pair.mUserData0);
const ElementSim* e1 = reinterpret_cast<const ElementSim*>(pair.mUserData1);
if(!testElementSimPointers(e0, e1))
continue;
PX_ASSERT(!findInteraction(e0, e1));
const ShapeSimBase* s0 = static_cast<const ShapeSimBase*>(e0);
const ShapeSimBase* s1 = static_cast<const ShapeSimBase*>(e1);
if(!testShapeSimCorePointers(s0, s1))
continue;
PX_ASSERT(&s0->getActor() != &s1->getActor()); // No actor internal interactions
filterInfo[i].filterFlags = PxFilterFlags(0);
filterInfo[i].pairFlags = PxPairFlags(0);
filterInfo[i].hasPairID = false;
filterRbCollisionPairAllTests(filterInfo[i], context, *s0, *s1);
const PxFilterFlags filterFlags = filterInfo[i].filterFlags;
if(!(filterFlags & PxFilterFlag::eKILL))
{
if(!(filterFlags & PxFilterFlag::eSUPPRESS))
nbToKeep++;
else
nbToSuppress++;
keepMap[i / 32] |= (1 << (i & 31));
}
}
nbToKeep_ = nbToKeep;
nbToSuppress_ = nbToSuppress;
}
ElementSimInteraction* NPhaseCore::createTriggerElementInteraction(ShapeSimBase& s0, ShapeSimBase& s1)
{
PX_ASSERT((s0.getFlags() & PxShapeFlag::eTRIGGER_SHAPE) || (s1.getFlags() & PxShapeFlag::eTRIGGER_SHAPE));
const FilteringContext context(mOwnerScene);
bool isTriggerPair;
FilterInfo filterInfo;
filterRbCollisionPair(filterInfo, context, s0, s1, isTriggerPair, false);
PX_ASSERT(isTriggerPair);
if(filterInfo.filterFlags & PxFilterFlag::eKILL)
{
PX_ASSERT(!filterInfo.hasPairID); // No filter callback pair info for killed pairs
return NULL;
}
return createRbElementInteraction(filterInfo, s0, s1, NULL, NULL, NULL, isTriggerPair);
}
void NPhaseCore::onTriggerOverlapCreated(const Bp::AABBOverlap* PX_RESTRICT pairs, PxU32 pairCount)
{
for(PxU32 i=0; i<pairCount; i++)
{
ElementSim* volume0 = reinterpret_cast<ElementSim*>(pairs[i].mUserData0);
ElementSim* volume1 = reinterpret_cast<ElementSim*>(pairs[i].mUserData1);
if(!testElementSimPointers(volume0, volume1))
continue;
PX_ASSERT(!findInteraction(volume0, volume1));
ShapeSimBase* shapeHi = static_cast<ShapeSimBase*>(volume1);
ShapeSimBase* shapeLo = static_cast<ShapeSimBase*>(volume0);
// No actor internal interactions
PX_ASSERT(&shapeHi->getActor() != &shapeLo->getActor());
// PT: this case is only for triggers these days
PX_ASSERT((shapeLo->getFlags() & PxShapeFlag::eTRIGGER_SHAPE) || (shapeHi->getFlags() & PxShapeFlag::eTRIGGER_SHAPE));
createTriggerElementInteraction(*shapeHi, *shapeLo);
}
}
void NPhaseCore::callPairLost(const ShapeSimBase& s0, const ShapeSimBase& s1, bool objVolumeRemoved)
{
const PxFilterObjectAttributes fa0 = getFilterObjectAttributes<true>(s0);
const PxFilterObjectAttributes fa1 = getFilterObjectAttributes<true>(s1);
const PxFilterData& fd0 = s0.getCore().getSimulationFilterData();
const PxFilterData& fd1 = s1.getCore().getSimulationFilterData();
mOwnerScene.getFilterCallbackFast()->pairLost(getPairID(s0, s1), fa0, fd0, fa1, fd1, objVolumeRemoved);
}
ElementSimInteraction* NPhaseCore::refilterInteraction(ElementSimInteraction* pair, const FilterInfo* filterInfo, bool removeFromDirtyList, PxsContactManagerOutputIterator& outputs)
{
const InteractionType::Enum oldType = pair->getType();
switch (oldType)
{
case InteractionType::eTRIGGER:
case InteractionType::eMARKER:
case InteractionType::eOVERLAP:
{
ShapeSimBase& s0 = static_cast<ShapeSimBase&>(pair->getElement0());
ShapeSimBase& s1 = static_cast<ShapeSimBase&>(pair->getElement1());
FilterInfo finfo;
if(filterInfo)
{
// The filter changes are provided by an outside source (the user filter callback)
finfo = *filterInfo;
PX_ASSERT(finfo.hasPairID);
if((finfo.filterFlags & PxFilterFlag::eKILL) &&
((finfo.filterFlags & PxFilterFlag::eNOTIFY) == PxFilterFlag::eNOTIFY) )
{
callPairLost(s0, s1, false);
finfo.hasPairID = false;
}
ActorSim& bs0 = s0.getActor();
ActorSim& bs1 = s1.getActor();
const bool isKinePair = PxFilterObjectIsKinematic(bs0.getFilterAttributes()) && PxFilterObjectIsKinematic(bs1.getFilterAttributes());
finfo.pairFlags = checkRbPairFlags(s0, s1, isKinePair, finfo.pairFlags, finfo.filterFlags, s0.getActor().isNonRigid() || s1.getActor().isNonRigid());
}
else
{
if(pair->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR))
callPairLost(s0, s1, false);
const FilteringContext context(mOwnerScene);
bool isTriggerPair;
filterRbCollisionPair(finfo, context, s0, s1, isTriggerPair, true);
PX_UNUSED(isTriggerPair);
}
if(pair->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR) &&
((finfo.filterFlags & PxFilterFlag::eNOTIFY) != PxFilterFlag::eNOTIFY) )
{
// The pair was a filter callback pair but not any longer
pair->clearInteractionFlag(InteractionFlag::eIS_FILTER_PAIR);
finfo.hasPairID = false;
}
struct Local
{
static InteractionType::Enum getRbElementInteractionType(const ShapeSimBase* primitive0, const ShapeSimBase* primitive1, PxFilterFlags filterFlag)
{
if(filterFlag & PxFilterFlag::eKILL)
return InteractionType::eINVALID;
if(filterFlag & PxFilterFlag::eSUPPRESS)
return InteractionType::eMARKER;
if(primitive0->getFlags() & PxShapeFlag::eTRIGGER_SHAPE
|| primitive1->getFlags() & PxShapeFlag::eTRIGGER_SHAPE)
return InteractionType::eTRIGGER;
PX_ASSERT( (primitive0->getGeometryType() != PxGeometryType::eTRIANGLEMESH) ||
(primitive1->getGeometryType() != PxGeometryType::eTRIANGLEMESH));
return InteractionType::eOVERLAP;
}
};
const InteractionType::Enum newType = Local::getRbElementInteractionType(&s0, &s1, finfo.filterFlags);
if(pair->getType() != newType) //Only convert interaction type if the type has changed
{
return convert(pair, newType, finfo, removeFromDirtyList, outputs);
}
else
{
//The pair flags might have changed, we need to forward the new ones
if(oldType == InteractionType::eOVERLAP)
{
ShapeInteraction* si = static_cast<ShapeInteraction*>(pair);
const PxU32 newPairFlags = finfo.pairFlags;
const PxU32 oldPairFlags = si->getPairFlags();
PX_ASSERT((newPairFlags & ShapeInteraction::PAIR_FLAGS_MASK) == newPairFlags);
PX_ASSERT((oldPairFlags & ShapeInteraction::PAIR_FLAGS_MASK) == oldPairFlags);
if(newPairFlags != oldPairFlags)
{
if(!(oldPairFlags & ShapeInteraction::CONTACT_REPORT_EVENTS) && (newPairFlags & ShapeInteraction::CONTACT_REPORT_EVENTS) && (si->getActorPair() == NULL || !si->getActorPair()->isReportPair()))
{
// for this actor pair there was no shape pair that requested contact reports but now there is one
// -> all the existing shape pairs need to get re-adjusted to point to an ActorPairReport instance instead.
ActorPair* actorPair = findActorPair(&s0, &s1, PxIntTrue);
if (si->getActorPair() == NULL)
{
actorPair->incRefCount();
si->setActorPair(*actorPair);
}
}
if(si->readFlag(ShapeInteraction::IN_PERSISTENT_EVENT_LIST) && (!(newPairFlags & PxPairFlag::eNOTIFY_TOUCH_PERSISTS)))
{
// the new report pair flags don't require persistent checks anymore -> remove from persistent list
// Note: The pair might get added to the force threshold list later
if(si->readFlag(ShapeInteraction::IS_IN_PERSISTENT_EVENT_LIST))
removeFromPersistentContactEventPairs(si);
else
si->clearFlag(ShapeInteraction::WAS_IN_PERSISTENT_EVENT_LIST);
}
if(newPairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS)
{
PX_ASSERT((si->mReportPairIndex == INVALID_REPORT_PAIR_ID) || (!si->readFlag(ShapeInteraction::WAS_IN_PERSISTENT_EVENT_LIST)));
if(si->mReportPairIndex == INVALID_REPORT_PAIR_ID && si->readInteractionFlag(InteractionFlag::eIS_ACTIVE))
{
PX_ASSERT(!si->readFlag(ShapeInteraction::WAS_IN_PERSISTENT_EVENT_LIST)); // sanity check: an active pair should never have this flag set
if(si->hasTouch())
addToForceThresholdContactEventPairs(si);
}
}
else if((oldPairFlags & ShapeInteraction::CONTACT_FORCE_THRESHOLD_PAIRS))
{
// no force threshold events needed any longer -> clear flags
si->clearFlag(ShapeInteraction::FORCE_THRESHOLD_EXCEEDED_FLAGS);
if(si->readFlag(ShapeInteraction::IS_IN_FORCE_THRESHOLD_EVENT_LIST))
removeFromForceThresholdContactEventPairs(si);
}
}
si->setPairFlags(finfo.pairFlags);
}
else if(oldType == InteractionType::eTRIGGER)
static_cast<TriggerInteraction*>(pair)->setTriggerFlags(finfo.pairFlags);
return pair;
}
}
case InteractionType::eCONSTRAINTSHADER:
case InteractionType::eARTICULATION:
case InteractionType::eTRACKED_IN_SCENE_COUNT:
case InteractionType::eINVALID:
PX_ASSERT(0);
break;
}
return NULL;
}
void NPhaseCore::fireCustomFilteringCallbacks(PxsContactManagerOutputIterator& outputs)
{
PX_PROFILE_ZONE("Sim.fireCustomFilteringCallbacks", mOwnerScene.getContextId());
PxSimulationFilterCallback* callback = mOwnerScene.getFilterCallbackFast();
if(callback)
{
// Ask user for pair filter status changes
PxU64 pairID;
PxFilterFlags filterFlags;
PxPairFlags pairFlags;
while(callback->statusChange(pairID, pairFlags, filterFlags))
{
const PxU32 id0 = PxU32(pairID);
const PxU32 id1 = PxU32(pairID>>32);
const PxHashMap<ElementSimKey, ElementSimInteraction*>::Entry* pair = mElementSimMap.find(ElementSimKey(id0, id1));
ElementSimInteraction* ei = pair ? pair->second : NULL;
PX_ASSERT(ei);
// Check if the user tries to update a pair even though he deleted it earlier in the same frame
checkFilterFlags(filterFlags);
PX_ASSERT(ei->readInteractionFlag(InteractionFlag::eIS_FILTER_PAIR));
FilterInfo finfo;
finfo.filterFlags = filterFlags;
finfo.pairFlags = pairFlags;
finfo.hasPairID = true;
ElementSimInteraction* refInt = refilterInteraction(ei, &finfo, true, outputs);
// this gets called at the end of the simulation -> there should be no dirty interactions around
PX_ASSERT(!refInt->readInteractionFlag(InteractionFlag::eIN_DIRTY_LIST));
PX_ASSERT(!refInt->getDirtyFlags());
if((refInt == ei) && (refInt->getType() == InteractionType::eOVERLAP)) // No interaction conversion happened, the pairFlags were just updated
static_cast<ShapeInteraction*>(refInt)->updateState(InteractionDirtyFlag::eFILTER_STATE);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScRigidSim.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 "ScScene.h"
#include "ScRigidSim.h"
#include "ScShapeSim.h"
#include "PxsSimulationController.h"
using namespace physx;
using namespace Sc;
/*
PT:
The BP group ID comes from a Cm::IDPool, and ActorSim is the only class releasing the ID.
The rigid tracker ID comes from a Cm::IDPool internal to an ObjectIDTracker, and ActorSim
is the only class using it.
Thus we should:
- promote the BP group ID stuff to a "tracker" object
- use the BP group ID as a rigid ID
*/
RigidSim::RigidSim(Scene& scene, RigidCore& core) : ActorSim(scene, core)
{
}
RigidSim::~RigidSim()
{
}
void notifyActorInteractionsOfTransformChange(ActorSim& actor);
void RigidSim::notifyShapesOfTransformChange()
{
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*elems++);
sim->markBoundsForUpdate();
}
notifyActorInteractionsOfTransformChange(*this);
}
void RigidSim::setBodyNodeIndex(const PxNodeIndex nodeIndex)
{
PxU32 nbElems = getNbElements();
ElementSim** elems = getElements();
while (nbElems--)
{
ShapeSim* sim = static_cast<ShapeSim*>(*elems++);
getScene().getSimulationController()->updateShape(sim->getLLShapeSim(), nodeIndex);
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScHairSystemShapeCore.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.
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "foundation/PxErrorCallback.h"
#include "ScHairSystemShapeCore.h"
#include "ScHairSystemShapeSim.h"
#include "ScPhysics.h"
#include "PxvGlobals.h"
#include "PxPhysXGpu.h"
using namespace physx;
using namespace Sc;
namespace physx
{
namespace Sc
{
HairSystemShapeCore::HairSystemShapeCore()
: ShapeCore(PxEmpty)
, mGpuMemStat(0)
{
mSimulationFilterData = PxFilterData();
mCore = PxsShapeCore();
const PxTolerancesScale& scale = Physics::getInstance().getTolerancesScale();
mCore.setTransform(PxTransform(PxIdentity));
mCore.mContactOffset = 0.0f;
mCore.mRestOffset = 0.0f;
mCore.mShapeFlags = 0;
mCore.mMinTorsionalPatchRadius = 0.f;
mCore.mTorsionalRadius = 0.f;
mLLCore.mSleepThreshold = 5e-5f * scale.speed * scale.speed;
mLLCore.mWakeCounter = Physics::sWakeCounterOnCreation;
}
// PX_SERIALIZATION
HairSystemShapeCore::HairSystemShapeCore(const PxEMPTY)
: ShapeCore(PxEmpty)
{
}
HairSystemShapeCore::~HairSystemShapeCore()
{
releaseBuffers();
}
void HairSystemShapeCore::createBuffers(PxCudaContextManager* cudaContextManager)
{
mCudaContextManager = cudaContextManager;
// nothing else to do at the moment
}
void HairSystemShapeCore::releaseBuffers()
{
// nothing to do at the moment
}
} // namespace Sc
} // namespace physx
#endif // PX_SUPPORT_GPU_PHYSX
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/src/ScStaticCore.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 "ScStaticCore.h"
#include "ScStaticSim.h"
#include "PxRigidStatic.h"
using namespace physx;
Sc::StaticSim* Sc::StaticCore::getSim() const
{
return static_cast<StaticSim*>(Sc::ActorCore::getSim());
}
void Sc::StaticCore::setActor2World(const PxTransform& actor2World)
{
mCore.body2World = actor2World;
StaticSim* sim = getSim();
if(sim)
sim->notifyShapesOfTransformChange();
}
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScBroadphase.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 SC_BROADPHASE_H
#define SC_BROADPHASE_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
// PT: this class captures parts of the Sc::Scene that deals with broadphase matters.
namespace physx
{
class PxBroadPhaseCallback;
namespace Bp
{
class AABBManagerBase;
}
namespace Sc
{
class ObjectIDTracker;
class BroadphaseManager
{
public:
BroadphaseManager();
~BroadphaseManager();
PX_FORCE_INLINE void setBroadPhaseCallback(PxBroadPhaseCallback* callback) { mBroadPhaseCallback = callback; }
PX_FORCE_INLINE PxBroadPhaseCallback* getBroadPhaseCallback() const { return mBroadPhaseCallback; }
void prepareOutOfBoundsCallbacks(Bp::AABBManagerBase* aabbManager);
bool fireOutOfBoundsCallbacks(Bp::AABBManagerBase* aabbManager, const ObjectIDTracker& tracker);
void flush(Bp::AABBManagerBase* aabbManager);
PxBroadPhaseCallback* mBroadPhaseCallback;
PxArray<PxU32> mOutOfBoundsIDs;
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScFEMClothCore.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_SCP_FEMCLOTH_CORE
#define PX_PHYSICS_SCP_FEMCLOTH_CORE
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#endif
#include "PxFEMParameter.h"
#include "../../lowleveldynamics/include/DyFEMClothCore.h"
#include "foundation/PxAssert.h"
#include "ScActorCore.h"
#include "ScShapeCore.h"
#include "PxFiltering.h"
#include "ScRigidCore.h" //KS - required for ShapeChangeNotifyFlags. Ideally, we should move that to a separate shared file
#include "PxConeLimitedConstraint.h"
namespace physx
{
namespace Sc
{
class FEMClothSim;
class FEMClothCore : public ActorCore
{
// PX_SERIALIZATION
public:
FEMClothCore(const PxEMPTY) : ActorCore(PxEmpty) {}
//static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
FEMClothCore();
~FEMClothCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
PxFEMParameters getParameter() const;
void setParameter(const PxFEMParameters& paramters);
void addRigidFilter(Sc::BodyCore* core, PxU32 vertId);
void removeRigidFilter(Sc::BodyCore* core, PxU32 vertId);
PxU32 addRigidAttachment(Sc::BodyCore* core, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void removeRigidAttachment(Sc::BodyCore* core, PxU32 handle);
void addTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx);
void removeTriRigidFilter(Sc::BodyCore* core, PxU32 triIdx);
PxU32 addTriRigidAttachment(Sc::BodyCore* core, PxU32 triIdx, const PxVec4& barycentric,
const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void removeTriRigidAttachment(Sc::BodyCore* core, PxU32 handle);
void addClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, PxU32 triIdx);
void removeClothFilter(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx0, PxU32 triIdx);
PxU32 addClothAttachment(Sc::FEMClothCore* otherCore, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx,
const PxVec4& triBarycentric);
void removeClothAttachment(Sc::FEMClothCore* otherCore, PxU32 handle);
#if 0 // disabled until future use.
void setDrag(const PxReal v) { mCore.drag = v; }
PxReal getDrag() const { return mCore.drag; }
void setLift(const PxReal v) { mCore.lift = v; }
PxReal getLift() const { return mCore.lift; }
void setWind(const PxVec3& wind) { mCore.wind = wind; }
PxVec3 getWind() const { return mCore.wind; }
void setAirDensity(const float airDensity) { mCore.airDensity = airDensity; }
PxReal getAirDensity() const { return mCore.airDensity; }
void setBendingActivationAngle(const PxReal angle) { mCore.mBendingActivationAngle = angle; }
PxReal getBendingActivationAngle() const { return mCore.mBendingActivationAngle; }
#endif
void setBendingScales(const PxReal* const bendingScales, PxU32 nbElements);
const PxReal* getBendingScales() const;
PxU32 getNbBendingScales() const { return mCore.mBendingScales.size(); }
void setMaxVelocity(const float maxVelocity) { mCore.maxVelocity = maxVelocity; }
PxReal getMaxVelocity() const { return mCore.maxVelocity; }
void setMaxDepenetrationVelocity(const float maxDepenetrationVelocity) { mCore.maxDepenetrationVelocity = maxDepenetrationVelocity; }
PxReal getMaxDepenetrationVelocity() const { return mCore.maxDepenetrationVelocity; }
void setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency) { mCore.nbCollisionPairUpdatesPerTimestep = frequency; }
PxU32 getNbCollisionPairUpdatesPerTimestep() const { return mCore.nbCollisionPairUpdatesPerTimestep; }
void setNbCollisionSubsteps(const PxU32 frequency) { mCore.nbCollisionSubsteps = frequency; }
PxU32 getNbCollisionSubsteps() const { return mCore.nbCollisionSubsteps; }
PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; }
void setSolverIterationCounts(PxU16 c);
PxActor* getPxActor() const;
void attachShapeCore(ShapeCore* shapeCore);
PxReal getWakeCounter() const;
void setWakeCounter(const PxReal v);
void setWakeCounterInternal(const PxReal v);
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
public:
FEMClothSim* getSim() const;
PX_FORCE_INLINE const Dy::FEMClothCore& getCore() const { return mCore; }
PX_FORCE_INLINE Dy::FEMClothCore& getCore() { return mCore; }
static PX_FORCE_INLINE FEMClothCore& getFEMClothCore(FEMClothCore& core)
{
size_t offset = PX_OFFSET_OF_RT(FEMClothCore, mCore);
return *reinterpret_cast<FEMClothCore*>(reinterpret_cast<PxU8*>(&core) - offset);
}
void setSimulationFilterData(const PxFilterData& data);
PxFilterData getSimulationFilterData() const;
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
PxFEMClothFlags getFlags() const { return mCore.mFlags; }
void setFlags(PxFEMClothFlags flags);
#endif
PX_FORCE_INLINE PxU64& getGpuMemStat() { return mGpuMemStat; }
void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags);
private:
Dy::FEMClothCore mCore;
PxFilterData mFilterData;
PxU64 mGpuMemStat;
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationAttachmentCore.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 SC_ATTACHMENT_CORE_H
#define SC_ATTACHMENT_CORE_H
#include "foundation/PxVec3.h"
namespace physx
{
namespace Sc
{
class ArticulationAttachmentCore
{
public:
// PX_SERIALIZATION
ArticulationAttachmentCore(const PxEMPTY) : mTendonSim(NULL) {}
void preExportDataReset() { }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationAttachmentCore() : mLowLimit(PX_MAX_F32), mHighLimit(-PX_MAX_F32), mRestLength(0.f)
{
}
PxVec3 mRelativeOffset; //relative offset to the link(in link space)
ArticulationAttachmentCore* mParent;
PxReal mLowLimit;
PxReal mHighLimit;
PxReal mRestLength;
PxReal mCoefficient;
PxU32 mLLLinkIndex;
PxU32 mAttachmentIndex;
Sc::ArticulationSpatialTendonSim* mTendonSim;
};
}//namespace Sc
}//namespace physx
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScScene.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 SC_SCENE_H
#define SC_SCENE_H
#include "PxPhysXConfig.h"
#include "PxScene.h"
#include "PxSimulationEventCallback.h"
#include "foundation/PxPool.h"
#include "foundation/PxHashSet.h"
#include "foundation/PxHashMap.h"
#include "CmTask.h"
#include "CmFlushPool.h"
#include "CmPreallocatingPool.h"
#include "foundation/PxBitMap.h"
#include "ScIterators.h"
#include "PxsMaterialManager.h"
#include "PxvManager.h"
#include "ScStaticCore.h"
#include "ScBodyCore.h"
#include "PxAggregate.h"
#include "PxsContext.h"
#include "PxsIslandSim.h"
#include "GuPrunerTypedef.h"
#include "DyContext.h"
#include "ScFiltering.h"
#include "ScBroadphase.h"
#include "ScInteraction.h"
#define PX_MAX_DOMINANCE_GROUP 32
class OverlapFilterTask;
namespace physx
{
class NpShape;
struct PxTriggerPair;
class PxsSimulationController;
class PxsSimulationControllerCallback;
class PxsMemoryManager;
struct PxConeLimitedConstraint;
#if PX_SUPPORT_GPU_PHYSX
class PxsKernelWranglerManager;
class PxsHeapMemoryAllocatorManager;
#endif
namespace IG
{
class SimpleIslandManager;
class NodeIndex;
typedef PxU32 EdgeIndex;
}
class PxsCCDContext;
namespace Cm
{
class IDPool;
}
namespace Bp
{
class AABBManagerBase;
class BroadPhase;
class BoundsArray;
}
namespace Dy
{
class FeatherstoneArticulation;
class Context;
#if PX_SUPPORT_GPU_PHYSX
class SoftBody;
class FEMCloth;
class ParticleSystem;
class HairSystem;
#endif
}
namespace Sc
{
class ActorSim;
class ElementSim;
class ShapeCore;
class RigidCore;
class ConstraintCore;
class ArticulationCore;
class ArticulationJointCore;
class ArticulationSpatialTendonCore;
class ArticulationFixedTendonCore;
class ArticulationSensorCore;
class LLArticulationPool;
class LLArticulationRCPool;
class LLSoftBodyPool;
class LLFEMClothPool;
class LLParticleSystemPool;
class LLHairSystemPool;
class BodyCore;
class SoftBodyCore;
class FEMClothCore;
class ParticleSystemCore;
class HairSystemCore;
class NPhaseCore;
class ConstraintInteraction;
class ElementSimInteraction;
class BodySim;
class ShapeSim;
class RigidSim;
class StaticSim;
class ConstraintSim;
struct TriggerPairExtraData;
class ObjectIDTracker;
class ActorPairReport;
class ContactStreamManager;
class SqBoundsManager;
class ShapeInteraction;
class ElementInteractionMarker;
class ArticulationSim;
class SoftBodySim;
class FEMClothSim;
class ParticleSystemSim;
class HairSystemSim;
class SimStats;
struct SimStateData;
struct BatchInsertionState
{
BodySim* bodySim;
StaticSim*staticSim;
ShapeSim* shapeSim;
ptrdiff_t staticActorOffset;
ptrdiff_t staticShapeTableOffset;
ptrdiff_t dynamicActorOffset;
ptrdiff_t dynamicShapeTableOffset;
ptrdiff_t shapeOffset;
};
struct BatchRemoveState
{
PxInlineArray<ShapeSim*, 64> bufferedShapes;
PxInlineArray<const ShapeCore*, 64> removedShapes;
};
struct SceneInternalFlag
{
enum Enum
{
eSCENE_SIP_STATES_DIRTY_DOMINANCE = (1<<1),
eSCENE_SIP_STATES_DIRTY_VISUALIZATION = (1<<2),
eSCENE_DEFAULT = 0
};
};
struct SimulationStage
{
enum Enum
{
eCOMPLETE,
eCOLLIDE,
eFETCHCOLLIDE,
eADVANCE,
eFETCHRESULT
};
};
struct SqBoundsSync;
struct SqRefFinder;
struct ParticleOrSoftBodyRigidInteraction
{
IG::EdgeIndex mIndex;
PxU32 mCount;
ParticleOrSoftBodyRigidInteraction() : mCount(0) {}
};
class Scene : public PxUserAllocated
{
struct SimpleBodyPair
{
ActorSim* body1;
ActorSim* body2;
PxU32 body1ID;
PxU32 body2ID;
};
PX_NOCOPY(Scene)
public:
Scene(const PxSceneDesc& desc, PxU64 contextID);
~Scene() {} //use release() plz.
void preAllocate(PxU32 nbStatics, PxU32 nbBodies, PxU32 nbStaticShapes, PxU32 nbDynamicShapes);
void release();
PX_FORCE_INLINE PxsSimulationController* getSimulationController() { return mSimulationController; }
PX_FORCE_INLINE const PxsSimulationController* getSimulationController() const { return mSimulationController; }
PX_FORCE_INLINE Bp::AABBManagerBase* getAABBManager() { return mAABBManager; }
PX_FORCE_INLINE const Bp::AABBManagerBase* getAABBManager() const { return mAABBManager; }
PX_FORCE_INLINE PxArray<BodySim*>& getCcdBodies() { return mCcdBodies; }
PX_FORCE_INLINE IG::SimpleIslandManager* getSimpleIslandManager() { return mSimpleIslandManager; }
PX_FORCE_INLINE const IG::SimpleIslandManager* getSimpleIslandManager() const { return mSimpleIslandManager; }
PX_FORCE_INLINE SimulationStage::Enum getSimulationStage() const { return mSimulationStage; }
PX_FORCE_INLINE void setSimulationStage(SimulationStage::Enum stage) { mSimulationStage = stage; }
PX_FORCE_INLINE PxPool<SimStateData>* getSimStateDataPool() { return mSimStateDataPool; }
PX_FORCE_INLINE PxBitMap& getDirtyShapeSimMap() { return mDirtyShapeSimMap; }
PX_FORCE_INLINE void setGravity(const PxVec3& g) { mGravity = g; }
PX_FORCE_INLINE const PxVec3& getGravity() const { return mGravity; }
PX_FORCE_INLINE void setElapsedTime(PxReal t) { mDt = t; mOneOverDt = t > 0.0f ? 1.0f/t : 0.0f; }
PX_FORCE_INLINE PxReal getOneOverDt() const { return mOneOverDt; }
// PX_FORCE_INLINE PxReal getDt() const { return mDt; }
PX_FORCE_INLINE void setLimits(const PxSceneLimits& limits) { mLimits = limits; }
PX_FORCE_INLINE const PxSceneLimits& getLimits() const { return mLimits; }
PX_FORCE_INLINE void setBatchRemove(BatchRemoveState* bs) { mBatchRemoveState = bs; }
PX_FORCE_INLINE BatchRemoveState* getBatchRemove() const { return mBatchRemoveState; }
PX_FORCE_INLINE void setMaxArticulationLinks(const PxU32 maxLinks) { mMaxNbArticulationLinks = maxLinks; }
PX_FORCE_INLINE PxU32 getMaxArticulationLinks() const { return mMaxNbArticulationLinks; }
// mDynamicsContext wrappers
PX_FORCE_INLINE Dy::Context* getDynamicsContext() { return mDynamicsContext; }
PX_FORCE_INLINE const Dy::Context* getDynamicsContext() const { return mDynamicsContext; }
PX_FORCE_INLINE void setBounceThresholdVelocity(PxReal t) { mDynamicsContext->setBounceThreshold(-t); }
PX_FORCE_INLINE PxReal getBounceThresholdVelocity() const { return -mDynamicsContext->getBounceThreshold(); }
PX_FORCE_INLINE PxSolverType::Enum getSolverType() const { return mDynamicsContext->getSolverType(); }
PX_FORCE_INLINE void setFrictionType(PxFrictionType::Enum model) { mDynamicsContext->setFrictionType(model); }
PX_FORCE_INLINE PxFrictionType::Enum getFrictionType() const { return mDynamicsContext->getFrictionType(); }
PX_FORCE_INLINE void setSolverBatchSize(PxU32 solverBatchSize) { mDynamicsContext->setSolverBatchSize(solverBatchSize); }
PX_FORCE_INLINE PxU32 getSolverBatchSize() const { return mDynamicsContext->getSolverBatchSize(); }
PX_FORCE_INLINE void setSolverArticBatchSize(PxU32 solverBatchSize) { mDynamicsContext->setSolverArticBatchSize(solverBatchSize); }
PX_FORCE_INLINE PxU32 getSolverArticBatchSize() const { return mDynamicsContext->getSolverArticBatchSize(); }
PX_FORCE_INLINE void setCCDMaxSeparation(PxReal separation) { mDynamicsContext->setCCDSeparationThreshold(separation); }
PX_FORCE_INLINE PxReal getCCDMaxSeparation() const { return mDynamicsContext->getCCDSeparationThreshold(); }
PX_FORCE_INLINE void setMaxBiasCoefficient(PxReal coeff) { mDynamicsContext->setMaxBiasCoefficient(coeff); }
PX_FORCE_INLINE PxReal getMaxBiasCoefficient() const { return mDynamicsContext->getMaxBiasCoefficient(); }
PX_FORCE_INLINE void setFrictionOffsetThreshold(PxReal t) { mDynamicsContext->setFrictionOffsetThreshold(t); }
PX_FORCE_INLINE PxReal getFrictionOffsetThreshold() const { return mDynamicsContext->getFrictionOffsetThreshold(); }
PX_FORCE_INLINE void setFrictionCorrelationDistance(PxReal t) { mDynamicsContext->setCorrelationDistance(t); }
PX_FORCE_INLINE PxReal getFrictionCorrelationDistance() const { return mDynamicsContext->getCorrelationDistance(); }
PX_FORCE_INLINE PxReal getLengthScale() const { return mDynamicsContext->getLengthScale(); }
PX_FORCE_INLINE void setDynamicsDirty() { mDynamicsContext->setStateDirty(true); }
//~mDynamicsContext wrappers
// mLLContext wrappers
PX_FORCE_INLINE PxsContext* getLowLevelContext() { return mLLContext; }
PX_FORCE_INLINE const PxsContext* getLowLevelContext() const { return mLLContext; }
PX_FORCE_INLINE Cm::FlushPool* getFlushPool() { return &mLLContext->getTaskPool(); }
PX_FORCE_INLINE void setPCM(bool enabled) { mLLContext->setPCM(enabled); }
PX_FORCE_INLINE void setContactCache(bool enabled) { mLLContext->setContactCache(enabled); }
PX_FORCE_INLINE void setContactModifyCallback(PxContactModifyCallback* callback) { mLLContext->setContactModifyCallback(callback); }
PX_FORCE_INLINE PxContactModifyCallback* getContactModifyCallback() const { return mLLContext->getContactModifyCallback(); }
PX_FORCE_INLINE void setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value)
{
mVisualizationParameterChanged = true;
mLLContext->setVisualizationParameter(param, value);
}
PX_FORCE_INLINE PxReal getVisualizationParameter(PxVisualizationParameter::Enum param) const { return mLLContext->getVisualizationParameter(param); }
PX_FORCE_INLINE void setVisualizationCullingBox(const PxBounds3& box) { mLLContext->setVisualizationCullingBox(box); }
PX_FORCE_INLINE const PxBounds3& getVisualizationCullingBox() const { return mLLContext->getVisualizationCullingBox(); }
PX_FORCE_INLINE PxReal getVisualizationScale() const { return mLLContext->getRenderScale(); }
PX_FORCE_INLINE PxRenderBuffer& getRenderBuffer() { return mLLContext->getRenderBuffer(); }
PX_FORCE_INLINE void setNbContactDataBlocks(PxU32 blockCount) { mLLContext->getNpMemBlockPool().setBlockCount(blockCount); }
PX_FORCE_INLINE PxU32 getNbContactDataBlocksUsed() const { return mLLContext->getNpMemBlockPool().getUsedBlockCount(); }
PX_FORCE_INLINE PxU32 getMaxNbContactDataBlocksUsed() const { return mLLContext->getNpMemBlockPool().getMaxUsedBlockCount(); }
PX_FORCE_INLINE PxU32 getMaxNbConstraintDataBlocksUsed() const { return mLLContext->getNpMemBlockPool().getPeakConstraintBlockCount(); }
PX_FORCE_INLINE void setScratchBlock(void* addr, PxU32 size) { mLLContext->setScratchBlock(addr, size); }
//~mLLContext wrappers
PX_FORCE_INLINE void setFlags(PxSceneFlags flags)
{
mPublicFlags = flags;
}
PX_FORCE_INLINE PxSceneFlags getFlags() const { return mPublicFlags; }
PX_FORCE_INLINE bool readInternalFlag(SceneInternalFlag::Enum flag) const { return (mInternalFlags & flag) != 0; }
void addStatic(StaticCore&, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* uninflatedBounds);
void removeStatic(StaticCore&, PxInlineArray<const ShapeCore*,64>& removedShapes, bool wakeOnLostTouch);
void addBody(BodyCore&, NpShape*const *shapes, PxU32 nbShapes, size_t shapePtrOffset, PxBounds3* uninflatedBounds, bool compound);
void removeBody(BodyCore&, PxInlineArray<const ShapeCore*,64>& removedShapes, bool wakeOnLostTouch);
// Batch insertion API.
// the bounds generated here are the uninflated bounds for the shapes, *if* they are trigger or sim shapes.
// It's up to the caller to ensure the bounds array is big enough.
// Some care is required in handling these since sim and SQ tweak the bounds in slightly different ways.
void startBatchInsertion(BatchInsertionState&);
void addStatic(PxActor* actor, BatchInsertionState&, PxBounds3* outBounds);
void addBody(PxActor* actor, BatchInsertionState&, PxBounds3* outBounds, bool compound);
void finishBatchInsertion(BatchInsertionState&);
void addConstraint(ConstraintCore&, RigidCore*, RigidCore*);
void removeConstraint(ConstraintCore&);
void addArticulation(ArticulationCore&, BodyCore& root);
void removeArticulation(ArticulationCore&);
void addArticulationJoint(ArticulationJointCore&, BodyCore& parent, BodyCore& child);
void removeArticulationJoint(ArticulationJointCore&);
void addArticulationTendon(ArticulationSpatialTendonCore&);
void removeArticulationTendon(ArticulationSpatialTendonCore&);
void addArticulationTendon(ArticulationFixedTendonCore&);
void removeArticulationTendon(ArticulationFixedTendonCore&);
void addArticulationSensor(ArticulationSensorCore&);
void removeArticulationSensor(ArticulationSensorCore&);
void addArticulationSimControl(ArticulationCore& core);
void removeArticulationSimControl(ArticulationCore& core);
void updateBodySim(BodySim& sim);
PX_FORCE_INLINE PxU32 getNbArticulations() const { return mArticulations.size(); }
PX_FORCE_INLINE ArticulationCore* const* getArticulations() { return mArticulations.getEntries(); }
PX_FORCE_INLINE PxU32 getNbConstraints() const { return mConstraints.size(); }
PX_FORCE_INLINE ConstraintCore*const* getConstraints() const { return mConstraints.getEntries(); }
PX_FORCE_INLINE ConstraintCore*const* getConstraints() { return mConstraints.getEntries(); }
void initContactsIterator(ContactIterator&, PxsContactManagerOutputIterator&);
void setSimulationEventCallback(PxSimulationEventCallback* callback);
PxSimulationEventCallback* getSimulationEventCallback() const;
void setCCDContactModifyCallback(PxCCDContactModifyCallback* callback);
PxCCDContactModifyCallback* getCCDContactModifyCallback() const;
void setCCDMaxPasses(PxU32 ccdMaxPasses);
PxU32 getCCDMaxPasses() const;
void setCCDThreshold(PxReal t);
PxReal getCCDThreshold() const;
// Broad-phase management
void finishBroadPhase(PxBaseTask* continuation);
void finishBroadPhaseStage2(PxU32 ccdPass);
void preallocateContactManagers(PxBaseTask* continuation);
void islandInsertion(PxBaseTask* continuation);
void registerContactManagers(PxBaseTask* continuation);
void registerInteractions(PxBaseTask* continuation);
void registerSceneInteractions(PxBaseTask* continuation);
void secondPassNarrowPhase(PxBaseTask* continuation);
void setDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance);
PxDominanceGroupPair getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const;
// Run
void simulate(PxReal timeStep, PxBaseTask* continuation);
void advance(PxReal timeStep, PxBaseTask* continuation);
void collide(PxReal timeStep, PxBaseTask* continuation);
void endSimulation();
void flush(bool sendPendingReports);
void fireBrokenConstraintCallbacks();
void fireTriggerCallbacks();
void fireQueuedContactCallbacks();
void fireOnAdvanceCallback();
const PxArray<PxContactPairHeader>&
getQueuedContactPairHeaders();
void postCallbacksPreSync();
void postCallbacksPreSyncKinematics();
void postReportsCleanup();
void fireCallbacksPostSync();
void syncSceneQueryBounds(SqBoundsSync& sync, SqRefFinder& finder);
PxU32 getDefaultContactReportStreamBufferSize() const;
void visualizeStartStep();
// PX_ENABLE_SIM_STATS
void getStats(PxSimulationStatistics& stats) const;
PX_FORCE_INLINE SimStats& getStatsInternal() { return *mStats; }
// PX_ENABLE_SIM_STATS
void buildActiveActors();
void buildActiveAndFrozenActors();
PxActor** getActiveActors(PxU32& nbActorsOut);
void setActiveActors(PxActor** actors, PxU32 nbActors);
PxActor** getFrozenActors(PxU32& nbActorsOut);
void finalizeContactStreamAndCreateHeader(PxContactPairHeader& header,
const ActorPairReport& aPair,
ContactStreamManager& cs, PxU32 removedShapeTestMask);
PxTaskManager* getTaskManagerPtr() const { return mTaskManager; }
PxCudaContextManager* getCudaContextManager() const { return mCudaContextManager; }
void shiftOrigin(const PxVec3& shift);
PX_FORCE_INLINE bool isCollisionPhaseActive() const { return mIsCollisionPhaseActive; }
PX_FORCE_INLINE void setCollisionPhaseToActive() { PX_ASSERT(!mIsCollisionPhaseActive); mIsCollisionPhaseActive = true; }
PX_FORCE_INLINE void setCollisionPhaseToInactive() { PX_ASSERT(mIsCollisionPhaseActive); mIsCollisionPhaseActive = false; }
void addShape_(RigidSim&, ShapeCore&);
void removeShape_(ShapeSim&, bool wakeOnLostTouch);
void registerShapeInNphase(RigidCore* rigidCore, const ShapeCore& shapeCore, const PxU32 transformCacheID);
void unregisterShapeFromNphase(const ShapeCore& shapeCore, const PxU32 transformCacheID);
void notifyNphaseOnUpdateShapeMaterial(const ShapeCore& shapeCore);
// Get an array of the active actors.
PX_FORCE_INLINE BodyCore*const* getActiveBodiesArray() const { return mActiveBodies.begin(); }
PX_FORCE_INLINE PxU32 getNumActiveBodies() const { return mActiveBodies.size(); }
PX_FORCE_INLINE BodyCore*const* getActiveCompoundBodiesArray() const { return mActiveCompoundBodies.begin(); }
PX_FORCE_INLINE PxU32 getNumActiveCompoundBodies() const { return mActiveCompoundBodies.size(); }
PX_FORCE_INLINE PxU32 getNbInteractions(InteractionType::Enum type) const { return mInteractions[type].size(); }
PX_FORCE_INLINE PxU32 getNbActiveInteractions(InteractionType::Enum type) const { return mActiveInteractionCount[type]; }
// Get all interactions of a certain type
PX_FORCE_INLINE ElementSimInteraction** getInteractions(InteractionType::Enum type) { return mInteractions[type].begin(); }
PX_FORCE_INLINE ElementSimInteraction** getActiveInteractions(InteractionType::Enum type) { return mInteractions[type].begin(); }
void registerInteraction(ElementSimInteraction* interaction, bool active);
void unregisterInteraction(ElementSimInteraction* interaction);
void notifyInteractionActivated(Interaction* interaction);
void notifyInteractionDeactivated(Interaction* interaction);
// for pool management of interaction arrays, a major cause of dynamic allocation
void** allocatePointerBlock(PxU32 size);
void deallocatePointerBlock(void**, PxU32 size);
private:
// Get the number of active one-way dominator actors
PX_FORCE_INLINE PxU32 getActiveKinematicBodiesCount() const { return mActiveKinematicBodyCount; }
// Get an iterator to the active one-way dominator actors
PX_FORCE_INLINE BodyCore*const* getActiveKinematicBodies() const { return mActiveBodies.begin(); }
// Get the number of active non-kinematic actors
PX_FORCE_INLINE PxU32 getActiveDynamicBodiesCount() const { return mActiveBodies.size() - mActiveKinematicBodyCount; }
// Get the active non-kinematic actors
PX_FORCE_INLINE BodyCore*const* getActiveDynamicBodies() const { return mActiveBodies.begin() + mActiveKinematicBodyCount; }
void swapInteractionArrayIndices(PxU32 id1, PxU32 id2, InteractionType::Enum type);
public:
void addDirtyArticulationSim(ArticulationSim* artiSim);
void removeDirtyArticulationSim(ArticulationSim* artiSim);
void addToActiveList(ActorSim& actor);
void removeFromActiveList(ActorSim& actor);
void removeFromActiveCompoundBodyList(BodySim& actor);
void swapInActiveBodyList(BodySim& body); // call when an active body gets switched from dynamic to kinematic or vice versa
void addActiveBreakableConstraint(ConstraintSim*, ConstraintInteraction*);
void removeActiveBreakableConstraint(ConstraintSim*);
//the Actor should register its top level shapes with these.
void removeBody(BodySim&);
//lists of actors woken up or put to sleep last simulate
void onBodyWakeUp(BodySim* body);
void onBodySleep(BodySim* body);
PX_FORCE_INLINE bool isValid() const { return (mLLContext != NULL); }
void addToLostTouchList(ActorSim& body1, ActorSim& body2);
PxU32 createAggregate(void* userData, PxU32 maxNumShapes, PxAggregateFilterHint filterHint);
void deleteAggregate(PxU32 id);
Dy::FeatherstoneArticulation* createLLArticulation(ArticulationSim* sim);
void destroyLLArticulation(Dy::FeatherstoneArticulation&);
PX_FORCE_INLINE PxPool<ConstraintInteraction>* getConstraintInteractionPool() const { return mConstraintInteractionPool; }
public:
PX_FORCE_INLINE const PxsMaterialManager& getMaterialManager() const { return mMaterialManager; }
PX_FORCE_INLINE PxsMaterialManager& getMaterialManager() { return mMaterialManager; }
PX_FORCE_INLINE const BroadphaseManager& getBroadphaseManager() const { return mBroadphaseManager; }
PX_FORCE_INLINE BroadphaseManager& getBroadphaseManager() { return mBroadphaseManager; }
PX_FORCE_INLINE bool fireOutOfBoundsCallbacks()
{
return mBroadphaseManager.fireOutOfBoundsCallbacks(mAABBManager, *mElementIDPool);
}
// Collision filtering
void setFilterShaderData(const void* data, PxU32 dataSize);
PX_FORCE_INLINE const void* getFilterShaderDataFast() const { return mFilterShaderData; }
PX_FORCE_INLINE PxU32 getFilterShaderDataSizeFast() const { return mFilterShaderDataSize; }
PX_FORCE_INLINE PxSimulationFilterShader getFilterShaderFast() const { return mFilterShader; }
PX_FORCE_INLINE PxSimulationFilterCallback* getFilterCallbackFast() const { return mFilterCallback; }
PX_FORCE_INLINE PxPairFilteringMode::Enum getKineKineFilteringMode() const { return mKineKineFilteringMode; }
PX_FORCE_INLINE PxPairFilteringMode::Enum getStaticKineFilteringMode() const { return mStaticKineFilteringMode; }
PX_FORCE_INLINE PxU32 getTimeStamp() const { return mTimeStamp; }
PX_FORCE_INLINE PxU32 getReportShapePairTimeStamp() const { return mReportShapePairTimeStamp; }
PX_FORCE_INLINE NPhaseCore* getNPhaseCore() const { return mNPhaseCore; }
void checkConstraintBreakage();
PX_FORCE_INLINE PxArray<TriggerPairExtraData>&
getTriggerBufferExtraData() { return *mTriggerBufferExtraData; }
PX_FORCE_INLINE PxArray<PxTriggerPair>& getTriggerBufferAPI() { return mTriggerBufferAPI; }
void reserveTriggerReportBufferSpace(const PxU32 pairCount, PxTriggerPair*& triggerPairBuffer, TriggerPairExtraData*& triggerPairExtraBuffer);
PX_FORCE_INLINE ObjectIDTracker& getActorIDTracker() { return *mActorIDTracker; }
PX_FORCE_INLINE void markReleasedBodyIDForLostTouch(PxU32 id) { mLostTouchPairsDeletedBodyIDs.growAndSet(id); }
void resizeReleasedBodyIDMaps(PxU32 maxActors, PxU32 numActors);
PX_FORCE_INLINE StaticSim& getStaticAnchor() { return *mStaticAnchor; }
PX_FORCE_INLINE Bp::BoundsArray& getBoundsArray() const { return *mBoundsArray; }
PX_FORCE_INLINE void updateContactDistance(PxU32 idx, PxReal distance) { (*mContactDistance)[idx] = distance; mHasContactDistanceChanged = true; }
PX_FORCE_INLINE SqBoundsManager& getSqBoundsManager() const { return *mSqBoundsManager; }
PX_FORCE_INLINE BodyCore* const* getSleepBodiesArray(PxU32& count) { count = mSleepBodies.size(); return mSleepBodies.getEntries(); }
PX_FORCE_INLINE PxTaskManager& getTaskManager() const { PX_ASSERT(mTaskManager); return *mTaskManager; }
PX_FORCE_INLINE void setPostSolverVelocityNeeded() { mContactReportsNeedPostSolverVelocity = true; }
PX_FORCE_INLINE ObjectIDTracker& getConstraintIDTracker() { return *mConstraintIDTracker; }
PX_FORCE_INLINE ObjectIDTracker& getElementIDPool() { return *mElementIDPool; }
PX_FORCE_INLINE PxBitMap& getVelocityModifyMap() { return mVelocityModifyMap; }
void* allocateConstraintBlock(PxU32 size);
void deallocateConstraintBlock(void* addr, PxU32 size);
void stepSetupCollide(PxBaseTask* continuation);//This is very important to guarantee thread safty in the collide
PX_FORCE_INLINE void addToPosePreviewList(BodySim& b) { PX_ASSERT(!mPosePreviewBodies.contains(&b)); mPosePreviewBodies.insert(&b); }
PX_FORCE_INLINE void removeFromPosePreviewList(BodySim& b) { PX_ASSERT(mPosePreviewBodies.contains(&b)); mPosePreviewBodies.erase(&b); }
#if PX_DEBUG
PX_FORCE_INLINE bool isInPosePreviewList(BodySim& b) const { return mPosePreviewBodies.contains(&b); }
#endif
PX_FORCE_INLINE void setSpeculativeCCDRigidBody(PxU32 index) { mSpeculativeCCDRigidBodyBitMap.growAndSet(index); }
PX_FORCE_INLINE void resetSpeculativeCCDRigidBody(PxU32 index) { if(index < mSpeculativeCCDRigidBodyBitMap.size()) mSpeculativeCCDRigidBodyBitMap.reset(index); }
PX_FORCE_INLINE void setSpeculativeCCDArticulationLink(PxU32 index) { mSpeculativeCDDArticulationBitMap.growAndSet(index); }
PX_FORCE_INLINE void resetSpeculativeCCDArticulationLink(PxU32 index) { if(index < mSpeculativeCDDArticulationBitMap.size()) mSpeculativeCDDArticulationBitMap.reset(index); }
PX_FORCE_INLINE PxU64 getContextId() const { return mContextId; }
PX_FORCE_INLINE bool isUsingGpuDynamicsOrBp() const { return mUseGpuBp || mUseGpuDynamics; }
PX_FORCE_INLINE bool isUsingGpuDynamicsAndBp() const { return mUseGpuBp && mUseGpuDynamics; }
PX_FORCE_INLINE bool isUsingGpuDynamics() const { return mUseGpuDynamics; }
PX_FORCE_INLINE bool isUsingGpuBp() const { return mUseGpuBp; }
PX_FORCE_INLINE void setDirectGPUAPIInitialized() { mIsDirectGPUAPIInitialized = true; }
PX_FORCE_INLINE bool isDirectGPUAPIInitialized() const { return mIsDirectGPUAPIInitialized; }
// statistics counters increase/decrease
PX_FORCE_INLINE void increaseNumKinematicsCounter() { mNbRigidKinematic++; }
PX_FORCE_INLINE void decreaseNumKinematicsCounter() { mNbRigidKinematic--; }
PX_FORCE_INLINE void increaseNumDynamicsCounter() { mNbRigidDynamics++; }
PX_FORCE_INLINE void decreaseNumDynamicsCounter() { mNbRigidDynamics--; }
ConstraintCore* findConstraintCore(const ActorSim* sim0, const ActorSim* sim1);
//internal private methods:
private:
void activateEdgesInternal(const IG::EdgeIndex* activatingEdges, const PxU32 nbActivatingEdges);
void releaseConstraints(bool endOfScene);
PX_INLINE void clearBrokenConstraintBuffer() { mBrokenConstraints.clear(); }
/////////////////////////////////////////////////////////////
void collideStep(PxBaseTask* continuation);
void advanceStep(PxBaseTask* continuation);
// subroutines of collideStep/solveStep:
void kinematicsSetup(PxBaseTask* continuation);
void stepSetupSolve(PxBaseTask* continuation);
//void stepSetupSimulate();
void processNarrowPhaseTouchEvents();
void processNarrowPhaseTouchEventsStage2(PxBaseTask*);
void setEdgesConnected(PxBaseTask*);
void processNarrowPhaseLostTouchEvents(PxBaseTask*);
void processNarrowPhaseLostTouchEventsIslands(PxBaseTask*);
void processLostTouchPairs();
void integrateKinematicPose();
void updateKinematicCached(PxBaseTask* task);
void beforeSolver(PxBaseTask* continuation);
void checkForceThresholdContactEvents(PxU32 ccdPass);
private:
void putObjectsToSleep();
void wakeObjectsUp();
void collectPostSolverVelocitiesBeforeCCD();
void clearSleepWakeBodies(void);
PX_INLINE void cleanUpSleepBodies();
PX_INLINE void cleanUpWokenBodies();
PX_INLINE void cleanUpSleepOrWokenBodies(PxCoalescedHashSet<BodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker);
private:
// Material manager
PX_ALIGN(16, PxsMaterialManager mMaterialManager);
BroadphaseManager mBroadphaseManager;
PxU64 mContextId;
PxArray<BodyCore*> mActiveBodies; // Sorted: kinematic before dynamic
PxU32 mActiveKinematicBodyCount; // Number of active kinematics. This is also the index in mActiveBodies where the active dynamic bodies start.
PxU32 mActiveDynamicBodyCount; // Number of active dynamics. This is also the index in mActiveBodies where the active soft bodies start.
PxArray<BodyCore*> mActiveCompoundBodies;
BodyCore** mActiveKinematicsCopy;
PxU32 mActiveKinematicsCopyCapacity;
// PT: this array used for:
// - debug visualization
// - processing trigger interactions
// - updating dirty interactions
PxArray<ElementSimInteraction*> mInteractions[InteractionType::eTRACKED_IN_SCENE_COUNT];
PxU32 mActiveInteractionCount[InteractionType::eTRACKED_IN_SCENE_COUNT]; // Interactions with id < activeInteractionCount are active
template <typename T, PxU32 size>
struct Block
{
PxU8 mem[sizeof(T)*size];
Block() {} // get around VS warning C4345, otherwise useless
};
typedef Block<void*, 8> PointerBlock8;
typedef Block<void*, 16> PointerBlock16;
typedef Block<void*, 32> PointerBlock32;
PxPool<PointerBlock8> mPointerBlock8Pool;
PxPool<PointerBlock16> mPointerBlock16Pool;
PxPool<PointerBlock32> mPointerBlock32Pool;
PxsContext* mLLContext;
Bp::AABBManagerBase* mAABBManager;
PxsCCDContext* mCCDContext;
PxI32 mNumFastMovingShapes;
PxU32 mCCDPass;
IG::SimpleIslandManager* mSimpleIslandManager;
Dy::Context* mDynamicsContext;
PxsMemoryManager* mMemoryManager;
#if PX_SUPPORT_GPU_PHYSX
PxsKernelWranglerManager* mGpuWranglerManagers;
PxsHeapMemoryAllocatorManager* mHeapMemoryAllocationManager;
#endif
PxsSimulationController* mSimulationController;
PxsSimulationControllerCallback* mSimulationControllerCallback;
PxSceneLimits mLimits;
PxVec3 mGravity; //!< Gravity vector
PxArray<PxContactPairHeader>
mQueuedContactPairHeaders;
//time:
//constants set with setTiming():
PxReal mDt; //delta time for current step.
PxReal mOneOverDt; //inverse of dt.
//stepping / counters:
PxU32 mTimeStamp; //Counts number of steps.
PxU32 mReportShapePairTimeStamp; //Timestamp for refreshing the shape pair report structure. Updated before delayed shape/actor deletion and before CCD passes.
//containers:
// Those ones contain shape ptrs from Actor, i.e. compound level, not subparts
PxCoalescedHashSet<ConstraintCore*> mConstraints;
Bp::BoundsArray* mBoundsArray;
PxFloatArrayPinned* mContactDistance;
bool mHasContactDistanceChanged;
SqBoundsManager* mSqBoundsManager;
PxArray<BodySim*> mCcdBodies;
PxArray<PxTriggerPair> mTriggerBufferAPI;
PxArray<TriggerPairExtraData>* mTriggerBufferExtraData;
PxCoalescedHashSet<ArticulationCore*> mArticulations;
PxCoalescedHashSet<ArticulationSim*> mDirtyArticulationSims;
PxArray<ConstraintCore*> mBrokenConstraints;
PxCoalescedHashSet<ConstraintSim*> mActiveBreakableConstraints;
// pools for joint buffers
// Fixed joint is 92 bytes, D6 is 364 bytes right now. So these three pools cover all the internal cases
typedef Block<PxU8, 128> MemBlock128;
typedef Block<PxU8, 256> MemBlock256;
typedef Block<PxU8, 384> MemBlock384;
PxPool2<MemBlock128, 8192> mMemBlock128Pool;
PxPool2<MemBlock256, 8192> mMemBlock256Pool;
PxPool2<MemBlock384, 8192> mMemBlock384Pool;
// broad phase data:
NPhaseCore* mNPhaseCore;
// Collision filtering
void* mFilterShaderData;
PxU32 mFilterShaderDataSize;
PxU32 mFilterShaderDataCapacity;
PxSimulationFilterShader mFilterShader;
PxSimulationFilterCallback* mFilterCallback;
const PxPairFilteringMode::Enum mKineKineFilteringMode;
const PxPairFilteringMode::Enum mStaticKineFilteringMode;
PxCoalescedHashSet<BodyCore*> mSleepBodies;
PxCoalescedHashSet<BodyCore*> mWokeBodies;
bool mWokeBodyListValid;
bool mSleepBodyListValid;
const bool mEnableStabilization;
PxArray<PxActor*> mActiveActors;
PxArray<PxActor*> mFrozenActors;
PxArray<const PxRigidBody*> mClientPosePreviewBodies; // buffer for bodies that requested early report of the integrated pose (eENABLE_POSE_INTEGRATION_PREVIEW).
// This buffer gets exposed to users. Is officially accessible from PxSimulationEventCallback::onAdvance()
// until the next simulate()/advance().
PxArray<PxTransform> mClientPosePreviewBuffer; // buffer of newly integrated poses for the bodies that requested a preview. This buffer gets exposed
// to users.
PxSimulationEventCallback* mSimulationEventCallback;
SimStats* mStats;
PxU32 mInternalFlags; // PT: combination of ::SceneInternalFlag, looks like only 2 bits are needed
PxSceneFlags mPublicFlags; // Copy of PxSceneDesc::flags, of type PxSceneFlag
// PT: TODO: unify names, "tracker" or "pool"?
ObjectIDTracker* mConstraintIDTracker; // PT: provides Sc::ContraintSim::mLowLevelConstraint::index
ObjectIDTracker* mActorIDTracker; // PT: provides Sc::ActorSim::mId
ObjectIDTracker* mElementIDPool; // PT: provides Sc::ElementSim::mElementID
StaticCore mAnchorCore;
StaticSim* mStaticAnchor;
Cm::PreallocatingPool<ShapeSim>* mShapeSimPool;
Cm::PreallocatingPool<StaticSim>* mStaticSimPool;
Cm::PreallocatingPool<BodySim>* mBodySimPool;
PxPool<ConstraintSim>* mConstraintSimPool;
LLArticulationRCPool* mLLArticulationRCPool;
PxHashMap<PxPair<const ActorSim*, const ActorSim*>, ConstraintCore*> mConstraintMap;
PxPool<ConstraintInteraction>* mConstraintInteractionPool;
PxPool<SimStateData>* mSimStateDataPool;
BatchRemoveState* mBatchRemoveState;
PxArray<SimpleBodyPair> mLostTouchPairs;
PxBitMap mLostTouchPairsDeletedBodyIDs; // Need to know which bodies have been deleted when processing the lost touch pair list.
// Can't use the existing rigid object ID tracker class since this map needs to be cleared at
// another point in time.
PxBitMap mVelocityModifyMap;
PxArray<PxvContactManagerTouchEvent> mTouchFoundEvents;
PxArray<PxvContactManagerTouchEvent> mTouchLostEvents;
PxBitMap mDirtyShapeSimMap;
PxU32 mDominanceBitMatrix[PX_MAX_DOMINANCE_GROUP];
bool mVisualizationParameterChanged;
PxU32 mMaxNbArticulationLinks;
// statics:
PxU32 mNbRigidStatics;
PxU32 mNbRigidDynamics;
PxU32 mNbRigidKinematic;
PxU32 mNbGeometries[PxGeometryType::eGEOMETRY_COUNT];
//IG::Node::eTYPE_COUNT
PxU32 mNumDeactivatingNodes[IG::Node::eTYPE_COUNT];
// task decomposition
void broadPhase(PxBaseTask* continuation);
void broadPhaseFirstPass(PxBaseTask* continuation);
void broadPhaseSecondPass(PxBaseTask* continuation);
void updateBroadPhase(PxBaseTask* continuation);
void preIntegrate(PxBaseTask* continuation);
void postBroadPhase(PxBaseTask* continuation);
void postBroadPhaseContinuation(PxBaseTask* continuation);
void preRigidBodyNarrowPhase(PxBaseTask* continuation);
void postBroadPhaseStage2(PxBaseTask* continuation);
void postBroadPhaseStage3(PxBaseTask* continuation);
void updateBoundsAndShapes(PxBaseTask* continuation);
void rigidBodyNarrowPhase(PxBaseTask* continuation);
void unblockNarrowPhase(PxBaseTask* continuation);
void islandGen(PxBaseTask* continuation);
void processLostSolverPatches(PxBaseTask* continuation);
void processFoundSolverPatches(PxBaseTask* continuation);
void postIslandGen(PxBaseTask* continuation);
void solver(PxBaseTask* continuation);
void updateBodies(PxBaseTask* continuation);
void updateShapes(PxBaseTask* continuation);
void updateSimulationController(PxBaseTask* continuation);
void updateDynamics(PxBaseTask* continuation);
void processLostContacts(PxBaseTask*);
void processLostContacts2(PxBaseTask*);
void processLostContacts3(PxBaseTask*);
void destroyManagers(PxBaseTask*);
void lostTouchReports(PxBaseTask*);
void unregisterInteractions(PxBaseTask*);
void postThirdPassIslandGen(PxBaseTask*);
void postSolver(PxBaseTask* continuation);
void constraintProjection(PxBaseTask* continuation);
void afterIntegration(PxBaseTask* continuation); // performs sleep check, for instance
void postCCDPass(PxBaseTask* continuation);
void ccdBroadPhaseAABB(PxBaseTask* continuation);
void ccdBroadPhase(PxBaseTask* continuation);
void updateCCDMultiPass(PxBaseTask* continuation);
void updateCCDSinglePass(PxBaseTask* continuation);
void updateCCDSinglePassStage2(PxBaseTask* continuation);
void updateCCDSinglePassStage3(PxBaseTask* continuation);
void finalizationPhase(PxBaseTask* continuation);
void postNarrowPhase(PxBaseTask* continuation);
void addShapes(NpShape*const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& sim, PxBounds3* outBounds);
void removeShapes(RigidSim& , PxInlineArray<ShapeSim*, 64>& , PxInlineArray<const ShapeCore*, 64>&, bool wakeOnLostTouch);
private:
void addShapes(NpShape*const* shapes, PxU32 nbShapes, size_t ptrOffset, RigidSim& sim, ShapeSim*& prefetchedShapeSim, PxBounds3* outBounds);
void updateContactDistances(PxBaseTask* continuation);
void updateDirtyShapes(PxBaseTask* continuation);
Cm::DelegateTask<Scene, &Scene::secondPassNarrowPhase> mSecondPassNarrowPhase;
Cm::DelegateFanoutTask<Scene, &Scene::postNarrowPhase> mPostNarrowPhase;
Cm::DelegateFanoutTask<Scene, &Scene::finalizationPhase> mFinalizationPhase;
Cm::DelegateTask<Scene, &Scene::updateCCDMultiPass> mUpdateCCDMultiPass;
//multi-pass ccd stuff
PxArray<Cm::DelegateTask<Scene, &Scene::updateCCDSinglePass> > mUpdateCCDSinglePass;
PxArray<Cm::DelegateTask<Scene, &Scene::updateCCDSinglePassStage2> > mUpdateCCDSinglePass2;
PxArray<Cm::DelegateTask<Scene, &Scene::updateCCDSinglePassStage3> > mUpdateCCDSinglePass3;
PxArray<Cm::DelegateTask<Scene, &Scene::ccdBroadPhaseAABB> > mCCDBroadPhaseAABB;
PxArray<Cm::DelegateTask<Scene, &Scene::ccdBroadPhase> > mCCDBroadPhase;
PxArray<Cm::DelegateTask<Scene, &Scene::postCCDPass> > mPostCCDPass;
Cm::DelegateTask<Scene, &Scene::afterIntegration> mAfterIntegration;
Cm::DelegateTask<Scene, &Scene::postSolver> mPostSolver;
Cm::DelegateTask<Scene, &Scene::solver> mSolver;
Cm::DelegateTask<Scene, &Scene::updateBodies> mUpdateBodies;
Cm::DelegateTask<Scene, &Scene::updateShapes> mUpdateShapes;
Cm::DelegateTask<Scene, &Scene::updateSimulationController> mUpdateSimulationController;
Cm::DelegateTask<Scene, &Scene::updateDynamics> mUpdateDynamics;
Cm::DelegateTask<Scene, &Scene::processLostContacts> mProcessLostContactsTask;
Cm::DelegateTask<Scene, &Scene::processLostContacts2> mProcessLostContactsTask2;
Cm::DelegateTask<Scene, &Scene::processLostContacts3> mProcessLostContactsTask3;
Cm::DelegateTask<Scene, &Scene::destroyManagers> mDestroyManagersTask;
Cm::DelegateTask<Scene, &Scene::lostTouchReports> mLostTouchReportsTask;
Cm::DelegateTask<Scene, &Scene::unregisterInteractions> mUnregisterInteractionsTask;
Cm::DelegateTask<Scene,
&Scene::processNarrowPhaseLostTouchEventsIslands> mProcessNarrowPhaseLostTouchTasks;
Cm::DelegateTask<Scene,
&Scene::processNarrowPhaseLostTouchEvents> mProcessNPLostTouchEvents;
Cm::DelegateTask<Scene, &Scene::postThirdPassIslandGen> mPostThirdPassIslandGenTask;
Cm::DelegateTask<Scene, &Scene::postIslandGen> mPostIslandGen;
Cm::DelegateTask<Scene, &Scene::islandGen> mIslandGen;
Cm::DelegateTask<Scene, &Scene::preRigidBodyNarrowPhase> mPreRigidBodyNarrowPhase;
Cm::DelegateTask<Scene, &Scene::setEdgesConnected> mSetEdgesConnectedTask;
Cm::DelegateTask<Scene, &Scene::processLostSolverPatches> mProcessLostPatchesTask;
Cm::DelegateTask<Scene, &Scene::processFoundSolverPatches> mProcessFoundPatchesTask;
Cm::DelegateFanoutTask<Scene, &Scene::updateBoundsAndShapes> mUpdateBoundAndShapeTask;
Cm::DelegateTask<Scene, &Scene::rigidBodyNarrowPhase> mRigidBodyNarrowPhase;
Cm::DelegateTask<Scene, &Scene::unblockNarrowPhase> mRigidBodyNPhaseUnlock;
Cm::DelegateTask<Scene, &Scene::postBroadPhase> mPostBroadPhase;
Cm::DelegateTask<Scene, &Scene::postBroadPhaseContinuation> mPostBroadPhaseCont;
Cm::DelegateTask<Scene, &Scene::postBroadPhaseStage2> mPostBroadPhase2;
Cm::DelegateFanoutTask<Scene, &Scene::postBroadPhaseStage3> mPostBroadPhase3;
Cm::DelegateTask<Scene, &Scene::preallocateContactManagers> mPreallocateContactManagers;
Cm::DelegateTask<Scene, &Scene::islandInsertion> mIslandInsertion;
Cm::DelegateTask<Scene, &Scene::registerContactManagers> mRegisterContactManagers;
Cm::DelegateTask<Scene, &Scene::registerInteractions> mRegisterInteractions;
Cm::DelegateTask<Scene, &Scene::registerSceneInteractions> mRegisterSceneInteractions;
Cm::DelegateTask<Scene, &Scene::broadPhase> mBroadPhase;
Cm::DelegateTask<Scene, &Scene::advanceStep> mAdvanceStep;
Cm::DelegateTask<Scene, &Scene::collideStep> mCollideStep;
Cm::DelegateTask<Scene, &Scene::broadPhaseFirstPass> mBpFirstPass;
Cm::DelegateTask<Scene, &Scene::broadPhaseSecondPass> mBpSecondPass;
Cm::DelegateTask<Scene, &Scene::updateBroadPhase> mBpUpdate;
Cm::DelegateTask<Scene, &Scene::preIntegrate> mPreIntegrate;
Cm::FlushPool mTaskPool;
PxTaskManager* mTaskManager;
PxCudaContextManager* mCudaContextManager;
bool mContactReportsNeedPostSolverVelocity;
bool mUseGpuDynamics;
bool mUseGpuBp;
bool mCCDBp;
SimulationStage::Enum mSimulationStage;
PxCoalescedHashSet<const BodySim*> mPosePreviewBodies; // list of bodies that requested early report of the integrated pose (eENABLE_POSE_INTEGRATION_PREVIEW).
PxArray<PxsContactManager*> mPreallocatedContactManagers;
PxArray<ShapeInteraction*> mPreallocatedShapeInteractions;
PxArray<ElementInteractionMarker*> mPreallocatedInteractionMarkers;
OverlapFilterTask* mOverlapFilterTaskHead; // PT: tmp data passed from finishBroadPhase to preallocateContactManagers
PxArray<FilterInfo> mFilterInfo; // PT: tmp data passed from finishBroadPhase to preallocateContactManagers
PxBitMap mSpeculativeCCDRigidBodyBitMap;
PxBitMap mSpeculativeCDDArticulationBitMap;
bool mIsCollisionPhaseActive;
// Set to true as long as collision phase is active (used as an indicator that it is OK to read object pose,
// velocity etc. compared to the solver phase where these properties might get written to).
bool mIsDirectGPUAPIInitialized;
public:
// For OmniPVD. To notify NpScene that actor's sleeping state has changed.
typedef void(*SleepingStateChangedCallback)(PxRigidDynamic&, bool);
SleepingStateChangedCallback mOnSleepingStateChanged;
// PT: moved all the GPU-related code & data here in an attempt to clearly separate the CPU/GPU bits
#if PX_SUPPORT_GPU_PHYSX
public:
void gpu_addToActiveList(ActorSim& actorSim, ActorCore* appendedActorCore);
void gpu_removeFromActiveList(ActorSim& actorSim, PxU32 removedActiveIndex);
void gpu_clearSleepWakeBodies();
void gpu_buildActiveActors();
void gpu_buildActiveAndFrozenActors();
void gpu_setSimulationEventCallback(PxSimulationEventCallback* callback);
PxU32 gpu_cleanUpSleepAndWokenBodies();
void gpu_fireOnSleepCallback(PxActor** actors);
void gpu_fireOnWakeCallback(PxActor** actors);
void gpu_updateBounds();
void gpu_releasePools();
void gpu_release();
void addSoftBody(SoftBodyCore&);
void removeSoftBody(SoftBodyCore&);
void addFEMCloth(FEMClothCore&);
void removeFEMCloth(FEMClothCore&);
void addParticleSystem(ParticleSystemCore&);
void removeParticleSystem(ParticleSystemCore&);
void addHairSystem(HairSystemCore&);
void removeHairSystem(HairSystemCore&);
PX_FORCE_INLINE PxU32 getNbSoftBodies() const { return mSoftBodies.size(); }
PX_FORCE_INLINE SoftBodyCore* const* getSoftBodies() { return mSoftBodies.getEntries(); }
PX_FORCE_INLINE PxU32 getNbFEMCloths() const { return mFEMCloths.size(); }
PX_FORCE_INLINE FEMClothCore* const* getFEMCloths() { return mFEMCloths.getEntries(); }
PX_FORCE_INLINE PxU32 getNbParticleSystems() const { return mParticleSystems.size(); }
PX_FORCE_INLINE ParticleSystemCore* const* getParticleSystems() { return mParticleSystems.getEntries(); }
PX_FORCE_INLINE PxU32 getNbHairSystems() const { return mHairSystems.size(); }
PX_FORCE_INLINE HairSystemCore* const* getHairSystems() { return mHairSystems.getEntries(); }
PX_FORCE_INLINE SoftBodyCore*const* getActiveSoftBodiesArray() const { return mActiveSoftBodies.begin(); }
PX_FORCE_INLINE PxU32 getNumActiveSoftBodies() const { return mActiveSoftBodies.size(); }
PX_FORCE_INLINE FEMClothCore*const* getActiveFEMClothsArray() const { return mActiveFEMCloths.begin(); }
PX_FORCE_INLINE PxU32 getNumActiveFEMCloths() const { return mActiveFEMCloths.size(); }
PX_FORCE_INLINE HairSystemCore*const* getActiveHairSystemsArray() const { return mActiveHairSystems.begin(); }
PX_FORCE_INLINE PxU32 getNumActiveHairSystems() const { return mActiveHairSystems.size(); }
// PT: redundant?
// Get the active soft body actors
PX_FORCE_INLINE SoftBodyCore*const* getActiveSoftBodies() const { return mActiveSoftBodies.begin(); }
PX_FORCE_INLINE SoftBodyCore*const* getSleepSoftBodiesArray(PxU32& count) { count = mSleepSoftBodies.size(); return mSleepSoftBodies.getEntries(); }
// PT: redundant?
// Get the active FEM-cloth actors
PX_FORCE_INLINE FEMClothCore*const* getActiveFEMCloths() const { return mActiveFEMCloths.begin(); }
PX_FORCE_INLINE const PxsFEMMaterialManager& getFEMMaterialManager() const { return mFEMMaterialManager; }
PX_FORCE_INLINE PxsFEMMaterialManager& getFEMMaterialManager() { return mFEMMaterialManager; }
PX_FORCE_INLINE const PxsFEMClothMaterialManager& getFEMClothMaterialManager() const { return mFEMClothMaterialManager; }
PX_FORCE_INLINE PxsFEMClothMaterialManager& getFEMClothMaterialManager() { return mFEMClothMaterialManager; }
PX_FORCE_INLINE const PxsPBDMaterialManager& getPBDMaterialManager() const { return mPBDMaterialManager; }
PX_FORCE_INLINE PxsPBDMaterialManager& getPBDMaterialManager() { return mPBDMaterialManager; }
PX_FORCE_INLINE const PxsFLIPMaterialManager& getFLIPMaterialManager() const { return mFLIPMaterialManager; }
PX_FORCE_INLINE PxsFLIPMaterialManager& getFLIPMaterialManager() { return mFLIPMaterialManager; }
PX_FORCE_INLINE const PxsMPMMaterialManager& getMPMMaterialManager() const { return mMPMMaterialManager; }
PX_FORCE_INLINE PxsMPMMaterialManager& getMPMMaterialManager() { return mMPMMaterialManager; }
Dy::SoftBody* createLLSoftBody(SoftBodySim* sim);
void destroyLLSoftBody(Dy::SoftBody& softBody);
Dy::FEMCloth* createLLFEMCloth(FEMClothSim* sim);
void destroyLLFEMCloth(Dy::FEMCloth& femCloth);
Dy::ParticleSystem* createLLParticleSystem(ParticleSystemSim* sim);
void destroyLLParticleSystem(Dy::ParticleSystem& softBody);
Dy::HairSystem* createLLHairSystem(HairSystemSim* sim);
void destroyLLHairSystem(Dy::HairSystem& hairSystem);
// PT: TODO: why inline these ones?
PX_INLINE void cleanUpSleepSoftBodies();
PX_INLINE void cleanUpWokenSoftBodies();
PX_INLINE void cleanUpSleepOrWokenSoftBodies(PxCoalescedHashSet<SoftBodyCore*>& bodyList, PxU32 removeFlag, bool& validMarker);
PX_INLINE void cleanUpSleepHairSystems();
PX_INLINE void cleanUpWokenHairSystems();
PX_INLINE void cleanUpSleepOrWokenHairSystems(PxCoalescedHashSet<HairSystemCore*>& bodyList, PxU32 removeFlag, bool& validMarker);
void addSoftBodySimControl(SoftBodyCore& core);
void removeSoftBodySimControl(SoftBodyCore& core);
void addFEMClothSimControl(FEMClothCore& core);
void removeFEMClothSimControl(FEMClothCore& core);
void addParticleSystemSimControl(ParticleSystemCore& core);
void removeParticleSystemSimControl(ParticleSystemCore& core);
void addHairSystemSimControl(HairSystemCore& core);
void removeHairSystemSimControl(HairSystemCore& core);
void addParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId);
void removeParticleFilter(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId);
PxU32 addParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric);
void removeParticleAttachment(Sc::ParticleSystemCore* core, SoftBodySim& sim, PxU32 handle);
void addRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 vertId);
void removeRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 vertId);
PxU32 addRigidAttachment(BodyCore* core, SoftBodySim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void removeRigidAttachment(BodyCore* core, SoftBodySim& sim, PxU32 handle);
void addTetRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 tetIdx);
void removeTetRigidFilter(BodyCore* core, SoftBodySim& sim, PxU32 tetIdx);
PxU32 addTetRigidAttachment(BodyCore* core, SoftBodySim& sim, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void addSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1);
void removeSoftBodyFilter(SoftBodyCore& core, PxU32 tetIdx0, SoftBodySim& sim, PxU32 tetIdx1);
void addSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize);
void removeSoftBodyFilters(SoftBodyCore& core, SoftBodySim& sim, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize);
PxU32 addSoftBodyAttachment(SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, SoftBodySim& sim, PxU32 tetIdx1, const PxVec4& tetBarycentric1, PxConeLimitedConstraint* constraint, PxReal constraintOffset);
void removeSoftBodyAttachment(SoftBodyCore& core, SoftBodySim& sim, PxU32 handle);
void addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx);
void removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, Sc::SoftBodySim& sim, PxU32 tetIdx);
void addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx);
void removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, Sc::SoftBodySim& sim, PxU32 tetIdx);
PxU32 addClothAttachment(FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, SoftBodySim& sim, PxU32 tetIdx, const PxVec4& tetBarycentric, PxConeLimitedConstraint* constraint, PxReal constraintOffset);
void removeClothAttachment(FEMClothCore& core, SoftBodySim& sim, PxU32 handle);
void addRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 vertId);
void removeRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 vertId);
PxU32 addRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void removeRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 handle);
void addClothFilter(FEMClothCore& core0, PxU32 triIdx0, Sc::FEMClothSim& sim1, PxU32 triIdx1);
void removeClothFilter(FEMClothCore& core, PxU32 triIdx0, FEMClothSim& sim1, PxU32 triIdx1);
PxU32 addTriClothAttachment(FEMClothCore& core0, PxU32 triIdx0, const PxVec4& barycentric0, Sc::FEMClothSim& sim1, PxU32 triIdx1, const PxVec4& barycentric1);
void removeTriClothAttachment(FEMClothCore& core, FEMClothSim& sim1, PxU32 handle);
void addTriRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 triIdx);
void removeTriRigidFilter(BodyCore* core, FEMClothSim& sim, PxU32 triIdx);
PxU32 addTriRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 triIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void removeTriRigidAttachment(BodyCore* core, FEMClothSim& sim, PxU32 handle);
void addRigidAttachment(BodyCore* core, ParticleSystemSim& sim);
void removeRigidAttachment(BodyCore* core, ParticleSystemSim& sim);
void addAttachment(const BodySim& bodySim, const HairSystemSim& hairSim);
void addAttachment(const SoftBodySim& sbSim, const HairSystemSim& hairSim);
void removeAttachment(const BodySim& bodySim, const HairSystemSim& hairSim);
void removeAttachment(const SoftBodySim& sbSim, const HairSystemSim& hairSim);
PxActor** getActiveSoftBodyActors(PxU32& nbActorsOut);
void setActiveSoftBodyActors(PxActor** actors, PxU32 nbActors);
//PxActor** getActiveFEMClothActors(PxU32& nbActorsOut);
//void setActiveFEMClothActors(PxActor** actors, PxU32 nbActors);
PX_ALIGN(16, PxsFEMMaterialManager mFEMMaterialManager);
PX_ALIGN(16, PxsFEMClothMaterialManager mFEMClothMaterialManager);
PX_ALIGN(16, PxsPBDMaterialManager mPBDMaterialManager);
PX_ALIGN(16, PxsFLIPMaterialManager mFLIPMaterialManager);
PX_ALIGN(16, PxsMPMMaterialManager mMPMMaterialManager);
PxArray<SoftBodyCore*> mActiveSoftBodies;
PxArray<FEMClothCore*> mActiveFEMCloths;
PxArray<ParticleSystemCore*> mActiveParticleSystems;
PxArray<HairSystemCore*> mActiveHairSystems;
PxCoalescedHashSet<SoftBodyCore*> mSoftBodies;
PxCoalescedHashSet<FEMClothCore*> mFEMCloths;
PxCoalescedHashSet<ParticleSystemCore*> mParticleSystems;
PxCoalescedHashSet<HairSystemCore*> mHairSystems;
PxCoalescedHashSet<SoftBodyCore*> mSleepSoftBodies;
PxCoalescedHashSet<SoftBodyCore*> mWokeSoftBodies;
PxCoalescedHashSet<HairSystemCore*> mSleepHairSystems;
PxCoalescedHashSet<HairSystemCore*> mWokeHairSystems;
PxArray<PxActor*> mActiveSoftBodyActors;
PxArray<PxActor*> mActiveFEMClothActors;
PxArray<PxActor*> mActiveHairSystemActors;
LLSoftBodyPool* mLLSoftBodyPool;
LLFEMClothPool* mLLFEMClothPool;
LLParticleSystemPool* mLLParticleSystemPool;
LLHairSystemPool* mLLHairSystemPool;
PxHashMap<PxPair<PxU32, PxU32>, ParticleOrSoftBodyRigidInteraction> mParticleOrSoftBodyRigidInteractionMap;
bool mWokeSoftBodyListValid;
bool mSleepSoftBodyListValid;
bool mWokeHairSystemListValid;
bool mSleepHairSystemListValid;
#endif
};
bool activateInteraction(Interaction* interaction, void* data);
void activateInteractions(Sc::ActorSim& actorSim);
void deactivateInteractions(Sc::ActorSim& actorSim);
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationCore.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 SC_ARTICULATION_CORE_H
#define SC_ARTICULATION_CORE_H
#include "ScActorCore.h"
#include "DyFeatherstoneArticulation.h"
namespace physx
{
class PxNodeIndex;
namespace Sc
{
class ArticulationSim;
class ArticulationCore
{
//---------------------------------------------------------------------------------
// Construction, destruction & initialization
//---------------------------------------------------------------------------------
// PX_SERIALIZATION
public:
ArticulationCore(const PxEMPTY) : mSim(NULL), mCore(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationCore();
~ArticulationCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
PX_FORCE_INLINE PxReal getSleepThreshold() const { return mCore.sleepThreshold; }
PX_FORCE_INLINE void setSleepThreshold(const PxReal v) { mCore.sleepThreshold = v; }
PX_FORCE_INLINE PxReal getFreezeThreshold() const { return mCore.freezeThreshold; }
PX_FORCE_INLINE void setFreezeThreshold(const PxReal v) { mCore.freezeThreshold = v; }
PX_FORCE_INLINE PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; }
PX_FORCE_INLINE void setSolverIterationCounts(PxU16 c) { mCore.solverIterationCounts = c; }
PX_FORCE_INLINE PxReal getWakeCounter() const { return mCore.wakeCounter; }
PX_FORCE_INLINE void setWakeCounterInternal(const PxReal v) { mCore.wakeCounter = v; }
void setWakeCounter(const PxReal v);
PX_FORCE_INLINE PxReal getMaxLinearVelocity() const { return mCore.maxLinearVelocity; }
void setMaxLinearVelocity(const PxReal max);
PX_FORCE_INLINE PxReal getMaxAngularVelocity() const { return mCore.maxAngularVelocity; }
void setMaxAngularVelocity(const PxReal max);
bool isSleeping() const;
void wakeUp(PxReal wakeCounter);
void putToSleep();
//---------------------------------------------------------------------------------
// external reduced coordinate API
//---------------------------------------------------------------------------------
void setArticulationFlags(PxArticulationFlags flags);
PxArticulationFlags getArticulationFlags() const { return mCore.flags; }
PxU32 getDofs() const;
PxArticulationCache* createCache() const;
PxU32 getCacheDataSize() const;
void zeroCache(PxArticulationCache& cache) const;
bool applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flag)const;
void copyInternalStateToCache
(PxArticulationCache& cache, const PxArticulationCacheFlags flag, const bool isGpuSimEnabled) const;
void packJointData(const PxReal* maximum, PxReal* reduced) const;
void unpackJointData(const PxReal* reduced, PxReal* maximum) const;
void commonInit() const;
void computeGeneralizedGravityForce(PxArticulationCache& cache) const;
void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const;
void computeGeneralizedExternalForce(PxArticulationCache& cache) const;
void computeJointAcceleration(PxArticulationCache& cache) const;
void computeJointForce(PxArticulationCache& cache) const;
void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const;
void computeCoefficientMatrix(PxArticulationCache& cache) const;
bool computeLambda(PxArticulationCache& cache, PxArticulationCache& rollBackCache, const PxReal* const jointTorque, const PxVec3 gravity, const PxU32 maxIter) const;
void computeGeneralizedMassMatrix(PxArticulationCache& cache) const;
PxU32 getCoefficientMatrixSize() const;
PxSpatialVelocity getLinkAcceleration(const PxU32 linkId, const bool isGpuSimEnabled) const;
PxU32 getGpuArticulationIndex() const;
void updateKinematic(PxArticulationKinematicFlags flags);
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
public:
PX_FORCE_INLINE void setSim(ArticulationSim* sim)
{
PX_ASSERT((sim==0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE ArticulationSim* getSim() const { return mSim; }
PX_FORCE_INLINE Dy::ArticulationCore& getCore() { return mCore; }
static PX_FORCE_INLINE ArticulationCore& getArticulationCore(ArticulationCore& core)
{
const size_t offset = PX_OFFSET_OF(ArticulationCore, mCore);
return *reinterpret_cast<ArticulationCore*>(reinterpret_cast<PxU8*>(&core) - offset);
}
PxNodeIndex getIslandNodeIndex() const;
void setGlobalPose();
private:
ArticulationSim* mSim;
Dy::ArticulationCore mCore;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScActorCore.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 SC_ACTOR_CORE_H
#define SC_ACTOR_CORE_H
#include "common/PxMetaData.h"
#include "PxActor.h"
namespace physx
{
namespace Sc
{
class ActorSim;
class ActorCore
{
public:
// PX_SERIALIZATION
ActorCore(const PxEMPTY) : mSim(NULL), mActorFlags(PxEmpty)
{
}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ActorCore(PxActorType::Enum actorType, PxU8 actorFlags, PxClientID owner, PxDominanceGroup dominanceGroup);
~ActorCore();
PX_FORCE_INLINE ActorSim* getSim() const { return mSim; }
PX_FORCE_INLINE void setSim(ActorSim* sim)
{
PX_ASSERT((sim==NULL) ^ (mSim==NULL));
mSim = sim;
}
PX_FORCE_INLINE PxActorFlags getActorFlags() const { return mActorFlags; }
void setActorFlags(PxActorFlags af);
PX_FORCE_INLINE PxDominanceGroup getDominanceGroup() const
{
return PxDominanceGroup(mDominanceGroup);
}
void setDominanceGroup(PxDominanceGroup g);
PX_FORCE_INLINE void setOwnerClient(PxClientID inId)
{
const PxU32 aggid = mAggregateIDOwnerClient & 0x00ffffff;
mAggregateIDOwnerClient = (PxU32(inId)<<24) | aggid;
}
PX_FORCE_INLINE PxClientID getOwnerClient() const
{
return mAggregateIDOwnerClient>>24;
}
PX_FORCE_INLINE PxActorType::Enum getActorCoreType() const { return PxActorType::Enum(mActorType); }
void reinsertShapes();
PX_FORCE_INLINE void setAggregateID(PxU32 id)
{
PX_ASSERT(id==0xffffffff || id<(1<<24));
const PxU32 ownerClient = mAggregateIDOwnerClient & 0xff000000;
mAggregateIDOwnerClient = (id & 0x00ffffff) | ownerClient;
}
PX_FORCE_INLINE PxU32 getAggregateID() const
{
const PxU32 id = mAggregateIDOwnerClient & 0x00ffffff;
return id == 0x00ffffff ? PX_INVALID_U32 : id;
}
private:
ActorSim* mSim; //
PxU32 mAggregateIDOwnerClient; // PxClientID (8bit) | aggregate ID (24bit)
// PT: TODO: the remaining members could be packed into just a 16bit mask
PxActorFlags mActorFlags; // PxActor's flags (PxU8) => only 4 bits used
PxU8 mActorType; // Actor type (8 bits, but 3 would be enough)
PxU8 mDominanceGroup; // Dominance group (8 bits, but 5 would be enough because "must be < 32")
};
#if PX_P64_FAMILY
PX_COMPILE_TIME_ASSERT(sizeof(Sc::ActorCore)==16);
#else
PX_COMPILE_TIME_ASSERT(sizeof(Sc::ActorCore)==12);
#endif
} // namespace Sc
}
//////////////////////////////////////////////////////////////////////////
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScPhysics.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 SC_PHYSICS_H
#define SC_PHYSICS_H
#include "PxPhysics.h"
#include "PxScene.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxBasicTemplates.h"
#include "PxActor.h"
namespace physx
{
class PxMaterial;
class PxTolerancesScale;
struct PxvOffsetTable;
#if PX_SUPPORT_GPU_PHYSX
class PxPhysXGpu;
#endif
namespace Sc
{
class Scene;
class StaticCore;
class RigidCore;
class BodyCore;
class ArticulationCore;
class ArticulationJointCore;
class ConstraintCore;
class ShapeCore;
struct OffsetTable
{
PX_FORCE_INLINE OffsetTable() {}
PX_FORCE_INLINE PxShape* convertScShape2Px(ShapeCore* sc) const { return PxPointerOffset<PxShape*>(sc, scShape2Px); }
PX_FORCE_INLINE const PxShape* convertScShape2Px(const ShapeCore* sc) const { return PxPointerOffset<const PxShape*>(sc, scShape2Px); }
PX_FORCE_INLINE PxConstraint* convertScConstraint2Px(ConstraintCore* sc) const { return PxPointerOffset<PxConstraint*>(sc, scConstraint2Px); }
PX_FORCE_INLINE const PxConstraint* convertScConstraint2Px(const ConstraintCore* sc) const { return PxPointerOffset<const PxConstraint*>(sc, scConstraint2Px); }
PX_FORCE_INLINE PxArticulationReducedCoordinate* convertScArticulation2Px(ArticulationCore* sc) const
{
return PxPointerOffset<PxArticulationReducedCoordinate*>(sc, scArticulationRC2Px);
}
PX_FORCE_INLINE const PxArticulationReducedCoordinate* convertScArticulation2Px(const ArticulationCore* sc) const
{
return PxPointerOffset<const PxArticulationReducedCoordinate*>(sc, scArticulationRC2Px);
}
PX_FORCE_INLINE PxArticulationJointReducedCoordinate* convertScArticulationJoint2Px(ArticulationJointCore* sc) const
{
return PxPointerOffset<PxArticulationJointReducedCoordinate*>(sc, scArticulationJointRC2Px);
}
PX_FORCE_INLINE const PxArticulationJointReducedCoordinate* convertScArticulationJoint2Px(const ArticulationJointCore* sc) const
{
return PxPointerOffset<const PxArticulationJointReducedCoordinate*>(sc, scArticulationJointRC2Px);
}
ptrdiff_t scRigidStatic2PxActor;
ptrdiff_t scRigidDynamic2PxActor;
ptrdiff_t scArticulationLink2PxActor;
ptrdiff_t scSoftBody2PxActor;
ptrdiff_t scPBDParticleSystem2PxActor;
ptrdiff_t scFLIPParticleSystem2PxActor;
ptrdiff_t scMPMParticleSystem2PxActor;
ptrdiff_t scHairSystem2PxActor;
ptrdiff_t scShape2Px;
ptrdiff_t scArticulationRC2Px;
ptrdiff_t scArticulationJointRC2Px;
ptrdiff_t scConstraint2Px;
ptrdiff_t scCore2PxActor[PxActorType::eACTOR_COUNT];
};
extern OffsetTable gOffsetTable;
class Physics : public PxUserAllocated
{
public:
PX_FORCE_INLINE static Physics& getInstance() { return *mInstance; }
Physics(const PxTolerancesScale&, const PxvOffsetTable& pxvOffsetTable);
~Physics();
PX_FORCE_INLINE const PxTolerancesScale& getTolerancesScale() const { return mScale; }
private:
PxTolerancesScale mScale;
static Physics* mInstance;
public:
static const PxReal sWakeCounterOnCreation;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScRigidCore.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 SC_RIGID_CORE_H
#define SC_RIGID_CORE_H
#include "ScActorCore.h"
#include "ScPhysics.h"
#include "PxvDynamics.h"
#include "PxShape.h"
namespace physx
{
namespace Sc
{
class RigidSim;
class ShapeCore;
struct ShapeChangeNotifyFlag
{
enum Enum
{
eGEOMETRY = 1<<0,
eMATERIAL = 1<<1,
eSHAPE2BODY = 1<<2,
eFILTERDATA = 1<<3,
eCONTACTOFFSET = 1<<4,
eRESTOFFSET = 1<<5,
eRESET_FILTERING = 1<<6
};
};
typedef PxFlags<ShapeChangeNotifyFlag::Enum, PxU32> ShapeChangeNotifyFlags;
PX_FLAGS_OPERATORS(ShapeChangeNotifyFlag::Enum,PxU32)
class RigidCore : public ActorCore
{
public:
PX_FORCE_INLINE PxActor* getPxActor() const
{
return PxPointerOffset<PxActor*>(const_cast<RigidCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]);
}
void addShapeToScene(ShapeCore& shape);
void removeShapeFromScene(ShapeCore& shape, bool wakeOnLostTouch);
void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags);
void onShapeFlagsChange(ShapeCore& shape, PxShapeFlags oldShapeFlags);
void unregisterShapeFromNphase(ShapeCore& shapeCore);
void registerShapeInNphase(ShapeCore& shapeCore);
RigidSim* getSim() const;
PxU32 getRigidID() const;
static void getBinaryMetaData(PxOutputStream& stream);
protected:
RigidCore(const PxEMPTY) : ActorCore(PxEmpty) {}
RigidCore(PxActorType::Enum type);
~RigidCore();
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationTendonCore.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_SCP_ARTICULATION_TENDON_CORE
#define PX_PHYSICS_SCP_ARTICULATION_TENDON_CORE
#include "DyArticulationTendon.h"
namespace physx
{
namespace Sc
{
class ArticulationSpatialTendonSim;
class ArticulationFixedTendonSim;
class ArticulationTendonCore
{
public:
// PX_SERIALIZATION
ArticulationTendonCore(const PxEMPTY) {}
void preExportDataReset() { }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationTendonCore() : mStiffness(0.f), mDamping(0.f), mOffset(0.f), mLimitStiffness(0.f)
{
}
PxReal mStiffness;
PxReal mDamping;
PxReal mOffset;
PxReal mLimitStiffness;
};
class ArticulationSpatialTendonCore : public ArticulationTendonCore
{
public:
// PX_SERIALIZATION
ArticulationSpatialTendonCore(const PxEMPTY) : ArticulationTendonCore(PxEmpty), mSim(NULL) {}
void preExportDataReset() { }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationSpatialTendonCore() : ArticulationTendonCore() { mSim = NULL; }
~ArticulationSpatialTendonCore() {}
void setStiffness(const PxReal stiffness);
PxReal getStiffness() const;
void setDamping(const PxReal damping);
PxReal getDamping() const;
void setLimitStiffness(const PxReal stiffness);
PxReal getLimitStiffness() const;
void setOffset(const PxReal offset);
PxReal getOffset() const;
PX_FORCE_INLINE void setSim(ArticulationSpatialTendonSim* sim)
{
PX_ASSERT((sim == 0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE ArticulationSpatialTendonSim* getSim() const { return mSim; }
ArticulationSpatialTendonSim* mSim;
};
class ArticulationFixedTendonCore : public ArticulationTendonCore
{
public:
// PX_SERIALIZATION
ArticulationFixedTendonCore(const PxEMPTY) : ArticulationTendonCore(PxEmpty), mSim(NULL) {}
void preExportDataReset() {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationFixedTendonCore() : ArticulationTendonCore(), mLowLimit(PX_MAX_F32), mHighLimit(-PX_MAX_F32), mRestLength(0.f)
{ mSim = NULL; }
~ArticulationFixedTendonCore() {}
void setStiffness(const PxReal stiffness);
PxReal getStiffness() const;
void setDamping(const PxReal damping);
PxReal getDamping() const;
void setLimitStiffness(const PxReal stiffness);
PxReal getLimitStiffness() const;
void setOffset(const PxReal offset);
PxReal getOffset() const;
void setSpringRestLength(const PxReal restLength);
PxReal getSpringRestLength() const;
void setLimitRange(const PxReal lowLimit, const PxReal highLimit);
void getLimitRange(PxReal& lowLimit, PxReal& highLimit) const;
PX_FORCE_INLINE void setSim(ArticulationFixedTendonSim* sim)
{
PX_ASSERT((sim == 0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE ArticulationFixedTendonSim* getSim() const { return mSim; }
PxReal mLowLimit;
PxReal mHighLimit;
PxReal mRestLength;
ArticulationFixedTendonSim* mSim;
};
}//namespace Sc
} //namespace physx
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScSqBoundsSync.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 SC_SQ_BOUNDS_SYNC_H
#define SC_SQ_BOUNDS_SYNC_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxBitMap.h"
#include "PxSceneQuerySystem.h"
namespace physx
{
class PxBounds3;
class PxRigidBody;
class PxShape;
typedef PxSQPrunerHandle ScPrunerHandle;
namespace Sc
{
// PT: TODO: revisit the need for a virtual interface
struct SqRefFinder
{
virtual ScPrunerHandle find(const PxRigidBody* body, const PxShape* shape, PxU32& prunerIndex) = 0;
virtual ~SqRefFinder() {}
};
// PT: TODO: revisit the need for a virtual interface
struct SqBoundsSync
{
virtual void sync(PxU32 prunerIndex, const ScPrunerHandle* handles, const PxU32* boundsIndices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0;
virtual ~SqBoundsSync() {}
};
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScShapeCore.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 SC_SHAPE_CORE_H
#define SC_SHAPE_CORE_H
#include "foundation/PxUtilities.h"
#include "PxvGeometry.h"
#include "PxFiltering.h"
#include "PxShape.h"
namespace physx
{
class PxShape;
class PxsSimulationController;
namespace Sc
{
class ShapeSim;
class ShapeCore
{
public:
// PX_SERIALIZATION
ShapeCore(const PxEMPTY);
void exportExtraData(PxSerializationContext& stream);
void importExtraData(PxDeserializationContext& context);
void resolveReferences(PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
void resolveMaterialReference(PxU32 materialTableIndex, PxU16 materialIndex);
//~PX_SERIALIZATION
ShapeCore(const PxGeometry& geometry, PxShapeFlags shapeFlags,
const PxU16* materialIndices, PxU16 materialCount, bool isExclusive,
PxShapeCoreFlag::Enum softOrClothFlags = PxShapeCoreFlag::Enum(0));
~ShapeCore();
PX_FORCE_INLINE PxGeometryType::Enum getGeometryType() const { return mCore.mGeometry.getType(); }
PxShape* getPxShape();
const PxShape* getPxShape() const;
PX_FORCE_INLINE const GeometryUnion& getGeometryUnion() const { return mCore.mGeometry; }
PX_FORCE_INLINE const PxGeometry& getGeometry() const { return mCore.mGeometry.getGeometry(); }
void setGeometry(const PxGeometry& geom);
PxU16 getNbMaterialIndices() const;
const PxU16* getMaterialIndices() const;
void setMaterialIndices(const PxU16* materialIndices, PxU16 materialIndexCount);
PX_FORCE_INLINE const PxTransform& getShape2Actor() const { return mCore.getTransform(); }
PX_FORCE_INLINE void setShape2Actor(const PxTransform& s2b) { mCore.setTransform(s2b); }
PX_FORCE_INLINE const PxFilterData& getSimulationFilterData() const { return mSimulationFilterData; }
PX_FORCE_INLINE void setSimulationFilterData(const PxFilterData& data) { mSimulationFilterData = data; }
PX_FORCE_INLINE PxReal getContactOffset() const { return mCore.mContactOffset; }
void setContactOffset(PxReal offset);
PX_FORCE_INLINE PxReal getRestOffset() const { return mCore.mRestOffset; }
PX_FORCE_INLINE void setRestOffset(PxReal offset) { mCore.mRestOffset = offset; }
PX_FORCE_INLINE PxReal getDensityForFluid() const { return mCore.getDensityForFluid(); }
PX_FORCE_INLINE void setDensityForFluid(PxReal densityForFluid) { mCore.setDensityForFluid(densityForFluid); }
PX_FORCE_INLINE PxReal getTorsionalPatchRadius() const { return mCore.mTorsionalRadius; }
PX_FORCE_INLINE void setTorsionalPatchRadius(PxReal tpr) { mCore.mTorsionalRadius = tpr; }
PX_FORCE_INLINE PxReal getMinTorsionalPatchRadius() const {return mCore.mMinTorsionalPatchRadius; }
PX_FORCE_INLINE void setMinTorsionalPatchRadius(PxReal radius) { mCore.mMinTorsionalPatchRadius = radius; }
PX_FORCE_INLINE PxShapeFlags getFlags() const { return PxShapeFlags(mCore.mShapeFlags); }
PX_FORCE_INLINE void setFlags(PxShapeFlags f) { mCore.mShapeFlags = f; }
PX_FORCE_INLINE const PxsShapeCore& getCore() const { return mCore; }
static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF(ShapeCore, mCore); }
static PX_FORCE_INLINE ShapeCore& getCore(PxsShapeCore& core)
{
return *reinterpret_cast<ShapeCore*>(reinterpret_cast<PxU8*>(&core) - getCoreOffset());
}
PX_FORCE_INLINE ShapeSim* getExclusiveSim() const
{
return mExclusiveSim;
}
PX_FORCE_INLINE void setExclusiveSim(ShapeSim* sim)
{
if (!sim || mCore.mShapeCoreFlags.isSet(PxShapeCoreFlag::eIS_EXCLUSIVE))
{
mExclusiveSim = sim;
}
}
PxU32 getInternalShapeIndex(PxsSimulationController& simulationController) const;
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
protected:
#endif
PxFilterData mSimulationFilterData; // Simulation filter data
PxsShapeCore PX_ALIGN(16, mCore);
ShapeSim* mExclusiveSim; //only set if shape is exclusive
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
public:
#endif
const char* mName; // PT: moved here from NpShape to fill padding bytes
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationJointCore.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 SC_ARTICULATION_JOINT_CORE_H
#define SC_ARTICULATION_JOINT_CORE_H
#include "foundation/PxTransform.h"
#include "common/PxMetaData.h"
#include "DyVArticulation.h"
namespace physx
{
namespace Sc
{
class BodyCore;
class ArticulationJointSim;
class ArticulationCore;
class ArticulationJointDesc
{
public:
BodyCore* parent;
BodyCore* child;
PxTransform parentPose;
PxTransform childPose;
};
class ArticulationJointCore
{
public:
// PX_SERIALIZATION
ArticulationJointCore(const PxEMPTY) : mCore(PxEmpty), mSim(NULL) {}
void preExportDataReset() { mCore.jointDirtyFlag = Dy::ArticulationJointCoreDirtyFlag::eALL; }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationJointCore(const PxTransform& parentFrame, const PxTransform& childFrame);
~ArticulationJointCore();
//Those methods are not allowed while the articulation are in the scene
PX_FORCE_INLINE const PxTransform& getParentPose() const { return mCore.parentPose; }
void setParentPose(const PxTransform&);
PX_FORCE_INLINE const PxTransform& getChildPose() const { return mCore.childPose; }
void setChildPose(const PxTransform&);
//Those functions doesn't change the articulation configuration so the application is allowed to change those value in run-time
PX_FORCE_INLINE PxArticulationLimit getLimit(PxArticulationAxis::Enum axis) const { return mCore.limits[axis]; }
void setLimit(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit);
PX_FORCE_INLINE PxArticulationDrive getDrive(PxArticulationAxis::Enum axis) const { return mCore.drives[axis]; }
void setDrive(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive);
void setTargetP(PxArticulationAxis::Enum axis, PxReal targetP);
PX_FORCE_INLINE PxReal getTargetP(PxArticulationAxis::Enum axis) const { return mCore.targetP[axis]; }
void setTargetV(PxArticulationAxis::Enum axis, PxReal targetV);
PX_FORCE_INLINE PxReal getTargetV(PxArticulationAxis::Enum axis) const { return mCore.targetV[axis]; }
void setArmature(PxArticulationAxis::Enum axis, PxReal armature);
PX_FORCE_INLINE PxReal getArmature(PxArticulationAxis::Enum axis) const { return mCore.armature[axis]; }
void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos);
PxReal getJointPosition(PxArticulationAxis::Enum axis) const;
void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel);
PxReal getJointVelocity(PxArticulationAxis::Enum axis) const;
// PT: TODO: don't we need to set ArticulationJointCoreDirtyFlag::eMOTION here?
PX_FORCE_INLINE void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) { mCore.motion[axis] = PxU8(motion); }
PX_FORCE_INLINE PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const { return PxArticulationMotion::Enum(mCore.motion[axis]); }
PX_FORCE_INLINE void setJointType(PxArticulationJointType::Enum type) { mCore.initJointType(type); }
PX_FORCE_INLINE PxArticulationJointType::Enum getJointType() const { return PxArticulationJointType::Enum(mCore.jointType); }
PX_FORCE_INLINE void setFrictionCoefficient(const PxReal coefficient) { mCore.initFrictionCoefficient(coefficient); }
PX_FORCE_INLINE PxReal getFrictionCoefficient() const { return mCore.frictionCoefficient; }
PX_FORCE_INLINE void setMaxJointVelocity(const PxReal maxJointV) { mCore.initMaxJointVelocity(maxJointV); }
PX_FORCE_INLINE PxReal getMaxJointVelocity() const { return mCore.maxJointVelocity; }
PX_FORCE_INLINE ArticulationJointSim* getSim() const { return mSim; }
PX_FORCE_INLINE void setSim(ArticulationJointSim* sim)
{
PX_ASSERT((sim==0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE Dy::ArticulationJointCore& getCore() { return mCore; }
PX_FORCE_INLINE void setArticulation(ArticulationCore* articulation) { mArticulation = articulation; }
PX_FORCE_INLINE const ArticulationCore* getArticulation() const { return mArticulation; }
PX_FORCE_INLINE void setRoot(PxArticulationJointReducedCoordinate* base) { mRootType = base; }
PX_FORCE_INLINE PxArticulationJointReducedCoordinate* getRoot() const { return mRootType; }
PX_FORCE_INLINE void setLLIndex(const PxU32 llLinkIndex) { mLLLinkIndex = llLinkIndex; }
private:
void setSimDirty();
PX_FORCE_INLINE void setDirty(Dy::ArticulationJointCoreDirtyFlag::Enum dirtyFlag)
{
mCore.jointDirtyFlag |= dirtyFlag;
setSimDirty();
}
Dy::ArticulationJointCore mCore;
ArticulationJointSim* mSim;
ArticulationCore* mArticulation;
PxArticulationJointReducedCoordinate* mRootType;
PxU32 mLLLinkIndex;
#if PX_P64_FAMILY
PxU32 pad;
#endif
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationSensor.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 SC_ARTICULATION_SENSOR_CORE
#define SC_ARTICULATION_SENSOR_CORE
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
namespace physx
{
namespace Sc
{
class ArticulationCore;
class ArticulationSensorSim;
class ArticulationSensorCore
{
public:
// PX_SERIALIZATION
ArticulationSensorCore(const PxEMPTY) :mSim(NULL) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationSensorCore(){}
PX_FORCE_INLINE void setSim(ArticulationSensorSim* sim)
{
PX_ASSERT((sim == 0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE ArticulationSensorSim* getSim() const { return mSim; }
ArticulationSensorSim* mSim;
PxTransform mRelativePose;
PxU16 mFlags;
};
}//namespace Sc
}//namespace physx
#endif //SC_ARTICULATION_SENSOR_CORE
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScStaticCore.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 SC_STATIC_CORE_H
#define SC_STATIC_CORE_H
#include "ScRigidCore.h"
#include "PxvDynamics.h"
namespace physx
{
namespace Sc
{
class StaticSim;
class StaticCore : public RigidCore
{
public:
StaticCore(const PxTransform& actor2World): RigidCore(PxActorType::eRIGID_STATIC)
{
mCore.body2World = actor2World;
mCore.mFlags = PxRigidBodyFlags();
}
PX_FORCE_INLINE const PxTransform& getActor2World() const { return mCore.body2World; }
void setActor2World(const PxTransform& actor2World);
PX_FORCE_INLINE PxsRigidCore& getCore() { return mCore; }
static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(StaticCore, mCore);}
StaticCore(const PxEMPTY) : RigidCore(PxEmpty), mCore(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
StaticSim* getSim() const;
PX_FORCE_INLINE void onOriginShift(const PxVec3& shift) { mCore.body2World.p -= shift; }
private:
PxsRigidCore mCore;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScBodyCore.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 SC_BODY_CORE_H
#define SC_BODY_CORE_H
#include "foundation/PxTransform.h"
#include "ScRigidCore.h"
#include "PxRigidDynamic.h"
#include "PxvDynamics.h"
#include "PxvConfig.h"
namespace physx
{
namespace Sc
{
class BodySim;
class BodyCore : public RigidCore
{
public:
// PX_SERIALIZATION
BodyCore(const PxEMPTY) : RigidCore(PxEmpty), mCore(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
void restoreDynamicData();
//~PX_SERIALIZATION
BodyCore(PxActorType::Enum type, const PxTransform& bodyPose);
~BodyCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
PX_FORCE_INLINE const PxTransform& getBody2World() const { return mCore.body2World; }
void setBody2World(const PxTransform& p);
void setCMassLocalPose(const PxTransform& body2Actor);
PX_FORCE_INLINE const PxVec3& getLinearVelocity() const { return mCore.linearVelocity; }
void setLinearVelocity(const PxVec3& v, bool skipBodySimUpdate=false);
PX_FORCE_INLINE const PxVec3& getAngularVelocity() const { return mCore.angularVelocity; }
void setAngularVelocity(const PxVec3& v, bool skipBodySimUpdate=false);
PX_FORCE_INLINE PxReal getCfmScale() const { return mCore.cfmScale; }
void setCfmScale(PxReal d);
PX_FORCE_INLINE void updateVelocities(const PxVec3& linearVelModPerStep, const PxVec3& angularVelModPerStep)
{
mCore.linearVelocity += linearVelModPerStep;
mCore.angularVelocity += angularVelModPerStep;
}
PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return mCore.getBody2Actor(); }
void setBody2Actor(const PxTransform& p);
void addSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc);
void setSpatialAcceleration(const PxVec3* linAcc, const PxVec3* angAcc);
void clearSpatialAcceleration(bool force, bool torque);
void addSpatialVelocity(const PxVec3* linVelDelta, const PxVec3* angVelDelta);
void clearSpatialVelocity(bool force, bool torque);
PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; }
PX_FORCE_INLINE void setMaxPenetrationBias(PxReal p) { mCore.maxPenBias = p; }
PxReal getInverseMass() const;
void setInverseMass(PxReal m);
const PxVec3& getInverseInertia() const;
void setInverseInertia(const PxVec3& i);
PxReal getLinearDamping() const;
void setLinearDamping(PxReal d);
PxReal getAngularDamping() const;
void setAngularDamping(PxReal d);
PX_FORCE_INLINE PxRigidBodyFlags getFlags() const { return mCore.mFlags; }
void setFlags(PxRigidBodyFlags f);
PX_FORCE_INLINE PxRigidDynamicLockFlags getRigidDynamicLockFlags() const { return mCore.lockFlags; }
PX_FORCE_INLINE void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) { mCore.lockFlags = flags; }
PX_FORCE_INLINE PxReal getSleepThreshold() const { return mCore.sleepThreshold; }
void setSleepThreshold(PxReal t);
PX_FORCE_INLINE PxReal getFreezeThreshold() const { return mCore.freezeThreshold; }
void setFreezeThreshold(PxReal t);
PX_FORCE_INLINE PxReal getMaxContactImpulse() const { return mCore.maxContactImpulse; }
void setMaxContactImpulse(PxReal m);
PX_FORCE_INLINE PxReal getOffsetSlop() const { return mCore.offsetSlop; }
void setOffsetSlop(PxReal slop);
PxNodeIndex getInternalIslandNodeIndex() const;
PX_FORCE_INLINE PxReal getWakeCounter() const { return mCore.wakeCounter; }
void setWakeCounter(PxReal wakeCounter, bool forceWakeUp=false);
bool isSleeping() const;
PX_FORCE_INLINE void wakeUp(PxReal wakeCounter) { setWakeCounter(wakeCounter, true); }
void putToSleep();
PxReal getMaxAngVelSq() const;
void setMaxAngVelSq(PxReal v);
PxReal getMaxLinVelSq() const;
void setMaxLinVelSq(PxReal v);
PX_FORCE_INLINE PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; }
void setSolverIterationCounts(PxU16 c);
bool getKinematicTarget(PxTransform& p) const;
bool getHasValidKinematicTarget() const;
void setKinematicTarget(const PxTransform& p, PxReal wakeCounter);
void invalidateKinematicTarget();
PX_FORCE_INLINE PxReal getContactReportThreshold() const { return mCore.contactReportThreshold; }
void setContactReportThreshold(PxReal t) { mCore.contactReportThreshold = t; }
void onOriginShift(const PxVec3& shift);
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
PX_FORCE_INLINE void setLinearVelocityInternal(const PxVec3& v) { mCore.linearVelocity = v; }
PX_FORCE_INLINE void setAngularVelocityInternal(const PxVec3& v) { mCore.angularVelocity = v; }
PX_FORCE_INLINE void setWakeCounterFromSim(PxReal c) { mCore.wakeCounter = c; }
BodySim* getSim() const;
PX_FORCE_INLINE PxsBodyCore& getCore() { return mCore; }
PX_FORCE_INLINE const PxsBodyCore& getCore() const { return mCore; }
static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(BodyCore, mCore); }
PX_FORCE_INLINE PxReal getCCDAdvanceCoefficient() const { return mCore.ccdAdvanceCoefficient; }
PX_FORCE_INLINE void setCCDAdvanceCoefficient(PxReal c) { mCore.ccdAdvanceCoefficient = c; }
void onRemoveKinematicFromScene();
PxIntBool isFrozen() const;
static PX_FORCE_INLINE BodyCore& getCore(PxsBodyCore& core)
{
return *reinterpret_cast<BodyCore*>(reinterpret_cast<PxU8*>(&core) - getCoreOffset());
}
void setFixedBaseLink(bool value);
private:
PX_ALIGN_PREFIX(16) PxsBodyCore mCore PX_ALIGN_SUFFIX(16);
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScSoftBodyCore.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 SC_SOFT_BODY_CORE_H
#define SC_SOFT_BODY_CORE_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxSoftBody.h"
#include "DySoftBodyCore.h"
#include "foundation/PxAssert.h"
#include "ScActorCore.h"
#include "ScShapeCore.h"
#include "PxFiltering.h"
#include "ScRigidCore.h" //KS - needed for ShapeChangeNotifyFlags. Move to a shared header
namespace physx
{
namespace Sc
{
class SoftBodySim;
class BodyCore;
class FEMClothCore;
class ParticleSystemCore;
class SoftBodyCore : public ActorCore
{
// PX_SERIALIZATION
public:
SoftBodyCore(const PxEMPTY) : ActorCore(PxEmpty){}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
SoftBodyCore();
~SoftBodyCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
void setMaterial(const PxU16 handle);
void clearMaterials();
PxFEMParameters getParameter() const;
void setParameter(const PxFEMParameters paramters);
PxReal getSleepThreshold() const;
void setSleepThreshold(const PxReal v);
PxReal getFreezeThreshold() const;
void setFreezeThreshold(const PxReal v);
PxU16 getSolverIterationCounts() const { return mCore.solverIterationCounts; }
void setSolverIterationCounts(PxU16 c);
PxReal getWakeCounter() const;
void setWakeCounter(const PxReal v);
void setWakeCounterInternal(const PxReal v);
bool isSleeping() const;
void wakeUp(PxReal wakeCounter);
void putToSleep();
PxActor* getPxActor() const;
void attachShapeCore(ShapeCore* shapeCore);
void attachSimulationMesh(PxTetrahedronMesh* simulationMesh, PxSoftBodyAuxData* simulationState);
void addParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId);
void removeParticleFilter(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId);
PxU32 addParticleAttachment(Sc::ParticleSystemCore* core, PxU32 particleId, PxU32 userBufferId, PxU32 tetId, const PxVec4& barycentric);
void removeParticleAttachment(Sc::ParticleSystemCore* core, PxU32 handle);
void addRigidFilter(Sc::BodyCore* core, PxU32 vertId);
void removeRigidFilter(Sc::BodyCore* core, PxU32 vertId);
PxU32 addRigidAttachment(Sc::BodyCore* core, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
void removeRigidAttachment(Sc::BodyCore* core, PxU32 handle);
void addTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx);
void removeTetRigidFilter(Sc::BodyCore* core, PxU32 tetIdx);
PxU32 addTetRigidAttachment(Sc::BodyCore* core, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose,
PxConeLimitedConstraint* constraint);
void addSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1);
void removeSoftBodyFilter(Sc::SoftBodyCore& core, PxU32 tetIdx0, PxU32 tetIdx1);
void addSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize);
void removeSoftBodyFilters(Sc::SoftBodyCore& core, PxU32* tetIndices0, PxU32* tetIndices1, PxU32 tetIndicesSize);
PxU32 addSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 tetIdx0, const PxVec4& triBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1,
PxConeLimitedConstraint* constraint, PxReal constraintOffset);
void removeSoftBodyAttachment(Sc::SoftBodyCore& core, PxU32 handle);
void addClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx);
void removeClothFilter(Sc::FEMClothCore& core, PxU32 triIdx, PxU32 tetIdx);
void addVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx);
void removeVertClothFilter(Sc::FEMClothCore& core, PxU32 vertIdx, PxU32 tetIdx);
PxU32 addClothAttachment(Sc::FEMClothCore& core, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric,
PxConeLimitedConstraint* constraint, PxReal constraintOffset);
void removeClothAttachment(Sc::FEMClothCore& core, PxU32 handle);
PxU32 getGpuSoftBodyIndex() const;
void setKinematicTargets(const PxVec4* positions, PxSoftBodyFlags flags);
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
public:
SoftBodySim* getSim() const;
PX_FORCE_INLINE const Dy::SoftBodyCore& getCore() const { return mCore; }
PX_FORCE_INLINE Dy::SoftBodyCore& getCore() { return mCore; }
void setSimulationFilterData(const PxFilterData& data);
PxFilterData getSimulationFilterData() const;
PxSoftBodyFlags getFlags() const { return mCore.mFlags; }
void setFlags(PxSoftBodyFlags flags);
PX_FORCE_INLINE PxReal getMaxPenetrationBias() const { return mCore.maxPenBias; }
PX_FORCE_INLINE void setMaxPenetrationBias(PxReal p) { mCore.maxPenBias = p; }
PX_FORCE_INLINE PxU64& getGpuMemStat() { return mGpuMemStat; }
void onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags);
private:
Dy::SoftBodyCore mCore;
PxFilterData mFilterData;
PxU64 mGpuMemStat;
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScIterators.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 SC_ITERATORS_H
#define SC_ITERATORS_H
#include "foundation/PxVec3.h"
#include "PxContact.h"
namespace physx
{
class PxShape;
class PxsContactManagerOutputIterator;
namespace Sc
{
class ShapeSimBase;
class ElementSimInteraction;
class ActorSim;
struct Contact
{
Contact()
: normal(0.0f)
, point(0.0f)
, separation(0.0f)
, normalForce(0.0f)
{}
PxVec3 normal;
PxVec3 point;
PxShape* shape0;
PxShape* shape1;
PxReal separation;
PxReal normalForce;
PxU32 faceIndex0; // these are the external indices
PxU32 faceIndex1;
bool normalForceAvailable;
};
class ContactIterator
{
public:
class Pair
{
public:
Pair() : mIter(NULL, NULL, NULL, 0, 0) {}
Pair(const void*& contactPatches, const void*& contactPoints, const PxU32 /*contactDataSize*/, const PxReal*& forces, PxU32 numContacts, PxU32 numPatches, ShapeSimBase& shape0, ShapeSimBase& shape1, ActorSim* actor0, ActorSim* actor1);
Contact* getNextContact();
PxActor* getActor0() { return mActor0; }
PxActor* getActor1() { return mActor1; }
private:
PxU32 mIndex;
PxU32 mNumContacts;
PxContactStreamIterator mIter;
const PxReal* mForces;
Contact mCurrentContact;
PxActor* mActor0;
PxActor* mActor1;
};
ContactIterator() {}
explicit ContactIterator(ElementSimInteraction** first, ElementSimInteraction** last, PxsContactManagerOutputIterator& outputs): mCurrent(first), mLast(last), mOffset(0), mOutputs(&outputs)
{
if ((!first) || (!last) || (first == last))
{
mCurrent = NULL;
mLast = NULL;
}
}
Pair* getNextPair();
private:
ElementSimInteraction** mCurrent;
ElementSimInteraction** mLast;
Pair mCurrentPair;
PxU32 mOffset;
PxsContactManagerOutputIterator* mOutputs;
private:
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScParticleSystemCore.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 SC_PARTICLESYSTEM_CORE_H
#define SC_PARTICLESYSTEM_CORE_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxParticleSystem.h"
#include "foundation/PxAssert.h"
#include "ScActorCore.h"
#include "ScShapeCore.h"
#include "PxFiltering.h"
#include "DyParticleSystem.h"
#include "ScParticleSystemShapeCore.h"
namespace physx
{
namespace Sc
{
class ParticleSystemSim;
class BodyCore;
class ParticleSystemCore : public ActorCore
{
// PX_SERIALIZATION
public:
ParticleSystemCore(const PxEMPTY) : ActorCore(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ParticleSystemCore(PxActorType::Enum actorType);
~ParticleSystemCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
PxReal getSleepThreshold() const;
void setSleepThreshold(const PxReal v);
PxReal getRestOffset() const;
void setRestOffset(const PxReal v);
PxReal getContactOffset() const;
void setContactOffset(const PxReal v);
PxReal getParticleContactOffset() const;
void setParticleContactOffset(const PxReal v);
PxReal getSolidRestOffset() const;
void setSolidRestOffset(const PxReal v);
PxReal getFluidRestOffset() const;
void setFluidRestOffset(const PxReal v);
PxReal getMaxDepenetrationVelocity() const;
void setMaxDepenetrationVelocity(const PxReal v);
PxReal getMaxVelocity() const;
void setMaxVelocity(const PxReal v);
PxParticleSystemCallback* getParticleSystemCallback() const;
void setParticleSystemCallback(PxParticleSystemCallback* callback);
PxReal getFluidBoundaryDensityScale() const;
void setFluidBoundaryDensityScale(const PxReal v);
PxU32 getGridSizeX() const;
void setGridSizeX(const PxU32 v);
PxU32 getGridSizeY() const;
void setGridSizeY(const PxU32 v);
PxU32 getGridSizeZ() const;
void setGridSizeZ(const PxU32 v);
PxU16 getSolverIterationCounts() const { return mShapeCore.getLLCore().solverIterationCounts; }
void setSolverIterationCounts(PxU16 c);
PxReal getWakeCounter() const;
void setWakeCounter(const PxReal v);
void setWakeCounterInternal(const PxReal v);
bool isSleeping() const;
void wakeUp(PxReal wakeCounter);
void putToSleep();
PxActor* getPxActor() const;
// TOFIX
void enableCCD(const bool enable);
PxParticleFlags getFlags() const { return mShapeCore.getLLCore().mFlags; }
//void setFlags(PxParticleFlags flags) { mShapeCore.getLLCore().mFlags = flags; }
void setFlags(PxParticleFlags flags);
void setWind(const PxVec3& wind) {mShapeCore.getLLCore().mWind = wind;}
PxVec3 getWind() const { return mShapeCore.getLLCore().mWind; }
void setSolverType(const PxParticleSolverType::Enum solverType) { mShapeCore.getLLCore().solverType = solverType; }
PxParticleSolverType::Enum getSolverType() const { return mShapeCore.getLLCore().solverType; }
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
PxSparseGridParams getSparseGridParams() const { return mShapeCore.getLLCore().sparseGridParams; }
void setSparseGridParams(const PxSparseGridParams& params) { mShapeCore.getLLCore().sparseGridParams = params; }
PxFLIPParams getFLIPParams() const { return mShapeCore.getLLCore().flipParams; }
void setFLIPParams(const PxFLIPParams& params) { mShapeCore.getLLCore().flipParams = params; }
PxMPMParams getMPMParams() const { return mShapeCore.getLLCore().mpmParams; }
void setMPMParams(const PxMPMParams& params) { mShapeCore.getLLCore().mpmParams = params; }
#endif
void addRigidAttachment(Sc::BodyCore* core);
void removeRigidAttachment(Sc::BodyCore* core);
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
public:
ParticleSystemSim* getSim() const;
PX_FORCE_INLINE const ParticleSystemShapeCore& getShapeCore() const { return mShapeCore; }
PX_FORCE_INLINE ParticleSystemShapeCore& getShapeCore() { return mShapeCore; }
void setDirty(const bool dirty);
private:
//ParticleSystemSim* mSim;
ParticleSystemShapeCore mShapeCore;
};
} // namespace Sc
}
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScConstraintCore.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 SC_CONSTRAINT_CORE_H
#define SC_CONSTRAINT_CORE_H
#include "PxConstraint.h"
namespace physx
{
namespace Sc
{
class ConstraintSim;
class RigidCore;
class ConstraintCore
{
public:
// PX_SERIALIZATION
ConstraintCore(const PxEMPTY) : mFlags(PxEmpty), mConnector(NULL), mSim(NULL) {}
PX_FORCE_INLINE void setConstraintFunctions(PxConstraintConnector& n, const PxConstraintShaderTable& shaders)
{
mConnector = &n;
mSolverPrep = shaders.solverPrep;
mVisualize = shaders.visualize;
}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ConstraintCore(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize);
~ConstraintCore() {}
void setBodies(RigidCore* r0v, RigidCore* r1v);
PxConstraint* getPxConstraint();
const PxConstraint* getPxConstraint() const;
PX_FORCE_INLINE PxConstraintConnector* getPxConnector() const { return mConnector; }
PX_FORCE_INLINE PxConstraintFlags getFlags() const { return mFlags; }
void setFlags(PxConstraintFlags flags);
void getForce(PxVec3& force, PxVec3& torque) const;
void setBreakForce(PxReal linear, PxReal angular);
PX_FORCE_INLINE void getBreakForce(PxReal& linear, PxReal& angular) const
{
linear = mLinearBreakForce;
angular = mAngularBreakForce;
}
void setMinResponseThreshold(PxReal threshold);
PX_FORCE_INLINE PxReal getMinResponseThreshold() const { return mMinResponseThreshold; }
void breakApart();
PX_FORCE_INLINE PxConstraintVisualize getVisualize() const { return mVisualize; }
PX_FORCE_INLINE PxConstraintSolverPrep getSolverPrep() const { return mSolverPrep; }
PX_FORCE_INLINE PxU32 getConstantBlockSize() const { return mDataSize; }
PX_FORCE_INLINE void setSim(ConstraintSim* sim)
{
PX_ASSERT((sim==0) ^ (mSim == 0));
mSim = sim;
}
PX_FORCE_INLINE ConstraintSim* getSim() const { return mSim; }
PX_FORCE_INLINE bool isDirty() const { return mIsDirty ? true : false; }
PX_FORCE_INLINE void setDirty() { mIsDirty = 1; }
PX_FORCE_INLINE void clearDirty() { mIsDirty = 0; }
private:
PxConstraintFlags mFlags;
//In order to support O(1) insert/remove mIsDirty really wants to be an index into NpScene's dirty joint array
PxU8 mIsDirty;
PxU8 mPadding;
PxVec3 mAppliedForce;
PxVec3 mAppliedTorque;
PxConstraintConnector* mConnector;
PxConstraintSolverPrep mSolverPrep;
PxConstraintVisualize mVisualize;
PxU32 mDataSize;
PxReal mLinearBreakForce;
PxReal mAngularBreakForce;
PxReal mMinResponseThreshold;
ConstraintSim* mSim;
};
} // namespace Sc
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScArticulationTendonJointCore.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 SC_TENDON_JOINT_CORE_H
#define SC_TENDON_JOINT_CORE_H
#include "foundation/PxVec3.h"
#include "solver/PxSolverDefs.h"
namespace physx
{
namespace Sc
{
class ArticulationFixedTendonSim;
class ArticulationTendonJointCore
{
public:
// PX_SERIALIZATION
ArticulationTendonJointCore(const PxEMPTY) : mTendonSim(NULL) {}
void preExportDataReset() { }
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
ArticulationTendonJointCore()
{
coefficient = PX_MAX_F32;
recipCoefficient = PX_MAX_F32;
}
PX_FORCE_INLINE PxArticulationAxis::Enum getAxis()
{
return axis;
}
PX_FORCE_INLINE void getCoefficient(PxArticulationAxis::Enum& axis_, PxReal& coefficient_, PxReal& recipCoefficient_) const
{
axis_ = axis;
coefficient_ = coefficient;
recipCoefficient_ = recipCoefficient;
}
void setCoefficient(PxArticulationAxis::Enum axis_, const PxReal coefficient_, const PxReal recipCoefficient_);
PxArticulationAxis::Enum axis;
PxReal coefficient;
PxReal recipCoefficient;
PxU32 mLLLinkIndex;
ArticulationTendonJointCore* mParent;
PxU32 mLLTendonJointIndex;
Sc::ArticulationFixedTendonSim* mTendonSim;
};
}//namespace Sc
}//namespace physx
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/simulationcontroller/include/ScHairSystemCore.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.
#ifndef SC_HAIR_SYSTEM_CORE_H
#define SC_HAIR_SYSTEM_CORE_H
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#include "ScActorCore.h"
#include "ScHairSystemShapeCore.h"
#include "DyHairSystem.h"
namespace physx
{
namespace Sc
{
class HairSystemSim;
class BodySim;
class SoftBodySim;
class HairSystemCore : public ActorCore
{
// PX_SERIALIZATION
public:
HairSystemCore(const PxEMPTY) : ActorCore(PxEmpty) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
HairSystemCore();
~HairSystemCore();
//---------------------------------------------------------------------------------
// External API
//---------------------------------------------------------------------------------
void setMaterial(const PxU16 handle);
void clearMaterials();
PxReal getContactOffset() const;
void setContactOffset(PxReal v);
PxReal getSleepThreshold() const { return mShapeCore.getLLCore().mSleepThreshold; }
void setSleepThreshold(const PxReal v);
PxU16 getSolverIterationCounts() const { return mShapeCore.getLLCore().mSolverIterationCounts; }
void setSolverIterationCounts(PxU16 c);
PxReal getWakeCounter() const { return mShapeCore.getLLCore().mWakeCounter; }
void setWakeCounter(const PxReal v);
bool isSleeping() const;
void wakeUp(PxReal wakeCounter);
void putToSleep();
PxActor* getPxActor() const;
void addAttachment(const BodySim& bodySim);
void removeAttachment(const BodySim& bodySim);
void addAttachment(const SoftBodySim& sbSim);
void removeAttachment(const SoftBodySim& sbSim);
//---------------------------------------------------------------------------------
// Internal API
//---------------------------------------------------------------------------------
public:
HairSystemSim* getSim() const;
PX_FORCE_INLINE const HairSystemShapeCore& getShapeCore() const { return mShapeCore; }
PX_FORCE_INLINE HairSystemShapeCore& getShapeCore() { return mShapeCore; }
PxHairSystemFlags getFlags() const { return PxHairSystemFlags(mShapeCore.getLLCore().mParams.mFlags); }
void setFlags(PxHairSystemFlags flags);
private:
HairSystemShapeCore mShapeCore;
};
} // namespace Sc
} // namespace physx
#endif
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/fastxml/src/PsFastXml.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/PxAssert.h"
#include "foundation/PxMemory.h"
#include "foundation/PxFoundationConfig.h"
#include "foundation/PxAllocator.h"
#include "PsFastXml.h"
#include <stdio.h>
#include <string.h>
#include <new>
#include <ctype.h>
using namespace physx;
namespace
{
#define MIN_CLOSE_COUNT 2
#define DEFAULT_READ_BUFFER_SIZE (16 * 1024)
#define NUM_ENTITY 5
struct Entity
{
const char* str;
unsigned int strLength;
char chr;
};
static const Entity entity[NUM_ENTITY] = {
{ "<", 4, '<' }, { "&", 5, '&' }, { ">", 4, '>' }, { """, 6, '\"' }, { "'", 6, '\'' }
};
class MyFastXml : public physx::shdfnd::FastXml
{
public:
enum CharType
{
CT_DATA,
CT_EOF,
CT_SOFT,
CT_END_OF_ELEMENT, // either a forward slash or a greater than symbol
CT_END_OF_LINE
};
MyFastXml(Callback* c)
{
mStreamFromMemory = true;
mCallback = c;
memset(mTypes, CT_DATA, sizeof(mTypes));
mTypes[0] = CT_EOF;
mTypes[uint8_t(' ')] = mTypes[uint8_t('\t')] = CT_SOFT;
mTypes[uint8_t('/')] = mTypes[uint8_t('>')] = mTypes[uint8_t('?')] = CT_END_OF_ELEMENT;
mTypes[uint8_t('\n')] = mTypes[uint8_t('\r')] = CT_END_OF_LINE;
mError = 0;
mStackIndex = 0;
mFileBuf = NULL;
mReadBufferEnd = NULL;
mReadBuffer = NULL;
mReadBufferSize = DEFAULT_READ_BUFFER_SIZE;
mOpenCount = 0;
mLastReadLoc = 0;
for(uint32_t i = 0; i < (MAX_STACK + 1); i++)
{
mStack[i] = NULL;
mStackAllocated[i] = false;
}
}
char* processClose(char c, const char* element, char* scan, int32_t argc, const char** argv,
FastXml::Callback* iface, bool& isError)
{
AttributePairs attr(argc, argv);
if(c == '/' || c == '?')
{
char* slash = const_cast<char*>(static_cast<const char*>(strchr(element, c)));
if(slash)
*slash = 0;
if(c == '?' && strcmp(element, "xml") == 0)
{
isError = true;
if(!iface->processXmlDeclaration(attr, 0, mLineNo))
return NULL;
}
else
{
if(!iface->processElement(element, 0, attr, mLineNo))
{
isError = true;
mError = "User aborted the parsing process";
return NULL;
}
pushElement(element);
const char* close = popElement();
if(!iface->processClose(close, mStackIndex, isError))
{
return NULL;
}
}
if(!slash)
++scan;
}
else
{
scan = skipNextData(scan);
char* data = scan; // this is the data portion of the element, only copies memory if we encounter line feeds
char* dest_data = 0;
while(*scan && *scan != '<')
{
if(getCharType(scan) == CT_END_OF_LINE)
{
if(*scan == '\r')
mLineNo++;
dest_data = scan;
*dest_data++ = ' '; // replace the linefeed with a space...
scan = skipNextData(scan);
while(*scan && *scan != '<')
{
if(getCharType(scan) == CT_END_OF_LINE)
{
if(*scan == '\r')
mLineNo++;
*dest_data++ = ' '; // replace the linefeed with a space...
scan = skipNextData(scan);
}
else
{
*dest_data++ = *scan++;
}
}
break;
}
else if('&' == *scan)
{
dest_data = scan;
while(*scan && *scan != '<')
{
if('&' == *scan)
{
if(*(scan + 1) && *(scan + 1) == '#' && *(scan + 2))
{
if(*(scan + 2) == 'x')
{
// Hexadecimal.
if(!*(scan + 3))
break;
char* q = scan + 3;
q = strchr(q, ';');
if(!q || !*q)
PX_ASSERT(0);
--q;
char ch = char(*q > '9' ? (tolower(*q) - 'a' + 10) : *q - '0');
if(*(--q) != tolower('x'))
ch |= char(*q > '9' ? (tolower(*q) - 'a' + 10) : *q - '0') << 4;
*dest_data++ = ch;
}
else
{
// Decimal.
if(!*(scan + 2))
break;
const char* q = scan + 2;
q = strchr(q, ';');
if(!q || !*q)
PX_ASSERT(0);
--q;
char ch = *q - '0';
if(*(--q) != '#')
ch |= (*q - '0') * 10;
*dest_data++ = ch;
}
char* start = scan;
char* end = strchr(start, ';');
if(end)
{
*end = 0;
scan = end + 1;
}
continue;
}
for(int i = 0; i < NUM_ENTITY; ++i)
{
if(strncmp(entity[i].str, scan, entity[i].strLength) == 0)
{
*dest_data++ = entity[i].chr;
scan += entity[i].strLength;
break;
}
}
}
else
{
*dest_data++ = *scan++;
}
}
break;
}
else
++scan;
}
if(*scan == '<')
{
if(scan[1] != '/')
{
PX_ASSERT(mOpenCount > 0);
mOpenCount--;
}
if(dest_data)
{
*dest_data = 0;
}
else
{
*scan = 0;
}
scan++; // skip it..
if(*data == 0)
data = 0;
if(!iface->processElement(element, data, attr, mLineNo))
{
isError = true;
mError = "User aborted the parsing process";
return NULL;
}
pushElement(element);
// check for the comment use case...
if(scan[0] == '!' && scan[1] == '-' && scan[2] == '-')
{
scan += 3;
while(*scan && *scan == ' ')
++scan;
char* comment = scan;
char* comment_end = strstr(scan, "-->");
if(comment_end)
{
*comment_end = 0;
scan = comment_end + 3;
if(!iface->processComment(comment))
{
isError = true;
mError = "User aborted the parsing process";
return NULL;
}
}
}
else if(*scan == '/')
{
scan = processClose(scan, iface, isError);
if(scan == NULL)
{
return NULL;
}
}
}
else
{
isError = true;
mError = "Data portion of an element wasn't terminated properly";
return NULL;
}
}
if(mOpenCount < MIN_CLOSE_COUNT)
{
scan = readData(scan);
}
return scan;
}
char* processClose(char* scan, FastXml::Callback* iface, bool& isError)
{
const char* start = popElement(), *close = start;
if(scan[1] != '>')
{
scan++;
close = scan;
while(*scan && *scan != '>')
scan++;
*scan = 0;
}
if(0 != strcmp(start, close))
{
isError = true;
mError = "Open and closing tags do not match";
return 0;
}
if(!iface->processClose(close, mStackIndex, isError))
{
// we need to set the read pointer!
uint32_t offset = uint32_t(mReadBufferEnd - scan) - 1;
uint32_t readLoc = mLastReadLoc - offset;
mFileBuf->seek(readLoc);
return NULL;
}
++scan;
return scan;
}
virtual bool processXml(physx::PxInputData& fileBuf, bool streamFromMemory)
{
releaseMemory();
mFileBuf = &fileBuf;
mStreamFromMemory = streamFromMemory;
return processXml(mCallback);
}
// if we have finished processing the data we had pending..
char* readData(char* scan)
{
for(uint32_t i = 0; i < (mStackIndex + 1); i++)
{
if(!mStackAllocated[i])
{
const char* text = mStack[i];
if(text)
{
uint32_t tlen = uint32_t(strlen(text));
mStack[i] = static_cast<const char*>(mCallback->allocate(tlen + 1));
PxMemCopy(const_cast<void*>(static_cast<const void*>(mStack[i])), text, tlen + 1);
mStackAllocated[i] = true;
}
}
}
if(!mStreamFromMemory)
{
if(scan == NULL)
{
uint32_t seekLoc = mFileBuf->tell();
mReadBufferSize = (mFileBuf->getLength() - seekLoc);
}
else
{
return scan;
}
}
if(mReadBuffer == NULL)
{
mReadBuffer = static_cast<char*>(mCallback->allocate(mReadBufferSize + 1));
}
uint32_t offset = 0;
uint32_t readLen = mReadBufferSize;
if(scan)
{
offset = uint32_t(scan - mReadBuffer);
uint32_t copyLen = mReadBufferSize - offset;
if(copyLen)
{
PX_ASSERT(scan >= mReadBuffer);
memmove(mReadBuffer, scan, copyLen);
mReadBuffer[copyLen] = 0;
readLen = mReadBufferSize - copyLen;
}
offset = copyLen;
}
uint32_t readCount = mFileBuf->read(&mReadBuffer[offset], readLen);
while(readCount > 0)
{
mReadBuffer[readCount + offset] = 0; // end of string terminator...
mReadBufferEnd = &mReadBuffer[readCount + offset];
const char* scan_ = &mReadBuffer[offset];
while(*scan_)
{
if(*scan_ == '<' && scan_[1] != '/')
{
mOpenCount++;
}
scan_++;
}
if(mOpenCount < MIN_CLOSE_COUNT)
{
uint32_t oldSize = uint32_t(mReadBufferEnd - mReadBuffer);
mReadBufferSize = mReadBufferSize * 2;
char* oldReadBuffer = mReadBuffer;
mReadBuffer = static_cast<char*>(mCallback->allocate(mReadBufferSize + 1));
PxMemCopy(mReadBuffer, oldReadBuffer, oldSize);
mCallback->deallocate(oldReadBuffer);
offset = oldSize;
uint32_t readSize = mReadBufferSize - oldSize;
readCount = mFileBuf->read(&mReadBuffer[offset], readSize);
if(readCount == 0)
break;
}
else
{
break;
}
}
mLastReadLoc = mFileBuf->tell();
return mReadBuffer;
}
bool processXml(FastXml::Callback* iface)
{
bool ret = true;
const int MAX_ATTRIBUTE = 2048; // can't imagine having more than 2,048 attributes in a single element right?
mLineNo = 1;
char* element, *scan = readData(0);
while(*scan)
{
scan = skipNextData(scan);
if(*scan == 0)
break;
if(*scan == '<')
{
if(scan[1] != '/')
{
PX_ASSERT(mOpenCount > 0);
mOpenCount--;
}
scan++;
if(*scan == '?') // Allow xml declarations
{
scan++;
}
else if(scan[0] == '!' && scan[1] == '-' && scan[2] == '-')
{
scan += 3;
while(*scan && *scan == ' ')
scan++;
char* comment = scan, *comment_end = strstr(scan, "-->");
if(comment_end)
{
*comment_end = 0;
scan = comment_end + 3;
if(!iface->processComment(comment))
{
mError = "User aborted the parsing process";
return false;
}
}
continue;
}
else if(scan[0] == '!') // Allow doctype
{
scan++;
// DOCTYPE syntax differs from usual XML so we parse it here
// Read DOCTYPE
const char* tag = "DOCTYPE";
if(!strstr(scan, tag))
{
mError = "Invalid DOCTYPE";
return false;
}
scan += strlen(tag);
// Skip whites
while(CT_SOFT == getCharType(scan))
++scan;
// Read rootElement
const char* rootElement = scan;
while(CT_DATA == getCharType(scan))
++scan;
char* endRootElement = scan;
// TODO: read remaining fields (fpi, uri, etc.)
while(CT_END_OF_ELEMENT != getCharType(scan++))
;
*endRootElement = 0;
if(!iface->processDoctype(rootElement, 0, 0, 0))
{
mError = "User aborted the parsing process";
return false;
}
continue; // Restart loop
}
}
if(*scan == '/')
{
bool isError = false;
scan = processClose(scan, iface, isError);
if(!scan)
{
if(isError)
{
mError = "User aborted the parsing process";
}
return !isError;
}
}
else
{
if(*scan == '?')
scan++;
element = scan;
int32_t argc = 0;
const char* argv[MAX_ATTRIBUTE];
bool close;
scan = nextSoftOrClose(scan, close);
if(close)
{
char c = *(scan - 1);
if(c != '?' && c != '/')
{
c = '>';
}
*scan++ = 0;
bool isError = false;
scan = processClose(c, element, scan, argc, argv, iface, isError);
if(!scan)
{
if(isError)
{
mError = "User aborted the parsing process";
}
return !isError;
}
}
else
{
if(*scan == 0)
{
return ret;
}
*scan = 0; // place a zero byte to indicate the end of the element name...
scan++;
while(*scan)
{
scan = skipNextData(scan); // advance past any soft seperators (tab or space)
if(getCharType(scan) == CT_END_OF_ELEMENT)
{
char c = *scan++;
if('?' == c)
{
if('>' != *scan) //?>
{
PX_ASSERT(0);
return false;
}
scan++;
}
bool isError = false;
scan = processClose(c, element, scan, argc, argv, iface, isError);
if(!scan)
{
if(isError)
{
mError = "User aborted the parsing process";
}
return !isError;
}
break;
}
else
{
if(argc >= MAX_ATTRIBUTE)
{
mError = "encountered too many attributes";
return false;
}
argv[argc] = scan;
scan = nextSep(scan); // scan up to a space, or an equal
if(*scan)
{
if(*scan != '=')
{
*scan = 0;
scan++;
while(*scan && *scan != '=')
scan++;
if(*scan == '=')
scan++;
}
else
{
*scan = 0;
scan++;
}
if(*scan) // if not eof...
{
scan = skipNextData(scan);
if(*scan == '"')
{
scan++;
argc++;
argv[argc] = scan;
argc++;
while(*scan && *scan != 34)
scan++;
if(*scan == '"')
{
*scan = 0;
scan++;
}
else
{
mError = "Failed to find closing quote for attribute";
return false;
}
}
else
{
// mError = "Expected quote to begin attribute";
// return false;
// PH: let's try to have a more graceful fallback
argc--;
while(*scan != '/' && *scan != '>' && *scan != 0)
scan++;
}
}
} // if( *scan )
} // if ( mTypes[*scan]
} // if( close )
} // if( *scan == '/'
} // while( *scan )
}
if(mStackIndex)
{
mError = "Invalid file format";
return false;
}
return ret;
}
const char* getError(int32_t& lineno)
{
const char* ret = mError;
lineno = mLineNo;
mError = 0;
return ret;
}
virtual void release(void)
{
Callback* c = mCallback; // get the user allocator interface
MyFastXml* f = this; // cast the this pointer
f->~MyFastXml(); // explicitely invoke the destructor for this class
c->deallocate(f); // now free up the memory associated with it.
}
private:
virtual ~MyFastXml(void)
{
releaseMemory();
}
PX_INLINE void releaseMemory(void)
{
mFileBuf = NULL;
mCallback->deallocate(mReadBuffer);
mReadBuffer = NULL;
mStackIndex = 0;
mReadBufferEnd = NULL;
mOpenCount = 0;
mLastReadLoc = 0;
mError = NULL;
for(uint32_t i = 0; i < (mStackIndex + 1); i++)
{
if(mStackAllocated[i])
{
mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[i])));
mStackAllocated[i] = false;
}
mStack[i] = NULL;
}
}
PX_INLINE CharType getCharType(char* scan) const
{
return mTypes[uint8_t(*scan)];
}
PX_INLINE char* nextSoftOrClose(char* scan, bool& close)
{
while(*scan && getCharType(scan) != CT_SOFT && *scan != '>')
scan++;
close = *scan == '>';
return scan;
}
PX_INLINE char* nextSep(char* scan)
{
while(*scan && getCharType(scan) != CT_SOFT && *scan != '=')
scan++;
return scan;
}
PX_INLINE char* skipNextData(char* scan)
{
// while we have data, and we encounter soft seperators or line feeds...
while(*scan && (getCharType(scan) == CT_SOFT || getCharType(scan) == CT_END_OF_LINE))
{
if(*scan == '\n')
mLineNo++;
scan++;
}
return scan;
}
void pushElement(const char* element)
{
PX_ASSERT(mStackIndex < uint32_t(MAX_STACK));
if(mStackIndex < uint32_t(MAX_STACK))
{
if(mStackAllocated[mStackIndex])
{
mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[mStackIndex])));
mStackAllocated[mStackIndex] = false;
}
mStack[mStackIndex++] = element;
}
}
const char* popElement(void)
{
PX_ASSERT(mStackIndex > 0);
if(mStackAllocated[mStackIndex])
{
mCallback->deallocate(const_cast<void*>(static_cast<const void*>(mStack[mStackIndex])));
mStackAllocated[mStackIndex] = false;
}
mStack[mStackIndex] = NULL;
return mStackIndex ? mStack[--mStackIndex] : NULL;
}
static const int MAX_STACK = 2048;
CharType mTypes[256];
physx::PxInputData* mFileBuf;
char* mReadBuffer;
char* mReadBufferEnd;
uint32_t mOpenCount;
uint32_t mReadBufferSize;
uint32_t mLastReadLoc;
int32_t mLineNo;
const char* mError;
uint32_t mStackIndex;
const char* mStack[MAX_STACK + 1];
bool mStreamFromMemory;
bool mStackAllocated[MAX_STACK + 1];
Callback* mCallback;
};
}
namespace physx
{
namespace shdfnd
{
FastXml* createFastXml(FastXml::Callback* iface)
{
MyFastXml* m = static_cast<MyFastXml*>(iface->allocate(sizeof(MyFastXml)));
if(m)
{
PX_PLACEMENT_NEW(m, MyFastXml(iface));
}
return static_cast<FastXml*>(m);
}
}
}
|
NVIDIA-Omniverse/PhysX/physx/source/fastxml/include/PsFastXml.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 PSFASTXML_PSFASTXML_H
#define PSFASTXML_PSFASTXML_H
#include "foundation/PxSimpleTypes.h" // defines basic data types; modify for your platform as needed.
#include "foundation/PxIO.h"
#include "foundation/PxAssert.h"
#include "foundation/PxAllocator.h"
namespace physx
{
namespace shdfnd
{
class FastXml
{
PX_NOCOPY(FastXml)
public:
class AttributePairs
{
int argc;
const char** argv;
public:
AttributePairs() : argc(0), argv(NULL)
{
}
AttributePairs(int c, const char** v) : argc(c), argv(v)
{
}
PX_INLINE int getNbAttr() const
{
return argc / 2;
}
const char* getKey(uint32_t index) const
{
PX_ASSERT((index * 2) < uint32_t(argc));
return argv[index * 2];
}
const char* getValue(uint32_t index) const
{
PX_ASSERT((index * 2 + 1) < uint32_t(argc));
return argv[index * 2 + 1];
}
const char* get(const char* attr) const
{
int32_t count = argc / 2;
for(int32_t i = 0; i < count; ++i)
{
const char* key = argv[i * 2], *value = argv[i * 2 + 1];
if(strcmp(key, attr) == 0)
return value;
}
return NULL;
}
};
/***
* Callbacks to the user with the contents of the XML file properly digested.
*/
class Callback
{
public:
virtual ~Callback()
{
}
virtual bool processComment(const char* comment) = 0; // encountered a comment in the XML
// 'element' is the name of the element that is being closed.
// depth is the recursion depth of this element.
// Return true to continue processing the XML file.
// Return false to stop processing the XML file; leaves the read pointer of the stream right after this close
// tag.
// The bool 'isError' indicates whether processing was stopped due to an error, or intentionally canceled early.
virtual bool processClose(const char* element, uint32_t depth, bool& isError) = 0; // process the 'close'
// indicator for a previously
// encountered element
// return true to continue processing the XML document, false to skip.
virtual bool processElement(const char* elementName, // name of the element
const char* elementData, // element data, null if none
const AttributePairs& attr, // attributes
int32_t lineno) = 0; // line number in the source XML file
// process the XML declaration header
virtual bool processXmlDeclaration(const AttributePairs&, // attributes
const char* /*elementData*/, int32_t /*lineno*/)
{
return true;
}
virtual bool processDoctype(const char* /*rootElement*/, // Root element tag
const char* /*type*/, // SYSTEM or PUBLIC
const char* /*fpi*/, // Formal Public Identifier
const char* /*uri*/) // Path to schema file
{
return true;
}
virtual void* allocate(uint32_t size)
{
return PxGetBroadcastAllocator()->allocate(size, "FastXml", PX_FL);
}
virtual void deallocate(void* ptr)
{
PxGetBroadcastAllocator()->deallocate(ptr);
}
};
virtual bool processXml(PxInputData& buff, bool streamFromMemory = false) = 0;
virtual const char* getError(int32_t& lineno) = 0; // report the reason for a parsing error, and the line number
// where it occurred.
FastXml()
{
}
virtual void release(void) = 0;
protected:
virtual ~FastXml()
{
}
};
FastXml* createFastXml(FastXml::Callback* iface);
} // shdfnd
} // physx
#endif // PSFASTXML_PSFASTXML_H
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMSoftBodyMaterial.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 "NpFEMSoftBodyMaterial.h"
#include "NpPhysics.h"
#include "CmUtils.h"
#if PX_SUPPORT_GPU_PHYSX
using namespace physx;
using namespace Cm;
NpFEMSoftBodyMaterial::NpFEMSoftBodyMaterial(const PxsFEMSoftBodyMaterialCore& desc) :
PxFEMSoftBodyMaterial(PxConcreteType::eSOFTBODY_MATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mMaterial(desc)
{
mMaterial.mMaterial = this; // back-reference
}
NpFEMSoftBodyMaterial::~NpFEMSoftBodyMaterial()
{
NpPhysics::getInstance().removeMaterialFromTable(*this);
}
// PX_SERIALIZATION
void NpFEMSoftBodyMaterial::resolveReferences(PxDeserializationContext&)
{
// ### this one could be automated if NpMaterial would inherit from MaterialCore
// ### well actually in that case the pointer would not even be needed....
mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial
// Maybe not the best place to do it but it has to be done before the shapes resolve material indices
// since the material index translation table is needed there. This requires that the materials have
// been added to the table already.
NpPhysics::getInstance().addMaterial(this);
}
void NpFEMSoftBodyMaterial::onRefCountZero()
{
void* ud = userData;
if (getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
{
NpFactory::getInstance().releaseFEMMaterialToPool(*this);
}
else
this->~NpFEMSoftBodyMaterial();
NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud);
}
NpFEMSoftBodyMaterial* NpFEMSoftBodyMaterial::createObject(PxU8*& address, PxDeserializationContext& context)
{
NpFEMSoftBodyMaterial* obj = PX_PLACEMENT_NEW(address, NpFEMSoftBodyMaterial(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(NpFEMSoftBodyMaterial);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
//~PX_SERIALIZATION
void NpFEMSoftBodyMaterial::release()
{
RefCountable_decRefCount(*this);
}
void NpFEMSoftBodyMaterial::acquireReference()
{
RefCountable_incRefCount(*this);
}
PxU32 NpFEMSoftBodyMaterial::getReferenceCount() const
{
return RefCountable_getRefCount(*this);
}
PX_INLINE void NpFEMSoftBodyMaterial::updateMaterial()
{
NpPhysics::getInstance().updateMaterial(*this);
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setYoungsModulus(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "NpFEMSoftBodyMaterial::setYoungsModulus: invalid float");
mMaterial.youngs = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getYoungsModulus() const
{
return mMaterial.youngs;
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setPoissons(PxReal x)
{
PX_CHECK_AND_RETURN(x >= 0.f && x < 0.5f, "PxMaterial::setPoissons: invalid float");
mMaterial.poissons = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getPoissons() const
{
return mMaterial.poissons;
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setDynamicFriction(PxReal x)
{
PX_CHECK_AND_RETURN(x >= 0.f, "PxMaterial::setDynamicFriction: invalid float");
mMaterial.dynamicFriction = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getDynamicFriction() const
{
return mMaterial.dynamicFriction;
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setDamping(PxReal x)
{
PX_CHECK_AND_RETURN(x >= 0.f, "PxMaterial::setDamping: invalid float");
mMaterial.damping = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getDamping() const
{
return mMaterial.damping;
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setDampingScale(PxReal x)
{
PX_CHECK_AND_RETURN(x >= 0.f && x<= 1.f, "PxMaterial::setDampingScale: invalid float, must be in [0.0, 1.0] range.");
mMaterial.dampingScale = toUniformU16(x);
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getDampingScale() const
{
return toUniformReal(mMaterial.dampingScale);
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setMaterialModel(PxFEMSoftBodyMaterialModel::Enum model)
{
mMaterial.materialModel = PxU16(model);
updateMaterial();
}
PxFEMSoftBodyMaterialModel::Enum NpFEMSoftBodyMaterial::getMaterialModel() const
{
return PxFEMSoftBodyMaterialModel::Enum(mMaterial.materialModel);
}
///////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setDeformThreshold(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformThreshold: invalid float");
mMaterial.deformThreshold = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getDeformThreshold() const
{
return mMaterial.deformThreshold;
}
/////////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setDeformLowLimitRatio(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformLowLimitRatio: invalid float");
mMaterial.deformLowLimitRatio = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getDeformLowLimitRatio() const
{
return mMaterial.deformLowLimitRatio;
}
/////////////////////////////////////////////////////////////////////////////////
void NpFEMSoftBodyMaterial::setDeformHighLimitRatio(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "PxFEMMaterial::setDeformLowLimitRatio: invalid float");
mMaterial.deformHighLimitRatio = x;
updateMaterial();
}
PxReal NpFEMSoftBodyMaterial::getDeformHighLimitRatio() const
{
return mMaterial.deformHighLimitRatio;
}
///////////////////////////////////////////////////////////////////////////////
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMPMMaterial.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 NP_MPM_MATERIAL_H
#define NP_MPM_MATERIAL_H
#include "common/PxSerialFramework.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
#include "CmRefCountable.h"
#include "PxsMPMMaterialCore.h"
#include "PxMPMMaterial.h"
namespace physx
{
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
// Compared to other objects, materials are special since they belong to the SDK and not to scenes
// (similar to meshes). That's why the NpMPMMaterial does have direct access to the core material instead
// of having a buffered interface for it. Scenes will have copies of the SDK material table and there
// the materials will be buffered.
class NpMPMMaterial : public PxMPMMaterial, public PxUserAllocated
{
public:
// PX_SERIALIZATION
NpMPMMaterial(PxBaseFlags baseFlags) : PxMPMMaterial(baseFlags), mMaterial(PxEmpty) {}
virtual void resolveReferences(PxDeserializationContext& context);
static NpMPMMaterial* createObject(PxU8*& address, PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
void preExportDataReset() { Cm::RefCountable_preExportDataReset(*this); }
void exportExtraData(PxSerializationContext&) {}
void importExtraData(PxDeserializationContext&) {}
virtual void requiresObjects(PxProcessPxBaseCallback&) {}
//~PX_SERIALIZATION
NpMPMMaterial(const PxsMPMMaterialCore& desc);
virtual ~NpMPMMaterial();
// PxBase
virtual void release() PX_OVERRIDE;
//~PxBase
// PxRefCounted
virtual void acquireReference() PX_OVERRIDE;
virtual PxU32 getReferenceCount() const PX_OVERRIDE;
virtual void onRefCountZero() PX_OVERRIDE;
//~PxRefCounted
// PxParticleMaterial
virtual void setFriction(PxReal friction) PX_OVERRIDE;
virtual PxReal getFriction() const PX_OVERRIDE;
virtual void setDamping(PxReal damping) PX_OVERRIDE;
virtual PxReal getDamping() const PX_OVERRIDE;
virtual void setAdhesion(PxReal adhesion) PX_OVERRIDE;
virtual PxReal getAdhesion() const PX_OVERRIDE;
virtual void setGravityScale(PxReal scale) PX_OVERRIDE;
virtual PxReal getGravityScale() const PX_OVERRIDE;
virtual void setAdhesionRadiusScale(PxReal scale) PX_OVERRIDE;
virtual PxReal getAdhesionRadiusScale() const PX_OVERRIDE;
//~PxParticleMaterial
// PxMPMMaterial
virtual void setStretchAndShearDamping(PxReal stretchAndShearDamping) PX_OVERRIDE;
virtual PxReal getStretchAndShearDamping() const PX_OVERRIDE;
virtual void setRotationalDamping(PxReal rotationalDamping) PX_OVERRIDE;
virtual PxReal getRotationalDamping() const PX_OVERRIDE;
virtual void setDensity(PxReal) PX_OVERRIDE;
virtual PxReal getDensity() const PX_OVERRIDE;
virtual void setMaterialModel(PxMPMMaterialModel::Enum) PX_OVERRIDE;
virtual PxMPMMaterialModel::Enum getMaterialModel() const PX_OVERRIDE;
virtual void setCuttingFlags(PxMPMCuttingFlags cuttingFlags) PX_OVERRIDE;
virtual PxMPMCuttingFlags getCuttingFlags() const PX_OVERRIDE;
virtual void setSandFrictionAngle(PxReal sandFrictionAngle) PX_OVERRIDE;
virtual PxReal getSandFrictionAngle() const PX_OVERRIDE;
virtual void setYieldStress(PxReal yieldStress) PX_OVERRIDE;
virtual PxReal getYieldStress() const PX_OVERRIDE;
virtual void setIsPlastic(bool) PX_OVERRIDE;
virtual bool getIsPlastic() const PX_OVERRIDE;
virtual void setYoungsModulus(PxReal) PX_OVERRIDE;
virtual PxReal getYoungsModulus() const PX_OVERRIDE;
virtual void setPoissons(PxReal) PX_OVERRIDE;
virtual PxReal getPoissons() const PX_OVERRIDE;
virtual void setHardening(PxReal) PX_OVERRIDE;
virtual PxReal getHardening() const PX_OVERRIDE;
virtual void setCriticalCompression(PxReal) PX_OVERRIDE;
virtual PxReal getCriticalCompression() const PX_OVERRIDE;
virtual void setCriticalStretch(PxReal) PX_OVERRIDE;
virtual PxReal getCriticalStretch() const PX_OVERRIDE;
virtual void setTensileDamageSensitivity(PxReal) PX_OVERRIDE;
virtual PxReal getTensileDamageSensitivity() const PX_OVERRIDE;
virtual void setCompressiveDamageSensitivity(PxReal) PX_OVERRIDE;
virtual PxReal getCompressiveDamageSensitivity() const PX_OVERRIDE;
virtual void setAttractiveForceResidual(PxReal) PX_OVERRIDE;
virtual PxReal getAttractiveForceResidual() const PX_OVERRIDE;
//~PxMPMMaterial
PX_FORCE_INLINE static void getMaterialIndices(NpMPMMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount);
private:
PX_INLINE void updateMaterial();
// PX_SERIALIZATION
public:
//~PX_SERIALIZATION
PxsMPMMaterialCore mMaterial;
};
PX_FORCE_INLINE void NpMPMMaterial::getMaterialIndices(NpMPMMaterial*const* materials, PxU16* materialIndices, PxU32 materialCount)
{
for (PxU32 i = 0; i < materialCount; i++)
materialIndices[i] = static_cast<NpMPMMaterial*>(materials[i])->mMaterial.mMaterialIndex;
}
#endif
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidStatic.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 NP_RIGID_STATIC_H
#define NP_RIGID_STATIC_H
#include "common/PxMetaData.h"
#include "PxRigidStatic.h"
#include "NpRigidActorTemplate.h"
#include "ScStaticCore.h"
namespace physx
{
typedef NpRigidActorTemplate<PxRigidStatic> NpRigidStaticT;
class NpRigidStatic : public NpRigidStaticT
{
public:
// PX_SERIALIZATION
NpRigidStatic(PxBaseFlags baseFlags) : NpRigidStaticT(baseFlags), mCore(PxEmpty) {}
void preExportDataReset() { NpRigidStaticT::preExportDataReset(); }
virtual void requiresObjects(PxProcessPxBaseCallback& c);
static NpRigidStatic* createObject(PxU8*& address, PxDeserializationContext& context);
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
NpRigidStatic(const PxTransform& pose);
virtual ~NpRigidStatic();
// PxActor
virtual void release() PX_OVERRIDE;
virtual PxActorType::Enum getType() const PX_OVERRIDE { return PxActorType::eRIGID_STATIC; }
//~PxActor
// PxRigidActor
virtual void setGlobalPose(const PxTransform& pose, bool wake) PX_OVERRIDE;
virtual PxTransform getGlobalPose() const PX_OVERRIDE;
//~PxRigidActor
// PT: I think these come from NpRigidActorTemplate
// PT: TODO: drop them eventually, they all re-route to NpActor now
virtual void switchToNoSim() PX_OVERRIDE;
virtual void switchFromNoSim() PX_OVERRIDE;
#if PX_CHECKED
bool checkConstraintValidity() const;
#endif
PX_FORCE_INLINE const Sc::StaticCore& getCore() const { return mCore; }
PX_FORCE_INLINE Sc::StaticCore& getCore() { return mCore; }
static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpRigidStatic, mCore); }
static PX_FORCE_INLINE size_t getNpShapeManagerOffset() { return PX_OFFSET_OF_RT(NpRigidStatic, mShapeManager); }
#if PX_ENABLE_DEBUG_VISUALIZATION
void visualize(PxRenderOutput& out, NpScene& scene, float scale) const;
#else
PX_CATCH_UNDEFINED_ENABLE_DEBUG_VISUALIZATION
#endif
private:
Sc::StaticCore mCore;
};
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpRigidActorTemplateInternal.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 NP_RIGID_ACTOR_TEMPLATE_INTERNAL_H
#define NP_RIGID_ACTOR_TEMPLATE_INTERNAL_H
// PT: TODO: what is not internal about NpRigidActorTemplate.h ? Just merge the two files
namespace physx
{
template<class APIClass, class T>
static PX_FORCE_INLINE void removeRigidActorT(T& rigidActor)
{
NpScene* s = rigidActor.getNpScene();
NP_WRITE_CHECK(s);
//Remove constraints (if any constraint is attached to the actor).
rigidActor.NpRigidActorTemplate<APIClass>::removeConstraints(rigidActor);
//Remove from aggregate (if it is in an aggregate).
rigidActor.NpActorTemplate<APIClass>::removeFromAggregate(rigidActor);
//Remove from scene (if it is in a scene).
PxSceneQuerySystem* sqManager = NULL;
if(s)
{
sqManager = &s->getSQAPI();
const bool noSim = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION);
s->scRemoveActor(rigidActor, true, noSim);
}
//Remove associated shapes.
rigidActor.NpRigidActorTemplate<APIClass>::removeShapes(sqManager);
}
template<class APIClass, class T>
static PX_FORCE_INLINE bool releaseRigidActorT(T& rigidActor)
{
NpScene* s = rigidActor.getNpScene();
NP_WRITE_CHECK(s);
PX_CHECK_SCENE_API_WRITE_FORBIDDEN_AND_RETURN_VAL(s, "PxActor::release() not allowed while simulation is running. Call will be ignored.", false)
const bool noSim = rigidActor.getActorFlags().isSet(PxActorFlag::eDISABLE_SIMULATION);
if(s && noSim)
{
// need to do it here because the Np-shape buffer will not be valid anymore after the removal below
// and unlike simulation objects, there is no shape buffer in the simulation controller
rigidActor.getShapeManager().clearShapesOnRelease(*s, rigidActor);
}
NpPhysics::getInstance().notifyDeletionListenersUserRelease(&rigidActor, rigidActor.userData);
//Remove constraints, aggregates, scene, shapes.
removeRigidActorT<APIClass, T>(rigidActor);
if (s)
{
s->removeFromRigidActorList(rigidActor);
}
return true;
}
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterialManager.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 NP_MATERIALMANAGER
#define NP_MATERIALMANAGER
#include "foundation/PxMemory.h"
#include "CmIDPool.h"
namespace physx
{
template<class Material>
class NpMaterialManager
{
public:
NpMaterialManager()
{
const PxU32 matCount = 128;
mMaterials = reinterpret_cast<Material**>(PX_ALLOC(sizeof(Material*) * matCount, "NpMaterialManager::initialise"));
mMaxMaterials = matCount;
PxMemZero(mMaterials, sizeof(Material*)*mMaxMaterials);
}
~NpMaterialManager() {}
void releaseMaterials()
{
for(PxU32 i=0; i<mMaxMaterials; ++i)
{
if(mMaterials[i])
{
const PxU32 handle(mMaterials[i]->mMaterial.mMaterialIndex);
mHandleManager.freeID(handle);
mMaterials[i]->release();
mMaterials[i] = NULL;
}
}
PX_FREE(mMaterials);
}
bool setMaterial(Material& mat)
{
const PxU32 poolID = mHandleManager.getNewID();
if (poolID >= MATERIAL_INVALID_HANDLE)
return false;
const PxU16 materialIndex = PxTo16(poolID);
if(materialIndex >= mMaxMaterials)
resize();
mMaterials[materialIndex] = &mat;
mat.mMaterial.mMaterialIndex = materialIndex;
return true;
}
void updateMaterial(Material& mat)
{
mMaterials[mat.mMaterial.mMaterialIndex] = &mat;
}
PX_FORCE_INLINE PxU32 getNumMaterials() const
{
return mHandleManager.getNumUsedID();
}
void removeMaterial(Material& mat)
{
const PxU16 handle = mat.mMaterial.mMaterialIndex;
if(handle != MATERIAL_INVALID_HANDLE)
{
mMaterials[handle] = NULL;
mHandleManager.freeID(PxU32(handle));
}
}
PX_FORCE_INLINE Material* getMaterial(const PxU32 index) const
{
PX_ASSERT(index < mMaxMaterials);
return mMaterials[index];
}
PX_FORCE_INLINE PxU32 getMaxSize() const
{
return mMaxMaterials;
}
PX_FORCE_INLINE Material** getMaterials() const
{
return mMaterials;
}
private:
void resize()
{
const PxU32 numMaterials = mMaxMaterials;
mMaxMaterials = PxMin(mMaxMaterials*2, PxU32(MATERIAL_INVALID_HANDLE));
Material** mat = reinterpret_cast<Material**>(PX_ALLOC(sizeof(Material*)*mMaxMaterials, "NpMaterialManager::resize"));
PxMemZero(mat, sizeof(Material*)*mMaxMaterials);
for(PxU32 i=0; i<numMaterials; ++i)
mat[i] = mMaterials[i];
PX_FREE(mMaterials);
mMaterials = mat;
}
Cm::IDPool mHandleManager;
Material** mMaterials;
PxU32 mMaxMaterials;
};
template<class Material>
class NpMaterialManagerIterator
{
public:
NpMaterialManagerIterator(const NpMaterialManager<Material>& manager) : mManager(manager), mIndex(0)
{
}
bool getNextMaterial(Material*& np)
{
const PxU32 maxSize = mManager.getMaxSize();
PxU32 index = mIndex;
while(index < maxSize && mManager.getMaterial(index)==NULL)
index++;
np = NULL;
if(index < maxSize)
np = mManager.getMaterial(index++);
mIndex = index;
return np!=NULL;
}
private:
NpMaterialManagerIterator& operator=(const NpMaterialManagerIterator&);
const NpMaterialManager<Material>& mManager;
PxU32 mIndex;
};
}
#endif
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpMaterial.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 "NpMaterial.h"
#include "NpPhysics.h"
#include "CmUtils.h"
#include "omnipvd/NpOmniPvdSetData.h"
using namespace physx;
using namespace Cm;
NpMaterial::NpMaterial(const PxsMaterialCore& desc) :
PxMaterial(PxConcreteType::eMATERIAL, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE),
mMaterial(desc)
{
mMaterial.mMaterial = this; // back-reference
}
NpMaterial::~NpMaterial()
{
OMNI_PVD_DESTROY(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, static_cast<PxMaterial &>(*this))
NpPhysics::getInstance().removeMaterialFromTable(*this);
}
// PX_SERIALIZATION
void NpMaterial::resolveReferences(PxDeserializationContext&)
{
// ### this one could be automated if NpMaterial would inherit from MaterialCore
// ### well actually in that case the pointer would not even be needed....
mMaterial.mMaterial = this; // Resolve MaterialCore::mMaterial
// Maybe not the best place to do it but it has to be done before the shapes resolve material indices
// since the material index translation table is needed there. This requires that the materials have
// been added to the table already.
NpPhysics::getInstance().addMaterial(this);
}
void NpMaterial::onRefCountZero()
{
void* ud = userData;
if(getBaseFlags() & PxBaseFlag::eOWNS_MEMORY)
NpFactory::getInstance().releaseMaterialToPool(*this);
else
this->~NpMaterial();
NpPhysics::getInstance().notifyDeletionListenersMemRelease(this, ud);
}
NpMaterial* NpMaterial::createObject(PxU8*& address, PxDeserializationContext& context)
{
NpMaterial* obj = PX_PLACEMENT_NEW(address, NpMaterial(PxBaseFlag::eIS_RELEASABLE));
address += sizeof(NpMaterial);
obj->importExtraData(context);
obj->resolveReferences(context);
return obj;
}
//~PX_SERIALIZATION
void NpMaterial::release()
{
RefCountable_decRefCount(*this);
}
void NpMaterial::acquireReference()
{
RefCountable_incRefCount(*this);
}
PxU32 NpMaterial::getReferenceCount() const
{
return RefCountable_getRefCount(*this);
}
PX_INLINE void NpMaterial::updateMaterial()
{
NpPhysics::getInstance().updateMaterial(*this);
}
///////////////////////////////////////////////////////////////////////////////
void NpMaterial::setDynamicFriction(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setDynamicFriction: invalid float");
mMaterial.dynamicFriction = x;
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, dynamicFriction, static_cast<PxMaterial &>(*this), x)
}
PxReal NpMaterial::getDynamicFriction() const
{
return mMaterial.dynamicFriction;
}
///////////////////////////////////////////////////////////////////////////////
void NpMaterial::setStaticFriction(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setStaticFriction: invalid float");
mMaterial.staticFriction = x;
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, staticFriction, static_cast<PxMaterial &>(*this), x)
}
PxReal NpMaterial::getStaticFriction() const
{
return mMaterial.staticFriction;
}
///////////////////////////////////////////////////////////////////////////////
void NpMaterial::setRestitution(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x), "PxMaterial::setRestitution: invalid float");
PX_CHECK_MSG(((mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT || x >= 0.0f) && (x <= 1.0f)), "PxMaterial::setRestitution: Restitution value has to be in [0,1]!");
if ((!(mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x < 0.0f) || (x > 1.0f))
{
PxClamp(x, 0.0f, 1.0f);
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMaterial::setRestitution: Invalid value %f was clamped to [0,1]!", PxF64(x));
}
mMaterial.restitution = x;
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitution, static_cast<PxMaterial &>(*this), x)
}
PxReal NpMaterial::getRestitution() const
{
return mMaterial.restitution;
}
/////////////////////////////////////////////////////////////////////////////////
void NpMaterial::setDamping(PxReal x)
{
PX_CHECK_AND_RETURN(PxIsFinite(x) && x >= 0.f, "PxMaterial::setDamping: invalid float. Must be >= 0");
PX_CHECK_MSG((((mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x >= 0.f) || x == 0.f), "PxMaterial::setDamping: Damping value has to be in [0,INF] and PxMaterialFlag::eCOMPLIANT_CONTACT should be raised!");
if ((!(mMaterial.flags & PxMaterialFlag::eCOMPLIANT_CONTACT) && x != 0.0f))
{
x = 0.f;
PxGetFoundation().error(PxErrorCode::eINVALID_PARAMETER, PX_FL, "PxMaterial::setDamping: Attempting to set a non-zero damping coefficient without raising PxMaterialFlag::eCOMPLIANT_CONTACT first!");
}
mMaterial.damping = x;
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, damping, static_cast<PxMaterial &>(*this), x)
}
PxReal NpMaterial::getDamping() const
{
return mMaterial.damping;
}
/////////////////////////////////////////////////////////////////////////////////
void NpMaterial::setFlag(PxMaterialFlag::Enum flag, bool value)
{
if (value)
mMaterial.flags |= flag;
else
mMaterial.flags &= ~PxMaterialFlags(flag);
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, static_cast<PxMaterial &>(*this), mMaterial.flags)
}
void NpMaterial::setFlags(PxMaterialFlags inFlags)
{
mMaterial.flags = inFlags;
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, flags, static_cast<PxMaterial &>(*this), mMaterial.flags)
}
PxMaterialFlags NpMaterial::getFlags() const
{
return mMaterial.flags;
}
///////////////////////////////////////////////////////////////////////////////
void NpMaterial::setFrictionCombineMode(PxCombineMode::Enum x)
{
mMaterial.setFrictionCombineMode(x);
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, frictionCombineMode, static_cast<PxMaterial &>(*this), x)
}
PxCombineMode::Enum NpMaterial::getFrictionCombineMode() const
{
return mMaterial.getFrictionCombineMode();
}
///////////////////////////////////////////////////////////////////////////////
void NpMaterial::setRestitutionCombineMode(PxCombineMode::Enum x)
{
mMaterial.setRestitutionCombineMode(x);
updateMaterial();
OMNI_PVD_SET(OMNI_PVD_CONTEXT_HANDLE, PxMaterial, restitutionCombineMode, static_cast<PxMaterial &>(*this), x)
}
PxCombineMode::Enum NpMaterial::getRestitutionCombineMode() const
{
return mMaterial.getRestitutionCombineMode();
}
///////////////////////////////////////////////////////////////////////////////
|
NVIDIA-Omniverse/PhysX/physx/source/physx/src/NpFEMCloth.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_NP_FEMCLOTH
#define PX_PHYSICS_NP_FEMCLOTH
#include "foundation/PxPreprocessor.h"
#if PX_SUPPORT_GPU_PHYSX
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#endif
#include "ScFEMClothCore.h"
#include "NpActorTemplate.h"
namespace physx
{
class NpShape;
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
class NpFEMCloth : public NpActorTemplate<PxFEMCloth>
{
public:
NpFEMCloth(PxCudaContextManager& cudaContextManager);
NpFEMCloth(PxBaseFlags baseFlags, PxCudaContextManager& cudaContextManager);
virtual ~NpFEMCloth() {}
void exportData(PxSerializationContext& /*context*/) const {}
//external API
virtual PxActorType::Enum getType() const { return PxActorType::eFEMCLOTH; }
virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const;
virtual void setFEMClothFlag(PxFEMClothFlag::Enum flag, bool val);
virtual void setFEMClothFlags(PxFEMClothFlags flags);
virtual PxFEMClothFlags getFEMClothFlag() const;
#if 0 // disabled until future use.
virtual void setDrag(const PxReal drag);
virtual PxReal getDrag() const;
virtual void setLift(const PxReal lift);
virtual PxReal getLift() const;
virtual void setWind(const PxVec3& wind);
virtual PxVec3 getWind() const;
virtual void setAirDensity(const PxReal wind);
virtual PxReal getAirDensity() const;
virtual void setBendingActivationAngle(const PxReal angle);
virtual PxReal getBendingActivationAngle() const;
#endif
virtual void setParameter(const PxFEMParameters& paramters);
virtual PxFEMParameters getParameter() const;
virtual void setBendingScales(const PxReal* const bendingScale, PxU32 nbElements);
virtual const PxReal* getBendingScales() const;
virtual PxU32 getNbBendingScales() const;
virtual void setMaxVelocity(const PxReal v);
virtual PxReal getMaxVelocity() const;
virtual void setMaxDepenetrationVelocity(const PxReal v);
virtual PxReal getMaxDepenetrationVelocity() const;
virtual void setNbCollisionPairUpdatesPerTimestep(const PxU32 frequency);
virtual PxU32 getNbCollisionPairUpdatesPerTimestep() const;
virtual void setNbCollisionSubsteps(const PxU32 frequency);
virtual PxU32 getNbCollisionSubsteps() const;
virtual PxVec4* getPositionInvMassBufferD();
virtual PxVec4* getVelocityBufferD();
virtual PxVec4* getRestPositionBufferD();
virtual void markDirty(PxFEMClothDataFlags flags);
virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId);
virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId);
virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle);
virtual void addTriRigidFilter(PxRigidActor* actor, PxU32 triangleId);
virtual void removeTriRigidFilter(PxRigidActor* actor, PxU32 triangleId);
virtual PxU32 addTriRigidAttachment(PxRigidActor* actor, PxU32 triangleId, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint);
virtual void removeTriRigidAttachment(PxRigidActor* actor, PxU32 handle);
virtual void addClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx);
virtual void removeClothFilter(PxFEMCloth* otherCloth, PxU32 otherTriIdx, PxU32 triIdx);
virtual PxU32 addClothAttachment(PxFEMCloth* otherCloth, PxU32 otherTriIdx, const PxVec4& otherTriBarycentric, PxU32 triIdx, const PxVec4& triBarycentric);
virtual void removeClothAttachment(PxFEMCloth* otherCloth, PxU32 handle);
virtual PxCudaContextManager* getCudaContextManager() const;
virtual void setCudaContextManager(PxCudaContextManager*);
virtual void setSolverIterationCounts(PxU32 minPositionIters);
virtual void getSolverIterationCounts(PxU32& minPositionIters) const;
virtual PxShape* getShape();
virtual bool attachShape(PxShape& shape);
virtual void detachShape();
virtual void release();
PX_FORCE_INLINE const Sc::FEMClothCore& getCore() const { return mCore; }
PX_FORCE_INLINE Sc::FEMClothCore& getCore() { return mCore; }
static PX_FORCE_INLINE size_t getCoreOffset() { return PX_OFFSET_OF_RT(NpFEMCloth, mCore); }
virtual bool isSleeping() const;
// Debug name
void setName(const char*);
const char* getName() const;
void updateMaterials();
private:
NpShape* mShape;
Sc::FEMClothCore mCore;
PxCudaContextManager* mCudaContextManager;
};
#endif
}
#endif
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.