file_path
stringlengths 21
202
| content
stringlengths 12
1.02M
| size
int64 12
1.02M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 10
993
| alphanum_fraction
float64 0.27
0.93
|
---|---|---|---|---|---|---|
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/src/px_globals.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxvGlobals.h"
#include "PxsContext.h"
#include "PxcContactMethodImpl.h"
#include "GuContactMethodImpl.h"
#if PX_SUPPORT_GPU_PHYSX
#include "PxPhysXGpu.h"
static physx::PxPhysXGpu* gPxPhysXGpu = NULL;
#endif
namespace physx
{
PxvOffsetTable gPxvOffsetTable;
void PxvInit(const PxvOffsetTable& offsetTable)
{
#if PX_SUPPORT_GPU_PHYSX
gPxPhysXGpu = NULL;
#endif
gPxvOffsetTable = offsetTable;
}
void PxvTerm()
{
#if PX_SUPPORT_GPU_PHYSX
PX_RELEASE(gPxPhysXGpu);
#endif
}
}
#if PX_SUPPORT_GPU_PHYSX
namespace physx
{
//forward declare stuff from PxPhysXGpuModuleLoader.cpp
void PxLoadPhysxGPUModule(const char* appGUID);
void PxUnloadPhysxGPUModule();
typedef physx::PxPhysXGpu* (PxCreatePhysXGpu_FUNC)();
extern PxCreatePhysXGpu_FUNC* g_PxCreatePhysXGpu_Func;
PxPhysXGpu* PxvGetPhysXGpu(bool createIfNeeded)
{
if (!gPxPhysXGpu && createIfNeeded)
{
#ifdef PX_PHYSX_GPU_STATIC
gPxPhysXGpu = PxCreatePhysXGpu();
#else
PxLoadPhysxGPUModule(NULL);
if (g_PxCreatePhysXGpu_Func)
{
gPxPhysXGpu = g_PxCreatePhysXGpu_Func();
}
#endif
}
return gPxPhysXGpu;
}
// PT: added for the standalone GPU BP but we may want to revisit this
void PxvReleasePhysXGpu(PxPhysXGpu* gpu)
{
PX_ASSERT(gpu==gPxPhysXGpu);
PxUnloadPhysxGPUModule();
PX_RELEASE(gpu);
gPxPhysXGpu = NULL;
}
}
#endif
#include "common/PxMetaData.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "PxsPBDMaterialCore.h"
#include "PxsMaterialCore.h"
namespace physx
{
template<> void PxsMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxCombineMode::Enum, PxU32)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxMaterialFlags, PxU16)
PX_DEF_BIN_METADATA_CLASS(stream, PxsMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, staticFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, restitution, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxMaterialFlags, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU8, fricCombineMode, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU8, restCombineMode, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFEMSoftBodyMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFEMSoftBodyMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, youngs, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, poissons, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, dampingScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, materialModel, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformThreshold, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformLowLimitRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxReal, deformHighLimitRatio, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxFEMSoftBodyMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMSoftBodyMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFEMClothMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFEMClothMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, youngs, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, poissons, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, dynamicFriction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxReal, thickness, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxFEMClothMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFEMClothMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsPBDMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsPBDMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxU32, flags, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, viscosity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, vorticityConfinement, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, surfaceTension, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, cohesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, lift, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, drag, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, cflCoefficient, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, particleFrictionScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxReal, particleAdhesionScale, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxPBDMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsPBDMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsFLIPMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsFLIPMaterialCore)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, viscosity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxReal, surfaceTension, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxFLIPMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsFLIPMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
template<> void PxsMPMMaterialCore::getBinaryMetaData(PxOutputStream& stream)
{
PX_DEF_BIN_METADATA_CLASS(stream, PxsMPMMaterialCore)
PX_DEF_BIN_METADATA_TYPEDEF(stream, PxIntBool, PxU32)
// MaterialData
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, friction, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, damping, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, adhesion, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, gravityScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, adhesionRadiusScale, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxIntBool, isPlastic, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, youngsModulus, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, poissonsRatio, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, hardening, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, criticalCompression, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, criticalStretch, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, tensileDamageSensitivity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, compressiveDamageSensitivity, 0)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxReal, attractiveForceResidual, 0)
// MaterialCore
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxMPMMaterial, mMaterial, PxMetaDataFlag::ePTR)
PX_DEF_BIN_METADATA_ITEM(stream, PxsMPMMaterialCore, PxU16, mMaterialIndex, PxMetaDataFlag::eHANDLE)
}
}
| 10,403 | C++ | 41.814815 | 118 | 0.783908 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvGeometry.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_GEOMETRY_H
#define PXV_GEOMETRY_H
#include "foundation/PxTransform.h"
#include "PxvConfig.h"
/*!
\file
Geometry interface
*/
/************************************************************************/
/* Shapes */
/************************************************************************/
#include "GuGeometryChecks.h"
#include "CmUtils.h"
namespace physx
{
//
// Summary of our material approach:
//
// On the API level, materials are accessed via pointer. Internally we store indices into the material table.
// The material table is stored in the SDK and the materials are shared among scenes. To make this threadsafe,
// we have the following approach:
//
// - Every scene has a copy of the SDK master material table
// - At the beginning of a simulation step, the scene material table gets synced to the master material table.
// - While the simulation is running, the scene table does not get touched.
// - Each shape stores the indices of its material(s). When the simulation is not running and a user requests the
// materials of the shape, the indices are used to fetch the material from the master material table. When the
// the simulation is running then the same indices are used internally to fetch the materials from the scene
// material table.
// - This whole scheme only works as long as the position of a material in the material table does not change
// when other materials get deleted/inserted. The data structure of the material table makes sure that is the case.
//
struct MaterialIndicesStruct
{
// PX_SERIALIZATION
MaterialIndicesStruct(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
MaterialIndicesStruct()
: indices(NULL)
, numIndices(0)
, pad(PX_PADDING_16)
{
}
~MaterialIndicesStruct()
{
}
void allocate(PxU16 size)
{
indices = PX_ALLOCATE(PxU16, size, "MaterialIndicesStruct::allocate");
numIndices = size;
}
void deallocate()
{
PX_FREE(indices);
numIndices = 0;
}
PxU16* indices; // the remap table for material index
PxU16 numIndices; // the size of the remap table
PxU16 pad; // pad for serialization
PxU32 gpuRemapId; // PT: using padding bytes on x64
};
struct PxConvexMeshGeometryLL: public PxConvexMeshGeometry
{
bool gpuCompatible; // PT: TODO: remove?
};
struct PxTriangleMeshGeometryLL: public PxTriangleMeshGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxParticleSystemGeometryLL : public PxParticleSystemGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxTetrahedronMeshGeometryLL : public PxTetrahedronMeshGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxHeightFieldGeometryLL : public PxHeightFieldGeometry
{
MaterialIndicesStruct materialsLL;
};
struct PxHairSystemGeometryLL : public PxHairSystemGeometry
{
PxU32 gpuRemapId;
};
template <> struct PxcGeometryTraits<PxParticleSystemGeometryLL> { enum { TypeID = PxGeometryType::ePARTICLESYSTEM}; };
template <> struct PxcGeometryTraits<PxConvexMeshGeometryLL> { enum { TypeID = PxGeometryType::eCONVEXMESH }; };
template <> struct PxcGeometryTraits<PxTriangleMeshGeometryLL> { enum { TypeID = PxGeometryType::eTRIANGLEMESH }; };
template <> struct PxcGeometryTraits<PxTetrahedronMeshGeometryLL> { enum { TypeID = PxGeometryType::eTETRAHEDRONMESH }; };
template <> struct PxcGeometryTraits<PxHeightFieldGeometryLL> { enum { TypeID = PxGeometryType::eHEIGHTFIELD }; };
template <> struct PxcGeometryTraits<PxHairSystemGeometryLL> { enum { TypeID = PxGeometryType::eHAIRSYSTEM }; };
class InvalidGeometry : public PxGeometry
{
public:
PX_CUDA_CALLABLE PX_FORCE_INLINE InvalidGeometry() : PxGeometry(PxGeometryType::eINVALID) {}
};
class GeometryUnion
{
public:
// PX_SERIALIZATION
GeometryUnion(const PxEMPTY) {}
static void getBinaryMetaData(PxOutputStream& stream);
//~PX_SERIALIZATION
PX_CUDA_CALLABLE PX_FORCE_INLINE GeometryUnion() { reinterpret_cast<InvalidGeometry&>(mGeometry) = InvalidGeometry(); }
PX_CUDA_CALLABLE PX_FORCE_INLINE GeometryUnion(const PxGeometry& g) { set(g); }
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxGeometry& getGeometry() const { return reinterpret_cast<const PxGeometry&>(mGeometry); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxGeometryType::Enum getType() const { return reinterpret_cast<const PxGeometry&>(mGeometry).getType(); }
PX_CUDA_CALLABLE void set(const PxGeometry& g);
template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE Geom& get()
{
checkType<Geom>(getGeometry());
return reinterpret_cast<Geom&>(mGeometry);
}
template<class Geom> PX_CUDA_CALLABLE PX_FORCE_INLINE const Geom& get() const
{
checkType<Geom>(getGeometry());
return reinterpret_cast<const Geom&>(mGeometry);
}
private:
union {
void* alignment; // PT: Makes sure the class is at least aligned to pointer size. See DE6803.
PxU8 box[sizeof(PxBoxGeometry)];
PxU8 sphere[sizeof(PxSphereGeometry)];
PxU8 capsule[sizeof(PxCapsuleGeometry)];
PxU8 plane[sizeof(PxPlaneGeometry)];
PxU8 convex[sizeof(PxConvexMeshGeometryLL)];
PxU8 particleSystem[sizeof(PxParticleSystemGeometryLL)];
PxU8 mesh[sizeof(PxTriangleMeshGeometryLL)];
PxU8 tetMesh[sizeof(PxTetrahedronMeshGeometryLL)];
PxU8 heightfield[sizeof(PxHeightFieldGeometryLL)];
PxU8 hairsystem[sizeof(PxHairSystemGeometryLL)];
PxU8 custom[sizeof(PxCustomGeometry)];
PxU8 invalid[sizeof(InvalidGeometry)];
} mGeometry;
};
struct PxShapeCoreFlag
{
enum Enum
{
eOWNS_MATERIAL_IDX_MEMORY = (1<<0), // PT: for de-serialization to avoid deallocating material index list. Moved there from Sc::ShapeCore (since one byte was free).
eIS_EXCLUSIVE = (1<<1), // PT: shape's exclusive flag
eIDT_TRANSFORM = (1<<2), // PT: true if PxsShapeCore::transform is identity
eSOFT_BODY_SHAPE = (1<<3), // True if this shape is a soft body shape
eCLOTH_SHAPE = (1<<4) // True if this shape is a cloth shape
};
};
typedef PxFlags<PxShapeCoreFlag::Enum,PxU8> PxShapeCoreFlags;
PX_FLAGS_OPERATORS(PxShapeCoreFlag::Enum,PxU8)
struct PxsShapeCore
{
PxsShapeCore()
{
setDensityForFluid(800.0f);
}
// PX_SERIALIZATION
PxsShapeCore(const PxEMPTY) : mShapeCoreFlags(PxEmpty), mGeometry(PxEmpty) {}
//~PX_SERIALIZATION
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
protected:
#endif
PX_ALIGN_PREFIX(16)
PxTransform mTransform PX_ALIGN_SUFFIX(16); // PT: Offset 0
#if PX_WINDOWS_FAMILY // PT: to avoid "error: offset of on non-standard-layout type" on Linux
public:
#endif
PX_FORCE_INLINE const PxTransform& getTransform() const
{
return mTransform;
}
PX_FORCE_INLINE void setTransform(const PxTransform& t)
{
mTransform = t;
if(t.p.isZero() && t.q.isIdentity())
mShapeCoreFlags.raise(PxShapeCoreFlag::eIDT_TRANSFORM);
else
mShapeCoreFlags.clear(PxShapeCoreFlag::eIDT_TRANSFORM);
}
PxReal mContactOffset; // PT: Offset 28
PxU8 mShapeFlags; // PT: Offset 32 !< API shape flags // PT: TODO: use PxShapeFlags here. Needs to move flags to separate file.
PxShapeCoreFlags mShapeCoreFlags; // PT: Offset 33
PxU16 mMaterialIndex; // PT: Offset 34
PxReal mRestOffset; // PT: Offset 36 - same as the API property of the same name - PT: moved from Sc::ShapeCore to fill padding bytes
GeometryUnion mGeometry; // PT: Offset 40
PxReal mTorsionalRadius; // PT: Offset 104 - PT: moved from Sc::ShapeCore to fill padding bytes
PxReal mMinTorsionalPatchRadius; // PT: Offset 108 - PT: moved from Sc::ShapeCore to fill padding bytes
PX_FORCE_INLINE float getDensityForFluid() const
{
return mGeometry.getGeometry().mTypePadding;
}
PX_FORCE_INLINE void setDensityForFluid(float density)
{
const_cast<PxGeometry&>(mGeometry.getGeometry()).mTypePadding = density;
}
};
PX_COMPILE_TIME_ASSERT( sizeof(GeometryUnion) <= 64); // PT: if you break this one I will not be happy
PX_COMPILE_TIME_ASSERT( (sizeof(PxsShapeCore)&0xf) == 0);
}
#endif
| 9,715 | C | 35.253731 | 167 | 0.732373 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsFEMSoftBodyMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_FEM_MATERIAL_CORE_H
#define PXS_FEM_MATERIAL_CORE_H
#include "PxFEMSoftBodyMaterial.h"
#include "PxsMaterialShared.h"
namespace physx
{
PX_FORCE_INLINE PX_CUDA_CALLABLE PxU16 toUniformU16(PxReal f)
{
f = PxClamp(f, 0.0f, 1.0f);
return PxU16(f * 65535.0f);
}
PX_FORCE_INLINE PX_CUDA_CALLABLE PxReal toUniformReal(PxU16 v)
{
return PxReal(v) * (1.0f / 65535.0f);
}
PX_ALIGN_PREFIX(16) struct PxsFEMSoftBodyMaterialData
{
PxReal youngs; //4
PxReal poissons; //8
PxReal dynamicFriction; //12
PxReal damping; //16
PxU16 dampingScale; //20, known to be in the range of 0...1. Mapped to integer range 0...65535
PxU16 materialModel; //22
PxReal deformThreshold; //24
PxReal deformLowLimitRatio; //28
PxReal deformHighLimitRatio; //32
PX_CUDA_CALLABLE PxsFEMSoftBodyMaterialData() :
youngs (1.e+6f),
poissons (0.45f),
dynamicFriction (0.0f),
damping (0.0f),
//dampingScale (0),
materialModel (PxFEMSoftBodyMaterialModel::eCO_ROTATIONAL),
deformThreshold (PX_MAX_F32),
deformLowLimitRatio (1.0f),
deformHighLimitRatio(1.0f)
{}
PxsFEMSoftBodyMaterialData(const PxEMPTY) {}
}PX_ALIGN_SUFFIX(16);
typedef MaterialCoreT<PxsFEMSoftBodyMaterialData, PxFEMSoftBodyMaterial> PxsFEMSoftBodyMaterialCore;
} //namespace phyxs
#endif
| 3,047 | C | 35.722891 | 101 | 0.737118 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIAL_MANAGER_H
#define PXS_MATERIAL_MANAGER_H
#include "PxsMaterialCore.h"
#include "PxsFEMSoftBodyMaterialCore.h"
#include "PxsFEMClothMaterialCore.h"
#include "PxsPBDMaterialCore.h"
#include "PxsFLIPMaterialCore.h"
#include "PxsMPMMaterialCore.h"
#include "foundation/PxAlignedMalloc.h"
namespace physx
{
struct PxsMaterialInfo
{
PxU16 mMaterialIndex0;
PxU16 mMaterialIndex1;
};
template<class MaterialCore>
class PxsMaterialManagerT
{
public:
PxsMaterialManagerT()
{
const PxU32 matCount = 128;
materials = reinterpret_cast<MaterialCore*>(physx::PxAlignedAllocator<16>().allocate(sizeof(MaterialCore)*matCount, PX_FL));
maxMaterials = matCount;
for(PxU32 i=0; i<matCount; ++i)
{
materials[i].mMaterialIndex = MATERIAL_INVALID_HANDLE;
}
}
~PxsMaterialManagerT()
{
physx::PxAlignedAllocator<16>().deallocate(materials);
}
void setMaterial(MaterialCore* mat)
{
const PxU16 materialIndex = mat->mMaterialIndex;
resize(PxU32(materialIndex) + 1);
materials[materialIndex] = *mat;
}
void updateMaterial(MaterialCore* mat)
{
materials[mat->mMaterialIndex] =*mat;
}
void removeMaterial(MaterialCore* mat)
{
mat->mMaterialIndex = MATERIAL_INVALID_HANDLE;
}
PX_FORCE_INLINE MaterialCore* getMaterial(const PxU32 index)const
{
PX_ASSERT(index < maxMaterials);
return &materials[index];
}
PxU32 getMaxSize()const
{
return maxMaterials;
}
void resize(PxU32 minValueForMax)
{
if(maxMaterials>=minValueForMax)
return;
const PxU32 numMaterials = maxMaterials;
maxMaterials = (minValueForMax+31)&~31;
MaterialCore* mat = reinterpret_cast<MaterialCore*>(physx::PxAlignedAllocator<16>().allocate(sizeof(MaterialCore)*maxMaterials, PX_FL));
for(PxU32 i=0; i<numMaterials; ++i)
mat[i] = materials[i];
for(PxU32 i = numMaterials; i < maxMaterials; ++i)
mat[i].mMaterialIndex = MATERIAL_INVALID_HANDLE;
physx::PxAlignedAllocator<16>().deallocate(materials);
materials = mat;
}
MaterialCore* materials;//make sure materials's start address is 16 bytes align
PxU32 maxMaterials;
PxU32 mPad;
#if !PX_P64_FAMILY
PxU32 mPad2;
#endif
};
//This class is used for forward declaration
class PxsMaterialManager : public PxsMaterialManagerT<PxsMaterialCore>
{
};
class PxsFEMMaterialManager : public PxsMaterialManagerT<PxsFEMSoftBodyMaterialCore>
{
};
class PxsFEMClothMaterialManager : public PxsMaterialManagerT<PxsFEMClothMaterialCore>
{
};
class PxsPBDMaterialManager : public PxsMaterialManagerT<PxsPBDMaterialCore>
{
};
class PxsFLIPMaterialManager : public PxsMaterialManagerT<PxsFLIPMaterialCore>
{
};
class PxsMPMMaterialManager : public PxsMaterialManagerT<PxsMPMMaterialCore>
{
};
template<class MaterialCore>
class PxsMaterialManagerIterator
{
public:
PxsMaterialManagerIterator(PxsMaterialManagerT<MaterialCore>& manager) : mManager(manager), mIndex(0)
{
}
bool getNextMaterial(MaterialCore*& materialCore)
{
const PxU32 maxSize = mManager.getMaxSize();
PxU32 index = mIndex;
while(index < maxSize && mManager.getMaterial(index)->mMaterialIndex == MATERIAL_INVALID_HANDLE)
index++;
materialCore = NULL;
if(index < maxSize)
materialCore = mManager.getMaterial(index++);
mIndex = index;
return materialCore!=NULL;
}
private:
PxsMaterialManagerIterator& operator=(const PxsMaterialManagerIterator&);
PxsMaterialManagerT<MaterialCore>& mManager;
PxU32 mIndex;
};
}
#endif
| 5,236 | C | 28.094444 | 140 | 0.744079 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvDynamics.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_DYNAMICS_H
#define PXV_DYNAMICS_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxIntrinsics.h"
#include "PxRigidDynamic.h"
namespace physx
{
/*!
\file
Dynamics interface.
*/
struct PxsRigidCore
{
PxsRigidCore() : mFlags(0), solverIterationCounts(0) {}
PxsRigidCore(const PxEMPTY) : mFlags(PxEmpty) {}
PX_ALIGN_PREFIX(16)
PxTransform body2World PX_ALIGN_SUFFIX(16);
PxRigidBodyFlags mFlags; // API body flags
PxU16 solverIterationCounts; // vel iters are in low word and pos iters in high word.
PX_FORCE_INLINE PxU32 isKinematic() const { return mFlags & PxRigidBodyFlag::eKINEMATIC; }
PX_FORCE_INLINE PxU32 hasCCD() const { return mFlags & PxRigidBodyFlag::eENABLE_CCD; }
PX_FORCE_INLINE PxU32 hasCCDFriction() const { return mFlags & PxRigidBodyFlag::eENABLE_CCD_FRICTION; }
PX_FORCE_INLINE PxU32 hasIdtBody2Actor() const { return mFlags & PxRigidBodyFlag::eRESERVED; }
};
PX_COMPILE_TIME_ASSERT(sizeof(PxsRigidCore) == 32);
#define PXV_CONTACT_REPORT_DISABLED PX_MAX_F32
struct PxsBodyCore : public PxsRigidCore
{
PxsBodyCore() : PxsRigidCore() { fixedBaseLink = PxU8(0); }
PxsBodyCore(const PxEMPTY) : PxsRigidCore(PxEmpty) {}
PX_FORCE_INLINE const PxTransform& getBody2Actor() const { return body2Actor; }
PX_FORCE_INLINE void setBody2Actor(const PxTransform& t)
{
if(t.p.isZero() && t.q.isIdentity())
mFlags.raise(PxRigidBodyFlag::eRESERVED);
else
mFlags.clear(PxRigidBodyFlag::eRESERVED);
body2Actor = t;
}
protected:
PxTransform body2Actor;
public:
PxReal ccdAdvanceCoefficient; //64
PxVec3 linearVelocity;
PxReal maxPenBias;
PxVec3 angularVelocity;
PxReal contactReportThreshold; //96
PxReal maxAngularVelocitySq;
PxReal maxLinearVelocitySq;
PxReal linearDamping;
PxReal angularDamping; //112
PxVec3 inverseInertia;
PxReal inverseMass; //128
PxReal maxContactImpulse;
PxReal sleepThreshold;
union
{
PxReal freezeThreshold;
PxReal cfmScale;
};
PxReal wakeCounter; //144 this is authoritative wakeCounter
PxReal solverWakeCounter; //this is calculated by the solver when it performs sleepCheck. It is committed to wakeCounter in ScAfterIntegrationTask if the body is still awake.
PxU32 numCountedInteractions;
PxReal offsetSlop; //Slop value used to snap contact line of action back in-line with the COM
PxU8 isFastMoving; //This could be a single bit but it's a u8 at the moment for simplicity's sake
PxU8 disableGravity; //This could be a single bit but it's a u8 at the moment for simplicity's sake
PxRigidDynamicLockFlags lockFlags; //This is u8.
PxU8 fixedBaseLink; //160 This indicates whether the articulation link has PxArticulationFlag::eFIX_BASE. All fits into 16 byte alignment
// PT: moved from Sc::BodyCore ctor - we don't want to duplicate all this in immediate mode
PX_FORCE_INLINE void init( const PxTransform& bodyPose,
const PxVec3& inverseInertia_, PxReal inverseMass_,
PxReal wakeCounter_, PxReal scaleSpeed,
PxReal linearDamping_, PxReal angularDamping_,
PxReal maxLinearVelocitySq_, PxReal maxAngularVelocitySq_,
PxActorType::Enum type)
{
PX_ASSERT(bodyPose.p.isFinite());
PX_ASSERT(bodyPose.q.isFinite());
// PT: TODO: unify naming convention
// From PxsRigidCore
body2World = bodyPose;
mFlags = PxRigidBodyFlags();
solverIterationCounts = (1 << 8) | 4;
setBody2Actor(PxTransform(PxIdentity));
ccdAdvanceCoefficient = 0.15f;
linearVelocity = PxVec3(0.0f);
maxPenBias = -1e32f;//-PX_MAX_F32;
angularVelocity = PxVec3(0.0f);
contactReportThreshold = PXV_CONTACT_REPORT_DISABLED;
maxAngularVelocitySq = maxAngularVelocitySq_;
maxLinearVelocitySq = maxLinearVelocitySq_;
linearDamping = linearDamping_;
angularDamping = angularDamping_;
inverseInertia = inverseInertia_;
inverseMass = inverseMass_;
maxContactImpulse = 1e32f;// PX_MAX_F32;
sleepThreshold = 5e-5f * scaleSpeed * scaleSpeed;
if(type == PxActorType::eARTICULATION_LINK)
cfmScale = 0.025f;
else
freezeThreshold = 2.5e-5f * scaleSpeed * scaleSpeed;
wakeCounter = wakeCounter_;
offsetSlop = 0.f;
// PT: this one is not initialized?
//solverWakeCounter
// PT: these are initialized in BodySim ctor
//numCountedInteractions;
//numBodyInteractions;
isFastMoving = false;
disableGravity = false;
lockFlags = PxRigidDynamicLockFlags(0);
}
};
PX_COMPILE_TIME_ASSERT(sizeof(PxsBodyCore) == 160);
}
#endif
| 6,401 | C | 36.00578 | 180 | 0.732698 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMPMMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MPM_MATERIAL_CORE_H
#define PXS_MPM_MATERIAL_CORE_H
#include "PxParticleGpu.h"
#include "PxsMaterialShared.h"
#include "PxMPMMaterial.h"
namespace physx
{
struct PxsMPMMaterialData : public PxsParticleMaterialData
{
PxsMPMMaterialData() {} // PT: TODO: ctor leaves things uninitialized, is that by design?
PxsMPMMaterialData(const PxEMPTY) {}
PxIntBool isPlastic; //24
PxReal youngsModulus; //28
PxReal poissonsRatio; //32
PxReal hardening; //snow //36
PxReal criticalCompression; //snow //40
PxReal criticalStretch; //snow //44
//Only used when damage tracking is activated in the cutting flags
PxReal tensileDamageSensitivity; //48
PxReal compressiveDamageSensitivity; //52
PxReal attractiveForceResidual; //56
PxReal sandFrictionAngle; //sand //60
PxReal yieldStress; //von Mises //64
PxMPMMaterialModel::Enum materialModel; //68
PxMPMCuttingFlags cuttingFlags; //72
PxReal density; //76;
PxReal stretchAndShearDamping; //80;
PxReal rotationalDamping; //84;
};
typedef MaterialCoreT<PxsMPMMaterialData, PxMPMMaterial> PxsMPMMaterialCore;
} //namespace phyxs
#endif
| 2,888 | C | 38.575342 | 94 | 0.74723 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxsMaterialCore.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXS_MATERIAL_CORE_H
#define PXS_MATERIAL_CORE_H
#include "PxMaterial.h"
#include "foundation/PxUtilities.h"
#include "PxsMaterialShared.h"
namespace physx
{
struct PxsMaterialData
{
PxReal dynamicFriction; //4
PxReal staticFriction; //8
PxReal restitution; //12
PxReal damping; //16
PxMaterialFlags flags; //18
PxU8 fricCombineMode; //19 PxCombineMode::Enum
PxU8 restCombineMode; //20 PxCombineMode::Enum
PxsMaterialData() :
dynamicFriction (0.0f),
staticFriction (0.0f),
restitution (0.0f),
damping (0.0f),
flags (PxMaterialFlag::eIMPROVED_PATCH_FRICTION),
fricCombineMode (PxCombineMode::eAVERAGE),
restCombineMode (PxCombineMode::eAVERAGE)
{}
PxsMaterialData(const PxEMPTY) {}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxCombineMode::Enum getFrictionCombineMode() const { return PxCombineMode::Enum(fricCombineMode); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxCombineMode::Enum getRestitutionCombineMode() const { return PxCombineMode::Enum(restCombineMode); }
PX_FORCE_INLINE void setFrictionCombineMode(PxCombineMode::Enum combineMode) { fricCombineMode = PxTo8(combineMode); }
PX_FORCE_INLINE void setRestitutionCombineMode(PxCombineMode::Enum combineMode) { restCombineMode = PxTo8(combineMode); }
};
typedef MaterialCoreT<PxsMaterialData, PxMaterial> PxsMaterialCore;
} //namespace phyxs
#endif
| 3,091 | C | 42.549295 | 137 | 0.757037 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvSimStats.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_SIM_STATS_H
#define PXV_SIM_STATS_H
#include "foundation/PxAssert.h"
#include "foundation/PxMemory.h"
#include "geometry/PxGeometry.h"
namespace physx
{
/*!
\file
Context handling
*/
/************************************************************************/
/* Context handling, types */
/************************************************************************/
/*!
Description: contains statistics for the simulation.
*/
struct PxvSimStats
{
PxvSimStats() { clearAll(); }
void clearAll() { PxMemZero(this, sizeof(PxvSimStats)); } // set counters to zero
PX_FORCE_INLINE void incCCDPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
mNbCCDPairs[g0][g1]++;
}
PX_FORCE_INLINE void decCCDPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
PX_ASSERT(mNbCCDPairs[g0][g1]);
mNbCCDPairs[g0][g1]--;
}
PX_FORCE_INLINE void incModifiedContactPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
mNbModifiedContactPairs[g0][g1]++;
}
PX_FORCE_INLINE void decModifiedContactPairs(PxGeometryType::Enum g0, PxGeometryType::Enum g1)
{
PX_ASSERT(g0 <= g1); // That's how they should be sorted
PX_ASSERT(mNbModifiedContactPairs[g0][g1]);
mNbModifiedContactPairs[g0][g1]--;
}
// PT: those guys are now persistent and shouldn't be cleared each frame
PxU32 mNbDiscreteContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbCCDPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbModifiedContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mNbDiscreteContactPairsTotal; // PT: sum of mNbDiscreteContactPairs, i.e. number of pairs reaching narrow phase
PxU32 mNbDiscreteContactPairsWithCacheHits;
PxU32 mNbDiscreteContactPairsWithContacts;
PxU32 mNbActiveConstraints;
PxU32 mNbActiveDynamicBodies;
PxU32 mNbActiveKinematicBodies;
PxU32 mNbAxisSolverConstraints;
PxU32 mTotalCompressedContactSize;
PxU32 mTotalConstraintSize;
PxU32 mPeakConstraintBlockAllocations;
PxU32 mNbNewPairs;
PxU32 mNbLostPairs;
PxU32 mNbNewTouches;
PxU32 mNbLostTouches;
PxU32 mNbPartitions;
};
}
#endif
| 4,082 | C | 35.455357 | 119 | 0.727095 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/api/include/PxvManager.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXV_MANAGER_H
#define PXV_MANAGER_H
#include "foundation/PxVec3.h"
#include "foundation/PxQuat.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMemory.h"
#include "PxvConfig.h"
#include "PxvGeometry.h"
namespace physx
{
/*!
\file
Manager interface
*/
/************************************************************************/
/* Managers */
/************************************************************************/
class PxsContactManager;
struct PxsRigidCore;
struct PxsShapeCore;
class PxsRigidBody;
/*!
Type of PXD_MANAGER_CCD_MODE property
*/
enum PxvContactManagerCCDMode
{
PXD_MANAGER_CCD_NONE,
PXD_MANAGER_CCD_LINEAR
};
/*!
Manager descriptor
*/
struct PxvManagerDescRigidRigid
{
/*!
Manager user data
\sa PXD_MANAGER_USER_DATA
*/
//void* userData;
/*!
Dominance setting for one way interactions.
A dominance of 0 means the corresp. body will
not be pushable by the other body in the constraint.
\sa PXD_MANAGER_DOMINANCE0
*/
PxU8 dominance0;
/*!
Dominance setting for one way interactions.
A dominance of 0 means the corresp. body will
not be pushable by the other body in the constraint.
\sa PXD_MANAGER_DOMINANCE1
*/
PxU8 dominance1;
/*!
PxsRigidBodies
*/
PxsRigidBody* rigidBody0;
PxsRigidBody* rigidBody1;
/*!
Shape Core structures
*/
const PxsShapeCore* shapeCore0;
const PxsShapeCore* shapeCore1;
/*!
Body Core structures
*/
PxsRigidCore* rigidCore0;
PxsRigidCore* rigidCore1;
/*!
Enable contact information reporting.
*/
int reportContactInfo;
/*!
Enable contact impulse threshold reporting.
*/
int hasForceThreshold;
/*!
Enable generated contacts to be changeable
*/
int contactChangeable;
/*!
Disable strong friction
*/
//int disableStrongFriction;
/*!
Contact resolution rest distance.
*/
PxReal restDistance;
/*!
Disable contact response
*/
int disableResponse;
/*!
Disable discrete contact generation
*/
int disableDiscreteContact;
/*!
Disable CCD contact generation
*/
int disableCCDContact;
/*!
Is connected to an articulation (1 - first body, 2 - second body)
*/
int hasArticulations;
/*!
is connected to a dynamic (1 - first body, 2 - second body)
*/
int hasDynamics;
/*!
Is the pair touching? Use when re-creating the manager with prior knowledge about touch status.
positive: pair is touching
0: touch state unknown (this is a new pair)
negative: pair is not touching
Default is 0
*/
int hasTouch;
/*!
Identifies whether body 1 is kinematic. We can treat kinematics as statics and embed velocity into constraint
because kinematic bodies' velocities will not change
*/
bool body1Kinematic;
/*
Index entries into the transform cache for shape 0
*/
PxU32 transformCache0;
/*
Index entries into the transform cache for shape 1
*/
PxU32 transformCache1;
PxvManagerDescRigidRigid()
{
PxMemSet(this, 0, sizeof(PxvManagerDescRigidRigid));
dominance0 = 1u;
dominance1 = 1u;
}
};
/*!
Report struct for contact manager touch reports
*/
struct PxvContactManagerTouchEvent
{
void* userData;
// PT: only useful to search for places where we get/set this specific user data
PX_FORCE_INLINE void setCMTouchEventUserData(void* ud) { userData = ud; }
PX_FORCE_INLINE void* getCMTouchEventUserData() const { return userData; }
};
}
#endif
| 5,101 | C | 22.730232 | 110 | 0.709273 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpMemBlockPool.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "foundation/PxMath.h"
#include "PxcNpMemBlockPool.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxInlineArray.h"
#include "PxcScratchAllocator.h"
using namespace physx;
PxcNpMemBlockPool::PxcNpMemBlockPool(PxcScratchAllocator& allocator) :
mConstraints("PxcNpMemBlockPool::mConstraints"),
mExceptionalConstraints("PxcNpMemBlockPool::mExceptionalConstraints"),
mNpCacheActiveStream(0),
mFrictionActiveStream(0),
mCCDCacheActiveStream(0),
mContactIndex(0),
mAllocatedBlocks(0),
mMaxBlocks(0),
mUsedBlocks(0),
mMaxUsedBlocks(0),
mScratchBlockAddr(0),
mNbScratchBlocks(0),
mScratchAllocator(allocator),
mPeakConstraintAllocations(0),
mConstraintAllocations(0)
{
}
void PxcNpMemBlockPool::init(PxU32 initialBlockCount, PxU32 maxBlocks)
{
mMaxBlocks = maxBlocks;
mInitialBlocks = initialBlockCount;
PxU32 reserve = PxMax<PxU32>(initialBlockCount, 64);
mConstraints.reserve(reserve);
mExceptionalConstraints.reserve(16);
mFriction[0].reserve(reserve);
mFriction[1].reserve(reserve);
mNpCache[0].reserve(reserve);
mNpCache[1].reserve(reserve);
mUnused.reserve(reserve);
setBlockCount(initialBlockCount);
}
PxU32 PxcNpMemBlockPool::getUsedBlockCount() const
{
return mUsedBlocks;
}
PxU32 PxcNpMemBlockPool::getMaxUsedBlockCount() const
{
return mMaxUsedBlocks;
}
PxU32 PxcNpMemBlockPool::getPeakConstraintBlockCount() const
{
return mPeakConstraintAllocations;
}
void PxcNpMemBlockPool::setBlockCount(PxU32 blockCount)
{
PxMutex::ScopedLock lock(mLock);
PxU32 current = getUsedBlockCount();
for(PxU32 i=current;i<blockCount;i++)
{
mUnused.pushBack(reinterpret_cast<PxcNpMemBlock *>(PX_ALLOC(PxcNpMemBlock::SIZE, "PxcNpMemBlock")));
mAllocatedBlocks++;
}
}
void PxcNpMemBlockPool::releaseUnusedBlocks()
{
PxMutex::ScopedLock lock(mLock);
while(mUnused.size())
{
PxcNpMemBlock* ptr = mUnused.popBack();
PX_FREE(ptr);
mAllocatedBlocks--;
}
}
PxcNpMemBlockPool::~PxcNpMemBlockPool()
{
// swapping twice guarantees all blocks are released from the stream pairs
swapFrictionStreams();
swapFrictionStreams();
swapNpCacheStreams();
swapNpCacheStreams();
releaseConstraintMemory();
releaseContacts();
releaseContacts();
PX_ASSERT(mUsedBlocks == 0);
flushUnused();
}
void PxcNpMemBlockPool::acquireConstraintMemory()
{
PxU32 size;
void* addr = mScratchAllocator.allocAll(size);
size = size&~(PxcNpMemBlock::SIZE-1);
PX_ASSERT(mScratchBlocks.size()==0);
mScratchBlockAddr = reinterpret_cast<PxcNpMemBlock*>(addr);
mNbScratchBlocks = size/PxcNpMemBlock::SIZE;
mScratchBlocks.resize(mNbScratchBlocks);
for(PxU32 i=0;i<mNbScratchBlocks;i++)
mScratchBlocks[i] = mScratchBlockAddr+i;
}
void PxcNpMemBlockPool::releaseConstraintMemory()
{
PxMutex::ScopedLock lock(mLock);
mPeakConstraintAllocations = mConstraintAllocations = 0;
while(mConstraints.size())
{
PxcNpMemBlock* block = mConstraints.popBack();
if(mScratchAllocator.isScratchAddr(block))
mScratchBlocks.pushBack(block);
else
{
mUnused.pushBack(block);
PX_ASSERT(mUsedBlocks>0);
mUsedBlocks--;
}
}
for(PxU32 i=0;i<mExceptionalConstraints.size();i++)
PX_FREE(mExceptionalConstraints[i]);
mExceptionalConstraints.clear();
PX_ASSERT(mScratchBlocks.size()==mNbScratchBlocks); // check we released them all
mScratchBlocks.clear();
if(mScratchBlockAddr)
{
mScratchAllocator.free(mScratchBlockAddr);
mScratchBlockAddr = 0;
mNbScratchBlocks = 0;
}
}
PxcNpMemBlock* PxcNpMemBlockPool::acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount, PxU32* peakAllocationCount, bool isScratchAllocation)
{
PxMutex::ScopedLock lock(mLock);
if(allocationCount && peakAllocationCount)
{
*peakAllocationCount = PxMax(*allocationCount + 1, *peakAllocationCount);
(*allocationCount)++;
}
// this is a bit of hack - the logic would be better placed in acquireConstraintBlock, but then we'd have to grab the mutex
// once there to check the scratch block array and once here if we fail - or, we'd need a larger refactor to separate out
// locking and acquisition.
if(isScratchAllocation && mScratchBlocks.size()>0)
{
PxcNpMemBlock* block = mScratchBlocks.popBack();
trackingArray.pushBack(block);
return block;
}
if(mUnused.size())
{
PxcNpMemBlock* block = mUnused.popBack();
trackingArray.pushBack(block);
mMaxUsedBlocks = PxMax<PxU32>(mUsedBlocks+1, mMaxUsedBlocks);
mUsedBlocks++;
return block;
}
if(mAllocatedBlocks == mMaxBlocks)
{
#if PX_CHECKED
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL,
"Reached maximum number of allocated blocks so 16k block allocation will fail!");
#endif
return NULL;
}
#if PX_CHECKED
if(mInitialBlocks)
{
PxGetFoundation().error(PxErrorCode::eDEBUG_WARNING, PX_FL,
"Number of required 16k memory blocks has exceeded the initial number of blocks. Allocator is being called. Consider increasing the number of pre-allocated 16k blocks.");
}
#endif
// increment here so that if we hit the limit in separate threads we won't overallocated
mAllocatedBlocks++;
PxcNpMemBlock* block = reinterpret_cast<PxcNpMemBlock*>(PX_ALLOC(sizeof(PxcNpMemBlock), "PxcNpMemBlock"));
if(block)
{
trackingArray.pushBack(block);
mMaxUsedBlocks = PxMax<PxU32>(mUsedBlocks+1, mMaxUsedBlocks);
mUsedBlocks++;
}
else
mAllocatedBlocks--;
return block;
}
PxU8* PxcNpMemBlockPool::acquireExceptionalConstraintMemory(PxU32 size)
{
PxU8* memory = reinterpret_cast<PxU8*>(PX_ALLOC(size, "PxcNpExceptionalMemory"));
if(memory)
{
PxMutex::ScopedLock lock(mLock);
mExceptionalConstraints.pushBack(memory);
}
return memory;
}
void PxcNpMemBlockPool::release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount)
{
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mUsedBlocks >= deadArray.size());
mUsedBlocks -= deadArray.size();
if(allocationCount)
{
*allocationCount -= deadArray.size();
}
while(deadArray.size())
{
PxcNpMemBlock* block = deadArray.popBack();
for(PxU32 a = 0; a < mUnused.size(); ++a)
{
PX_ASSERT(mUnused[a] != block);
}
mUnused.pushBack(block);
}
}
void PxcNpMemBlockPool::flushUnused()
{
while(mUnused.size())
{
PxcNpMemBlock* ptr = mUnused.popBack();
PX_FREE(ptr);
}
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireConstraintBlock()
{
// we track the scratch blocks in the constraint block array, because the code in acquireMultipleConstraintBlocks
// assumes that acquired blocks are listed there.
return acquire(mConstraints);
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireConstraintBlock(PxcNpMemBlockArray& memBlocks)
{
return acquire(memBlocks, &mConstraintAllocations, &mPeakConstraintAllocations, true);
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireContactBlock()
{
return acquire(mContacts[mContactIndex], NULL, NULL, true);
}
void PxcNpMemBlockPool::releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks)
{
PxMutex::ScopedLock lock(mLock);
while(memBlocks.size())
{
PxcNpMemBlock* block = memBlocks.popBack();
if(mScratchAllocator.isScratchAddr(block))
mScratchBlocks.pushBack(block);
else
{
mUnused.pushBack(block);
PX_ASSERT(mUsedBlocks>0);
mUsedBlocks--;
}
}
}
void PxcNpMemBlockPool::releaseContacts()
{
//releaseConstraintBlocks(mContacts);
release(mContacts[1-mContactIndex]);
mContactIndex = 1-mContactIndex;
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireFrictionBlock()
{
return acquire(mFriction[mFrictionActiveStream]);
}
void PxcNpMemBlockPool::swapFrictionStreams()
{
release(mFriction[1-mFrictionActiveStream]);
mFrictionActiveStream = 1-mFrictionActiveStream;
}
PxcNpMemBlock* PxcNpMemBlockPool::acquireNpCacheBlock()
{
return acquire(mNpCache[mNpCacheActiveStream]);
}
void PxcNpMemBlockPool::swapNpCacheStreams()
{
release(mNpCache[1-mNpCacheActiveStream]);
mNpCacheActiveStream = 1-mNpCacheActiveStream;
}
| 9,542 | C++ | 26.501441 | 173 | 0.763991 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcContactCache.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcContactCache.h"
#include "PxsContactManager.h"
#include "foundation/PxUtilities.h"
#include "PxcNpCache.h"
#include "CmMatrix34.h"
using namespace physx;
using namespace Gu;
using namespace Cm;
//#define ENABLE_CONTACT_CACHE_STATS
#ifdef ENABLE_CONTACT_CACHE_STATS
static PxU32 gNbCalls;
static PxU32 gNbHits;
#endif
void PxcClearContactCacheStats()
{
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbCalls = 0;
gNbHits = 0;
#endif
}
void PxcDisplayContactCacheStats()
{
#ifdef ENABLE_CONTACT_CACHE_STATS
pxPrintf("%d|%d (%f)\n", gNbHits, gNbCalls, gNbCalls ? float(gNbHits)/float(gNbCalls) : 0.0f);
#endif
}
namespace physx
{
const bool g_CanUseContactCache[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
false, //PxcContactSphereSphere
false, //PxcContactSpherePlane
true, //PxcContactSphereCapsule
false, //PxcContactSphereBox
true, //PxcContactSphereConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactSphereMesh
true, //PxcContactSphereHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::ePLANE
{
false, //-
false, //PxcInvalidContactPair
true, //PxcContactPlaneCapsule
true, //PxcContactPlaneBox
true, //PxcContactPlaneConvex
false, //ParticleSystem
true, //SoftBody
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eCAPSULE
{
false, //-
false, //-
true, //PxcContactCapsuleCapsule
true, //PxcContactCapsuleBox
true, //PxcContactCapsuleConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactCapsuleMesh
true, //PxcContactCapsuleHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eBOX
{
false, //-
false, //-
false, //-
true, //PxcContactBoxBox
true, //PxcContactBoxConvex
false, //ParticleSystem
true, //SoftBody
true, //PxcContactBoxMesh
true, //PxcContactBoxHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::eCONVEXMESH
{
false, //-
false, //-
false, //-
false, //-
true, //PxcContactConvexConvex
false, //-
true, //-
true, //PxcContactConvexMesh2
true, //PxcContactConvexHeightField
false, //PxcInvalidContactPair (hair)
false, //PxcContactGeometryCustomGeometry
},
//PxGeometryType::ePARTICLESYSTEM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eTETRAHEDRONMESH
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eTRIANGLEMESH
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eHEIGHTFIELD
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair (hair)
false, //PxcInvalidContactPair
},
//PxGeometryType::eHAIRSYSTEM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
},
//PxGeometryType::eCUSTOM
{
false, //-
false, //-
false, //-
false, //-
false, //-
false, //-
true, //-
false, //-
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
false, //PxcInvalidContactPair
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_CanUseContactCache) / sizeof(g_CanUseContactCache[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
static PX_FORCE_INLINE void updateContact( PxContactPoint& dst, const PxcLocalContactsCache& contactsData,
const PxMat34& world0, const PxMat34& world1,
const PxVec3& point, const PxVec3& normal, float separation)
{
const PxVec3 tmp0 = contactsData.mTransform0.transformInv(point);
const PxVec3 worldpt0 = world0.transform(tmp0);
const PxVec3 tmp1 = contactsData.mTransform1.transformInv(point);
const PxVec3 worldpt1 = world1.transform(tmp1);
const PxVec3 motion = worldpt0 - worldpt1;
dst.normal = normal;
dst.point = (worldpt0 + worldpt1)*0.5f;
//dst.point = point;
dst.separation = separation + motion.dot(normal);
}
static PX_FORCE_INLINE void prefetchData128(PxU8* PX_RESTRICT ptr, PxU32 size)
{
// PT: always prefetch the cache line containing our address (which unfortunately won't be aligned to 128 most of the time)
PxPrefetchLine(ptr, 0);
// PT: compute start offset of our data within its cache line
const PxU32 startOffset = PxU32(size_t(ptr)&127);
// PT: prefetch next cache line if needed
if(startOffset+size>128)
PxPrefetchLine(ptr+128, 0);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, const PxVec3& v)
{
*reinterpret_cast<PxVec3*>(bytes) = v;
return bytes + sizeof(PxVec3);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, PxReal v)
{
*reinterpret_cast<PxReal*>(bytes) = v;
return bytes + sizeof(PxReal);
}
static PX_FORCE_INLINE PxU8* outputToCache(PxU8* PX_RESTRICT bytes, PxU32 v)
{
*reinterpret_cast<PxU32*>(bytes) = v;
return bytes + sizeof(PxU32);
}
//PxU32 gContactCache_NbCalls = 0;
//PxU32 gContactCache_NbHits = 0;
static PX_FORCE_INLINE PxReal maxComponentDeltaPos(const PxTransform& t0, const PxTransform& t1)
{
PxReal delta = PxAbs(t0.p.x - t1.p.x);
delta = PxMax(delta, PxAbs(t0.p.y - t1.p.y));
delta = PxMax(delta, PxAbs(t0.p.z - t1.p.z));
return delta;
}
static PX_FORCE_INLINE PxReal maxComponentDeltaRot(const PxTransform& t0, const PxTransform& t1)
{
PxReal delta = PxAbs(t0.q.x - t1.q.x);
delta = PxMax(delta, PxAbs(t0.q.y - t1.q.y));
delta = PxMax(delta, PxAbs(t0.q.z - t1.q.z));
delta = PxMax(delta, PxAbs(t0.q.w - t1.q.w));
return delta;
}
bool physx::PxcCacheLocalContacts( PxcNpThreadContext& context, Cache& pairContactCache,
const PxTransform32& tm0, const PxTransform32& tm1,
const PxcContactMethod conMethod,
const PxGeometry& shape0, const PxGeometry& shape1)
{
const NarrowPhaseParams& params = context.mNarrowPhaseParams;
// gContactCache_NbCalls++;
if(pairContactCache.mCachedData)
prefetchData128(pairContactCache.mCachedData, pairContactCache.mCachedSize);
PxContactBuffer& contactBuffer = context.mContactBuffer;
contactBuffer.reset();
PxcLocalContactsCache contactsData;
PxU32 nbCachedBytes;
const PxU8* cachedBytes = PxcNpCacheRead2(pairContactCache, contactsData, nbCachedBytes);
pairContactCache.mCachedData = NULL;
pairContactCache.mCachedSize = 0;
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbCalls++;
#endif
const PxU32 payloadSize = (sizeof(PxcLocalContactsCache)+3)&~3;
if(cachedBytes)
{
// PT: we used to store the relative TM but it's better to save memory and recompute it
const PxTransform t0to1 = tm1.transformInv(tm0);
const PxTransform relTM = contactsData.mTransform1.transformInv(contactsData.mTransform0);
const PxReal epsilon = 0.01f;
if( maxComponentDeltaPos(t0to1, relTM)<epsilon*params.mToleranceLength
&& maxComponentDeltaRot(t0to1, relTM)<epsilon)
{
// gContactCache_NbHits++;
const PxU32 nbContacts = contactsData.mNbCachedContacts;
PxU8* ls = PxcNpCacheWriteInitiate(context.mNpCacheStreamPair, pairContactCache, contactsData, nbCachedBytes);
prefetchData128(ls, (payloadSize + 4 + nbCachedBytes + 0xF)&~0xF);
contactBuffer.count = nbContacts;
if(nbContacts)
{
PxContactPoint* PX_RESTRICT dst = contactBuffer.contacts;
const Matrix34FromTransform world1(tm1);
const Matrix34FromTransform world0(tm0);
const bool sameNormal = contactsData.mSameNormal;
const PxU8* contacts = reinterpret_cast<const PxU8*>(cachedBytes);
const PxVec3* normal0 = NULL;
for(PxU32 i=0;i<nbContacts;i++)
{
if(i!=nbContacts-1)
PxPrefetchLine(contacts, 128);
const PxVec3* cachedNormal;
if(!i || !sameNormal)
{
cachedNormal = reinterpret_cast<const PxVec3*>(contacts); contacts += sizeof(PxVec3);
normal0 = cachedNormal;
}
else
{
cachedNormal = normal0;
}
const PxVec3* cachedPoint = reinterpret_cast<const PxVec3*>(contacts); contacts += sizeof(PxVec3);
const PxReal* cachedPD = reinterpret_cast<const PxReal*>(contacts); contacts += sizeof(PxReal);
updateContact(*dst, contactsData, world0, world1, *cachedPoint, *cachedNormal, *cachedPD);
if(contactsData.mUseFaceIndices)
{
const PxU32* cachedIndex1 = reinterpret_cast<const PxU32*>(contacts); contacts += sizeof(PxU32);
dst->internalFaceIndex1 = *cachedIndex1;
}
else
{
dst->internalFaceIndex1 = PXC_CONTACT_NO_FACE_INDEX;
}
dst++;
}
}
if(ls)
PxcNpCacheWriteFinalize(ls, contactsData, nbCachedBytes, cachedBytes);
#ifdef ENABLE_CONTACT_CACHE_STATS
gNbHits++;
#endif
return true;
}
else
{
// PT: if we reach this point we cached the contacts but we couldn't use them next frame
// => waste of time and memory
}
}
conMethod(shape0, shape1, tm0, tm1, params, pairContactCache, context.mContactBuffer, &context.mRenderOutput);
//if(contactBuffer.count)
{
contactsData.mTransform0 = tm0;
contactsData.mTransform1 = tm1;
PxU32 nbBytes = 0;
const PxU8* bytes = NULL;
const PxU32 count = contactBuffer.count;
if(count)
{
const bool useFaceIndices = contactBuffer.contacts[0].internalFaceIndex1!=PXC_CONTACT_NO_FACE_INDEX;
contactsData.mNbCachedContacts = PxTo16(count);
contactsData.mUseFaceIndices = useFaceIndices;
const PxContactPoint* PX_RESTRICT srcContacts = contactBuffer.contacts;
// PT: this loop should not be here. We should output the contacts directly compressed, as we used to.
bool sameNormal = true;
{
const PxVec3 normal0 = srcContacts->normal;
for(PxU32 i=1;i<count;i++)
{
if(srcContacts[i].normal!=normal0)
{
sameNormal = false;
break;
}
}
}
contactsData.mSameNormal = sameNormal;
if(!sameNormal)
{
const PxU32 sizeof_CachedContactPoint = sizeof(PxVec3) + sizeof(PxVec3) + sizeof(PxReal);
const PxU32 sizeof_CachedContactPointAndFaceIndices = sizeof_CachedContactPoint + sizeof(PxU32);
const PxU32 sizeOfItem = useFaceIndices ? sizeof_CachedContactPointAndFaceIndices : sizeof_CachedContactPoint;
nbBytes = count * sizeOfItem;
}
else
{
const PxU32 sizeof_CachedContactPoint = sizeof(PxVec3) + sizeof(PxReal);
const PxU32 sizeof_CachedContactPointAndFaceIndices = sizeof_CachedContactPoint + sizeof(PxU32);
const PxU32 sizeOfItem = useFaceIndices ? sizeof_CachedContactPointAndFaceIndices : sizeof_CachedContactPoint;
nbBytes = sizeof(PxVec3) + count * sizeOfItem;
}
PxU8* ls = PxcNpCacheWriteInitiate(context.mNpCacheStreamPair, pairContactCache, contactsData, nbBytes);
if(ls)
{
*reinterpret_cast<PxcLocalContactsCache*>(ls) = contactsData;
*reinterpret_cast<PxU32*>(ls+payloadSize) = nbBytes;
bytes = ls+payloadSize+sizeof(PxU32);
PxU8* dest = const_cast<PxU8*>(bytes);
for(PxU32 i=0;i<count;i++)
{
if(!i || !sameNormal)
dest = outputToCache(dest, srcContacts[i].normal);
dest = outputToCache(dest, srcContacts[i].point);
dest = outputToCache(dest, srcContacts[i].separation);
if(useFaceIndices)
{
dest = outputToCache(dest, srcContacts[i].internalFaceIndex1);
}
}
PX_ASSERT(size_t(dest) - size_t(bytes)==nbBytes);
}
else
{
contactsData.mNbCachedContacts = 0;
PxcNpCacheWrite(context.mNpCacheStreamPair, pairContactCache, contactsData, 0, bytes);
}
}
else
{
contactsData.mNbCachedContacts = 0;
contactsData.mUseFaceIndices = false;
PxcNpCacheWrite(context.mNpCacheStreamPair, pairContactCache, contactsData, nbBytes, bytes);
}
}
return false;
}
| 14,360 | C++ | 28.671488 | 124 | 0.700139 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcMaterialMethodImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcMaterialMethodImpl.h"
#include "PxvGeometry.h"
#include "PxcNpThreadContext.h"
#include "PxsMaterialManager.h"
#include "GuTriangleMesh.h"
#include "GuHeightField.h"
using namespace physx;
using namespace Gu;
// PT: moved these functions to same file for improving code locality and easily reusing code (calling smaller functions from larger ones, see below)
///////////////////////////////////////////////////////////////////////////////
static void PxcGetMaterialShape(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxU16 materialIndex = shape->mMaterialIndex;
const PxU32 count = context.mContactBuffer.count;
PX_ASSERT(index==0 || index==1);
for(PxU32 i=0; i<count; i++)
(&materialInfo[i].mMaterialIndex0)[index] = materialIndex;
}
static void PxcGetMaterialShapeShape(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxU16 materialIndex0 = shape0->mMaterialIndex;
const PxU16 materialIndex1 = shape1->mMaterialIndex;
const PxU32 count = context.mContactBuffer.count;
for(PxU32 i=0; i<count; i++)
{
materialInfo[i].mMaterialIndex0 = materialIndex0;
materialInfo[i].mMaterialIndex1 = materialIndex1;
}
}
///////////////////////////////////////////////////////////////////////////////
static PX_FORCE_INLINE const PxU16* getMaterialIndicesLL(const PxTriangleMeshGeometry& meshGeom)
{
return static_cast<const Gu::TriangleMesh*>(meshGeom.triangleMesh)->getMaterials();
}
static void PxcGetMaterialMesh(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 0 || index == 1);
const PxTriangleMeshGeometryLL& shapeMesh = shape->mGeometry.get<const PxTriangleMeshGeometryLL>();
if(shapeMesh.materialsLL.numIndices <= 1)
{
PxcGetMaterialShape(shape, index, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh);
const PxU16* indices = shapeMesh.materialsLL.indices;
for(PxU32 i=0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
(&materialInfo[i].mMaterialIndex0)[index] = indices[localMaterialIndex];
}
}
}
static void PxcGetMaterialShapeMesh(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxTriangleMeshGeometryLL& shapeMesh = shape1->mGeometry.get<const PxTriangleMeshGeometryLL>();
if(shapeMesh.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh);
const PxU16* indices = shapeMesh.materialsLL.indices;
const PxU16 materialIndex0 = shape0->mMaterialIndex;
for(PxU32 i=0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = materialIndex0;
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
materialInfo[i].mMaterialIndex1 = indices[localMaterialIndex];
}
}
}
static void PxcGetMaterialSoftBodyMesh(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
// PT: TODO: check this, it reads shape0 and labels it shapeMesh1? It's otherwise the same code as PxcGetMaterialShapeMesh ?
const PxTriangleMeshGeometryLL& shapeMesh1 = shape0->mGeometry.get<const PxTriangleMeshGeometryLL>();
if (shapeMesh1.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* eaMaterialIndices = getMaterialIndicesLL(shapeMesh1);
const PxU16* indices = shapeMesh1.materialsLL.indices;
const PxU16 materialIndex0 = shape0->mMaterialIndex;
for (PxU32 i = 0; i<count; i++)
{
PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = materialIndex0;
const PxU32 localMaterialIndex = eaMaterialIndices ? eaMaterialIndices[contact.internalFaceIndex1] : 0;//shapeMesh.triangleMesh->getTriangleMaterialIndex(contact.featureIndex1);
//contact.featureIndex1 = shapeMesh.materials.indices[localMaterialIndex];
materialInfo[i].mMaterialIndex1 = indices[localMaterialIndex];
}
}
}
///////////////////////////////////////////////////////////////////////////////
static PxU32 GetMaterialIndex(const Gu::HeightFieldData* hfData, PxU32 triangleIndex)
{
const PxU32 sampleIndex = triangleIndex >> 1;
const bool isFirstTriangle = (triangleIndex & 0x1) == 0;
//get sample
const PxHeightFieldSample* hf = &hfData->samples[sampleIndex];
return isFirstTriangle ? hf->materialIndex0 : hf->materialIndex1;
}
static void PxcGetMaterialHeightField(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 0 || index == 1);
const PxHeightFieldGeometryLL& hfGeom = shape->mGeometry.get<const PxHeightFieldGeometryLL>();
if(hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShape(shape, index, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
(&materialInfo[i].mMaterialIndex0)[index] = materialIndices[localMaterialIndex];
}
}
}
static void PxcGetMaterialShapeHeightField(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxHeightFieldGeometryLL& hfGeom = shape1->mGeometry.get<const PxHeightFieldGeometryLL>();
if(hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = shape0->mMaterialIndex;
//contact.featureIndex0 = shape0->materialIndex;
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
//contact.featureIndex1 = materialIndices[localMaterialIndex];
PX_ASSERT(localMaterialIndex<hfGeom.materialsLL.numIndices);
materialInfo[i].mMaterialIndex1 = materialIndices[localMaterialIndex];
}
}
}
static void PxcGetMaterialSoftBodyHeightField(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
const PxHeightFieldGeometryLL& hfGeom = shape1->mGeometry.get<const PxHeightFieldGeometryLL>();
if (hfGeom.materialsLL.numIndices <= 1)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
else
{
const PxContactBuffer& contactBuffer = context.mContactBuffer;
const PxU32 count = contactBuffer.count;
const PxU16* materialIndices = hfGeom.materialsLL.indices;
const Gu::HeightFieldData* hf = &static_cast<const Gu::HeightField*>(hfGeom.heightField)->getData();
for(PxU32 i=0; i<count; i++)
{
const PxContactPoint& contact = contactBuffer.contacts[i];
materialInfo[i].mMaterialIndex0 = shape0->mMaterialIndex;
//contact.featureIndex0 = shape0->materialIndex;
const PxU32 localMaterialIndex = GetMaterialIndex(hf, contact.internalFaceIndex1);
//contact.featureIndex1 = materialIndices[localMaterialIndex];
PX_ASSERT(localMaterialIndex<hfGeom.materialsLL.numIndices);
materialInfo[i].mMaterialIndex1 = materialIndices[localMaterialIndex];
}
}
}
///////////////////////////////////////////////////////////////////////////////
static void PxcGetMaterialSoftBody(const PxsShapeCore* shape, const PxU32 index, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PX_ASSERT(index == 1);
PX_UNUSED(index);
PxcGetMaterialShape(shape, index, context, materialInfo);
}
static void PxcGetMaterialShapeSoftBody(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
static void PxcGetMaterialSoftBodySoftBody(const PxsShapeCore* shape0, const PxsShapeCore* shape1, PxcNpThreadContext& context, PxsMaterialInfo* materialInfo)
{
PxcGetMaterialShapeShape(shape0, shape1, context, materialInfo);
}
///////////////////////////////////////////////////////////////////////////////
namespace physx
{
PxcGetSingleMaterialMethod g_GetSingleMaterialMethodTable[] =
{
PxcGetMaterialShape, //PxGeometryType::eSPHERE
PxcGetMaterialShape, //PxGeometryType::ePLANE
PxcGetMaterialShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShape, //PxGeometryType::eBOX
PxcGetMaterialShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShape, //PxGeometryType::eCUSTOM
};
PX_COMPILE_TIME_ASSERT(sizeof(g_GetSingleMaterialMethodTable) / sizeof(g_GetSingleMaterialMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
//Table of contact methods for different shape-type combinations
PxcGetMaterialMethod g_GetMaterialMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcGetMaterialShapeShape, //PxGeometryType::eSPHERE
PxcGetMaterialShapeShape, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcGetMaterialShapeShape, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcGetMaterialShapeShape, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcGetMaterialShapeShape, //PxGeometryType::eCONVEXMESH
PxcGetMaterialShapeSoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialShapeSoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialShapeMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialShapeHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeSoftBody, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialSoftBodyMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialSoftBodyHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
PxcGetMaterialSoftBodySoftBody, //PxGeometryType::eTETRAHEDRONMESH
PxcGetMaterialSoftBodyMesh, //PxGeometryType::eTRIANGLEMESH //not used: mesh always uses swept method for midphase.
PxcGetMaterialSoftBodyHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcGetMaterialShapeShape, //PxGeometryType::eHAIRYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcGetMaterialShapeShape, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_GetMaterialMethodTable) / sizeof(g_GetMaterialMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
| 19,532 | C++ | 42.310421 | 180 | 0.746314 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcContactMethodImpl.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxGeometry.h"
#include "PxcContactMethodImpl.h"
using namespace physx;
#define ARGS shape0, shape1, transform0, transform1, params, cache, contactBuffer, renderOutput
static bool PxcInvalidContactPair (GU_CONTACT_METHOD_ARGS_UNUSED) { return false; }
// PT: IMPORTANT: do NOT remove the indirection! Using the Gu functions directly in the table produces massive perf problems.
static bool PxcContactSphereSphere (GU_CONTACT_METHOD_ARGS) { return contactSphereSphere(ARGS); }
static bool PxcContactSphereCapsule (GU_CONTACT_METHOD_ARGS) { return contactSphereCapsule(ARGS); }
static bool PxcContactSphereBox (GU_CONTACT_METHOD_ARGS) { return contactSphereBox(ARGS); }
static bool PxcContactSpherePlane (GU_CONTACT_METHOD_ARGS) { return contactSpherePlane(ARGS); }
static bool PxcContactSphereConvex (GU_CONTACT_METHOD_ARGS) { return contactCapsuleConvex(ARGS); }
static bool PxcContactSphereMesh (GU_CONTACT_METHOD_ARGS) { return contactSphereMesh(ARGS); }
static bool PxcContactSphereHeightField (GU_CONTACT_METHOD_ARGS) { return contactSphereHeightfield(ARGS); }
static bool PxcContactPlaneBox (GU_CONTACT_METHOD_ARGS) { return contactPlaneBox(ARGS); }
static bool PxcContactPlaneCapsule (GU_CONTACT_METHOD_ARGS) { return contactPlaneCapsule(ARGS); }
static bool PxcContactPlaneConvex (GU_CONTACT_METHOD_ARGS) { return contactPlaneConvex(ARGS); }
static bool PxcContactCapsuleCapsule (GU_CONTACT_METHOD_ARGS) { return contactCapsuleCapsule(ARGS); }
static bool PxcContactCapsuleBox (GU_CONTACT_METHOD_ARGS) { return contactCapsuleBox(ARGS); }
static bool PxcContactCapsuleConvex (GU_CONTACT_METHOD_ARGS) { return contactCapsuleConvex(ARGS); }
static bool PxcContactCapsuleMesh (GU_CONTACT_METHOD_ARGS) { return contactCapsuleMesh(ARGS); }
static bool PxcContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS) { return contactCapsuleHeightfield(ARGS); }
static bool PxcContactBoxBox (GU_CONTACT_METHOD_ARGS) { return contactBoxBox(ARGS); }
static bool PxcContactBoxConvex (GU_CONTACT_METHOD_ARGS) { return contactBoxConvex(ARGS); }
static bool PxcContactBoxMesh (GU_CONTACT_METHOD_ARGS) { return contactBoxMesh(ARGS); }
static bool PxcContactBoxHeightField (GU_CONTACT_METHOD_ARGS) { return contactBoxHeightfield(ARGS); }
static bool PxcContactConvexConvex (GU_CONTACT_METHOD_ARGS) { return contactConvexConvex(ARGS); }
static bool PxcContactConvexMesh (GU_CONTACT_METHOD_ARGS) { return contactConvexMesh(ARGS); }
static bool PxcContactConvexHeightField (GU_CONTACT_METHOD_ARGS) { return contactConvexHeightfield(ARGS); }
static bool PxcContactGeometryCustomGeometry (GU_CONTACT_METHOD_ARGS) { return contactGeometryCustomGeometry(ARGS); }
static bool PxcPCMContactSphereSphere (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereSphere(ARGS); }
static bool PxcPCMContactSpherePlane (GU_CONTACT_METHOD_ARGS) { return pcmContactSpherePlane(ARGS); }
static bool PxcPCMContactSphereBox (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereBox(ARGS); }
static bool PxcPCMContactSphereCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereCapsule(ARGS); }
static bool PxcPCMContactSphereConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereConvex(ARGS); }
static bool PxcPCMContactSphereMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereMesh(ARGS); }
static bool PxcPCMContactSphereHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactSphereHeightField(ARGS); }
static bool PxcPCMContactPlaneCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneCapsule(ARGS); }
static bool PxcPCMContactPlaneBox (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneBox(ARGS); }
static bool PxcPCMContactPlaneConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactPlaneConvex(ARGS); }
static bool PxcPCMContactCapsuleCapsule (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleCapsule(ARGS); }
static bool PxcPCMContactCapsuleBox (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleBox(ARGS); }
static bool PxcPCMContactCapsuleConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleConvex(ARGS); }
static bool PxcPCMContactCapsuleMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleMesh(ARGS); }
static bool PxcPCMContactCapsuleHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactCapsuleHeightField(ARGS); }
static bool PxcPCMContactBoxBox (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxBox(ARGS); }
static bool PxcPCMContactBoxConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxConvex(ARGS); }
static bool PxcPCMContactBoxMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxMesh(ARGS); }
static bool PxcPCMContactBoxHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactBoxHeightField(ARGS); }
static bool PxcPCMContactConvexConvex (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexConvex(ARGS); }
static bool PxcPCMContactConvexMesh (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexMesh(ARGS); }
static bool PxcPCMContactConvexHeightField (GU_CONTACT_METHOD_ARGS) { return pcmContactConvexHeightField(ARGS); }
static bool PxcPCMContactGeometryCustomGeometry (GU_CONTACT_METHOD_ARGS) { return pcmContactGeometryCustomGeometry(ARGS); }
#undef ARGS
namespace physx
{
//Table of contact methods for different shape-type combinations
PxcContactMethod g_ContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcContactSphereSphere, //PxGeometryType::eSPHERE
PxcContactSpherePlane, //PxGeometryType::ePLANE
PxcContactSphereCapsule, //PxGeometryType::eCAPSULE
PxcContactSphereBox, //PxGeometryType::eBOX
PxcContactSphereConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactSphereMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactSphereHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
PxcInvalidContactPair, //PxGeometryType::ePLANE
PxcContactPlaneCapsule, //PxGeometryType::eCAPSULE
PxcContactPlaneBox, //PxGeometryType::eBOX
PxcContactPlaneConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcContactCapsuleCapsule, //PxGeometryType::eCAPSULE
PxcContactCapsuleBox, //PxGeometryType::eBOX
PxcContactCapsuleConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactCapsuleMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactCapsuleHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcContactBoxBox, //PxGeometryType::eBOX
PxcContactBoxConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactBoxMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactBoxHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcContactConvexConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcContactConvexMesh, //PxGeometryType::eTRIANGLEMESH
PxcContactConvexHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_ContactMethodTable) / sizeof(g_ContactMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
//Table of contact methods for different shape-type combinations
PxcContactMethod g_PCMContactMethodTable[][PxGeometryType::eGEOMETRY_COUNT] =
{
//PxGeometryType::eSPHERE
{
PxcPCMContactSphereSphere, //PxGeometryType::eSPHERE
PxcPCMContactSpherePlane, //PxGeometryType::ePLANE
PxcPCMContactSphereCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactSphereBox, //PxGeometryType::eBOX
PxcPCMContactSphereConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactSphereMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactSphereHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePLANE
{
0, //PxGeometryType::eSPHERE
PxcInvalidContactPair, //PxGeometryType::ePLANE
PxcPCMContactPlaneCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactPlaneBox, //PxGeometryType::eBOX
PxcPCMContactPlaneConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eCAPSULE
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
PxcPCMContactCapsuleCapsule, //PxGeometryType::eCAPSULE
PxcPCMContactCapsuleBox, //PxGeometryType::eBOX
PxcPCMContactCapsuleConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactCapsuleMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactCapsuleHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eBOX
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
PxcPCMContactBoxBox, //PxGeometryType::eBOX
PxcPCMContactBoxConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactBoxMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactBoxHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCONVEXMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
PxcPCMContactConvexConvex, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcPCMContactConvexMesh, //PxGeometryType::eTRIANGLEMESH
PxcPCMContactConvexHeightField, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry, //PxGeometryType::eCUSTOM
},
//PxGeometryType::ePARTICLESYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTETRAHEDRONMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
PxcInvalidContactPair, //PxGeometryType::ePARTICLESYSTEM
PxcInvalidContactPair, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD //TODO: make HF midphase that will mask this
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eTRIANGLEMESH
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
PxcInvalidContactPair, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eHEIGHTFIELD
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
PxcInvalidContactPair, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
//PxGeometryType::eHAIRSYSTEM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
PxcInvalidContactPair, //PxGeometryType::eHAIRSYSTEM
PxcInvalidContactPair, //PxGeometryType::eCUSTOM
},
//PxGeometryType::eCUSTOM
{
0, //PxGeometryType::eSPHERE
0, //PxGeometryType::ePLANE
0, //PxGeometryType::eCAPSULE
0, //PxGeometryType::eBOX
0, //PxGeometryType::eCONVEXMESH
0, //PxGeometryType::ePARTICLESYSTEM
0, //PxGeometryType::eTETRAHEDRONMESH
0, //PxGeometryType::eTRIANGLEMESH
0, //PxGeometryType::eHEIGHTFIELD
0, //PxGeometryType::eHAIRSYSTEM
PxcPCMContactGeometryCustomGeometry,//PxGeometryType::eCUSTOM
},
};
PX_COMPILE_TIME_ASSERT(sizeof(g_PCMContactMethodTable) / sizeof(g_PCMContactMethodTable[0]) == PxGeometryType::eGEOMETRY_COUNT);
}
| 21,192 | C++ | 48.05787 | 128 | 0.74514 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpThreadContext.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxcConstraintBlockStream.h"
#include "PxcNpThreadContext.h"
using namespace physx;
PxcNpThreadContext::PxcNpThreadContext(PxcNpContext* params) :
mRenderOutput (params->mRenderBuffer),
mContactBlockStream (params->mNpMemBlockPool),
mNpCacheStreamPair (params->mNpMemBlockPool),
mNarrowPhaseParams (0.0f, params->mMeshContactMargin, params->mToleranceLength),
mBodySimPool ("BodySimPool"),
mPCM (false),
mContactCache (false),
mCreateAveragePoint (false),
#if PX_ENABLE_SIM_STATS
mCompressedCacheSize (0),
mNbDiscreteContactPairsWithCacheHits(0),
mNbDiscreteContactPairsWithContacts (0),
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
mMaxPatches (0),
mTotalCompressedCacheSize (0),
mContactStreamPool (params->mContactStreamPool),
mPatchStreamPool (params->mPatchStreamPool),
mForceAndIndiceStreamPool (params->mForceAndIndiceStreamPool),
mMaterialManager (params->mMaterialManager),
mLocalNewTouchCount (0),
mLocalLostTouchCount (0)
{
#if PX_ENABLE_SIM_STATS
clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
PxcNpThreadContext::~PxcNpThreadContext()
{
}
#if PX_ENABLE_SIM_STATS
void PxcNpThreadContext::clearStats()
{
PxMemSet(mDiscreteContactPairs, 0, sizeof(mDiscreteContactPairs));
PxMemSet(mModifiedContactPairs, 0, sizeof(mModifiedContactPairs));
mCompressedCacheSize = 0;
mNbDiscreteContactPairsWithCacheHits = 0;
mNbDiscreteContactPairsWithContacts = 0;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
void PxcNpThreadContext::reset(PxU32 cmCount)
{
mContactBlockStream.reset();
mNpCacheStreamPair.reset();
mLocalChangeTouch.clear();
mLocalChangeTouch.resize(cmCount);
mLocalNewTouchCount = 0;
mLocalLostTouchCount = 0;
}
| 3,476 | C++ | 36.387096 | 85 | 0.767261 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpBatch.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "geometry/PxTriangleMesh.h"
#include "common/PxProfileZone.h"
#include "PxcNpBatch.h"
#include "PxcNpWorkUnit.h"
#include "PxcContactCache.h"
#include "PxcNpContactPrepShared.h"
#include "PxvGeometry.h"
#include "CmTask.h"
#include "PxsMaterialManager.h"
#include "PxsTransformCache.h"
#include "PxsContactManagerState.h"
// PT: use this define to enable detailed analysis of the NP functions.
//#define LOCAL_PROFILE_ZONE(x, y) PX_PROFILE_ZONE(x, y)
#define LOCAL_PROFILE_ZONE(x, y)
using namespace physx;
using namespace Gu;
PX_COMPILE_TIME_ASSERT(sizeof(PxsCachedTransform)==sizeof(PxTransform32));
static void startContacts(PxsContactManagerOutput& output, PxcNpThreadContext& context)
{
context.mContactBuffer.reset();
output.contactForces = NULL;
output.contactPatches = NULL;
output.contactPoints = NULL;
output.nbContacts = 0;
output.nbPatches = 0;
output.statusFlag = 0;
}
static void flipContacts(PxcNpThreadContext& threadContext, PxsMaterialInfo* PX_RESTRICT materialInfo)
{
PxContactBuffer& buffer = threadContext.mContactBuffer;
for(PxU32 i=0; i<buffer.count; ++i)
{
PxContactPoint& contactPoint = buffer.contacts[i];
contactPoint.normal = -contactPoint.normal;
PxSwap(materialInfo[i].mMaterialIndex0, materialInfo[i].mMaterialIndex1);
}
}
static PX_FORCE_INLINE void updateDiscreteContactStats(PxcNpThreadContext& context, PxGeometryType::Enum type0, PxGeometryType::Enum type1)
{
#if PX_ENABLE_SIM_STATS
PX_ASSERT(type0<=type1);
context.mDiscreteContactPairs[type0][type1]++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(context);
PX_UNUSED(type0);
PX_UNUSED(type1);
#endif
}
static bool copyBuffers(PxsContactManagerOutput& cmOutput, Gu::Cache& cache, PxcNpThreadContext& context, const bool useContactCache, const bool isMeshType)
{
bool ret = false;
//Copy the contact stream from previous buffer to current buffer...
PxU32 oldSize = sizeof(PxContact) * cmOutput.nbContacts + sizeof(PxContactPatch)*cmOutput.nbPatches;
if(oldSize)
{
ret = true;
PxU8* oldPatches = cmOutput.contactPatches;
PxU8* oldContacts = cmOutput.contactPoints;
PxReal* oldForces = cmOutput.contactForces;
PxU32 forceSize = cmOutput.nbContacts * sizeof(PxReal);
if(isMeshType)
forceSize += cmOutput.nbContacts * sizeof(PxU32);
PxU8* PX_RESTRICT contactPatches = NULL;
PxU8* PX_RESTRICT contactPoints = NULL;
PxReal* forceBuffer = NULL;
bool isOverflown = false;
//ML: if we are using contactStreamPool, which means we are running the GPU codepath
if(context.mContactStreamPool)
{
const PxU32 patchSize = cmOutput.nbPatches * sizeof(PxContactPatch);
const PxU32 contactSize = cmOutput.nbContacts * sizeof(PxContact);
PxU32 index = PxU32(PxAtomicAdd(&context.mContactStreamPool->mSharedDataIndex, PxI32(contactSize)));
if(context.mContactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactPoints = context.mContactStreamPool->mDataStream + context.mContactStreamPool->mDataStreamSize - index;
const PxU32 patchIndex = PxU32(PxAtomicAdd(&context.mPatchStreamPool->mSharedDataIndex, PxI32(patchSize)));
if(context.mPatchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactPatches = context.mPatchStreamPool->mDataStream + context.mPatchStreamPool->mDataStreamSize - patchIndex;
if(forceSize)
{
index = PxU32(PxAtomicAdd(&context.mForceAndIndiceStreamPool->mSharedDataIndex, PxI32(forceSize)));
if(context.mForceAndIndiceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
forceBuffer = reinterpret_cast<PxReal*>(context.mForceAndIndiceStreamPool->mDataStream + context.mForceAndIndiceStreamPool->mDataStreamSize - index);
}
if(isOverflown)
{
contactPatches = NULL;
contactPoints = NULL;
forceBuffer = NULL;
cmOutput.nbContacts = cmOutput.nbPatches = 0;
}
else
{
PxMemCopy(contactPatches, oldPatches, patchSize);
PxMemCopy(contactPoints, oldContacts, contactSize);
if(isMeshType)
PxMemCopy(forceBuffer + cmOutput.nbContacts, oldForces + cmOutput.nbContacts, sizeof(PxU32) * cmOutput.nbContacts);
}
}
else
{
const PxU32 alignedOldSize = (oldSize + 0xf) & 0xfffffff0;
PxU8* data = context.mContactBlockStream.reserve(alignedOldSize + forceSize);
if(forceSize)
forceBuffer = reinterpret_cast<PxReal*>(data + alignedOldSize);
contactPatches = data;
contactPoints = data + cmOutput.nbPatches * sizeof(PxContactPatch);
PxMemCopy(data, oldPatches, oldSize);
if(isMeshType)
PxMemCopy(forceBuffer + cmOutput.nbContacts, oldForces + cmOutput.nbContacts, sizeof(PxU32) * cmOutput.nbContacts);
}
if(forceSize)
PxMemZero(forceBuffer, forceSize);
cmOutput.contactPatches= contactPatches;
cmOutput.contactPoints = contactPoints;
cmOutput.contactForces = forceBuffer;
}
if(cache.mCachedSize)
{
if(cache.isMultiManifold())
{
PX_ASSERT((cache.mCachedSize & 0xF) == 0);
PxU8* newData = context.mNpCacheStreamPair.reserve(cache.mCachedSize);
PX_ASSERT((reinterpret_cast<uintptr_t>(newData)& 0xF) == 0);
PxMemCopy(newData, & cache.getMultipleManifold(), cache.mCachedSize);
cache.setMultiManifold(newData);
}
else if(useContactCache)
{
//Copy cache information as well...
const PxU8* cachedData = cache.mCachedData;
PxU8* newData = context.mNpCacheStreamPair.reserve(PxU32(cache.mCachedSize + 0xf) & 0xfff0);
PxMemCopy(newData, cachedData, cache.mCachedSize);
cache.mCachedData = newData;
}
}
return ret;
}
//ML: isMeshType is used in the GPU codepath. If the collision pair is mesh/heightfield vs primitives, we need to allocate enough memory for the mForceAndIndiceStreamPool in the threadContext.
static bool finishContacts(const PxcNpWorkUnit& input, PxsContactManagerOutput& npOutput, PxcNpThreadContext& threadContext, PxsMaterialInfo* PX_RESTRICT pMaterials, const bool isMeshType, PxU64 contextID)
{
PX_UNUSED(contextID);
LOCAL_PROFILE_ZONE("finishContacts", contextID);
PxContactBuffer& buffer = threadContext.mContactBuffer;
PX_ASSERT((npOutput.statusFlag & PxsContactManagerStatusFlag::eTOUCH_KNOWN) != PxsContactManagerStatusFlag::eTOUCH_KNOWN);
PxU8 statusFlags = PxU16(npOutput.statusFlag & (~PxsContactManagerStatusFlag::eTOUCH_KNOWN));
if(buffer.count)
statusFlags |= PxsContactManagerStatusFlag::eHAS_TOUCH;
else
statusFlags |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
npOutput.nbContacts = PxTo16(buffer.count);
if(!buffer.count)
{
npOutput.statusFlag = statusFlags;
npOutput.nbContacts = 0;
npOutput.nbPatches = 0;
return true;
}
PX_ASSERT(buffer.count);
#if PX_ENABLE_SIM_STATS
threadContext.mNbDiscreteContactPairsWithContacts++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
npOutput.statusFlag = statusFlags;
PxU32 contactForceByteSize = buffer.count * sizeof(PxReal);
//Regardless of the flags, we need to now record the compressed contact stream
PxU16 compressedContactSize;
const bool createReports =
input.flags & PxcNpWorkUnitFlag::eOUTPUT_CONTACTS
|| (input.flags & PxcNpWorkUnitFlag::eFORCE_THRESHOLD);
if((!isMeshType && !createReports))
contactForceByteSize = 0;
bool res = (writeCompressedContact(buffer.contacts, buffer.count, &threadContext, npOutput.nbContacts, npOutput.contactPatches, npOutput.contactPoints, compressedContactSize,
reinterpret_cast<PxReal*&>(npOutput.contactForces), contactForceByteSize, threadContext.mMaterialManager, ((input.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT) != 0),
false, pMaterials, npOutput.nbPatches, 0, NULL, NULL, threadContext.mCreateAveragePoint, threadContext.mContactStreamPool,
threadContext.mPatchStreamPool, threadContext.mForceAndIndiceStreamPool, isMeshType) != 0);
//handle buffer overflow
if(!npOutput.nbContacts)
{
PxU8 thisStatusFlags = PxU16(npOutput.statusFlag & (~PxsContactManagerStatusFlag::eTOUCH_KNOWN));
thisStatusFlags |= PxsContactManagerStatusFlag::eHAS_NO_TOUCH;
npOutput.statusFlag = thisStatusFlags;
npOutput.nbContacts = 0;
npOutput.nbPatches = 0;
#if PX_ENABLE_SIM_STATS
threadContext.mNbDiscreteContactPairsWithContacts--;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
}
return res;
}
template<bool useContactCacheT>
static PX_FORCE_INLINE bool checkContactsMustBeGenerated(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output,
const PxsCachedTransform* cachedTransform0, const PxsCachedTransform* cachedTransform1,
const bool flip, PxGeometryType::Enum type0, PxGeometryType::Enum type1)
{
PX_ASSERT(cachedTransform0->transform.isSane() && cachedTransform1->transform.isSane());
//ML : if user doesn't raise the eDETECT_DISCRETE_CONTACT, we should not generate contacts
if(!(input.flags & PxcNpWorkUnitFlag::eDETECT_DISCRETE_CONTACT))
return false;
if(!(output.statusFlag & PxcNpWorkUnitStatusFlag::eDIRTY_MANAGER) && !(input.flags & PxcNpWorkUnitFlag::eMODIFIABLE_CONTACT))
{
const PxU32 body0Dynamic = PxU32(input.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY0 | PxcNpWorkUnitFlag::eARTICULATION_BODY0 | PxcNpWorkUnitFlag::eSOFT_BODY));
const PxU32 body1Dynamic = PxU32(input.flags & (PxcNpWorkUnitFlag::eDYNAMIC_BODY1 | PxcNpWorkUnitFlag::eARTICULATION_BODY1 | PxcNpWorkUnitFlag::eSOFT_BODY));
const PxU32 active0 = PxU32(body0Dynamic && !cachedTransform0->isFrozen());
const PxU32 active1 = PxU32(body1Dynamic && !cachedTransform1->isFrozen());
if(!(active0 || active1))
{
if(flip)
PxSwap(type0, type1);
const bool useContactCache = useContactCacheT ? context.mContactCache && g_CanUseContactCache[type0][type1] : false;
#if PX_ENABLE_SIM_STATS
if(output.nbContacts)
context.mNbDiscreteContactPairsWithContacts++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
const bool isMeshType = type1 > PxGeometryType::eCONVEXMESH;
copyBuffers(output, cache, context, useContactCache, isMeshType);
return false;
}
}
output.statusFlag &= (~PxcNpWorkUnitStatusFlag::eDIRTY_MANAGER);
const PxReal contactDist0 = context.mContactDistances[input.mTransformCache0];
const PxReal contactDist1 = context.mContactDistances[input.mTransformCache1];
//context.mNarrowPhaseParams.mContactDistance = shape0->contactOffset + shape1->contactOffset;
context.mNarrowPhaseParams.mContactDistance = contactDist0 + contactDist1;
return true;
}
template<bool useLegacyCodepath>
static PX_FORCE_INLINE void discreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
PxGeometryType::Enum type0 = static_cast<PxGeometryType::Enum>(input.geomType0);
PxGeometryType::Enum type1 = static_cast<PxGeometryType::Enum>(input.geomType1);
const bool flip = (type1<type0);
const PxsCachedTransform* cachedTransform0 = &context.mTransformCache->getTransformCache(input.mTransformCache0);
const PxsCachedTransform* cachedTransform1 = &context.mTransformCache->getTransformCache(input.mTransformCache1);
if(!checkContactsMustBeGenerated<useLegacyCodepath>(context, input, cache, output, cachedTransform0, cachedTransform1, flip, type0, type1))
return;
PxsShapeCore* shape0 = const_cast<PxsShapeCore*>(input.shapeCore0);
PxsShapeCore* shape1 = const_cast<PxsShapeCore*>(input.shapeCore1);
if(flip)
{
PxSwap(type0, type1);
PxSwap(shape0, shape1);
PxSwap(cachedTransform0, cachedTransform1);
}
PxsMaterialInfo materialInfo[PxContactBuffer::MAX_CONTACTS];
Gu::MultiplePersistentContactManifold& manifold = context.mTempManifold;
bool isMultiManifold = false;
if(!useLegacyCodepath)
{
if(cache.isMultiManifold())
{
//We are using a multi-manifold. This is cached in a reduced npCache...
isMultiManifold = true;
uintptr_t address = uintptr_t(&cache.getMultipleManifold());
manifold.fromBuffer(reinterpret_cast<PxU8*>(address));
cache.setMultiManifold(&manifold);
}
else if(cache.isManifold())
{
void* address = reinterpret_cast<void*>(&cache.getManifold());
PxPrefetch(address);
PxPrefetch(address, 128);
PxPrefetch(address, 256);
}
}
updateDiscreteContactStats(context, type0, type1);
startContacts(output, context);
const PxTransform32* tm0 = reinterpret_cast<const PxTransform32*>(cachedTransform0);
const PxTransform32* tm1 = reinterpret_cast<const PxTransform32*>(cachedTransform1);
PX_ASSERT(tm0->isSane() && tm1->isSane());
const PxGeometry& contactShape0 = shape0->mGeometry.getGeometry();
const PxGeometry& contactShape1 = shape1->mGeometry.getGeometry();
if(useLegacyCodepath)
{
// PT: many cache misses here...
PxPrefetchLine(shape1, 0); // PT: at least get rid of L2s for shape1
const PxcContactMethod conMethod = g_ContactMethodTable[type0][type1];
PX_ASSERT(conMethod);
const bool useContactCache = context.mContactCache && g_CanUseContactCache[type0][type1];
if(useContactCache)
{
const bool status = PxcCacheLocalContacts(context, cache, *tm0, *tm1, conMethod, contactShape0, contactShape1);
#if PX_ENABLE_SIM_STATS
if(status)
context.mNbDiscreteContactPairsWithCacheHits++;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
PX_UNUSED(status);
#endif
}
else
{
LOCAL_PROFILE_ZONE("conMethod", contextID);
conMethod(contactShape0, contactShape1, *tm0, *tm1, context.mNarrowPhaseParams, cache, context.mContactBuffer, &context.mRenderOutput);
}
}
else
{
LOCAL_PROFILE_ZONE("conMethod", contextID);
const PxcContactMethod conMethod = g_PCMContactMethodTable[type0][type1];
PX_ASSERT(conMethod);
conMethod(contactShape0, contactShape1, *tm0, *tm1, context.mNarrowPhaseParams, cache, context.mContactBuffer, &context.mRenderOutput);
}
if(context.mContactBuffer.count)
{
const PxcGetMaterialMethod materialMethod = g_GetMaterialMethodTable[type0][type1];
if(materialMethod)
{
LOCAL_PROFILE_ZONE("materialMethod", contextID);
materialMethod(shape0, shape1, context, materialInfo);
}
if(flip)
{
LOCAL_PROFILE_ZONE("flipContacts", contextID);
flipContacts(context, materialInfo);
}
}
if(!useLegacyCodepath)
{
if(isMultiManifold)
{
//Store the manifold back...
const PxU32 size = (sizeof(MultiPersistentManifoldHeader) +
manifold.mNumManifolds * sizeof(SingleManifoldHeader) +
manifold.mNumTotalContacts * sizeof(Gu::CachedMeshPersistentContact));
PxU8* buffer = context.mNpCacheStreamPair.reserve(size);
PX_ASSERT((reinterpret_cast<uintptr_t>(buffer)& 0xf) == 0);
manifold.toBuffer(buffer);
cache.setMultiManifold(buffer);
cache.mCachedSize = PxTo16(size);
}
}
const bool isMeshType = type1 > PxGeometryType::eCONVEXMESH;
finishContacts(input, output, context, materialInfo, isMeshType, contextID);
}
void physx::PxcDiscreteNarrowPhase(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
LOCAL_PROFILE_ZONE("PxcDiscreteNarrowPhase", contextID);
discreteNarrowPhase<true>(context, input, cache, output, contextID);
}
void physx::PxcDiscreteNarrowPhasePCM(PxcNpThreadContext& context, const PxcNpWorkUnit& input, Gu::Cache& cache, PxsContactManagerOutput& output, PxU64 contextID)
{
LOCAL_PROFILE_ZONE("PxcDiscreteNarrowPhasePCM", contextID);
discreteNarrowPhase<false>(context, input, cache, output, contextID);
}
| 17,311 | C++ | 35.91258 | 205 | 0.763214 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/src/pipeline/PxcNpContactPrepShared.cpp | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "foundation/PxPreprocessor.h"
#include "PxcNpWorkUnit.h"
#include "PxvDynamics.h"
using namespace physx;
using namespace Gu;
#include "PxsMaterialManager.h"
#include "PxsMaterialCombiner.h"
#include "PxcNpContactPrepShared.h"
#include "foundation/PxAtomic.h"
#include "PxsContactManagerState.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxErrors.h"
using namespace physx;
using namespace aos;
static PX_FORCE_INLINE void copyContactPoint(PxContact* PX_RESTRICT point, const PxContactPoint* PX_RESTRICT cp)
{
// PT: TODO: consider moving "separation" right after "point" in both structures, to copy both at the same time.
// point->contact = cp->point;
const Vec4V contactV = V4LoadA(&cp->point.x); // PT: V4LoadA safe because 'point' is aligned.
V4StoreU(contactV, &point->contact.x);
point->separation = cp->separation;
}
void combineMaterials(const PxsMaterialManager* materialManager, PxU16 origMatIndex0, PxU16 origMatIndex1, PxReal& staticFriction, PxReal& dynamicFriction, PxReal& combinedRestitution, PxU32& materialFlags, PxReal& combinedDamping)
{
const PxsMaterialData& data0 = *materialManager->getMaterial(origMatIndex0);
const PxsMaterialData& data1 = *materialManager->getMaterial(origMatIndex1);
combinedRestitution = PxsCombineRestitution(data0, data1);
combinedDamping = PxMax(data0.damping, data1.damping);
PxsCombineIsotropicFriction(data0, data1, dynamicFriction, staticFriction, materialFlags);
}
struct StridePatch
{
PxU8 startIndex;
PxU8 endIndex;
PxU8 nextIndex;
PxU8 totalCount;
bool isRoot;
};
PxU32 physx::writeCompressedContact(const PxContactPoint* const PX_RESTRICT contactPoints, const PxU32 numContactPoints, PxcNpThreadContext* threadContext,
PxU16& writtenContactCount, PxU8*& outContactPatches, PxU8*& outContactPoints, PxU16& compressedContactSize, PxReal*& outContactForces, PxU32 contactForceByteSize,
const PxsMaterialManager* materialManager, bool hasModifiableContacts, bool forceNoResponse, const PxsMaterialInfo* PX_RESTRICT pMaterial, PxU8& numPatches,
PxU32 additionalHeaderSize, PxsConstraintBlockManager* manager, PxcConstraintBlockStream* blockStream, bool insertAveragePoint,
PxcDataStreamPool* contactStreamPool, PxcDataStreamPool* patchStreamPool, PxcDataStreamPool* forceStreamPool, const bool isMeshType)
{
if(numContactPoints == 0)
{
writtenContactCount = 0;
outContactPatches = NULL;
outContactPoints = NULL;
outContactForces = NULL;
compressedContactSize = 0;
numPatches = 0;
return 0;
}
//Calculate the size of the contact buffer...
PX_ALLOCA(strPatches, StridePatch, numContactPoints);
StridePatch* stridePatches = &strPatches[0];
PxU32 numStrideHeaders = 1;
PxU32 totalUniquePatches = 1;
PxU32 totalContactPoints = numContactPoints;
PxU32 strideStart = 0;
bool root = true;
StridePatch* parentRootPatch = NULL;
{
const PxReal closeNormalThresh = PXC_SAME_NORMAL;
//Go through and tag how many patches we have...
PxVec3 normal = contactPoints[0].normal;
PxU16 mat0 = pMaterial[0].mMaterialIndex0;
PxU16 mat1 = pMaterial[0].mMaterialIndex1;
for(PxU32 a = 1; a < numContactPoints; ++a)
{
if(normal.dot(contactPoints[a].normal) < closeNormalThresh ||
pMaterial[a].mMaterialIndex0 != mat0 || pMaterial[a].mMaterialIndex1 != mat1)
{
StridePatch& patch = stridePatches[numStrideHeaders-1];
patch.startIndex = PxU8(strideStart);
patch.endIndex = PxU8(a);
patch.nextIndex = 0xFF;
patch.totalCount = PxU8(a - strideStart);
patch.isRoot = root;
if(parentRootPatch)
parentRootPatch->totalCount += PxU8(a - strideStart);
root = true;
parentRootPatch = NULL;
for(PxU32 b = 1; b < numStrideHeaders; ++b)
{
StridePatch& thisPatch = stridePatches[b-1];
if(thisPatch.isRoot)
{
PxU32 ind = thisPatch.startIndex;
PxReal dp2 = contactPoints[a].normal.dot(contactPoints[ind].normal);
if(dp2 >= closeNormalThresh && pMaterial[a].mMaterialIndex0 == pMaterial[ind].mMaterialIndex0 &&
pMaterial[a].mMaterialIndex1 == pMaterial[ind].mMaterialIndex1)
{
PxU32 nextInd = b-1;
while(stridePatches[nextInd].nextIndex != 0xFF)
nextInd = stridePatches[nextInd].nextIndex;
stridePatches[nextInd].nextIndex = PxU8(numStrideHeaders);
root = false;
parentRootPatch = &stridePatches[b-1];
break;
}
}
}
normal = contactPoints[a].normal;
mat0 = pMaterial[a].mMaterialIndex0;
mat1 = pMaterial[a].mMaterialIndex1;
totalContactPoints = insertAveragePoint && (a - strideStart) > 1 ? totalContactPoints + 1 : totalContactPoints;
strideStart = a;
numStrideHeaders++;
if(root)
totalUniquePatches++;
}
}
totalContactPoints = insertAveragePoint &&(numContactPoints - strideStart) > 1 ? totalContactPoints + 1 : totalContactPoints;
contactForceByteSize = insertAveragePoint && contactForceByteSize != 0 ? contactForceByteSize + sizeof(PxF32) * (totalContactPoints - numContactPoints) : contactForceByteSize;
}
{
StridePatch& patch = stridePatches[numStrideHeaders-1];
patch.startIndex = PxU8(strideStart);
patch.endIndex = PxU8(numContactPoints);
patch.nextIndex = 0xFF;
patch.totalCount = PxU8(numContactPoints - strideStart);
patch.isRoot = root;
if(parentRootPatch)
parentRootPatch->totalCount += PxU8(numContactPoints - strideStart);
}
numPatches = PxU8(totalUniquePatches);
//Calculate the number of patches/points required
const bool isModifiable = !forceNoResponse && hasModifiableContacts;
const PxU32 patchHeaderSize = sizeof(PxContactPatch) * (isModifiable ? totalContactPoints : totalUniquePatches) + additionalHeaderSize;
const PxU32 pointSize = totalContactPoints * (isModifiable ? sizeof(PxModifiableContact) : sizeof(PxContact));
PxU32 requiredContactSize = pointSize;
PxU32 requiredPatchSize = patchHeaderSize;
PxU32 totalRequiredSize;
PxU8* PX_RESTRICT contactData = NULL;
PxU8* PX_RESTRICT patchData = NULL;
PxReal* PX_RESTRICT forceData = NULL;
PxU32* PX_RESTRICT triangleIndice = NULL;
if(contactStreamPool && !isModifiable && additionalHeaderSize == 0) //If the contacts are modifiable, we **DON'T** allocate them in GPU pinned memory. This will be handled later when they're modified
{
bool isOverflown = false;
PxU32 contactIndex = PxU32(PxAtomicAdd(&contactStreamPool->mSharedDataIndex, PxI32(requiredContactSize)));
if (contactStreamPool->isOverflown())
{
PX_WARN_ONCE("Contact buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
contactData = contactStreamPool->mDataStream + contactStreamPool->mDataStreamSize - contactIndex;
PxU32 patchIndex = PxU32(PxAtomicAdd(&patchStreamPool->mSharedDataIndex, PxI32(requiredPatchSize)));
if (patchStreamPool->isOverflown())
{
PX_WARN_ONCE("Patch buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
patchData = patchStreamPool->mDataStream + patchStreamPool->mDataStreamSize - patchIndex;
if(contactForceByteSize)
{
contactForceByteSize = isMeshType ? contactForceByteSize * 2 : contactForceByteSize;
contactIndex = PxU32(PxAtomicAdd(&forceStreamPool->mSharedDataIndex, PxI32(contactForceByteSize)));
if (forceStreamPool->isOverflown())
{
PX_WARN_ONCE("Force buffer overflow detected, please increase its size in the scene desc!\n");
isOverflown = true;
}
forceData = reinterpret_cast<PxReal*>(forceStreamPool->mDataStream + forceStreamPool->mDataStreamSize - contactIndex);
if (isMeshType)
triangleIndice = reinterpret_cast<PxU32*>(forceData + numContactPoints);
}
totalRequiredSize = requiredContactSize + requiredPatchSize;
if (isOverflown)
{
patchData = NULL;
contactData = NULL;
forceData = NULL;
triangleIndice = NULL;
}
}
else
{
PxU32 alignedRequiredSize = (requiredContactSize + requiredPatchSize + 0xf) & 0xfffffff0;
contactForceByteSize = (isMeshType ? contactForceByteSize * 2 : contactForceByteSize);
PxU32 totalSize = alignedRequiredSize + contactForceByteSize;
PxU8* data = manager ? blockStream->reserve(totalSize, *manager) : threadContext->mContactBlockStream.reserve(totalSize);
patchData = data;
contactData = patchData + requiredPatchSize;
if(contactForceByteSize)
{
forceData = reinterpret_cast<PxReal*>((data + alignedRequiredSize));
if (isMeshType)
triangleIndice = reinterpret_cast<PxU32*>(forceData + numContactPoints);
if(data)
{
PxMemZero(forceData, contactForceByteSize);
}
}
totalRequiredSize = alignedRequiredSize;
}
PxPrefetchLine(patchData);
PxPrefetchLine(contactData);
if(patchData == NULL)
{
writtenContactCount = 0;
outContactPatches = NULL;
outContactPoints = NULL;
outContactForces = NULL;
compressedContactSize = 0;
numPatches = 0;
return 0;
}
#if PX_ENABLE_SIM_STATS
if(threadContext)
{
threadContext->mCompressedCacheSize += totalRequiredSize;
threadContext->mTotalCompressedCacheSize += totalRequiredSize;
}
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
compressedContactSize = PxTo16(totalRequiredSize);
//PxU32 startIndex = 0;
//Extract first material
PxU16 origMatIndex0 = pMaterial[0].mMaterialIndex0;
PxU16 origMatIndex1 = pMaterial[0].mMaterialIndex1;
PxReal staticFriction, dynamicFriction, combinedRestitution, combinedDamping;
PxU32 materialFlags;
combineMaterials(materialManager, origMatIndex0, origMatIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
PxU8* PX_RESTRICT dataPlusOffset = patchData + additionalHeaderSize;
PxContactPatch* PX_RESTRICT patches = reinterpret_cast<PxContactPatch*>(dataPlusOffset);
PxU32* PX_RESTRICT faceIndice = triangleIndice;
outContactPatches = patchData;
outContactPoints = contactData;
outContactForces = forceData;
struct Local
{
static PX_FORCE_INLINE void fillPatch(PxContactPatch* PX_RESTRICT patch, const StridePatch& rootPatch, const PxVec3& normal,
PxU32 currentIndex, PxReal staticFriction_, PxReal dynamicFriction_, PxReal combinedRestitution_, PxReal combinedDamping_,
PxU32 materialFlags_, PxU32 flags, PxU16 matIndex0, PxU16 matIndex1
)
{
patch->mMassModification.linear0 = 1.0f;
patch->mMassModification.linear1 = 1.0f;
patch->mMassModification.angular0 = 1.0f;
patch->mMassModification.angular1 = 1.0f;
PX_ASSERT(PxAbs(normal.magnitude() - 1) < 1e-3f);
patch->normal = normal;
patch->restitution = combinedRestitution_;
patch->dynamicFriction = dynamicFriction_;
patch->staticFriction = staticFriction_;
patch->damping = combinedDamping_;
patch->startContactIndex = PxTo8(currentIndex);
//KS - we could probably compress this further into the header but the complexity might not be worth it
patch->nbContacts = rootPatch.totalCount;
patch->materialFlags = PxU8(materialFlags_);
patch->internalFlags = PxU8(flags);
patch->materialIndex0 = matIndex0;
patch->materialIndex1 = matIndex1;
}
};
if(isModifiable)
{
PxU32 flags = PxU32(isModifiable ? PxContactPatch::eMODIFIABLE : 0) |
(forceNoResponse ? PxContactPatch::eFORCE_NO_RESPONSE : 0) |
(isMeshType ? PxContactPatch::eHAS_FACE_INDICES : 0);
PxU32 currentIndex = 0;
PxModifiableContact* PX_RESTRICT point = reinterpret_cast<PxModifiableContact*>(contactData);
for(PxU32 a = 0; a < numStrideHeaders; ++a)
{
StridePatch& rootPatch = stridePatches[a];
if(rootPatch.isRoot)
{
const PxU32 startIndex = rootPatch.startIndex;
const PxU16 matIndex0 = pMaterial[startIndex].mMaterialIndex0;
const PxU16 matIndex1 = pMaterial[startIndex].mMaterialIndex1;
if(matIndex0 != origMatIndex0 || matIndex1 != origMatIndex1)
{
combineMaterials(materialManager, matIndex0, matIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
origMatIndex0 = matIndex0;
origMatIndex1 = matIndex1;
}
PxContactPatch* PX_RESTRICT patch = patches++;
Local::fillPatch(patch, rootPatch, contactPoints[startIndex].normal, currentIndex, staticFriction, dynamicFriction, combinedRestitution, combinedDamping, materialFlags, flags, matIndex0, matIndex1);
//const PxU32 endIndex = strideHeader[a];
const PxU32 totalCountThisPatch = rootPatch.totalCount;
if(insertAveragePoint && totalCountThisPatch > 1)
{
PxVec3 avgPt(0.0f);
PxF32 avgPen(0.0f);
PxF32 recipCount = 1.0f/(PxF32(rootPatch.totalCount));
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
avgPt += contactPoints[b].point;
avgPen += contactPoints[b].separation;
}
index = p.nextIndex;
}
if (faceIndice)
{
StridePatch& p = stridePatches[index];
*faceIndice = contactPoints[p.startIndex].internalFaceIndex1;
faceIndice++;
}
patch->nbContacts++;
point->contact = avgPt * recipCount;
point->separation = avgPen * recipCount;
point->normal = contactPoints[startIndex].normal;
point->maxImpulse = PX_MAX_REAL;
point->targetVelocity = PxVec3(0.0f);
point->staticFriction = staticFriction;
point->dynamicFriction = dynamicFriction;
point->restitution = combinedRestitution;
point->materialFlags = materialFlags;
point->materialIndex0 = matIndex0;
point->materialIndex1 = matIndex1;
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
copyContactPoint(point, &contactPoints[b]);
point->normal = contactPoints[b].normal;
point->maxImpulse = PX_MAX_REAL;
point->targetVelocity = PxVec3(0.0f);
point->staticFriction = staticFriction;
point->dynamicFriction = dynamicFriction;
point->restitution = combinedRestitution;
point->materialFlags = materialFlags;
point->materialIndex0 = matIndex0;
point->materialIndex1 = matIndex1;
if (faceIndice)
{
*faceIndice = contactPoints[b].internalFaceIndex1;
faceIndice++;
}
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
index = p.nextIndex;
}
}
}
}
else
{
PxU32 flags = PxU32(isMeshType ? PxContactPatch::eHAS_FACE_INDICES : 0);
PxContact* PX_RESTRICT point = reinterpret_cast<PxContact*>(contactData);
PxU32 currentIndex = 0;
{
for(PxU32 a = 0; a < numStrideHeaders; ++a)
{
StridePatch& rootPatch = stridePatches[a];
if(rootPatch.isRoot)
{
const PxU32 startIndex = rootPatch.startIndex;
const PxU16 matIndex0 = pMaterial[startIndex].mMaterialIndex0;
const PxU16 matIndex1 = pMaterial[startIndex].mMaterialIndex1;
if(matIndex0 != origMatIndex0 || matIndex1 != origMatIndex1)
{
combineMaterials(materialManager, matIndex0, matIndex1, staticFriction, dynamicFriction, combinedRestitution, materialFlags, combinedDamping);
origMatIndex0 = matIndex0;
origMatIndex1 = matIndex1;
}
PxContactPatch* PX_RESTRICT patch = patches++;
Local::fillPatch(patch, rootPatch, contactPoints[startIndex].normal, currentIndex, staticFriction, dynamicFriction, combinedRestitution, combinedDamping, materialFlags, flags, matIndex0, matIndex1);
if(insertAveragePoint && (rootPatch.totalCount) > 1)
{
patch->nbContacts++;
PxVec3 avgPt(0.0f);
PxF32 avgPen(0.0f);
PxF32 recipCount = 1.0f/(PxF32(rootPatch.totalCount));
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
avgPt += contactPoints[b].point;
avgPen += contactPoints[b].separation;
}
index = stridePatches[index].nextIndex;
}
if (faceIndice)
{
StridePatch& p = stridePatches[index];
*faceIndice = contactPoints[p.startIndex].internalFaceIndex1;
faceIndice++;
}
point->contact = avgPt * recipCount;
point->separation = avgPen * recipCount;
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
PxU32 index = a;
while(index != 0xFF)
{
StridePatch& p = stridePatches[index];
for(PxU32 b = p.startIndex; b < p.endIndex; ++b)
{
copyContactPoint(point, &contactPoints[b]);
if (faceIndice)
{
*faceIndice = contactPoints[b].internalFaceIndex1;
faceIndice++;
}
point++;
currentIndex++;
PxPrefetchLine(point, 128);
}
index = stridePatches[index].nextIndex;
}
}
}
}
}
writtenContactCount = PxTo16(totalContactPoints);
return totalRequiredSize;
}
| 18,676 | C++ | 33.91028 | 231 | 0.720979 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcMaterialMethodImpl.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_MATERIAL_METHOD_H
#define PXC_MATERIAL_METHOD_H
#include "geometry/PxGeometry.h"
namespace physx
{
struct PxsShapeCore;
struct PxsMaterialInfo;
class PxcNpThreadContext;
#define MATERIAL_METHOD_ARGS \
const PxsShapeCore* shape0, \
const PxsShapeCore* shape1, \
PxcNpThreadContext& pairContext, \
PxsMaterialInfo* materialInfo
#define SINGLE_MATERIAL_METHOD_ARGS \
const PxsShapeCore* shape, \
const PxU32 index, \
PxcNpThreadContext& pairContext, \
PxsMaterialInfo* materialInfo
/*!
Method prototype for fetch material routines
*/
typedef void (*PxcGetMaterialMethod) (MATERIAL_METHOD_ARGS);
typedef void (*PxcGetSingleMaterialMethod) (SINGLE_MATERIAL_METHOD_ARGS);
extern PxcGetMaterialMethod g_GetMaterialMethodTable[][PxGeometryType::eGEOMETRY_COUNT];
extern PxcGetSingleMaterialMethod g_GetSingleMaterialMethodTable[PxGeometryType::eGEOMETRY_COUNT];
}
#endif
| 2,609 | C | 37.382352 | 98 | 0.774243 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpWorkUnit.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_WORK_UNIT_H
#define PXC_NP_WORK_UNIT_H
#include "PxcNpThreadContext.h"
#include "PxcMaterialMethodImpl.h"
#include "PxcNpCache.h"
namespace physx
{
struct PxsRigidCore;
struct PxsShapeCore;
struct PxcNpWorkUnitFlag
{
enum Enum
{
eOUTPUT_CONTACTS = 1 << 0,
eOUTPUT_CONSTRAINTS = 1 << 1,
eDISABLE_STRONG_FRICTION = 1 << 2,
eARTICULATION_BODY0 = 1 << 3,
eARTICULATION_BODY1 = 1 << 4,
eDYNAMIC_BODY0 = 1 << 5,
eDYNAMIC_BODY1 = 1 << 6,
eSOFT_BODY = 1 << 7,
eMODIFIABLE_CONTACT = 1 << 8,
eFORCE_THRESHOLD = 1 << 9,
eDETECT_DISCRETE_CONTACT = 1 << 10,
eHAS_KINEMATIC_ACTOR = 1 << 11,
eDISABLE_RESPONSE = 1 << 12,
eDETECT_CCD_CONTACTS = 1 << 13,
};
};
struct PxcNpWorkUnitStatusFlag
{
enum Enum
{
eHAS_NO_TOUCH = (1 << 0),
eHAS_TOUCH = (1 << 1),
//eHAS_SOLVER_CONSTRAINTS = (1 << 2),
eREQUEST_CONSTRAINTS = (1 << 3),
eHAS_CCD_RETOUCH = (1 << 4), // Marks pairs that are touching at a CCD pass and were touching at discrete collision or at a previous CCD pass already
// but we can not tell whether they lost contact in a pass before. We send them as pure eNOTIFY_TOUCH_CCD events to the
// contact report callback if requested.
eDIRTY_MANAGER = (1 << 5),
eREFRESHED_WITH_TOUCH = (1 << 6),
eTOUCH_KNOWN = eHAS_NO_TOUCH | eHAS_TOUCH // The touch status is known (if narrowphase never ran for a pair then no flag will be set)
};
};
// PT: TODO: fix the inconsistent namings (mXXX) in this class
struct PxcNpWorkUnit
{
const PxsRigidCore* rigidCore0; // INPUT //4 //8
const PxsRigidCore* rigidCore1; // INPUT //8 //16
const PxsShapeCore* shapeCore0; // INPUT //12 //24
const PxsShapeCore* shapeCore1; // INPUT //16 //32
PxU8* ccdContacts; // OUTPUT //20 //40
PxU8* frictionDataPtr; // INOUT //24 //48
PxU16 flags; // INPUT //26 //50
PxU8 frictionPatchCount; // INOUT //27 //51
PxU8 statusFlags; // OUTPUT (see PxcNpWorkUnitStatusFlag) //28 //52
PxU8 dominance0; // INPUT //29 //53
PxU8 dominance1; // INPUT //30 //54
PxU8 geomType0; // INPUT //31 //55
PxU8 geomType1; // INPUT //32 //56
PxU32 index; // INPUT //36 //60
PxReal restDistance; // INPUT //40 //64
PxU32 mTransformCache0; // //44 //68
PxU32 mTransformCache1; // //48 //72
PxU32 mEdgeIndex; //inout the island gen edge index //52 //76
PxU32 mNpIndex; //INPUT //56 //80
PxReal mTorsionalPatchRadius; //60 //84
PxReal mMinTorsionalPatchRadius; //64 //88
PxReal mOffsetSlop; //68 //92
PX_FORCE_INLINE void clearCachedState()
{
frictionDataPtr = NULL;
frictionPatchCount = 0;
ccdContacts = NULL;
}
};
//#if !defined(PX_P64)
//PX_COMPILE_TIME_ASSERT(0 == (sizeof(PxcNpWorkUnit) & 0x0f));
//#endif
#if !defined(PX_P64)
//PX_COMPILE_TIME_ASSERT(sizeof(PxcNpWorkUnit)==128);
#endif
}
#endif
| 4,799 | C | 35.090225 | 153 | 0.656178 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpMemBlockPool.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_MEM_BLOCK_POOL_H
#define PXC_NP_MEM_BLOCK_POOL_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
namespace physx
{
class PxcScratchAllocator;
struct PxcNpMemBlock
{
enum
{
SIZE = 16384
};
PxU8 data[SIZE];
};
typedef PxArray<PxcNpMemBlock*> PxcNpMemBlockArray;
class PxcNpMemBlockPool
{
PX_NOCOPY(PxcNpMemBlockPool)
public:
PxcNpMemBlockPool(PxcScratchAllocator& allocator);
~PxcNpMemBlockPool();
void init(PxU32 initial16KDataBlocks, PxU32 maxBlocks);
void flush();
void setBlockCount(PxU32 count);
PxU32 getUsedBlockCount() const;
PxU32 getMaxUsedBlockCount() const;
PxU32 getPeakConstraintBlockCount() const;
void releaseUnusedBlocks();
PxcNpMemBlock* acquireConstraintBlock();
PxcNpMemBlock* acquireConstraintBlock(PxcNpMemBlockArray& memBlocks);
PxcNpMemBlock* acquireContactBlock();
PxcNpMemBlock* acquireFrictionBlock();
PxcNpMemBlock* acquireNpCacheBlock();
PxU8* acquireExceptionalConstraintMemory(PxU32 size);
void acquireConstraintMemory();
void releaseConstraintMemory();
void releaseConstraintBlocks(PxcNpMemBlockArray& memBlocks);
void releaseContacts();
void swapFrictionStreams();
void swapNpCacheStreams();
void flushUnused();
private:
PxMutex mLock;
PxcNpMemBlockArray mConstraints;
PxcNpMemBlockArray mContacts[2];
PxcNpMemBlockArray mFriction[2];
PxcNpMemBlockArray mNpCache[2];
PxcNpMemBlockArray mScratchBlocks;
PxArray<PxU8*> mExceptionalConstraints;
PxcNpMemBlockArray mUnused;
PxU32 mNpCacheActiveStream;
PxU32 mFrictionActiveStream;
PxU32 mCCDCacheActiveStream;
PxU32 mContactIndex;
PxU32 mAllocatedBlocks;
PxU32 mMaxBlocks;
PxU32 mInitialBlocks;
PxU32 mUsedBlocks;
PxU32 mMaxUsedBlocks;
PxcNpMemBlock* mScratchBlockAddr;
PxU32 mNbScratchBlocks;
PxcScratchAllocator& mScratchAllocator;
PxU32 mPeakConstraintAllocations;
PxU32 mConstraintAllocations;
PxcNpMemBlock* acquire(PxcNpMemBlockArray& trackingArray, PxU32* allocationCount = NULL, PxU32* peakAllocationCount = NULL, bool isScratchAllocation = false);
void release(PxcNpMemBlockArray& deadArray, PxU32* allocationCount = NULL);
};
}
#endif
| 3,940 | C | 32.398305 | 159 | 0.770812 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpContactPrepShared.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_CONTACT_PREP_SHARED_H
#define PXC_NP_CONTACT_PREP_SHARED_H
namespace physx
{
class PxcNpThreadContext;
struct PxsMaterialInfo;
class PxsMaterialManager;
class PxsConstraintBlockManager;
class PxcConstraintBlockStream;
struct PxsContactManagerOutput;
namespace Gu
{
struct ContactPoint;
}
static const PxReal PXC_SAME_NORMAL = 0.999f; //Around 6 degrees
PxU32 writeCompressedContact(const PxContactPoint* const PX_RESTRICT contactPoints, const PxU32 numContactPoints, PxcNpThreadContext* threadContext,
PxU16& writtenContactCount, PxU8*& outContactPatches, PxU8*& outContactPoints, PxU16& compressedContactSize, PxReal*& contactForces, PxU32 contactForceByteSize,
const PxsMaterialManager* materialManager, bool hasModifiableContacts, bool forceNoResponse, const PxsMaterialInfo* PX_RESTRICT pMaterial, PxU8& numPatches,
PxU32 additionalHeaderSize = 0, PxsConstraintBlockManager* manager = NULL, PxcConstraintBlockStream* blockStream = NULL, bool insertAveragePoint = false,
PxcDataStreamPool* pool = NULL, PxcDataStreamPool* patchStreamPool = NULL, PxcDataStreamPool* forcePool = NULL, const bool isMeshType = false);
}
#endif
| 2,879 | C | 49.526315 | 168 | 0.783258 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcConstraintBlockStream.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_CONSTRAINT_BLOCK_POOL_H
#define PXC_CONSTRAINT_BLOCK_POOL_H
#include "PxvConfig.h"
#include "foundation/PxArray.h"
#include "foundation/PxMutex.h"
#include "PxcNpMemBlockPool.h"
namespace physx
{
class PxsConstraintBlockManager
{
public:
PxsConstraintBlockManager(PxcNpMemBlockPool & blockPool):
mBlockPool(blockPool)
{
}
PX_FORCE_INLINE void reset()
{
mBlockPool.releaseConstraintBlocks(mTrackingArray);
}
PxcNpMemBlockArray mTrackingArray;
PxcNpMemBlockPool& mBlockPool;
private:
PxsConstraintBlockManager& operator=(const PxsConstraintBlockManager&);
};
class PxcConstraintBlockStream
{
PX_NOCOPY(PxcConstraintBlockStream)
public:
PxcConstraintBlockStream(PxcNpMemBlockPool & blockPool) :
mBlockPool (blockPool),
mBlock (NULL),
mUsed (0)
{
}
PX_FORCE_INLINE PxU8* reserve(PxU32 size, PxsConstraintBlockManager& manager)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
return mBlockPool.acquireExceptionalConstraintMemory(size);
if(mBlock == NULL || size+mUsed>PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireConstraintBlock(manager.mTrackingArray);
PX_ASSERT(0==mBlock || mBlock->data == reinterpret_cast<PxU8*>(mBlock));
mUsed = size;
return reinterpret_cast<PxU8*>(mBlock);
}
PX_ASSERT(mBlock && mBlock->data == reinterpret_cast<PxU8*>(mBlock));
PxU8* PX_RESTRICT result = mBlock->data+mUsed;
mUsed += size;
return result;
}
PX_FORCE_INLINE void reset()
{
mBlock = NULL;
mUsed = 0;
}
PX_FORCE_INLINE PxcNpMemBlockPool& getMemBlockPool() { return mBlockPool; }
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock; // current constraint block
PxU32 mUsed; // number of bytes used in constraint block
//Tracking peak allocations
PxU32 mPeakUsed;
};
class PxcContactBlockStream
{
PX_NOCOPY(PxcContactBlockStream)
public:
PxcContactBlockStream(PxcNpMemBlockPool & blockPool):
mBlockPool(blockPool),
mBlock(NULL),
mUsed(0)
{
}
PX_FORCE_INLINE PxU8* reserve(PxU32 size)
{
size = (size+15)&~15;
if(size>PxcNpMemBlock::SIZE)
return mBlockPool.acquireExceptionalConstraintMemory(size);
PX_ASSERT(size <= PxcNpMemBlock::SIZE);
if(mBlock == NULL || size+mUsed>PxcNpMemBlock::SIZE)
{
mBlock = mBlockPool.acquireContactBlock();
PX_ASSERT(0==mBlock || mBlock->data == reinterpret_cast<PxU8*>(mBlock));
mUsed = size;
return reinterpret_cast<PxU8*>(mBlock);
}
PX_ASSERT(mBlock && mBlock->data == reinterpret_cast<PxU8*>(mBlock));
PxU8* PX_RESTRICT result = mBlock->data+mUsed;
mUsed += size;
return result;
}
PX_FORCE_INLINE void reset()
{
mBlock = NULL;
mUsed = 0;
}
PX_FORCE_INLINE PxcNpMemBlockPool& getMemBlockPool() { return mBlockPool; }
private:
PxcNpMemBlockPool& mBlockPool;
PxcNpMemBlock* mBlock; // current constraint block
PxU32 mUsed; // number of bytes used in constraint block
};
}
#endif
| 4,995 | C | 31.232258 | 84 | 0.682082 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_CACHE_H
#define PXC_NP_CACHE_H
#include "foundation/PxMemory.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxPool.h"
#include "foundation/PxUtilities.h"
#include "PxcNpCacheStreamPair.h"
#include "GuContactMethodImpl.h"
namespace physx
{
template <typename T>
void PxcNpCacheWrite(PxcNpCacheStreamPair& streams,
Gu::Cache& cache,
const T& payload,
PxU32 bytes,
const PxU8* data)
{
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
cache.mCachedSize = PxTo16((payloadSize + 4 + bytes + 0xF)&~0xF);
PxU8* ls = streams.reserve(cache.mCachedSize);
cache.mCachedData = ls;
if(ls==NULL || (reinterpret_cast<PxU8*>(-1))==ls)
{
if(ls==NULL)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for narrow phase. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
return;
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in narrowphase. "
"Either accept dropped contacts or simplify collision geometry.");
cache.mCachedData = NULL;
ls = NULL;
return;
}
}
*reinterpret_cast<T*>(ls) = payload;
*reinterpret_cast<PxU32*>(ls+payloadSize) = bytes;
if(data)
PxMemCopy(ls+payloadSize+sizeof(PxU32), data, bytes);
}
template <typename T>
PxU8* PxcNpCacheWriteInitiate(PxcNpCacheStreamPair& streams, Gu::Cache& cache, const T& payload, PxU32 bytes)
{
PX_UNUSED(payload);
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
cache.mCachedSize = PxTo16((payloadSize + 4 + bytes + 0xF)&~0xF);
PxU8* ls = streams.reserve(cache.mCachedSize);
cache.mCachedData = ls;
if(NULL==ls || reinterpret_cast<PxU8*>(-1)==ls)
{
if(NULL==ls)
{
PX_WARN_ONCE(
"Reached limit set by PxSceneDesc::maxNbContactDataBlocks - ran out of buffer space for narrow phase. "
"Either accept dropped contacts or increase buffer size allocated for narrow phase by increasing PxSceneDesc::maxNbContactDataBlocks.");
}
else
{
PX_WARN_ONCE(
"Attempting to allocate more than 16K of contact data for a single contact pair in narrowphase. "
"Either accept dropped contacts or simplify collision geometry.");
cache.mCachedData = NULL;
ls = NULL;
}
}
return ls;
}
template <typename T>
PX_FORCE_INLINE void PxcNpCacheWriteFinalize(PxU8* ls, const T& payload, PxU32 bytes, const PxU8* data)
{
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
*reinterpret_cast<T*>(ls) = payload;
*reinterpret_cast<PxU32*>(ls+payloadSize) = bytes;
if(data)
PxMemCopy(ls+payloadSize+sizeof(PxU32), data, bytes);
}
template <typename T>
PX_FORCE_INLINE PxU8* PxcNpCacheRead(Gu::Cache& cache, T*& payload)
{
PxU8* ls = cache.mCachedData;
payload = reinterpret_cast<T*>(ls);
const PxU32 payloadSize = (sizeof(T)+3)&~3;
return reinterpret_cast<PxU8*>(ls+payloadSize+sizeof(PxU32));
}
template <typename T>
const PxU8* PxcNpCacheRead2(Gu::Cache& cache, T& payload, PxU32& bytes)
{
const PxU8* ls = cache.mCachedData;
if(ls==NULL)
{
bytes = 0;
return NULL;
}
const PxU32 payloadSize = (sizeof(payload)+3)&~3;
payload = *reinterpret_cast<const T*>(ls);
bytes = *reinterpret_cast<const PxU32*>(ls+payloadSize);
PX_ASSERT(cache.mCachedSize == ((payloadSize + 4 + bytes+0xF)&~0xF));
return reinterpret_cast<const PxU8*>(ls+payloadSize+sizeof(PxU32));
}
}
#endif
| 5,161 | C | 32.738562 | 140 | 0.728347 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/pipeline/PxcNpThreadContext.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_NP_THREAD_CONTEXT_H
#define PXC_NP_THREAD_CONTEXT_H
#include "geometry/PxGeometry.h"
#include "geomutils/PxContactBuffer.h"
#include "common/PxRenderOutput.h"
#include "CmRenderBuffer.h"
#include "PxvConfig.h"
#include "CmScaling.h"
#include "PxcNpCacheStreamPair.h"
#include "PxcConstraintBlockStream.h"
#include "PxcThreadCoherentCache.h"
#include "PxcScratchAllocator.h"
#include "foundation/PxBitMap.h"
#include "../pcm/GuPersistentContactManifold.h"
#include "../contact/GuContactMethodImpl.h"
namespace physx
{
class PxsTransformCache;
class PxsMaterialManager;
namespace Sc
{
class BodySim;
}
/*!
Per-thread context used by contact generation routines.
*/
struct PxcDataStreamPool
{
PxU8* mDataStream;
PxI32 mSharedDataIndex;
PxU32 mDataStreamSize;
PxU32 mSharedDataIndexGPU;
bool isOverflown() const
{
//FD: my expectaton is that reading those variables is atomic, shared indices are non-decreasing,
//so we can only get a false overflow alert because of concurrency issues, which is not a big deal as it means
//it did overflow a bit later
return (mSharedDataIndex + mSharedDataIndexGPU) > mDataStreamSize;
}
};
struct PxcNpContext
{
private:
PX_NOCOPY(PxcNpContext)
public:
PxcNpContext() :
mNpMemBlockPool (mScratchAllocator),
mMeshContactMargin (0.0f),
mToleranceLength (0.0f),
mContactStreamPool (NULL),
mPatchStreamPool (NULL),
mForceAndIndiceStreamPool(NULL),
mMaterialManager (NULL)
{
}
PxcScratchAllocator mScratchAllocator;
PxcNpMemBlockPool mNpMemBlockPool;
PxReal mMeshContactMargin;
PxReal mToleranceLength;
Cm::RenderBuffer mRenderBuffer;
PxcDataStreamPool* mContactStreamPool;
PxcDataStreamPool* mPatchStreamPool;
PxcDataStreamPool* mForceAndIndiceStreamPool;
PxcDataStreamPool* mConstraintWriteBackStreamPool;
PxsMaterialManager* mMaterialManager;
PX_FORCE_INLINE PxReal getToleranceLength() const { return mToleranceLength; }
PX_FORCE_INLINE void setToleranceLength(PxReal x) { mToleranceLength = x; }
PX_FORCE_INLINE PxReal getMeshContactMargin() const { return mMeshContactMargin; }
PX_FORCE_INLINE void setMeshContactMargin(PxReal x) { mMeshContactMargin = x; }
PX_FORCE_INLINE PxcNpMemBlockPool& getNpMemBlockPool() { return mNpMemBlockPool; }
PX_FORCE_INLINE const PxcNpMemBlockPool& getNpMemBlockPool() const { return mNpMemBlockPool; }
PX_FORCE_INLINE void setMaterialManager(PxsMaterialManager* m){ mMaterialManager = m; }
PX_FORCE_INLINE PxsMaterialManager* getMaterialManager() const { return mMaterialManager; }
};
class PxcNpThreadContext : public PxcThreadCoherentCache<PxcNpThreadContext, PxcNpContext>::EntryBase
{
PX_NOCOPY(PxcNpThreadContext)
public:
PxcNpThreadContext(PxcNpContext* params);
~PxcNpThreadContext();
#if PX_ENABLE_SIM_STATS
void clearStats();
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PX_FORCE_INLINE void addLocalNewTouchCount(PxU32 newTouchCMCount) { mLocalNewTouchCount += newTouchCMCount; }
PX_FORCE_INLINE void addLocalLostTouchCount(PxU32 lostTouchCMCount) { mLocalLostTouchCount += lostTouchCMCount; }
PX_FORCE_INLINE PxU32 getLocalNewTouchCount() const { return mLocalNewTouchCount; }
PX_FORCE_INLINE PxU32 getLocalLostTouchCount() const { return mLocalLostTouchCount; }
PX_FORCE_INLINE PxBitMap& getLocalChangeTouch() { return mLocalChangeTouch; }
void reset(PxU32 cmCount);
// debugging
PxRenderOutput mRenderOutput;
// dsequeira: Need to think about this block pool allocation a bit more. Ideally we'd be
// taking blocks from a single pool, except that we want to be able to selectively reclaim
// blocks if the user needs to defragment, depending on which artifacts they're willing
// to tolerate, such that the blocks we don't reclaim are contiguous.
#if PX_ENABLE_SIM_STATS
PxU32 mDiscreteContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 mModifiedContactPairs [PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxcContactBlockStream mContactBlockStream; // constraint block pool
PxcNpCacheStreamPair mNpCacheStreamPair; // narrow phase pairwise data cache
// Everything below here is scratch state. Most of it can even overlap.
// temporary contact buffer
PxContactBuffer mContactBuffer;
PX_ALIGN(16, Gu::MultiplePersistentContactManifold mTempManifold);
Gu::NarrowPhaseParams mNarrowPhaseParams;
// DS: this stuff got moved here from the PxcNpPairContext. As Pierre says:
////////// PT: those members shouldn't be there in the end, it's not necessary
PxArray<Sc::BodySim*> mBodySimPool;
PxsTransformCache* mTransformCache;
const PxReal* mContactDistances;
bool mPCM;
bool mContactCache;
bool mCreateAveragePoint; // flag to enforce whether we create average points
#if PX_ENABLE_SIM_STATS
PxU32 mCompressedCacheSize;
PxU32 mNbDiscreteContactPairsWithCacheHits;
PxU32 mNbDiscreteContactPairsWithContacts;
#else
PX_CATCH_UNDEFINED_ENABLE_SIM_STATS
#endif
PxReal mDt; // AP: still needed for ccd
PxU32 mCCDPass;
PxU32 mCCDFaceIndex;
PxU32 mMaxPatches;
//PxU32 mTotalContactCount;
PxU32 mTotalCompressedCacheSize;
//PxU32 mTotalPatchCount;
PxcDataStreamPool* mContactStreamPool;
PxcDataStreamPool* mPatchStreamPool;
PxcDataStreamPool* mForceAndIndiceStreamPool; //this stream is used to store the force buffer and triangle index if we are performing mesh/heightfield contact gen
PxcDataStreamPool* mConstraintWriteBackStreamPool;
PxsMaterialManager* mMaterialManager;
private:
// change touch handling.
PxBitMap mLocalChangeTouch;
PxU32 mLocalNewTouchCount;
PxU32 mLocalLostTouchCount;
};
}
#endif
| 7,962 | C | 38.034314 | 169 | 0.72846 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/utils/PxcScratchAllocator.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_SCRATCH_ALLOCATOR_H
#define PXC_SCRATCH_ALLOCATOR_H
#include "foundation/PxAssert.h"
#include "PxvConfig.h"
#include "foundation/PxMutex.h"
#include "foundation/PxArray.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxUserAllocated.h"
namespace physx
{
class PxcScratchAllocator : public PxUserAllocated
{
PX_NOCOPY(PxcScratchAllocator)
public:
PxcScratchAllocator() : mStack("PxcScratchAllocator"), mStart(NULL), mSize(0)
{
mStack.reserve(64);
mStack.pushBack(0);
}
void setBlock(void* addr, PxU32 size)
{
PX_ASSERT(!(size&15));
// if the stack is not empty then some scratch memory was not freed on the previous frame. That's
// likely indicative of a problem, because when the scratch block is too small the memory will have
// come from the heap
PX_ASSERT(mStack.size()==1);
mStack.popBack();
mStart = reinterpret_cast<PxU8*>(addr);
mSize = size;
mStack.pushBack(mStart + size);
}
void* allocAll(PxU32& size)
{
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>0);
size = PxU32(mStack.back()-mStart);
if(size==0)
return NULL;
mStack.pushBack(mStart);
return mStart;
}
void* alloc(PxU32 requestedSize, bool fallBackToHeap = false)
{
requestedSize = (requestedSize+15)&~15;
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>=1);
PxU8* top = mStack.back();
if(top - mStart >= ptrdiff_t(requestedSize))
{
PxU8* addr = top - requestedSize;
mStack.pushBack(addr);
return addr;
}
if(!fallBackToHeap)
return NULL;
return PX_ALLOC(requestedSize, "Scratch Block Fallback");
}
void free(void* addr)
{
PX_ASSERT(addr!=NULL);
if(!isScratchAddr(addr))
{
PX_FREE(addr);
return;
}
PxMutex::ScopedLock lock(mLock);
PX_ASSERT(mStack.size()>1);
PxU32 i=mStack.size()-1;
while(mStack[i]<addr)
i--;
PX_ASSERT(mStack[i]==addr);
mStack.remove(i);
}
bool isScratchAddr(void* addr) const
{
PxU8* a = reinterpret_cast<PxU8*>(addr);
return a>= mStart && a<mStart+mSize;
}
private:
PxMutex mLock;
PxArray<PxU8*> mStack;
PxU8* mStart;
PxU32 mSize;
};
}
#endif
| 3,831 | C | 26.768116 | 101 | 0.719394 |
NVIDIA-Omniverse/PhysX/physx/source/lowlevel/common/include/utils/PxcThreadCoherentCache.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PXC_THREAD_COHERENT_CACHE_H
#define PXC_THREAD_COHERENT_CACHE_H
#include "foundation/PxMutex.h"
#include "foundation/PxAllocator.h"
#include "foundation/PxSList.h"
namespace physx
{
class PxsContext;
/*!
Controls a pool of large objects which must be thread safe.
Tries to return the object most recently used by the thread(for better cache coherancy).
Assumes the object has a default contructor.
(Note the semantics are different to a pool because we dont want to construct/destroy each time
an object is requested, which may be expensive).
TODO: add thread coherancy.
*/
template<class T, class Params>
class PxcThreadCoherentCache : public PxAlignedAllocator<16, PxReflectionAllocator<T> >
{
typedef PxAlignedAllocator<16, PxReflectionAllocator<T> > Allocator;
PX_NOCOPY(PxcThreadCoherentCache)
public:
typedef PxSListEntry EntryBase;
PX_INLINE PxcThreadCoherentCache(Params* params, const Allocator& alloc = Allocator()) : Allocator(alloc), mParams(params)
{
}
PX_INLINE ~PxcThreadCoherentCache()
{
T* np = static_cast<T*>(root.pop());
while(np!=NULL)
{
np->~T();
Allocator::deallocate(np);
np = static_cast<T*>(root.pop());
}
}
PX_INLINE T* get()
{
T* rv = static_cast<T*>(root.pop());
if(rv==NULL)
{
rv = reinterpret_cast<T*>(Allocator::allocate(sizeof(T), PX_FL));
PX_PLACEMENT_NEW(rv, T(mParams));
}
return rv;
}
PX_INLINE void put(T* item)
{
root.push(*item);
}
private:
PxSList root;
Params* mParams;
template<class T2, class P2>
friend class PxcThreadCoherentCacheIterator;
};
/*!
Used to iterate over all objects controlled by the cache.
Note: The iterator flushes the cache(extracts all items on construction and adds them back on
destruction so we can iterate the list in a safe manner).
*/
template<class T, class Params>
class PxcThreadCoherentCacheIterator
{
public:
PxcThreadCoherentCacheIterator(PxcThreadCoherentCache<T, Params>& cache) : mCache(cache)
{
mNext = cache.root.flush();
mFirst = mNext;
}
~PxcThreadCoherentCacheIterator()
{
PxSListEntry* np = mFirst;
while(np != NULL)
{
PxSListEntry* npNext = np->next();
mCache.root.push(*np);
np = npNext;
}
}
PX_INLINE T* getNext()
{
if(mNext == NULL)
return NULL;
T* rv = static_cast<T*>(mNext);
mNext = mNext->next();
return rv;
}
private:
PxcThreadCoherentCacheIterator<T, Params>& operator=(const PxcThreadCoherentCacheIterator<T, Params>&);
PxcThreadCoherentCache<T, Params> &mCache;
PxSListEntry* mNext;
PxSListEntry* mFirst;
};
}
#endif
| 4,247 | C | 27.510067 | 123 | 0.73652 |
NVIDIA-Omniverse/PhysX/physx/include/PxSimulationEventCallback.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SIMULATION_EVENT_CALLBACK_H
#define PX_SIMULATION_EVENT_CALLBACK_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "foundation/PxMemory.h"
#include "PxPhysXConfig.h"
#include "PxFiltering.h"
#include "PxContact.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxActor;
class PxRigidActor;
class PxRigidBody;
class PxConstraint;
/**
\brief Extra data item types for contact pairs.
@see PxContactPairExtraDataItem.type
*/
struct PxContactPairExtraDataType
{
enum Enum
{
ePRE_SOLVER_VELOCITY, //!< see #PxContactPairVelocity
ePOST_SOLVER_VELOCITY, //!< see #PxContactPairVelocity
eCONTACT_EVENT_POSE, //!< see #PxContactPairPose
eCONTACT_PAIR_INDEX //!< see #PxContactPairIndex
};
};
/**
\brief Base class for items in the extra data stream of contact pairs
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairExtraDataItem() {}
/**
\brief The type of the extra data stream item
*/
PxU8 type;
};
/**
\brief Velocities of the contact pair rigid bodies
This struct is shared by multiple types of extra data items. The #type field allows to distinguish between them:
\li PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY: see #PxPairFlag::ePRE_SOLVER_VELOCITY
\li PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY: see #PxPairFlag::ePOST_SOLVER_VELOCITY
\note For static rigid bodies, the velocities will be set to zero.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairVelocity : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairVelocity() {}
/**
\brief The linear velocity of the rigid bodies
*/
PxVec3 linearVelocity[2];
/**
\brief The angular velocity of the rigid bodies
*/
PxVec3 angularVelocity[2];
};
/**
\brief World space actor poses of the contact pair rigid bodies
@see PxContactPairHeader.extraDataStream PxPairFlag::eCONTACT_EVENT_POSE
*/
struct PxContactPairPose : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairPose() {}
/**
\brief The world space pose of the rigid bodies
*/
PxTransform globalPose[2];
};
/**
\brief Marker for the beginning of a new item set in the extra data stream.
If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same
object multiple times. Also, different shapes of the same actor might gain and lose contact with an other
object over multiple passes. This marker allows to separate the extra data items for each collision case, as well as
distinguish the shape pair reports of different CCD passes.
Example:
Let us assume that an actor a0 with shapes s0_0 and s0_1 hits another actor a1 with shape s1.
First s0_0 will hit s1, then a0 will slightly rotate and s0_1 will hit s1 while s0_0 will lose contact with s1.
Furthermore, let us say that contact event pose information is requested as extra data.
The extra data stream will look like this:
PxContactPairIndexA | PxContactPairPoseA | PxContactPairIndexB | PxContactPairPoseB
The corresponding array of PxContactPair events (see #PxSimulationEventCallback.onContact()) will look like this:
PxContactPair(touch_found: s0_0, s1) | PxContactPair(touch_lost: s0_0, s1) | PxContactPair(touch_found: s0_1, s1)
The #index of PxContactPairIndexA will point to the first entry in the PxContactPair array, for PxContactPairIndexB,
#index will point to the third entry.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairIndex : public PxContactPairExtraDataItem
{
public:
PX_FORCE_INLINE PxContactPairIndex() {}
/**
\brief The next item set in the extra data stream refers to the contact pairs starting at #index in the reported PxContactPair array.
*/
PxU16 index;
};
/**
\brief A class to iterate over a contact pair extra data stream.
@see PxContactPairHeader.extraDataStream
*/
struct PxContactPairExtraDataIterator
{
/**
\brief Constructor
\param[in] stream Pointer to the start of the stream.
\param[in] size Size of the stream in bytes.
*/
PX_FORCE_INLINE PxContactPairExtraDataIterator(const PxU8* stream, PxU32 size)
: currPtr(stream), endPtr(stream + size), contactPairIndex(0)
{
clearDataPtrs();
}
/**
\brief Advances the iterator to next set of extra data items.
The contact pair extra data stream contains sets of items as requested by the corresponding #PxPairFlag flags
#PxPairFlag::ePRE_SOLVER_VELOCITY, #PxPairFlag::ePOST_SOLVER_VELOCITY, #PxPairFlag::eCONTACT_EVENT_POSE. A set can contain one
item of each plus the PxContactPairIndex item. This method parses the stream and points the iterator
member variables to the corresponding items of the current set, if they are available. If CCD is not enabled,
you should only get one set of items. If CCD with multiple passes is enabled, you might get more than one item
set.
\note Even though contact pair extra data is requested per shape pair, you will not get an item set per shape pair
but one per actor pair. If, for example, an actor has two shapes and both collide with another actor, then
there will only be one item set (since it applies to both shape pairs).
\return True if there was another set of extra data items in the stream, else false.
@see PxContactPairVelocity PxContactPairPose PxContactPairIndex
*/
PX_INLINE bool nextItemSet()
{
clearDataPtrs();
bool foundEntry = false;
bool endOfItemSet = false;
while ((currPtr < endPtr) && (!endOfItemSet))
{
const PxContactPairExtraDataItem* edItem = reinterpret_cast<const PxContactPairExtraDataItem*>(currPtr);
PxU8 type = edItem->type;
switch(type)
{
case PxContactPairExtraDataType::ePRE_SOLVER_VELOCITY:
{
PX_ASSERT(!preSolverVelocity);
preSolverVelocity = static_cast<const PxContactPairVelocity*>(edItem);
currPtr += sizeof(PxContactPairVelocity);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::ePOST_SOLVER_VELOCITY:
{
postSolverVelocity = static_cast<const PxContactPairVelocity*>(edItem);
currPtr += sizeof(PxContactPairVelocity);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::eCONTACT_EVENT_POSE:
{
eventPose = static_cast<const PxContactPairPose*>(edItem);
currPtr += sizeof(PxContactPairPose);
foundEntry = true;
}
break;
case PxContactPairExtraDataType::eCONTACT_PAIR_INDEX:
{
if (!foundEntry)
{
contactPairIndex = static_cast<const PxContactPairIndex*>(edItem)->index;
currPtr += sizeof(PxContactPairIndex);
foundEntry = true;
}
else
endOfItemSet = true;
}
break;
default:
return foundEntry;
}
}
return foundEntry;
}
private:
/**
\brief Internal helper
*/
PX_FORCE_INLINE void clearDataPtrs()
{
preSolverVelocity = NULL;
postSolverVelocity = NULL;
eventPose = NULL;
}
public:
/**
\brief Current pointer in the stream.
*/
const PxU8* currPtr;
/**
\brief Pointer to the end of the stream.
*/
const PxU8* endPtr;
/**
\brief Pointer to the current pre solver velocity item in the stream. NULL if there is none.
@see PxContactPairVelocity
*/
const PxContactPairVelocity* preSolverVelocity;
/**
\brief Pointer to the current post solver velocity item in the stream. NULL if there is none.
@see PxContactPairVelocity
*/
const PxContactPairVelocity* postSolverVelocity;
/**
\brief Pointer to the current contact event pose item in the stream. NULL if there is none.
@see PxContactPairPose
*/
const PxContactPairPose* eventPose;
/**
\brief The contact pair index of the current item set in the stream.
@see PxContactPairIndex
*/
PxU32 contactPairIndex;
};
/**
\brief Collection of flags providing information on contact report pairs.
@see PxContactPairHeader
*/
struct PxContactPairHeaderFlag
{
enum Enum
{
eREMOVED_ACTOR_0 = (1<<0), //!< The actor with index 0 has been removed from the scene.
eREMOVED_ACTOR_1 = (1<<1) //!< The actor with index 1 has been removed from the scene.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxContactPairHeaderFlag.
@see PxContactPairHeaderFlag
*/
typedef PxFlags<PxContactPairHeaderFlag::Enum, PxU16> PxContactPairHeaderFlags;
PX_FLAGS_OPERATORS(PxContactPairHeaderFlag::Enum, PxU16)
/**
\brief An Instance of this class is passed to PxSimulationEventCallback.onContact().
@see PxSimulationEventCallback.onContact()
*/
struct PxContactPairHeader
{
public:
PX_INLINE PxContactPairHeader() {}
/**
\brief The two actors of the notification shape pairs.
\note The actor pointers might reference deleted actors. This will be the case if PxPairFlag::eNOTIFY_TOUCH_LOST
or PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved actors
gets deleted or removed from the scene. Check the #flags member to see whether that is the case.
Do not dereference a pointer to a deleted actor. The pointer to a deleted actor is only provided
such that user data structures which might depend on the pointer value can be updated.
@see PxActor
*/
PxActor* actors[2];
/**
\brief Stream containing extra data as requested in the PxPairFlag flags of the simulation filter.
This pointer is only valid if any kind of extra data information has been requested for the contact report pair (see #PxPairFlag::ePOST_SOLVER_VELOCITY etc.),
else it will be NULL.
@see PxPairFlag
*/
const PxU8* extraDataStream;
/**
\brief Size of the extra data stream [bytes]
*/
PxU16 extraDataStreamSize;
/**
\brief Additional information on the contact report pair.
@see PxContactPairHeaderFlag
*/
PxContactPairHeaderFlags flags;
/**
\brief pointer to the contact pairs
*/
const struct PxContactPair* pairs;
/**
\brief number of contact pairs
*/
PxU32 nbPairs;
};
/**
\brief Collection of flags providing information on contact report pairs.
@see PxContactPair
*/
struct PxContactPairFlag
{
enum Enum
{
/**
\brief The shape with index 0 has been removed from the actor/scene.
*/
eREMOVED_SHAPE_0 = (1<<0),
/**
\brief The shape with index 1 has been removed from the actor/scene.
*/
eREMOVED_SHAPE_1 = (1<<1),
/**
\brief First actor pair contact.
The provided shape pair marks the first contact between the two actors, no other shape pair has been touching prior to the current simulation frame.
\note: This info is only available if #PxPairFlag::eNOTIFY_TOUCH_FOUND has been declared for the pair.
*/
eACTOR_PAIR_HAS_FIRST_TOUCH = (1<<2),
/**
\brief All contact between the actor pair was lost.
All contact between the two actors has been lost, no shape pairs remain touching after the current simulation frame.
*/
eACTOR_PAIR_LOST_TOUCH = (1<<3),
/**
\brief Internal flag, used by #PxContactPair.extractContacts()
The applied contact impulses are provided for every contact point.
This is the case if #PxPairFlag::eSOLVE_CONTACT has been set for the pair.
*/
eINTERNAL_HAS_IMPULSES = (1<<4),
/**
\brief Internal flag, used by #PxContactPair.extractContacts()
The provided contact point information is flipped with regards to the shapes of the contact pair. This mainly concerns the order of the internal triangle indices.
*/
eINTERNAL_CONTACTS_ARE_FLIPPED = (1<<5)
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxContactPairFlag.
@see PxContactPairFlag
*/
typedef PxFlags<PxContactPairFlag::Enum, PxU16> PxContactPairFlags;
PX_FLAGS_OPERATORS(PxContactPairFlag::Enum, PxU16)
/**
\brief A contact point as used by contact notification
*/
struct PxContactPairPoint
{
/**
\brief The position of the contact point between the shapes, in world space.
*/
PxVec3 position;
/**
\brief The separation of the shapes at the contact point. A negative separation denotes a penetration.
*/
PxReal separation;
/**
\brief The normal of the contacting surfaces at the contact point. The normal direction points from the second shape to the first shape.
*/
PxVec3 normal;
/**
\brief The surface index of shape 0 at the contact point. This is used to identify the surface material.
*/
PxU32 internalFaceIndex0;
/**
\brief The impulse applied at the contact point, in world space. Divide by the simulation time step to get a force value.
*/
PxVec3 impulse;
/**
\brief The surface index of shape 1 at the contact point. This is used to identify the surface material.
*/
PxU32 internalFaceIndex1;
};
/**
\brief Contact report pair information.
Instances of this class are passed to PxSimulationEventCallback.onContact(). If contact reports have been requested for a pair of shapes (see #PxPairFlag),
then the corresponding contact information will be provided through this structure.
@see PxSimulationEventCallback.onContact()
*/
struct PxContactPair
{
public:
PX_INLINE PxContactPair() {}
/**
\brief The two shapes that make up the pair.
\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST
or #PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST events were requested for the pair and one of the involved shapes
gets deleted. Check the #flags member to see whether that is the case. Do not dereference a pointer to a
deleted shape. The pointer to a deleted shape is only provided such that user data structures which might
depend on the pointer value can be updated.
@see PxShape
*/
PxShape* shapes[2];
/**
\brief Pointer to first patch header in contact stream containing contact patch data
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxU8* contactPatches;
/**
\brief Pointer to first contact point in contact stream containing contact data
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxU8* contactPoints;
/**
\brief Buffer containing applied impulse data.
This pointer is only valid if contact point information has been requested for the contact report pair (see #PxPairFlag::eNOTIFY_CONTACT_POINTS).
Use #extractContacts() as a reference for the data layout of the stream.
*/
const PxReal* contactImpulses;
/**
\brief Size of the contact stream [bytes] including force buffer
*/
PxU32 requiredBufferSize;
/**
\brief Number of contact points stored in the contact stream
*/
PxU8 contactCount;
/**
\brief Number of contact patches stored in the contact stream
*/
PxU8 patchCount;
/**
\brief Size of the contact stream [bytes] not including force buffer
*/
PxU16 contactStreamSize;
/**
\brief Additional information on the contact report pair.
@see PxContactPairFlag
*/
PxContactPairFlags flags;
/**
\brief Flags raised due to the contact.
The events field is a combination of:
<ul>
<li>PxPairFlag::eNOTIFY_TOUCH_FOUND,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_PERSISTS,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_LOST,</li>
<li>PxPairFlag::eNOTIFY_TOUCH_CCD,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_FOUND,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_PERSISTS,</li>
<li>PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST</li>
</ul>
See the documentation of #PxPairFlag for an explanation of each.
\note eNOTIFY_TOUCH_CCD can get raised even if the pair did not request this event. However, in such a case it will only get
raised in combination with one of the other flags to point out that the other event occured during a CCD pass.
@see PxPairFlag
*/
PxPairFlags events;
PxU32 internalData[2]; // For internal use only
/**
\brief Extracts the contact points from the stream and stores them in a convenient format.
\param[out] userBuffer Array of PxContactPairPoint structures to extract the contact points to. The number of contacts for a pair is defined by #contactCount
\param[in] bufferSize Number of PxContactPairPoint structures the provided buffer can store.
\return Number of contact points written to the buffer.
@see PxContactPairPoint
*/
PX_INLINE PxU32 extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const;
/**
\brief Helper method to clone the contact pair and copy the contact data stream into a user buffer.
The contact data stream is only accessible during the contact report callback. This helper function provides copy functionality
to buffer the contact stream information such that it can get accessed at a later stage.
\param[out] newPair The contact pair info will get copied to this instance. The contact data stream pointer of the copy will be redirected to the provided user buffer. Use NULL to skip the contact pair copy operation.
\param[out] bufferMemory Memory block to store the contact data stream to. At most #requiredBufferSize bytes will get written to the buffer.
*/
PX_INLINE void bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const;
PX_INLINE const PxU32* getInternalFaceIndices() const;
};
PX_INLINE PxU32 PxContactPair::extractContacts(PxContactPairPoint* userBuffer, PxU32 bufferSize) const
{
PxU32 nbContacts = 0;
if(contactCount && bufferSize)
{
PxContactStreamIterator iter(contactPatches, contactPoints, getInternalFaceIndices(), patchCount, contactCount);
const PxReal* impulses = contactImpulses;
const PxU32 flippedContacts = (flags & PxContactPairFlag::eINTERNAL_CONTACTS_ARE_FLIPPED);
const PxU32 hasImpulses = (flags & PxContactPairFlag::eINTERNAL_HAS_IMPULSES);
while(iter.hasNextPatch())
{
iter.nextPatch();
while(iter.hasNextContact())
{
iter.nextContact();
PxContactPairPoint& dst = userBuffer[nbContacts];
dst.position = iter.getContactPoint();
dst.separation = iter.getSeparation();
dst.normal = iter.getContactNormal();
if(!flippedContacts)
{
dst.internalFaceIndex0 = iter.getFaceIndex0();
dst.internalFaceIndex1 = iter.getFaceIndex1();
}
else
{
dst.internalFaceIndex0 = iter.getFaceIndex1();
dst.internalFaceIndex1 = iter.getFaceIndex0();
}
if(hasImpulses)
{
const PxReal impulse = impulses[nbContacts];
dst.impulse = dst.normal * impulse;
}
else
dst.impulse = PxVec3(0.0f);
++nbContacts;
if(nbContacts == bufferSize)
return nbContacts;
}
}
}
return nbContacts;
}
PX_INLINE void PxContactPair::bufferContacts(PxContactPair* newPair, PxU8* bufferMemory) const
{
PxU8* patches = bufferMemory;
PxU8* contacts = NULL;
if(patches)
{
contacts = bufferMemory + patchCount * sizeof(PxContactPatch);
PxMemCopy(patches, contactPatches, sizeof(PxContactPatch)*patchCount);
PxMemCopy(contacts, contactPoints, contactStreamSize - (sizeof(PxContactPatch)*patchCount));
}
if(contactImpulses)
{
PxMemCopy(bufferMemory + ((contactStreamSize + 15) & (~15)), contactImpulses, sizeof(PxReal) * contactCount);
}
if (newPair)
{
*newPair = *this;
newPair->contactPatches = patches;
newPair->contactPoints = contacts;
}
}
PX_INLINE const PxU32* PxContactPair::getInternalFaceIndices() const
{
return reinterpret_cast<const PxU32*>(contactImpulses + contactCount);
}
/**
\brief Collection of flags providing information on trigger report pairs.
@see PxTriggerPair
*/
struct PxTriggerPairFlag
{
enum Enum
{
eREMOVED_SHAPE_TRIGGER = (1<<0), //!< The trigger shape has been removed from the actor/scene.
eREMOVED_SHAPE_OTHER = (1<<1), //!< The shape causing the trigger event has been removed from the actor/scene.
eNEXT_FREE = (1<<2) //!< For internal use only.
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxTriggerPairFlag.
@see PxTriggerPairFlag
*/
typedef PxFlags<PxTriggerPairFlag::Enum, PxU8> PxTriggerPairFlags;
PX_FLAGS_OPERATORS(PxTriggerPairFlag::Enum, PxU8)
/**
\brief Descriptor for a trigger pair.
An array of these structs gets passed to the PxSimulationEventCallback::onTrigger() report.
\note The shape pointers might reference deleted shapes. This will be the case if #PxPairFlag::eNOTIFY_TOUCH_LOST
events were requested for the pair and one of the involved shapes gets deleted. Check the #flags member to see
whether that is the case. Do not dereference a pointer to a deleted shape. The pointer to a deleted shape is
only provided such that user data structures which might depend on the pointer value can be updated.
@see PxSimulationEventCallback.onTrigger()
*/
struct PxTriggerPair
{
PX_INLINE PxTriggerPair() {}
PxShape* triggerShape; //!< The shape that has been marked as a trigger.
PxActor* triggerActor; //!< The actor to which triggerShape is attached
PxShape* otherShape; //!< The shape causing the trigger event. \deprecated (see #PxSimulationEventCallback::onTrigger()) If collision between trigger shapes is enabled, then this member might point to a trigger shape as well.
PxActor* otherActor; //!< The actor to which otherShape is attached
PxPairFlag::Enum status; //!< Type of trigger event (eNOTIFY_TOUCH_FOUND or eNOTIFY_TOUCH_LOST). eNOTIFY_TOUCH_PERSISTS events are not supported.
PxTriggerPairFlags flags; //!< Additional information on the pair (see #PxTriggerPairFlag)
};
/**
\brief Descriptor for a broken constraint.
An array of these structs gets passed to the PxSimulationEventCallback::onConstraintBreak() report.
@see PxConstraint PxSimulationEventCallback.onConstraintBreak()
*/
struct PxConstraintInfo
{
PX_INLINE PxConstraintInfo() {}
PX_INLINE PxConstraintInfo(PxConstraint* c, void* extRef, PxU32 t) : constraint(c), externalReference(extRef), type(t) {}
PxConstraint* constraint; //!< The broken constraint.
void* externalReference; //!< The external object which owns the constraint (see #PxConstraintConnector::getExternalReference())
PxU32 type; //!< Unique type ID of the external object. Allows to cast the provided external reference to the appropriate type
};
/**
\brief An interface class that the user can implement in order to receive simulation events.
With the exception of onAdvance(), the events get sent during the call to either #PxScene::fetchResults() or
#PxScene::flushSimulation() with sendPendingReports=true. onAdvance() gets called while the simulation
is running (that is between PxScene::simulate() or PxScene::advance() and PxScene::fetchResults()).
\note SDK state should not be modified from within the callbacks. In particular objects should not
be created or destroyed. If state modification is needed then the changes should be stored to a buffer
and performed after the simulation step.
<b>Threading:</b> With the exception of onAdvance(), it is not necessary to make these callbacks thread safe as
they will only be called in the context of the user thread.
@see PxScene.setSimulationEventCallback() PxScene.getSimulationEventCallback()
*/
class PxSimulationEventCallback
{
public:
/**
\brief This is called when a breakable constraint breaks.
\note The user should not release the constraint shader inside this call!
\note No event will get reported if the constraint breaks but gets deleted while the time step is still being simulated.
\param[in] constraints - The constraints which have been broken.
\param[in] count - The number of constraints
@see PxConstraint PxConstraintDesc.linearBreakForce PxConstraintDesc.angularBreakForce
*/
virtual void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) = 0;
/**
\brief This is called with the actors which have just been woken up.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame
will get reported. For example, let us assume actor A is awake, then A->putToSleep() gets called, then later A->wakeUp() gets called.
At the next simulate/fetchResults() step only an onWake() event will get triggered because that was the last transition.
\note If an actor gets newly added to a scene with properties such that it is awake and the sleep state does not get changed by
the user or simulation, then an onWake() event will get sent at the next simulate/fetchResults() step.
\param[in] actors - The actors which just woke up.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
virtual void onWake(PxActor** actors, PxU32 count) = 0;
/**
\brief This is called with the actors which have just been put to sleep.
\note Only supported by rigid bodies yet.
\note Only called on actors for which the PxActorFlag eSEND_SLEEP_NOTIFIES has been set.
\note Only the latest sleep state transition happening between fetchResults() of the previous frame and fetchResults() of the current frame
will get reported. For example, let us assume actor A is asleep, then A->wakeUp() gets called, then later A->putToSleep() gets called.
At the next simulate/fetchResults() step only an onSleep() event will get triggered because that was the last transition (assuming the simulation
does not wake the actor up).
\note If an actor gets newly added to a scene with properties such that it is asleep and the sleep state does not get changed by
the user or simulation, then an onSleep() event will get sent at the next simulate/fetchResults() step.
\param[in] actors - The actors which have just been put to sleep.
\param[in] count - The number of actors
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxActorFlag PxActor.setActorFlag()
*/
virtual void onSleep(PxActor** actors, PxU32 count) = 0;
/**
\brief This is called when certain contact events occur.
The method will be called for a pair of actors if one of the colliding shape pairs requested contact notification.
You request which events are reported using the filter shader/callback mechanism (see #PxSimulationFilterShader,
#PxSimulationFilterCallback, #PxPairFlag).
Do not keep references to the passed objects, as they will be
invalid after this function returns.
\param[in] pairHeader Information on the two actors whose shapes triggered a contact report.
\param[in] pairs The contact pairs of two actors for which contact reports have been requested. See #PxContactPair.
\param[in] nbPairs The number of provided contact pairs.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxContactPair PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual void onContact(const PxContactPairHeader& pairHeader, const PxContactPair* pairs, PxU32 nbPairs) = 0;
/**
\brief This is called with the current trigger pair events.
Shapes which have been marked as triggers using PxShapeFlag::eTRIGGER_SHAPE will send events
according to the pair flag specification in the filter shader (see #PxPairFlag, #PxSimulationFilterShader).
\note Trigger shapes will no longer send notification events for interactions with other trigger shapes.
\param[in] pairs - The trigger pair events.
\param[in] count - The number of trigger pair events.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxPairFlag PxSimulationFilterShader PxShapeFlag PxShape.setFlag()
*/
virtual void onTrigger(PxTriggerPair* pairs, PxU32 count) = 0;
/**
\brief Provides early access to the new pose of moving rigid bodies.
When this call occurs, rigid bodies having the #PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW
flag set, were moved by the simulation and their new poses can be accessed through the provided buffers.
\note The provided buffers are valid and can be read until the next call to #PxScene::simulate() or #PxScene::collide().
\note This callback gets triggered while the simulation is running. If the provided rigid body references are used to
read properties of the object, then the callback has to guarantee no other thread is writing to the same body at the same
time.
\note The code in this callback should be lightweight as it can block the simulation, that is, the
#PxScene::fetchResults() call.
\param[in] bodyBuffer The rigid bodies that moved and requested early pose reporting.
\param[in] poseBuffer The integrated rigid body poses of the bodies listed in bodyBuffer.
\param[in] count The number of entries in the provided buffers.
@see PxScene.setSimulationEventCallback() PxSceneDesc.simulationEventCallback PxRigidBodyFlag::eENABLE_POSE_INTEGRATION_PREVIEW
*/
virtual void onAdvance(const PxRigidBody*const* bodyBuffer, const PxTransform* poseBuffer, const PxU32 count) = 0;
virtual ~PxSimulationEventCallback() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,876 | C | 32.930769 | 230 | 0.754502 |
NVIDIA-Omniverse/PhysX/physx/include/PxContactModifyCallback.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_CONTACT_MODIFY_CALLBACK_H
#define PX_CONTACT_MODIFY_CALLBACK_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxShape.h"
#include "PxContact.h"
#include "foundation/PxTransform.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
/**
\brief An array of contact points, as passed to contact modification.
The word 'set' in the name does not imply that duplicates are filtered in any
way. This initial set of contacts does potentially get reduced to a smaller
set before being passed to the solver.
You can use the accessors to read and write contact properties. The number of
contacts is immutable, other than being able to disable contacts using ignore().
@see PxContactModifyCallback, PxModifiableContact
*/
class PxContactSet
{
public:
/**
\brief Get the position of a specific contact point in the set.
\param[in] i Index of the point in the set
\return Position to the requested point in world space
@see PxModifiableContact.point
*/
PX_FORCE_INLINE const PxVec3& getPoint(PxU32 i) const { return mContacts[i].contact; }
/**
\brief Alter the position of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] p The new position in world space
@see PxModifiableContact.point
*/
PX_FORCE_INLINE void setPoint(PxU32 i, const PxVec3& p) { mContacts[i].contact = p; }
/**
\brief Get the contact normal of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The requested normal in world space
@see PxModifiableContact.normal
*/
PX_FORCE_INLINE const PxVec3& getNormal(PxU32 i) const { return mContacts[i].normal; }
/**
\brief Alter the contact normal of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] n The new normal in world space
\note Changing the normal can cause contact points to be ignored.
@see PxModifiableContact.normal
*/
PX_FORCE_INLINE void setNormal(PxU32 i, const PxVec3& n)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].normal = n;
}
/**
\brief Get the separation distance of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The separation. Negative implies penetration.
@see PxModifiableContact.separation
*/
PX_FORCE_INLINE PxReal getSeparation(PxU32 i) const { return mContacts[i].separation; }
/**
\brief Alter the separation of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] s The new separation
@see PxModifiableContact.separation
*/
PX_FORCE_INLINE void setSeparation(PxU32 i, PxReal s) { mContacts[i].separation = s; }
/**
\brief Get the target velocity of a specific contact point in the set.
\param[in] i Index of the point in the set
\return The target velocity in world frame
@see PxModifiableContact.targetVelocity
*/
PX_FORCE_INLINE const PxVec3& getTargetVelocity(PxU32 i) const { return mContacts[i].targetVelocity; }
/**
\brief Alter the target velocity of a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] v The new velocity in world frame as seen from the second actor in the contact pair, i.e., the solver will try to achieve targetVel == (vel1 - vel2)
\note The sign of the velocity needs to be flipped depending on the order of the actors in the pair. There is no guarantee about the consistency of the order from frame to frame.
@see PxModifiableContact.targetVelocity
*/
PX_FORCE_INLINE void setTargetVelocity(PxU32 i, const PxVec3& v)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eHAS_TARGET_VELOCITY;
mContacts[i].targetVelocity = v;
}
/**
\brief Get the face index with respect to the first shape of the pair for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The face index of the first shape
\note At the moment, the first shape is never a tri-mesh, therefore this function always returns PXC_CONTACT_NO_FACE_INDEX
@see PxModifiableContact.internalFaceIndex0
*/
PX_FORCE_INLINE PxU32 getInternalFaceIndex0(PxU32 i) const { PX_UNUSED(i); return PXC_CONTACT_NO_FACE_INDEX; }
/**
\brief Get the face index with respect to the second shape of the pair for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The face index of the second shape
@see PxModifiableContact.internalFaceIndex1
*/
PX_FORCE_INLINE PxU32 getInternalFaceIndex1(PxU32 i) const
{
PxContactPatch* patch = getPatch();
if (patch->internalFlags & PxContactPatch::eHAS_FACE_INDICES)
{
return reinterpret_cast<PxU32*>(mContacts + mCount)[mCount + i];
}
return PXC_CONTACT_NO_FACE_INDEX;
}
/**
\brief Get the maximum impulse for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The maximum impulse
@see PxModifiableContact.maxImpulse
*/
PX_FORCE_INLINE PxReal getMaxImpulse(PxU32 i) const { return mContacts[i].maxImpulse; }
/**
\brief Alter the maximum impulse for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] s The new maximum impulse
\note Must be nonnegative. If set to zero, the contact point will be ignored
@see PxModifiableContact.maxImpulse, ignore()
*/
PX_FORCE_INLINE void setMaxImpulse(PxU32 i, PxReal s)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eHAS_MAX_IMPULSE;
mContacts[i].maxImpulse = s;
}
/**
\brief Get the restitution coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The restitution coefficient
@see PxModifiableContact.restitution
*/
PX_FORCE_INLINE PxReal getRestitution(PxU32 i) const { return mContacts[i].restitution; }
/**
\brief Alter the restitution coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] r The new restitution coefficient
\note Valid ranges [0,1]
@see PxModifiableContact.restitution
*/
PX_FORCE_INLINE void setRestitution(PxU32 i, PxReal r)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].restitution = r;
}
/**
\brief Get the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The friction coefficient (dimensionless)
@see PxModifiableContact.staticFriction
*/
PX_FORCE_INLINE PxReal getStaticFriction(PxU32 i) const { return mContacts[i].staticFriction; }
/**
\brief Alter the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] f The new friction coefficient (dimensionless), range [0, inf]
@see PxModifiableContact.staticFriction
*/
PX_FORCE_INLINE void setStaticFriction(PxU32 i, PxReal f)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].staticFriction = f;
}
/**
\brief Get the static friction coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\return The friction coefficient
@see PxModifiableContact.dynamicFriction
*/
PX_FORCE_INLINE PxReal getDynamicFriction(PxU32 i) const { return mContacts[i].dynamicFriction; }
/**
\brief Alter the static dynamic coefficient for a specific contact point in the set.
\param[in] i Index of the point in the set
\param[in] f The new friction coefficient
@see PxModifiableContact.dynamicFriction
*/
PX_FORCE_INLINE void setDynamicFriction(PxU32 i, PxReal f)
{
PxContactPatch* patch = getPatch();
patch->internalFlags |= PxContactPatch::eREGENERATE_PATCHES;
mContacts[i].dynamicFriction = f;
}
/**
\brief Ignore the contact point.
\param[in] i Index of the point in the set
If a contact point is ignored then no force will get applied at this point. This can be used to disable collision in certain areas of a shape, for example.
*/
PX_FORCE_INLINE void ignore(PxU32 i) { setMaxImpulse(i, 0.0f); }
/**
\brief The number of contact points in the set.
*/
PX_FORCE_INLINE PxU32 size() const { return mCount; }
/**
\brief Returns the invMassScale of body 0
A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE PxReal getInvMassScale0() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.linear0;
}
/**
\brief Returns the invMassScale of body 1
A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE PxReal getInvMassScale1() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.linear1;
}
/**
\brief Returns the invInertiaScale of body 0
A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE PxReal getInvInertiaScale0() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.angular0;
}
/**
\brief Returns the invInertiaScale of body 1
A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE PxReal getInvInertiaScale1() const
{
PxContactPatch* patch = getPatch();
return patch->mMassModification.angular1;
}
/**
\brief Sets the invMassScale of body 0
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE void setInvMassScale0(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.linear0 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invMassScale of body 1
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger mass. A value of 0.f makes this contact
treat the body as if it had infinite mass. Any value > 1.f makes this contact treat the body as if it had smaller mass.
*/
PX_FORCE_INLINE void setInvMassScale1(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.linear1 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invInertiaScale of body 0
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE void setInvInertiaScale0(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.angular0 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
/**
\brief Sets the invInertiaScale of body 1
\param[in] scale The new scale
This can be set to any value in the range [0, PX_MAX_F32). A value < 1.0 makes this contact treat the body as if it had larger inertia. A value of 0.f makes this contact
treat the body as if it had infinite inertia. Any value > 1.f makes this contact treat the body as if it had smaller inertia.
*/
PX_FORCE_INLINE void setInvInertiaScale1(const PxReal scale)
{
PxContactPatch* patch = getPatch();
patch->mMassModification.angular1 = scale;
patch->internalFlags |= PxContactPatch::eHAS_MODIFIED_MASS_RATIOS;
}
protected:
PX_FORCE_INLINE PxContactPatch* getPatch() const
{
const size_t headerOffset = sizeof(PxContactPatch)*mCount;
return reinterpret_cast<PxContactPatch*>(reinterpret_cast<PxU8*>(mContacts) - headerOffset);
}
PxU32 mCount; //!< Number of contact points in the set
PxModifiableContact* mContacts; //!< The contact points of the set
};
/**
\brief An array of instances of this class is passed to PxContactModifyCallback::onContactModify().
@see PxContactModifyCallback
*/
class PxContactModifyPair
{
public:
/**
\brief The actors which make up the pair in contact.
Note that these are the actors as seen by the simulation, and may have been deleted since the simulation step started.
*/
const PxRigidActor* actor[2];
/**
\brief The shapes which make up the pair in contact.
Note that these are the shapes as seen by the simulation, and may have been deleted since the simulation step started.
*/
const PxShape* shape[2];
/**
\brief The shape to world transforms of the two shapes.
These are the transforms as the simulation engine sees them, and may have been modified by the application
since the simulation step started.
*/
PxTransform transform[2];
/**
\brief An array of contact points between these two shapes.
*/
PxContactSet contacts;
};
/**
\brief An interface class that the user can implement in order to modify contact constraints.
<b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the
simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded
parts of the physics engine.
You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in
the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects.
Please note:
+ Raising the contact modification flag will not wake the actors up automatically.
+ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the
filter shader/callback has to be used to clear the contact modification flag.
+ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping.
@see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
class PxContactModifyCallback
{
public:
/**
\brief Passes modifiable arrays of contacts to the application.
The initial contacts are regenerated from scratch each frame by collision detection.
The number of contacts can not be changed, so you cannot add your own contacts. You may however
disable contacts using PxContactSet::ignore().
\param[in,out] pairs The contact pairs that may be modified
\param[in] count Number of contact pairs
@see PxContactModifyPair
*/
virtual void onContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0;
protected:
virtual ~PxContactModifyCallback(){}
};
/**
\brief An interface class that the user can implement in order to modify CCD contact constraints.
<b>Threading:</b> It is <b>necessary</b> to make this class thread safe as it will be called in the context of the
simulation thread. It might also be necessary to make it reentrant, since some calls can be made by multi-threaded
parts of the physics engine.
You can enable the use of this contact modification callback by raising the flag PxPairFlag::eMODIFY_CONTACTS in
the filter shader/callback (see #PxSimulationFilterShader) for a pair of rigid body objects.
Please note:
+ Raising the contact modification flag will not wake the actors up automatically.
+ It is not possible to turn off the performance degradation by simply removing the callback from the scene, the
filter shader/callback has to be used to clear the contact modification flag.
+ The contacts will only be reported as long as the actors are awake. There will be no callbacks while the actors are sleeping.
@see PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
class PxCCDContactModifyCallback
{
public:
/**
\brief Passes modifiable arrays of contacts to the application.
The initial contacts are regenerated from scratch each frame by collision detection.
The number of contacts can not be changed, so you cannot add your own contacts. You may however
disable contacts using PxContactSet::ignore().
\param[in,out] pairs The contact pairs that may be modified
\param[in] count Number of contact pairs
*/
virtual void onCCDContactModify(PxContactModifyPair* const pairs, PxU32 count) = 0;
protected:
virtual ~PxCCDContactModifyCallback(){}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 18,893 | C | 34.784091 | 179 | 0.747473 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysicsAPI.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_API_H
#define PX_PHYSICS_API_H
/** \addtogroup physics
@{
*/
/**
This is the main include header for the Physics SDK, for users who
want to use a single #include file.
Alternatively, one can instead directly #include a subset of the below files.
*/
// Foundation SDK
#include "foundation/Px.h"
#include "foundation/PxAlignedMalloc.h"
#include "foundation/PxAlloca.h"
#include "foundation/PxAllocatorCallback.h"
#include "foundation/PxArray.h"
#include "foundation/PxAssert.h"
#include "foundation/PxAtomic.h"
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxBitAndData.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxBitUtils.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxBroadcast.h"
#include "foundation/PxErrorCallback.h"
#include "foundation/PxErrors.h"
#include "foundation/PxFlags.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxFoundationConfig.h"
#include "foundation/PxFPU.h"
#include "foundation/PxHash.h"
#include "foundation/PxHashMap.h"
#include "foundation/PxHashSet.h"
#include "foundation/PxInlineAllocator.h"
#include "foundation/PxInlineArray.h"
#include "foundation/PxIntrinsics.h"
#include "foundation/PxIO.h"
#include "foundation/PxMat33.h"
#include "foundation/PxMat44.h"
#include "foundation/PxMath.h"
#include "foundation/PxMathIntrinsics.h"
#include "foundation/PxMathUtils.h"
#include "foundation/PxMemory.h"
#include "foundation/PxMutex.h"
#include "foundation/PxPhysicsVersion.h"
#include "foundation/PxPlane.h"
#include "foundation/PxPool.h"
#include "foundation/PxPreprocessor.h"
#include "foundation/PxProfiler.h"
#include "foundation/PxQuat.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxSList.h"
#include "foundation/PxSocket.h"
#include "foundation/PxSort.h"
#include "foundation/PxStrideIterator.h"
#include "foundation/PxString.h"
#include "foundation/PxSync.h"
#include "foundation/PxTempAllocator.h"
#include "foundation/PxThread.h"
#include "foundation/PxTime.h"
#include "foundation/PxTransform.h"
#include "foundation/PxUnionCast.h"
#include "foundation/PxUserAllocated.h"
#include "foundation/PxUtilities.h"
#include "foundation/PxVec2.h"
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#include "foundation/PxVecMath.h"
#include "foundation/PxVecQuat.h"
#include "foundation/PxVecTransform.h"
//Not physics specific utilities and common code
#include "common/PxCoreUtilityTypes.h"
#include "common/PxPhysXCommonConfig.h"
#include "common/PxRenderBuffer.h"
#include "common/PxBase.h"
#include "common/PxTolerancesScale.h"
#include "common/PxTypeInfo.h"
#include "common/PxStringTable.h"
#include "common/PxSerializer.h"
#include "common/PxMetaData.h"
#include "common/PxMetaDataFlags.h"
#include "common/PxSerialFramework.h"
#include "common/PxInsertionCallback.h"
//Task Manager
#include "task/PxTask.h"
// Cuda Mananger
#if PX_SUPPORT_GPU_PHYSX
#include "gpu/PxGpu.h"
#endif
//Geometry Library
#include "geometry/PxBoxGeometry.h"
#include "geometry/PxBVH.h"
#include "geometry/PxBVHBuildStrategy.h"
#include "geometry/PxCapsuleGeometry.h"
#include "geometry/PxConvexMesh.h"
#include "geometry/PxConvexMeshGeometry.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHelpers.h"
#include "geometry/PxGeometryQuery.h"
#include "geometry/PxHeightField.h"
#include "geometry/PxHeightFieldDesc.h"
#include "geometry/PxHeightFieldFlag.h"
#include "geometry/PxHeightFieldGeometry.h"
#include "geometry/PxHeightFieldSample.h"
#include "geometry/PxMeshQuery.h"
#include "geometry/PxMeshScale.h"
#include "geometry/PxPlaneGeometry.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "geometry/PxSphereGeometry.h"
#include "geometry/PxTriangle.h"
#include "geometry/PxTriangleMesh.h"
#include "geometry/PxTriangleMeshGeometry.h"
#include "geometry/PxTetrahedron.h"
#include "geometry/PxTetrahedronMesh.h"
#include "geometry/PxTetrahedronMeshGeometry.h"
// PhysX Core SDK
#include "PxActor.h"
#include "PxAggregate.h"
#include "PxArticulationReducedCoordinate.h"
#include "PxArticulationJointReducedCoordinate.h"
#include "PxArticulationLink.h"
#include "PxClient.h"
#include "PxConeLimitedConstraint.h"
#include "PxConstraint.h"
#include "PxConstraintDesc.h"
#include "PxContact.h"
#include "PxContactModifyCallback.h"
#include "PxDeletionListener.h"
#include "PxFEMSoftBodyMaterial.h"
#include "PxFiltering.h"
#include "PxForceMode.h"
#include "PxLockedData.h"
#include "PxMaterial.h"
#include "PxParticleBuffer.h"
#include "PxParticleSystem.h"
#include "PxPBDParticleSystem.h"
#include "PxPBDMaterial.h"
#include "PxPhysics.h"
#include "PxPhysXConfig.h"
#include "PxQueryFiltering.h"
#include "PxQueryReport.h"
#include "PxRigidActor.h"
#include "PxRigidBody.h"
#include "PxRigidDynamic.h"
#include "PxRigidStatic.h"
#include "PxScene.h"
#include "PxSceneDesc.h"
#include "PxSceneLock.h"
#include "PxShape.h"
#include "PxSimulationEventCallback.h"
#include "PxSimulationStatistics.h"
#include "PxSoftBody.h"
#include "PxVisualizationParameter.h"
#include "PxPruningStructure.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#include "PxFEMClothMaterial.h"
#include "PxFLIPParticleSystem.h"
#include "PxFLIPMaterial.h"
#include "PxHairSystem.h"
#include "PxMPMMaterial.h"
#include "PxMPMParticleSystem.h"
#endif
//Character Controller
#include "characterkinematic/PxBoxController.h"
#include "characterkinematic/PxCapsuleController.h"
#include "characterkinematic/PxController.h"
#include "characterkinematic/PxControllerBehavior.h"
#include "characterkinematic/PxControllerManager.h"
#include "characterkinematic/PxControllerObstacles.h"
#include "characterkinematic/PxExtended.h"
//Cooking (data preprocessing)
#include "cooking/Pxc.h"
#include "cooking/PxConvexMeshDesc.h"
#include "cooking/PxCooking.h"
#include "cooking/PxTriangleMeshDesc.h"
#include "cooking/PxBVH33MidphaseDesc.h"
#include "cooking/PxBVH34MidphaseDesc.h"
#include "cooking/PxMidphaseDesc.h"
//Extensions to the SDK
#include "extensions/PxDefaultStreams.h"
#include "extensions/PxExtensionsAPI.h"
//Serialization
#include "extensions/PxSerialization.h"
#include "extensions/PxBinaryConverter.h"
#include "extensions/PxRepXSerializer.h"
//Vehicle Simulation
#include "vehicle2/PxVehicleAPI.h"
#include "vehicle/PxVehicleComponents.h"
#include "vehicle/PxVehicleDrive.h"
#include "vehicle/PxVehicleDrive4W.h"
#include "vehicle/PxVehicleDriveTank.h"
#include "vehicle/PxVehicleSDK.h"
#include "vehicle/PxVehicleShaders.h"
#include "vehicle/PxVehicleTireFriction.h"
#include "vehicle/PxVehicleUpdate.h"
#include "vehicle/PxVehicleUtil.h"
#include "vehicle/PxVehicleUtilControl.h"
#include "vehicle/PxVehicleUtilSetup.h"
#include "vehicle/PxVehicleUtilTelemetry.h"
#include "vehicle/PxVehicleWheels.h"
#include "vehicle/PxVehicleNoDrive.h"
#include "vehicle/PxVehicleDriveNW.h"
//Connecting the SDK to Visual Debugger
#include "pvd/PxPvdSceneClient.h"
#include "pvd/PxPvd.h"
#include "pvd/PxPvdTransport.h"
/** @} */
#endif
| 8,680 | C | 33.312253 | 77 | 0.792742 |
NVIDIA-Omniverse/PhysX/physx/include/PxNodeIndex.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_NODEINDEX_H
#define PX_NODEINDEX_H
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#define PX_INVALID_NODE 0xFFFFFFFFu
/**
\brief PxNodeIndex
Node index is the unique index for each actor referenced by the island gen. It contains details like
if the actor is an articulation or rigid body. If it is an articulation, the node index also contains
the link index of the rigid body within the articulation. Also, it contains information to detect whether
the rigid body is static body or not
*/
class PxNodeIndex
{
protected:
PxU64 ind;
public:
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id, PxU32 articLinkId) : ind((PxU64(id) << 32) | (articLinkId << 1) | 1)
{
}
explicit PX_CUDA_CALLABLE PX_FORCE_INLINE PxNodeIndex(PxU32 id = PX_INVALID_NODE) : ind((PxU64(id) << 32))
{
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 index() const { return PxU32(ind >> 32); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 articulationLinkId() const { return PxU32((ind >> 1) & 0x7FFFFFFF); }
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 isArticulation() const { return PxU32(ind & 1); }
PX_CUDA_CALLABLE PX_FORCE_INLINE bool isStaticBody() const { return PxU32(ind >> 32) == PX_INVALID_NODE; }
PX_CUDA_CALLABLE bool isValid() const { return PxU32(ind >> 32) != PX_INVALID_NODE; }
PX_CUDA_CALLABLE void setIndices(PxU32 index, PxU32 articLinkId) { ind = ((PxU64(index) << 32) | (articLinkId << 1) | 1); }
PX_CUDA_CALLABLE void setIndices(PxU32 index) { ind = ((PxU64(index) << 32)); }
PX_CUDA_CALLABLE bool operator < (const PxNodeIndex& other) const { return ind < other.ind; }
PX_CUDA_CALLABLE bool operator <= (const PxNodeIndex& other) const { return ind <= other.ind; }
PX_CUDA_CALLABLE bool operator == (const PxNodeIndex& other) const { return ind == other.ind; }
PX_CUDA_CALLABLE PxU64 getInd() const { return ind; }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,668 | C | 39.766666 | 134 | 0.73337 |
NVIDIA-Omniverse/PhysX/physx/include/PxQueryFiltering.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_QUERY_FILTERING_H
#define PX_QUERY_FILTERING_H
/** \addtogroup scenequery
@{
*/
#include "PxPhysXConfig.h"
#include "PxFiltering.h"
#include "PxQueryReport.h"
#include "PxClient.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxRigidActor;
struct PxQueryHit;
/**
\brief Filtering flags for scene queries.
@see PxQueryFilterData.flags
*/
struct PxQueryFlag
{
enum Enum
{
eSTATIC = (1<<0), //!< Traverse static shapes
eDYNAMIC = (1<<1), //!< Traverse dynamic shapes
ePREFILTER = (1<<2), //!< Run the pre-intersection-test filter (see #PxQueryFilterCallback::preFilter())
ePOSTFILTER = (1<<3), //!< Run the post-intersection-test filter (see #PxQueryFilterCallback::postFilter())
eANY_HIT = (1<<4), //!< Abort traversal as soon as any hit is found and return it via callback.block.
//!< Helps query performance. Both eTOUCH and eBLOCK hitTypes are considered hits with this flag.
eNO_BLOCK = (1<<5), //!< All hits are reported as touching. Overrides eBLOCK returned from user filters with eTOUCH.
//!< This is also an optimization hint that may improve query performance.
eBATCH_QUERY_LEGACY_BEHAVIOUR = (1<<6), //!< Run with legacy batch query filter behavior. Raising this flag ensures that
//!< the hardcoded filter equation is neglected. This guarantees that any provided PxQueryFilterCallback
//!< will be utilised, as specified by the ePREFILTER and ePOSTFILTER flags.
eDISABLE_HARDCODED_FILTER = (1<<6), //!< Same as eBATCH_QUERY_LEGACY_BEHAVIOUR, more explicit name making it clearer that this can also be used
//!< with regular/non-batched queries if needed.
eRESERVED = (1<<15) //!< Reserved for internal use
};
};
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eSTATIC==(1<<0));
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eDYNAMIC==(1<<1));
PX_COMPILE_TIME_ASSERT(PxQueryFlag::eBATCH_QUERY_LEGACY_BEHAVIOUR==PxQueryFlag::eDISABLE_HARDCODED_FILTER);
/**
\brief Flags typedef for the set of bits defined in PxQueryFlag.
*/
typedef PxFlags<PxQueryFlag::Enum,PxU16> PxQueryFlags;
PX_FLAGS_OPERATORS(PxQueryFlag::Enum,PxU16)
/**
\brief Classification of scene query hits (intersections).
- eNONE: Returning this hit type means that the hit should not be reported.
- eBLOCK: For all raycast, sweep and overlap queries the nearest eBLOCK type hit will always be returned in PxHitCallback::block member.
- eTOUCH: Whenever a raycast, sweep or overlap query was called with non-zero PxHitCallback::nbTouches and PxHitCallback::touches
parameters, eTOUCH type hits that are closer or same distance (touchDistance <= blockDistance condition)
as the globally nearest eBLOCK type hit, will be reported.
- For example, to record all hits from a raycast query, always return eTOUCH.
All hits in overlap() queries are treated as if the intersection distance were zero.
This means the hits are unsorted and all eTOUCH hits are recorded by the callback even if an eBLOCK overlap hit was encountered.
Even though all overlap() blocking hits have zero length, only one (arbitrary) eBLOCK overlap hit is recorded in PxHitCallback::block.
All overlap() eTOUCH type hits are reported (zero touchDistance <= zero blockDistance condition).
For raycast/sweep/overlap calls with zero touch buffer or PxHitCallback::nbTouches member,
only the closest hit of type eBLOCK is returned. All eTOUCH hits are discarded.
@see PxQueryFilterCallback.preFilter PxQueryFilterCallback.postFilter PxScene.raycast PxScene.sweep PxScene.overlap
*/
struct PxQueryHitType
{
enum Enum
{
eNONE = 0, //!< the query should ignore this shape
eTOUCH = 1, //!< a hit on the shape touches the intersection geometry of the query but does not block it
eBLOCK = 2 //!< a hit on the shape blocks the query (does not block overlap queries)
};
};
/**
\brief Scene query filtering data.
Whenever the scene query intersects a shape, filtering is performed in the following order:
\li For non-batched queries only:<br>If the data field is non-zero, and the bitwise-AND value of data AND the shape's
queryFilterData is zero, the shape is skipped
\li If filter callbacks are enabled in flags field (see #PxQueryFlags) they will get invoked accordingly.
\li If neither #PxQueryFlag::ePREFILTER or #PxQueryFlag::ePOSTFILTER is set, the hit defaults
to type #PxQueryHitType::eBLOCK when the value of PxHitCallback::nbTouches provided with the query is zero and to type
#PxQueryHitType::eTOUCH when PxHitCallback::nbTouches is positive.
@see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlag::eANY_HIT
*/
struct PxQueryFilterData
{
/** \brief default constructor */
explicit PX_INLINE PxQueryFilterData() : flags(PxQueryFlag::eDYNAMIC | PxQueryFlag::eSTATIC) {}
/** \brief constructor to set both filter data and filter flags */
explicit PX_INLINE PxQueryFilterData(const PxFilterData& fd, PxQueryFlags f) : data(fd), flags(f) {}
/** \brief constructor to set filter flags only */
explicit PX_INLINE PxQueryFilterData(PxQueryFlags f) : flags(f) {}
PxFilterData data; //!< Filter data associated with the scene query
PxQueryFlags flags; //!< Filter flags (see #PxQueryFlags)
};
/**
\brief Scene query filtering callbacks.
Custom filtering logic for scene query intersection candidates. If an intersection candidate object passes the data based filter
(see #PxQueryFilterData), filtering callbacks are executed if requested (see #PxQueryFilterData.flags)
\li If #PxQueryFlag::ePREFILTER is set, the preFilter function runs before exact intersection tests.
If this function returns #PxQueryHitType::eTOUCH or #PxQueryHitType::eBLOCK, exact testing is performed to
determine the intersection location.
The preFilter function may overwrite the copy of queryFlags it receives as an argument to specify any of #PxHitFlag::eMODIFIABLE_FLAGS
on a per-shape basis. Changes apply only to the shape being filtered, and changes to other flags are ignored.
\li If #PxQueryFlag::ePREFILTER is not set, precise intersection testing is performed using the original query's filterData.flags.
\li If #PxQueryFlag::ePOSTFILTER is set, the postFilter function is called for each intersection to determine the touch/block status.
This overrides any touch/block status previously returned from the preFilter function for this shape.
Filtering calls are not guaranteed to be sorted along the ray or sweep direction.
@see PxScene.raycast PxScene.sweep PxScene.overlap PxQueryFlags PxHitFlags
*/
class PxQueryFilterCallback
{
public:
/**
\brief This filter callback is executed before the exact intersection test if PxQueryFlag::ePREFILTER flag was set.
\param[in] filterData custom filter data specified as the query's filterData.data parameter.
\param[in] shape A shape that has not yet passed the exact intersection test.
\param[in] actor The shape's actor.
\param[in,out] queryFlags scene query flags from the query's function call (only flags from PxHitFlag::eMODIFIABLE_FLAGS bitmask can be modified)
\return the updated type for this hit (see #PxQueryHitType)
*/
virtual PxQueryHitType::Enum preFilter(const PxFilterData& filterData, const PxShape* shape, const PxRigidActor* actor, PxHitFlags& queryFlags) = 0;
/**
\brief This filter callback is executed if the exact intersection test returned true and PxQueryFlag::ePOSTFILTER flag was set.
\param[in] filterData custom filter data of the query
\param[in] hit Scene query hit information. faceIndex member is not valid for overlap queries. For sweep and raycast queries the hit information can be cast to #PxSweepHit and #PxRaycastHit respectively.
\param[in] shape Hit shape
\param[in] actor Hit actor
\return the updated hit type for this hit (see #PxQueryHitType)
*/
virtual PxQueryHitType::Enum postFilter(const PxFilterData& filterData, const PxQueryHit& hit, const PxShape* shape, const PxRigidActor* actor) = 0;
/**
\brief virtual destructor
*/
virtual ~PxQueryFilterCallback() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,786 | C | 44.948357 | 206 | 0.759963 |
NVIDIA-Omniverse/PhysX/physx/include/PxSmoothing.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SMOOTHING_H
#define PX_SMOOTHING_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
class PxgKernelLauncher;
class PxParticleNeighborhoodProvider;
/**
\brief Ccomputes smoothed positions for a particle system to improve rendering quality
*/
class PxSmoothedPositionGenerator
{
public:
/**
\brief Schedules the compuation of smoothed positions on the specified cuda stream
\param[in] gpuParticleSystem A gpu pointer to access particle system data
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateSmoothedPositions(PxGpuParticleSystem* gpuParticleSystem, PxU32 numParticles, CUstream stream) = 0;
/**
\brief Schedules the compuation of smoothed positions on the specified cuda stream
\param[in] particlePositionsGpu A gpu pointer containing the particle positions
\param[in] neighborhoodProvider A neighborhood provider object that supports fast neighborhood queries
\param[in] numParticles The number of particles
\param[in] particleContactOffset The particle contact offset
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateSmoothedPositions(PxVec4* particlePositionsGpu, PxParticleNeighborhoodProvider& neighborhoodProvider, PxU32 numParticles, PxReal particleContactOffset, CUstream stream) = 0;
/**
\brief Set a host buffer that holds the smoothed position data after the timestep completed
\param[in] smoothedPositions A host buffer with memory for all particles already allocated
*/
virtual void setResultBufferHost(PxVec4* smoothedPositions) = 0;
/**
\brief Set a device buffer that holds the smoothed position data after the timestep completed
\param[in] smoothedPositions A device buffer with memory for all particles already allocated
*/
virtual void setResultBufferDevice(PxVec4* smoothedPositions) = 0;
/**
\brief Sets the intensity of the position smoothing effect
\param[in] smoothingStrenght The strength of the smoothing effect
*/
virtual void setSmoothing(float smoothingStrenght) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the device pointer for the smoothed positions. Only available after calling setResultBufferHost or setResultBufferDevice
\return The device pointer for the smoothed positions
*/
virtual PxVec4* getSmoothedPositionsDevicePointer() const = 0;
/**
\brief Enables or disables the smoothed position generator
\param[in] enabled The boolean to set the generator to enabled or disabled
*/
virtual void setEnabled(bool enabled) = 0;
/**
\brief Allows to query if the smoothed position generator is enabled
\return True if enabled, false otherwise
*/
virtual bool isEnabled() const = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxSmoothedPositionGenerator() {}
};
/**
\brief Default implementation of a particle system callback to trigger smoothed position calculations. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the post solve task completed.
*/
class PxSmoothedPositionCallback : public PxParticleSystemCallback
{
public:
/**
\brief Initializes the smoothing callback
\param[in] smoothedPositionGenerator The smoothed position generator
*/
void initialize(PxSmoothedPositionGenerator* smoothedPositionGenerator)
{
mSmoothedPositionGenerator = smoothedPositionGenerator;
}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream)
{
if (mSmoothedPositionGenerator)
{
mSmoothedPositionGenerator->generateSmoothedPositions(gpuParticleSystem.mDevicePtr, gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream);
}
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
private:
PxSmoothedPositionGenerator* mSmoothedPositionGenerator;
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,555 | C | 33.324607 | 196 | 0.769031 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleNeighborhoodProvider.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H
#define PX_PARTICLE_NEIGHBORHOOD_PROVIDER_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
/**
\brief Computes neighborhood information for a point cloud
*/
class PxParticleNeighborhoodProvider
{
public:
/**
\brief Schedules the compuation of neighborhood information on the specified cuda stream
\param[in] deviceParticlePos A gpu pointer containing the particle positions
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
\param[in] devicePhases An optional gpu pointer with particle phases
\param[in] validPhaseMask An optional phase mask to define which particles should be included into the neighborhood computation
\param[in] deviceActiveIndices An optional device pointer containing all indices of particles that are currently active
*/
virtual void buildNeighborhood(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* devicePhases = NULL,
PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid, const PxU32* deviceActiveIndices = NULL) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the maximal number of grid cells
\return The maximal number of grid cells
*/
virtual PxU32 getMaxGridCells() const = 0;
/**
\brief Gets the cell size
\return The cell size
*/
virtual PxReal getCellSize() const = 0;
/**
\brief Gets the number of grid cells in use
\return The number of grid cells in use
*/
virtual PxU32 getNumGridCellsInUse() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxGridCells The maximal number of grid cells
\param[in] cellSize The cell size. Should be equal to 2*contactOffset for PBD particle systems.
*/
virtual void setCellProperties(PxU32 maxGridCells, PxReal cellSize) = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxParticleNeighborhoodProvider() {}
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,383 | C | 31.474074 | 130 | 0.751312 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleSolverType.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_SOLVER_TYPE_H
#define PX_PARTICLE_SOLVER_TYPE_H
/** \addtogroup physics
@{ */
#include "foundation/PxPreprocessor.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
/**
\brief Identifies the solver to use for a particle system.
*/
struct PxParticleSolverType
{
enum Enum
{
ePBD = 1 << 0, //!< The position based dynamics solver that can handle fluid, granular material, cloth, inflatables etc. See #PxPBDParticleSystem.
eFLIP = 1 << 1, //!< The FLIP fluid solver. See #PxFLIPParticleSystem.
eMPM = 1 << 2 //!< The MPM (material point method) solver that can handle a variety of materials. See #PxMPMParticleSystem.
};
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,528 | C | 34.619718 | 150 | 0.743275 |
NVIDIA-Omniverse/PhysX/physx/include/PxAggregate.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_AGGREGATE_H
#define PX_AGGREGATE_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxActor;
class PxBVH;
class PxScene;
struct PxAggregateType
{
enum Enum
{
eGENERIC = 0, //!< Aggregate will contain various actors of unspecified types
eSTATIC = 1, //!< Aggregate will only contain static actors
eKINEMATIC = 2 //!< Aggregate will only contain kinematic actors
};
};
// PxAggregateFilterHint is used for more efficient filtering of aggregates outside of the broadphase.
// It is a combination of a PxAggregateType and a self-collision bit.
typedef PxU32 PxAggregateFilterHint;
PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateFilterHint PxGetAggregateFilterHint(PxAggregateType::Enum type, bool enableSelfCollision)
{
const PxU32 selfCollisionBit = enableSelfCollision ? 1 : 0;
return PxAggregateFilterHint((PxU32(type)<<1)|selfCollisionBit);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 PxGetAggregateSelfCollisionBit(PxAggregateFilterHint hint)
{
return hint & 1;
}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxAggregateType::Enum PxGetAggregateType(PxAggregateFilterHint hint)
{
return PxAggregateType::Enum(hint>>1);
}
/**
\brief Class to aggregate actors into a single broad-phase entry.
A PxAggregate object is a collection of PxActors, which will exist as a single entry in the
broad-phase structures. This has 3 main benefits:
1) it reduces "broad phase pollution" by allowing a collection of spatially coherent broad-phase
entries to be replaced by a single aggregated entry (e.g. a ragdoll or a single actor with a
large number of attached shapes).
2) it reduces broad-phase memory usage
3) filtering can be optimized a lot if self-collisions within an aggregate are not needed. For
example if you don't need collisions between ragdoll bones, it's faster to simply disable
filtering once and for all, for the aggregate containing the ragdoll, rather than filtering
out each bone-bone collision in the filter shader.
@see PxActor, PxPhysics.createAggregate
*/
class PxAggregate : public PxBase
{
public:
/**
\brief Deletes the aggregate object.
Deleting the PxAggregate object does not delete the aggregated actors. If the PxAggregate object
belongs to a scene, the aggregated actors are automatically re-inserted in that scene. If you intend
to delete both the PxAggregate and its actors, it is best to release the actors first, then release
the PxAggregate when it is empty.
*/
virtual void release() = 0;
/**
\brief Adds an actor to the aggregate object.
A warning is output if the total number of actors is reached, or if the incoming actor already belongs
to an aggregate.
If the aggregate belongs to a scene, adding an actor to the aggregate also adds the actor to that scene.
If the actor already belongs to a scene, a warning is output and the call is ignored. You need to remove
the actor from the scene first, before adding it to the aggregate.
\note When a BVH is provided the actor shapes are grouped together.
The scene query pruning structure inside PhysX SDK will store/update one
bound per actor. The scene queries against such an actor will query actor
bounds and then make a local space query against the provided BVH, which is in actor's local space.
\param [in] actor The actor that should be added to the aggregate
\param [in] bvh BVH for actor shapes.
return true if success
*/
virtual bool addActor(PxActor& actor, const PxBVH* bvh = NULL) = 0;
/**
\brief Removes an actor from the aggregate object.
A warning is output if the incoming actor does not belong to the aggregate. Otherwise the actor is
removed from the aggregate. If the aggregate belongs to a scene, the actor is reinserted in that
scene. If you intend to delete the actor, it is best to call #PxActor::release() directly. That way
the actor will be automatically removed from its aggregate (if any) and not reinserted in a scene.
\param [in] actor The actor that should be removed from the aggregate
return true if success
*/
virtual bool removeActor(PxActor& actor) = 0;
/**
\brief Adds an articulation to the aggregate object.
A warning is output if the total number of actors is reached (every articulation link counts as an actor),
or if the incoming articulation already belongs to an aggregate.
If the aggregate belongs to a scene, adding an articulation to the aggregate also adds the articulation to that scene.
If the articulation already belongs to a scene, a warning is output and the call is ignored. You need to remove
the articulation from the scene first, before adding it to the aggregate.
\param [in] articulation The articulation that should be added to the aggregate
return true if success
*/
virtual bool addArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Removes an articulation from the aggregate object.
A warning is output if the incoming articulation does not belong to the aggregate. Otherwise the articulation is
removed from the aggregate. If the aggregate belongs to a scene, the articulation is reinserted in that
scene. If you intend to delete the articulation, it is best to call #PxArticulationReducedCoordinate::release() directly. That way
the articulation will be automatically removed from its aggregate (if any) and not reinserted in a scene.
\param [in] articulation The articulation that should be removed from the aggregate
return true if success
*/
virtual bool removeArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Returns the number of actors contained in the aggregate.
You can use #getActors() to retrieve the actor pointers.
\return Number of actors contained in the aggregate.
@see PxActor getActors()
*/
virtual PxU32 getNbActors() const = 0;
/**
\brief Retrieves max amount of actors that can be contained in the aggregate.
\return Max actor size.
@see PxPhysics::createAggregate()
*/
virtual PxU32 getMaxNbActors() const = 0;
/**
\brief Retrieves max amount of shapes that can be contained in the aggregate.
\return Max shape size.
@see PxPhysics::createAggregate()
*/
virtual PxU32 getMaxNbShapes() const = 0;
/**
\brief Retrieve all actors contained in the aggregate.
You can retrieve the number of actor pointers by calling #getNbActors()
\param[out] userBuffer The buffer to store the actor pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of actor pointers written to the buffer.
@see PxShape getNbShapes()
*/
virtual PxU32 getActors(PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Retrieves the scene which this aggregate belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() = 0;
/**
\brief Retrieves aggregate's self-collision flag.
\return self-collision flag
*/
virtual bool getSelfCollision() const = 0;
virtual const char* getConcreteTypeName() const { return "PxAggregate"; }
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxAggregate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxAggregate(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxAggregate() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxAggregate", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,371 | C | 36.338645 | 134 | 0.762672 |
NVIDIA-Omniverse/PhysX/physx/include/PxSceneQuerySystem.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SCENE_QUERY_SYSTEM_H
#define PX_SCENE_QUERY_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxBitMap.h"
#include "foundation/PxTransform.h"
#include "PxSceneQueryDesc.h"
#include "PxQueryReport.h"
#include "PxQueryFiltering.h"
#include "geometry/PxGeometryQueryFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
class PxRenderOutput;
class PxGeometry;
class PxRigidActor;
class PxShape;
class PxBVH;
class PxPruningStructure;
/**
\brief Built-in enum for default PxScene pruners
This is passed as a pruner index to various functions in the following APIs.
@see PxSceneQuerySystemBase::forceRebuildDynamicTree PxSceneQuerySystem::preallocate
@see PxSceneQuerySystem::visualize PxSceneQuerySystem::sync PxSceneQuerySystem::prepareSceneQueryBuildStep
*/
enum PxScenePrunerIndex
{
PX_SCENE_PRUNER_STATIC = 0,
PX_SCENE_PRUNER_DYNAMIC = 1,
PX_SCENE_COMPOUND_PRUNER = 0xffffffff
};
/**
\brief Base class for the scene-query system.
Methods defined here are common to both the traditional PxScene API and the PxSceneQuerySystem API.
@see PxScene PxSceneQuerySystem
*/
class PxSceneQuerySystemBase
{
protected:
PxSceneQuerySystemBase() {}
virtual ~PxSceneQuerySystemBase() {}
public:
/** @name Scene Query
*/
//@{
/**
\brief Sets the rebuild rate of the dynamic tree pruning structures.
\param[in] dynamicTreeRebuildRateHint Rebuild rate of the dynamic tree pruning structures.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint getDynamicTreeRebuildRateHint() forceRebuildDynamicTree()
*/
virtual void setDynamicTreeRebuildRateHint(PxU32 dynamicTreeRebuildRateHint) = 0;
/**
\brief Retrieves the rebuild rate of the dynamic tree pruning structures.
\return The rebuild rate of the dynamic tree pruning structures.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() forceRebuildDynamicTree()
*/
virtual PxU32 getDynamicTreeRebuildRateHint() const = 0;
/**
\brief Forces dynamic trees to be immediately rebuilt.
\param[in] prunerIndex Index of pruner containing the dynamic tree to rebuild
\note PxScene will call this function with the PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC value.
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint()
*/
virtual void forceRebuildDynamicTree(PxU32 prunerIndex) = 0;
/**
\brief Sets scene query update mode
\param[in] updateMode Scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
virtual void setUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) = 0;
/**
\brief Gets scene query update mode
\return Current scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
virtual PxSceneQueryUpdateMode::Enum getUpdateMode() const = 0;
/**
\brief Retrieves the system's internal scene query timestamp, increased each time a change to the
static scene query structure is performed.
\return scene query static timestamp
*/
virtual PxU32 getStaticTimestamp() const = 0;
/**
\brief Flushes any changes to the scene query representation.
This method updates the state of the scene query representation to match changes in the scene state.
By default, these changes are buffered until the next query is submitted. Calling this function will not change
the results from scene queries, but can be used to ensure that a query will not perform update work in the course of
its execution.
A thread performing updates will hold a write lock on the query structure, and thus stall other querying threads. In multithread
scenarios it can be useful to explicitly schedule the period where this lock may be held for a significant period, so that
subsequent queries issued from multiple threads will not block.
*/
virtual void flushUpdates() = 0;
/**
\brief Performs a raycast against objects in the scene, returns results in a PxRaycastBuffer object
or via a custom user callback implementation inheriting from PxRaycastCallback.
\note Touching hits are not ordered.
\note Shooting a ray from within an object leads to different results depending on the shape type. Please check the details in user guide article SceneQuery. User can ignore such objects by employing one of the provided filter mechanisms.
\param[in] origin Origin of the ray.
\param[in] unitDir Normalized direction of the ray.
\param[in] distance Length of the ray. Has to be in the [0, inf) range.
\param[out] hitCall Raycast hit buffer or callback object used to report raycast hits.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] filterData Filtering data passed to the filter shader.
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking.
\param[in] cache Cached hit shape (optional). Ray is tested against cached shape first. If no hit is found the ray gets queried against the scene.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\param[in] queryFlags Optional flags controlling the query.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
@see PxRaycastCallback PxRaycastBuffer PxQueryFilterData PxQueryFilterCallback PxQueryCache PxRaycastHit PxQueryFlag PxQueryFlag::eANY_HIT PxGeometryQueryFlag
*/
virtual bool raycast(const PxVec3& origin, const PxVec3& unitDir, const PxReal distance,
PxRaycastCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Performs a sweep test against objects in the scene, returns results in a PxSweepBuffer object
or via a custom user callback implementation inheriting from PxSweepCallback.
\note Touching hits are not ordered.
\note If a shape from the scene is already overlapping with the query shape in its starting position,
the hit is returned unless eASSUME_NO_INITIAL_OVERLAP was specified.
\param[in] geometry Geometry of object to sweep (supported types are: box, sphere, capsule, convex).
\param[in] pose Pose of the sweep object.
\param[in] unitDir Normalized direction of the sweep.
\param[in] distance Sweep distance. Needs to be in [0, inf) range and >0 if eASSUME_NO_INITIAL_OVERLAP was specified. Will be clamped to PX_MAX_SWEEP_DISTANCE.
\param[out] hitCall Sweep hit buffer or callback object used to report sweep hits.
\param[in] hitFlags Specifies which properties per hit should be computed and returned via the hit callback.
\param[in] filterData Filtering data and simple logic.
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to be blocking.
\param[in] cache Cached hit shape (optional). Sweep is performed against cached shape first. If no hit is found the sweep gets queried against the scene.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\param[in] inflation This parameter creates a skin around the swept geometry which increases its extents for sweeping. The sweep will register a hit as soon as the skin touches a shape, and will return the corresponding distance and normal.
Note: ePRECISE_SWEEP doesn't support inflation. Therefore the sweep will be performed with zero inflation.
\param[in] queryFlags Optional flags controlling the query.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
@see PxSweepCallback PxSweepBuffer PxQueryFilterData PxQueryFilterCallback PxSweepHit PxQueryCache PxGeometryQueryFlag
*/
virtual bool sweep( const PxGeometry& geometry, const PxTransform& pose, const PxVec3& unitDir, const PxReal distance,
PxSweepCallback& hitCall, PxHitFlags hitFlags = PxHitFlag::eDEFAULT,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, const PxReal inflation = 0.0f, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
/**
\brief Performs an overlap test of a given geometry against objects in the scene, returns results in a PxOverlapBuffer object
or via a custom user callback implementation inheriting from PxOverlapCallback.
\note Filtering: returning eBLOCK from user filter for overlap queries will cause a warning (see #PxQueryHitType).
\param[in] geometry Geometry of object to check for overlap (supported types are: box, sphere, capsule, convex).
\param[in] pose Pose of the object.
\param[out] hitCall Overlap hit buffer or callback object used to report overlap hits.
\param[in] filterData Filtering data and simple logic. See #PxQueryFilterData #PxQueryFilterCallback
\param[in] filterCall Custom filtering logic (optional). Only used if the corresponding #PxQueryFlag flags are set. If NULL, all hits are assumed to overlap.
\param[in] cache Cached hit shape (optional). Overlap is performed against cached shape first. If no hit is found the overlap gets queried against the scene.
\param[in] queryFlags Optional flags controlling the query.
Note: Filtering is not executed for a cached shape if supplied; instead, if a hit is found, it is assumed to be a blocking hit.
Note: Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\return True if any touching or blocking hits were found or any hit was found in case PxQueryFlag::eANY_HIT was specified.
\note eBLOCK should not be returned from user filters for overlap(). Doing so will result in undefined behavior, and a warning will be issued.
\note If the PxQueryFlag::eNO_BLOCK flag is set, the eBLOCK will instead be automatically converted to an eTOUCH and the warning suppressed.
@see PxOverlapCallback PxOverlapBuffer PxHitFlags PxQueryFilterData PxQueryFilterCallback PxGeometryQueryFlag
*/
virtual bool overlap(const PxGeometry& geometry, const PxTransform& pose, PxOverlapCallback& hitCall,
const PxQueryFilterData& filterData = PxQueryFilterData(), PxQueryFilterCallback* filterCall = NULL,
const PxQueryCache* cache = NULL, PxGeometryQueryFlags queryFlags = PxGeometryQueryFlag::eDEFAULT) const = 0;
//@}
};
/**
\brief Traditional SQ system for PxScene.
Methods defined here are only available through the traditional PxScene API.
Thus PxSceneSQSystem effectively captures the scene-query related part of the PxScene API.
@see PxScene PxSceneQuerySystemBase
*/
class PxSceneSQSystem : public PxSceneQuerySystemBase
{
protected:
PxSceneSQSystem() {}
virtual ~PxSceneSQSystem() {}
public:
/** @name Scene Query
*/
//@{
/**
\brief Sets scene query update mode
\param[in] updateMode Scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
PX_FORCE_INLINE void setSceneQueryUpdateMode(PxSceneQueryUpdateMode::Enum updateMode) { setUpdateMode(updateMode); }
/**
\brief Gets scene query update mode
\return Current scene query update mode.
@see PxSceneQueryUpdateMode::Enum
*/
PX_FORCE_INLINE PxSceneQueryUpdateMode::Enum getSceneQueryUpdateMode() const { return getUpdateMode(); }
/**
\brief Retrieves the scene's internal scene query timestamp, increased each time a change to the
static scene query structure is performed.
\return scene query static timestamp
*/
PX_FORCE_INLINE PxU32 getSceneQueryStaticTimestamp() const { return getStaticTimestamp(); }
/**
\brief Flushes any changes to the scene query representation.
@see flushUpdates
*/
PX_FORCE_INLINE void flushQueryUpdates() { flushUpdates(); }
/**
\brief Forces dynamic trees to be immediately rebuilt.
\param[in] rebuildStaticStructure True to rebuild the dynamic tree containing static objects
\param[in] rebuildDynamicStructure True to rebuild the dynamic tree containing dynamic objects
@see PxSceneQueryDesc.dynamicTreeRebuildRateHint setDynamicTreeRebuildRateHint() getDynamicTreeRebuildRateHint()
*/
PX_FORCE_INLINE void forceDynamicTreeRebuild(bool rebuildStaticStructure, bool rebuildDynamicStructure)
{
if(rebuildStaticStructure)
forceRebuildDynamicTree(PX_SCENE_PRUNER_STATIC);
if(rebuildDynamicStructure)
forceRebuildDynamicTree(PX_SCENE_PRUNER_DYNAMIC);
}
/**
\brief Return the value of PxSceneQueryDesc::staticStructure that was set when creating the scene with PxPhysics::createScene
@see PxSceneQueryDesc::staticStructure, PxPhysics::createScene
*/
virtual PxPruningStructureType::Enum getStaticStructure() const = 0;
/**
\brief Return the value of PxSceneQueryDesc::dynamicStructure that was set when creating the scene with PxPhysics::createScene
@see PxSceneQueryDesc::dynamicStructure, PxPhysics::createScene
*/
virtual PxPruningStructureType::Enum getDynamicStructure() const = 0;
/**
\brief Executes scene queries update tasks.
This function will refit dirty shapes within the pruner and will execute a task to build a new AABB tree, which is
build on a different thread. The new AABB tree is built based on the dynamic tree rebuild hint rate. Once
the new tree is ready it will be commited in next fetchQueries call, which must be called after.
This function is equivalent to the following PxSceneQuerySystem calls:
Synchronous calls:
- PxSceneQuerySystemBase::flushUpdates()
- handle0 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_STATIC)
- handle1 = PxSceneQuerySystem::prepareSceneQueryBuildStep(PX_SCENE_PRUNER_DYNAMIC)
Asynchronous calls:
- PxSceneQuerySystem::sceneQueryBuildStep(handle0);
- PxSceneQuerySystem::sceneQueryBuildStep(handle1);
This function is part of the PxSceneSQSystem interface because it uses the PxScene task system under the hood. But
it calls PxSceneQuerySystem functions, which are independent from this system and could be called in a similar
fashion by a separate, possibly user-defined task manager.
\note If PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED is used, it is required to update the scene queries
using this function.
\param[in] completionTask if non-NULL, this task will have its refcount incremented in sceneQueryUpdate(), then
decremented when the scene is ready to have fetchQueries called. So the task will not run until the
application also calls removeReference().
\param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave
true unless the application is calling the PxTaskManager start/stopSimulation() methods itself.
@see PxSceneQueryUpdateMode::eBUILD_DISABLED_COMMIT_DISABLED
*/
virtual void sceneQueriesUpdate(PxBaseTask* completionTask = NULL, bool controlSimulation = true) = 0;
/**
\brief This checks to see if the scene queries update has completed.
This does not cause the data available for reading to be updated with the results of the scene queries update, it is simply a status check.
The bool will allow it to either return immediately or block waiting for the condition to be met so that it can return true
\param[in] block When set to true will block until the condition is met.
\return True if the results are available.
@see sceneQueriesUpdate() fetchResults()
*/
virtual bool checkQueries(bool block = false) = 0;
/**
This method must be called after sceneQueriesUpdate. It will wait for the scene queries update to finish. If the user makes an illegal scene queries update call,
the SDK will issue an error message.
If a new AABB tree build finished, then during fetchQueries the current tree within the pruning structure is swapped with the new tree.
\param[in] block When set to true will block until the condition is met, which is tree built task must finish running.
*/
virtual bool fetchQueries(bool block = false) = 0;
//@}
};
typedef PxU32 PxSQCompoundHandle;
typedef PxU32 PxSQPrunerHandle;
typedef void* PxSQBuildStepHandle;
/**
\brief Scene-queries external sub-system for PxScene-based objects.
The default PxScene has hardcoded support for 2 regular pruners + 1 compound pruner, but these interfaces
should work with multiple pruners.
Regular shapes are traditional PhysX shapes that belong to an actor. That actor can be a compound, i.e. it has
more than one shape. *All of these go to the regular pruners*. This is important because it might be misleading:
by default all shapes go to one of the two regular pruners, even shapes that belong to compound actors.
For compound actors, adding all the actor's shapes individually to the SQ system can be costly, since all the
corresponding bounds will always move together and remain close together - that can put a lot of stress on the
code that updates the SQ spatial structures. In these cases it can be more efficient to add the compound's bounds
(i.e. the actor's bounds) to the system, as the first level of a bounds hierarchy. The scene queries would then
be performed against the actor's bounds first, and only visit the shapes' bounds second. This is only useful
for actors that have more than one shape, i.e. compound actors. Such actors added to the SQ system are thus
called "SQ compounds". These objects are managed by the "compound pruner", which is only used when an explicit
SQ compound is added to the SQ system via the addSQCompound call. So in the end one has to distinguish between:
- a "compound shape", which is added to regular pruners as its own individual entity.
- an "SQ compound shape", which is added to the compound pruner as a subpart of an SQ compound actor.
A compound shape has an invalid compound ID, since it does not belong to an SQ compound.
An SQ compound shape has a valid compound ID, that identifies its SQ compound owner.
@see PxScene PxSceneQuerySystemBase
*/
class PxSceneQuerySystem : public PxSceneQuerySystemBase
{
protected:
PxSceneQuerySystem() {}
virtual ~PxSceneQuerySystem() {}
public:
/**
\brief Decrements the reference count of the object and releases it if the new reference count is zero.
*/
virtual void release() = 0;
/**
\brief Acquires a counted reference to this object.
This method increases the reference count of the object by 1. Decrement the reference count by calling release()
*/
virtual void acquireReference() = 0;
/**
\brief Preallocates internal arrays to minimize the amount of reallocations.
The system does not prevent more allocations than given numbers. It is legal to not call this function at all,
or to add more shapes to the system than the preallocated amounts.
\param[in] prunerIndex Index of pruner to preallocate (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene).
\param[in] nbShapes Expected number of (regular) shapes
*/
virtual void preallocate(PxU32 prunerIndex, PxU32 nbShapes) = 0;
/**
\brief Frees internal memory that may not be in-use anymore.
This is an entry point for reclaiming transient memory allocated at some point by the SQ system,
but which wasn't been immediately freed for performance reason. Calling this function might free
some memory, but it might also produce a new set of allocations in the next frame.
*/
virtual void flushMemory() = 0;
/**
\brief Adds a shape to the SQ system.
The same function is used to add either a regular shape, or a SQ compound shape.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[in] bounds Shape bounds, in world-space for regular shapes, in local-space for SQ compound shapes.
\param[in] transform Shape transform, in world-space for regular shapes, in local-space for SQ compound shapes.
\param[in] compoundHandle Handle of SQ compound owner, or NULL for regular shapes.
\param[in] hasPruningStructure True if the shape is part of a pruning structure. The structure will be merged later, adding the objects will not invalidate the pruner.
@see merge() PxPruningStructure
*/
virtual void addSQShape( const PxRigidActor& actor, const PxShape& shape, const PxBounds3& bounds,
const PxTransform& transform, const PxSQCompoundHandle* compoundHandle=NULL, bool hasPruningStructure=false) = 0;
/**
\brief Removes a shape from the SQ system.
The same function is used to remove either a regular shape, or a SQ compound shape.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
*/
virtual void removeSQShape(const PxRigidActor& actor, const PxShape& shape) = 0;
/**
\brief Updates a shape in the SQ system.
The same function is used to update either a regular shape, or a SQ compound shape.
The transforms are eager-evaluated, but the bounds are lazy-evaluated. This means that
the updated transform has to be passed to the update function, while the bounds are automatically
recomputed by the system whenever needed.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[in] transform New shape transform, in world-space for regular shapes, in local-space for SQ compound shapes.
*/
virtual void updateSQShape(const PxRigidActor& actor, const PxShape& shape, const PxTransform& transform) = 0;
/**
\brief Adds a compound to the SQ system.
\param[in] actor The compound actor
\param[in] shapes The compound actor's shapes
\param[in] bvh BVH structure containing the compound's shapes in local space
\param[in] transforms Shape transforms, in local-space
\return SQ compound handle
@see PxBVH PxCooking::createBVH
*/
virtual PxSQCompoundHandle addSQCompound(const PxRigidActor& actor, const PxShape** shapes, const PxBVH& bvh, const PxTransform* transforms) = 0;
/**
\brief Removes a compound from the SQ system.
\param[in] compoundHandle SQ compound handle (returned by addSQCompound)
*/
virtual void removeSQCompound(PxSQCompoundHandle compoundHandle) = 0;
/**
\brief Updates a compound in the SQ system.
The compound structures are immediately updated when the call occurs.
\param[in] compoundHandle SQ compound handle (returned by addSQCompound)
\param[in] compoundTransform New actor/compound transform, in world-space
*/
virtual void updateSQCompound(PxSQCompoundHandle compoundHandle, const PxTransform& compoundTransform) = 0;
/**
\brief Shift the data structures' origin by the specified vector.
Please refer to the notes of the similar function in PxScene.
\param[in] shift Translation vector to shift the origin by.
*/
virtual void shiftOrigin(const PxVec3& shift) = 0;
/**
\brief Visualizes the system's internal data-structures, for debugging purposes.
\param[in] prunerIndex Index of pruner to visualize (PX_SCENE_PRUNER_STATIC, PX_SCENE_PRUNER_DYNAMIC or PX_SCENE_COMPOUND_PRUNER when called from PxScene).
\param[out] out Filled with render output data
@see PxRenderOutput
*/
virtual void visualize(PxU32 prunerIndex, PxRenderOutput& out) const = 0;
/**
\brief Merges a pruning structure with the SQ system's internal pruners.
\param[in] pruningStructure The pruning structure to merge
@see PxPruningStructure
*/
virtual void merge(const PxPruningStructure& pruningStructure) = 0;
/**
\brief Shape to SQ-pruner-handle mapping function.
This function finds and returns the SQ pruner handle associated with a given (actor/shape) couple
that was previously added to the system. This is needed for the sync function.
\param[in] actor The shape's actor owner
\param[in] shape The shape itself
\param[out] prunerIndex Index of pruner the shape belongs to
\return Associated SQ pruner handle.
*/
virtual PxSQPrunerHandle getHandle(const PxRigidActor& actor, const PxShape& shape, PxU32& prunerIndex) const = 0;
/**
\brief Synchronizes the scene-query system with another system that references the same objects.
This function is used when the scene-query objects also exist in another system that can also update them. For example the scene-query objects
(used for raycast, overlap or sweep queries) might be driven by equivalent objects in an external rigid-body simulation engine. In this case
the rigid-body simulation engine computes the new poses and transforms, and passes them to the scene-query system using this function. It is
more efficient than calling updateSQShape on each object individually, since updateSQShape would end up recomputing the bounds already available
in the rigid-body engine.
\param[in] prunerIndex Index of pruner being synched (PX_SCENE_PRUNER_DYNAMIC for regular PhysX usage)
\param[in] handles Handles of updated objects
\param[in] indices Bounds & transforms indices of updated objects, i.e. object handles[i] has bounds[indices[i]] and transforms[indices[i]]
\param[in] bounds Array of bounds for all objects (not only updated bounds)
\param[in] transforms Array of transforms for all objects (not only updated transforms)
\param[in] count Number of updated objects
\param[in] ignoredIndices Optional bitmap of ignored indices, i.e. update is skipped if ignoredIndices[indices[i]] is set.
@see PxBounds3 PxTransform32 PxBitMap
*/
virtual void sync(PxU32 prunerIndex, const PxSQPrunerHandle* handles, const PxU32* indices, const PxBounds3* bounds, const PxTransform32* transforms, PxU32 count, const PxBitMap& ignoredIndices) = 0;
/**
\brief Finalizes updates made to the SQ system.
This function should be called after updates have been made to the SQ system, to fully reflect the changes
inside the internal pruners. In particular it should be called:
- after calls to updateSQShape
- after calls to sync
This function:
- recomputes bounds of manually updated shapes (i.e. either regular or SQ compound shapes modified by updateSQShape)
- updates dynamic pruners (refit operations)
- incrementally rebuilds AABB-trees
The amount of work performed in this function depends on PxSceneQueryUpdateMode.
@see PxSceneQueryUpdateMode updateSQShape() sync()
*/
virtual void finalizeUpdates() = 0;
/**
\brief Prepares asynchronous build step.
This is directly called (synchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there.
This function is called to let the system execute any necessary synchronous operation before the
asynchronous sceneQueryBuildStep() function is called.
If there is any work to do for the specific pruner, the function returns a pruner-specific handle that
will be passed to the corresponding, asynchronous sceneQueryBuildStep function.
\return A pruner-specific handle that will be sent to sceneQueryBuildStep if there is any work to do, i.e. to execute the corresponding sceneQueryBuildStep() call.
\param[in] prunerIndex Index of pruner being built. (PX_SCENE_PRUNER_STATIC or PX_SCENE_PRUNER_DYNAMIC when called by PxScene).
\return Null if there is no work to do, otherwise a pruner-specific handle.
@see PxSceneSQSystem::sceneQueriesUpdate sceneQueryBuildStep
*/
virtual PxSQBuildStepHandle prepareSceneQueryBuildStep(PxU32 prunerIndex) = 0;
/**
\brief Executes asynchronous build step.
This is directly called (asynchronously) by PxSceneSQSystem::sceneQueriesUpdate(). See the comments there.
This function incrementally builds the internal trees/pruners. It is called asynchronously, i.e. this can be
called from different threads for building multiple trees at the same time.
\param[in] handle Pruner-specific handle previously returned by the prepareSceneQueryBuildStep function.
@see PxSceneSQSystem::sceneQueriesUpdate prepareSceneQueryBuildStep
*/
virtual void sceneQueryBuildStep(PxSQBuildStepHandle handle) = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,407 | C | 45.283105 | 242 | 0.769625 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationTendon.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_TENDON_H
#define PX_ARTICULATION_TENDON_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#include "solver/PxSolverDefs.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxArticulationSpatialTendon;
class PxArticulationFixedTendon;
class PxArticulationLink;
/**
\brief Defines the low/high limits of the length of a tendon.
*/
class PxArticulationTendonLimit
{
public:
PxReal lowLimit;
PxReal highLimit;
};
/**
\brief Defines a spatial tendon attachment point on a link.
*/
class PxArticulationAttachment : public PxBase
{
public:
virtual ~PxArticulationAttachment() {}
/**
\brief Sets the spring rest length for the sub-tendon from the root to this leaf attachment.
Setting this on non-leaf attachments has no effect.
\param[in] restLength The rest length of the spring.
<b>Default:</b> 0
@see getRestLength(), isLeaf()
*/
virtual void setRestLength(const PxReal restLength) = 0;
/**
\brief Gets the spring rest length for the sub-tendon from the root to this leaf attachment.
\return The rest length.
@see setRestLength()
*/
virtual PxReal getRestLength() const = 0;
/**
\brief Sets the low and high limit on the length of the sub-tendon from the root to this leaf attachment.
Setting this on non-leaf attachments has no effect.
\param[in] parameters Struct with the low and high limit.
<b>Default:</b> (PX_MAX_F32, -PX_MAX_F32) (i.e. an invalid configuration that can only work if stiffness is zero)
@see PxArticulationTendonLimit, getLimitParameters(), isLeaf()
*/
virtual void setLimitParameters(const PxArticulationTendonLimit& parameters) = 0;
/**
\brief Gets the low and high limit on the length of the sub-tendon from the root to this leaf attachment.
\return Struct with the low and high limit.
@see PxArticulationTendonLimit, setLimitParameters()
*/
virtual PxArticulationTendonLimit getLimitParameters() const = 0;
/**
\brief Sets the attachment's relative offset in the link actor frame.
\param[in] offset The relative offset in the link actor frame.
@see getRelativeOffset()
*/
virtual void setRelativeOffset(const PxVec3& offset) = 0;
/**
\brief Gets the attachment's relative offset in the link actor frame.
\return The relative offset in the link actor frame.
@see setRelativeOffset()
*/
virtual PxVec3 getRelativeOffset() const = 0;
/**
\brief Sets the attachment coefficient.
\param[in] coefficient The scale that the distance between this attachment and its parent is multiplied by when summing up the spatial tendon's length.
@see getCoefficient()
*/
virtual void setCoefficient(const PxReal coefficient) = 0;
/**
\brief Gets the attachment coefficient.
\return The scale that the distance between this attachment and its parent is multiplied by when summing up the spatial tendon's length.
@see setCoefficient()
*/
virtual PxReal getCoefficient() const = 0;
/**
\brief Gets the articulation link.
\return The articulation link that this attachment is attached to.
*/
virtual PxArticulationLink* getLink() const = 0;
/**
\brief Gets the parent attachment.
\return The parent attachment.
*/
virtual PxArticulationAttachment* getParent() const = 0;
/**
\brief Indicates that this attachment is a leaf, and thus defines a sub-tendon from the root to this attachment.
\return True: This attachment is a leaf and has zero children; False: Not a leaf.
*/
virtual bool isLeaf() const = 0;
/**
\brief Gets the spatial tendon that the attachment is a part of.
\return The tendon.
@see PxArticulationSpatialTendon
*/
virtual PxArticulationSpatialTendon* getTendon() const = 0;
/**
\brief Releases the attachment.
\note Releasing the attachment is not allowed while the articulation is in a scene. In order to
release the attachment, remove and then re-add the articulation to the scene.
@see PxArticulationSpatialTendon::createAttachment()
*/
virtual void release() = 0;
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationAttachment"; }
protected:
PX_INLINE PxArticulationAttachment(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationAttachment(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief Defines a fixed-tendon joint on an articulation joint degree of freedom.
*/
class PxArticulationTendonJoint : public PxBase
{
public:
virtual ~PxArticulationTendonJoint() {}
/**
\brief Sets the tendon joint coefficient.
\param[in] axis The degree of freedom that the tendon joint operates on (must correspond to a degree of freedom of the associated link's incoming joint).
\param[in] coefficient The scale that the axis' joint position is multiplied by when summing up the fixed tendon's length.
\param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint.
\note RecipCoefficient is commonly expected to be 1/coefficient, but it can be set to different values to tune behavior; for example, zero can be used to
have a joint axis only participate in the length computation of the tendon, but not have any tendon force applied to it.
@see getCoefficient()
*/
virtual void setCoefficient(const PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient) = 0;
/**
\brief Gets the tendon joint coefficient.
\param[out] axis The degree of freedom that the tendon joint operates on.
\param[out] coefficient The scale that the axis' joint position is multiplied by when summing up the fixed tendon's length.
\param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint.
@see setCoefficient()
*/
virtual void getCoefficient(PxArticulationAxis::Enum& axis, PxReal& coefficient, PxReal& recipCoefficient) const = 0;
/**
\brief Gets the articulation link.
\return The articulation link (and its incoming joint in particular) that this tendon joint is associated with.
*/
virtual PxArticulationLink* getLink() const = 0;
/**
\brief Gets the parent tendon joint.
\return The parent tendon joint.
*/
virtual PxArticulationTendonJoint* getParent() const = 0;
/**
\brief Gets the tendon that the joint is a part of.
\return The tendon.
@see PxArticulationFixedTendon
*/
virtual PxArticulationFixedTendon* getTendon() const = 0;
/**
\brief Releases a tendon joint.
\note Releasing a tendon joint is not allowed while the articulation is in a scene. In order to
release the joint, remove and then re-add the articulation to the scene.
@see PxArticulationFixedTendon::createTendonJoint()
*/
virtual void release() = 0;
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationTendonJoint"; }
protected:
PX_INLINE PxArticulationTendonJoint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationTendonJoint(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief Common API base class shared by PxArticulationSpatialTendon and PxArticulationFixedTendon.
*/
class PxArticulationTendon : public PxBase
{
public:
/**
\brief Sets the spring stiffness term acting on the tendon length.
\param[in] stiffness The spring stiffness.
<b>Default:</b> 0
@see getStiffness()
*/
virtual void setStiffness(const PxReal stiffness) = 0;
/**
\brief Gets the spring stiffness of the tendon.
\return The spring stiffness.
@see setStiffness()
*/
virtual PxReal getStiffness() const = 0;
/**
\brief Sets the damping term acting both on the tendon length and tendon-length limits.
\param[in] damping The damping term.
<b>Default:</b> 0
@see getDamping()
*/
virtual void setDamping(const PxReal damping) = 0;
/**
\brief Gets the damping term acting both on the tendon length and tendon-length limits.
\return The damping term.
@see setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Sets the limit stiffness term acting on the tendon's length limits.
For spatial tendons, this parameter applies to all its leaf attachments / sub-tendons.
\param[in] stiffness The limit stiffness term.
<b>Default:</b> 0
@see getLimitStiffness()
*/
virtual void setLimitStiffness(const PxReal stiffness) = 0;
/**
\brief Gets the limit stiffness term acting on the tendon's length limits.
For spatial tendons, this parameter applies to all its leaf attachments / sub-tendons.
\return The limit stiffness term.
@see setLimitStiffness()
*/
virtual PxReal getLimitStiffness() const = 0;
/**
\brief Sets the length offset term for the tendon.
An offset defines an amount to be added to the accumulated length computed for the tendon. It allows the
application to actuate the tendon by shortening or lengthening it.
\param[in] offset The offset term. <b>Default:</b> 0
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
@see getOffset()
*/
virtual void setOffset(const PxReal offset, bool autowake = true) = 0;
/**
\brief Gets the length offset term for the tendon.
\return The offset term.
@see setOffset()
*/
virtual PxReal getOffset() const = 0;
/**
\brief Gets the articulation that the tendon is a part of.
\return The articulation.
@see PxArticulationReducedCoordinate
*/
virtual PxArticulationReducedCoordinate* getArticulation() const = 0;
/**
\brief Releases a tendon to remove it from the articulation and free its associated memory.
When an articulation is released, its attached tendons are automatically released.
\note Releasing a tendon is not allowed while the articulation is in a scene. In order to
release the tendon, remove and then re-add the articulation to the scene.
*/
virtual void release() = 0;
virtual ~PxArticulationTendon() {}
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxArticulationTendon(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationTendon(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief A spatial tendon that attaches to an articulation.
A spatial tendon attaches to multiple links in an articulation using a set of PxArticulationAttachments.
The tendon is defined as a tree of attachment points, where each attachment can have an arbitrary number of children.
Each leaf of the attachment tree defines a subtendon between itself and the root attachment. The subtendon then
applies forces at the leaf, and an equal but opposing force at the root, in order to satisfy the spring-damper and limit
constraints that the user sets up. Attachments in between the root and leaf do not exert any force on the articulation,
but define the geometry of the tendon from which the length is computed together with the attachment coefficients.
*/
class PxArticulationSpatialTendon : public PxArticulationTendon
{
public:
/**
\brief Creates an articulation attachment and adds it to the list of children in the parent attachment.
Creating an attachment is not allowed while the articulation is in a scene. In order to
add the attachment, remove and then re-add the articulation to the scene.
\param[in] parent The parent attachment. Can be NULL for the root attachment of a tendon.
\param[in] coefficient A user-defined scale that the accumulated length is scaled by.
\param[in] relativeOffset An offset vector in the link's actor frame to the point where the tendon attachment is attached to the link.
\param[in] link The link that this attachment is associated with.
\return The newly-created attachment if creation was successful, otherwise a null pointer.
@see releaseAttachment()
*/
virtual PxArticulationAttachment* createAttachment(PxArticulationAttachment* parent, const PxReal coefficient, const PxVec3 relativeOffset, PxArticulationLink* link) = 0;
/**
\brief Fills a user-provided buffer of attachment pointers with the set of attachments.
\param[in] userBuffer The user-provided buffer.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to attachments,
only as many as can fit are written. Use getNbAttachments to size for all attachments.
\param[in] startIndex Index of first attachment pointer to be retrieved.
\return The number of attachments that were filled into the user buffer.
@see getNbAttachments
*/
virtual PxU32 getAttachments(PxArticulationAttachment** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of attachments in the tendon.
\return The number of attachments.
*/
virtual PxU32 getNbAttachments() const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationSpatialTendon"; }
virtual ~PxArticulationSpatialTendon() {}
protected:
PX_INLINE PxArticulationSpatialTendon(PxType concreteType, PxBaseFlags baseFlags) : PxArticulationTendon(concreteType, baseFlags) {}
PX_INLINE PxArticulationSpatialTendon(PxBaseFlags baseFlags) : PxArticulationTendon(baseFlags) {}
};
/**
\brief A fixed tendon that can be used to link multiple degrees of freedom of multiple articulation joints via length and limit constraints.
Fixed tendons allow the simulation of coupled relationships between joint degrees of freedom in an articulation. Fixed tendons do not allow
linking arbitrary joint axes of the articulation: The respective joints must all be directly connected to each other in the articulation structure,
i.e. each of the joints in the tendon must be connected by a single articulation link to another joint in the same tendon. This implies both that
1) fixed tendons can branch along a branching articulation; and 2) they cannot be used to create relationships between axes in a spherical joint with
more than one degree of freedom. Locked joint axes or fixed joints are currently not supported.
*/
class PxArticulationFixedTendon : public PxArticulationTendon
{
public:
/**
\brief Creates an articulation tendon joint and adds it to the list of children in the parent tendon joint.
Creating a tendon joint is not allowed while the articulation is in a scene. In order to
add the joint, remove and then re-add the articulation to the scene.
\param[in] parent The parent tendon joint. Can be NULL for the root tendon joint of a tendon.
\param[in] axis The degree of freedom that this tendon joint is associated with.
\param[in] coefficient A user-defined scale that the accumulated tendon length is scaled by.
\param[in] recipCoefficient The scale that the tendon's response is multiplied by when applying to this tendon joint.
\param[in] link The link (and the link's incoming joint in particular) that this tendon joint is associated with.
\return The newly-created tendon joint if creation was successful, otherwise a null pointer.
\note
- The axis motion must not be configured as PxArticulationMotion::eLOCKED.
- The axis cannot be part of a fixed joint, i.e. joint configured as PxArticulationJointType::eFIX.
@see PxArticulationTendonJoint PxArticulationAxis
*/
virtual PxArticulationTendonJoint* createTendonJoint(PxArticulationTendonJoint* parent, PxArticulationAxis::Enum axis, const PxReal coefficient, const PxReal recipCoefficient, PxArticulationLink* link) = 0;
/**
\brief Fills a user-provided buffer of tendon-joint pointers with the set of tendon joints.
\param[in] userBuffer The user-provided buffer.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendon joints,
only as many as can fit are written. Use getNbTendonJoints to size for all tendon joints.
\param[in] startIndex Index of first tendon joint pointer to be retrieved.
\return The number of tendon joints filled into the user buffer.
@see getNbTendonJoints
*/
virtual PxU32 getTendonJoints(PxArticulationTendonJoint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of tendon joints in the tendon.
\return The number of tendon joints.
*/
virtual PxU32 getNbTendonJoints() const = 0;
/**
\brief Sets the spring rest length of the tendon.
The accumulated "length" of a fixed tendon is a linear combination of the joint axis positions that the tendon is
associated with, scaled by the respective tendon joints' coefficients. As such, when the joint positions of all
joints are zero, the accumulated length of a fixed tendon is zero.
The spring of the tendon is not exerting any force on the articulation when the rest length is equal to the
tendon's accumulated length plus the tendon offset.
\param[in] restLength The spring rest length of the tendon.
@see getRestLength()
*/
virtual void setRestLength(const PxReal restLength) = 0;
/**
\brief Gets the spring rest length of the tendon.
\return The spring rest length of the tendon.
@see setRestLength()
*/
virtual PxReal getRestLength() const = 0;
/**
\brief Sets the low and high limit on the length of the tendon.
\param[in] parameter Struct with the low and high limit.
The limits, together with the damping and limit stiffness parameters, act on the accumulated length of the tendon.
@see PxArticulationTendonLimit getLimitParameters() setRestLength()
*/
virtual void setLimitParameters(const PxArticulationTendonLimit& parameter) = 0;
/**
\brief Gets the low and high limit on the length of the tendon.
\return Struct with the low and high limit.
@see PxArticulationTendonLimit setLimitParameters()
*/
virtual PxArticulationTendonLimit getLimitParameters() const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationFixedTendon"; }
virtual ~PxArticulationFixedTendon() {}
protected:
PX_INLINE PxArticulationFixedTendon(PxType concreteType, PxBaseFlags baseFlags) : PxArticulationTendon(concreteType, baseFlags) {}
PX_INLINE PxArticulationFixedTendon(PxBaseFlags baseFlags) : PxArticulationTendon(baseFlags) {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 21,144 | C | 34.838983 | 210 | 0.742575 |
NVIDIA-Omniverse/PhysX/physx/include/PxSparseGridParams.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SPARSE_GRID_PARAMS_H
#define PX_SPARSE_GRID_PARAMS_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxMath.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Parameters to define the sparse grid settings like grid spacing, maximal number of subgrids etc.
*/
struct PxSparseGridParams
{
/**
\brief Default constructor.
*/
PX_INLINE PxSparseGridParams()
{
maxNumSubgrids = 512;
subgridSizeX = 32;
subgridSizeY = 32;
subgridSizeZ = 32;
gridSpacing = 0.2f;
haloSize = 1;
}
/**
\brief Copy constructor.
*/
PX_CUDA_CALLABLE PX_INLINE PxSparseGridParams(const PxSparseGridParams& params)
{
maxNumSubgrids = params.maxNumSubgrids;
subgridSizeX = params.subgridSizeX;
subgridSizeY = params.subgridSizeY;
subgridSizeZ = params.subgridSizeZ;
gridSpacing = params.gridSpacing;
haloSize = params.haloSize;
}
PX_CUDA_CALLABLE PX_INLINE PxU32 getNumCellsPerSubgrid() const
{
return subgridSizeX * subgridSizeY * subgridSizeZ;
}
PX_CUDA_CALLABLE PX_INLINE PxReal getSqrt3dx() const
{
return PxSqrt(3.0f) * gridSpacing;
}
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault()
{
*this = PxSparseGridParams();
}
/**
\brief Assignment operator
*/
PX_INLINE void operator = (const PxSparseGridParams& params)
{
maxNumSubgrids = params.maxNumSubgrids;
subgridSizeX = params.subgridSizeX;
subgridSizeY = params.subgridSizeY;
subgridSizeZ = params.subgridSizeZ;
gridSpacing = params.gridSpacing;
haloSize = params.haloSize;
}
PxU32 maxNumSubgrids; //!< Maximum number of subgrids
PxReal gridSpacing; //!< Grid spacing for the grid
PxU16 subgridSizeX; //!< Subgrid resolution in x dimension (must be an even number)
PxU16 subgridSizeY; //!< Subgrid resolution in y dimension (must be an even number)
PxU16 subgridSizeZ; //!< Subgrid resolution in z dimension (must be an even number)
PxU16 haloSize; //!< Number of halo cell layers around every subgrid cell. Only 0 and 1 are valid values
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,881 | C | 31.35 | 109 | 0.730224 |
NVIDIA-Omniverse/PhysX/physx/include/PxMPMMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_MPM_MATERIAL_H
#define PX_MPM_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxParticleMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief MPM material models
*/
struct PxMPMMaterialModel
{
enum Enum
{
eATTACHED = 1 << 0, //!< Marker to indicate that all particles with an attached material should be treated as attached to whatever object they are located in
eNEO_HOOKEAN = 1 << 1, //!< A Neo-Hookean material model will be used
eELASTIC = 1 << 2, //!< A corotaional cauchy strain based material model will be used
eSNOW = 1 << 3, //!< A corotaional cauchy strain based material model with strain limiting and hardening will be used
eSAND = 1 << 4, //!< A Ducker-Prager elastoplasticity material model will be used
eVON_MISES = 1 << 5 //!< A von Mises material model will be used
};
};
/**
\brief MPM surface types that influence interaction between particles and obstacles
*/
struct PxMPMSurfaceType
{
enum Enum
{
eDEFAULT = 0, //!< Normal surface with friction in tangential direction
eSTICKY = 1 << 0, //!< Surface will always have friction in the tangential and the normal direction
eSLIPPERY = 1 << 1 //!< Surface will not cause any friction
};
};
/**
\brief Optional MPM modes that improve the quality of fracture and/or cutting
*/
struct PxMPMCuttingFlag
{
enum Enum
{
eNONE = 0, //!< No special processing to support cutting will be performed
eSUPPORT_THIN_BLADES = 1 << 0, //!< Special collision detection will be performed to improve support for blade like objects that are thinner than the mpm grid spacing
eENABLE_DAMAGE_TRACKING = 1 << 1 //!< A damage value will get updated on every particle to simulate material weakening to get more realistic crack propagation
};
};
typedef PxFlags<PxMPMCuttingFlag::Enum,PxU16> PxMPMCuttingFlags;
PX_FLAGS_OPERATORS(PxMPMCuttingFlag::Enum,PxU16)
class PxScene;
/**
\brief Material class to represent a set of MPM particle material properties.
@see PxPhysics.createMPMMaterial
*/
class PxMPMMaterial : public PxParticleMaterial
{
public:
/**
\brief Sets stretch and shear damping which dampens stretch and shear motion of MPM bodies. The effect is comparable to viscosity for fluids.
\param[in] stretchAndShearDamping The stretch and shear damping
@see getStretchAndShearDamping()
*/
virtual void setStretchAndShearDamping(PxReal stretchAndShearDamping) = 0;
/**
\brief Retrieves the stretch and shear damping.
\return The stretch and shear damping
@see setStretchAndShearDamping()
*/
virtual PxReal getStretchAndShearDamping() const = 0;
/**
\brief Sets the rotational damping which dampens rotations of mpm bodies
\param[in] rotationalDamping The rotational damping
@see getRotationalDamping()
*/
virtual void setRotationalDamping(PxReal rotationalDamping) = 0;
/**
\brief Retrieves the rotational damping.
\return The rotational damping
@see setRotationalDamping()
*/
virtual PxReal getRotationalDamping() const = 0;
/**
\brief Sets density which influences the body's weight
\param[in] density The material's density
@see getDensity()
*/
virtual void setDensity(PxReal density) = 0;
/**
\brief Retrieves the density value.
\return The density
@see setDensity()
*/
virtual PxReal getDensity() const = 0;
/**
\brief Sets the material model which influences interaction between MPM particles
\param[in] materialModel The material model
@see getMaterialModel()
*/
virtual void setMaterialModel(PxMPMMaterialModel::Enum materialModel) = 0;
/**
\brief Retrieves the material model.
\return The material model
@see setMaterialModel()
*/
virtual PxMPMMaterialModel::Enum getMaterialModel() const = 0;
/**
\brief Sets the cutting flags which can enable damage tracking or thin blade support
\param[in] cuttingFlags The cutting flags
@see getCuttingFlags()
*/
virtual void setCuttingFlags(PxMPMCuttingFlags cuttingFlags) = 0;
/**
\brief Retrieves the cutting flags.
\return The cutting flags
@see setCuttingFlags()
*/
virtual PxMPMCuttingFlags getCuttingFlags() const = 0;
/**
\brief Sets the sand friction angle, only applied if the material model is set to sand
\param[in] sandFrictionAngle The sand friction angle
@see getSandFrictionAngle()
*/
virtual void setSandFrictionAngle(PxReal sandFrictionAngle) = 0;
/**
\brief Retrieves the sand friction angle.
\return The sand friction angle
@see setSandFrictionAngle()
*/
virtual PxReal getSandFrictionAngle() const = 0;
/**
\brief Sets the yield stress, only applied if the material model is set to Von Mises
\param[in] yieldStress The yield stress
@see getYieldStress()
*/
virtual void setYieldStress(PxReal yieldStress) = 0;
/**
\brief Retrieves the yield stress.
\return The yield stress
@see setYieldStress()
*/
virtual PxReal getYieldStress() const = 0;
/**
\brief Set material to plastic
\param[in] isPlastic True if plastic
@see getIsPlastic()
*/
virtual void setIsPlastic(bool isPlastic) = 0;
/**
\brief Returns true if material is plastic
\return True if plastic
@see setIsPlastic()
*/
virtual bool getIsPlastic() const = 0;
/**
\brief Sets Young's modulus which defines the body's stiffness
\param[in] young Young's modulus. <b>Range:</b> [0, PX_MAX_F32)
@see getYoungsModulus()
*/
virtual void setYoungsModulus(PxReal young) = 0;
/**
\brief Retrieves the Young's modulus value.
\return The Young's modulus value.
@see setYoungsModulus()
*/
virtual PxReal getYoungsModulus() const = 0;
/**
\brief Sets Poisson's ratio defines the body's volume preservation. Completely incompressible materials have a Poisson ratio of 0.5 which will lead to numerical problems.
\param[in] poisson Poisson's ratio. <b>Range:</b> [0, 0.5)
@see getPoissons()
*/
virtual void setPoissons(PxReal poisson) = 0;
/**
\brief Retrieves the Poisson's ratio.
\return The Poisson's ratio.
@see setPoissons()
*/
virtual PxReal getPoissons() const = 0;
/**
\brief Sets material hardening coefficient
Tendency to get more rigid under compression. <b>Range:</b> [0, PX_MAX_F32)
\param[in] hardening Material hardening coefficient.
@see getHardening
*/
virtual void setHardening(PxReal hardening) = 0;
/**
\brief Retrieves the hardening coefficient.
\return The hardening coefficient.
@see setHardening()
*/
virtual PxReal getHardening() const = 0;
/**
\brief Sets material critical compression coefficient
Compression clamping threshold (higher means more compression is allowed before yield). <b>Range:</b> [0, 1)
\param[in] criticalCompression Material critical compression coefficient.
@see getCriticalCompression
*/
virtual void setCriticalCompression(PxReal criticalCompression) = 0;
/**
\brief Retrieves the critical compression coefficient.
\return The criticalCompression coefficient.
@see setCriticalCompression()
*/
virtual PxReal getCriticalCompression() const = 0;
/**
\brief Sets material critical stretch coefficient
Stretch clamping threshold (higher means more stretching is allowed before yield). <b>Range:</b> [0, 1]
\param[in] criticalStretch Material critical stretch coefficient.
@see getCriticalStretch
*/
virtual void setCriticalStretch(PxReal criticalStretch) = 0;
/**
\brief Retrieves the critical stretch coefficient.
\return The criticalStretch coefficient.
@see setCriticalStretch()
*/
virtual PxReal getCriticalStretch() const = 0;
/**
\brief Sets material tensile damage sensitivity coefficient
Sensitivity to tensile loads. The higher the sensitivity, the quicker damage will occur under tensile loads. <b>Range:</b> [0, PX_MAX_U32)
\param[in] tensileDamageSensitivity Material tensile damage sensitivity coefficient.
@see getTensileDamageSensitivity
*/
virtual void setTensileDamageSensitivity(PxReal tensileDamageSensitivity) = 0;
/**
\brief Retrieves the tensile damage sensitivity coefficient.
\return The tensileDamageSensitivity coefficient.
@see setTensileDamageSensitivity()
*/
virtual PxReal getTensileDamageSensitivity() const = 0;
/**
\brief Sets material compressive damage sensitivity coefficient
Sensitivity to compressive loads. The higher the sensitivity, the quicker damage will occur under compressive loads <b>Range:</b> [0, PX_MAX_U32)
\param[in] compressiveDamageSensitivity Material compressive damage sensitivity coefficient.
@see getCompressiveDamageSensitivity
*/
virtual void setCompressiveDamageSensitivity(PxReal compressiveDamageSensitivity) = 0;
/**
\brief Retrieves the compressive damage sensitivity coefficient.
\return The compressiveDamageSensitivity coefficient.
@see setCompressiveDamageSensitivity()
*/
virtual PxReal getCompressiveDamageSensitivity() const = 0;
/**
\brief Sets material attractive force residual coefficient
Relative amount of attractive force a fully damaged particle can exert on other particles compared to an undamaged one. <b>Range:</b> [0, 1]
\param[in] attractiveForceResidual Material attractive force residual coefficient.
@see getAttractiveForceResidual
*/
virtual void setAttractiveForceResidual(PxReal attractiveForceResidual) = 0;
/**
\brief Retrieves the attractive force residual coefficient.
\return The attractiveForceResidual coefficient.
@see setAttractiveForceResidual()
*/
virtual PxReal getAttractiveForceResidual() const = 0;
virtual const char* getConcreteTypeName() const { return "PxMPMMaterial"; }
protected:
PX_INLINE PxMPMMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxParticleMaterial(concreteType, baseFlags) {}
PX_INLINE PxMPMMaterial(PxBaseFlags baseFlags) : PxParticleMaterial(baseFlags) {}
virtual ~PxMPMMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxMPMMaterial", PxParticleMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 11,907 | C | 27.556355 | 172 | 0.73419 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationTendonData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_TENDON_DATA_H
#define PX_ARTICULATION_TENDON_DATA_H
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief PxGpuSpatialTendonData
This data structure is to be used by the direct GPU API for spatial tendon data updates.
@see PxArticulationSpatialTendon PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuSpatialTendonData
{
public:
PxReal stiffness;
PxReal damping;
PxReal limitStiffness;
PxReal offset;
}
PX_ALIGN_SUFFIX(16);
/**
\brief PxGpuFixedTendonData
This data structure is to be used by the direct GPU API for fixed tendon data updates.
@see PxArticulationFixedTendon PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuFixedTendonData : public PxGpuSpatialTendonData
{
public:
PxReal lowLimit;
PxReal highLimit;
PxReal restLength;
PxReal padding;
}
PX_ALIGN_SUFFIX(16);
/**
\brief PxGpuTendonJointCoefficientData
This data structure is to be used by the direct GPU API for fixed tendon joint data updates.
@see PxArticulationTendonJoint PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuTendonJointCoefficientData
{
public:
PxReal coefficient;
PxReal recipCoefficient;
PxU32 axis;
PxU32 pad;
}
PX_ALIGN_SUFFIX(16);
/**
\brief PxGpuTendonAttachmentData
This data structure is to be used by the direct GPU API for spatial tendon attachment data updates.
@see PxArticulationAttachment PxScene::copyArticulationData PxScene::applyArticulationData
*/
PX_ALIGN_PREFIX(16)
class PxGpuTendonAttachmentData
{
public:
PxVec3 relativeOffset;
PxReal restLength;
PxReal coefficient;
PxReal lowLimit;
PxReal highLimit;
PxReal padding;
}
PX_ALIGN_SUFFIX(16);
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,590 | C | 28.677686 | 99 | 0.776602 |
NVIDIA-Omniverse/PhysX/physx/include/PxConeLimitedConstraint.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_CONE_LIMITED_CONSTRAINT_H
#define PX_CONE_LIMITED_CONSTRAINT_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxVec4.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A constraint descriptor for limiting movement to a conical region.
*/
struct PxConeLimitedConstraint
{
PxConeLimitedConstraint()
{
setToDefault();
}
/**
\brief Set values such that constraint is disabled.
*/
PX_INLINE void setToDefault()
{
mAxis = PxVec3(0.f, 0.f, 0.f);
mAngle = -1.f;
mLowLimit = -1.f;
mHighLimit = -1.f;
}
/**
\brief Checks for valitity.
\return true if the constaint is valid
*/
PX_INLINE bool isValid() const
{
//disabled
if (mAngle < 0.f && mLowLimit < 0.f && mHighLimit < 0.f)
{
return true;
}
if (!mAxis.isNormalized())
{
return false;
}
//negative signifies that cone is disabled
if (mAngle >= PxPi)
{
return false;
}
//negative signifies that distance limits are disabled
if (mLowLimit > mHighLimit && mHighLimit >= 0.0f && mLowLimit >= 0.0f)
{
return false;
}
return true;
}
PxVec3 mAxis; //!< Axis of the cone in actor space
PxReal mAngle; //!< Opening angle in radians, negative indicates unlimited
PxReal mLowLimit; //!< Minimum distance, negative indicates unlimited
PxReal mHighLimit; //!< Maximum distance, negative indicates unlimited
};
/**
\brief Compressed form of cone limit parameters
@see PxConeLimitedConstraint
*/
PX_ALIGN_PREFIX(16)
struct PxConeLimitParams
{
PX_CUDA_CALLABLE PxConeLimitParams() {}
PX_CUDA_CALLABLE PxConeLimitParams(const PxConeLimitedConstraint& coneLimitedConstraint) :
lowHighLimits(coneLimitedConstraint.mLowLimit, coneLimitedConstraint.mHighLimit, 0.0f, 0.0f),
axisAngle(coneLimitedConstraint.mAxis, coneLimitedConstraint.mAngle)
{
}
PxVec4 lowHighLimits; // [lowLimit, highLimit, unused, unused]
PxVec4 axisAngle; // [axis.x, axis.y, axis.z, angle]
}PX_ALIGN_SUFFIX(16);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,717 | C | 27.821705 | 95 | 0.732311 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_MATERIAL_H
#define PX_PARTICLE_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "foundation/PxSimpleTypes.h"
#include "PxBaseMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Material class to represent a set of particle material properties.
@see #PxPhysics.createPBDMaterial, #PxPhysics.createFLIPMaterial, #PxPhysics.createMPMMaterial
*/
class PxParticleMaterial : public PxBaseMaterial
{
public:
/**
\brief Sets friction
\param[in] friction Friction. <b>Range:</b> [0, PX_MAX_F32)
@see #getFriction()
*/
virtual void setFriction(PxReal friction) = 0;
/**
\brief Retrieves the friction value.
\return The friction value.
@see #setFriction()
*/
virtual PxReal getFriction() const = 0;
/**
\brief Sets velocity damping term
\param[in] damping Velocity damping term. <b>Range:</b> [0, PX_MAX_F32)
@see #getDamping
*/
virtual void setDamping(PxReal damping) = 0;
/**
\brief Retrieves the velocity damping term
\return The velocity damping term.
@see #setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Sets adhesion term
\param[in] adhesion adhesion coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getAdhesion
*/
virtual void setAdhesion(PxReal adhesion) = 0;
/**
\brief Retrieves the adhesion term
\return The adhesion term.
@see #setAdhesion()
*/
virtual PxReal getAdhesion() const = 0;
/**
\brief Sets gravity scale term
\param[in] scale gravity scale coefficient. <b>Range:</b> (-PX_MAX_F32, PX_MAX_F32)
@see #getAdhesion
*/
virtual void setGravityScale(PxReal scale) = 0;
/**
\brief Retrieves the gravity scale term
\return The gravity scale term.
@see #setAdhesion()
*/
virtual PxReal getGravityScale() const = 0;
/**
\brief Sets material adhesion radius scale. This is multiplied by the particle rest offset to compute the fall-off distance
at which point adhesion ceases to operate.
\param[in] scale Material adhesion radius scale. <b>Range:</b> [0, PX_MAX_F32)
@see #getAdhesionRadiusScale
*/
virtual void setAdhesionRadiusScale(PxReal scale) = 0;
/**
\brief Retrieves the adhesion radius scale.
\return The adhesion radius scale.
@see #setAdhesionRadiusScale()
*/
virtual PxReal getAdhesionRadiusScale() const = 0;
protected:
PX_INLINE PxParticleMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {}
PX_INLINE PxParticleMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {}
virtual ~PxParticleMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxParticleMaterial", PxBaseMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,408 | C | 27.816993 | 124 | 0.736388 |
NVIDIA-Omniverse/PhysX/physx/include/PxRigidBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_RIGID_BODY_H
#define PX_RIGID_BODY_H
/** \addtogroup physics
@{
*/
#include "PxRigidActor.h"
#include "PxForceMode.h"
#include "PxNodeIndex.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Collection of flags describing the behavior of a rigid body.
@see PxRigidBody.setRigidBodyFlag(), PxRigidBody.getRigidBodyFlags()
*/
struct PxRigidBodyFlag
{
enum Enum
{
/**
\brief Enables kinematic mode for the actor.
Kinematic actors are special dynamic actors that are not
influenced by forces (such as gravity), and have no momentum. They are considered to have infinite
mass and can be moved around the world using the setKinematicTarget() method. They will push
regular dynamic actors out of the way. Kinematics will not collide with static or other kinematic objects.
Kinematic actors are great for moving platforms or characters, where direct motion control is desired.
You can not connect Reduced joints to kinematic actors. Lagrange joints work ok if the platform
is moving with a relatively low, uniform velocity.
<b>Sleeping:</b>
\li Setting this flag on a dynamic actor will put the actor to sleep and set the velocities to 0.
\li If this flag gets cleared, the current sleep state of the actor will be kept.
\note kinematic actors are incompatible with CCD so raising this flag will automatically clear eENABLE_CCD
@see PxRigidDynamic.setKinematicTarget()
*/
eKINEMATIC = (1<<0), //!< Enable kinematic mode for the body.
/**
\brief Use the kinematic target transform for scene queries.
If this flag is raised, then scene queries will treat the kinematic target transform as the current pose
of the body (instead of using the actual pose). Without this flag, the kinematic target will only take
effect with respect to scene queries after a simulation step.
@see PxRigidDynamic.setKinematicTarget()
*/
eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES = (1<<1),
/**
\brief Enables swept integration for the actor.
If this flag is raised and CCD is enabled on the scene, then this body will be simulated by the CCD system to ensure that collisions are not missed due to
high-speed motion. Note individual shape pairs still need to enable PxPairFlag::eDETECT_CCD_CONTACT in the collision filtering to enable the CCD to respond to
individual interactions.
\note kinematic actors are incompatible with CCD so this flag will be cleared automatically when raised on a kinematic actor
*/
eENABLE_CCD = (1<<2), //!< Enable CCD for the body.
/**
\brief Enabled CCD in swept integration for the actor.
If this flag is raised and CCD is enabled, CCD interactions will simulate friction. By default, friction is disabled in CCD interactions because
CCD friction has been observed to introduce some simulation artifacts. CCD friction was enabled in previous versions of the SDK. Raising this flag will result in behavior
that is a closer match for previous versions of the SDK.
\note This flag requires PxRigidBodyFlag::eENABLE_CCD to be raised to have any effect.
*/
eENABLE_CCD_FRICTION = (1<<3),
/**
\brief Register a rigid body to dynamically adjust contact offset based on velocity. This can be used to achieve a CCD effect.
If both eENABLE_CCD and eENABLE_SPECULATIVE_CCD are set on the same body, then angular motions are handled by speculative
contacts (eENABLE_SPECULATIVE_CCD) while linear motions are handled by sweeps (eENABLE_CCD).
*/
eENABLE_SPECULATIVE_CCD = (1<<4),
/**
\brief Register a rigid body for reporting pose changes by the simulation at an early stage.
Sometimes it might be advantageous to get access to the new pose of a rigid body as early as possible and
not wait until the call to fetchResults() returns. Setting this flag will schedule the rigid body to get reported
in #PxSimulationEventCallback::onAdvance(). Please refer to the documentation of that callback to understand
the behavior and limitations of this functionality.
@see PxSimulationEventCallback::onAdvance()
*/
eENABLE_POSE_INTEGRATION_PREVIEW = (1<<5),
/**
\brief Permit CCD to limit maxContactImpulse. This is useful for use-cases like a destruction system but can cause visual artefacts so is not enabled by default.
*/
eENABLE_CCD_MAX_CONTACT_IMPULSE = (1<<6),
/**
\brief Carries over forces/accelerations between frames, rather than clearing them
*/
eRETAIN_ACCELERATIONS = (1<<7),
/**
\brief Forces kinematic-kinematic pairs notifications for this actor.
This flag overrides the global scene-level PxPairFilteringMode setting for kinematic actors.
This is equivalent to having PxPairFilteringMode::eKEEP for pairs involving this actor.
A particular use case is when you have a large amount of kinematic actors, but you are only
interested in interactions between a few of them. In this case it is best to use
PxSceneDesc.kineKineFilteringMode = PxPairFilteringMode::eKILL, and then raise the
eFORCE_KINE_KINE_NOTIFICATIONS flag on the small set of kinematic actors that need
notifications.
\note This has no effect if PxRigidBodyFlag::eKINEMATIC is not set.
\warning Changing this flag at runtime will not have an effect until you remove and re-add the actor to the scene.
@see PxPairFilteringMode PxSceneDesc.kineKineFilteringMode
*/
eFORCE_KINE_KINE_NOTIFICATIONS = (1<<8),
/**
\brief Forces static-kinematic pairs notifications for this actor.
Similar to eFORCE_KINE_KINE_NOTIFICATIONS, but for static-kinematic interactions.
\note This has no effect if PxRigidBodyFlag::eKINEMATIC is not set.
\warning Changing this flag at runtime will not have an effect until you remove and re-add the actor to the scene.
@see PxPairFilteringMode PxSceneDesc.staticKineFilteringMode
*/
eFORCE_STATIC_KINE_NOTIFICATIONS = (1<<9),
/**
\brief Enables computation of gyroscopic forces on the rigid body.
*/
eENABLE_GYROSCOPIC_FORCES = (1<<10),
/**
\brief Reserved for internal usage
*/
eRESERVED = (1<<15)
};
};
/**
\brief collection of set bits defined in PxRigidBodyFlag.
@see PxRigidBodyFlag
*/
typedef PxFlags<PxRigidBodyFlag::Enum,PxU16> PxRigidBodyFlags;
PX_FLAGS_OPERATORS(PxRigidBodyFlag::Enum,PxU16)
/**
\brief PxRigidBody is a base class shared between dynamic rigid body objects.
@see PxRigidActor
*/
class PxRigidBody : public PxRigidActor
{
public:
// Runtime modifications
/************************************************************************************************/
/** @name Mass Manipulation
*/
/**
\brief Sets the pose of the center of mass relative to the actor.
\note Changing this transform will not move the actor in the world!
\note Setting an unrealistic center of mass which is a long way from the body can make it difficult for
the SDK to solve constraints. Perhaps leading to instability and jittering bodies.
\note Changing this transform will not update the linear velocity reported by getLinearVelocity() to account
for the shift in center of mass. If the shift should be accounted for, the user should update the velocity
using setLinearVelocity().
<b>Default:</b> the identity transform
\param[in] pose Mass frame offset transform relative to the actor frame. <b>Range:</b> rigid body transform.
@see getCMassLocalPose() getLinearVelocity()
*/
virtual void setCMassLocalPose(const PxTransform& pose) = 0;
/**
\brief Retrieves the center of mass pose relative to the actor frame.
\return The center of mass pose relative to the actor frame.
@see setCMassLocalPose()
*/
virtual PxTransform getCMassLocalPose() const = 0;
/**
\brief Sets the mass of a dynamic actor.
The mass must be non-negative.
setMass() does not update the inertial properties of the body, to change the inertia tensor
use setMassSpaceInertiaTensor() or the PhysX extensions method #PxRigidBodyExt::updateMassAndInertia().
\note A value of 0 is interpreted as infinite mass.
\note Values of 0 are not permitted for instances of PxArticulationLink but are permitted for instances of PxRigidDynamic.
<b>Default:</b> 1.0
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] mass New mass value for the actor. <b>Range:</b> [0, PX_MAX_F32)
@see getMass() setMassSpaceInertiaTensor()
*/
virtual void setMass(PxReal mass) = 0;
/**
\brief Retrieves the mass of the actor.
\note A value of 0 is interpreted as infinite mass.
\return The mass of this actor.
@see setMass() setMassSpaceInertiaTensor()
*/
virtual PxReal getMass() const = 0;
/**
\brief Retrieves the inverse mass of the actor.
\return The inverse mass of this actor.
@see setMass() setMassSpaceInertiaTensor()
*/
virtual PxReal getInvMass() const = 0;
/**
\brief Sets the inertia tensor, using a parameter specified in mass space coordinates.
Note that such matrices are diagonal -- the passed vector is the diagonal.
If you have a non diagonal world/actor space inertia tensor(3x3 matrix). Then you need to
diagonalize it and set an appropriate mass space transform. See #setCMassLocalPose().
The inertia tensor elements must be non-negative.
\note A value of 0 in an element is interpreted as infinite inertia along that axis.
\note Values of 0 are not permitted for instances of PxArticulationLink but are permitted for instances of PxRigidDynamic.
<b>Default:</b> (1.0, 1.0, 1.0)
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] m New mass space inertia tensor for the actor.
@see getMassSpaceInertia() setMass() setCMassLocalPose()
*/
virtual void setMassSpaceInertiaTensor(const PxVec3& m) = 0;
/**
\brief Retrieves the diagonal inertia tensor of the actor relative to the mass coordinate frame.
This method retrieves a mass frame inertia vector.
\return The mass space inertia tensor of this actor.
\note A value of 0 in an element is interpreted as infinite inertia along that axis.
@see setMassSpaceInertiaTensor() setMass() setCMassLocalPose()
*/
virtual PxVec3 getMassSpaceInertiaTensor() const = 0;
/**
\brief Retrieves the diagonal inverse inertia tensor of the actor relative to the mass coordinate frame.
This method retrieves a mass frame inverse inertia vector.
\note A value of 0 in an element is interpreted as infinite inertia along that axis.
\return The mass space inverse inertia tensor of this actor.
@see setMassSpaceInertiaTensor() setMass() setCMassLocalPose()
*/
virtual PxVec3 getMassSpaceInvInertiaTensor() const = 0;
/************************************************************************************************/
/** @name Damping
*/
/**
\brief Sets the linear damping coefficient.
Zero represents no damping. The damping coefficient must be nonnegative.
<b>Default:</b> 0.05 for PxArticulationLink, 0.0 for PxRigidDynamic
\param[in] linDamp Linear damping coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see getLinearDamping() setAngularDamping()
*/
virtual void setLinearDamping(PxReal linDamp) = 0;
/**
\brief Retrieves the linear damping coefficient.
\return The linear damping coefficient associated with this actor.
@see setLinearDamping() getAngularDamping()
*/
virtual PxReal getLinearDamping() const = 0;
/**
\brief Sets the angular damping coefficient.
Zero represents no damping.
The angular damping coefficient must be nonnegative.
<b>Default:</b> 0.05
\param[in] angDamp Angular damping coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see getAngularDamping() setLinearDamping()
*/
virtual void setAngularDamping(PxReal angDamp) = 0;
/**
\brief Retrieves the angular damping coefficient.
\return The angular damping coefficient associated with this actor.
@see setAngularDamping() getLinearDamping()
*/
virtual PxReal getAngularDamping() const = 0;
/************************************************************************************************/
/** @name Velocity
*/
/**
\brief Retrieves the linear velocity of an actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\note The linear velocity is reported with respect to the rigid body's center of mass and not the actor frame origin.
\return The linear velocity of the actor.
@see PxRigidDynamic.setLinearVelocity() getAngularVelocity()
*/
virtual PxVec3 getLinearVelocity() const = 0;
/**
\brief Retrieves the angular velocity of the actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\return The angular velocity of the actor.
@see PxRigidDynamic.setAngularVelocity() getLinearVelocity()
*/
virtual PxVec3 getAngularVelocity() const = 0;
/**
\brief Lets you set the maximum linear velocity permitted for this actor.
With this function, you can set the maximum linear velocity permitted for this rigid body.
Higher linear velocities are clamped to this value.
Note: The linear velocity is clamped to the set value <i>before</i> the solver, which means that
the limit may still be momentarily exceeded.
<b>Default:</b> 100*PxTolerancesScale::length for PxArticulationLink, 1e^16 for PxRigidDynamic
\param[in] maxLinVel Max allowable linear velocity for actor. <b>Range:</b> [0, 1e^16)
@see getMaxAngularVelocity()
*/
virtual void setMaxLinearVelocity(PxReal maxLinVel) = 0;
/**
\brief Retrieves the maximum angular velocity permitted for this actor.
\return The maximum allowed angular velocity for this actor.
@see setMaxLinearVelocity
*/
virtual PxReal getMaxLinearVelocity() const = 0;
/**
\brief Lets you set the maximum angular velocity permitted for this actor.
For various internal computations, very quickly rotating actors introduce error
into the simulation, which leads to undesired results.
With this function, you can set the maximum angular velocity permitted for this rigid body.
Higher angular velocities are clamped to this value.
Note: The angular velocity is clamped to the set value <i>before</i> the solver, which means that
the limit may still be momentarily exceeded.
<b>Default:</b> 50.0 for PxArticulationLink, 100.0 for PxRigidDynamic
<b>Range:</b> [0, 1e^16)
\param[in] maxAngVel Max allowable angular velocity for actor.
@see getMaxAngularVelocity()
*/
virtual void setMaxAngularVelocity(PxReal maxAngVel) = 0;
/**
\brief Retrieves the maximum angular velocity permitted for this actor.
\return The maximum allowed angular velocity for this actor.
@see setMaxAngularVelocity
*/
virtual PxReal getMaxAngularVelocity() const = 0;
/************************************************************************************************/
/** @name Forces
*/
/**
\brief Applies a force (or impulse) defined in the global coordinate frame to the actor at its center of mass.
<b>This will not induce a torque</b>.
::PxForceMode determines if the force is to be conventional or impulsive.
Each actor has an acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION
and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same
accumulators and are just short hand for multiplying the vector parameter by inverse mass and then using PxForceMode::eACCELERATION and
PxForceMode::eVELOCITY_CHANGE respectively.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note if this is called on an articulation link, only the link is updated, not the entire articulation.
\note see #PxRigidBodyExt::computeVelocityDeltaFromImpulse for details of how to compute the change in linear velocity that
will arise from the application of an impulsive force, where an impulsive force is applied force multiplied by a timestep.
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the force is non-zero.
\param[in] force Force/Impulse to apply defined in the global frame.
\param[in] mode The mode to use when applying the force/impulse(see #PxForceMode)
\param[in] autowake Specify if the call should wake up the actor if it is currently asleep. If true and the current wake counter value
is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see PxForceMode addTorque
*/
virtual void addForce(const PxVec3& force, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true) = 0;
/**
\brief Applies an impulsive torque defined in the global coordinate frame to the actor.
::PxForceMode determines if the torque is to be conventional or impulsive.
Each actor has an angular acceleration and an angular velocity change accumulator which are directly modified using the modes
PxForceMode::eACCELERATION and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE
also modify these same accumulators and are just short hand for multiplying the vector parameter by inverse inertia and then
using PxForceMode::eACCELERATION and PxForceMode::eVELOCITY_CHANGE respectively.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note if this called on an articulation link, only the link is updated, not the entire articulation.
\note see #PxRigidBodyExt::computeVelocityDeltaFromImpulse for details of how to compute the change in angular velocity that
will arise from the application of an impulsive torque, where an impulsive torque is an applied torque multiplied by a timestep.
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the torque is non-zero.
\param[in] torque Torque to apply defined in the global frame. <b>Range:</b> torque vector
\param[in] mode The mode to use when applying the force/impulse(see #PxForceMode).
\param[in] autowake Specify if the call should wake up the actor if it is currently asleep. If true and the current wake counter value
is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see PxForceMode addForce()
*/
virtual void addTorque(const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE, bool autowake = true) = 0;
/**
\brief Clears the accumulated forces (sets the accumulated force back to zero).
Each actor has an acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION
and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same
accumulators (see PxRigidBody::addForce() for details); therefore the effect of calling clearForce(PxForceMode::eFORCE) is equivalent to calling
clearForce(PxForceMode::eACCELERATION), and the effect of calling clearForce(PxForceMode::eIMPULSE) is equivalent to calling
clearForce(PxForceMode::eVELOCITY_CHANGE).
::PxForceMode determines if the cleared force is to be conventional or impulsive.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\param[in] mode The mode to use when clearing the force/impulse(see #PxForceMode)
@see PxForceMode addForce
*/
virtual void clearForce(PxForceMode::Enum mode = PxForceMode::eFORCE) = 0;
/**
\brief Clears the impulsive torque defined in the global coordinate frame to the actor.
::PxForceMode determines if the cleared torque is to be conventional or impulsive.
Each actor has an angular acceleration and a velocity change accumulator which are directly modified using the modes PxForceMode::eACCELERATION
and PxForceMode::eVELOCITY_CHANGE respectively. The modes PxForceMode::eFORCE and PxForceMode::eIMPULSE also modify these same
accumulators (see PxRigidBody::addTorque() for details); therefore the effect of calling clearTorque(PxForceMode::eFORCE) is equivalent to calling
clearTorque(PxForceMode::eACCELERATION), and the effect of calling clearTorque(PxForceMode::eIMPULSE) is equivalent to calling
clearTorque(PxForceMode::eVELOCITY_CHANGE).
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\param[in] mode The mode to use when clearing the force/impulse(see #PxForceMode).
@see PxForceMode addTorque
*/
virtual void clearTorque(PxForceMode::Enum mode = PxForceMode::eFORCE) = 0;
/**
\brief Sets the impulsive force and torque defined in the global coordinate frame to the actor.
::PxForceMode determines if the cleared torque is to be conventional or impulsive.
\note The force modes PxForceMode::eIMPULSE and PxForceMode::eVELOCITY_CHANGE can not be applied to articulation links.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
@see PxForceMode addTorque
*/
virtual void setForceAndTorque(const PxVec3& force, const PxVec3& torque, PxForceMode::Enum mode = PxForceMode::eFORCE) = 0;
/**
\brief Raises or clears a particular rigid body flag.
See the list of flags #PxRigidBodyFlag
<b>Default:</b> no flags are set
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] flag The PxRigidBody flag to raise(set) or clear. See #PxRigidBodyFlag.
\param[in] value The new boolean value for the flag.
@see PxRigidBodyFlag getRigidBodyFlags()
*/
virtual void setRigidBodyFlag(PxRigidBodyFlag::Enum flag, bool value) = 0;
virtual void setRigidBodyFlags(PxRigidBodyFlags inFlags) = 0;
/**
\brief Reads the PxRigidBody flags.
See the list of flags #PxRigidBodyFlag
\return The values of the PxRigidBody flags.
@see PxRigidBodyFlag setRigidBodyFlag()
*/
virtual PxRigidBodyFlags getRigidBodyFlags() const = 0;
/**
\brief Sets the CCD minimum advance coefficient.
The CCD minimum advance coefficient is a value in the range [0, 1] that is used to control the minimum amount of time a body is integrated when
it has a CCD contact. The actual minimum amount of time that is integrated depends on various properties, including the relative speed and collision shapes
of the bodies involved in the contact. From these properties, a numeric value is calculated that determines the maximum distance (and therefore maximum time)
which these bodies could be integrated forwards that would ensure that these bodies did not pass through each-other. This value is then scaled by CCD minimum advance
coefficient to determine the amount of time that will be consumed in the CCD pass.
<b>Things to consider:</b>
A large value (approaching 1) ensures that the objects will always advance some time. However, larger values increase the chances of objects gently drifting through each-other in
scenes which the constraint solver can't converge, e.g. scenes where an object is being dragged through a wall with a constraint.
A value of 0 ensures that the pair of objects stop at the exact time-of-impact and will not gently drift through each-other. However, with very small/thin objects initially in
contact, this can lead to a large amount of time being dropped and increases the chances of jamming. Jamming occurs when the an object is persistently in contact with an object
such that the time-of-impact is 0, which results in no time being advanced for those objects in that CCD pass.
The chances of jamming can be reduced by increasing the number of CCD mass @see PxSceneDesc.ccdMaxPasses. However, increasing this number increases the CCD overhead.
\param[in] advanceCoefficient The CCD min advance coefficient. <b>Range:</b> [0, 1] <b>Default:</b> 0.15
*/
virtual void setMinCCDAdvanceCoefficient(PxReal advanceCoefficient) = 0;
/**
\brief Gets the CCD minimum advance coefficient.
\return The value of the CCD min advance coefficient.
@see setMinCCDAdvanceCoefficient
*/
virtual PxReal getMinCCDAdvanceCoefficient() const = 0;
/**
\brief Sets the maximum depenetration velocity permitted to be introduced by the solver.
This value controls how much velocity the solver can introduce to correct for penetrations in contacts.
\param[in] biasClamp The maximum velocity to de-penetrate by <b>Range:</b> (0, PX_MAX_F32].
*/
virtual void setMaxDepenetrationVelocity(PxReal biasClamp) = 0;
/**
\brief Returns the maximum depenetration velocity the solver is permitted to introduced.
This value controls how much velocity the solver can introduce to correct for penetrations in contacts.
\return The maximum penetration bias applied by the solver.
*/
virtual PxReal getMaxDepenetrationVelocity() const = 0;
/**
\brief Sets a limit on the impulse that may be applied at a contact. The maximum impulse at a contact between two dynamic or kinematic
bodies will be the minimum of the two limit values. For a collision between a static and a dynamic body, the impulse is limited
by the value for the dynamic body.
\param[in] maxImpulse the maximum contact impulse. <b>Range:</b> [0, PX_MAX_F32] <b>Default:</b> PX_MAX_F32
@see getMaxContactImpulse
*/
virtual void setMaxContactImpulse(PxReal maxImpulse) = 0;
/**
\brief Returns the maximum impulse that may be applied at a contact.
\return The maximum impulse that may be applied at a contact
@see setMaxContactImpulse
*/
virtual PxReal getMaxContactImpulse() const = 0;
/**
\brief Sets a distance scale whereby the angular influence of a contact on the normal constraint in a contact is
zeroed if normal.cross(offset) falls below this tolerance. Rather than acting as an absolute value, this tolerance
is scaled by the ratio rXn.dot(angVel)/normal.dot(linVel) such that contacts that have relatively larger angular velocity
than linear normal velocity (e.g. rolling wheels) achieve larger slop values as the angular velocity increases.
\param[in] slopCoefficient the Slop coefficient. <b>Range:</b> [0, PX_MAX_F32] <b>Default:</b> 0
@see getContactSlopCoefficient
*/
virtual void setContactSlopCoefficient(PxReal slopCoefficient) = 0;
/**
\brief Returns the contact slop coefficient.
\return The contact slop coefficient.
@see setContactSlopCoefficient
*/
virtual PxReal getContactSlopCoefficient() const = 0;
/**
\brief Returns the island node index
\return The island node index.
*/
virtual PxNodeIndex getInternalIslandNodeIndex() const = 0;
protected:
PX_INLINE PxRigidBody(PxType concreteType, PxBaseFlags baseFlags) : PxRigidActor(concreteType, baseFlags) {}
PX_INLINE PxRigidBody(PxBaseFlags baseFlags) : PxRigidActor(baseFlags) {}
virtual ~PxRigidBody() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidBody", PxRigidActor); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 29,286 | C | 39.732962 | 179 | 0.757188 |
NVIDIA-Omniverse/PhysX/physx/include/PxPBDParticleSystem.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PBD_PARTICLE_SYSTEM_H
#define PX_PBD_PARTICLE_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxParticleSystem.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
/**
\brief A particle system that uses the position based dynamics(PBD) solver.
The position based dynamics solver for particle systems supports behaviors like
fluid, cloth, inflatables etc.
*/
class PxPBDParticleSystem : public PxParticleSystem
{
public:
virtual ~PxPBDParticleSystem() {}
/**
\brief Set wind direction and intensity
\param[in] wind The wind direction and intensity
*/
virtual void setWind(const PxVec3& wind) = 0;
/**
\brief Retrieves the wind direction and intensity.
\return The wind direction and intensity
*/
virtual PxVec3 getWind() const = 0;
/**
\brief Set the fluid boundary density scale
Defines how strong of a contribution the boundary (typically a rigid surface) should have on a fluid particle's density.
\param[in] fluidBoundaryDensityScale <b>Range:</b> (0.0, 1.0)
*/
virtual void setFluidBoundaryDensityScale(PxReal fluidBoundaryDensityScale) = 0;
/**
\brief Return the fluid boundary density scale
\return the fluid boundary density scale
See #setFluidBoundaryDensityScale()
*/
virtual PxReal getFluidBoundaryDensityScale() const = 0;
/**
\brief Set the fluid rest offset
Two fluid particles will come to rest at a distance equal to twice the fluidRestOffset value.
\param[in] fluidRestOffset <b>Range:</b> (0, particleContactOffset)
*/
virtual void setFluidRestOffset(PxReal fluidRestOffset) = 0;
/**
\brief Return the fluid rest offset
\return the fluid rest offset
See #setFluidRestOffset()
*/
virtual PxReal getFluidRestOffset() const = 0;
/**
\brief Set the particle system grid size x dimension
\param[in] gridSizeX x dimension in the particle grid
*/
virtual void setGridSizeX(PxU32 gridSizeX) = 0;
/**
\brief Set the particle system grid size y dimension
\param[in] gridSizeY y dimension in the particle grid
*/
virtual void setGridSizeY(PxU32 gridSizeY) = 0;
/**
\brief Set the particle system grid size z dimension
\param[in] gridSizeZ z dimension in the particle grid
*/
virtual void setGridSizeZ(PxU32 gridSizeZ) = 0;
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxPBDParticleSystem"; }
protected:
PX_INLINE PxPBDParticleSystem(PxType concreteType, PxBaseFlags baseFlags) : PxParticleSystem(concreteType, baseFlags) {}
PX_INLINE PxPBDParticleSystem(PxBaseFlags baseFlags) : PxParticleSystem(baseFlags) {}
virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxPBDParticleSystem", PxParticleSystem); }
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,923 | C | 31.826666 | 147 | 0.705667 |
NVIDIA-Omniverse/PhysX/physx/include/PxFEMMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FEM_MATERIAL_H
#define PX_FEM_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxBaseMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxScene;
/**
\brief Material class to represent a set of FEM material properties.
@see PxPhysics.createFEMSoftBodyMaterial
*/
class PxFEMMaterial : public PxBaseMaterial
{
public:
/**
\brief Sets young's modulus which defines the body's stiffness
\param[in] young Young's modulus. <b>Range:</b> [0, PX_MAX_F32)
@see getYoungsModulus()
*/
virtual void setYoungsModulus(PxReal young) = 0;
/**
\brief Retrieves the young's modulus value.
\return The young's modulus value.
@see setYoungsModulus()
*/
virtual PxReal getYoungsModulus() const = 0;
/**
\brief Sets the Poisson's ratio which defines the body's volume preservation. Completely incompressible materials have a poisson ratio of 0.5. Its value should not be set to exactly 0.5 because this leads to numerical problems.
\param[in] poisson Poisson's ratio. <b>Range:</b> [0, 0.5)
@see getPoissons()
*/
virtual void setPoissons(PxReal poisson) = 0;
/**
\brief Retrieves the Poisson's ratio.
\return The Poisson's ratio.
@see setPoissons()
*/
virtual PxReal getPoissons() const = 0;
/**
\brief Sets the dynamic friction value which defines the strength of resistance when two objects slide relative to each other while in contact.
\param[in] dynamicFriction The dynamic friction value. <b>Range:</b> [0, PX_MAX_F32)
@see getDynamicFriction()
*/
virtual void setDynamicFriction(PxReal dynamicFriction) = 0;
/**
\brief Retrieves the dynamic friction value
\return The dynamic friction value
@see setDynamicFriction()
*/
virtual PxReal getDynamicFriction() const = 0;
protected:
PX_INLINE PxFEMMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {}
PX_INLINE PxFEMMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {}
virtual ~PxFEMMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxFEMMaterial", PxBaseMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,925 | C | 31.991596 | 229 | 0.736306 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationJointReducedCoordinate.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_JOINT_RC_H
#define PX_ARTICULATION_JOINT_RC_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#include "solver/PxSolverDefs.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A joint between two links in an articulation.
@see PxArticulationReducedCoordinate, PxArticulationLink
*/
class PxArticulationJointReducedCoordinate : public PxBase
{
public:
/**
\brief Gets the parent articulation link of this joint.
\return The parent link.
*/
virtual PxArticulationLink& getParentArticulationLink() const = 0;
/**
\brief Sets the joint pose in the parent link actor frame.
\param[in] pose The joint pose.
<b>Default:</b> The identity transform.
\note This call is not allowed while the simulation is running.
@see getParentPose
*/
virtual void setParentPose(const PxTransform& pose) = 0;
/**
\brief Gets the joint pose in the parent link actor frame.
\return The joint pose.
@see setParentPose
*/
virtual PxTransform getParentPose() const = 0;
/**
\brief Gets the child articulation link of this joint.
\return The child link.
*/
virtual PxArticulationLink& getChildArticulationLink() const = 0;
/**
\brief Sets the joint pose in the child link actor frame.
\param[in] pose The joint pose.
<b>Default:</b> The identity transform.
\note This call is not allowed while the simulation is running.
@see getChildPose
*/
virtual void setChildPose(const PxTransform& pose) = 0;
/**
\brief Gets the joint pose in the child link actor frame.
\return The joint pose.
@see setChildPose
*/
virtual PxTransform getChildPose() const = 0;
/**
\brief Sets the joint type (e.g. revolute).
\param[in] jointType The joint type to set.
\note Setting the joint type is not allowed while the articulation is in a scene.
In order to amend the joint type, remove and then re-add the articulation to the scene.
<b>Default:</b> PxArticulationJointType::eUNDEFINED
@see PxArticulationJointType, getJointType
*/
virtual void setJointType(PxArticulationJointType::Enum jointType) = 0;
/**
\brief Gets the joint type.
\return The joint type.
@see PxArticulationJointType, setJointType
*/
virtual PxArticulationJointType::Enum getJointType() const = 0;
/**
\brief Sets the joint motion for a given axis.
\param[in] axis The target axis.
\param[in] motion The motion type to set.
\note Setting the motion of joint axes is not allowed while the articulation is in a scene.
In order to set the motion, remove and then re-add the articulation to the scene.
<b>Default:</b> PxArticulationMotion::eLOCKED
@see PxArticulationAxis, PxArticulationMotion, getMotion
*/
virtual void setMotion(PxArticulationAxis::Enum axis, PxArticulationMotion::Enum motion) = 0;
/**
\brief Returns the joint motion for the given axis.
\param[in] axis The target axis.
\return The joint motion of the given axis.
@see PxArticulationAxis, PxArticulationMotion, setMotion
*/
virtual PxArticulationMotion::Enum getMotion(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint limits for a given axis.
- The motion of the corresponding axis should be set to PxArticulationMotion::eLIMITED in order for the limits to be enforced.
- The lower limit should be strictly smaller than the higher limit. If the limits should be equal, use PxArticulationMotion::eLOCKED
and an appropriate offset in the parent/child joint frames.
\param[in] axis The target axis.
\param[in] limit The joint limits.
\note This call is not allowed while the simulation is running.
\note For PxArticulationJointType::eSPHERICAL, limit.min and limit.max must both be in range [-Pi, Pi].
\note For PxArticulationJointType::eREVOLUTE, limit.min and limit.max must both be in range [-2*Pi, 2*Pi].
\note For PxArticulationJointType::eREVOLUTE_UNWRAPPED, limit.min and limit.max must both be in range [-PX_MAX_REAL, PX_MAX_REAL].
\note For PxArticulationJointType::ePRISMATIC, limit.min and limit.max must both be in range [-PX_MAX_REAL, PX_MAX_REAL].
<b>Default:</b> (0,0)
@see getLimitParams, PxArticulationAxis, PxArticulationLimit
*/
virtual void setLimitParams(PxArticulationAxis::Enum axis, const PxArticulationLimit& limit) = 0;
/**
\brief Returns the joint limits for a given axis.
\param[in] axis The target axis.
\return The joint limits.
@see setLimitParams, PxArticulationAxis, PxArticulationLimit
*/
virtual PxArticulationLimit getLimitParams(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Configures a joint drive for the given axis.
See PxArticulationDrive for parameter details; and the manual for further information, and the drives' implicit spring-damper (i.e. PD control) implementation in particular.
\param[in] axis The target axis.
\param[in] drive The drive parameters
\note This call is not allowed while the simulation is running.
@see getDriveParams, PxArticulationAxis, PxArticulationDrive
<b>Default:</b> PxArticulationDrive(0.0f, 0.0f, 0.0f, PxArticulationDriveType::eNONE)
*/
virtual void setDriveParams(PxArticulationAxis::Enum axis, const PxArticulationDrive& drive) = 0;
/**
\brief Gets the joint drive configuration for the given axis.
\param[in] axis The target axis.
\return The drive parameters.
@see setDriveParams, PxArticulationAxis, PxArticulationDrive
*/
virtual PxArticulationDrive getDriveParams(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint drive position target for the given axis.
The target units are linear units (equivalent to scene units) for a translational axis, or rad for a rotational axis.
\param[in] axis The target axis.
\param[in] target The target position.
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
\note This call is not allowed while the simulation is running.
\note For spherical joints, target must be in range [-Pi, Pi].
\note The target is specified in the parent frame of the joint. If Gp, Gc are the parent and child actor poses in the world frame and Lp, Lc are the parent and child joint frames expressed in the parent and child actor frames then the joint will drive the parent and child links to poses that obey Gp * Lp * J = Gc * Lc. For joints restricted to angular motion, J has the form PxTranfsorm(PxVec3(PxZero), PxExp(PxVec3(twistTarget, swing1Target, swing2Target))). For joints restricted to linear motion, J has the form PxTransform(PxVec3(XTarget, YTarget, ZTarget), PxQuat(PxIdentity)).
\note For spherical joints with more than 1 degree of freedom, the joint target angles taken together can collectively represent a rotation of greater than Pi around a vector. When this happens the rotation that matches the joint drive target is not the shortest path rotation. The joint pose J that is the outcome after driving to the target pose will always be the equivalent of the shortest path rotation.
@see PxArticulationAxis, getDriveTarget
<b>Default:</b> 0.0
*/
virtual void setDriveTarget(PxArticulationAxis::Enum axis, const PxReal target, bool autowake = true) = 0;
/**
\brief Returns the joint drive position target for the given axis.
\param[in] axis The target axis.
\return The target position.
@see PxArticulationAxis, setDriveTarget
*/
virtual PxReal getDriveTarget(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint drive velocity target for the given axis.
The target units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\param[in] axis The target axis.
\param[in] targetVel The target velocity.
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
\note This call is not allowed while the simulation is running.
@see PxArticulationAxis, getDriveVelocity
<b>Default:</b> 0.0
*/
virtual void setDriveVelocity(PxArticulationAxis::Enum axis, const PxReal targetVel, bool autowake = true) = 0;
/**
\brief Returns the joint drive velocity target for the given axis.
\param[in] axis The target axis.
\return The target velocity.
@see PxArticulationAxis, setDriveVelocity
*/
virtual PxReal getDriveVelocity(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint armature for the given axis.
- The armature is directly added to the joint-space spatial inertia of the corresponding axis.
- The armature is in mass units for a prismatic (i.e. linear) joint, and in mass units * (scene linear units)^2 for a rotational joint.
\param[in] axis The target axis.
\param[in] armature The joint axis armature.
\note This call is not allowed while the simulation is running.
@see PxArticulationAxis, getArmature
<b>Default:</b> 0.0
*/
virtual void setArmature(PxArticulationAxis::Enum axis, const PxReal armature) = 0;
/**
\brief Gets the joint armature for the given axis.
\param[in] axis The target axis.
\return The armature set on the given axis.
@see PxArticulationAxis, setArmature
*/
virtual PxReal getArmature(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint friction coefficient, which applies to all joint axes.
- The joint friction is unitless and relates the magnitude of the spatial force [F_trans, T_trans] transmitted from parent to child link to
the maximal friction force F_resist that may be applied by the solver to resist joint motion, per axis; i.e. |F_resist| <= coefficient * (|F_trans| + |T_trans|),
where F_resist may refer to a linear force or torque depending on the joint axis.
- The simulated friction effect is therefore similar to static and Coulomb friction. In order to simulate dynamic joint friction, use a joint drive with
zero stiffness and zero velocity target, and an appropriately dimensioned damping parameter.
\param[in] coefficient The joint friction coefficient.
\note This call is not allowed while the simulation is running.
@see getFrictionCoefficient
<b>Default:</b> 0.05
*/
virtual void setFrictionCoefficient(const PxReal coefficient) = 0;
/**
\brief Gets the joint friction coefficient.
\return The joint friction coefficient.
@see setFrictionCoefficient
*/
virtual PxReal getFrictionCoefficient() const = 0;
/**
\brief Sets the maximal joint velocity enforced for all axes.
- The solver will apply appropriate joint-space impulses in order to enforce the per-axis joint-velocity limit.
- The velocity units are linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\param[in] maxJointV The maximal per-axis joint velocity.
\note This call is not allowed while the simulation is running.
@see getMaxJointVelocity
<b>Default:</b> 100.0
*/
virtual void setMaxJointVelocity(const PxReal maxJointV) = 0;
/**
\brief Gets the maximal joint velocity enforced for all axes.
\return The maximal per-axis joint velocity.
@see setMaxJointVelocity
*/
virtual PxReal getMaxJointVelocity() const = 0;
/**
\brief Sets the joint position for the given axis.
- For performance, prefer PxArticulationCache::jointPosition to set joint positions in a batch articulation state update.
- Use PxArticulationReducedCoordinate::updateKinematic after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] axis The target axis.
\param[in] jointPos The joint position in linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis.
\note This call is not allowed while the simulation is running.
\note For PxArticulationJointType::eSPHERICAL, jointPos must be in range [-Pi, Pi].
\note For PxArticulationJointType::eREVOLUTE, jointPos must be in range [-2*Pi, 2*Pi].
\note For PxArticulationJointType::eREVOLUTE_UNWRAPPED, jointPos must be in range [-PX_MAX_REAL, PX_MAX_REAL].
\note For PxArticulationJointType::ePRISMATIC, jointPos must be in range [-PX_MAX_REAL, PX_MAX_REAL].
\note Joint position is specified in the parent frame of the joint. If Gp, Gc are the parent and child actor poses in the world frame and Lp, Lc are the parent and child joint frames expressed in the parent and child actor frames then the parent and child links will be given poses that obey Gp * Lp * J = Gc * Lc with J denoting the joint pose. For joints restricted to angular motion, J has the form PxTranfsorm(PxVec3(PxZero), PxExp(PxVec3(twistPos, swing1Pos, swing2Pos))). For joints restricted to linear motion, J has the form PxTransform(PxVec3(xPos, yPos, zPos), PxQuat(PxIdentity)).
\note For spherical joints with more than 1 degree of freedom, the input joint positions taken together can collectively represent a rotation of greater than Pi around a vector. When this happens the rotation that matches the joint positions is not the shortest path rotation. The joint pose J that is the outcome of setting and applying the joint positions will always be the equivalent of the shortest path rotation.
@see PxArticulationAxis, getJointPosition, PxArticulationCache::jointPosition, PxArticulationReducedCoordinate::updateKinematic
<b>Default:</b> 0.0
*/
virtual void setJointPosition(PxArticulationAxis::Enum axis, const PxReal jointPos) = 0;
/**
\brief Gets the joint position for the given axis, i.e. joint degree of freedom (DOF).
For performance, prefer PxArticulationCache::jointPosition to get joint positions in a batch query.
\param[in] axis The target axis.
\return The joint position in linear units (equivalent to scene units) for a translational axis, or radians for a rotational axis.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
@see PxArticulationAxis, setJointPosition, PxArticulationCache::jointPosition
*/
virtual PxReal getJointPosition(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Sets the joint velocity for the given axis.
- For performance, prefer PxArticulationCache::jointVelocity to set joint velocities in a batch articulation state update.
- Use PxArticulationReducedCoordinate::updateKinematic after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] axis The target axis.
\param[in] jointVel The joint velocity in linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\note This call is not allowed while the simulation is running.
@see PxArticulationAxis, getJointVelocity, PxArticulationCache::jointVelocity, PxArticulationReducedCoordinate::updateKinematic
<b>Default:</b> 0.0
*/
virtual void setJointVelocity(PxArticulationAxis::Enum axis, const PxReal jointVel) = 0;
/**
\brief Gets the joint velocity for the given axis.
For performance, prefer PxArticulationCache::jointVelocity to get joint velocities in a batch query.
\param[in] axis The target axis.
\return The joint velocity in linear units (equivalent to scene units) per second for a translational axis, or radians per second for a rotational axis.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
@see PxArticulationAxis, setJointVelocity, PxArticulationCache::jointVelocity
*/
virtual PxReal getJointVelocity(PxArticulationAxis::Enum axis) const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationJointReducedCoordinate"; }
virtual ~PxArticulationJointReducedCoordinate() {}
//public variables:
void* userData; //!< The user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxArticulationJointReducedCoordinate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationJointReducedCoordinate(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationJointReducedCoordinate", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 18,865 | C | 39.7473 | 594 | 0.751179 |
NVIDIA-Omniverse/PhysX/physx/include/PxIsosurfaceExtraction.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ISOSURFACE_EXTRACTION_H
#define PX_ISOSURFACE_EXTRACTION_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "PxSparseGridParams.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
/**
\brief Identifies filter type to be applied on the isosurface grid.
*/
struct PxIsosurfaceGridFilteringType
{
enum Enum
{
eNONE = 0, //!< No filtering
eSMOOTH = 1, //!< Gaussian-blur-like filtering
eGROW = 2, //!< A dilate/erode operation will be applied that makes the fluid grow approximately one cell size
eSHRINK = 3 //!< A dilate/erode operation will be applied that makes the fluid shrink approximately one cell size
};
};
/**
\brief Parameters to define the isosurface extraction settings like isosurface level, filtering etc.
*/
struct PxIsosurfaceParams
{
/**
\brief Default constructor.
*/
PX_INLINE PxIsosurfaceParams()
{
particleCenterToIsosurfaceDistance = 0.2f;
numMeshSmoothingPasses = 4;
numMeshNormalSmoothingPasses = 4;
gridFilteringFlags = 0;
gridSmoothingRadius = 0.2f;
}
/**
\brief Clears the filtering operations
*/
PX_INLINE void clearFilteringPasses()
{
gridFilteringFlags = 0;
}
/**
\brief Adds a smoothing pass after the existing ones
At most 32 smoothing passes can be defined. Every pass can repeat itself up to 4 times.
\param[in] operation The smoothing operation to add
\return The index of the smoothing pass that was added
*/
PX_INLINE PxU64 addGridFilteringPass(PxIsosurfaceGridFilteringType::Enum operation)
{
for (PxU32 i = 0; i < 32; ++i)
{
PxIsosurfaceGridFilteringType::Enum o;
if (!getGridFilteringPass(i, o))
{
setGridFilteringPass(i, operation);
return i;
}
}
return 0xFFFFFFFFFFFFFFFF;
}
/**
\brief Sets the operation of a smoothing pass
\param[in] passIndex The index of the smoothing pass whose operation should be set <b>Range:</b> [0, 31]
\param[in] operation The operation the modified smoothing will perform
*/
PX_INLINE void setGridFilteringPass(PxU32 passIndex, PxIsosurfaceGridFilteringType::Enum operation)
{
PX_ASSERT(passIndex < 32u);
PxU32 shift = passIndex * 2;
gridFilteringFlags &= ~(PxU64(3) << shift);
gridFilteringFlags |= PxU64(operation) << shift;
}
/**
\brief Returns the operation of a smoothing pass
\param[in] passIndex The index of the smoothing pass whose operation is requested <b>Range:</b> [0, 31]
\param[out] operation The operation the requested smoothing pass will perform
\return true if the requested pass performs an operation
*/
PX_INLINE bool getGridFilteringPass(PxU32 passIndex, PxIsosurfaceGridFilteringType::Enum& operation) const
{
PxU32 shift = passIndex * 2;
PxU64 v = gridFilteringFlags >> shift;
v &= 3; //Extract last 2 bits
operation = PxIsosurfaceGridFilteringType::Enum(v);
return operation != PxIsosurfaceGridFilteringType::eNONE;
}
PxReal particleCenterToIsosurfaceDistance; //!< Distance form a particle center to the isosurface
PxU32 numMeshSmoothingPasses; //!< Number of Taubin mesh postprocessing smoothing passes. Using an even number of passes lead to less shrinking.
PxU32 numMeshNormalSmoothingPasses; //!< Number of mesh normal postprocessing smoothing passes.
PxU64 gridFilteringFlags; //!< Encodes the smoothing steps to apply on the sparse grid. Use setGridSmoothingPass method to set up.
PxReal gridSmoothingRadius; //!< Gaussian blur smoothing kernel radius used for smoothing operations on the grid
};
/**
\brief Base class for isosurface extractors. Allows to register the data arrays for the isosurface and to obtain the number vertices/triangles in use.
*/
class PxIsosurfaceExtractor
{
public:
/**
\brief Returns the isosurface parameters.
\return The isosurfacesettings used for the isosurface extraction
*/
virtual PxIsosurfaceParams getIsosurfaceParams() const = 0;
/**
\brief Set the isosurface extraction parameters
Allows to configure the isosurface extraction by controlling threshold value, smoothing options etc.
\param[in] params A collection of settings to control the isosurface extraction
*/
virtual void setIsosurfaceParams(const PxIsosurfaceParams& params) = 0;
/**
\brief Returns the number of vertices that the current isosurface triangle mesh uses
\return The number of vertices currently in use
*/
virtual PxU32 getNumVertices() const = 0;
/**
\brief Returns the number of triangles that the current isosurface triangle mesh uses
\return The number of triangles currently in use
*/
virtual PxU32 getNumTriangles() const = 0;
/**
\brief Returns the maximum number of vertices that the isosurface triangle mesh can contain
\return The maximum number of vertices that can be genrated
*/
virtual PxU32 getMaxVertices() const = 0;
/**
\brief Returns the maximum number of triangles that the isosurface triangle mesh can contain
\return The maximum number of triangles that can be generated
*/
virtual PxU32 getMaxTriangles() const = 0;
/**
\brief Resizes the internal triangle mesh buffers.
If the output buffers are device buffers, nothing will get resized but new output buffers can be set using setResultBufferDevice.
For host side output buffers, temporary buffers will get resized. The new host side result buffers with the same size must be set using setResultBufferHost.
\param[in] maxNumVertices The maximum number of vertices the output buffer can hold
\param[in] maxNumTriangles The maximum number of triangles the ouput buffer can hold
*/
virtual void setMaxVerticesAndTriangles(PxU32 maxNumVertices, PxU32 maxNumTriangles) = 0;
/**
\brief The maximal number of particles the isosurface extractor can process
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles the isosurface extractor can process
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Releases the isosurface extractor instance and its data
*/
virtual void release() = 0;
/**
\brief Triggers the compuation of a new isosurface based on the specified particle locations
\param[in] deviceParticlePos A gpu pointer pointing to the start of the particle array
\param[in] numParticles The number of particles
\param[in] stream The stream on which all the gpu work will be performed
\param[in] phases A phase value per particle
\param[in] validPhaseMask A mask that specifies which phases should contribute to the isosurface. If the binary and operation
between this mask and the particle phase is non zero, then the particle will contribute to the isosurface
\param[in] activeIndices Optional array with indices of all active particles
\param[in] anisotropy1 Optional anisotropy information, x axis direction (xyz) and scale in w component
\param[in] anisotropy2 Optional anisotropy information, y axis direction (xyz) and scale in w component
\param[in] anisotropy3 Optional anisotropy information, z axis direction (xyz) and scale in w component
\param[in] anisotropyFactor A factor to multiply with the anisotropy scale
*/
virtual void extractIsosurface(PxVec4* deviceParticlePos, const PxU32 numParticles, CUstream stream, PxU32* phases = NULL, PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid,
PxU32* activeIndices = NULL, PxVec4* anisotropy1 = NULL, PxVec4* anisotropy2 = NULL, PxVec4* anisotropy3 = NULL, PxReal anisotropyFactor = 1.0f) = 0;
/**
\brief Allows to register the host buffers into which the final isosurface triangle mesh will get stored
\param[in] vertices A host buffer to store the vertices of the isosurface mesh
\param[in] triIndices A host buffer to store the triangles of the isosurface mesh
\param[in] normals A host buffer to store the normals of the isosurface mesh
*/
virtual void setResultBufferHost(PxVec4* vertices, PxU32* triIndices, PxVec4* normals = NULL) = 0;
/**
\brief Allows to register the host buffers into which the final isosurface triangle mesh will get stored
\param[in] vertices A device buffer to store the vertices of the isosurface mesh
\param[in] triIndices A device buffer to store the triangles of the isosurface mesh
\param[in] normals A device buffer to store the normals of the isosurface mesh
*/
virtual void setResultBufferDevice(PxVec4* vertices, PxU32* triIndices, PxVec4* normals) = 0;
/**
\brief Enables or disables the isosurface extractor
\param[in] enabled The boolean to set the extractor to enabled or disabled
*/
virtual void setEnabled(bool enabled) = 0;
/**
\brief Allows to query if the isosurface extractor is enabled
\return True if enabled, false otherwise
*/
virtual bool isEnabled() const = 0;
/**
\brief Destructor
*/
virtual ~PxIsosurfaceExtractor() {}
};
/**
\brief Base class for sparse grid based isosurface extractors. Allows to register the data arrays for the isosurface and to obtain the number vertices/triangles in use.
*/
class PxSparseGridIsosurfaceExtractor : public PxIsosurfaceExtractor
{
/**
\brief Returns the sparse grid parameters.
\return The sparse grid settings used for the isosurface extraction
*/
virtual PxSparseGridParams getSparseGridParams() const = 0;
/**
\brief Set the sparse grid parameters
Allows to configure cell size, number of subgrids etc.
\param[in] params A collection of settings to control the isosurface grid
*/
virtual void setSparseGridParams(const PxSparseGridParams& params) = 0;
};
/**
\brief Default implementation of a particle system callback to trigger the isosurface extraction. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the post solve task completed.
*/
class PxIsosurfaceCallback : public PxParticleSystemCallback
{
public:
/**
\brief Initializes the isosurface callback
\param[in] isosurfaceExtractor The isosurface extractor
\param[in] validPhaseMask The valid phase mask marking the phase bits that particles must have set in order to contribute to the isosurface
*/
void initialize(PxIsosurfaceExtractor* isosurfaceExtractor, PxU32 validPhaseMask = PxParticlePhaseFlag::eParticlePhaseFluid)
{
mIsosurfaceExtractor = isosurfaceExtractor;
mValidPhaseMask = validPhaseMask;
}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream)
{
mIsosurfaceExtractor->extractIsosurface(reinterpret_cast<PxVec4*>(gpuParticleSystem.mHostPtr->mUnsortedPositions_InvMass),
gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream, gpuParticleSystem.mHostPtr->mUnsortedPhaseArray, mValidPhaseMask);
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
private:
PxIsosurfaceExtractor* mIsosurfaceExtractor;
PxU32 mValidPhaseMask;
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 13,251 | C | 36.541076 | 189 | 0.755037 |
NVIDIA-Omniverse/PhysX/physx/include/PxFiltering.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FILTERING_H
#define PX_FILTERING_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxActor;
class PxShape;
/**
\brief Collection of flags describing the actions to take for a collision pair.
@see PxPairFlags PxSimulationFilterShader.filter() PxSimulationFilterCallback
*/
struct PxPairFlag
{
enum Enum
{
/**
\brief Process the contacts of this collision pair in the dynamics solver.
\note Only takes effect if the colliding actors are rigid bodies.
*/
eSOLVE_CONTACT = (1<<0),
/**
\brief Call contact modification callback for this collision pair
\note Only takes effect if the colliding actors are rigid bodies.
@see PxContactModifyCallback
*/
eMODIFY_CONTACTS = (1<<1),
/**
\brief Call contact report callback or trigger callback when this collision pair starts to be in contact.
If one of the two collision objects is a trigger shape (see #PxShapeFlag::eTRIGGER_SHAPE)
then the trigger callback will get called as soon as the other object enters the trigger volume.
If none of the two collision objects is a trigger shape then the contact report callback will get
called when the actors of this collision pair start to be in contact.
\note Only takes effect if the colliding actors are rigid bodies.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_FOUND = (1<<2),
/**
\brief Call contact report callback while this collision pair is in contact
If none of the two collision objects is a trigger shape then the contact report callback will get
called while the actors of this collision pair are in contact.
\note Triggers do not support this event. Persistent trigger contacts need to be tracked separately by observing eNOTIFY_TOUCH_FOUND/eNOTIFY_TOUCH_LOST events.
\note Only takes effect if the colliding actors are rigid bodies.
\note No report will get sent if the objects in contact are sleeping.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
\note If this flag gets enabled while a pair is in touch already, there will be no eNOTIFY_TOUCH_PERSISTS events until the pair loses and regains touch.
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_PERSISTS = (1<<3),
/**
\brief Call contact report callback or trigger callback when this collision pair stops to be in contact
If one of the two collision objects is a trigger shape (see #PxShapeFlag::eTRIGGER_SHAPE)
then the trigger callback will get called as soon as the other object leaves the trigger volume.
If none of the two collision objects is a trigger shape then the contact report callback will get
called when the actors of this collision pair stop to be in contact.
\note Only takes effect if the colliding actors are rigid bodies.
\note This event will also get triggered if one of the colliding objects gets deleted.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_LOST = (1<<4),
/**
\brief Call contact report callback when this collision pair is in contact during CCD passes.
If CCD with multiple passes is enabled, then a fast moving object might bounce on and off the same
object multiple times. Hence, the same pair might be in contact multiple times during a simulation step.
This flag will make sure that all the detected collision during CCD will get reported. For performance
reasons, the system can not always tell whether the contact pair lost touch in one of the previous CCD
passes and thus can also not always tell whether the contact is new or has persisted. eNOTIFY_TOUCH_CCD
just reports when the two collision objects were detected as being in contact during a CCD pass.
\note Only takes effect if the colliding actors are rigid bodies.
\note Trigger shapes are not supported.
\note Only takes effect if eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxSimulationEventCallback.onTrigger()
*/
eNOTIFY_TOUCH_CCD = (1<<5),
/**
\brief Call contact report callback when the contact force between the actors of this collision pair exceeds one of the actor-defined force thresholds.
\note Only takes effect if the colliding actors are rigid bodies.
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact()
*/
eNOTIFY_THRESHOLD_FORCE_FOUND = (1<<6),
/**
\brief Call contact report callback when the contact force between the actors of this collision pair continues to exceed one of the actor-defined force thresholds.
\note Only takes effect if the colliding actors are rigid bodies.
\note If a pair gets re-filtered and this flag has previously been disabled, then the report will not get fired in the same frame even if the force threshold has been reached in the
previous one (unless #eNOTIFY_THRESHOLD_FORCE_FOUND has been set in the previous frame).
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact()
*/
eNOTIFY_THRESHOLD_FORCE_PERSISTS = (1<<7),
/**
\brief Call contact report callback when the contact force between the actors of this collision pair falls below one of the actor-defined force thresholds (includes the case where this collision pair stops being in contact).
\note Only takes effect if the colliding actors are rigid bodies.
\note If a pair gets re-filtered and this flag has previously been disabled, then the report will not get fired in the same frame even if the force threshold has been reached in the
previous one (unless #eNOTIFY_THRESHOLD_FORCE_FOUND or #eNOTIFY_THRESHOLD_FORCE_PERSISTS has been set in the previous frame).
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact()
*/
eNOTIFY_THRESHOLD_FORCE_LOST = (1<<8),
/**
\brief Provide contact points in contact reports for this collision pair.
\note Only takes effect if the colliding actors are rigid bodies and if used in combination with the flags eNOTIFY_TOUCH_... or eNOTIFY_THRESHOLD_FORCE_...
\note Only takes effect if eDETECT_DISCRETE_CONTACT or eDETECT_CCD_CONTACT is raised
@see PxSimulationEventCallback.onContact() PxContactPair PxContactPair.extractContacts()
*/
eNOTIFY_CONTACT_POINTS = (1<<9),
/**
\brief This flag is used to indicate whether this pair generates discrete collision detection contacts.
\note Contacts are only responded to if eSOLVE_CONTACT is enabled.
*/
eDETECT_DISCRETE_CONTACT = (1<<10),
/**
\brief This flag is used to indicate whether this pair generates CCD contacts.
\note The contacts will only be responded to if eSOLVE_CONTACT is enabled on this pair.
\note The scene must have PxSceneFlag::eENABLE_CCD enabled to use this feature.
\note Non-static bodies of the pair should have PxRigidBodyFlag::eENABLE_CCD specified for this feature to work correctly.
\note This flag is not supported with trigger shapes. However, CCD trigger events can be emulated using non-trigger shapes
and requesting eNOTIFY_TOUCH_FOUND and eNOTIFY_TOUCH_LOST and not raising eSOLVE_CONTACT on the pair.
@see PxRigidBodyFlag::eENABLE_CCD
@see PxSceneFlag::eENABLE_CCD
*/
eDETECT_CCD_CONTACT = (1<<11),
/**
\brief Provide pre solver velocities in contact reports for this collision pair.
If the collision pair has contact reports enabled, the velocities of the rigid bodies before contacts have been solved
will be provided in the contact report callback unless the pair lost touch in which case no data will be provided.
\note Usually it is not necessary to request these velocities as they will be available by querying the velocity from the provided
PxRigidActor object directly. However, it might be the case that the velocity of a rigid body gets set while the simulation is running
in which case the PxRigidActor would return this new velocity in the contact report callback and not the velocity the simulation used.
@see PxSimulationEventCallback.onContact(), PxContactPairVelocity, PxContactPairHeader.extraDataStream
*/
ePRE_SOLVER_VELOCITY = (1<<12),
/**
\brief Provide post solver velocities in contact reports for this collision pair.
If the collision pair has contact reports enabled, the velocities of the rigid bodies after contacts have been solved
will be provided in the contact report callback unless the pair lost touch in which case no data will be provided.
@see PxSimulationEventCallback.onContact(), PxContactPairVelocity, PxContactPairHeader.extraDataStream
*/
ePOST_SOLVER_VELOCITY = (1<<13),
/**
\brief Provide rigid body poses in contact reports for this collision pair.
If the collision pair has contact reports enabled, the rigid body poses at the contact event will be provided
in the contact report callback unless the pair lost touch in which case no data will be provided.
\note Usually it is not necessary to request these poses as they will be available by querying the pose from the provided
PxRigidActor object directly. However, it might be the case that the pose of a rigid body gets set while the simulation is running
in which case the PxRigidActor would return this new pose in the contact report callback and not the pose the simulation used.
Another use case is related to CCD with multiple passes enabled, A fast moving object might bounce on and off the same
object multiple times. This flag can be used to request the rigid body poses at the time of impact for each such collision event.
@see PxSimulationEventCallback.onContact(), PxContactPairPose, PxContactPairHeader.extraDataStream
*/
eCONTACT_EVENT_POSE = (1<<14),
eNEXT_FREE = (1<<15), //!< For internal use only.
/**
\brief Provided default flag to do simple contact processing for this collision pair.
*/
eCONTACT_DEFAULT = eSOLVE_CONTACT | eDETECT_DISCRETE_CONTACT,
/**
\brief Provided default flag to get commonly used trigger behavior for this collision pair.
*/
eTRIGGER_DEFAULT = eNOTIFY_TOUCH_FOUND | eNOTIFY_TOUCH_LOST | eDETECT_DISCRETE_CONTACT
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxPairFlag.
@see PxPairFlag
*/
typedef PxFlags<PxPairFlag::Enum, PxU16> PxPairFlags;
PX_FLAGS_OPERATORS(PxPairFlag::Enum, PxU16)
/**
\brief Collection of flags describing the filter actions to take for a collision pair.
@see PxFilterFlags PxSimulationFilterShader PxSimulationFilterCallback
*/
struct PxFilterFlag
{
enum Enum
{
/**
\brief Ignore the collision pair as long as the bounding volumes of the pair objects overlap.
Killed pairs will be ignored by the simulation and won't run through the filter again until one
of the following occurs:
\li The bounding volumes of the two objects overlap again (after being separated)
\li The user enforces a re-filtering (see #PxScene::resetFiltering())
@see PxScene::resetFiltering()
*/
eKILL = (1<<0),
/**
\brief Ignore the collision pair as long as the bounding volumes of the pair objects overlap or until filtering relevant data changes for one of the collision objects.
Suppressed pairs will be ignored by the simulation and won't make another filter request until one
of the following occurs:
\li Same conditions as for killed pairs (see #eKILL)
\li The filter data or the filter object attributes change for one of the collision objects
@see PxFilterData PxFilterObjectAttributes
*/
eSUPPRESS = (1<<1),
/**
\brief Invoke the filter callback (#PxSimulationFilterCallback::pairFound()) for this collision pair.
@see PxSimulationFilterCallback
*/
eCALLBACK = (1<<2),
/**
\brief Track this collision pair with the filter callback mechanism.
When the bounding volumes of the collision pair lose contact, the filter callback #PxSimulationFilterCallback::pairLost()
will be invoked. Furthermore, the filter status of the collision pair can be adjusted through #PxSimulationFilterCallback::statusChange()
once per frame (until a pairLost() notification occurs).
@see PxSimulationFilterCallback
*/
eNOTIFY = (1<<3) | eCALLBACK,
/**
\brief Provided default to get standard behavior:
The application configure the pair's collision properties once when bounding volume overlap is found and
doesn't get asked again about that pair until overlap status or filter properties changes, or re-filtering is requested.
No notification is provided when bounding volume overlap is lost
The pair will not be killed or suppressed, so collision detection will be processed
*/
eDEFAULT = 0
};
};
/**
\brief Bitfield that contains a set of raised flags defined in PxFilterFlag.
@see PxFilterFlag
*/
typedef PxFlags<PxFilterFlag::Enum, PxU16> PxFilterFlags;
PX_FLAGS_OPERATORS(PxFilterFlag::Enum, PxU16)
/**
\brief PxFilterData is user-definable data which gets passed into the collision filtering shader and/or callback.
@see PxShape.setSimulationFilterData() PxShape.getSimulationFilterData() PxSimulationFilterShader PxSimulationFilterCallback
*/
struct PxFilterData
{
PX_INLINE PxFilterData(const PxEMPTY)
{
}
/**
\brief Default constructor.
*/
PX_INLINE PxFilterData()
{
word0 = word1 = word2 = word3 = 0;
}
/**
\brief Copy constructor.
*/
PX_INLINE PxFilterData(const PxFilterData& fd) : word0(fd.word0), word1(fd.word1), word2(fd.word2), word3(fd.word3) {}
/**
\brief Constructor to set filter data initially.
*/
PX_INLINE PxFilterData(PxU32 w0, PxU32 w1, PxU32 w2, PxU32 w3) : word0(w0), word1(w1), word2(w2), word3(w3) {}
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault()
{
*this = PxFilterData();
}
/**
\brief Assignment operator
*/
PX_INLINE void operator = (const PxFilterData& fd)
{
word0 = fd.word0;
word1 = fd.word1;
word2 = fd.word2;
word3 = fd.word3;
}
/**
\brief Comparison operator to allow use in Array.
*/
PX_INLINE bool operator == (const PxFilterData& a) const
{
return a.word0 == word0 && a.word1 == word1 && a.word2 == word2 && a.word3 == word3;
}
/**
\brief Comparison operator to allow use in Array.
*/
PX_INLINE bool operator != (const PxFilterData& a) const
{
return !(a == *this);
}
PxU32 word0;
PxU32 word1;
PxU32 word2;
PxU32 word3;
};
/**
\brief Identifies each type of filter object.
@see PxGetFilterObjectType()
*/
struct PxFilterObjectType
{
enum Enum
{
/**
\brief A static rigid body
@see PxRigidStatic
*/
eRIGID_STATIC,
/**
\brief A dynamic rigid body
@see PxRigidDynamic
*/
eRIGID_DYNAMIC,
/**
\brief An articulation
@see PxArticulationReducedCoordinate
*/
eARTICULATION,
/**
\brief A particle system
@see PxParticleSystem
*/
ePARTICLESYSTEM,
/**
\brief A FEM-based soft body
@see PxSoftBody
*/
eSOFTBODY,
/**
\brief A FEM-based cloth
\note In development
@see PxFEMCloth
*/
eFEMCLOTH,
/**
\brief A hair system
\note In development
@see PxHairSystem
*/
eHAIRSYSTEM,
//! \brief internal use only!
eMAX_TYPE_COUNT = 16,
//! \brief internal use only!
eUNDEFINED = eMAX_TYPE_COUNT-1
};
};
// For internal use only
struct PxFilterObjectFlag
{
enum Enum
{
eKINEMATIC = (1<<4),
eTRIGGER = (1<<5),
eNEXT_FREE = (1<<6) // Used internally
};
};
/**
\brief Structure which gets passed into the collision filtering shader and/or callback providing additional information on objects of a collision pair
@see PxSimulationFilterShader PxSimulationFilterCallback getActorType() PxFilterObjectIsKinematic() PxFilterObjectIsTrigger()
*/
typedef PxU32 PxFilterObjectAttributes;
/**
\brief Extract filter object type from the filter attributes of a collision pair object
\param[in] attr The filter attribute of a collision pair object
\return The type of the collision pair object.
@see PxFilterObjectType
*/
PX_INLINE PxFilterObjectType::Enum PxGetFilterObjectType(PxFilterObjectAttributes attr)
{
return PxFilterObjectType::Enum(attr & (PxFilterObjectType::eMAX_TYPE_COUNT-1));
}
/**
\brief Specifies whether the collision object belongs to a kinematic rigid body
\param[in] attr The filter attribute of a collision pair object
\return True if the object belongs to a kinematic rigid body, else false
@see PxRigidBodyFlag::eKINEMATIC
*/
PX_INLINE bool PxFilterObjectIsKinematic(PxFilterObjectAttributes attr)
{
return (attr & PxFilterObjectFlag::eKINEMATIC) != 0;
}
/**
\brief Specifies whether the collision object is a trigger shape
\param[in] attr The filter attribute of a collision pair object
\return True if the object is a trigger shape, else false
@see PxShapeFlag::eTRIGGER_SHAPE
*/
PX_INLINE bool PxFilterObjectIsTrigger(PxFilterObjectAttributes attr)
{
return (attr & PxFilterObjectFlag::eTRIGGER) != 0;
}
/**
\brief Filter method to specify how a pair of potentially colliding objects should be processed.
Collision filtering is a mechanism to specify how a pair of potentially colliding objects should be processed by the
simulation. A pair of objects is potentially colliding if the bounding volumes of the two objects overlap.
In short, a collision filter decides whether a collision pair should get processed, temporarily ignored or discarded.
If a collision pair should get processed, the filter can additionally specify how it should get processed, for instance,
whether contacts should get resolved, which callbacks should get invoked or which reports should be sent etc.
The function returns the PxFilterFlag flags and sets the PxPairFlag flags to define what the simulation should do with the given collision pair.
\note A default implementation of a filter shader is provided in the PhysX extensions library, see #PxDefaultSimulationFilterShader.
This methods gets called when:
\li The bounding volumes of two objects start to overlap.
\li The bounding volumes of two objects overlap and the filter data or filter attributes of one of the objects changed
\li A re-filtering was forced through resetFiltering() (see #PxScene::resetFiltering())
\li Filtering is requested in scene queries
\note Certain pairs of objects are always ignored and this method does not get called. This is the case for the
following pairs:
\li Pair of static rigid actors
\li A static rigid actor and a kinematic actor (unless one is a trigger or if explicitly enabled through PxPairFilteringMode::eKEEP)
\li Two kinematic actors (unless one is a trigger or if explicitly enabled through PxPairFilteringMode::eKEEP)
\li Two jointed rigid bodies and the joint was defined to disable collision
\li Two articulation links if connected through an articulation joint
\note This is a performance critical method and should be stateless. You should neither access external objects
from within this method nor should you call external methods that are not inlined. If you need a more complex
logic to filter a collision pair then use the filter callback mechanism for this pair (see #PxSimulationFilterCallback,
#PxFilterFlag::eCALLBACK, #PxFilterFlag::eNOTIFY).
\param[in] attributes0 The filter attribute of the first object
\param[in] filterData0 The custom filter data of the first object
\param[in] attributes1 The filter attribute of the second object
\param[in] filterData1 The custom filter data of the second object
\param[out] pairFlags Flags giving additional information on how an accepted pair should get processed
\param[in] constantBlock The constant global filter data (see #PxSceneDesc.filterShaderData)
\param[in] constantBlockSize Size of the global filter data (see #PxSceneDesc.filterShaderDataSize)
\return Filter flags defining whether the pair should be discarded, temporarily ignored, processed and whether the
filter callback should get invoked for this pair.
@see PxSimulationFilterCallback PxFilterData PxFilterObjectAttributes PxFilterFlag PxFilterFlags PxPairFlag PxPairFlags PxSceneDesc.filterShader
*/
typedef PxFilterFlags (*PxSimulationFilterShader)
(PxFilterObjectAttributes attributes0, PxFilterData filterData0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1,
PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize);
/**
\brief Filter callback to specify handling of collision pairs.
This class is provided to implement more complex and flexible collision pair filtering logic, for instance, taking
the state of the user application into account. Filter callbacks also give the user the opportunity to track collision
pairs and update their filter state.
You might want to check the documentation on #PxSimulationFilterShader as well since it includes more general information
on filtering.
\note SDK state should not be modified from within the callbacks. In particular objects should not
be created or destroyed. If state modification is needed then the changes should be stored to a buffer
and performed after the simulation step.
\note The callbacks may execute in user threads or simulation threads, possibly simultaneously. The corresponding objects
may have been deleted by the application earlier in the frame. It is the application's responsibility to prevent race conditions
arising from using the SDK API in the callback while an application thread is making write calls to the scene, and to ensure that
the callbacks are thread-safe. Return values which depend on when the callback is called during the frame will introduce nondeterminism
into the simulation.
@see PxSceneDesc.filterCallback PxSimulationFilterShader
*/
class PxSimulationFilterCallback
{
public:
/**
\brief Filter method to specify how a pair of potentially colliding objects should be processed.
This method gets called when the filter flags returned by the filter shader (see #PxSimulationFilterShader)
indicate that the filter callback should be invoked (#PxFilterFlag::eCALLBACK or #PxFilterFlag::eNOTIFY set).
Return the PxFilterFlag flags and set the PxPairFlag flags to define what the simulation should do with the given
collision pair.
\param[in] pairID Unique ID of the collision pair used to issue filter status changes for the pair (see #statusChange())
\param[in] attributes0 The filter attribute of the first object
\param[in] filterData0 The custom filter data of the first object
\param[in] a0 Actor pointer of the first object
\param[in] s0 Shape pointer of the first object (NULL if the object has no shapes)
\param[in] attributes1 The filter attribute of the second object
\param[in] filterData1 The custom filter data of the second object
\param[in] a1 Actor pointer of the second object
\param[in] s1 Shape pointer of the second object (NULL if the object has no shapes)
\param[in,out] pairFlags In: Pair flags returned by the filter shader. Out: Additional information on how an accepted pair should get processed
\return Filter flags defining whether the pair should be discarded, temporarily ignored or processed and whether the pair
should be tracked and send a report on pair deletion through the filter callback
@see PxSimulationFilterShader PxFilterData PxFilterObjectAttributes PxFilterFlag PxPairFlag
*/
virtual PxFilterFlags pairFound( PxU64 pairID,
PxFilterObjectAttributes attributes0, PxFilterData filterData0, const PxActor* a0, const PxShape* s0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1, const PxActor* a1, const PxShape* s1,
PxPairFlags& pairFlags) = 0;
/**
\brief Callback to inform that a tracked collision pair is gone.
This method gets called when a collision pair disappears or gets re-filtered. Only applies to
collision pairs which have been marked as filter callback pairs (#PxFilterFlag::eNOTIFY set in #pairFound()).
\param[in] pairID Unique ID of the collision pair that disappeared
\param[in] attributes0 The filter attribute of the first object
\param[in] filterData0 The custom filter data of the first object
\param[in] attributes1 The filter attribute of the second object
\param[in] filterData1 The custom filter data of the second object
\param[in] objectRemoved True if the pair was lost because one of the objects got removed from the scene
@see pairFound() PxSimulationFilterShader PxFilterData PxFilterObjectAttributes
*/
virtual void pairLost( PxU64 pairID,
PxFilterObjectAttributes attributes0, PxFilterData filterData0,
PxFilterObjectAttributes attributes1, PxFilterData filterData1,
bool objectRemoved) = 0;
/**
\brief Callback to give the opportunity to change the filter state of a tracked collision pair.
This method gets called once per simulation step to let the application change the filter and pair
flags of a collision pair that has been reported in #pairFound() and requested callbacks by
setting #PxFilterFlag::eNOTIFY. To request a change of filter status, the target pair has to be
specified by its ID, the new filter and pair flags have to be provided and the method should return true.
\note If this method changes the filter status of a collision pair and the pair should keep being tracked
by the filter callbacks then #PxFilterFlag::eNOTIFY has to be set.
\note The application is responsible to ensure that this method does not get called for pairs that have been
reported as lost, see #pairLost().
\param[out] pairID ID of the collision pair for which the filter status should be changed
\param[out] pairFlags The new pairFlags to apply to the collision pair
\param[out] filterFlags The new filterFlags to apply to the collision pair
\return True if the changes should be applied. In this case the method will get called again. False if
no more status changes should be done in the current simulation step. In that case the provided flags will be discarded.
@see pairFound() pairLost() PxFilterFlag PxPairFlag
*/
virtual bool statusChange(PxU64& pairID, PxPairFlags& pairFlags, PxFilterFlags& filterFlags) = 0;
protected:
virtual ~PxSimulationFilterCallback() {}
};
struct PxPairFilteringMode
{
enum Enum
{
/**
\brief Output pair from BP, potentially send to user callbacks, create regular interaction object.
Enable contact pair filtering between kinematic/static or kinematic/kinematic rigid bodies.
By default contacts between these are suppressed (see #PxFilterFlag::eSUPPRESS) and don't get reported to the filter mechanism.
Use this mode if these pairs should go through the filtering pipeline nonetheless.
\note This mode is not mutable, and must be set in PxSceneDesc at scene creation.
*/
eKEEP,
/**
\brief Output pair from BP, create interaction marker. Can be later switched to regular interaction.
*/
eSUPPRESS,
/**
\brief Don't output pair from BP. Cannot be later switched to regular interaction, needs "resetFiltering" call.
*/
eKILL,
/**
\brief Default is eSUPPRESS for compatibility with previous PhysX versions.
*/
eDEFAULT = eSUPPRESS
};
};
/**
\brief Struct for storing a particle/vertex - rigid filter pair with comparison operators
*/
struct PxParticleRigidFilterPair
{
PX_CUDA_CALLABLE PxParticleRigidFilterPair() {}
PX_CUDA_CALLABLE PxParticleRigidFilterPair(const PxU64 id0, const PxU64 id1): mID0(id0), mID1(id1) {}
PxU64 mID0; //!< Rigid node index
PxU64 mID1; //!< Particle/vertex id
PX_CUDA_CALLABLE bool operator<(const PxParticleRigidFilterPair& other) const
{
if(mID0 < other.mID0)
return true;
if(mID0 == other.mID0 && mID1 < other.mID1)
return true;
return false;
}
PX_CUDA_CALLABLE bool operator>(const PxParticleRigidFilterPair& other) const
{
if(mID0 > other.mID0)
return true;
if(mID0 == other.mID0 && mID1 > other.mID1)
return true;
return false;
}
PX_CUDA_CALLABLE bool operator==(const PxParticleRigidFilterPair& other) const
{
return (mID0 == other.mID0 && mID1 == other.mID1);
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 30,117 | C | 37.56338 | 226 | 0.765647 |
NVIDIA-Omniverse/PhysX/physx/include/PxRigidDynamic.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_RIGID_DYNAMIC_H
#define PX_RIGID_DYNAMIC_H
/** \addtogroup physics
@{
*/
#include "PxRigidBody.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Collection of flags providing a mechanism to lock motion along/around a specific axis.
@see PxRigidDynamic.setRigidDynamicLockFlag(), PxRigidBody.getRigidDynamicLockFlags()
*/
struct PxRigidDynamicLockFlag
{
enum Enum
{
eLOCK_LINEAR_X = (1 << 0),
eLOCK_LINEAR_Y = (1 << 1),
eLOCK_LINEAR_Z = (1 << 2),
eLOCK_ANGULAR_X = (1 << 3),
eLOCK_ANGULAR_Y = (1 << 4),
eLOCK_ANGULAR_Z = (1 << 5)
};
};
typedef PxFlags<PxRigidDynamicLockFlag::Enum, PxU8> PxRigidDynamicLockFlags;
PX_FLAGS_OPERATORS(PxRigidDynamicLockFlag::Enum, PxU8)
/**
\brief PxRigidDynamic represents a dynamic rigid simulation object in the physics SDK.
<h3>Creation</h3>
Instances of this class are created by calling #PxPhysics::createRigidDynamic() and deleted with #release().
<h3>Visualizations</h3>
\li #PxVisualizationParameter::eACTOR_AXES
\li #PxVisualizationParameter::eBODY_AXES
\li #PxVisualizationParameter::eBODY_MASS_AXES
\li #PxVisualizationParameter::eBODY_LIN_VELOCITY
\li #PxVisualizationParameter::eBODY_ANG_VELOCITY
@see PxRigidBody PxPhysics.createRigidDynamic() release()
*/
class PxRigidDynamic : public PxRigidBody
{
public:
// Runtime modifications
/************************************************************************************************/
/** @name Kinematic Actors
*/
/**
\brief Moves kinematically controlled dynamic actors through the game world.
You set a dynamic actor to be kinematic using the PxRigidBodyFlag::eKINEMATIC flag
with setRigidBodyFlag().
The move command will result in a velocity that will move the body into
the desired pose. After the move is carried out during a single time step,
the velocity is returned to zero. Thus, you must continuously call
this in every time step for kinematic actors so that they move along a path.
This function simply stores the move destination until the next simulation
step is processed, so consecutive calls will simply overwrite the stored target variable.
The motion is always fully carried out.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
<b>Sleeping:</b> This call wakes the actor if it is sleeping and will set the wake counter to #PxSceneDesc::wakeCounterResetValue.
\param[in] destination The desired pose for the kinematic actor, in the global frame. <b>Range:</b> rigid body transform.
@see getKinematicTarget() PxRigidBodyFlag setRigidBodyFlag()
*/
virtual void setKinematicTarget(const PxTransform& destination) = 0;
/**
\brief Get target pose of a kinematically controlled dynamic actor.
\param[out] target Transform to write the target pose to. Only valid if the method returns true.
\return True if the actor is a kinematically controlled dynamic and the target has been set, else False.
@see setKinematicTarget() PxRigidBodyFlag setRigidBodyFlag()
*/
virtual bool getKinematicTarget(PxTransform& target) const = 0;
/************************************************************************************************/
/** @name Sleeping
*/
/**
\brief Returns true if this body is sleeping.
When an actor does not move for a period of time, it is no longer simulated in order to save time. This state
is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object,
or one of its properties is changed by the user, the entire sleep mechanism should be transparent to the user.
In general, a dynamic rigid actor is guaranteed to be awake if at least one of the following holds:
\li The wake counter is positive (see #setWakeCounter()).
\li The linear or angular velocity is non-zero.
\li A non-zero force or torque has been applied.
If a dynamic rigid actor is sleeping, the following state is guaranteed:
\li The wake counter is zero.
\li The linear and angular velocity is zero.
\li There is no force update pending.
When an actor gets inserted into a scene, it will be considered asleep if all the points above hold, else it will be treated as awake.
If an actor is asleep after the call to PxScene::fetchResults() returns, it is guaranteed that the pose of the actor
was not changed. You can use this information to avoid updating the transforms of associated objects.
\note A kinematic actor is asleep unless a target pose has been set (in which case it will stay awake until two consecutive
simulation steps without a target pose being set have passed). The wake counter will get set to zero or to the reset value
#PxSceneDesc::wakeCounterResetValue in the case where a target pose has been set to be consistent with the definitions above.
\note It is invalid to use this method if the actor has not been added to a scene already.
\note It is not allowed to use this method while the simulation is running.
\return True if the actor is sleeping.
@see isSleeping() wakeUp() putToSleep() getSleepThreshold()
*/
virtual bool isSleeping() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which an actor may go to sleep.
Actors whose kinetic energy divided by their mass is below this threshold will be candidates for sleeping.
<b>Default:</b> 5e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which an actor may go to sleep. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getSleepThreshold() wakeUp() putToSleep() PxTolerancesScale
*/
virtual void setSleepThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which an actor may go to sleep.
\return The energy threshold for sleeping.
@see isSleeping() wakeUp() putToSleep() setSleepThreshold()
*/
virtual PxReal getSleepThreshold() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which an actor may participate in stabilization.
Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
This value has no effect if PxSceneFlag::eENABLE_STABILIZATION was not enabled on the PxSceneDesc.
<b>Default:</b> 1e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which an actor may participate in stabilization. <b>Range:</b> [0,inf)
@see getStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual void setStabilizationThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which an actor may participate in stabilization.
Actors whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
\return The energy threshold for participating in stabilization.
@see setStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual PxReal getStabilizationThreshold() const = 0;
/**
\brief Reads the PxRigidDynamic lock flags.
See the list of flags #PxRigidDynamicLockFlag
\return The values of the PxRigidDynamicLock flags.
@see PxRigidDynamicLockFlag setRigidDynamicLockFlag()
*/
virtual PxRigidDynamicLockFlags getRigidDynamicLockFlags() const = 0;
/**
\brief Raises or clears a particular rigid dynamic lock flag.
See the list of flags #PxRigidDynamicLockFlag
<b>Default:</b> no flags are set
\param[in] flag The PxRigidDynamicLockBody flag to raise(set) or clear. See #PxRigidBodyFlag.
\param[in] value The new boolean value for the flag.
@see PxRigidDynamicLockFlag getRigidDynamicLockFlags()
*/
virtual void setRigidDynamicLockFlag(PxRigidDynamicLockFlag::Enum flag, bool value) = 0;
virtual void setRigidDynamicLockFlags(PxRigidDynamicLockFlags flags) = 0;
/**
\brief Retrieves the linear velocity of an actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\note The linear velocity is reported with respect to the rigid dynamic's center of mass and not the actor frame origin.
\return The linear velocity of the actor.
@see PxRigidDynamic.setLinearVelocity() getAngularVelocity()
*/
virtual PxVec3 getLinearVelocity() const = 0;
/**
\brief Sets the linear velocity of the actor.
Note that if you continuously set the velocity of an actor yourself,
forces such as gravity or friction will not be able to manifest themselves, because forces directly
influence only the velocity/momentum of an actor.
<b>Default:</b> (0.0, 0.0, 0.0)
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the
new velocity is non-zero.
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
\note The linear velocity is applied with respect to the rigid dynamic's center of mass and not the actor frame origin.
\param[in] linVel New linear velocity of actor. <b>Range:</b> velocity vector
\param[in] autowake Whether to wake the object up if it is asleep. If true and the current wake counter value is
smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see getLinearVelocity() setAngularVelocity()
*/
virtual void setLinearVelocity(const PxVec3& linVel, bool autowake = true) = 0;
/**
\brief Retrieves the angular velocity of the actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\return The angular velocity of the actor.
@see PxRigidDynamic.setAngularVelocity() getLinearVelocity()
*/
virtual PxVec3 getAngularVelocity() const = 0;
/**
\brief Sets the angular velocity of the actor.
Note that if you continuously set the angular velocity of an actor yourself,
forces such as friction will not be able to rotate the actor, because forces directly influence only the velocity/momentum.
<b>Default:</b> (0.0, 0.0, 0.0)
<b>Sleeping:</b> This call wakes the actor if it is sleeping, and the autowake parameter is true (default) or the
new velocity is non-zero.
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
\param[in] angVel New angular velocity of actor. <b>Range:</b> angular velocity vector
\param[in] autowake Whether to wake the object up if it is asleep. If true and the current wake counter value is
smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see getAngularVelocity() setLinearVelocity()
*/
virtual void setAngularVelocity(const PxVec3& angVel, bool autowake = true) = 0;
/**
\brief Sets the wake counter for the actor.
The wake counter value determines the minimum amount of time until the body can be put to sleep. Please note
that a body will not be put to sleep if the energy is above the specified threshold (see #setSleepThreshold())
or if other awake bodies are touching it.
\note Passing in a positive value will wake the actor up automatically.
\note It is invalid to use this method for kinematic actors since the wake counter for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
<b>Default:</b> 0.4 (which corresponds to 20 frames for a time step of 0.02)
\param[in] wakeCounterValue Wake counter value. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getWakeCounter()
*/
virtual void setWakeCounter(PxReal wakeCounterValue) = 0;
/**
\brief Returns the wake counter of the actor.
\note It is not allowed to use this method while the simulation is running.
\return The wake counter of the actor.
@see isSleeping() setWakeCounter()
*/
virtual PxReal getWakeCounter() const = 0;
/**
\brief Wakes up the actor if it is sleeping.
The actor will get woken up and might cause other touching actors to wake up as well during the next simulation step.
\note This will set the wake counter of the actor to the value specified in #PxSceneDesc::wakeCounterResetValue.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
@see isSleeping() putToSleep()
*/
virtual void wakeUp() = 0;
/**
\brief Forces the actor to sleep.
The actor will stay asleep during the next simulation step if not touched by another non-sleeping actor.
\note Any applied force will be cleared and the velocity and the wake counter of the actor will be set to 0.
\note It is invalid to use this method if the actor has not been added to a scene already or if PxActorFlag::eDISABLE_SIMULATION is set.
\note It is invalid to use this method for kinematic actors since the sleep state for kinematics is defined
based on whether a target pose has been set (see the comment in #isSleeping()).
@see isSleeping() wakeUp()
*/
virtual void putToSleep() = 0;
/************************************************************************************************/
/**
\brief Sets the solver iteration counts for the body.
The solver iteration count determines how accurately joints and contacts are resolved.
If you are having trouble with jointed bodies oscillating and behaving erratically, then
setting a higher position iteration count may improve their stability.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations. More velocity iterations will drive the relative exit velocity of the intersecting
objects closer to the correct value given the restitution.
<b>Default:</b> 4 position iterations, 1 velocity iteration
\param[in] minPositionIters Number of position iterations the solver should perform for this body. <b>Range:</b> [1,255]
\param[in] minVelocityIters Number of velocity iterations the solver should perform for this body. <b>Range:</b> [0,255]
@see getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Retrieves the solver iteration counts.
@see setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Retrieves the force threshold for contact reports.
The contact report threshold is a force threshold. If the force between
two actors exceeds this threshold for either of the two actors, a contact report
will be generated according to the contact report threshold flags provided by
the filter shader/callback.
See #PxPairFlag.
The threshold used for a collision between a dynamic actor and the static environment is
the threshold of the dynamic actor, and all contacts with static actors are summed to find
the total normal force.
<b>Default:</b> PX_MAX_F32
\return Force threshold for contact reports.
@see setContactReportThreshold PxPairFlag PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual PxReal getContactReportThreshold() const = 0;
/**
\brief Sets the force threshold for contact reports.
See #getContactReportThreshold().
\param[in] threshold Force threshold for contact reports. <b>Range:</b> [0, PX_MAX_F32)
@see getContactReportThreshold PxPairFlag
*/
virtual void setContactReportThreshold(PxReal threshold) = 0;
virtual const char* getConcreteTypeName() const { return "PxRigidDynamic"; }
protected:
PX_INLINE PxRigidDynamic(PxType concreteType, PxBaseFlags baseFlags) : PxRigidBody(concreteType, baseFlags) { }
PX_INLINE PxRigidDynamic(PxBaseFlags baseFlags) : PxRigidBody(baseFlags) {}
virtual ~PxRigidDynamic() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidDynamic", PxRigidBody); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 17,957 | C | 38.124183 | 137 | 0.748789 |
NVIDIA-Omniverse/PhysX/physx/include/PxBroadPhase.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_BROAD_PHASE_H
#define PX_BROAD_PHASE_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxBounds3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBaseTask;
class PxCudaContextManager;
/**
\brief Broad phase algorithm used in the simulation
eSAP is a good generic choice with great performance when many objects are sleeping. Performance
can degrade significantly though, when all objects are moving, or when large numbers of objects
are added to or removed from the broad phase. This algorithm does not need world bounds to be
defined in order to work.
eMBP is an alternative broad phase algorithm that does not suffer from the same performance
issues as eSAP when all objects are moving or when inserting large numbers of objects. However
its generic performance when many objects are sleeping might be inferior to eSAP, and it requires
users to define world bounds in order to work.
eABP is a revisited implementation of MBP, which automatically manages broad-phase regions.
It offers the convenience of eSAP (no need to define world bounds or regions) and the performance
of eMBP when a lot of objects are moving. While eSAP can remain faster when most objects are
sleeping and eMBP can remain faster when it uses a large number of properly-defined regions,
eABP often gives the best performance on average and the best memory usage.
ePABP is a parallel implementation of ABP. It can often be the fastest (CPU) broadphase, but it
can use more memory than ABP.
eGPU is a GPU implementation of the incremental sweep and prune approach. Additionally, it uses a ABP-style
initial pair generation approach to avoid large spikes when inserting shapes. It not only has the advantage
of traditional SAP approch which is good for when many objects are sleeping, but due to being fully parallel,
it also is great when lots of shapes are moving or for runtime pair insertion and removal. It can become a
performance bottleneck if there are a very large number of shapes roughly projecting to the same values
on a given axis. If the scene has a very large number of shapes in an actor, e.g. a humanoid, it is recommended
to use an aggregate to represent multi-shape or multi-body actors to minimize stress placed on the broad phase.
*/
struct PxBroadPhaseType
{
enum Enum
{
eSAP, //!< 3-axes sweep-and-prune
eMBP, //!< Multi box pruning
eABP, //!< Automatic box pruning
ePABP, //!< Parallel automatic box pruning
eGPU, //!< GPU broad phase
eLAST
};
};
/**
\brief "Region of interest" for the broad-phase.
This is currently only used for the PxBroadPhaseType::eMBP broad-phase, which requires zones or regions to be defined
when the simulation starts in order to work. Regions can overlap and be added or removed at runtime, but at least one
region needs to be defined when the scene is created.
If objects that do no overlap any region are inserted into the scene, they will not be added to the broad-phase and
thus collisions will be disabled for them. A PxBroadPhaseCallback out-of-bounds notification will be sent for each one
of those objects.
The total number of regions is limited by PxBroadPhaseCaps::mMaxNbRegions.
The number of regions has a direct impact on performance and memory usage, so it is recommended to experiment with
various settings to find the best combination for your game. A good default setup is to start with global bounds
around the whole world, and subdivide these bounds into 4*4 regions. The PxBroadPhaseExt::createRegionsFromWorldBounds
function can do that for you.
@see PxBroadPhaseCallback PxBroadPhaseExt.createRegionsFromWorldBounds
*/
struct PxBroadPhaseRegion
{
PxBounds3 mBounds; //!< Region's bounds
void* mUserData; //!< Region's user-provided data
};
/**
\brief Information & stats structure for a region
*/
struct PxBroadPhaseRegionInfo
{
PxBroadPhaseRegion mRegion; //!< User-provided region data
PxU32 mNbStaticObjects; //!< Number of static objects in the region
PxU32 mNbDynamicObjects; //!< Number of dynamic objects in the region
bool mActive; //!< True if region is currently used, i.e. it has not been removed
bool mOverlap; //!< True if region overlaps other regions (regions that are just touching are not considering overlapping)
};
/**
\brief Caps class for broad phase.
*/
struct PxBroadPhaseCaps
{
PxU32 mMaxNbRegions; //!< Max number of regions supported by the broad-phase (0 = explicit regions not needed)
};
/**
\brief Broadphase descriptor.
This structure is used to create a standalone broadphase. It captures all the parameters needed to
initialize a broadphase.
For the GPU broadphase (PxBroadPhaseType::eGPU) it is necessary to provide a CUDA context manager.
The kinematic filtering flags are currently not supported by the GPU broadphase. They are used to
dismiss pairs that involve kinematic objects directly within the broadphase.
\see PxCreateBroadPhase
*/
class PxBroadPhaseDesc
{
public:
PxBroadPhaseDesc(PxBroadPhaseType::Enum type = PxBroadPhaseType::eLAST) :
mType (type),
mContextID (0),
mContextManager (NULL),
mFoundLostPairsCapacity (256 * 1024),
mDiscardStaticVsKinematic (false),
mDiscardKinematicVsKinematic(false)
{}
PxBroadPhaseType::Enum mType; //!< Desired broadphase implementation
PxU64 mContextID; //!< Context ID for profiler. See PxProfilerCallback.
PxCudaContextManager* mContextManager; //!< (GPU) CUDA context manager, must be provided for PxBroadPhaseType::eGPU.
PxU32 mFoundLostPairsCapacity; //!< (GPU) Capacity of found and lost buffers allocated in GPU global memory. This is used for the found/lost pair reports in the BP.
bool mDiscardStaticVsKinematic; //!< Static-vs-kinematic filtering flag. Not supported by PxBroadPhaseType::eGPU.
bool mDiscardKinematicVsKinematic; //!< kinematic-vs-kinematic filtering flag. Not supported by PxBroadPhaseType::eGPU.
PX_INLINE bool isValid() const
{
if(PxU32(mType)>=PxBroadPhaseType::eLAST)
return false;
if(mType==PxBroadPhaseType::eGPU && !mContextManager)
return false;
return true;
}
};
typedef PxU32 PxBpIndex; //!< Broadphase index. Indexes bounds, groups and distance arrays.
typedef PxU32 PxBpFilterGroup; //!< Broadphase filter group.
#define PX_INVALID_BP_FILTER_GROUP 0xffffffff //!< Invalid broadphase filter group
/**
\brief Retrieves the filter group for static objects.
Mark static objects with this group when adding them to the broadphase.
Overlaps between static objects will not be detected. All static objects
should have the same group.
\return Filter group for static objects.
\see PxBpFilterGroup
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseStaticFilterGroup();
/**
\brief Retrieves a filter group for dynamic objects.
Mark dynamic objects with this group when adding them to the broadphase.
Each dynamic object must have an ID, and overlaps between dynamic objects that have
the same ID will not be detected. This is useful to dismiss overlaps between shapes
of the same (compound) actor directly within the broadphase.
\param id [in] ID/Index of dynamic object
\return Filter group for the object.
\see PxBpFilterGroup
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseDynamicFilterGroup(PxU32 id);
/**
\brief Retrieves a filter group for kinematic objects.
Mark kinematic objects with this group when adding them to the broadphase.
Each kinematic object must have an ID, and overlaps between kinematic objects that have
the same ID will not be detected.
\param id [in] ID/Index of kinematic object
\return Filter group for the object.
\see PxBpFilterGroup
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBpFilterGroup PxGetBroadPhaseKinematicFilterGroup(PxU32 id);
/**
\brief Broadphase data update structure.
This structure is used to update the low-level broadphase (PxBroadPhase). All added, updated and removed objects
must be batched and submitted at once to the broadphase.
Broadphase objects have bounds, a filtering group, and a distance. With the low-level broadphase the data must be
externally managed by the clients of the broadphase API, and passed to the update function.
The provided bounds are non-inflated "base" bounds that can be further extended by the broadphase using the passed
distance value. These can be contact offsets, or dynamically updated distance values for e.g. speculative contacts.
Either way they are optional and can be left to zero. The broadphase implementations efficiently combine the base
bounds with the per-object distance values at runtime.
The per-object filtering groups are used to discard some pairs directly within the broadphase, which is more
efficient than reporting the pairs and culling them in a second pass.
\see PxBpFilterGroup PxBpIndex PxBounds3 PxBroadPhase::update
*/
class PxBroadPhaseUpdateData
{
public:
PxBroadPhaseUpdateData( const PxBpIndex* created, PxU32 nbCreated,
const PxBpIndex* updated, PxU32 nbUpdated,
const PxBpIndex* removed, PxU32 nbRemoved,
const PxBounds3* bounds, const PxBpFilterGroup* groups, const float* distances,
PxU32 capacity) :
mCreated (created), mNbCreated (nbCreated),
mUpdated (updated), mNbUpdated (nbUpdated),
mRemoved (removed), mNbRemoved (nbRemoved),
mBounds (bounds), mGroups (groups), mDistances (distances),
mCapacity (capacity)
{
}
PxBroadPhaseUpdateData(const PxBroadPhaseUpdateData& other) :
mCreated (other.mCreated), mNbCreated (other.mNbCreated),
mUpdated (other.mUpdated), mNbUpdated (other.mNbUpdated),
mRemoved (other.mRemoved), mNbRemoved (other.mNbRemoved),
mBounds (other.mBounds), mGroups (other.mGroups), mDistances (other.mDistances),
mCapacity (other.mCapacity)
{
}
PxBroadPhaseUpdateData& operator=(const PxBroadPhaseUpdateData& other);
const PxBpIndex* mCreated; //!< Indices of created objects.
const PxU32 mNbCreated; //!< Number of created objects.
const PxBpIndex* mUpdated; //!< Indices of updated objects.
const PxU32 mNbUpdated; //!< Number of updated objects.
const PxBpIndex* mRemoved; //!< Indices of removed objects.
const PxU32 mNbRemoved; //!< Number of removed objects.
const PxBounds3* mBounds; //!< (Persistent) array of bounds.
const PxBpFilterGroup* mGroups; //!< (Persistent) array of groups.
const float* mDistances; //!< (Persistent) array of distances.
const PxU32 mCapacity; //!< Capacity of bounds / groups / distance buffers.
};
/**
\brief Broadphase pair.
A pair of indices returned by the broadphase for found or lost pairs.
\see PxBroadPhaseResults
*/
struct PxBroadPhasePair
{
PxBpIndex mID0; //!< Index of first object
PxBpIndex mID1; //!< Index of second object
};
/**
\brief Broadphase results.
Set of found and lost pairs after a broadphase update.
\see PxBroadPhasePair PxBroadPhase::fetchResults PxAABBManager::fetchResults
*/
struct PxBroadPhaseResults
{
PxBroadPhaseResults() : mNbCreatedPairs(0), mCreatedPairs(NULL), mNbDeletedPairs(0), mDeletedPairs(NULL) {}
PxU32 mNbCreatedPairs; //!< Number of new/found/created pairs.
const PxBroadPhasePair* mCreatedPairs; //!< Array of new/found/created pairs.
PxU32 mNbDeletedPairs; //!< Number of lost/deleted pairs.
const PxBroadPhasePair* mDeletedPairs; //!< Array of lost/deleted pairs.
};
/**
\brief Broadphase regions.
An API to manage broadphase regions. Only needed for the MBP broadphase (PxBroadPhaseType::eMBP).
\see PxBroadPhase::getRegions()
*/
class PxBroadPhaseRegions
{
protected:
PxBroadPhaseRegions() {}
virtual ~PxBroadPhaseRegions() {}
public:
/**
\brief Returns number of regions currently registered in the broad-phase.
\return Number of regions
*/
virtual PxU32 getNbRegions() const = 0;
/**
\brief Gets broad-phase regions.
\param userBuffer [out] Returned broad-phase regions
\param bufferSize [in] Size of provided userBuffer.
\param startIndex [in] Index of first desired region, in [0 ; getNbRegions()[
\return Number of written out regions.
\see PxBroadPhaseRegionInfo
*/
virtual PxU32 getRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Adds a new broad-phase region.
The total number of regions is limited to PxBroadPhaseCaps::mMaxNbRegions. If that number is exceeded, the call is ignored.
The newly added region will be automatically populated with already existing objects that touch it, if the
'populateRegion' parameter is set to true. Otherwise the newly added region will be empty, and it will only be
populated with objects when those objects are added to the simulation, or updated if they already exist.
Using 'populateRegion=true' has a cost, so it is best to avoid it if possible. In particular it is more efficient
to create the empty regions first (with populateRegion=false) and then add the objects afterwards (rather than
the opposite).
Objects automatically move from one region to another during their lifetime. The system keeps tracks of what
regions a given object is in. It is legal for an object to be in an arbitrary number of regions. However if an
object leaves all regions, or is created outside of all regions, several things happen:
- collisions get disabled for this object
- the object appears in the getOutOfBoundsObjects() array
If an out-of-bounds object, whose collisions are disabled, re-enters a valid broadphase region, then collisions
are re-enabled for that object.
\param region [in] User-provided region data
\param populateRegion [in] True to automatically populate the newly added region with existing objects touching it
\param bounds [in] User-managed array of bounds
\param distances [in] User-managed array of distances
\return Handle for newly created region, or 0xffffffff in case of failure.
\see PxBroadPhaseRegion getOutOfBoundsObjects()
*/
virtual PxU32 addRegion(const PxBroadPhaseRegion& region, bool populateRegion, const PxBounds3* bounds, const float* distances) = 0;
/**
\brief Removes a broad-phase region.
If the region still contains objects, and if those objects do not overlap any region any more, they are not
automatically removed from the simulation. Instead, the PxBroadPhaseCallback::onObjectOutOfBounds notification
is used for each object. Users are responsible for removing the objects from the simulation if this is the
desired behavior.
If the handle is invalid, or if a valid handle is removed twice, an error message is sent to the error stream.
\param handle [in] Region's handle, as returned by addRegion
\return True if success
*/
virtual bool removeRegion(PxU32 handle) = 0;
/*
\brief Return the number of objects that are not in any region.
*/
virtual PxU32 getNbOutOfBoundsObjects() const = 0;
/*
\brief Return an array of objects that are not in any region.
*/
virtual const PxU32* getOutOfBoundsObjects() const = 0;
};
/**
\brief Low-level broadphase API.
This low-level API only supports batched updates and leaves most of the data management to its clients.
This is useful if you want to use the broadphase with your own memory buffers. Note however that the GPU broadphase
works best with buffers allocated in CUDA memory. The getAllocator() function returns an allocator that is compatible
with the selected broadphase. It is recommended to allocate and deallocate the broadphase data (bounds, groups, distances)
using this allocator.
Important note: it must be safe to load 4 bytes past the end of the provided bounds array.
The high-level broadphase API (PxAABBManager) is an easier-to-use interface that automatically deals with these requirements.
\see PxCreateBroadPhase
*/
class PxBroadPhase
{
protected:
PxBroadPhase() {}
virtual ~PxBroadPhase() {}
public:
/*
\brief Releases the broadphase.
*/
virtual void release() = 0;
/**
\brief Gets the broadphase type.
\return Broadphase type.
\see PxBroadPhaseType::Enum
*/
virtual PxBroadPhaseType::Enum getType() const = 0;
/**
\brief Gets broad-phase caps.
\param caps [out] Broad-phase caps
\see PxBroadPhaseCaps
*/
virtual void getCaps(PxBroadPhaseCaps& caps) const = 0;
/**
\brief Retrieves the regions API if applicable.
For broadphases that do not use explicit user-defined regions, this call returns NULL.
\return Region API, or NULL.
\see PxBroadPhaseRegions
*/
virtual PxBroadPhaseRegions* getRegions() = 0;
/**
\brief Retrieves the broadphase allocator.
User-provided buffers should ideally be allocated with this allocator, for best performance.
This is especially true for the GPU broadphases, whose buffers need to be allocated in CUDA
host memory.
\return The broadphase allocator.
\see PxAllocatorCallback
*/
virtual PxAllocatorCallback* getAllocator() = 0;
/**
\brief Retrieves the profiler's context ID.
\return The context ID.
\see PxBroadPhaseDesc
*/
virtual PxU64 getContextID() const = 0;
/**
\brief Sets a scratch buffer
Some broadphases might take advantage of a scratch buffer to limit runtime allocations.
All broadphases still work without providing a scratch buffer, this is an optional function
that can potentially reduce runtime allocations.
\param scratchBlock [in] The scratch buffer
\param size [in] Size of the scratch buffer in bytes
*/
virtual void setScratchBlock(void* scratchBlock, PxU32 size) = 0;
/**
\brief Updates the broadphase and computes the lists of created/deleted pairs.
The provided update data describes changes to objects since the last broadphase update.
To benefit from potentially multithreaded implementations, it is necessary to provide a continuation
task to the function. It is legal to pass NULL there, but the underlying (CPU) implementations will
then run single-threaded.
\param updateData [in] The update data
\param continuation [in] Continuation task to enable multi-threaded implementations, or NULL.
\see PxBroadPhaseUpdateData PxBaseTask
*/
virtual void update(const PxBroadPhaseUpdateData& updateData, PxBaseTask* continuation=NULL) = 0;
/**
\brief Retrieves the broadphase results after an update.
This should be called once after each update call to retrieve the results of the broadphase. The
results are incremental, i.e. the system only returns new and lost pairs, not all current pairs.
\param results [out] The broadphase results
\see PxBroadPhaseResults
*/
virtual void fetchResults(PxBroadPhaseResults& results) = 0;
/**
\brief Helper for single-threaded updates.
This short helper function performs a single-theaded update and reports the results in a single call.
\param results [out] The broadphase results
\param updateData [in] The update data
\see PxBroadPhaseUpdateData PxBroadPhaseResults
*/
PX_FORCE_INLINE void update(PxBroadPhaseResults& results, const PxBroadPhaseUpdateData& updateData)
{
update(updateData);
fetchResults(results);
}
};
/**
\brief Broadphase factory function.
Use this function to create a new standalone broadphase.
\param desc [in] Broadphase descriptor
\return Newly created broadphase, or NULL
\see PxBroadPhase PxBroadPhaseDesc
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxBroadPhase* PxCreateBroadPhase(const PxBroadPhaseDesc& desc);
/**
\brief High-level broadphase API.
The low-level broadphase API (PxBroadPhase) only supports batched updates and has a few non-trivial
requirements for managing the bounds data.
The high-level broadphase API (PxAABBManager) is an easier-to-use one-object-at-a-time API that
automatically deals with the quirks of the PxBroadPhase data management.
\see PxCreateAABBManager
*/
class PxAABBManager
{
protected:
PxAABBManager() {}
virtual ~PxAABBManager() {}
public:
/*
\brief Releases the AABB manager.
*/
virtual void release() = 0;
/**
\brief Retrieves the underlying broadphase.
\return The managed broadphase.
\see PxBroadPhase
*/
virtual PxBroadPhase& getBroadPhase() = 0;
/**
\brief Retrieves the managed bounds.
This is needed as input parameters to functions like PxBroadPhaseRegions::addRegion.
\return The managed object bounds.
\see PxBounds3
*/
virtual const PxBounds3* getBounds() const = 0;
/**
\brief Retrieves the managed distances.
This is needed as input parameters to functions like PxBroadPhaseRegions::addRegion.
\return The managed object distances.
*/
virtual const float* getDistances() const = 0;
/**
\brief Retrieves the managed filter groups.
\return The managed object groups.
*/
virtual const PxBpFilterGroup* getGroups() const = 0;
/**
\brief Retrieves the managed buffers' capacity.
Bounds, distances and groups buffers have the same capacity.
\return The managed buffers' capacity.
*/
virtual PxU32 getCapacity() const = 0;
/**
\brief Adds an object to the manager.
Objects' indices are externally managed, i.e. they must be provided by users (as opposed to handles
that could be returned by this manager). The design allows users to identify an object by a single ID,
and use the same ID in multiple sub-systems.
\param index [in] The object's index
\param bounds [in] The object's bounds
\param group [in] The object's filter group
\param distance [in] The object's distance (optional)
\see PxBpIndex PxBounds3 PxBpFilterGroup
*/
virtual void addObject(PxBpIndex index, const PxBounds3& bounds, PxBpFilterGroup group, float distance=0.0f) = 0;
/**
\brief Removes an object from the manager.
\param index [in] The object's index
\see PxBpIndex
*/
virtual void removeObject(PxBpIndex index) = 0;
/**
\brief Updates an object in the manager.
This call can update an object's bounds, distance, or both.
It is not possible to update an object's filter group.
\param index [in] The object's index
\param bounds [in] The object's updated bounds, or NULL
\param distance [in] The object's updated distance, or NULL
\see PxBpIndex PxBounds3
*/
virtual void updateObject(PxBpIndex index, const PxBounds3* bounds=NULL, const float* distance=NULL) = 0;
/**
\brief Updates the broadphase and computes the lists of created/deleted pairs.
The data necessary for updating the broadphase is internally computed by the AABB manager.
To benefit from potentially multithreaded implementations, it is necessary to provide a continuation
task to the function. It is legal to pass NULL there, but the underlying (CPU) implementations will
then run single-threaded.
\param continuation [in] Continuation task to enable multi-threaded implementations, or NULL.
\see PxBaseTask
*/
virtual void update(PxBaseTask* continuation=NULL) = 0;
/**
\brief Retrieves the broadphase results after an update.
This should be called once after each update call to retrieve the results of the broadphase. The
results are incremental, i.e. the system only returns new and lost pairs, not all current pairs.
\param results [out] The broadphase results
\see PxBroadPhaseResults
*/
virtual void fetchResults(PxBroadPhaseResults& results) = 0;
/**
\brief Helper for single-threaded updates.
This short helper function performs a single-theaded update and reports the results in a single call.
\param results [out] The broadphase results
\see PxBroadPhaseResults
*/
PX_FORCE_INLINE void update(PxBroadPhaseResults& results)
{
update();
fetchResults(results);
}
};
/**
\brief AABB manager factory function.
Use this function to create a new standalone high-level broadphase.
\param broadphase [in] The broadphase that will be managed by the AABB manager
\return Newly created AABB manager, or NULL
\see PxAABBManager PxBroadPhase
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxAABBManager* PxCreateAABBManager(PxBroadPhase& broadphase);
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 25,948 | C | 35.754957 | 171 | 0.753931 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleGpu.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_GPU_PARTICLE_SYSTEM_H
#define PX_GPU_PARTICLE_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec3.h"
#include "PxParticleSystem.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
@brief Common material properties for particles. See #PxParticleMaterial.
Accessed by either integration or particle-rigid collisions
*/
struct PxsParticleMaterialData
{
PxReal friction; // 4
PxReal damping; // 8
PxReal adhesion; // 12
PxReal gravityScale; // 16
PxReal adhesionRadiusScale; // 20
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#if PX_SUPPORT_GPU_PHYSX
struct float4;
PX_CUDA_CALLABLE inline physx::PxU32 PxGetGroup(physx::PxU32 phase) { return phase & physx::PxParticlePhaseFlag::eParticlePhaseGroupMask; }
PX_CUDA_CALLABLE inline bool PxGetFluid(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseFluid) != 0; }
PX_CUDA_CALLABLE inline bool PxGetSelfCollide(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseSelfCollide) != 0; }
PX_CUDA_CALLABLE inline bool PxGetSelfCollideFilter(physx::PxU32 phase) { return (phase & physx::PxParticlePhaseFlag::eParticlePhaseSelfCollideFilter) != 0; }
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
@brief An iterator class to iterate over the neighbors of a particle during particle system simulation.
*/
class PxNeighborhoodIterator
{
const PxU32* PX_RESTRICT mCollisionIndex; //!< Pointer to the current state of the iterator.
PxU32 mMaxParticles; //!< The maximum number of particles of the particle system this iterator is used on.
public:
PX_CUDA_CALLABLE PxNeighborhoodIterator(const PxU32* PX_RESTRICT collisionIndex, PxU32 maxParticles) :
mCollisionIndex(collisionIndex), mMaxParticles(maxParticles)
{
}
PX_CUDA_CALLABLE PxU32 getNextIndex()
{
PxU32 result = *mCollisionIndex;
mCollisionIndex += mMaxParticles;
return result;
}
PX_INLINE PxNeighborhoodIterator(const PxNeighborhoodIterator& params)
{
mCollisionIndex = params.mCollisionIndex;
mMaxParticles = params.mMaxParticles;
}
PX_INLINE void operator = (const PxNeighborhoodIterator& params)
{
mCollisionIndex = params.mCollisionIndex;
mMaxParticles = params.mMaxParticles;
}
};
/**
@brief Structure that holds simulation parameters of a #PxGpuParticleSystem.
*/
struct PxGpuParticleData
{
PxU32 mGridSizeX; //!< Size of the x-dimension of the background simulation grid. Translates to an absolute size of mGridSizeX * mParticleContactDistance.
PxU32 mGridSizeY; //!< Size of the y-dimension of the background simulation grid. Translates to an absolute size of mGridSizeY * mParticleContactDistance.
PxU32 mGridSizeZ; //!< Size of the z-dimension of the background simulation grid. Translates to an absolute size of mGridSizeZ * mParticleContactDistance.
PxReal mParticleContactDistance; //!< Two particles start interacting if their distance is lower than mParticleContactDistance.
PxReal mParticleContactDistanceInv; //!< 1.f / mParticleContactDistance.
PxReal mParticleContactDistanceSq; //!< mParticleContactDistance * mParticleContactDistance.
PxU32 mNumParticles; //!< The number of particles in this particle system.
PxU32 mMaxParticles; //!< The maximum number of particles that can be simulated in this particle system.
PxU32 mMaxNeighborhood; //!< The maximum number of particles considered when computing neighborhood based particle interactions.
PxU32 mMaxDiffuseParticles; //!< The maximum number of diffuse particles that can be simulated using this particle system.
PxU32 mNumParticleBuffers; //!< The number of particle buffers that are simulated in this particle system.
};
/**
@brief Container class for a GPU particle system. Used to communicate particle system parameters and simulation state
between the internal SDK simulation and the particle system callbacks.
See #PxParticleSystem, #PxParticleSystemCallback.
*/
class PxGpuParticleSystem
{
public:
/**
@brief Returns the number of cells of the background simulation grid.
@return PxU32 the number of cells.
*/
PX_FORCE_INLINE PxU32 getNumCells() { return mCommonData.mGridSizeX * mCommonData.mGridSizeY * mCommonData.mGridSizeZ; }
/* Unsorted particle state buffers */
float4* mUnsortedPositions_InvMass; //!< GPU pointer to unsorted particle positions and inverse masses.
float4* mUnsortedVelocities; //!< GPU pointer to unsorted particle velocities.
PxU32* mUnsortedPhaseArray; //!< GPU pointer to unsorted particle phase array. See #PxParticlePhase.
/* Sorted particle state buffers. Sorted by increasing hash value in background grid. */
float4* mSortedPositions_InvMass; //!< GPU pointer to sorted particle positions
float4* mSortedVelocities; //!< GPU pointer to sorted particle velocities
PxU32* mSortedPhaseArray; //!< GPU pointer to sorted particle phase array
/* Mappings to/from sorted particle states */
PxU32* mUnsortedToSortedMapping; //!< GPU pointer to the mapping from unsortedParticle ID to sorted particle ID
PxU32* mSortedToUnsortedMapping; //!< GPU pointer to the mapping from sorted particle ID to unsorted particle ID
/* Neighborhood information */
PxU32* mParticleSelfCollisionCount; //!< Per-particle neighborhood count
PxU32* mCollisionIndex; //!< Set of sorted particle indices per neighbor
PxsParticleMaterialData* mParticleMaterials; //!< GPU pointer to the particle materials used in this particle system.
PxGpuParticleData mCommonData; //!< Structure holding simulation parameters and state for this particle system. See #PxGpuParticleData.
/**
@brief Get a PxNeighborhoodIterator initialized for usage with this particle system.
@param particleId An initial particle index for the initialization of the iterator.
@return An initialized PxNeighborhoodIterator.
*/
PX_CUDA_CALLABLE PxNeighborhoodIterator getIterator(PxU32 particleId) const
{
return PxNeighborhoodIterator(mCollisionIndex + particleId, mCommonData.mMaxParticles);
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
/** @} */
#endif
| 8,283 | C | 42.371728 | 176 | 0.727756 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysicsSerialization.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PHYSICS_SERIALIZATION_H
#define PX_PHYSICS_SERIALIZATION_H
#include "common/PxSerialFramework.h"
#include "PxPhysXConfig.h"
#if !PX_DOXYGEN
/**
\brief Retrieves the PhysX SDK metadata.
\deprecated Binary conversion and binary meta data are deprecated.
This function is used to implement PxSerialization.dumpBinaryMetaData() and is not intended to be needed otherwise.
@see PxSerialization.dumpBinaryMetaData()
*/
PX_DEPRECATED PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxGetPhysicsBinaryMetaData(physx::PxOutputStream& stream);
/**
\brief Registers physics classes for serialization.
This function is used to implement PxSerialization.createSerializationRegistry() and is not intended to be needed otherwise.
@see PxSerializationRegistry
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxRegisterPhysicsSerializers(physx::PxSerializationRegistry& sr);
/**
\brief Unregisters physics classes for serialization.
This function is used in the release implementation of PxSerializationRegistry and in not intended to be used otherwise.
@see PxSerializationRegistry
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxUnregisterPhysicsSerializers(physx::PxSerializationRegistry& sr);
/**
\brief Adds collected objects to PxPhysics.
This function adds all objects contained in the input collection to the PxPhysics instance. This is used after deserializing
the collection, to populate the physics with inplace deserialized objects. This function is used in the implementation of
PxSerialization.createCollectionFromBinary and is not intended to be needed otherwise.
\param[in] collection Objects to add to the PxPhysics instance.
@see PxCollection, PxSerialization.createCollectionFromBinary
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PX_CALL_CONV PxAddCollectionToPhysics(const physx::PxCollection& collection);
#endif // !PX_DOXYGEN
#endif
| 3,564 | C | 45.298701 | 124 | 0.792368 |
NVIDIA-Omniverse/PhysX/physx/include/PxSimulationStatistics.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SIMULATION_STATISTICS_H
#define PX_SIMULATION_STATISTICS_H
/** \addtogroup physics
@{
*/
#include "foundation/PxAssert.h"
#include "PxPhysXConfig.h"
#include "geometry/PxGeometry.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Class used to retrieve statistics for a simulation step.
@see PxScene::getSimulationStatistics()
*/
class PxSimulationStatistics
{
public:
/**
\brief Different types of rigid body collision pair statistics.
@see getRbPairStats
*/
enum RbPairStatsType
{
/**
\brief Shape pairs processed as discrete contact pairs for the current simulation step.
*/
eDISCRETE_CONTACT_PAIRS,
/**
\brief Shape pairs processed as swept integration pairs for the current simulation step.
\note Counts the pairs for which special CCD (continuous collision detection) work was actually done and NOT the number of pairs which were configured for CCD.
Furthermore, there can be multiple CCD passes and all processed pairs of all passes are summed up, hence the number can be larger than the amount of pairs which have been configured for CCD.
@see PxPairFlag::eDETECT_CCD_CONTACT,
*/
eCCD_PAIRS,
/**
\brief Shape pairs processed with user contact modification enabled for the current simulation step.
@see PxContactModifyCallback
*/
eMODIFIED_CONTACT_PAIRS,
/**
\brief Trigger shape pairs processed for the current simulation step.
@see PxShapeFlag::eTRIGGER_SHAPE
*/
eTRIGGER_PAIRS
};
//objects:
/**
\brief Number of active PxConstraint objects (joints etc.) for the current simulation step.
*/
PxU32 nbActiveConstraints;
/**
\brief Number of active dynamic bodies for the current simulation step.
\note Does not include active kinematic bodies
*/
PxU32 nbActiveDynamicBodies;
/**
\brief Number of active kinematic bodies for the current simulation step.
\note Kinematic deactivation occurs at the end of the frame after the last call to PxRigidDynamic::setKinematicTarget() was called so kinematics that are
deactivated in a given frame will be included by this counter.
*/
PxU32 nbActiveKinematicBodies;
/**
\brief Number of static bodies for the current simulation step.
*/
PxU32 nbStaticBodies;
/**
\brief Number of dynamic bodies for the current simulation step.
\note Includes inactive bodies and articulation links
\note Does not include kinematic bodies
*/
PxU32 nbDynamicBodies;
/**
\brief Number of kinematic bodies for the current simulation step.
\note Includes inactive bodies
*/
PxU32 nbKinematicBodies;
/**
\brief Number of shapes of each geometry type.
*/
PxU32 nbShapes[PxGeometryType::eGEOMETRY_COUNT];
/**
\brief Number of aggregates in the scene.
*/
PxU32 nbAggregates;
/**
\brief Number of articulations in the scene.
*/
PxU32 nbArticulations;
//solver:
/**
\brief The number of 1D axis constraints(joints+contact) present in the current simulation step.
*/
PxU32 nbAxisSolverConstraints;
/**
\brief The size (in bytes) of the compressed contact stream in the current simulation step
*/
PxU32 compressedContactSize;
/**
\brief The total required size (in bytes) of the contact constraints in the current simulation step
*/
PxU32 requiredContactConstraintMemory;
/**
\brief The peak amount of memory (in bytes) that was allocated for constraints (this includes joints) in the current simulation step
*/
PxU32 peakConstraintMemory;
//broadphase:
/**
\brief Get number of broadphase volumes added for the current simulation step.
\return Number of broadphase volumes added.
*/
PX_FORCE_INLINE PxU32 getNbBroadPhaseAdds() const
{
return nbBroadPhaseAdds;
}
/**
\brief Get number of broadphase volumes removed for the current simulation step.
\return Number of broadphase volumes removed.
*/
PX_FORCE_INLINE PxU32 getNbBroadPhaseRemoves() const
{
return nbBroadPhaseRemoves;
}
//collisions:
/**
\brief Get number of shape collision pairs of a certain type processed for the current simulation step.
There is an entry for each geometry pair type.
\note entry[i][j] = entry[j][i], hence, if you want the sum of all pair
types, you need to discard the symmetric entries
\param[in] pairType The type of pair for which to get information
\param[in] g0 The geometry type of one pair object
\param[in] g1 The geometry type of the other pair object
\return Number of processed pairs of the specified geometry types.
*/
PxU32 getRbPairStats(RbPairStatsType pairType, PxGeometryType::Enum g0, PxGeometryType::Enum g1) const
{
PX_ASSERT_WITH_MESSAGE( (pairType >= eDISCRETE_CONTACT_PAIRS) &&
(pairType <= eTRIGGER_PAIRS),
"Invalid pairType in PxSimulationStatistics::getRbPairStats");
if (g0 >= PxGeometryType::eGEOMETRY_COUNT || g1 >= PxGeometryType::eGEOMETRY_COUNT)
{
PX_ASSERT(false);
return 0;
}
PxU32 nbPairs = 0;
switch(pairType)
{
case eDISCRETE_CONTACT_PAIRS:
nbPairs = nbDiscreteContactPairs[g0][g1];
break;
case eCCD_PAIRS:
nbPairs = nbCCDPairs[g0][g1];
break;
case eMODIFIED_CONTACT_PAIRS:
nbPairs = nbModifiedContactPairs[g0][g1];
break;
case eTRIGGER_PAIRS:
nbPairs = nbTriggerPairs[g0][g1];
break;
}
return nbPairs;
}
/**
\brief Total number of (non CCD) pairs reaching narrow phase
*/
PxU32 nbDiscreteContactPairsTotal;
/**
\brief Total number of (non CCD) pairs for which contacts are successfully cached (<=nbDiscreteContactPairsTotal)
\note This includes pairs for which no contacts are generated, it still counts as a cache hit.
*/
PxU32 nbDiscreteContactPairsWithCacheHits;
/**
\brief Total number of (non CCD) pairs for which at least 1 contact was generated (<=nbDiscreteContactPairsTotal)
*/
PxU32 nbDiscreteContactPairsWithContacts;
/**
\brief Number of new pairs found by BP this frame
*/
PxU32 nbNewPairs;
/**
\brief Number of lost pairs from BP this frame
*/
PxU32 nbLostPairs;
/**
\brief Number of new touches found by NP this frame
*/
PxU32 nbNewTouches;
/**
\brief Number of lost touches from NP this frame
*/
PxU32 nbLostTouches;
/**
\brief Number of partitions used by the solver this frame
*/
PxU32 nbPartitions;
/**
\brief GPU device memory in bytes allocated for particle state accessible through API
*/
PxU64 gpuMemParticles;
/**
\brief GPU device memory in bytes allocated for FEM-based soft body state accessible through API
*/
PxU64 gpuMemSoftBodies;
/**
\brief GPU device memory in bytes allocated for FEM-based cloth state accessible through API
*/
PxU64 gpuMemFEMCloths;
/**
\brief GPU device memory in bytes allocated for hairsystem state accessible through API
*/
PxU64 gpuMemHairSystems;
/**
\brief GPU device memory in bytes allocated for internal heap allocation
*/
PxU64 gpuMemHeap;
/**
\brief GPU device heap memory used for broad phase in bytes
*/
PxU64 gpuMemHeapBroadPhase;
/**
\brief GPU device heap memory used for narrow phase in bytes
*/
PxU64 gpuMemHeapNarrowPhase;
/**
\brief GPU device heap memory used for solver in bytes
*/
PxU64 gpuMemHeapSolver;
/**
\brief GPU device heap memory used for articulations in bytes
*/
PxU64 gpuMemHeapArticulation;
/**
\brief GPU device heap memory used for simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulation;
/**
\brief GPU device heap memory used for articulations in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationArticulation;
/**
\brief GPU device heap memory used for particles in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationParticles;
/**
\brief GPU device heap memory used for soft bodies in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationSoftBody;
/**
\brief GPU device heap memory used for FEM-cloth in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationFEMCloth;
/**
\brief GPU device heap memory used for hairsystem in the simulation pipeline in bytes
*/
PxU64 gpuMemHeapSimulationHairSystem;
/**
\brief GPU device heap memory used for shared buffers in the particles pipeline in bytes
*/
PxU64 gpuMemHeapParticles;
/**
\brief GPU device heap memory used for shared buffers in the FEM-based soft body pipeline in bytes
*/
PxU64 gpuMemHeapSoftBodies;
/**
\brief GPU device heap memory used for shared buffers in the FEM-based cloth pipeline in bytes
*/
PxU64 gpuMemHeapFEMCloths;
/**
\brief GPU device heap memory used for shared buffers in the hairsystem pipeline in bytes
*/
PxU64 gpuMemHeapHairSystems;
/**
\brief GPU device heap memory not covered by other stats in bytes
*/
PxU64 gpuMemHeapOther;
PxSimulationStatistics() :
nbActiveConstraints (0),
nbActiveDynamicBodies (0),
nbActiveKinematicBodies (0),
nbStaticBodies (0),
nbDynamicBodies (0),
nbKinematicBodies (0),
nbAggregates (0),
nbArticulations (0),
nbAxisSolverConstraints (0),
compressedContactSize (0),
requiredContactConstraintMemory (0),
peakConstraintMemory (0),
nbDiscreteContactPairsTotal (0),
nbDiscreteContactPairsWithCacheHits (0),
nbDiscreteContactPairsWithContacts (0),
nbNewPairs (0),
nbLostPairs (0),
nbNewTouches (0),
nbLostTouches (0),
nbPartitions (0),
gpuMemParticles (0),
gpuMemSoftBodies (0),
gpuMemFEMCloths (0),
gpuMemHairSystems (0),
gpuMemHeap (0),
gpuMemHeapBroadPhase (0),
gpuMemHeapNarrowPhase (0),
gpuMemHeapSolver (0),
gpuMemHeapArticulation (0),
gpuMemHeapSimulation (0),
gpuMemHeapSimulationArticulation (0),
gpuMemHeapSimulationParticles (0),
gpuMemHeapSimulationSoftBody (0),
gpuMemHeapSimulationFEMCloth (0),
gpuMemHeapSimulationHairSystem (0),
gpuMemHeapParticles (0),
gpuMemHeapSoftBodies (0),
gpuMemHeapFEMCloths (0),
gpuMemHeapHairSystems (0),
gpuMemHeapOther (0)
{
nbBroadPhaseAdds = 0;
nbBroadPhaseRemoves = 0;
for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++)
{
for(PxU32 j=0; j < PxGeometryType::eGEOMETRY_COUNT; j++)
{
nbDiscreteContactPairs[i][j] = 0;
nbModifiedContactPairs[i][j] = 0;
nbCCDPairs[i][j] = 0;
nbTriggerPairs[i][j] = 0;
}
}
for(PxU32 i=0; i < PxGeometryType::eGEOMETRY_COUNT; i++)
{
nbShapes[i] = 0;
}
}
//
// We advise to not access these members directly. Use the provided accessor methods instead.
//
//broadphase:
PxU32 nbBroadPhaseAdds;
PxU32 nbBroadPhaseRemoves;
//collisions:
PxU32 nbDiscreteContactPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 nbCCDPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 nbModifiedContactPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
PxU32 nbTriggerPairs[PxGeometryType::eGEOMETRY_COUNT][PxGeometryType::eGEOMETRY_COUNT];
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 12,687 | C | 26.703057 | 192 | 0.733901 |
NVIDIA-Omniverse/PhysX/physx/include/PxBaseMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_BASE_MATERIAL_H
#define PX_BASE_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Base material class.
@see PxPhysics.createMaterial PxPhysics.createFEMClothMaterial PxPhysics.createFEMSoftBodyMaterial PxPhysics.createFLIPMaterial PxPhysics.createMPMMaterial PxPhysics.createPBDMaterial
*/
class PxBaseMaterial : public PxRefCounted
{
public:
PX_INLINE PxBaseMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxBaseMaterial(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
virtual ~PxBaseMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxBaseMaterial", PxRefCounted); }
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,698 | C | 40.523076 | 184 | 0.760193 |
NVIDIA-Omniverse/PhysX/physx/include/PxSDFBuilder.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SDF_BUILDER_H
#define PX_SDF_BUILDER_H
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "foundation/PxArray.h"
#include "cooking/PxSDFDesc.h"
#include "cudamanager/PxCudaTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Utility class to compute an SDF on the GPU
*/
class PxSDFBuilder
{
public:
/**
\brief Constructs a dense grid SDF for a triangle mesh using the GPU
\param[in] vertices The vertices of the triangle mesh
\param[in] numVertices The number of vertices
\param[in] indices The triangle indices
\param[in] numTriangleIndices The number of triangle indices
\param[in] width The number of samples along the x direction of the resulting SDF volume
\param[in] height The number of samples along the y direction of the resulting SDF volume
\param[in] depth The number of samples along the z direction of the resulting SDF volume
\param[in] minExtents The minimum corner location of the axis aligned box containing the SDF samples.
\param[in] maxExtents The maximum corner location of the axis aligned box containing the SDF samples.
\param[in] cellCenteredSamples Determines if the sample points are located at the center of a SDF cell or at the lower left (=min) corner of a cell.
\param[out] sdf The distance values. Must provide space for width*height*depth distance samples. Negative distance means the sample point is located inside of the triangle mesh.
\param[in] stream The cuda stream on which the conversion is processed. If the default stream (0) is used, a temporary stream will be created internally.
*/
virtual void buildSDF(const PxVec3* vertices, PxU32 numVertices, const PxU32* indices, PxU32 numTriangleIndices, PxU32 width, PxU32 height, PxU32 depth,
const PxVec3& minExtents, const PxVec3& maxExtents, bool cellCenteredSamples, PxReal* sdf, CUstream stream = 0) = 0;
/**
\brief Constructs a sparse grid SDF for a triangle mesh using the GPU
\param[in] vertices The vertices of the triangle mesh
\param[in] numVertices The number of vertices
\param[in] indices The triangle indices
\param[in] numTriangleIndices The number of triangle indices
\param[in] width The number of samples along the x direction of the resulting SDF volume
\param[in] height The number of samples along the y direction of the resulting SDF volume
\param[in] depth The number of samples along the z direction of the resulting SDF volume
\param[in] minExtents The minimum corner location of the axis aligned box containing the SDF samples.
\param[in] maxExtents The maximum corner location of the axis aligned box containing the SDF samples.
\param[in] narrowBandThickness The thickness of the narrow band.
\param[in] cellsPerSubgrid The number of cells in a sparse subgrid block (full block has mSubgridSize^3 cells and (mSubgridSize+1)^3 samples)
\param[in] bitsPerSubgridPixel Subgrid pixel compression
\param[out] subgridsMinSdfValue Used to store the minimum sdf value over all subgrids
\param[out] subgridsMaxSdfValue Used to store the maximum sdf value over all subgrids
\param[out] sdfSubgrids3DTexBlockDimX Used to store x dimension of the texture block that stores the subgrids
\param[out] sdfSubgrids3DTexBlockDimY Used to store y dimension of the texture block that stores the subgrids
\param[out] sdfSubgrids3DTexBlockDimZ Used to store z dimension of the texture block that stores the subgrids
\param[in] stream The cuda stream on which the conversion is processed. If the default stream (0) is used, a temporary stream will be created internally.
*/
virtual void buildSparseSDF(const PxVec3* vertices, PxU32 numVertices, const PxU32* indices, PxU32 numTriangleIndices, PxU32 width, PxU32 height, PxU32 depth,
const PxVec3& minExtents, const PxVec3& maxExtents, PxReal narrowBandThickness, PxU32 cellsPerSubgrid, PxSdfBitsPerSubgridPixel::Enum bitsPerSubgridPixel,
PxArray<PxReal>& sdfCoarse, PxArray<PxU32>& sdfSubgridsStartSlots, PxArray<PxU8>& sdfDataSubgrids,
PxReal& subgridsMinSdfValue, PxReal& subgridsMaxSdfValue,
PxU32& sdfSubgrids3DTexBlockDimX, PxU32& sdfSubgrids3DTexBlockDimY, PxU32& sdfSubgrids3DTexBlockDimZ, CUstream stream = 0) = 0;
/**
\brief Releases the memory including the this pointer
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxSDFBuilder() { }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 6,167 | C | 53.105263 | 178 | 0.781417 |
NVIDIA-Omniverse/PhysX/physx/include/PxLockedData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_LOCKED_DATA_H
#define PX_LOCKED_DATA_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxDataAccessFlag
{
enum Enum
{
eREADABLE = (1 << 0),
eWRITABLE = (1 << 1),
eDEVICE = (1 << 2)
};
};
/**
\brief collection of set bits defined in PxDataAccessFlag.
@see PxDataAccessFlag
*/
typedef PxFlags<PxDataAccessFlag::Enum,PxU8> PxDataAccessFlags;
PX_FLAGS_OPERATORS(PxDataAccessFlag::Enum,PxU8)
/**
\brief Parent class for bulk data that is shared between the SDK and the application.
*/
class PxLockedData
{
public:
/**
\brief Any combination of PxDataAccessFlag::eREADABLE and PxDataAccessFlag::eWRITABLE
@see PxDataAccessFlag
*/
virtual PxDataAccessFlags getDataAccessFlags() = 0;
/**
\brief Unlocks the bulk data.
*/
virtual void unlock() = 0;
/**
\brief virtual destructor
*/
virtual ~PxLockedData() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,706 | C | 28.423913 | 86 | 0.739468 |
NVIDIA-Omniverse/PhysX/physx/include/PxMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_MATERIAL_H
#define PX_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxBaseMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxScene;
/**
\brief Flags which control the behavior of a material.
@see PxMaterial
*/
struct PxMaterialFlag
{
enum Enum
{
/**
\brief If this flag is set, friction computations are always skipped between shapes with this material and any other shape.
*/
eDISABLE_FRICTION = 1 << 0,
/**
\brief Whether to use strong friction.
The difference between "normal" and "strong" friction is that the strong friction feature
remembers the "friction error" between simulation steps. The friction is a force trying to
hold objects in place (or slow them down) and this is handled in the solver. But since the
solver is only an approximation, the result of the friction calculation can include a small
"error" - e.g. a box resting on a slope should not move at all if the static friction is in
action, but could slowly glide down the slope because of a small friction error in each
simulation step. The strong friction counter-acts this by remembering the small error and
taking it to account during the next simulation step.
However, in some cases the strong friction could cause problems, and this is why it is
possible to disable the strong friction feature by setting this flag. One example is
raycast vehicles that are sliding fast across the surface, but still need a precise
steering behavior. It may be a good idea to reenable the strong friction when objects
are coming to a rest, to prevent them from slowly creeping down inclines.
Note: This flag only has an effect if the PxMaterialFlag::eDISABLE_FRICTION bit is 0.
*/
eDISABLE_STRONG_FRICTION = 1 << 1,
/**
\brief Whether to correct the friction force applied by the patch friction model to better match analytical models.
This flag only has an effect if the PxFrictionType::ePATCH friction model is used.
When using the patch friction model, up to two friction anchors are generated per patch. The normal force of all contacts
in the patch is accumulated and equally distributed among the anchors in order to compute friction forces. If this flag
is disabled, the legacy behavior is active which produces double the expected friction force in the case of two anchors,
since the full accumulated normal force is used in both anchors for the friction computation.
*/
eIMPROVED_PATCH_FRICTION = 1 << 2,
/**
\brief This flag has the effect of enabling an implicit spring model for the normal force computation.
@see PxMaterial.setRestitution, PxMaterial.setDamping
*/
eCOMPLIANT_CONTACT = 1 << 3
};
};
/**
\brief collection of set bits defined in PxMaterialFlag.
@see PxMaterialFlag
*/
typedef PxFlags<PxMaterialFlag::Enum,PxU16> PxMaterialFlags;
PX_FLAGS_OPERATORS(PxMaterialFlag::Enum,PxU16)
/**
\brief Enumeration that determines the way in which two material properties will be combined to yield a friction or restitution coefficient for a collision.
When two actors come in contact with each other, they each have materials with various coefficients, but we only need a single set of coefficients for the pair.
Physics doesn't have any inherent combinations because the coefficients are determined empirically on a case by case
basis. However, simulating this with a pairwise lookup table is often impractical.
For this reason the following combine behaviors are available:
eAVERAGE
eMIN
eMULTIPLY
eMAX
The effective combine mode for the pair is maximum(material0.combineMode, material1.combineMode).
@see PxMaterial.setFrictionCombineMode() PxMaterial.getFrictionCombineMode() PxMaterial.setRestitutionCombineMode() PxMaterial.getFrictionCombineMode()
*/
struct PxCombineMode
{
enum Enum
{
eAVERAGE = 0, //!< Average: (a + b)/2
eMIN = 1, //!< Minimum: minimum(a,b)
eMULTIPLY = 2, //!< Multiply: a*b
eMAX = 3, //!< Maximum: maximum(a,b)
eN_VALUES = 4, //!< This is not a valid combine mode, it is a sentinel to denote the number of possible values. We assert that the variable's value is smaller than this.
ePAD_32 = 0x7fffffff //!< This is not a valid combine mode, it is to assure that the size of the enum type is big enough.
};
};
/**
\brief Material class to represent a set of surface properties.
@see PxPhysics.createMaterial
*/
class PxMaterial : public PxBaseMaterial
{
public:
/**
\brief Sets the coefficient of dynamic friction.
The coefficient of dynamic friction should be in [0, PX_MAX_F32). If set to greater than staticFriction, the effective value of staticFriction will be increased to match.
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] coef Coefficient of dynamic friction. <b>Range:</b> [0, PX_MAX_F32)
@see getDynamicFriction()
*/
virtual void setDynamicFriction(PxReal coef) = 0;
/**
\brief Retrieves the DynamicFriction value.
\return The coefficient of dynamic friction.
@see setDynamicFriction
*/
virtual PxReal getDynamicFriction() const = 0;
/**
\brief Sets the coefficient of static friction
The coefficient of static friction should be in the range [0, PX_MAX_F32)
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] coef Coefficient of static friction. <b>Range:</b> [0, PX_MAX_F32)
@see getStaticFriction()
*/
virtual void setStaticFriction(PxReal coef) = 0;
/**
\brief Retrieves the coefficient of static friction.
\return The coefficient of static friction.
@see setStaticFriction
*/
virtual PxReal getStaticFriction() const = 0;
/**
\brief Sets the coefficient of restitution
A coefficient of 0 makes the object bounce as little as possible, higher values up to 1.0 result in more bounce.
This property is overloaded when PxMaterialFlag::eCOMPLIANT_CONTACT flag is enabled. This permits negative values for restitution to be provided.
The negative values are converted into spring stiffness terms for an implicit spring simulated at the contact site, with the spring positional error defined by
the contact separation value. Higher stiffness terms produce stiffer springs that behave more like a rigid contact.
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] rest Coefficient of restitution. <b>Range:</b> [-INF,1]
@see getRestitution()
*/
virtual void setRestitution(PxReal rest) = 0;
/**
\brief Retrieves the coefficient of restitution.
See #setRestitution.
\return The coefficient of restitution.
@see setRestitution()
*/
virtual PxReal getRestitution() const = 0;
/**
\brief Sets the coefficient of damping
This property only affects the simulation if PxMaterialFlag::eCOMPLIANT_CONTACT is raised.
Damping works together with spring stiffness (set through a negative restitution value). Spring stiffness corrects positional error while
damping resists relative velocity. Setting a high damping coefficient can produce spongy contacts.
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] damping Coefficient of damping. <b>Range:</b> [0,INF]
@see getDamping()
*/
virtual void setDamping(PxReal damping) = 0;
/**
\brief Retrieves the coefficient of damping.
See #setDamping.
\return The coefficient of damping.
@see setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Raises or clears a particular material flag.
See the list of flags #PxMaterialFlag
<b>Default:</b> eIMPROVED_PATCH_FRICTION
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] flag The PxMaterial flag to raise(set) or clear.
\param[in] b New state of the flag
@see getFlags() setFlags() PxMaterialFlag
*/
virtual void setFlag(PxMaterialFlag::Enum flag, bool b) = 0;
/**
\brief sets all the material flags.
See the list of flags #PxMaterialFlag
<b>Default:</b> eIMPROVED_PATCH_FRICTION
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] flags All PxMaterial flags
@see getFlags() setFlag() PxMaterialFlag
*/
virtual void setFlags(PxMaterialFlags flags) = 0;
/**
\brief Retrieves the flags. See #PxMaterialFlag.
\return The material flags.
@see PxMaterialFlag setFlags()
*/
virtual PxMaterialFlags getFlags() const = 0;
/**
\brief Sets the friction combine mode.
See the enum ::PxCombineMode .
<b>Default:</b> PxCombineMode::eAVERAGE
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] combMode Friction combine mode to set for this material. See #PxCombineMode.
@see PxCombineMode getFrictionCombineMode setStaticFriction() setDynamicFriction()
*/
virtual void setFrictionCombineMode(PxCombineMode::Enum combMode) = 0;
/**
\brief Retrieves the friction combine mode.
See #setFrictionCombineMode.
\return The friction combine mode for this material.
@see PxCombineMode setFrictionCombineMode()
*/
virtual PxCombineMode::Enum getFrictionCombineMode() const = 0;
/**
\brief Sets the restitution combine mode.
See the enum ::PxCombineMode .
<b>Default:</b> PxCombineMode::eAVERAGE
<b>Sleeping:</b> Does <b>NOT</b> wake any actors which may be affected.
\param[in] combMode Restitution combine mode for this material. See #PxCombineMode.
@see PxCombineMode getRestitutionCombineMode() setRestitution()
*/
virtual void setRestitutionCombineMode(PxCombineMode::Enum combMode) = 0;
/**
\brief Retrieves the restitution combine mode.
See #setRestitutionCombineMode.
\return The coefficient of restitution combine mode for this material.
@see PxCombineMode setRestitutionCombineMode getRestitution()
*/
virtual PxCombineMode::Enum getRestitutionCombineMode() const = 0;
// PxBase
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxMaterial"; }
//~PxBase
protected:
PX_INLINE PxMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxBaseMaterial(concreteType, baseFlags) {}
PX_INLINE PxMaterial(PxBaseFlags baseFlags) : PxBaseMaterial(baseFlags) {}
virtual ~PxMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxMaterial", PxBaseMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 11,967 | C | 32.80791 | 172 | 0.751734 |
NVIDIA-Omniverse/PhysX/physx/include/PxHairSystemFlag.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_HAIR_SYSTEM_FLAG_H
#define PX_HAIR_SYSTEM_FLAG_H
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Identifies input and output buffers for PxHairSystem
*/
struct PxHairSystemData
{
enum Enum
{
eNONE = 0, //!< No data specified
ePOSITION_INVMASS = 1 << 0, //!< Specifies the position (first 3 floats) and inverse mass (last float) data (array of PxVec4 * max number of vertices)
eVELOCITY = 1 << 1, //!< Specifies the velocity (first 3 floats) data (array of PxVec4 * max number of vertices)
eALL = ePOSITION_INVMASS | eVELOCITY //!< Specifies everything
};
};
typedef PxFlags<PxHairSystemData::Enum, PxU32> PxHairSystemDataFlags;
/**
\brief Binary settings for hair system simulation
*/
struct PxHairSystemFlag
{
enum Enum
{
eDISABLE_SELF_COLLISION = 1 << 0, //!< Determines if self-collision between hair vertices is ignored
eDISABLE_EXTERNAL_COLLISION = 1 << 1, //!< Determines if collision between hair and external bodies is ignored
eDISABLE_TWOSIDED_ATTACHMENT = 1 << 2 //!< Determines if attachment constraint is also felt by body to which the hair is attached
};
};
typedef PxFlags<PxHairSystemFlag::Enum, PxU32> PxHairSystemFlags;
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 3,044 | C | 40.148648 | 160 | 0.737516 |
NVIDIA-Omniverse/PhysX/physx/include/PxActor.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ACTOR_H
#define PX_ACTOR_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxBounds3.h"
#include "PxClient.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxRigidActor;
class PxRigidBody;
class PxRigidStatic;
class PxRigidDynamic;
class PxArticulationLink;
class PxScene;
/**
\brief Group index which allows to specify 1- or 2-way interaction
*/
typedef PxU8 PxDominanceGroup; // Must be < 32, PxU8.
/**
\brief Flags which control the behavior of an actor.
@see PxActorFlags PxActor PxActor.setActorFlag() PxActor.getActorFlags()
*/
struct PxActorFlag
{
enum Enum
{
/**
\brief Enable debug renderer for this actor
@see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter
*/
eVISUALIZATION = (1<<0),
/**
\brief Disables scene gravity for this actor
*/
eDISABLE_GRAVITY = (1<<1),
/**
\brief Enables the sending of PxSimulationEventCallback::onWake() and PxSimulationEventCallback::onSleep() notify events
@see PxSimulationEventCallback::onWake() PxSimulationEventCallback::onSleep()
*/
eSEND_SLEEP_NOTIFIES = (1<<2),
/**
\brief Disables simulation for the actor.
\note This is only supported by PxRigidStatic and PxRigidDynamic actors and can be used to reduce the memory footprint when rigid actors are
used for scene queries only.
\note Setting this flag will remove all constraints attached to the actor from the scene.
\note If this flag is set, the following calls are forbidden:
\li PxRigidBody: setLinearVelocity(), setAngularVelocity(), addForce(), addTorque(), clearForce(), clearTorque(), setForceAndTorque()
\li PxRigidDynamic: setKinematicTarget(), setWakeCounter(), wakeUp(), putToSleep()
\par <b>Sleeping:</b>
Raising this flag will set all velocities and the wake counter to 0, clear all forces, clear the kinematic target, put the actor
to sleep and wake up all touching actors from the previous frame.
*/
eDISABLE_SIMULATION = (1<<3)
};
};
/**
\brief collection of set bits defined in PxActorFlag.
@see PxActorFlag
*/
typedef PxFlags<PxActorFlag::Enum,PxU8> PxActorFlags;
PX_FLAGS_OPERATORS(PxActorFlag::Enum,PxU8)
/**
\brief Identifies each type of actor.
@see PxActor
*/
struct PxActorType
{
enum Enum
{
/**
\brief A static rigid body
@see PxRigidStatic
*/
eRIGID_STATIC,
/**
\brief A dynamic rigid body
@see PxRigidDynamic
*/
eRIGID_DYNAMIC,
/**
\brief An articulation link
@see PxArticulationLink
*/
eARTICULATION_LINK,
/**
\brief A FEM-based soft body
@see PxSoftBody
*/
eSOFTBODY,
/**
\brief A FEM-based cloth
\note In development
@see PxFEMCloth
*/
eFEMCLOTH,
/**
\brief A PBD ParticleSystem
@see PxPBDParticleSystem
*/
ePBD_PARTICLESYSTEM,
/**
\brief A FLIP ParticleSystem
\note In development
@see PxFLIPParticleSystem
*/
eFLIP_PARTICLESYSTEM,
/**
\brief A MPM ParticleSystem
\note In development
@see PxMPMParticleSystem
*/
eMPM_PARTICLESYSTEM,
/**
\brief A HairSystem
\note In development
@see PxHairSystem
*/
eHAIRSYSTEM,
//! \brief internal use only!
eACTOR_COUNT,
//! \brief internal use only!
eACTOR_FORCE_DWORD = 0x7fffffff
};
};
/**
\brief PxActor is the base class for the main simulation objects in the physics SDK.
The actor is owned by and contained in a PxScene.
*/
class PxActor : public PxBase
{
public:
/**
\brief Deletes the actor.
Do not keep a reference to the deleted instance.
If the actor belongs to a #PxAggregate object, it is automatically removed from the aggregate.
@see PxBase.release(), PxAggregate
*/
virtual void release() = 0;
/**
\brief Retrieves the type of actor.
\return The actor type of the actor.
@see PxActorType
*/
virtual PxActorType::Enum getType() const = 0;
/**
\brief Retrieves the scene which this actor belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() const = 0;
// Runtime modifications
/**
\brief Sets a name string for the object that can be retrieved with getName().
This is for debugging and is not used by the SDK. The string is not copied by the SDK,
only the pointer is stored.
\param[in] name String to set the objects name to.
<b>Default:</b> NULL
@see getName()
*/
virtual void setName(const char* name) = 0;
/**
\brief Retrieves the name string set with setName().
\return Name string associated with object.
@see setName()
*/
virtual const char* getName() const = 0;
/**
\brief Retrieves the axis aligned bounding box enclosing the actor.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value.
\return The actor's bounding box.
@see PxBounds3
*/
virtual PxBounds3 getWorldBounds(float inflation=1.01f) const = 0;
/**
\brief Raises or clears a particular actor flag.
See the list of flags #PxActorFlag
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] flag The PxActor flag to raise(set) or clear. See #PxActorFlag.
\param[in] value The boolean value to assign to the flag.
@see PxActorFlag getActorFlags()
*/
virtual void setActorFlag(PxActorFlag::Enum flag, bool value) = 0;
/**
\brief Sets the actor flags.
See the list of flags #PxActorFlag
@see PxActorFlag setActorFlag()
*/
virtual void setActorFlags( PxActorFlags inFlags ) = 0;
/**
\brief Reads the PxActor flags.
See the list of flags #PxActorFlag
\return The values of the PxActor flags.
@see PxActorFlag setActorFlag()
*/
virtual PxActorFlags getActorFlags() const = 0;
/**
\brief Assigns dynamic actors a dominance group identifier.
PxDominanceGroup is a 5 bit group identifier (legal range from 0 to 31).
The PxScene::setDominanceGroupPair() lets you set certain behaviors for pairs of dominance groups.
By default every dynamic actor is created in group 0.
<b>Default:</b> 0
<b>Sleeping:</b> Changing the dominance group does <b>NOT</b> wake the actor up automatically.
\param[in] dominanceGroup The dominance group identifier. <b>Range:</b> [0..31]
@see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
virtual void setDominanceGroup(PxDominanceGroup dominanceGroup) = 0;
/**
\brief Retrieves the value set with setDominanceGroup().
\return The dominance group of this actor.
@see setDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
virtual PxDominanceGroup getDominanceGroup() const = 0;
/**
\brief Sets the owner client of an actor.
This cannot be done once the actor has been placed into a scene.
<b>Default:</b> PX_DEFAULT_CLIENT
@see PxClientID PxScene::createClient()
*/
virtual void setOwnerClient( PxClientID inClient ) = 0;
/**
\brief Returns the owner client that was specified at creation time.
This value cannot be changed once the object is placed into the scene.
@see PxClientID PxScene::createClient()
*/
virtual PxClientID getOwnerClient() const = 0;
/**
\brief Retrieves the aggregate the actor might be a part of.
\return The aggregate the actor is a part of, or NULL if the actor does not belong to an aggregate.
@see PxAggregate
*/
virtual PxAggregate* getAggregate() const = 0;
//public variables:
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxActor(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxActor(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxActor() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxActor", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,734 | C | 25.169355 | 142 | 0.725293 |
NVIDIA-Omniverse/PhysX/physx/include/PxSoftBody.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SOFT_BODY_H
#define PX_SOFT_BODY_H
/** \addtogroup physics
@{ */
#include "PxFEMParameter.h"
#include "PxActor.h"
#include "PxConeLimitedConstraint.h"
#include "PxSoftBodyFlag.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
class PxCudaContextManager;
class PxTetrahedronMesh;
class PxSoftBodyAuxData;
class PxFEMCloth;
class PxParticleBuffer;
/**
\brief The maximum tetrahedron index supported in the model.
*/
#define PX_MAX_TETID 0x000fffff
/**
\brief Flags to enable or disable special modes of a SoftBody
*/
struct PxSoftBodyFlag
{
enum Enum
{
eDISABLE_SELF_COLLISION = 1 << 0, //!< Determines if self collision will be detected and resolved
eCOMPUTE_STRESS_TENSOR = 1 << 1, //!< Enables computation of a Cauchy stress tensor for every tetrahedron in the simulation mesh. The tensors can be accessed through the softbody direct API
eENABLE_CCD = 1 << 2, //!< Enables support for continuous collision detection
eDISPLAY_SIM_MESH = 1 << 3, //!< Enable debug rendering to display the simulation mesh
eKINEMATIC = 1 << 4, //!< Enables support for kinematic motion of the collision and simulation mesh.
ePARTIALLY_KINEMATIC = 1 << 5 //!< Enables partially kinematic motion of the collision and simulation mesh.
};
};
typedef PxFlags<PxSoftBodyFlag::Enum, PxU32> PxSoftBodyFlags;
/**
\brief Represents a FEM softbody including everything to calculate its definition like geometry and material properties
*/
class PxSoftBody : public PxActor
{
public:
virtual ~PxSoftBody() {}
/**
\brief Set a single softbody flag
\param[in] flag The flag to set or clear
\param[in] val The new state of the flag
*/
virtual void setSoftBodyFlag(PxSoftBodyFlag::Enum flag, bool val) = 0;
/**
\brief Set the softbody flags
\param[in] flags The new softbody flags
*/
virtual void setSoftBodyFlags(PxSoftBodyFlags flags) = 0;
/**
\brief Get the softbody flags
\return The softbody flags
*/
virtual PxSoftBodyFlags getSoftBodyFlag() const = 0;
/**
\brief Set parameter for FEM internal solve
\param[in] parameters The FEM parameters
*/
virtual void setParameter(PxFEMParameters parameters) = 0;
/**
\brief Get parameter for FEM internal solve
\return The FEM parameters
*/
virtual PxFEMParameters getParameter() const = 0;
/**
\brief Get a pointer to a device buffer containing positions and inverse masses of the
collision mesh.
This function returns a pointer to device memory for the positions and inverse masses of
the soft body. This buffer is used to both initialize/update the collision mesh vertices
of the soft body and read the simulation results.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::ePOSITION_INVMASS
when updating data in this buffer.
The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary.
The first 3 floats specify the vertex position and the last float contains the inverse mass of the
vertex. The size of the buffer is the number of vertices of the collision mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a shape is attached to the
softbody. Calling PxSoftBody::detachShape() will deallocate the memory.
It is not allowed to write to this buffer from the start of the PxScene::simulate() call
until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks
have finished, reading the data during a completion task is explicitly allowed. The
simulation will read and write directly from/into this buffer.
It is the users' responsibility to initialize this buffer with the initial positions of
the vertices of the collision mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing positions and inverse masses of
the collision mesh.
*/
virtual PxVec4* getPositionInvMassBufferD() = 0;
/**
\brief Get a pointer to a device buffer containing rest positions of the collision mesh vertices.
This function returns a pointer to device memory for the rest positions of the softbody collision
mesh. This buffer is used to initialize the rest positions of the collision mesh vertices.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::eREST_POSITION when
updating data in this buffer.
The simulation expects 4 floats per vertex, aligned to a 16B boundary. The first 3 specify the
rest position. The last float is unused. The size of the buffer is the number of vertices in
the collision mesh * sizeof(PxVec4). @see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a shape is attached to the softbody.
Calling PxSoftBody::detachShape() will deallocate the memory.
It is not allowed to write data into this buffer from the start of PxScene::simulate() until
PxScene::fetchResults() returns.
It is the users' responsibility to initialize this buffer with the initial rest positions of the
vertices of the collision mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing the rest positions of the collision mesh.
*/
virtual PxVec4* getRestPositionBufferD() = 0;
/**
\brief Get a pointer to a device buffer containing the vertex positions of the simulation mesh.
This function returns a pointer to device memory for the positions and inverse masses of the softbody
simulation mesh. This buffer is used to both initialize/update the simulation mesh vertices
of the softbody and read the simulation results.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::eSIM_POSITION_INVMASS when
updating data in this buffer.
The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The
first 3 floats specify the positions and the last float specifies the inverse mass of the vertex.
The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a simulation mesh is attached to the
softbody. Calling PxSoftBody::detachSimulationMesh() will deallocate the memory.
It is not allowed to write to this buffer from the start of the PxScene::simulate() call
until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks
have finished, reading the data during a completion task is explicitly allowed. The
simulation will read and write directly from/into this buffer.
It is the users' responsibility to initialize this buffer with the initial positions of
the vertices of the simulation mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing the vertex positions of the simulation mesh.
*/
virtual PxVec4* getSimPositionInvMassBufferD() = 0;
/**
\brief Get a pointer to a device buffer containing the vertex velocities of the simulation mesh.
This function returns a pointer to device memory for the velocities of the softbody simulation mesh
vertices. This buffer is used to both initialize/update the simulation mesh vertex velocities
of the soft body and read the simulation results.
\note It is mandatory to call PxSoftBody::markDirty() with PxSoftBodyDataFlag::eSIM_VELOCITY when
updating data in this buffer.
The simulation expects 4 consecutive floats for each vertex, aligned to a 16B boundary. The
first 3 specify the velocities for each vertex. The final float is unused. The size of the
buffer is the number of vertices of the simulation mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
The device memory pointed to by this pointer is allocated when a simulation mesh is attached to the
softbody. Calling PxSoftBody::detachSimulationMesh() will deallocate the memory.
It is not allowed to write to this buffer from the start of the PxScene::simulate() call
until PxScene::fetchResults() returns. Reading the data is allowed once all the PhysX tasks
have finished, reading the data during a completion task is explicitly allowed. The
simulation will read and write directly from/into this buffer.
It is the users' responsibility to initialize this buffer with the initial velocities of
the vertices of the simulation mesh. See PxSoftBodyExt::allocateAndInitializeHostMirror(),
PxSoftBodyExt::copyToDevice().
\return PxVec4* A pointer to a device buffer containing the vertex velocities of the simulation mesh.
*/
virtual PxVec4* getSimVelocityBufferD() = 0;
/**
\brief Marks per-vertex simulation state and configuration buffers dirty to signal to the simulation
that changes have been made.
Calling this function is mandatory to notify the simulation of changes made in the positionInvMass,
simPositionInvMass, simVelocity and rest position buffers.
This function can be called multiple times, and dirty flags are accumulated internally until
PxScene::simulate() is called.
@see getPositionInvMassBufferD, getSimVelocityBufferD, getRestPositionBufferD, getSimPositionInvMassBufferD
\param flags The buffers that have been updated.
*/
virtual void markDirty(PxSoftBodyDataFlags flags) = 0;
/**
\brief Set the device buffer containing the kinematic targets for this softbody.
This function sets the kinematic targets for a softbody to a user-provided device buffer. This buffer is
read by the simulation to obtain the target position for each vertex of the simulation mesh.
The simulation expects 4 consecutive float for each vertex, aligned to a 16B boundary. The first 3
floats specify the target positions. The last float determines (together with the flag argument)
if the target is active or not.
For a softbody with the flag PxSoftBodyFlag::eKINEMATIC raised, all target positions are considered
valid. In case a softbody has the PxSoftBodyFlag::ePARTIALLY_KINEMATIC raised, only target
positions whose corresponding last float has been set to 0.f are considered valid target positions.
@see PxConfigureSoftBodyKinematicTarget
The size of the buffer is the number of vertices of the simulation mesh * sizeof(PxVec4).
@see PxTetrahedronMesh::getNbVertices().
It is the users responsibility to manage the memory pointed to by the input to this function,
as well as guaranteeing the integrity of the input data. In particular, this means that it is
not allowed to write this data from from the start of PxScene::simulate() until PxScene::fetchResults()
returns. The memory is not allowed to be deallocated until PxScene::fetchResults() returns.
Calling this function with a null pointer for the positions will clear the input and resume normal
simulation. This will also clear both the PxSoftBodyFlag::eKINEMATIC and PxSoftBodyFlag::ePARTIALLY_KINEMATIC
flags of the softbody.
This call is persistent across calls to PxScene::simulate(). Once this function is called, the
simulation will look up the target positions from the same buffer for every call to PxScene::simulate().
The user is allowed to update the target positions without calling this function again, provided that
the synchronization requirements are adhered to (no changes between start of PxScene::simulate() until
PxScene::fetchResults() returns).
\param positions A pointer to a device buffer containing the kinematic targets for this softbody.
\param flags Flags specifying the type of kinematic softbody: this function ignores all flags except PxSoftBodyFlag::eKINEMATIC and PxSoftBodyFlag::ePARTIALLY_KINEMATIC.
*/
virtual void setKinematicTargetBufferD(const PxVec4* positions, PxSoftBodyFlags flags) = 0;
/**
\brief Return the cuda context manager
\return The cuda context manager
*/
virtual PxCudaContextManager* getCudaContextManager() const = 0;
/**
\brief Sets the wake counter for the soft body.
The wake counter value determines the minimum amount of time until the soft body can be put to sleep. Please note
that a soft body will not be put to sleep if any vertex velocity is above the specified threshold
or if other awake objects are touching it.
\note Passing in a positive value will wake the soft body up automatically.
<b>Default:</b> 0.4 (which corresponds to 20 frames for a time step of 0.02)
\param[in] wakeCounterValue Wake counter value. <b>Range:</b> [0, PX_MAX_F32)
@see isSleeping() getWakeCounter()
*/
virtual void setWakeCounter(PxReal wakeCounterValue) = 0;
/**
\brief Returns the wake counter of the soft body.
\return The wake counter of the soft body.
@see isSleeping() setWakeCounter()
*/
virtual PxReal getWakeCounter() const = 0;
/**
\brief Returns true if this soft body is sleeping.
When an actor does not move for a period of time, it is no longer simulated in order to save time. This state
is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object,
or a sleep-affecting property is changed by the user, the entire sleep mechanism should be transparent to the user.
A soft body can only go to sleep if all vertices are ready for sleeping. A soft body is guaranteed to be awake
if at least one of the following holds:
\li The wake counter is positive (@see setWakeCounter()).
\li The velocity of any vertex is above the sleep threshold.
If a soft body is sleeping, the following state is guaranteed:
\li The wake counter is zero.
\li The linear velocity of all vertices is zero.
When a soft body gets inserted into a scene, it will be considered asleep if all the points above hold, else it will
be treated as awake.
\note It is invalid to use this method if the soft body has not been added to a scene already.
\return True if the soft body is sleeping.
@see isSleeping()
*/
virtual bool isSleeping() const = 0;
/**
\brief Sets the solver iteration counts for the body.
The solver iteration count determines how accurately deformation and contacts are resolved.
If you are having trouble with softbodies that are not as stiff as they should be, then
setting a higher position iteration count may improve the behavior.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations.
<b>Default:</b> 4 position iterations, 1 velocity iteration
\param[in] minPositionIters Minimal number of position iterations the solver should perform for this body. <b>Range:</b> [1,255]
\param[in] minVelocityIters Minimal number of velocity iterations the solver should perform for this body. <b>Range:</b> [1,255]
@see getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Retrieves the solver iteration counts.
@see setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Retrieves the shape pointer belonging to the actor.
\return Pointer to the collision mesh's shape
@see PxShape getNbShapes() PxShape::release()
*/
virtual PxShape* getShape() = 0;
/**
\brief Retrieve the collision mesh pointer.
Allows to access the geometry of the tetrahedral mesh used to perform collision detection
\return Pointer to the collision mesh
*/
virtual PxTetrahedronMesh* getCollisionMesh() = 0;
//! \brief Const version of getCollisionMesh()
virtual const PxTetrahedronMesh* getCollisionMesh() const = 0;
/**
\brief Retrieves the simulation mesh pointer.
Allows to access the geometry of the tetrahedral mesh used to compute the object's deformation
\return Pointer to the simulation mesh
*/
virtual PxTetrahedronMesh* getSimulationMesh() = 0;
//! \brief Const version of getSimulationMesh()
virtual const PxTetrahedronMesh* getSimulationMesh() const = 0;
/**
\brief Retrieves the simulation state pointer.
Allows to access the additional data of the simulation mesh (inverse mass, rest state etc.).
The geometry part of the data is stored in the simulation mesh.
\return Pointer to the simulation state
*/
virtual PxSoftBodyAuxData* getSoftBodyAuxData() = 0;
//! \brief const version of getSoftBodyAuxData()
virtual const PxSoftBodyAuxData* getSoftBodyAuxData() const = 0;
/**
\brief Attaches a shape
Attaches the shape to use for collision detection
\param[in] shape The shape to use for collisions
\return Returns true if the operation was successful
*/
virtual bool attachShape(PxShape& shape) = 0;
/**
\brief Attaches a simulation mesh
Attaches the simulation mesh (geometry) and a state containing inverse mass, rest pose
etc. required to compute the softbody deformation.
\param[in] simulationMesh The tetrahedral mesh used to compute the softbody's deformation
\param[in] softBodyAuxData A state that contain a mapping from simulation to collision mesh, volume information etc.
\return Returns true if the operation was successful
*/
virtual bool attachSimulationMesh(PxTetrahedronMesh& simulationMesh, PxSoftBodyAuxData& softBodyAuxData) = 0;
/**
\brief Detaches the shape
Detaches the shape used for collision detection.
@see void detachSimulationMesh()
*/
virtual void detachShape() = 0;
/**
\brief Detaches the simulation mesh
Detaches the simulation mesh and simulation state used to compute the softbody deformation.
@see void detachShape()
*/
virtual void detachSimulationMesh() = 0;
/**
\brief Releases the softbody
Releases the softbody and frees its resources.
*/
virtual void release() = 0;
/**
\brief Creates a collision filter between a particle and a tetrahedron in the soft body's collision mesh.
\param[in] particlesystem The particle system used for the collision filter
\param[in] buffer The PxParticleBuffer to which the particle belongs to.
\param[in] particleId The particle whose collisions with the tetrahedron in the soft body are filtered.
\param[in] tetId The tetradedron in the soft body that is filtered. If tetId is PX_MAX_TETID, this particle will filter against all tetrahedra in this soft body
*/
virtual void addParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) = 0;
/**
\brief Removes a collision filter between a particle and a tetrahedron in the soft body's collision mesh.
\param[in] particlesystem The particle system used for the collision filter
\param[in] buffer The PxParticleBuffer to which the particle belongs to.
\param[in] particleId The particle whose collisions with the tetrahedron in the soft body are filtered.
\param[in] tetId The tetrahedron in the soft body is filtered.
*/
virtual void removeParticleFilter(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId) = 0;
/**
\brief Creates an attachment between a particle and a soft body.
Be aware that destroying the particle system before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the particle system does not.
\param[in] particlesystem The particle system used for the attachment
\param[in] buffer The PxParticleBuffer to which the particle belongs to.
\param[in] particleId The particle that is attached to a tetrahedron in the soft body's collision mesh.
\param[in] tetId The tetrahedron in the soft body's collision mesh to attach the particle to.
\param[in] barycentric The barycentric coordinates of the particle attachment position with respect to the tetrahedron specified with tetId.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addParticleAttachment(PxPBDParticleSystem* particlesystem, const PxParticleBuffer* buffer, PxU32 particleId, PxU32 tetId, const PxVec4& barycentric) = 0;
/**
\brief Removes an attachment between a particle and a soft body.
Be aware that destroying the particle system before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the particle system does not.
\param[in] particlesystem The particle system used for the attachment
\param[in] handle Index that identifies the attachment. This handle gets returned by the addParticleAttachment when the attachment is created
*/
virtual void removeParticleAttachment(PxPBDParticleSystem* particlesystem, PxU32 handle) = 0;
/**
\brief Creates a collision filter between a vertex in a soft body and a rigid body.
\param[in] actor The rigid body actor used for the collision filter
\param[in] vertId The index of a vertex in the softbody's collision mesh whose collisions with the rigid body are filtered.
*/
virtual void addRigidFilter(PxRigidActor* actor, PxU32 vertId) = 0;
/**
\brief Removes a collision filter between a vertex in a soft body and a rigid body.
\param[in] actor The rigid body actor used for the collision filter
\param[in] vertId The index of a vertex in the softbody's collision mesh whose collisions with the rigid body are filtered.
*/
virtual void removeRigidFilter(PxRigidActor* actor, PxU32 vertId) = 0;
/**
\brief Creates a rigid attachment between a soft body and a rigid body.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the rigid body does not.
This method attaches a vertex on the soft body collision mesh to the rigid body.
\param[in] actor The rigid body actor used for the attachment
\param[in] vertId The index of a vertex in the softbody's collision mesh that gets attached to the rigid body.
\param[in] actorSpacePose The location of the attachment point expressed in the rigid body's coordinate system.
\param[in] constraint The user defined cone distance limit constraint to limit the movement between a vertex in the soft body and rigid body.
\return Returns a handle that identifies the attachment created. This handle can be used to relese the attachment later
*/
virtual PxU32 addRigidAttachment(PxRigidActor* actor, PxU32 vertId, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint = NULL) = 0;
/**
\brief Releases a rigid attachment between a soft body and a rigid body.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the rigid body does not.
This method removes a previously-created attachment between a vertex of the soft body collision mesh and the rigid body.
\param[in] actor The rigid body actor used for the attachment
\param[in] handle Index that identifies the attachment. This handle gets returned by the addRigidAttachment when the attachment is created
*/
virtual void removeRigidAttachment(PxRigidActor* actor, PxU32 handle) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a rigid body.
\param[in] actor The rigid body actor used for collision filter
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh whose collisions with the rigid body is filtered.
*/
virtual void addTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a rigid body.
\param[in] actor The rigid body actor used for collision filter
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh whose collisions with the rigid body is filtered.
*/
virtual void removeTetRigidFilter(PxRigidActor* actor, PxU32 tetIdx) = 0;
/**
\brief Creates a rigid attachment between a soft body and a rigid body.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the rigid body does not.
This method attaches a point inside a tetrahedron of the collision to the rigid body.
\param[in] actor The rigid body actor used for the attachment
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh that contains the point to be attached to the rigid body
\param[in] barycentric The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx
\param[in] actorSpacePose The location of the attachment point expressed in the rigid body's coordinate system.
\param[in] constraint The user defined cone distance limit constraint to limit the movement between a tet and rigid body.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addTetRigidAttachment(PxRigidActor* actor, PxU32 tetIdx, const PxVec4& barycentric, const PxVec3& actorSpacePose, PxConeLimitedConstraint* constraint = NULL) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a tetrahedron in another soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIdx The index of the tetrahedron in the other softbody's collision mesh to be filtered.
\param[in] tetIdx1 The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void addSoftBodyFilter(PxSoftBody* otherSoftBody, PxU32 otherTetIdx, PxU32 tetIdx1) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a tetrahedron in other soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIdx The index of the other tetrahedron in the other softbody's collision mesh whose collision with the tetrahedron with the soft body is filtered.
\param[in] tetIdx1 The index of the tetrahedron in the softbody's collision mesh whose collision with the other tetrahedron with the other soft body is filtered.
*/
virtual void removeSoftBodyFilter(PxSoftBody* otherSoftBody, PxU32 otherTetIdx, PxU32 tetIdx1) = 0;
/**
\brief Creates collision filters between a tetrahedron in a soft body with another soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIndices The indices of the tetrahedron in the other softbody's collision mesh to be filtered.
\param[in] tetIndices The indices of the tetrahedron of the softbody's collision mesh to be filtered.
\param[in] tetIndicesSize The size of tetIndices.
*/
virtual void addSoftBodyFilters(PxSoftBody* otherSoftBody, PxU32* otherTetIndices, PxU32* tetIndices, PxU32 tetIndicesSize) = 0;
/**
\brief Removes collision filters between a tetrahedron in a soft body with another soft body.
\param[in] otherSoftBody The other soft body actor used for collision filter
\param[in] otherTetIndices The indices of the tetrahedron in the other softbody's collision mesh to be filtered.
\param[in] tetIndices The indices of the tetrahedron of the softbody's collision mesh to be filtered.
\param[in] tetIndicesSize The size of tetIndices.
*/
virtual void removeSoftBodyFilters(PxSoftBody* otherSoftBody, PxU32* otherTetIndices, PxU32* tetIndices, PxU32 tetIndicesSize) = 0;
/**
\brief Creates an attachment between two soft bodies.
This method attaches a point inside a tetrahedron of the collision mesh to a point in another soft body's tetrahedron collision mesh.
\param[in] softbody0 The soft body actor used for the attachment
\param[in] tetIdx0 The index of a tetrahedron in the other soft body that contains the point to be attached to the soft body
\param[in] tetBarycentric0 The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx0
\param[in] tetIdx1 The index of a tetrahedron in the softbody's collision mesh that contains the point to be attached to the softbody0
\param[in] tetBarycentric1 The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx1
\param[in] constraint The user defined cone distance limit constraint to limit the movement between tets.
\param[in] constraintOffset Offsets the cone and distance limit constraint along its axis, in order to specify the location of the cone tip.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addSoftBodyAttachment(PxSoftBody* softbody0, PxU32 tetIdx0, const PxVec4& tetBarycentric0, PxU32 tetIdx1, const PxVec4& tetBarycentric1,
PxConeLimitedConstraint* constraint = NULL, PxReal constraintOffset = 0.0f) = 0;
/**
\brief Releases an attachment between a soft body and the other soft body.
Be aware that destroying the soft body before destroying the attachment is illegal and may cause a crash.
This method removes a previously-created attachment between a point inside a tetrahedron of the collision mesh to a point in another soft body's tetrahedron collision mesh.
\param[in] softbody0 The softbody actor used for the attachment.
\param[in] handle Index that identifies the attachment. This handle gets returned by the addSoftBodyAttachment when the attachment is created.
*/
virtual void removeSoftBodyAttachment(PxSoftBody* softbody0, PxU32 handle) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a triangle in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] triIdx The index of the triangle in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void addClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a triangle in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] triIdx The index of the triangle in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void removeClothFilter(PxFEMCloth* cloth, PxU32 triIdx, PxU32 tetIdx) = 0;
/**
\brief Creates collision filter between a tetrahedron in a soft body and a vertex in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] vertIdx The index of the vertex in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void addVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx) = 0;
/**
\brief Removes collision filter between a tetrahedron in a soft body and a vertex in a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for collision filter
\param[in] vertIdx The index of the vertex in the cloth mesh to be filtered.
\param[in] tetIdx The index of the tetrahedron in the softbody's collision mesh to be filtered.
*/
virtual void removeVertClothFilter(PxFEMCloth* cloth, PxU32 vertIdx, PxU32 tetIdx) = 0;
/**
\brief Creates an attachment between a soft body and a cloth.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the cloth does not.
This method attaches a point inside a tetrahedron of the collision mesh to a cloth.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for the attachment
\param[in] triIdx The index of a triangle in the cloth mesh that contains the point to be attached to the soft body
\param[in] triBarycentric The barycentric coordinates of the attachment point inside the triangle specified by triangleIdx
\param[in] tetIdx The index of a tetrahedron in the softbody's collision mesh that contains the point to be attached to the cloth
\param[in] tetBarycentric The barycentric coordinates of the attachment point inside the tetrahedron specified by tetIdx
\param[in] constraint The user defined cone distance limit constraint to limit the movement between a triangle in the fem cloth and a tet in the soft body.
\param[in] constraintOffset Offsets the cone and distance limit constraint along its axis, in order to specify the location of the cone tip.
\return Returns a handle that identifies the attachment created. This handle can be used to release the attachment later
*/
virtual PxU32 addClothAttachment(PxFEMCloth* cloth, PxU32 triIdx, const PxVec4& triBarycentric, PxU32 tetIdx, const PxVec4& tetBarycentric,
PxConeLimitedConstraint* constraint = NULL, PxReal constraintOffset = 0.0f) = 0;
/**
\brief Releases an attachment between a cloth and a soft body.
Be aware that destroying the cloth before destroying the attachment is illegal and may cause a crash.
The soft body keeps track of these attachments but the cloth does not.
This method removes a previously-created attachment between a point inside a collision mesh tetrahedron and a point inside a cloth mesh.
\warning Feature under development, only for internal usage.
\param[in] cloth The cloth actor used for the attachment
\param[in] handle Index that identifies the attachment. This handle gets returned by the addClothAttachment when the attachment is created
*/
virtual void removeClothAttachment(PxFEMCloth* cloth, PxU32 handle) = 0;
/**
\brief Retrieves the axis aligned bounding box enclosing the soft body.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value.
\return The soft body's bounding box.
@see PxBounds3
*/
virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const = 0;
/**
\brief Returns the GPU soft body index.
\return The GPU index, or 0xFFFFFFFF if the soft body is not in a scene.
*/
virtual PxU32 getGpuSoftBodyIndex() = 0;
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxSoftBody"; }
protected:
PX_INLINE PxSoftBody(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {}
PX_INLINE PxSoftBody(PxBaseFlags baseFlags) : PxActor(baseFlags) {}
virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxSoftBody", PxActor); }
};
/**
\brief Adjusts a softbody kinematic target such that it is properly set as active or inactive. Inactive targets will not affect vertex position, they are ignored by the solver.
\param[in] target The kinematic target
\param[in] isActive A boolean indicating if the returned target should be marked as active or not
\return The target with adjusted w component
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureSoftBodyKinematicTarget(const PxVec4& target, bool isActive)
{
PxVec4 result = target;
if (isActive)
result.w = 0.0f;
else
{
//Any non-zero value will mark the target as inactive
if (result.w == 0.0f)
result.w = 1.0f;
}
return result;
}
/**
\brief Sets up a softbody kinematic target such that it is properly set as active or inactive. Inactive targets will not affect vertex position, they are ignored by the solver.
\param[in] target The kinematic target
\param[in] isActive A boolean indicating if the returned target should be marked as active or not
\return The target with configured w component
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxVec4 PxConfigureSoftBodyKinematicTarget(const PxVec3& target, bool isActive)
{
return PxConfigureSoftBodyKinematicTarget(PxVec4(target, 0.0f), isActive);
}
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 38,612 | C | 46.319853 | 193 | 0.763105 |
NVIDIA-Omniverse/PhysX/physx/include/PxScene.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SCENE_H
#define PX_SCENE_H
/** \addtogroup physics
@{
*/
#include "PxSceneQuerySystem.h"
#include "PxSceneDesc.h"
#include "PxVisualizationParameter.h"
#include "PxSimulationStatistics.h"
#include "PxClient.h"
#include "task/PxTask.h"
#include "PxArticulationFlag.h"
#include "PxSoftBodyFlag.h"
#include "PxHairSystemFlag.h"
#include "PxActorData.h"
#include "PxParticleSystemFlag.h"
#include "PxParticleSolverType.h"
#include "cudamanager/PxCudaTypes.h"
#include "pvd/PxPvdSceneClient.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxCollection;
class PxConstraint;
class PxSimulationEventCallback;
class PxPhysics;
class PxAggregate;
class PxRenderBuffer;
class PxArticulationReducedCoordinate;
class PxParticleSystem;
struct PxContactPairHeader;
typedef PxU8 PxDominanceGroup;
class PxPvdSceneClient;
class PxSoftBody;
class PxFEMCloth;
class PxHairSystem;
/**
\brief Expresses the dominance relationship of a contact.
For the time being only three settings are permitted:
(1, 1), (0, 1), and (1, 0).
@see getDominanceGroup() PxDominanceGroup PxScene::setDominanceGroupPair()
*/
struct PxDominanceGroupPair
{
PxDominanceGroupPair(PxU8 a, PxU8 b)
: dominance0(a), dominance1(b) {}
PxU8 dominance0;
PxU8 dominance1;
};
/**
\brief Identifies each type of actor for retrieving actors from a scene.
\note #PxArticulationLink objects are not supported. Use the #PxArticulationReducedCoordinate object to retrieve all its links.
@see PxScene::getActors(), PxScene::getNbActors()
*/
struct PxActorTypeFlag
{
enum Enum
{
/**
\brief A static rigid body
@see PxRigidStatic
*/
eRIGID_STATIC = (1 << 0),
/**
\brief A dynamic rigid body
@see PxRigidDynamic
*/
eRIGID_DYNAMIC = (1 << 1)
};
};
/**
\brief Collection of set bits defined in PxActorTypeFlag.
@see PxActorTypeFlag
*/
typedef PxFlags<PxActorTypeFlag::Enum,PxU16> PxActorTypeFlags;
PX_FLAGS_OPERATORS(PxActorTypeFlag::Enum,PxU16)
class PxActor;
/**
\brief Broad-phase callback to receive broad-phase related events.
Each broadphase callback object is associated with a PxClientID. It is possible to register different
callbacks for different clients. The callback functions are called this way:
- for shapes/actors, the callback assigned to the actors' clients are used
- for aggregates, the callbacks assigned to clients from aggregated actors are used
\note SDK state should not be modified from within the callbacks. In particular objects should not
be created or destroyed. If state modification is needed then the changes should be stored to a buffer
and performed after the simulation step.
<b>Threading:</b> It is not necessary to make this class thread safe as it will only be called in the context of the
user thread.
@see PxSceneDesc PxScene.setBroadPhaseCallback() PxScene.getBroadPhaseCallback()
*/
class PxBroadPhaseCallback
{
public:
virtual ~PxBroadPhaseCallback() {}
/**
\brief Out-of-bounds notification.
This function is called when an object leaves the broad-phase.
\param[in] shape Shape that left the broad-phase bounds
\param[in] actor Owner actor
*/
virtual void onObjectOutOfBounds(PxShape& shape, PxActor& actor) = 0;
/**
\brief Out-of-bounds notification.
This function is called when an aggregate leaves the broad-phase.
\param[in] aggregate Aggregate that left the broad-phase bounds
*/
virtual void onObjectOutOfBounds(PxAggregate& aggregate) = 0;
};
/**
\brief A scene is a collection of bodies and constraints which can interact.
The scene simulates the behavior of these objects over time. Several scenes may exist
at the same time, but each body or constraint is specific to a scene
-- they may not be shared.
@see PxSceneDesc PxPhysics.createScene() release()
*/
class PxScene : public PxSceneSQSystem
{
protected:
/************************************************************************************************/
/** @name Basics
*/
//@{
PxScene() : userData(NULL) {}
virtual ~PxScene() {}
public:
/**
\brief Deletes the scene.
Removes any actors and constraint shaders from this scene
(if the user hasn't already done so).
Be sure to not keep a reference to this object after calling release.
Avoid release calls while the scene is simulating (in between simulate() and fetchResults() calls).
@see PxPhysics.createScene()
*/
virtual void release() = 0;
/**
\brief Sets a scene flag. You can only set one flag at a time.
\note Not all flags are mutable and changing some will result in an error. Please check #PxSceneFlag to see which flags can be changed.
@see PxSceneFlag
*/
virtual void setFlag(PxSceneFlag::Enum flag, bool value) = 0;
/**
\brief Get the scene flags.
\return The scene flags. See #PxSceneFlag
@see PxSceneFlag
*/
virtual PxSceneFlags getFlags() const = 0;
/**
\brief Set new scene limits.
\note Increase the maximum capacity of various data structures in the scene. The new capacities will be
at least as large as required to deal with the objects currently in the scene. Further, these values
are for preallocation and do not represent hard limits.
\param[in] limits Scene limits.
@see PxSceneLimits
*/
virtual void setLimits(const PxSceneLimits& limits) = 0;
/**
\brief Get current scene limits.
\return Current scene limits.
@see PxSceneLimits
*/
virtual PxSceneLimits getLimits() const = 0;
/**
\brief Call this method to retrieve the Physics SDK.
\return The physics SDK this scene is associated with.
@see PxPhysics
*/
virtual PxPhysics& getPhysics() = 0;
/**
\brief Retrieves the scene's internal timestamp, increased each time a simulation step is completed.
\return scene timestamp
*/
virtual PxU32 getTimestamp() const = 0;
/**
\brief Sets a name string for the Scene that can be retrieved with getName().
This is for debugging and is not used by the SDK. The string is not copied by the SDK,
only the pointer is stored.
\param[in] name String to set the objects name to.
<b>Default:</b> NULL
@see getName()
*/
virtual void setName(const char* name) = 0;
/**
\brief Retrieves the name string set with setName().
\return Name string associated with the Scene.
@see setName()
*/
virtual const char* getName() const = 0;
//@}
/************************************************************************************************/
/** @name Add/Remove Articulations
*/
//@{
/**
\brief Adds an articulation to this scene.
\note If the articulation is already assigned to a scene (see #PxArticulationReducedCoordinate::getScene), the call is ignored and an error is issued.
\param[in] articulation The articulation to add to the scene.
\return True if success
@see PxArticulationReducedCoordinate
*/
virtual bool addArticulation(PxArticulationReducedCoordinate& articulation) = 0;
/**
\brief Removes an articulation from this scene.
\note If the articulation is not part of this scene (see #PxArticulationReducedCoordinate::getScene), the call is ignored and an error is issued.
\note If the articulation is in an aggregate it will be removed from the aggregate.
\param[in] articulation The articulation to remove from the scene.
\param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame.
Only applies to PxArticulationReducedCoordinate and PxRigidActor types.
@see PxArticulationReducedCoordinate, PxAggregate
*/
virtual void removeArticulation(PxArticulationReducedCoordinate& articulation, bool wakeOnLostTouch = true) = 0;
//@}
/************************************************************************************************/
/** @name Add/Remove Actors
*/
//@{
/**
\brief Adds an actor to this scene.
\note If the actor is already assigned to a scene (see #PxActor::getScene), the call is ignored and an error is issued.
\note If the actor has an invalid constraint, in checked builds the call is ignored and an error is issued.
\note You can not add individual articulation links (see #PxArticulationLink) to the scene. Use #addArticulation() instead.
\note If the actor is a PxRigidActor then each assigned PxConstraint object will get added to the scene automatically if
it connects to another actor that is part of the scene already.
\note When a BVH is provided the actor shapes are grouped together.
The scene query pruning structure inside PhysX SDK will store/update one
bound per actor. The scene queries against such an actor will query actor
bounds and then make a local space query against the provided BVH, which is in actor's local space.
\param[in] actor Actor to add to scene.
\param[in] bvh BVH for actor shapes.
\return True if success
@see PxActor, PxConstraint::isValid(), PxBVH
*/
virtual bool addActor(PxActor& actor, const PxBVH* bvh = NULL) = 0;
/**
\brief Adds actors to this scene. Only supports actors of type PxRigidStatic and PxRigidDynamic.
\note This method only supports actors of type PxRigidStatic and PxRigidDynamic. For other actors, use addActor() instead.
For articulation links, use addArticulation().
\note If one of the actors is already assigned to a scene (see #PxActor::getScene), the call is ignored and an error is issued.
\note If an actor in the array contains an invalid constraint, in checked builds the call is ignored and an error is issued.
\note If an actor in the array is a PxRigidActor then each assigned PxConstraint object will get added to the scene automatically if
it connects to another actor that is part of the scene already.
\note this method is optimized for high performance.
\param[in] actors Array of actors to add to scene.
\param[in] nbActors Number of actors in the array.
\return True if success
@see PxActor, PxConstraint::isValid()
*/
virtual bool addActors(PxActor*const* actors, PxU32 nbActors) = 0;
/**
\brief Adds a pruning structure together with its actors to this scene. Only supports actors of type PxRigidStatic and PxRigidDynamic.
\note This method only supports actors of type PxRigidStatic and PxRigidDynamic. For other actors, use addActor() instead.
For articulation links, use addArticulation().
\note If an actor in the pruning structure contains an invalid constraint, in checked builds the call is ignored and an error is issued.
\note For all actors in the pruning structure each assigned PxConstraint object will get added to the scene automatically if
it connects to another actor that is part of the scene already.
\note This method is optimized for high performance.
\note Merging a PxPruningStructure into an active scene query optimization AABB tree might unbalance the tree. A typical use case for
PxPruningStructure is a large world scenario where blocks of closely positioned actors get streamed in. The merge process finds the
best node in the active scene query optimization AABB tree and inserts the PxPruningStructure. Therefore using PxPruningStructure
for actors scattered throughout the world will result in an unbalanced tree.
\param[in] pruningStructure Pruning structure for a set of actors.
\return True if success
@see PxPhysics::createPruningStructure, PxPruningStructure
*/
virtual bool addActors(const PxPruningStructure& pruningStructure) = 0;
/**
\brief Removes an actor from this scene.
\note If the actor is not part of this scene (see #PxActor::getScene), the call is ignored and an error is issued.
\note You can not remove individual articulation links (see #PxArticulationLink) from the scene. Use #removeArticulation() instead.
\note If the actor is a PxRigidActor then all assigned PxConstraint objects will get removed from the scene automatically.
\note If the actor is in an aggregate it will be removed from the aggregate.
\param[in] actor Actor to remove from scene.
\param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCoordinate and PxRigidActor types.
@see PxActor, PxAggregate
*/
virtual void removeActor(PxActor& actor, bool wakeOnLostTouch = true) = 0;
/**
\brief Removes actors from this scene. Only supports actors of type PxRigidStatic and PxRigidDynamic.
\note This method only supports actors of type PxRigidStatic and PxRigidDynamic. For other actors, use removeActor() instead.
For articulation links, use removeArticulation().
\note If some actor is not part of this scene (see #PxActor::getScene), the actor remove is ignored and an error is issued.
\note You can not remove individual articulation links (see #PxArticulationLink) from the scene. Use #removeArticulation() instead.
\note If the actor is a PxRigidActor then all assigned PxConstraint objects will get removed from the scene automatically.
\param[in] actors Array of actors to add to scene.
\param[in] nbActors Number of actors in the array.
\param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCooridnate and PxRigidActor types.
@see PxActor
*/
virtual void removeActors(PxActor*const* actors, PxU32 nbActors, bool wakeOnLostTouch = true) = 0;
/**
\brief Adds an aggregate to this scene.
\note If the aggregate is already assigned to a scene (see #PxAggregate::getScene), the call is ignored and an error is issued.
\note If the aggregate contains an actor with an invalid constraint, in checked builds the call is ignored and an error is issued.
\note If the aggregate already contains actors, those actors are added to the scene as well.
\param[in] aggregate Aggregate to add to scene.
\return True if success
@see PxAggregate, PxConstraint::isValid()
*/
virtual bool addAggregate(PxAggregate& aggregate) = 0;
/**
\brief Removes an aggregate from this scene.
\note If the aggregate is not part of this scene (see #PxAggregate::getScene), the call is ignored and an error is issued.
\note If the aggregate contains actors, those actors are removed from the scene as well.
\param[in] aggregate Aggregate to remove from scene.
\param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCoordinate and PxRigidActor types.
@see PxAggregate
*/
virtual void removeAggregate(PxAggregate& aggregate, bool wakeOnLostTouch = true) = 0;
/**
\brief Adds objects in the collection to this scene.
This function adds the following types of objects to this scene: PxRigidActor (except PxArticulationLink), PxAggregate, PxArticulationReducedCoordinate.
This method is typically used after deserializing the collection in order to populate the scene with deserialized objects.
\note If the collection contains an actor with an invalid constraint, in checked builds the call is ignored and an error is issued.
\param[in] collection Objects to add to this scene. See #PxCollection
\return True if success
@see PxCollection, PxConstraint::isValid()
*/
virtual bool addCollection(const PxCollection& collection) = 0;
//@}
/************************************************************************************************/
/** @name Contained Object Retrieval
*/
//@{
/**
\brief Retrieve the number of actors of certain types in the scene. For supported types, see PxActorTypeFlags.
\param[in] types Combination of actor types.
\return the number of actors.
@see getActors()
*/
virtual PxU32 getNbActors(PxActorTypeFlags types) const = 0;
/**
\brief Retrieve an array of all the actors of certain types in the scene. For supported types, see PxActorTypeFlags.
\param[in] types Combination of actor types to retrieve.
\param[out] userBuffer The buffer to receive actor pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of actors written to the buffer.
@see getNbActors()
*/
virtual PxU32 getActors(PxActorTypeFlags types, PxActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Queries the PxScene for a list of the PxActors whose transforms have been
updated during the previous simulation step. Only includes actors of type PxRigidDynamic and PxArticulationLink.
\note PxSceneFlag::eENABLE_ACTIVE_ACTORS must be set.
\note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored and NULL will be returned.
\param[out] nbActorsOut The number of actors returned.
\return A pointer to the list of active PxActors generated during the last call to fetchResults().
@see PxActor
*/
virtual PxActor** getActiveActors(PxU32& nbActorsOut) = 0;
/**
\brief Retrieve the number of soft bodies in the scene.
\return the number of soft bodies.
@see getActors()
*/
virtual PxU32 getNbSoftBodies() const = 0;
/**
\brief Retrieve an array of all the soft bodies in the scene.
\param[out] userBuffer The buffer to receive actor pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of actors written to the buffer.
@see getNbActors()
*/
virtual PxU32 getSoftBodies(PxSoftBody** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Retrieve the number of particle systems of the requested type in the scene.
\param[in] type The particle system type. See PxParticleSolverType. Only one type can be requested per function call.
\return the number particle systems.
See getParticleSystems(), PxParticleSolverType
*/
virtual PxU32 getNbParticleSystems(PxParticleSolverType::Enum type) const = 0;
/**
\brief Retrieve an array of all the particle systems of the requested type in the scene.
\param[in] type The particle system type. See PxParticleSolverType. Only one type can be requested per function call.
\param[out] userBuffer The buffer to receive particle system pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first particle system pointer to be retrieved
\return Number of particle systems written to the buffer.
See getNbParticleSystems(), PxParticleSolverType
*/
virtual PxU32 getParticleSystems(PxParticleSolverType::Enum type, PxParticleSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Retrieve the number of FEM cloths in the scene.
\warning Feature under development, only for internal usage.
\return the number of FEM cloths.
See getFEMCloths()
*/
virtual PxU32 getNbFEMCloths() const = 0;
/**
\brief Retrieve an array of all the FEM cloths in the scene.
\warning Feature under development, only for internal usage.
\param[out] userBuffer The buffer to write the FEM cloth pointers to
\param[in] bufferSize Size of the provided user buffer
\param[in] startIndex Index of first FEM cloth pointer to be retrieved
\return Number of FEM cloths written to the buffer
*/
virtual PxU32 getFEMCloths(PxFEMCloth** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Retrieve the number of hair systems in the scene.
\warning Feature under development, only for internal usage.
\return the number of hair systems
@see getActors()
*/
virtual PxU32 getNbHairSystems() const = 0;
/**
\brief Retrieve an array of all the hair systems in the scene.
\warning Feature under development, only for internal usage.
\param[out] userBuffer The buffer to write the actor pointers to
\param[in] bufferSize Size of the provided user buffer
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of actors written to the buffer
*/
virtual PxU32 getHairSystems(PxHairSystem** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of articulations in the scene.
\return the number of articulations in this scene.
@see getArticulations()
*/
virtual PxU32 getNbArticulations() const = 0;
/**
\brief Retrieve all the articulations in the scene.
\param[out] userBuffer The buffer to receive articulations pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first articulations pointer to be retrieved
\return Number of articulations written to the buffer.
@see getNbArticulations()
*/
virtual PxU32 getArticulations(PxArticulationReducedCoordinate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Returns the number of constraint shaders in the scene.
\return the number of constraint shaders in this scene.
@see getConstraints()
*/
virtual PxU32 getNbConstraints() const = 0;
/**
\brief Retrieve all the constraint shaders in the scene.
\param[out] userBuffer The buffer to receive constraint shader pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first constraint pointer to be retrieved
\return Number of constraint shaders written to the buffer.
@see getNbConstraints()
*/
virtual PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Returns the number of aggregates in the scene.
\return the number of aggregates in this scene.
@see getAggregates()
*/
virtual PxU32 getNbAggregates() const = 0;
/**
\brief Retrieve all the aggregates in the scene.
\param[out] userBuffer The buffer to receive aggregates pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first aggregate pointer to be retrieved
\return Number of aggregates written to the buffer.
@see getNbAggregates()
*/
virtual PxU32 getAggregates(PxAggregate** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
//@}
/************************************************************************************************/
/** @name Dominance
*/
//@{
/**
\brief Specifies the dominance behavior of contacts between two actors with two certain dominance groups.
It is possible to assign each actor to a dominance groups using #PxActor::setDominanceGroup().
With dominance groups one can have all contacts created between actors act in one direction only. This is useful, for example, if you
want an object to push debris out of its way and be unaffected,while still responding physically to forces and collisions
with non-debris objects.
Whenever a contact between two actors (a0, a1) needs to be solved, the groups (g0, g1) of both
actors are retrieved. Then the PxDominanceGroupPair setting for this group pair is retrieved with getDominanceGroupPair(g0, g1).
In the contact, PxDominanceGroupPair::dominance0 becomes the dominance setting for a0, and
PxDominanceGroupPair::dominance1 becomes the dominance setting for a1. A dominanceN setting of 1.0f, the default,
will permit aN to be pushed or pulled by a(1-N) through the contact. A dominanceN setting of 0.0f, will however
prevent aN to be pushed by a(1-N) via the contact. Thus, a PxDominanceGroupPair of (1.0f, 0.0f) makes
the interaction one-way.
The matrix sampled by getDominanceGroupPair(g1, g2) is initialised by default 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
In other words, we permit actors in higher groups to be pushed around by actors in lower groups by default.
These settings should cover most applications, and in fact not overriding these settings may likely result in higher performance.
It is not possible to make the matrix asymetric, or to change the diagonal. In other words:
* it is not possible to change (g1, g2) if (g1==g2)
* if you set
(g1, g2) to X, then (g2, g1) will implicitly and automatically be set to ~X, where:
~(1.0f, 1.0f) is (1.0f, 1.0f)
~(0.0f, 1.0f) is (1.0f, 0.0f)
~(1.0f, 0.0f) is (0.0f, 1.0f)
These two restrictions are to make sure that contacts between two actors will always evaluate to the same dominance
setting, regardless of the order of the actors.
Dominance settings are currently specified as floats 0.0f or 1.0f because in the future we may permit arbitrary
fractional settings to express 'partly-one-way' interactions.
<b>Sleeping:</b> Does <b>NOT</b> wake actors up automatically.
@see getDominanceGroupPair() PxDominanceGroup PxDominanceGroupPair PxActor::setDominanceGroup() PxActor::getDominanceGroup()
*/
virtual void setDominanceGroupPair(
PxDominanceGroup group1, PxDominanceGroup group2, const PxDominanceGroupPair& dominance) = 0;
/**
\brief Samples the dominance matrix.
@see setDominanceGroupPair() PxDominanceGroup PxDominanceGroupPair PxActor::setDominanceGroup() PxActor::getDominanceGroup()
*/
virtual PxDominanceGroupPair getDominanceGroupPair(PxDominanceGroup group1, PxDominanceGroup group2) const = 0;
//@}
/************************************************************************************************/
/** @name Dispatcher
*/
//@{
/**
\brief Return the cpu dispatcher that was set in PxSceneDesc::cpuDispatcher when creating the scene with PxPhysics::createScene
@see PxSceneDesc::cpuDispatcher, PxPhysics::createScene
*/
virtual PxCpuDispatcher* getCpuDispatcher() const = 0;
/**
\brief Return the CUDA context manager that was set in PxSceneDesc::cudaContextManager when creating the scene with PxPhysics::createScene
<b>Platform specific:</b> Applies to PC GPU only.
@see PxSceneDesc::cudaContextManager, PxPhysics::createScene
*/
virtual PxCudaContextManager* getCudaContextManager() const = 0;
//@}
/************************************************************************************************/
/** @name Multiclient
*/
//@{
/**
\brief Reserves a new client ID.
PX_DEFAULT_CLIENT is always available as the default clientID.
Additional clients are returned by this function. Clients cannot be released once created.
An error is reported when more than a supported number of clients (currently 128) are created.
@see PxClientID
*/
virtual PxClientID createClient() = 0;
//@}
/************************************************************************************************/
/** @name Callbacks
*/
//@{
/**
\brief Sets a user notify object which receives special simulation events when they occur.
\note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored.
\param[in] callback User notification callback. See #PxSimulationEventCallback.
@see PxSimulationEventCallback getSimulationEventCallback
*/
virtual void setSimulationEventCallback(PxSimulationEventCallback* callback) = 0;
/**
\brief Retrieves the simulationEventCallback pointer set with setSimulationEventCallback().
\return The current user notify pointer. See #PxSimulationEventCallback.
@see PxSimulationEventCallback setSimulationEventCallback()
*/
virtual PxSimulationEventCallback* getSimulationEventCallback() const = 0;
/**
\brief Sets a user callback object, which receives callbacks on all contacts generated for specified actors.
\note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored.
\param[in] callback Asynchronous user contact modification callback. See #PxContactModifyCallback.
*/
virtual void setContactModifyCallback(PxContactModifyCallback* callback) = 0;
/**
\brief Sets a user callback object, which receives callbacks on all CCD contacts generated for specified actors.
\note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored.
\param[in] callback Asynchronous user contact modification callback. See #PxCCDContactModifyCallback.
*/
virtual void setCCDContactModifyCallback(PxCCDContactModifyCallback* callback) = 0;
/**
\brief Retrieves the PxContactModifyCallback pointer set with setContactModifyCallback().
\return The current user contact modify callback pointer. See #PxContactModifyCallback.
@see PxContactModifyCallback setContactModifyCallback()
*/
virtual PxContactModifyCallback* getContactModifyCallback() const = 0;
/**
\brief Retrieves the PxCCDContactModifyCallback pointer set with setContactModifyCallback().
\return The current user contact modify callback pointer. See #PxContactModifyCallback.
@see PxContactModifyCallback setContactModifyCallback()
*/
virtual PxCCDContactModifyCallback* getCCDContactModifyCallback() const = 0;
/**
\brief Sets a broad-phase user callback object.
\note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored.
\param[in] callback Asynchronous broad-phase callback. See #PxBroadPhaseCallback.
*/
virtual void setBroadPhaseCallback(PxBroadPhaseCallback* callback) = 0;
/**
\brief Retrieves the PxBroadPhaseCallback pointer set with setBroadPhaseCallback().
\return The current broad-phase callback pointer. See #PxBroadPhaseCallback.
@see PxBroadPhaseCallback setBroadPhaseCallback()
*/
virtual PxBroadPhaseCallback* getBroadPhaseCallback() const = 0;
//@}
/************************************************************************************************/
/** @name Collision Filtering
*/
//@{
/**
\brief Sets the shared global filter data which will get passed into the filter shader.
\note It is the user's responsibility to ensure that changing the shared global filter data does not change the filter output value for existing pairs.
If the filter output for existing pairs does change nonetheless then such a change will not take effect until the pair gets refiltered.
resetFiltering() can be used to explicitly refilter the pairs of specific objects.
\note The provided data will get copied to internal buffers and this copy will be used for filtering calls.
\note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored.
\param[in] data The shared global filter shader data.
\param[in] dataSize Size of the shared global filter shader data (in bytes).
@see getFilterShaderData() PxSceneDesc.filterShaderData PxSimulationFilterShader
*/
virtual void setFilterShaderData(const void* data, PxU32 dataSize) = 0;
/**
\brief Gets the shared global filter data in use for this scene.
\note The reference points to a copy of the original filter data specified in #PxSceneDesc.filterShaderData or provided by #setFilterShaderData().
\return Shared filter data for filter shader.
@see getFilterShaderDataSize() setFilterShaderData() PxSceneDesc.filterShaderData PxSimulationFilterShader
*/
virtual const void* getFilterShaderData() const = 0;
/**
\brief Gets the size of the shared global filter data (#PxSceneDesc.filterShaderData)
\return Size of shared filter data [bytes].
@see getFilterShaderData() PxSceneDesc.filterShaderDataSize PxSimulationFilterShader
*/
virtual PxU32 getFilterShaderDataSize() const = 0;
/**
\brief Gets the custom collision filter shader in use for this scene.
\return Filter shader class that defines the collision pair filtering.
@see PxSceneDesc.filterShader PxSimulationFilterShader
*/
virtual PxSimulationFilterShader getFilterShader() const = 0;
/**
\brief Gets the custom collision filter callback in use for this scene.
\return Filter callback class that defines the collision pair filtering.
@see PxSceneDesc.filterCallback PxSimulationFilterCallback
*/
virtual PxSimulationFilterCallback* getFilterCallback() const = 0;
/**
\brief Marks the object to reset interactions and re-run collision filters in the next simulation step.
This call forces the object to remove all existing collision interactions, to search anew for existing contact
pairs and to run the collision filters again for found collision pairs.
\note The operation is supported for PxRigidActor objects only.
\note All persistent state of existing interactions will be lost and can not be retrieved even if the same collison pair
is found again in the next step. This will mean, for example, that you will not get notified about persistent contact
for such an interaction (see #PxPairFlag::eNOTIFY_TOUCH_PERSISTS), the contact pair will be interpreted as newly found instead.
\note Lost touch contact reports will be sent for every collision pair which includes this shape, if they have
been requested through #PxPairFlag::eNOTIFY_TOUCH_LOST or #PxPairFlag::eNOTIFY_THRESHOLD_FORCE_LOST.
\note This is an expensive operation, don't use it if you don't have to.
\note Can be used to retrieve collision pairs that were killed by the collision filters (see #PxFilterFlag::eKILL)
\note It is invalid to use this method if the actor has not been added to a scene already.
\note It is invalid to use this method if PxActorFlag::eDISABLE_SIMULATION is set.
\note Do not use this method while the simulation is running.
<b>Sleeping:</b> Does wake up the actor.
\param[in] actor The actor for which to re-evaluate interactions.
\return True if success
@see PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual bool resetFiltering(PxActor& actor) = 0;
/**
\brief Marks the object to reset interactions and re-run collision filters for specified shapes in the next simulation step.
This is a specialization of the resetFiltering(PxActor& actor) method and allows to reset interactions for specific shapes of
a PxRigidActor.
\note Do not use this method while the simulation is running.
<b>Sleeping:</b> Does wake up the actor.
\param[in] actor The actor for which to re-evaluate interactions.
\param[in] shapes The shapes for which to re-evaluate interactions.
\param[in] shapeCount Number of shapes in the list.
@see PxSimulationFilterShader PxSimulationFilterCallback
*/
virtual bool resetFiltering(PxRigidActor& actor, PxShape*const* shapes, PxU32 shapeCount) = 0;
/**
\brief Gets the pair filtering mode for kinematic-kinematic pairs.
\return Filtering mode for kinematic-kinematic pairs.
@see PxPairFilteringMode PxSceneDesc
*/
virtual PxPairFilteringMode::Enum getKinematicKinematicFilteringMode() const = 0;
/**
\brief Gets the pair filtering mode for static-kinematic pairs.
\return Filtering mode for static-kinematic pairs.
@see PxPairFilteringMode PxSceneDesc
*/
virtual PxPairFilteringMode::Enum getStaticKinematicFilteringMode() const = 0;
//@}
/************************************************************************************************/
/** @name Simulation
*/
//@{
/**
\brief Advances the simulation by an elapsedTime time.
\note Large elapsedTime values can lead to instabilities. In such cases elapsedTime
should be subdivided into smaller time intervals and simulate() should be called
multiple times for each interval.
Calls to simulate() should pair with calls to fetchResults():
Each fetchResults() invocation corresponds to exactly one simulate()
invocation; calling simulate() twice without an intervening fetchResults()
or fetchResults() twice without an intervening simulate() causes an error
condition.
scene->simulate();
...do some processing until physics is computed...
scene->fetchResults();
...now results of run may be retrieved.
\param[in] elapsedTime Amount of time to advance simulation by. The parameter has to be larger than 0, else the resulting behavior will be undefined. <b>Range:</b> (0, PX_MAX_F32)
\param[in] completionTask if non-NULL, this task will have its refcount incremented in simulate(), then
decremented when the scene is ready to have fetchResults called. So the task will not run until the
application also calls removeReference().
\param[in] scratchMemBlock a memory region for physx to use for temporary data during simulation. This block may be reused by the application
after fetchResults returns. Must be aligned on a 16-byte boundary
\param[in] scratchMemBlockSize the size of the scratch memory block. Must be a multiple of 16K.
\param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave
true unless the application is calling the PxTaskManager start/stopSimulation() methods itself.
\return True if success
@see fetchResults() checkResults()
*/
virtual bool simulate(PxReal elapsedTime, physx::PxBaseTask* completionTask = NULL,
void* scratchMemBlock = 0, PxU32 scratchMemBlockSize = 0, bool controlSimulation = true) = 0;
/**
\brief Performs dynamics phase of the simulation pipeline.
\note Calls to advance() should follow calls to fetchCollision(). An error message will be issued if this sequence is not followed.
\param[in] completionTask if non-NULL, this task will have its refcount incremented in advance(), then
decremented when the scene is ready to have fetchResults called. So the task will not run until the
application also calls removeReference().
\return True if success
*/
virtual bool advance(physx::PxBaseTask* completionTask = 0) = 0;
/**
\brief Performs collision detection for the scene over elapsedTime
\note Calls to collide() should be the first method called to simulate a frame.
\param[in] elapsedTime Amount of time to advance simulation by. The parameter has to be larger than 0, else the resulting behavior will be undefined. <b>Range:</b> (0, PX_MAX_F32)
\param[in] completionTask if non-NULL, this task will have its refcount incremented in collide(), then
decremented when the scene is ready to have fetchResults called. So the task will not run until the
application also calls removeReference().
\param[in] scratchMemBlock a memory region for physx to use for temporary data during simulation. This block may be reused by the application
after fetchResults returns. Must be aligned on a 16-byte boundary
\param[in] scratchMemBlockSize the size of the scratch memory block. Must be a multiple of 16K.
\param[in] controlSimulation if true, the scene controls its PxTaskManager simulation state. Leave
true unless the application is calling the PxTaskManager start/stopSimulation() methods itself.
\return True if success
*/
virtual bool collide(PxReal elapsedTime, physx::PxBaseTask* completionTask = 0, void* scratchMemBlock = 0,
PxU32 scratchMemBlockSize = 0, bool controlSimulation = true) = 0;
/**
\brief This checks to see if the simulation run has completed.
This does not cause the data available for reading to be updated with the results of the simulation, it is simply a status check.
The bool will allow it to either return immediately or block waiting for the condition to be met so that it can return true
\param[in] block When set to true will block until the condition is met.
\return True if the results are available.
@see simulate() fetchResults()
*/
virtual bool checkResults(bool block = false) = 0;
/**
This method must be called after collide() and before advance(). It will wait for the collision phase to finish. If the user makes an illegal simulation call, the SDK will issue an error
message.
\param[in] block When set to true will block until the condition is met, which is collision must finish running.
*/
virtual bool fetchCollision(bool block = false) = 0;
/**
This is the big brother to checkResults() it basically does the following:
\code
if ( checkResults(block) )
{
fire appropriate callbacks
swap buffers
return true
}
else
return false
\endcode
\param[in] block When set to true will block until results are available.
\param[out] errorState Used to retrieve hardware error codes. A non zero value indicates an error.
\return True if the results have been fetched.
@see simulate() checkResults()
*/
virtual bool fetchResults(bool block = false, PxU32* errorState = 0) = 0;
/**
This call performs the first section of fetchResults, and returns a pointer to the contact streams output by the simulation. It can be used to process contact pairs in parallel, which is often a limiting factor
for fetchResults() performance.
After calling this function and processing the contact streams, call fetchResultsFinish(). Note that writes to the simulation are not
permitted between the start of fetchResultsStart() and the end of fetchResultsFinish().
\param[in] block When set to true will block until results are available.
\param[out] contactPairs an array of pointers to contact pair headers
\param[out] nbContactPairs the number of contact pairs
\return True if the results have been fetched.
@see simulate() checkResults() fetchResults() fetchResultsFinish()
*/
virtual bool fetchResultsStart(const PxContactPairHeader*& contactPairs, PxU32& nbContactPairs, bool block = false) = 0;
/**
This call processes all event callbacks in parallel. It takes a continuation task, which will be executed once all callbacks have been processed.
This is a utility function to make it easier to process callbacks in parallel using the PhysX task system. It can only be used in conjunction with
fetchResultsStart(...) and fetchResultsFinish(...)
\param[in] continuation The task that will be executed once all callbacks have been processed.
*/
virtual void processCallbacks(physx::PxBaseTask* continuation) = 0;
/**
This call performs the second section of fetchResults.
It must be called after fetchResultsStart() returns and contact reports have been processed.
Note that once fetchResultsFinish() has been called, the contact streams returned in fetchResultsStart() will be invalid.
\param[out] errorState Used to retrieve hardware error codes. A non zero value indicates an error.
@see simulate() checkResults() fetchResults() fetchResultsStart()
*/
virtual void fetchResultsFinish(PxU32* errorState = 0) = 0;
/**
This call performs the synchronization of particle system data copies.
*/
virtual void fetchResultsParticleSystem() = 0;
/**
\brief Clear internal buffers and free memory.
This method can be used to clear buffers and free internal memory without having to destroy the scene. Can be useful if
the physics data gets streamed in and a checkpoint with a clean state should be created.
\note It is not allowed to call this method while the simulation is running. The call will fail.
\param[in] sendPendingReports When set to true pending reports will be sent out before the buffers get cleaned up (for instance lost touch contact/trigger reports due to deleted objects).
*/
virtual void flushSimulation(bool sendPendingReports = false) = 0;
/**
\brief Sets a constant gravity for the entire scene.
\note Do not use this method while the simulation is running.
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] vec A new gravity vector(e.g. PxVec3(0.0f,-9.8f,0.0f) ) <b>Range:</b> force vector
@see PxSceneDesc.gravity getGravity()
*/
virtual void setGravity(const PxVec3& vec) = 0;
/**
\brief Retrieves the current gravity setting.
\return The current gravity for the scene.
@see setGravity() PxSceneDesc.gravity
*/
virtual PxVec3 getGravity() const = 0;
/**
\brief Set the bounce threshold velocity. Collision speeds below this threshold will not cause a bounce.
\note Do not use this method while the simulation is running.
@see PxSceneDesc::bounceThresholdVelocity, getBounceThresholdVelocity
*/
virtual void setBounceThresholdVelocity(const PxReal t) = 0;
/**
\brief Return the bounce threshold velocity.
@see PxSceneDesc.bounceThresholdVelocity, setBounceThresholdVelocity
*/
virtual PxReal getBounceThresholdVelocity() const = 0;
/**
\brief Sets the maximum number of CCD passes
\note Do not use this method while the simulation is running.
\param[in] ccdMaxPasses Maximum number of CCD passes
@see PxSceneDesc.ccdMaxPasses getCCDMaxPasses()
*/
virtual void setCCDMaxPasses(PxU32 ccdMaxPasses) = 0;
/**
\brief Gets the maximum number of CCD passes.
\return The maximum number of CCD passes.
@see PxSceneDesc::ccdMaxPasses setCCDMaxPasses()
*/
virtual PxU32 getCCDMaxPasses() const = 0;
/**
\brief Set the maximum CCD separation.
\note Do not use this method while the simulation is running.
@see PxSceneDesc::ccdMaxSeparation, getCCDMaxSeparation
*/
virtual void setCCDMaxSeparation(const PxReal t) = 0;
/**
\brief Gets the maximum CCD separation.
\return The maximum CCD separation.
@see PxSceneDesc::ccdMaxSeparation setCCDMaxSeparation()
*/
virtual PxReal getCCDMaxSeparation() const = 0;
/**
\brief Set the CCD threshold.
\note Do not use this method while the simulation is running.
@see PxSceneDesc::ccdThreshold, getCCDThreshold
*/
virtual void setCCDThreshold(const PxReal t) = 0;
/**
\brief Gets the CCD threshold.
\return The CCD threshold.
@see PxSceneDesc::ccdThreshold setCCDThreshold()
*/
virtual PxReal getCCDThreshold() const = 0;
/**
\brief Set the max bias coefficient.
\note Do not use this method while the simulation is running.
@see PxSceneDesc::maxBiasCoefficient, getMaxBiasCoefficient
*/
virtual void setMaxBiasCoefficient(const PxReal t) = 0;
/**
\brief Gets the max bias coefficient.
\return The max bias coefficient.
@see PxSceneDesc::maxBiasCoefficient setMaxBiasCoefficient()
*/
virtual PxReal getMaxBiasCoefficient() const = 0;
/**
\brief Set the friction offset threshold.
\note Do not use this method while the simulation is running.
@see PxSceneDesc::frictionOffsetThreshold, getFrictionOffsetThreshold
*/
virtual void setFrictionOffsetThreshold(const PxReal t) = 0;
/**
\brief Gets the friction offset threshold.
@see PxSceneDesc::frictionOffsetThreshold, setFrictionOffsetThreshold
*/
virtual PxReal getFrictionOffsetThreshold() const = 0;
/**
\brief Set the friction correlation distance.
\note Do not use this method while the simulation is running.
@see PxSceneDesc::frictionCorrelationDistance, getFrictionCorrelationDistance
*/
virtual void setFrictionCorrelationDistance(const PxReal t) = 0;
/**
\brief Gets the friction correlation distance.
@see PxSceneDesc::frictionCorrelationDistance, setFrictionCorrelationDistance
*/
virtual PxReal getFrictionCorrelationDistance() const = 0;
/**
\brief Return the friction model.
@see PxFrictionType, PxSceneDesc::frictionType
*/
virtual PxFrictionType::Enum getFrictionType() const = 0;
/**
\brief Return the solver model.
@see PxSolverType, PxSceneDesc::solverType
*/
virtual PxSolverType::Enum getSolverType() const = 0;
//@}
/************************************************************************************************/
/** @name Visualization and Statistics
*/
//@{
/**
\brief Function that lets you set debug visualization parameters.
Returns false if the value passed is out of range for usage specified by the enum.
\note Do not use this method while the simulation is running.
\param[in] param Parameter to set. See #PxVisualizationParameter
\param[in] value The value to set, see #PxVisualizationParameter for allowable values. Setting to zero disables visualization for the specified property, setting to a positive value usually enables visualization and defines the scale factor.
\return False if the parameter is out of range.
@see getVisualizationParameter PxVisualizationParameter getRenderBuffer()
*/
virtual bool setVisualizationParameter(PxVisualizationParameter::Enum param, PxReal value) = 0;
/**
\brief Function that lets you query debug visualization parameters.
\param[in] paramEnum The Parameter to retrieve.
\return The value of the parameter.
@see setVisualizationParameter PxVisualizationParameter
*/
virtual PxReal getVisualizationParameter(PxVisualizationParameter::Enum paramEnum) const = 0;
/**
\brief Defines a box in world space to which visualization geometry will be (conservatively) culled. Use a non-empty culling box to enable the feature, and an empty culling box to disable it.
\note Do not use this method while the simulation is running.
\param[in] box the box to which the geometry will be culled. Empty box to disable the feature.
@see setVisualizationParameter getVisualizationCullingBox getRenderBuffer()
*/
virtual void setVisualizationCullingBox(const PxBounds3& box) = 0;
/**
\brief Retrieves the visualization culling box.
\return the box to which the geometry will be culled.
@see setVisualizationParameter setVisualizationCullingBox
*/
virtual PxBounds3 getVisualizationCullingBox() const = 0;
/**
\brief Retrieves the render buffer.
This will contain the results of any active visualization for this scene.
\note Do not use this method while the simulation is running. Calls to this method while the simulation is running will result in undefined behaviour.
\return The render buffer.
@see PxRenderBuffer
*/
virtual const PxRenderBuffer& getRenderBuffer() = 0;
/**
\brief Call this method to retrieve statistics for the current simulation step.
\note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored.
\param[out] stats Used to retrieve statistics for the current simulation step.
@see PxSimulationStatistics
*/
virtual void getSimulationStatistics(PxSimulationStatistics& stats) const = 0;
//@}
/************************************************************************************************/
/** @name Broad-phase
*/
//@{
/**
\brief Returns broad-phase type.
\return Broad-phase type
*/
virtual PxBroadPhaseType::Enum getBroadPhaseType() const = 0;
/**
\brief Gets broad-phase caps.
\param[out] caps Broad-phase caps
\return True if success
*/
virtual bool getBroadPhaseCaps(PxBroadPhaseCaps& caps) const = 0;
/**
\brief Returns number of regions currently registered in the broad-phase.
\return Number of regions
*/
virtual PxU32 getNbBroadPhaseRegions() const = 0;
/**
\brief Gets broad-phase regions.
\param[out] userBuffer Returned broad-phase regions
\param[in] bufferSize Size of userBuffer
\param[in] startIndex Index of first desired region, in [0 ; getNbRegions()[
\return Number of written out regions
*/
virtual PxU32 getBroadPhaseRegions(PxBroadPhaseRegionInfo* userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Adds a new broad-phase region.
The bounds for the new region must be non-empty, otherwise an error occurs and the call is ignored.
Note that by default, objects already existing in the SDK that might touch this region will not be automatically
added to the region. In other words the newly created region will be empty, and will only be populated with new
objects when they are added to the simulation, or with already existing objects when they are updated.
It is nonetheless possible to override this default behavior and let the SDK populate the new region automatically
with already existing objects overlapping the incoming region. This has a cost though, and it should only be used
when the game can not guarantee that all objects within the new region will be added to the simulation after the
region itself.
Objects automatically move from one region to another during their lifetime. The system keeps tracks of what
regions a given object is in. It is legal for an object to be in an arbitrary number of regions. However if an
object leaves all regions, or is created outside of all regions, several things happen:
- collisions get disabled for this object
- if a PxBroadPhaseCallback object is provided, an "out-of-bounds" event is generated via that callback
- if a PxBroadPhaseCallback object is not provided, a warning/error message is sent to the error stream
If an object goes out-of-bounds and user deletes it during the same frame, neither the out-of-bounds event nor the
error message is generated.
\param[in] region User-provided region data
\param[in] populateRegion Automatically populate new region with already existing objects overlapping it
\return Handle for newly created region, or 0xffffffff in case of failure.
\see PxBroadPhaseRegion PxBroadPhaseCallback
*/
virtual PxU32 addBroadPhaseRegion(const PxBroadPhaseRegion& region, bool populateRegion=false) = 0;
/**
\brief Removes a new broad-phase region.
If the region still contains objects, and if those objects do not overlap any region any more, they are not
automatically removed from the simulation. Instead, the PxBroadPhaseCallback::onObjectOutOfBounds notification
is used for each object. Users are responsible for removing the objects from the simulation if this is the
desired behavior.
If the handle is invalid, or if a valid handle is removed twice, an error message is sent to the error stream.
\param[in] handle Region's handle, as returned by PxScene::addBroadPhaseRegion.
\return True if success
*/
virtual bool removeBroadPhaseRegion(PxU32 handle) = 0;
//@}
/************************************************************************************************/
/** @name Threads and Memory
*/
//@{
/**
\brief Get the task manager associated with this scene
\return the task manager associated with the scene
*/
virtual PxTaskManager* getTaskManager() const = 0;
/**
\brief Lock the scene for reading from the calling thread.
When the PxSceneFlag::eREQUIRE_RW_LOCK flag is enabled lockRead() must be
called before any read calls are made on the scene.
Multiple threads may read at the same time, no threads may read while a thread is writing.
If a call to lockRead() is made while another thread is holding a write lock
then the calling thread will be blocked until the writing thread calls unlockWrite().
\note Lock upgrading is *not* supported, that means it is an error to
call lockRead() followed by lockWrite().
\note Recursive locking is supported but each lockRead() call must be paired with an unlockRead().
\param file String representing the calling file, for debug purposes
\param line The source file line number, for debug purposes
*/
virtual void lockRead(const char* file=NULL, PxU32 line=0) = 0;
/**
\brief Unlock the scene from reading.
\note Each unlockRead() must be paired with a lockRead() from the same thread.
*/
virtual void unlockRead() = 0;
/**
\brief Lock the scene for writing from this thread.
When the PxSceneFlag::eREQUIRE_RW_LOCK flag is enabled lockWrite() must be
called before any write calls are made on the scene.
Only one thread may write at a time and no threads may read while a thread is writing.
If a call to lockWrite() is made and there are other threads reading then the
calling thread will be blocked until the readers complete.
Writers have priority. If a thread is blocked waiting to write then subsequent calls to
lockRead() from other threads will be blocked until the writer completes.
\note If multiple threads are waiting to write then the thread that is first
granted access depends on OS scheduling.
\note Recursive locking is supported but each lockWrite() call must be paired
with an unlockWrite().
\note If a thread has already locked the scene for writing then it may call
lockRead().
\param file String representing the calling file, for debug purposes
\param line The source file line number, for debug purposes
*/
virtual void lockWrite(const char* file=NULL, PxU32 line=0) = 0;
/**
\brief Unlock the scene from writing.
\note Each unlockWrite() must be paired with a lockWrite() from the same thread.
*/
virtual void unlockWrite() = 0;
/**
\brief set the cache blocks that can be used during simulate().
Each frame the simulation requires memory to store contact, friction, and contact cache data. This memory is used in blocks of 16K.
Each frame the blocks used by the previous frame are freed, and may be retrieved by the application using PxScene::flushSimulation()
This call will force allocation of cache blocks if the numBlocks parameter is greater than the currently allocated number
of blocks, and less than the max16KContactDataBlocks parameter specified at scene creation time.
\note Do not use this method while the simulation is running.
\param[in] numBlocks The number of blocks to allocate.
@see PxSceneDesc.nbContactDataBlocks PxSceneDesc.maxNbContactDataBlocks flushSimulation() getNbContactDataBlocksUsed getMaxNbContactDataBlocksUsed
*/
virtual void setNbContactDataBlocks(PxU32 numBlocks) = 0;
/**
\brief get the number of cache blocks currently used by the scene
This function may not be called while the scene is simulating
\return the number of cache blocks currently used by the scene
@see PxSceneDesc.nbContactDataBlocks PxSceneDesc.maxNbContactDataBlocks flushSimulation() setNbContactDataBlocks() getMaxNbContactDataBlocksUsed()
*/
virtual PxU32 getNbContactDataBlocksUsed() const = 0;
/**
\brief get the maximum number of cache blocks used by the scene
This function may not be called while the scene is simulating
\return the maximum number of cache blocks everused by the scene
@see PxSceneDesc.nbContactDataBlocks PxSceneDesc.maxNbContactDataBlocks flushSimulation() setNbContactDataBlocks() getNbContactDataBlocksUsed()
*/
virtual PxU32 getMaxNbContactDataBlocksUsed() const = 0;
/**
\brief Return the value of PxSceneDesc::contactReportStreamBufferSize that was set when creating the scene with PxPhysics::createScene
@see PxSceneDesc::contactReportStreamBufferSize, PxPhysics::createScene
*/
virtual PxU32 getContactReportStreamBufferSize() const = 0;
/**
\brief Sets the number of actors required to spawn a separate rigid body solver thread.
\note Do not use this method while the simulation is running.
\param[in] solverBatchSize Number of actors required to spawn a separate rigid body solver thread.
@see PxSceneDesc.solverBatchSize getSolverBatchSize()
*/
virtual void setSolverBatchSize(PxU32 solverBatchSize) = 0;
/**
\brief Retrieves the number of actors required to spawn a separate rigid body solver thread.
\return Current number of actors required to spawn a separate rigid body solver thread.
@see PxSceneDesc.solverBatchSize setSolverBatchSize()
*/
virtual PxU32 getSolverBatchSize() const = 0;
/**
\brief Sets the number of articulations required to spawn a separate rigid body solver thread.
\note Do not use this method while the simulation is running.
\param[in] solverBatchSize Number of articulations required to spawn a separate rigid body solver thread.
@see PxSceneDesc.solverBatchSize getSolverArticulationBatchSize()
*/
virtual void setSolverArticulationBatchSize(PxU32 solverBatchSize) = 0;
/**
\brief Retrieves the number of articulations required to spawn a separate rigid body solver thread.
\return Current number of articulations required to spawn a separate rigid body solver thread.
@see PxSceneDesc.solverBatchSize setSolverArticulationBatchSize()
*/
virtual PxU32 getSolverArticulationBatchSize() const = 0;
//@}
/**
\brief Returns the wake counter reset value.
\return Wake counter reset value
@see PxSceneDesc.wakeCounterResetValue
*/
virtual PxReal getWakeCounterResetValue() const = 0;
/**
\brief Shift the scene origin by the specified vector.
The poses of all objects in the scene and the corresponding data structures will get adjusted to reflect the new origin location
(the shift vector will get subtracted from all object positions).
\note It is the user's responsibility to keep track of the summed total origin shift and adjust all input/output to/from PhysX accordingly.
\note Do not use this method while the simulation is running. Calls to this method while the simulation is running will be ignored.
\note Make sure to propagate the origin shift to other dependent modules (for example, the character controller module etc.).
\note This is an expensive operation and we recommend to use it only in the case where distance related precision issues may arise in areas far from the origin.
\param[in] shift Translation vector to shift the origin by.
*/
virtual void shiftOrigin(const PxVec3& shift) = 0;
/**
\brief Returns the Pvd client associated with the scene.
\return the client, NULL if no PVD supported.
*/
virtual PxPvdSceneClient* getScenePvdClient() = 0;
/**
\brief Copy GPU articulation data from the internal GPU buffer to a user-provided device buffer.
\param[in] data User-provided gpu data buffer which should be sized appropriately for the particular data that is requested. Further details provided in the user guide.
\param[in] index User-provided gpu index buffer. This buffer stores the articulation indices which the user wants to copy.
\param[in] dataType Enum specifying the type of data the user wants to read back from the articulations.
\param[in] nbCopyArticulations Number of articulations that data should be copied from.
\param[in] copyEvent User-provided event for the articulation stream to signal when the data copy to the user buffer has completed. Defaults to NULL, which means that the function will wait for the copy to finish before returning.
*/
virtual void copyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbCopyArticulations, CUevent copyEvent = NULL) = 0;
/**
\brief Apply GPU articulation data from a user-provided device buffer to the internal GPU buffer.
\param[in] data User-provided gpu data buffer which should be sized appropriately for the particular data that is requested. Further details provided in the user guide.
\param[in] index User-provided gpu index buffer. This buffer stores the articulation indices which the user wants to write to.
\param[in] dataType Enum specifying the type of data the user wants to write to the articulations.
\param[in] nbUpdatedArticulations Number of articulations that data should be written to.
\param[in] waitEvent User-provided event for the articulation stream to wait for data. Defaults to NULL, which means the function will execute immediately.
\param[in] signalEvent User-provided event for the articulation stream to signal when the data read from the user buffer has completed. Defaults to NULL which means the function will wait for the copy to finish before returning.
*/
virtual void applyArticulationData(void* data, void* index, PxArticulationGpuDataType::Enum dataType, const PxU32 nbUpdatedArticulations, CUevent waitEvent = NULL, CUevent signalEvent = NULL) = 0;
/**
\brief Update link state for all articulations in the scene that have been updated using PxScene::applyArticulationData(). This function can be
called by the user to propagate changes made to root transform/root velocity/joint position/joint velocities to be reflected in the link transform/velocity.
Calling this function will perform the kinematic update for all the articulations in the scene that have outstanding changes to at least one of the properties
mentioned above. Calling this function will clear output calculated by the simulation, specifically link accelerations, link incoming joint forces, and
joint accelerations, for the articulations affected by the call.
\note Calling this function is not mandatory, as it will be called internally at the start of the simulation step for any outstanding changes.
\note This function has to be called if the user wants to obtain correct link transforms and velocities using PxScene::copyArticulationData() after setting
joint positions, joint velocities, root link transform or root link velocity using PxScene::applyArticulationData().
\note This function only has an effect if the PxSceneFlag::eENABLE_DIRECT_GPU_API is raised and the user has manipulated articulation state
using PxScene::applyArticulationData().
\param[in] signalEvent User-provided event for the articulation stream to signal when the kinematic update has been completed. Defaults to NULL which means the function will wait for the operation to finish before returning.
*/
virtual void updateArticulationsKinematic(CUevent signalEvent = NULL) = 0;
/**
\brief Copy GPU softbody data from the internal GPU buffer to a user-provided device buffer.
\param[in] data User-provided gpu buffer containing a pointer to another gpu buffer for every softbody to process
\param[in] dataSizes The size of every buffer in bytes
\param[in] softBodyIndices User provided gpu index buffer. This buffer stores the softbody index which the user want to copy.
\param[in] maxSize The largest size stored in dataSizes. Used internally to decide how many threads to launch for the copy process.
\param[in] flag Flag defining which data the user wants to read back from the softbody system
\param[in] nbCopySoftBodies The number of softbodies to be copied.
\param[in] copyEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the copy to finish before returning.
*/
virtual void copySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbCopySoftBodies, const PxU32 maxSize, CUevent copyEvent = NULL) = 0;
/**
\brief Apply user-provided data to the internal softbody system.
\param[in] data User-provided gpu buffer containing a pointer to another gpu buffer for every softbody to process
\param[in] dataSizes The size of every buffer in bytes
\param[in] softBodyIndices User provided gpu index buffer. This buffer stores the updated softbody index.
\param[in] flag Flag defining which data the user wants to write to the softbody system
\param[in] maxSize The largest size stored in dataSizes. Used internally to decide how many threads to launch for the copy process.
\param[in] nbUpdatedSoftBodies The number of updated softbodies
\param[in] applyEvent User-provided event for the softbody stream to wait for data.
\param[in] signalEvent User-provided event for the softbody stream to signal when the read from the user buffer has completed. Defaults to NULL which means the function will wait for the copy to finish before returning.
*/
virtual void applySoftBodyData(void** data, void* dataSizes, void* softBodyIndices, PxSoftBodyGpuDataFlag::Enum flag, const PxU32 nbUpdatedSoftBodies, const PxU32 maxSize, CUevent applyEvent = NULL, CUevent signalEvent = NULL) = 0;
/**
\brief Copy rigid body contact data from the internal GPU buffer to a user-provided device buffer.
\note This function only reports contact data for actor pairs where both actors are either rigid bodies or articulations.
\note The contact data contains pointers to internal state and is only valid until the next call to simulate().
\param[in] data User-provided gpu data buffer, which should be the size of PxGpuContactPair * numContactPairs
\param[in] maxContactPairs The maximum number of pairs that the buffer can contain
\param[in] numContactPairs The actual number of contact pairs that were written
\param[in] copyEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the copy to finish before returning.
*/
virtual void copyContactData(void* data, const PxU32 maxContactPairs, void* numContactPairs, CUevent copyEvent = NULL) = 0;
/**
\brief Direct-GPU interface that copies the simulation state for a set of rigid bodies into a user-provided device buffer.
\param[in] data User-provided gpu data buffer which has size (maxSrcIndex + 1) * sizeof(PxGpuBodyData), where maxSrcIndex is the largest index used in the PxGpuActorPairs provided with the index argument. Will contain the PxGpuBodyData for every requested body.
\param[in] index User-provided gpu index buffer containing elements of PxGpuActorPair. This buffer stores pairs of indices: the PxNodeIndex corresponding to the rigid body and an index corresponding to the location in the user buffer that this value should be placed. There must be 1 PxGpuActorPair for each element of the data buffer. The total size of the buffer must be sizeof(PxGpuActorPair) * nbCopyActors.
\param[in] nbCopyActors The number of rigid bodies to be copied.
\param[in] copyEvent User-provided event that is recorded at the end of this function. Defaults to NULL which means the function will wait for the copy to finish before returning.
\note This function only works if PxSceneFlag::eENABLE_DIRECT_GPU_API has been raised, the scene is using GPU dynamics, and the simulation has been warm-started by
simulating for at least 1 simulation step.
*/
virtual void copyBodyData(PxGpuBodyData* data, PxGpuActorPair* index, const PxU32 nbCopyActors, CUevent copyEvent = NULL) = 0;
/**
\brief Direct-GPU interface to apply batched updates to simulation state for a set of rigid bodies from a device buffer.
\param[in] data User-provided gpu data buffer which should be sized appropriately for the particular data that is requested. The data layout for PxActorCacheFlag::eFORCE and PxActorCacheFlag::eTORQUE is 1 PxVec4 per rigid body (4th component is unused). For PxActorCacheFlag::eACTOR_DATA the data layout it 1 PxGpuBodyData per rigid body. The total size of the buffer must be sizeof(type) * (maxSrcIndex + 1), where maxSrcIndex is the largest source index used in the PxGpuActorPairs provided in the index array.
\param[in] index User-provided PxGpuActorPair buffer. This buffer stores pairs of indices: the PxNodeIndex corresponding to the rigid body and an index (srcIndex) corresponding to the location in the user buffer that the value is located at. The total size of this buffer must be sizeof(PxGpuActorPair) * nbUpdatedActors.
\param[in] flag Flag specifying which data the user wants to write to the rigid bodies.
\param[in] nbUpdatedActors The number of updated rigid bodies.
\param[in] waitEvent User-provided event for the rigid body stream to wait for data. Will be awaited at the start of this function. Defaults to NULL which means the operation will start immediately.
\param[in] signalEvent User-provided event for the rigid body stream to signal when the read from the user buffer has completed. Defaults to NULL which means the function will wait for the copy to finish before returning.
\note This function only works if PxSceneFlag::eENABLE_DIRECT_GPU_API has been raised, the scene is using GPU dynamics, and the simulation has been warm-started by
simulating for at least 1 simulation step.
\note The combined usage of this function and the object-oriented CPU interface is forbidden for all parameters that can be set through this function.
Specifically, this includes: PxRigidDynamic::setGlobalPose(), PxRigidDynamic::setLinearVelocity(), PxRigidDynamic::setAngularVelocity(),
PxRigidDynamic::addForce(), PxRigidDynamic::addTorque(), PxRigidDynamic::setForceAndTorque(). However, using the CPU interface to update simulation
parameters like, for example, mass or angular damping is still supported.
*/
virtual void applyActorData(void* data, PxGpuActorPair* index, PxActorCacheFlag::Enum flag, const PxU32 nbUpdatedActors, CUevent waitEvent = NULL, CUevent signalEvent = NULL) = 0;
/**
\brief Evaluate sample point distances on sdf shapes
\param[in] sdfShapeIds The shapes ids in a gpu buffer (must be triangle mesh shapes with SDFs) which specify the shapes from which the sdf information is taken
\param[in] nbShapes The number of shapes
\param[in] localSamplePointsConcatenated User-provided gpu buffer containing the sample point locations for every shape in the shapes local space. The buffer stride is maxPointCount.
\param[in] samplePointCountPerShape Gpu buffer containing the number of sample points for every shape
\param[in] maxPointCount The maximum value in the array samplePointCountPerShape
\param[out] localGradientAndSDFConcatenated The gpu buffer where the evaluated distances and gradients in SDF local space get stored. It has the same structure as localSamplePointsConcatenated.
\param[in] event User-provided event for the user to sync. Defaults to NULL which means the function will wait for the operation to finish before returning.
*/
virtual void evaluateSDFDistances(const PxU32* sdfShapeIds, const PxU32 nbShapes, const PxVec4* localSamplePointsConcatenated,
const PxU32* samplePointCountPerShape, const PxU32 maxPointCount, PxVec4* localGradientAndSDFConcatenated, CUevent event = NULL) = 0;
/**
\brief Compute dense Jacobian matrices for specified articulations on the GPU.
The size of Jacobians can vary by articulation, since it depends on the number of links, degrees-of-freedom, and whether the base is fixed.
The size is determined using these formulas:
nCols = (fixedBase ? 0 : 6) + dofCount
nRows = (fixedBase ? 0 : 6) + (linkCount - 1) * 6;
The user must ensure that adequate space is provided for each Jacobian matrix.
\param[in] indices User-provided gpu buffer of (index, data) pairs. The entries map a GPU articulation index to a GPU block of memory where the returned Jacobian will be stored.
\param[in] nbIndices The number of (index, data) pairs provided.
\param[in] computeEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the computation to finish before returning.
*/
virtual void computeDenseJacobians(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent = NULL) = 0;
/**
\brief Compute the joint-space inertia matrices that maps joint accelerations to joint forces: forces = M * accelerations on the GPU.
The size of matrices can vary by articulation, since it depends on the number of links and degrees-of-freedom.
The size is determined using this formula:
sizeof(float) * dofCount * dofCount
The user must ensure that adequate space is provided for each mass matrix.
\param[in] indices User-provided gpu buffer of (index, data) pairs. The entries map a GPU articulation index to a GPU block of memory where the returned matrix will be stored.
\param[in] nbIndices The number of (index, data) pairs provided.
\param[in] computeEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the computation to finish before returning.
*/
virtual void computeGeneralizedMassMatrices(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent = NULL) = 0;
/**
\brief Computes the joint DOF forces required to counteract gravitational forces for the given articulation pose.
The size of the result can vary by articulation, since it depends on the number of links and degrees-of-freedom.
The size is determined using this formula:
sizeof(float) * dofCount
The user must ensure that adequate space is provided for each articulation.
\param[in] indices User-provided gpu buffer of (index, data) pairs. The entries map a GPU articulation index to a GPU block of memory where the returned matrix will be stored.
\param[in] nbIndices The number of (index, data) pairs provided.
\param[in] computeEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the computation to finish before returning.
*/
virtual void computeGeneralizedGravityForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent = NULL) = 0;
/**
\brief Computes the joint DOF forces required to counteract coriolis and centrifugal forces for the given articulation pose.
The size of the result can vary by articulation, since it depends on the number of links and degrees-of-freedom.
The size is determined using this formula:
sizeof(float) * dofCount
The user must ensure that adequate space is provided for each articulation.
\param[in] indices User-provided gpu buffer of (index, data) pairs. The entries map a GPU articulation index to a GPU block of memory where the returned matrix will be stored.
\param[in] nbIndices The number of (index, data) pairs provided.
\param[in] computeEvent User-provided event for the user to sync data. Defaults to NULL which means the function will wait for the computation to finish before returning.
*/
virtual void computeCoriolisAndCentrifugalForces(const PxIndexDataPair* indices, PxU32 nbIndices, CUevent computeEvent = NULL) = 0;
virtual PxgDynamicsMemoryConfig getGpuDynamicsConfig() const = 0;
/**
\brief Apply user-provided data to particle buffers.
This function should be used if the particle buffer flags are already on the device. Otherwise, use PxParticleBuffer::raiseFlags()
from the CPU.
This assumes the data has been changed directly in the PxParticleBuffer.
\param[in] indices User-provided index buffer that indexes into the BufferIndexPair and flags list.
\param[in] bufferIndexPair User-provided index pair buffer specifying the unique id and GPU particle system for each PxParticleBuffer. See PxGpuParticleBufferIndexPair.
\param[in] flags Flags to mark what data needs to be updated. See PxParticleBufferFlags.
\param[in] nbUpdatedBuffers The number of particle buffers to update.
\param[in] waitEvent User-provided event for the particle stream to wait for data. Defaults to NULL which means the operation will start immediately.
\param[in] signalEvent User-provided event for the particle stream to signal when the data read from the user buffer has completed. Defaults to NULL which means the function will wait for copy to finish before returning.
*/
virtual void applyParticleBufferData(const PxU32* indices, const PxGpuParticleBufferIndexPair* bufferIndexPair, const PxParticleBufferFlags* flags, PxU32 nbUpdatedBuffers, CUevent waitEvent = NULL, CUevent signalEvent = NULL) = 0;
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 79,934 | C | 41.31604 | 513 | 0.758989 |
NVIDIA-Omniverse/PhysX/physx/include/PxSceneQueryDesc.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SCENE_QUERY_DESC_H
#define PX_SCENE_QUERY_DESC_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "geometry/PxBVHBuildStrategy.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxSceneQuerySystem;
/**
\brief Pruning structure used to accelerate scene queries.
eNONE uses a simple data structure that consumes less memory than the alternatives,
but generally has slower query performance.
eDYNAMIC_AABB_TREE usually provides the fastest queries. However there is a
constant per-frame management cost associated with this structure. How much work should
be done per frame can be tuned via the #PxSceneQueryDesc::dynamicTreeRebuildRateHint
parameter.
eSTATIC_AABB_TREE is typically used for static objects. It is the same as the
dynamic AABB tree, without the per-frame overhead. This can be a good choice for static
objects, if no static objects are added, moved or removed after the scene has been
created. If there is no such guarantee (e.g. when streaming parts of the world in and out),
then the dynamic version is a better choice even for static objects.
*/
struct PxPruningStructureType
{
enum Enum
{
eNONE, //!< Using a simple data structure
eDYNAMIC_AABB_TREE, //!< Using a dynamic AABB tree
eSTATIC_AABB_TREE, //!< Using a static AABB tree
eLAST
};
};
/**
\brief Secondary pruning structure used for newly added objects in dynamic trees.
Dynamic trees (PxPruningStructureType::eDYNAMIC_AABB_TREE) are slowly rebuilt
over several frames. A secondary pruning structure holds and manages objects
added to the scene while this rebuild is in progress.
eNONE ignores newly added objects. This means that for a number of frames (roughly
defined by PxSceneQueryDesc::dynamicTreeRebuildRateHint) newly added objects will
be ignored by scene queries. This can be acceptable when streaming large worlds, e.g.
when the objects added at the boundaries of the game world don't immediately need to be
visible from scene queries (it would be equivalent to streaming that data in a few frames
later). The advantage of this approach is that there is no CPU cost associated with
inserting the new objects in the scene query data structures, and no extra runtime cost
when performing queries.
eBUCKET uses a structure similar to PxPruningStructureType::eNONE. Insertion is fast but
query cost can be high.
eINCREMENTAL uses an incremental AABB-tree, with no direct PxPruningStructureType equivalent.
Query time is fast but insertion cost can be high.
eBVH uses a PxBVH structure. This usually offers the best overall performance.
*/
struct PxDynamicTreeSecondaryPruner
{
enum Enum
{
eNONE, //!< no secondary pruner, new objects aren't visible to SQ for a few frames
eBUCKET , //!< bucket-based secondary pruner, faster updates, slower query time
eINCREMENTAL, //!< incremental-BVH secondary pruner, faster query time, slower updates
eBVH, //!< PxBVH-based secondary pruner, good overall performance
eLAST
};
};
/**
\brief Scene query update mode
This enum controls what work is done when the scene query system is updated. The updates traditionally happen when PxScene::fetchResults
is called. This function then calls PxSceneQuerySystem::finalizeUpdates, where the update mode is used.
fetchResults/finalizeUpdates will sync changed bounds during simulation and update the scene query bounds in pruners, this work is mandatory.
eBUILD_ENABLED_COMMIT_ENABLED does allow to execute the new AABB tree build step during fetchResults/finalizeUpdates, additionally
the pruner commit is called where any changes are applied. During commit PhysX refits the dynamic scene query tree and if a new tree
was built and the build finished the tree is swapped with current AABB tree.
eBUILD_ENABLED_COMMIT_DISABLED does allow to execute the new AABB tree build step during fetchResults/finalizeUpdates. Pruner commit
is not called, this means that refit will then occur during the first scene query following fetchResults/finalizeUpdates, or may be forced
by the method PxScene::flushQueryUpdates() / PxSceneQuerySystemBase::flushUpdates().
eBUILD_DISABLED_COMMIT_DISABLED no further scene query work is executed. The scene queries update needs to be called manually, see
PxScene::sceneQueriesUpdate (see that function's doc for the equivalent PxSceneQuerySystem sequence). It is recommended to call
PxScene::sceneQueriesUpdate right after fetchResults/finalizeUpdates as the pruning structures are not updated.
*/
struct PxSceneQueryUpdateMode
{
enum Enum
{
eBUILD_ENABLED_COMMIT_ENABLED, //!< Both scene query build and commit are executed.
eBUILD_ENABLED_COMMIT_DISABLED, //!< Scene query build only is executed.
eBUILD_DISABLED_COMMIT_DISABLED //!< No work is done, no update of scene queries
};
};
/**
\brief Descriptor class for scene query system. See #PxSceneQuerySystem.
*/
class PxSceneQueryDesc
{
public:
/**
\brief Defines the structure used to store static objects (PxRigidStatic actors).
There are usually a lot more static actors than dynamic actors in a scene, so they are stored
in a separate structure. The idea is that when dynamic actors move each frame, the static structure
remains untouched and does not need updating.
<b>Default:</b> PxPruningStructureType::eDYNAMIC_AABB_TREE
\note Only PxPruningStructureType::eSTATIC_AABB_TREE and PxPruningStructureType::eDYNAMIC_AABB_TREE are allowed here.
@see PxPruningStructureType PxSceneSQSystem.getStaticStructure()
*/
PxPruningStructureType::Enum staticStructure;
/**
\brief Defines the structure used to store dynamic objects (non-PxRigidStatic actors).
<b>Default:</b> PxPruningStructureType::eDYNAMIC_AABB_TREE
@see PxPruningStructureType PxSceneSQSystem.getDynamicStructure()
*/
PxPruningStructureType::Enum dynamicStructure;
/**
\brief Hint for how much work should be done per simulation frame to rebuild the pruning structures.
This parameter gives a hint on the distribution of the workload for rebuilding the dynamic AABB tree
pruning structure #PxPruningStructureType::eDYNAMIC_AABB_TREE. It specifies the desired number of simulation frames
the rebuild process should take. Higher values will decrease the workload per frame but the pruning
structure will get more and more outdated the longer the rebuild takes (which can make
scene queries less efficient).
\note Only used for #PxPruningStructureType::eDYNAMIC_AABB_TREE pruning structures.
\note Both staticStructure & dynamicStructure can use a PxPruningStructureType::eDYNAMIC_AABB_TREE, in which case
this parameter is used for both.
\note This parameter gives only a hint. The rebuild process might still take more or less time depending on the
number of objects involved.
<b>Range:</b> [4, PX_MAX_U32)<br>
<b>Default:</b> 100
@see PxSceneQuerySystemBase.setDynamicTreeRebuildRateHint() PxSceneQuerySystemBase.getDynamicTreeRebuildRateHint()
*/
PxU32 dynamicTreeRebuildRateHint;
/**
\brief Secondary pruner for dynamic tree.
This is used for PxPruningStructureType::eDYNAMIC_AABB_TREE structures, to control how objects added to the system
at runtime are managed.
\note Both staticStructure & dynamicStructure can use a PxPruningStructureType::eDYNAMIC_AABB_TREE, in which case
this parameter is used for both.
<b>Default:</b> PxDynamicTreeSecondaryPruner::eINCREMENTAL
@see PxDynamicTreeSecondaryPruner
*/
PxDynamicTreeSecondaryPruner::Enum dynamicTreeSecondaryPruner;
/**
\brief Build strategy for PxSceneQueryDesc::staticStructure.
This parameter is used to refine / control the build strategy of PxSceneQueryDesc::staticStructure. This is only
used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE.
<b>Default:</b> PxBVHBuildStrategy::eFAST
@see PxBVHBuildStrategy PxSceneQueryDesc::staticStructure
*/
PxBVHBuildStrategy::Enum staticBVHBuildStrategy;
/**
\brief Build strategy for PxSceneQueryDesc::dynamicStructure.
This parameter is used to refine / control the build strategy of PxSceneQueryDesc::dynamicStructure. This is only
used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE.
<b>Default:</b> PxBVHBuildStrategy::eFAST
@see PxBVHBuildStrategy PxSceneQueryDesc::dynamicStructure
*/
PxBVHBuildStrategy::Enum dynamicBVHBuildStrategy;
/**
\brief Number of objects per node for PxSceneQueryDesc::staticStructure.
This parameter is used to refine / control the number of objects per node for PxSceneQueryDesc::staticStructure.
This is only used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE.
This parameter has an impact on how quickly the structure gets built, and on the per-frame cost of maintaining
the structure. Increasing this value gives smaller AABB-trees that use less memory, are faster to build and
update, but it can lead to slower queries.
<b>Default:</b> 4
@see PxSceneQueryDesc::staticStructure
*/
PxU32 staticNbObjectsPerNode;
/**
\brief Number of objects per node for PxSceneQueryDesc::dynamicStructure.
This parameter is used to refine / control the number of objects per node for PxSceneQueryDesc::dynamicStructure.
This is only used with PxPruningStructureType::eDYNAMIC_AABB_TREE and PxPruningStructureType::eSTATIC_AABB_TREE.
This parameter has an impact on how quickly the structure gets built, and on the per-frame cost of maintaining
the structure. Increasing this value gives smaller AABB-trees that use less memory, are faster to build and
update, but it can lead to slower queries.
<b>Default:</b> 4
@see PxSceneQueryDesc::dynamicStructure
*/
PxU32 dynamicNbObjectsPerNode;
/**
\brief Defines the scene query update mode.
<b>Default:</b> PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED
@see PxSceneQuerySystemBase.setUpdateMode() PxSceneQuerySystemBase.getUpdateMode()
*/
PxSceneQueryUpdateMode::Enum sceneQueryUpdateMode;
public:
/**
\brief constructor sets to default.
*/
PX_INLINE PxSceneQueryDesc();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxSceneQueryDesc::PxSceneQueryDesc():
staticStructure (PxPruningStructureType::eDYNAMIC_AABB_TREE),
dynamicStructure (PxPruningStructureType::eDYNAMIC_AABB_TREE),
dynamicTreeRebuildRateHint (100),
dynamicTreeSecondaryPruner (PxDynamicTreeSecondaryPruner::eINCREMENTAL),
staticBVHBuildStrategy (PxBVHBuildStrategy::eFAST),
dynamicBVHBuildStrategy (PxBVHBuildStrategy::eFAST),
staticNbObjectsPerNode (4),
dynamicNbObjectsPerNode (4),
sceneQueryUpdateMode (PxSceneQueryUpdateMode::eBUILD_ENABLED_COMMIT_ENABLED)
{
}
PX_INLINE void PxSceneQueryDesc::setToDefault()
{
*this = PxSceneQueryDesc();
}
PX_INLINE bool PxSceneQueryDesc::isValid() const
{
if(staticStructure!=PxPruningStructureType::eSTATIC_AABB_TREE && staticStructure!=PxPruningStructureType::eDYNAMIC_AABB_TREE)
return false;
if(dynamicTreeRebuildRateHint < 4)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 12,911 | C | 38.2462 | 141 | 0.789482 |
NVIDIA-Omniverse/PhysX/physx/include/PxVisualizationParameter.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_VISUALIZATION_PARAMETER_H
#define PX_VISUALIZATION_PARAMETER_H
#include "foundation/PxPreprocessor.h"
/** \addtogroup physics
@{
*/
#if !PX_DOXYGEN
namespace physx
{
#endif
/*
NOTE: Parameters should NOT be conditionally compiled out. Even if a particular feature is not available.
Otherwise the parameter values get shifted about and the numeric values change per platform. This causes problems
when trying to serialize parameters.
New parameters should also be added to the end of the list for this reason. Also make sure to update
eNUM_VALUES, which should be one higher than the maximum value in the enum.
*/
/**
\brief Debug visualization parameters.
#PxVisualizationParameter::eSCALE is the master switch for enabling visualization, please read the corresponding documentation
for further details.
@see PxScene.setVisualizationParameter() PxScene.getVisualizationParameter() PxScene.getRenderBuffer()
*/
struct PxVisualizationParameter
{
enum Enum
{
/* RigidBody-related parameters */
/**
\brief This overall visualization scale gets multiplied with the individual scales. Setting to zero ignores all visualizations. Default is 0.
The below settings permit the debug visualization of various simulation properties.
The setting is either zero, in which case the property is not drawn. Otherwise it is a scaling factor
that determines the size of the visualization widgets.
Only objects for which visualization is turned on using setFlag(eVISUALIZATION) are visualized (see #PxActorFlag::eVISUALIZATION, #PxShapeFlag::eVISUALIZATION, ...).
Default is 0.
Notes:
- to see any visualization, you have to set PxVisualizationParameter::eSCALE to nonzero first.
- the scale factor has been introduced because it's difficult (if not impossible) to come up with a
good scale for 3D vectors. Normals are normalized and their length is always 1. But it doesn't mean
we should render a line of length 1. Depending on your objects/scene, this might be completely invisible
or extremely huge. That's why the scale factor is here, to let you tune the length until it's ok in
your scene.
- however, things like collision shapes aren't ambiguous. They are clearly defined for example by the
triangles & polygons themselves, and there's no point in scaling that. So the visualization widgets
are only scaled when it makes sense.
<b>Range:</b> [0, PX_MAX_F32)<br>
<b>Default:</b> 0
*/
eSCALE,
/**
\brief Visualize the world axes.
*/
eWORLD_AXES,
/* Body visualizations */
/**
\brief Visualize a bodies axes.
@see PxActor.globalPose PxActor
*/
eBODY_AXES,
/**
\brief Visualize a body's mass axes.
This visualization is also useful for visualizing the sleep state of bodies. Sleeping bodies are drawn in
black, while awake bodies are drawn in white. If the body is sleeping and part of a sleeping group, it is
drawn in red.
@see PxBodyDesc.massLocalPose PxActor
*/
eBODY_MASS_AXES,
/**
\brief Visualize the bodies linear velocity.
@see PxBodyDesc.linearVelocity PxActor
*/
eBODY_LIN_VELOCITY,
/**
\brief Visualize the bodies angular velocity.
@see PxBodyDesc.angularVelocity PxActor
*/
eBODY_ANG_VELOCITY,
/* Contact visualisations */
/**
\brief Visualize contact points. Will enable contact information.
*/
eCONTACT_POINT,
/**
\brief Visualize contact normals. Will enable contact information.
*/
eCONTACT_NORMAL,
/**
\brief Visualize contact errors. Will enable contact information.
*/
eCONTACT_ERROR,
/**
\brief Visualize Contact forces. Will enable contact information.
*/
eCONTACT_FORCE,
/**
\brief Visualize actor axes.
@see PxRigidStatic PxRigidDynamic PxArticulationLink
*/
eACTOR_AXES,
/**
\brief Visualize bounds (AABBs in world space)
*/
eCOLLISION_AABBS,
/**
\brief Shape visualization
@see PxShape
*/
eCOLLISION_SHAPES,
/**
\brief Shape axis visualization
@see PxShape
*/
eCOLLISION_AXES,
/**
\brief Compound visualization (compound AABBs in world space)
*/
eCOLLISION_COMPOUNDS,
/**
\brief Mesh & convex face normals
@see PxTriangleMesh PxConvexMesh
*/
eCOLLISION_FNORMALS,
/**
\brief Active edges for meshes
@see PxTriangleMesh
*/
eCOLLISION_EDGES,
/**
\brief Static pruning structures
*/
eCOLLISION_STATIC,
/**
\brief Dynamic pruning structures
*/
eCOLLISION_DYNAMIC,
/**
\brief Joint local axes
*/
eJOINT_LOCAL_FRAMES,
/**
\brief Joint limits
*/
eJOINT_LIMITS,
/**
\brief Visualize culling box
*/
eCULL_BOX,
/**
\brief MBP regions
*/
eMBP_REGIONS,
/**
\brief Renders the simulation mesh instead of the collision mesh (only available for tetmeshes)
*/
eSIMULATION_MESH,
/**
\brief Renders the SDF of a mesh instead of the collision mesh (only available for triangle meshes with SDFs)
*/
eSDF,
/**
\brief This is not a parameter, it just records the current number of parameters (as maximum(PxVisualizationParameter)+1) for use in loops.
*/
eNUM_VALUES,
eFORCE_DWORD = 0x7fffffff
};
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,909 | C | 26.312253 | 167 | 0.73151 |
NVIDIA-Omniverse/PhysX/physx/include/PxSceneDesc.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SCENE_DESC_H
#define PX_SCENE_DESC_H
/** \addtogroup physics
@{
*/
#include "PxSceneQueryDesc.h"
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxBitUtils.h"
#include "PxFiltering.h"
#include "PxBroadPhase.h"
#include "common/PxTolerancesScale.h"
#include "task/PxTask.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBroadPhaseCallback;
class PxCudaContextManager;
/**
\brief Enum for selecting the friction algorithm used for simulation.
#PxFrictionType::ePATCH selects the patch friction model which typically leads to the most stable results at low solver iteration counts and is also quite inexpensive, as it uses only
up to four scalar solver constraints per pair of touching objects. The patch friction model is the same basic strong friction algorithm as PhysX 3.2 and before.
#PxFrictionType::eTWO_DIRECTIONAL is identical to the one directional model, but it applies friction in both tangent directions simultaneously. This hurts convergence a bit so it
requires more solver iterations, but is more accurate. Like the one directional model, it is applied at every contact point, which makes it potentially more expensive
than patch friction for scenarios with many contact points.
#PxFrictionType::eFRICTION_COUNT is the total numer of friction models supported by the SDK.
*/
struct PxFrictionType
{
enum Enum
{
ePATCH, //!< Select default patch-friction model.
eONE_DIRECTIONAL PX_DEPRECATED, //!< @deprecated Please do not use any longer.
eTWO_DIRECTIONAL, //!< Select two directional per-contact friction model.
eFRICTION_COUNT //!< The total number of friction models supported by the SDK.
};
};
/**
\brief Enum for selecting the type of solver used for the simulation.
#PxSolverType::ePGS selects the iterative sequential impulse solver. This is the same kind of solver used in PhysX 3.4 and earlier releases.
#PxSolverType::eTGS selects a non linear iterative solver. This kind of solver can lead to improved convergence and handle large mass ratios, long chains and jointed systems better. It is slightly more expensive than the default solver and can introduce more energy to correct joint and contact errors.
*/
struct PxSolverType
{
enum Enum
{
ePGS, //!< Projected Gauss-Seidel iterative solver
eTGS //!< Temporal Gauss-Seidel solver
};
};
/**
\brief flags for configuring properties of the scene
@see PxScene
*/
struct PxSceneFlag
{
enum Enum
{
/**
\brief Enable Active Actors Notification.
This flag enables the Active Actor Notification feature for a scene. This
feature defaults to disabled. When disabled, the function
PxScene::getActiveActors() will always return a NULL list.
\note There may be a performance penalty for enabling the Active Actor Notification, hence this flag should
only be enabled if the application intends to use the feature.
<b>Default:</b> False
*/
eENABLE_ACTIVE_ACTORS = (1<<0),
/**
\brief Enables a second broad phase check after integration that makes it possible to prevent objects from tunneling through eachother.
PxPairFlag::eDETECT_CCD_CONTACT requires this flag to be specified.
\note For this feature to be effective for bodies that can move at a significant velocity, the user should raise the flag PxRigidBodyFlag::eENABLE_CCD for them.
\note This flag is not mutable, and must be set in PxSceneDesc at scene creation.
<b>Default:</b> False
@see PxRigidBodyFlag::eENABLE_CCD, PxPairFlag::eDETECT_CCD_CONTACT, eDISABLE_CCD_RESWEEP
*/
eENABLE_CCD = (1<<1),
/**
\brief Enables a simplified swept integration strategy, which sacrifices some accuracy for improved performance.
This simplified swept integration approach makes certain assumptions about the motion of objects that are not made when using a full swept integration.
These assumptions usually hold but there are cases where they could result in incorrect behavior between a set of fast-moving rigid bodies. A key issue is that
fast-moving dynamic objects may tunnel through each-other after a rebound. This will not happen if this mode is disabled. However, this approach will be potentially
faster than a full swept integration because it will perform significantly fewer sweeps in non-trivial scenes involving many fast-moving objects. This approach
should successfully resist objects passing through the static environment.
PxPairFlag::eDETECT_CCD_CONTACT requires this flag to be specified.
\note This scene flag requires eENABLE_CCD to be enabled as well. If it is not, this scene flag will do nothing.
\note For this feature to be effective for bodies that can move at a significant velocity, the user should raise the flag PxRigidBodyFlag::eENABLE_CCD for them.
\note This flag is not mutable, and must be set in PxSceneDesc at scene creation.
<b>Default:</b> False
@see PxRigidBodyFlag::eENABLE_CCD, PxPairFlag::eDETECT_CCD_CONTACT, eENABLE_CCD
*/
eDISABLE_CCD_RESWEEP = (1<<2),
/**
\brief Enable GJK-based distance collision detection system.
\note This flag is not mutable, and must be set in PxSceneDesc at scene creation.
<b>Default:</b> true
*/
eENABLE_PCM = (1 << 6),
/**
\brief Disable contact report buffer resize. Once the contact buffer is full, the rest of the contact reports will
not be buffered and sent.
\note This flag is not mutable, and must be set in PxSceneDesc at scene creation.
<b>Default:</b> false
*/
eDISABLE_CONTACT_REPORT_BUFFER_RESIZE = (1 << 7),
/**
\brief Disable contact cache.
Contact caches are used internally to provide faster contact generation. You can disable all contact caches
if memory usage for this feature becomes too high.
\note This flag is not mutable, and must be set in PxSceneDesc at scene creation.
<b>Default:</b> false
*/
eDISABLE_CONTACT_CACHE = (1 << 8),
/**
\brief Require scene-level locking
When set to true this requires that threads accessing the PxScene use the
multi-threaded lock methods.
\note This flag is not mutable, and must be set in PxSceneDesc at scene creation.
@see PxScene::lockRead
@see PxScene::unlockRead
@see PxScene::lockWrite
@see PxScene::unlockWrite
<b>Default:</b> false
*/
eREQUIRE_RW_LOCK = (1 << 9),
/**
\brief Enables additional stabilization pass in solver
When set to true, this enables additional stabilization processing to improve that stability of complex interactions between large numbers of bodies.
Note that this flag is not mutable and must be set in PxSceneDesc at scene creation. Also, this is an experimental feature which does result in some loss of momentum.
*/
eENABLE_STABILIZATION = (1 << 10),
/**
\brief Enables average points in contact manifolds
When set to true, this enables additional contacts to be generated per manifold to represent the average point in a manifold. This can stabilize stacking when only a small
number of solver iterations is used.
Note that this flag is not mutable and must be set in PxSceneDesc at scene creation.
*/
eENABLE_AVERAGE_POINT = (1 << 11),
/**
\brief Do not report kinematics in list of active actors.
Since the target pose for kinematics is set by the user, an application can track the activity state directly and use
this flag to avoid that kinematics get added to the list of active actors.
\note This flag has only an effect in combination with eENABLE_ACTIVE_ACTORS.
@see eENABLE_ACTIVE_ACTORS
<b>Default:</b> false
*/
eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS = (1 << 12),
/*\brief Enables the GPU dynamics pipeline
When set to true, a CUDA ARCH 3.0 or above-enabled NVIDIA GPU is present and the CUDA context manager has been configured, this will run the GPU dynamics pipelin instead of the CPU dynamics pipeline.
Note that this flag is not mutable and must be set in PxSceneDesc at scene creation.
*/
eENABLE_GPU_DYNAMICS = (1 << 13),
/**
\brief Provides improved determinism at the expense of performance.
By default, PhysX provides limited determinism guarantees. Specifically, PhysX guarantees that the exact scene (same actors created in the same order) and simulated using the same
time-stepping scheme should provide the exact same behaviour.
However, if additional actors are added to the simulation, this can affect the behaviour of the existing actors in the simulation, even if the set of new actors do not interact with
the existing actors.
This flag provides an additional level of determinism that guarantees that the simulation will not change if additional actors are added to the simulation, provided those actors do not interfere
with the existing actors in the scene. Determinism is only guaranteed if the actors are inserted in a consistent order each run in a newly-created scene and simulated using a consistent time-stepping
scheme.
Note that this flag is not mutable and must be set at scene creation.
Note that enabling this flag can have a negative impact on performance.
Note that this feature is not currently supported on GPU.
<b>Default</b> false
*/
eENABLE_ENHANCED_DETERMINISM = (1<<14),
/**
\brief Controls processing friction in all solver iterations
By default, PhysX processes friction only in the final 3 position iterations, and all velocity
iterations. This flag enables friction processing in all position and velocity iterations.
The default behaviour provides a good trade-off between performance and stability and is aimed
primarily at game development.
When simulating more complex frictional behaviour, such as grasping of complex geometries with
a robotic manipulator, better results can be achieved by enabling friction in all solver iterations.
\note This flag only has effect with the default solver. The TGS solver always performs friction per-iteration.
*/
eENABLE_FRICTION_EVERY_ITERATION = (1 << 15),
/*
\brief Enables the direct-GPU API. Raising this flag is only allowed if eENABLE_GPU_DYNAMICS is raised and
PxBroadphaseType::eGPU is used.
This is useful if your application only needs to communicate to the GPU via GPU buffers. Can be significantly
faster.
\note Enabling the direct-GPU API will disable the readback of simulation state from GPU to CPU. Simulation outputs
can only be accessed using the direct-GPU API functions in PxScene (PxScene::copyBodyData(), PxScene::copyArticulationData(),
PxScene::copySoftbodyData(), PxScene::copyContactData()), and reading state directly from the actor is not allowed.
\note This flag is not mutable and must be set in PxSceneDesc at scene creation.
*/
eENABLE_DIRECT_GPU_API = (1 << 16),
eMUTABLE_FLAGS = eENABLE_ACTIVE_ACTORS|eEXCLUDE_KINEMATICS_FROM_ACTIVE_ACTORS
};
};
/**
\brief collection of set bits defined in PxSceneFlag.
@see PxSceneFlag
*/
typedef PxFlags<PxSceneFlag::Enum,PxU32> PxSceneFlags;
PX_FLAGS_OPERATORS(PxSceneFlag::Enum,PxU32)
class PxSimulationEventCallback;
class PxContactModifyCallback;
class PxCCDContactModifyCallback;
class PxSimulationFilterCallback;
/**
\brief Class used to retrieve limits(e.g. maximum number of bodies) for a scene. The limits
are used as a hint to the size of the scene, not as a hard limit (i.e. it will be possible
to create more objects than specified in the scene limits).
0 indicates no limit. Using limits allows the SDK to preallocate various arrays, leading to
less re-allocations and faster code at runtime.
*/
class PxSceneLimits
{
public:
PxU32 maxNbActors; //!< Expected maximum number of actors
PxU32 maxNbBodies; //!< Expected maximum number of dynamic rigid bodies
PxU32 maxNbStaticShapes; //!< Expected maximum number of static shapes
PxU32 maxNbDynamicShapes; //!< Expected maximum number of dynamic shapes
PxU32 maxNbAggregates; //!< Expected maximum number of aggregates
PxU32 maxNbConstraints; //!< Expected maximum number of constraint shaders
PxU32 maxNbRegions; //!< Expected maximum number of broad-phase regions
PxU32 maxNbBroadPhaseOverlaps; //!< Expected maximum number of broad-phase overlaps
/**
\brief constructor sets to default
*/
PX_INLINE PxSceneLimits();
/**
\brief (re)sets the structure to the default
*/
PX_INLINE void setToDefault();
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxSceneLimits::PxSceneLimits() : //constructor sets to default
maxNbActors (0),
maxNbBodies (0),
maxNbStaticShapes (0),
maxNbDynamicShapes (0),
maxNbAggregates (0),
maxNbConstraints (0),
maxNbRegions (0),
maxNbBroadPhaseOverlaps (0)
{
}
PX_INLINE void PxSceneLimits::setToDefault()
{
*this = PxSceneLimits();
}
PX_INLINE bool PxSceneLimits::isValid() const
{
if(maxNbRegions>256) // max number of regions is currently limited
return false;
return true;
}
//#if PX_SUPPORT_GPU_PHYSX
/**
\brief Sizes of pre-allocated buffers use for GPU dynamics
*/
struct PxgDynamicsMemoryConfig
{
PxU32 tempBufferCapacity; //!< Initial capacity of temp solver buffer allocated in pinned host memory. This buffer will grow if more memory is needed than specified here.
PxU32 maxRigidContactCount; //!< Size of contact stream buffer allocated in pinned host memory. This is double-buffered so total allocation size = 2* contactStreamCapacity * sizeof(PxContact).
PxU32 maxRigidPatchCount; //!< Size of the contact patch stream buffer allocated in pinned host memory. This is double-buffered so total allocation size = 2 * patchStreamCapacity * sizeof(PxContactPatch).
PxU32 heapCapacity; //!< Initial capacity of the GPU and pinned host memory heaps. Additional memory will be allocated if more memory is required.
PxU32 foundLostPairsCapacity; //!< Capacity of found and lost buffers allocated in GPU global memory. This is used for the found/lost pair reports in the BP.
PxU32 foundLostAggregatePairsCapacity; //!<Capacity of found and lost buffers in aggregate system allocated in GPU global memory. This is used for the found/lost pair reports in AABB manager
PxU32 totalAggregatePairsCapacity; //!<Capacity of total number of aggregate pairs allocated in GPU global memory.
PxU32 maxSoftBodyContacts;
PxU32 maxFemClothContacts;
PxU32 maxParticleContacts;
PxU32 collisionStackSize;
PxU32 maxHairContacts;
PxgDynamicsMemoryConfig() :
tempBufferCapacity(16 * 1024 * 1024),
maxRigidContactCount(1024 * 512),
maxRigidPatchCount(1024 * 80),
heapCapacity(64 * 1024 * 1024),
foundLostPairsCapacity(256 * 1024),
foundLostAggregatePairsCapacity(1024),
totalAggregatePairsCapacity(1024),
maxSoftBodyContacts(1 * 1024 * 1024),
maxFemClothContacts(1 * 1024 * 1024),
maxParticleContacts(1*1024*1024),
collisionStackSize(64*1024*1024),
maxHairContacts(1 * 1024 * 1024)
{
}
PX_PHYSX_CORE_API bool isValid() const;
};
PX_INLINE bool PxgDynamicsMemoryConfig::isValid() const
{
const bool isPowerOfTwo = PxIsPowerOfTwo(heapCapacity);
return isPowerOfTwo;
}
//#endif
/**
\brief Descriptor class for scenes. See #PxScene.
This struct must be initialized with the same PxTolerancesScale values used to initialize PxPhysics.
@see PxScene PxPhysics.createScene PxTolerancesScale
*/
class PxSceneDesc : public PxSceneQueryDesc
{
public:
/**
\brief Gravity vector.
<b>Range:</b> force vector<br>
<b>Default:</b> Zero
@see PxScene.setGravity() PxScene.getGravity()
When setting gravity, you should probably also set bounce threshold.
*/
PxVec3 gravity;
/**
\brief Possible notification callback.
<b>Default:</b> NULL
@see PxSimulationEventCallback PxScene.setSimulationEventCallback() PxScene.getSimulationEventCallback()
*/
PxSimulationEventCallback* simulationEventCallback;
/**
\brief Possible asynchronous callback for contact modification.
<b>Default:</b> NULL
@see PxContactModifyCallback PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
PxContactModifyCallback* contactModifyCallback;
/**
\brief Possible asynchronous callback for contact modification.
<b>Default:</b> NULL
@see PxContactModifyCallback PxScene.setContactModifyCallback() PxScene.getContactModifyCallback()
*/
PxCCDContactModifyCallback* ccdContactModifyCallback;
/**
\brief Shared global filter data which will get passed into the filter shader.
\note The provided data will get copied to internal buffers and this copy will be used for filtering calls.
<b>Default:</b> NULL
@see PxSimulationFilterShader PxScene.setFilterShaderData() PxScene.getFilterShaderData()
*/
const void* filterShaderData;
/**
\brief Size (in bytes) of the shared global filter data #filterShaderData.
<b>Default:</b> 0
@see PxSimulationFilterShader filterShaderData PxScene.getFilterShaderDataSize()
*/
PxU32 filterShaderDataSize;
/**
\brief The custom filter shader to use for collision filtering.
\note This parameter is compulsory. If you don't want to define your own filter shader you can
use the default shader #PxDefaultSimulationFilterShader which can be found in the PhysX extensions
library.
@see PxSimulationFilterShader PxScene.getFilterShader()
*/
PxSimulationFilterShader filterShader;
/**
\brief A custom collision filter callback which can be used to implement more complex filtering operations which need
access to the simulation state, for example.
<b>Default:</b> NULL
@see PxSimulationFilterCallback PxScene.getFilterCallback()
*/
PxSimulationFilterCallback* filterCallback;
/**
\brief Filtering mode for kinematic-kinematic pairs in the broadphase.
<b>Default:</b> PxPairFilteringMode::eDEFAULT
@see PxPairFilteringMode PxScene.getKinematicKinematicFilteringMode()
*/
PxPairFilteringMode::Enum kineKineFilteringMode;
/**
\brief Filtering mode for static-kinematic pairs in the broadphase.
<b>Default:</b> PxPairFilteringMode::eDEFAULT
@see PxPairFilteringMode PxScene.getStaticKinematicFilteringMode()
*/
PxPairFilteringMode::Enum staticKineFilteringMode;
/**
\brief Selects the broad-phase algorithm to use.
<b>Default:</b> PxBroadPhaseType::ePABP
@see PxBroadPhaseType PxScene.getBroadPhaseType()
*/
PxBroadPhaseType::Enum broadPhaseType;
/**
\brief Broad-phase callback
<b>Default:</b> NULL
@see PxBroadPhaseCallback PxScene.getBroadPhaseCallback() PxScene.setBroadPhaseCallback()
*/
PxBroadPhaseCallback* broadPhaseCallback;
/**
\brief Expected scene limits.
@see PxSceneLimits PxScene.getLimits()
*/
PxSceneLimits limits;
/**
\brief Selects the friction algorithm to use for simulation.
\note frictionType cannot be modified after the first call to any of PxScene::simulate, PxScene::solve and PxScene::collide
<b>Default:</b> PxFrictionType::ePATCH
@see PxFrictionType PxScene.setFrictionType(), PxScene.getFrictionType()
*/
PxFrictionType::Enum frictionType;
/**
\brief Selects the solver algorithm to use.
<b>Default:</b> PxSolverType::ePGS
@see PxSolverType PxScene.getSolverType()
*/
PxSolverType::Enum solverType;
/**
\brief A contact with a relative velocity below this will not bounce. A typical value for simulation.
stability is about 0.2 * gravity.
<b>Range:</b> (0, PX_MAX_F32)<br>
<b>Default:</b> 0.2 * PxTolerancesScale::speed
@see PxMaterial PxScene.setBounceThresholdVelocity() PxScene.getBounceThresholdVelocity()
*/
PxReal bounceThresholdVelocity;
/**
\brief A threshold of contact separation distance used to decide if a contact point will experience friction forces.
\note If the separation distance of a contact point is greater than the threshold then the contact point will not experience friction forces.
\note If the aggregated contact offset of a pair of shapes is large it might be desirable to neglect friction
for contact points whose separation distance is sufficiently large that the shape surfaces are clearly separated.
\note This parameter can be used to tune the separation distance of contact points at which friction starts to have an effect.
<b>Range:</b> [0, PX_MAX_F32)<br>
<b>Default:</b> 0.04 * PxTolerancesScale::length
@see PxScene.setFrictionOffsetThreshold() PxScene.getFrictionOffsetThreshold()
*/
PxReal frictionOffsetThreshold;
/**
\brief Friction correlation distance used to decide whether contacts are close enough to be merged into a single friction anchor point or not.
\note If the correlation distance is larger than the distance between contact points generated between a pair of shapes, some of the contacts may not experience frictional forces.
\note This parameter can be used to tune the correlation distance used in the solver. Contact points can be merged into a single friction anchor if the distance between the contacts is smaller than correlation distance.
<b>Range:</b> [0, PX_MAX_F32)<br>
<b>Default:</b> 0.025f * PxTolerancesScale::length
@see PxScene.setFrictionCorrelationDistance() PxScene.getFrictionCorrelationDistance()
*/
PxReal frictionCorrelationDistance;
/**
\brief Flags used to select scene options.
<b>Default:</b> PxSceneFlag::eENABLE_PCM
@see PxSceneFlag PxSceneFlags PxScene.getFlags() PxScene.setFlag()
*/
PxSceneFlags flags;
/**
\brief The CPU task dispatcher for the scene.
@see PxCpuDispatcher, PxScene::getCpuDispatcher
*/
PxCpuDispatcher* cpuDispatcher;
/**
\brief The CUDA context manager for the scene.
<b>Platform specific:</b> Applies to PC GPU only.
@see PxCudaContextManager, PxScene::getCudaContextManager
*/
PxCudaContextManager* cudaContextManager;
/**
\brief Will be copied to PxScene::userData.
<b>Default:</b> NULL
*/
void* userData;
/**
\brief Defines the number of actors required to spawn a separate rigid body solver island task chain.
This parameter defines the minimum number of actors required to spawn a separate rigid body solver task chain. Setting a low value
will potentially cause more task chains to be generated. This may result in the overhead of spawning tasks can become a limiting performance factor.
Setting a high value will potentially cause fewer islands to be generated. This may reduce thread scaling (fewer task chains spawned) and may
detrimentally affect performance if some bodies in the scene have large solver iteration counts because all constraints in a given island are solved by the
maximum number of solver iterations requested by any body in the island.
Note that a rigid body solver task chain is spawned as soon as either a sufficient number of rigid bodies or articulations are batched together.
<b>Default:</b> 128
@see PxScene.setSolverBatchSize() PxScene.getSolverBatchSize()
*/
PxU32 solverBatchSize;
/**
\brief Defines the number of articulations required to spawn a separate rigid body solver island task chain.
This parameter defines the minimum number of articulations required to spawn a separate rigid body solver task chain. Setting a low value
will potentially cause more task chains to be generated. This may result in the overhead of spawning tasks can become a limiting performance factor.
Setting a high value will potentially cause fewer islands to be generated. This may reduce thread scaling (fewer task chains spawned) and may
detrimentally affect performance if some bodies in the scene have large solver iteration counts because all constraints in a given island are solved by the
maximum number of solver iterations requested by any body in the island.
Note that a rigid body solver task chain is spawned as soon as either a sufficient number of rigid bodies or articulations are batched together.
<b>Default:</b> 16
@see PxScene.setSolverArticulationBatchSize() PxScene.getSolverArticulationBatchSize()
*/
PxU32 solverArticulationBatchSize;
/**
\brief Setting to define the number of 16K blocks that will be initially reserved to store contact, friction, and contact cache data.
This is the number of 16K memory blocks that will be automatically allocated from the user allocator when the scene is instantiated. Further 16k
memory blocks may be allocated during the simulation up to maxNbContactDataBlocks.
\note This value cannot be larger than maxNbContactDataBlocks because that defines the maximum number of 16k blocks that can be allocated by the SDK.
<b>Default:</b> 0
<b>Range:</b> [0, PX_MAX_U32]<br>
@see PxPhysics::createScene PxScene::setNbContactDataBlocks
*/
PxU32 nbContactDataBlocks;
/**
\brief Setting to define the maximum number of 16K blocks that can be allocated to store contact, friction, and contact cache data.
As the complexity of a scene increases, the SDK may require to allocate new 16k blocks in addition to the blocks it has already
allocated. This variable controls the maximum number of blocks that the SDK can allocate.
In the case that the scene is sufficiently complex that all the permitted 16K blocks are used, contacts will be dropped and
a warning passed to the error stream.
If a warning is reported to the error stream to indicate the number of 16K blocks is insufficient for the scene complexity
then the choices are either (i) re-tune the number of 16K data blocks until a number is found that is sufficient for the scene complexity,
(ii) to simplify the scene or (iii) to opt to not increase the memory requirements of physx and accept some dropped contacts.
<b>Default:</b> 65536
<b>Range:</b> [0, PX_MAX_U32]<br>
@see nbContactDataBlocks PxScene.setNbContactDataBlocks()
*/
PxU32 maxNbContactDataBlocks;
/**
\brief The maximum bias coefficient used in the constraint solver
When geometric errors are found in the constraint solver, either as a result of shapes penetrating
or joints becoming separated or violating limits, a bias is introduced in the solver position iterations
to correct these errors. This bias is proportional to 1/dt, meaning that the bias becomes increasingly
strong as the time-step passed to PxScene::simulate(...) becomes smaller. This coefficient allows the
application to restrict how large the bias coefficient is, to reduce how violent error corrections are.
This can improve simulation quality in cases where either variable time-steps or extremely small time-steps
are used.
<b>Default:</b> PX_MAX_F32
<b> Range</b> [0, PX_MAX_F32] <br>
@see PxScene.setMaxBiasCoefficient() PxScene.getMaxBiasCoefficient()
*/
PxReal maxBiasCoefficient;
/**
\brief Size of the contact report stream (in bytes).
The contact report stream buffer is used during the simulation to store all the contact reports.
If the size is not sufficient, the buffer will grow by a factor of two.
It is possible to disable the buffer growth by setting the flag PxSceneFlag::eDISABLE_CONTACT_REPORT_BUFFER_RESIZE.
In that case the buffer will not grow but contact reports not stored in the buffer will not get sent in the contact report callbacks.
<b>Default:</b> 8192
<b>Range:</b> (0, PX_MAX_U32]<br>
@see PxScene.getContactReportStreamBufferSize()
*/
PxU32 contactReportStreamBufferSize;
/**
\brief Maximum number of CCD passes
The CCD performs multiple passes, where each pass every object advances to its time of first impact. This value defines how many passes the CCD system should perform.
\note The CCD system is a multi-pass best-effort conservative advancement approach. After the defined number of passes has been completed, any remaining time is dropped.
\note This defines the maximum number of passes the CCD can perform. It may perform fewer if additional passes are not necessary.
<b>Default:</b> 1
<b>Range:</b> [1, PX_MAX_U32]<br>
@see PxScene.setCCDMaxPasses() PxScene.getCCDMaxPasses()
*/
PxU32 ccdMaxPasses;
/**
\brief CCD threshold
CCD performs sweeps against shapes if and only if the relative motion of the shapes is fast-enough that a collision would be missed
by the discrete contact generation. However, in some circumstances, e.g. when the environment is constructed from large convex shapes, this
approach may produce undesired simulation artefacts. This parameter defines the minimum relative motion that would be required to force CCD between shapes.
The smaller of this value and the sum of the thresholds calculated for the shapes involved will be used.
\note It is not advisable to set this to a very small value as this may lead to CCD "jamming" and detrimentally effect performance. This value should be at least larger than the translation caused by a single frame's gravitational effect
<b>Default:</b> PX_MAX_F32
<b>Range:</b> [Eps, PX_MAX_F32]<br>
@see PxScene.setCCDThreshold() PxScene.getCCDThreshold()
*/
PxReal ccdThreshold;
/**
\brief A threshold for speculative CCD. Used to control whether bias, restitution or a combination of the two are used to resolve the contacts.
\note This only has any effect on contacting pairs where one of the bodies has PxRigidBodyFlag::eENABLE_SPECULATIVE_CCD raised.
<b>Range:</b> [0, PX_MAX_F32)<br>
<b>Default:</b> 0.04 * PxTolerancesScale::length
@see PxScene.setCCDMaxSeparation() PxScene.getCCDMaxSeparation()
*/
PxReal ccdMaxSeparation;
/**
\brief The wake counter reset value
Calling wakeUp() on objects which support sleeping will set their wake counter value to the specified reset value.
<b>Range:</b> (0, PX_MAX_F32)<br>
<b>Default:</b> 0.4 (which corresponds to 20 frames for a time step of 0.02)
@see PxRigidDynamic::wakeUp() PxArticulationReducedCoordinate::wakeUp() PxScene.getWakeCounterResetValue()
*/
PxReal wakeCounterResetValue;
/**
\brief The bounds used to sanity check user-set positions of actors and articulation links
These bounds are used to check the position values of rigid actors inserted into the scene, and positions set for rigid actors
already within the scene.
<b>Range:</b> any valid PxBounds3 <br>
<b>Default:</b> (-PX_MAX_BOUNDS_EXTENTS, PX_MAX_BOUNDS_EXTENTS) on each axis
*/
PxBounds3 sanityBounds;
/**
\brief The pre-allocations performed in the GPU dynamics pipeline.
*/
PxgDynamicsMemoryConfig gpuDynamicsConfig;
/**
\brief Limitation for the partitions in the GPU dynamics pipeline.
This variable must be power of 2.
A value greater than 32 is currently not supported.
<b>Range:</b> (1, 32)<br>
*/
PxU32 gpuMaxNumPartitions;
/**
\brief Limitation for the number of static rigid body partitions in the GPU dynamics pipeline.
<b>Range:</b> (1, 255)<br>
<b>Default:</b> 16
*/
PxU32 gpuMaxNumStaticPartitions;
/**
\brief Defines which compute version the GPU dynamics should target. DO NOT MODIFY
*/
PxU32 gpuComputeVersion;
/**
\brief Defines the size of a contact pool slab.
Contact pairs and associated data are allocated using a pool allocator. Increasing the slab size can trade
off some performance spikes when a large number of new contacts are found for an increase in overall memory
usage.
<b>Range:</b>(1, PX_MAX_U32)<br>
<b>Default:</b> 256
*/
PxU32 contactPairSlabSize;
/**
\brief The scene query sub-system for the scene.
If left to NULL, PxScene will use its usual internal sub-system. If non-NULL, all SQ-related calls
will be re-routed to the user-provided implementation. An external SQ implementation is available
in the Extensions library (see PxCreateExternalSceneQuerySystem). This can also be fully re-implemented by users if needed.
@see PxSceneQuerySystem
*/
PxSceneQuerySystem* sceneQuerySystem;
private:
/**
\cond
*/
// For internal use only
PxTolerancesScale tolerancesScale;
/**
\endcond
*/
public:
/**
\brief constructor sets to default.
\param[in] scale scale values for the tolerances in the scene, these must be the same values passed into
PxCreatePhysics(). The affected tolerances are bounceThresholdVelocity and frictionOffsetThreshold.
@see PxCreatePhysics() PxTolerancesScale bounceThresholdVelocity frictionOffsetThreshold
*/
PX_INLINE PxSceneDesc(const PxTolerancesScale& scale);
/**
\brief (re)sets the structure to the default.
\param[in] scale scale values for the tolerances in the scene, these must be the same values passed into
PxCreatePhysics(). The affected tolerances are bounceThresholdVelocity and frictionOffsetThreshold.
@see PxCreatePhysics() PxTolerancesScale bounceThresholdVelocity frictionOffsetThreshold
*/
PX_INLINE void setToDefault(const PxTolerancesScale& scale);
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
PX_INLINE bool isValid() const;
/**
\cond
*/
// For internal use only
PX_INLINE const PxTolerancesScale& getTolerancesScale() const { return tolerancesScale; }
/**
\endcond
*/
};
PX_INLINE PxSceneDesc::PxSceneDesc(const PxTolerancesScale& scale):
gravity (PxVec3(0.0f)),
simulationEventCallback (NULL),
contactModifyCallback (NULL),
ccdContactModifyCallback (NULL),
filterShaderData (NULL),
filterShaderDataSize (0),
filterShader (NULL),
filterCallback (NULL),
kineKineFilteringMode (PxPairFilteringMode::eDEFAULT),
staticKineFilteringMode (PxPairFilteringMode::eDEFAULT),
broadPhaseType (PxBroadPhaseType::ePABP),
broadPhaseCallback (NULL),
frictionType (PxFrictionType::ePATCH),
solverType (PxSolverType::ePGS),
bounceThresholdVelocity (0.2f * scale.speed),
frictionOffsetThreshold (0.04f * scale.length),
frictionCorrelationDistance (0.025f * scale.length),
flags (PxSceneFlag::eENABLE_PCM),
cpuDispatcher (NULL),
cudaContextManager (NULL),
userData (NULL),
solverBatchSize (128),
solverArticulationBatchSize (16),
nbContactDataBlocks (0),
maxNbContactDataBlocks (1<<16),
maxBiasCoefficient (PX_MAX_F32),
contactReportStreamBufferSize (8192),
ccdMaxPasses (1),
ccdThreshold (PX_MAX_F32),
ccdMaxSeparation (0.04f * scale.length),
wakeCounterResetValue (20.0f*0.02f),
sanityBounds (PxBounds3(PxVec3(-PX_MAX_BOUNDS_EXTENTS), PxVec3(PX_MAX_BOUNDS_EXTENTS))),
gpuMaxNumPartitions (8),
gpuMaxNumStaticPartitions (16),
gpuComputeVersion (0),
contactPairSlabSize (256),
sceneQuerySystem (NULL),
tolerancesScale (scale)
{
}
PX_INLINE void PxSceneDesc::setToDefault(const PxTolerancesScale& scale)
{
*this = PxSceneDesc(scale);
}
PX_INLINE bool PxSceneDesc::isValid() const
{
if(!PxSceneQueryDesc::isValid())
return false;
if(!filterShader)
return false;
if( ((filterShaderDataSize == 0) && (filterShaderData != NULL)) ||
((filterShaderDataSize > 0) && (filterShaderData == NULL)) )
return false;
if(!limits.isValid())
return false;
if(bounceThresholdVelocity <= 0.0f)
return false;
if(frictionOffsetThreshold < 0.0f)
return false;
if(frictionCorrelationDistance <= 0)
return false;
if(maxBiasCoefficient < 0.0f)
return false;
if(!ccdMaxPasses)
return false;
if(ccdThreshold <= 0.0f)
return false;
if(ccdMaxSeparation < 0.0f)
return false;
if(!cpuDispatcher)
return false;
if(!contactReportStreamBufferSize)
return false;
if(maxNbContactDataBlocks < nbContactDataBlocks)
return false;
if(wakeCounterResetValue <= 0.0f)
return false;
if(!sanityBounds.isValid())
return false;
#if PX_SUPPORT_GPU_PHYSX
if(!PxIsPowerOfTwo(gpuMaxNumPartitions))
return false;
if(gpuMaxNumPartitions > 32)
return false;
if (gpuMaxNumPartitions == 0)
return false;
if(!gpuDynamicsConfig.isValid())
return false;
if (flags & PxSceneFlag::eENABLE_DIRECT_GPU_API)
{
if(!(flags & PxSceneFlag::eENABLE_GPU_DYNAMICS && broadPhaseType == PxBroadPhaseType::eGPU))
return false;
}
#endif
if(contactPairSlabSize == 0)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 37,439 | C | 34.827751 | 302 | 0.76431 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleSystemFlag.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_SYSTEM_FLAG_H
#define PX_PARTICLE_SYSTEM_FLAG_H
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Identifies dirty particle buffers that need to be updated in the particle system.
This flag can be used mark the device user buffers that are dirty and need to be written to the particle system.
*/
struct PxParticleBufferFlag
{
enum Enum
{
eNONE = 0, //!< No data specified
eUPDATE_POSITION = 1 << 0, //!< Specifies the position (first 3 floats) and inverse mass (last float) data (array of PxVec4 * number of particles)
eUPDATE_VELOCITY = 1 << 1, //!< Specifies the velocity (first 3 floats) data (array of PxVec4 * number of particles)
eUPDATE_PHASE = 1 << 2, //!< Specifies the per-particle phase flag data (array of PxU32 * number of particles)
eUPDATE_RESTPOSITION = 1 << 3, //!< Specifies the rest position (first 3 floats) data for cloth buffers
eUPDATE_CLOTH = 1 << 5, //!< Specifies the cloth buffer (see PxParticleClothBuffer)
eUPDATE_RIGID = 1 << 6, //!< Specifies the rigid buffer (see PxParticleRigidBuffer)
eUPDATE_DIFFUSE_PARAM = 1 << 7, //!< Specifies the diffuse particle parameter buffer (see PxDiffuseParticleParams)
eUPDATE_ATTACHMENTS = 1 << 8, //!< Specifies the attachments.
eALL =
eUPDATE_POSITION | eUPDATE_VELOCITY | eUPDATE_PHASE | eUPDATE_RESTPOSITION | eUPDATE_CLOTH | eUPDATE_RIGID | eUPDATE_DIFFUSE_PARAM | eUPDATE_ATTACHMENTS
};
};
typedef PxFlags<PxParticleBufferFlag::Enum, PxU32> PxParticleBufferFlags;
/**
\brief A pair of particle buffer unique id and GPU particle system index.
@see PxScene::applyParticleBufferData
*/
struct PxGpuParticleBufferIndexPair
{
PxU32 systemIndex; // gpu particle system index
PxU32 bufferIndex; // particle buffer unique id
};
/**
\brief Identifies per-particle behavior for a PxParticleSystem.
See #PxParticleSystem::createPhase().
*/
struct PxParticlePhaseFlag
{
enum Enum
{
eParticlePhaseGroupMask = 0x000fffff, //!< Bits [ 0, 19] represent the particle group for controlling collisions
eParticlePhaseFlagsMask = 0xfff00000, //!< Bits [20, 23] hold flags about how the particle behave
eParticlePhaseSelfCollide = 1 << 20, //!< If set this particle will interact with particles of the same group
eParticlePhaseSelfCollideFilter = 1 << 21, //!< If set this particle will ignore collisions with particles closer than the radius in the rest pose, this flag should not be specified unless valid rest positions have been specified using setRestParticles()
eParticlePhaseFluid = 1 << 22 //!< If set this particle will generate fluid density constraints for its overlapping neighbors
};
};
typedef PxFlags<PxParticlePhaseFlag::Enum, PxU32> PxParticlePhaseFlags;
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 4,530 | C | 43.421568 | 257 | 0.747461 |
NVIDIA-Omniverse/PhysX/physx/include/PxContact.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_CONTACT_H
#define PX_CONTACT_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxAssert.h"
#include "PxConstraintDesc.h"
#include "PxNodeIndex.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#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
#define PXC_CONTACT_NO_FACE_INDEX 0xffffffff
class PxActor;
/**
\brief Header for a contact patch where all points share same material and normal
*/
PX_ALIGN_PREFIX(16)
struct PxContactPatch
{
enum PxContactPatchFlags
{
eHAS_FACE_INDICES = 1, //!< Indicates this contact stream has face indices.
eMODIFIABLE = 2, //!< Indicates this contact stream is modifiable.
eFORCE_NO_RESPONSE = 4, //!< Indicates this contact stream is notify-only (no contact response).
eHAS_MODIFIED_MASS_RATIOS = 8, //!< Indicates this contact stream has modified mass ratios
eHAS_TARGET_VELOCITY = 16, //!< Indicates this contact stream has target velocities set
eHAS_MAX_IMPULSE = 32, //!< Indicates this contact stream has max impulses set
eREGENERATE_PATCHES = 64, //!< Indicates this contact stream needs patches re-generated. This is required if the application modified either the contact normal or the material properties
eCOMPRESSED_MODIFIED_CONTACT = 128
};
/**
\brief Modifiers for scaling the inertia of the involved bodies
*/
PX_ALIGN(16, PxConstraintInvMassScale mMassModification);
/**
\brief Contact normal
*/
PX_ALIGN(16, PxVec3 normal);
/**
\brief Restitution coefficient
*/
PxReal restitution;
/**
\brief Dynamic friction coefficient
*/
PxReal dynamicFriction;
/**
\brief Static friction coefficient
*/
PxReal staticFriction;
/**
\brief Damping coefficient (for compliant contacts)
*/
PxReal damping;
/**
\brief Index of the first contact in the patch
*/
PxU16 startContactIndex;
/**
\brief The number of contacts in this patch
*/
PxU8 nbContacts;
/**
\brief The combined material flag of two actors that come in contact
@see PxMaterialFlag, PxCombineMode
*/
PxU8 materialFlags;
/**
\brief The PxContactPatchFlags for this patch
*/
PxU16 internalFlags;
/**
\brief Material index of first body
*/
PxU16 materialIndex0;
/**
\brief Material index of second body
*/
PxU16 materialIndex1;
PxU16 pad[5];
}
PX_ALIGN_SUFFIX(16);
/**
\brief Contact point data
*/
PX_ALIGN_PREFIX(16)
struct PxContact
{
/**
\brief Contact point in world space
*/
PxVec3 contact;
/**
\brief Separation value (negative implies penetration).
*/
PxReal separation;
}
PX_ALIGN_SUFFIX(16);
/**
\brief Contact point data with additional target and max impulse values
*/
PX_ALIGN_PREFIX(16)
struct PxExtendedContact : public PxContact
{
/**
\brief Target velocity
*/
PX_ALIGN(16, PxVec3 targetVelocity);
/**
\brief Maximum impulse
*/
PxReal maxImpulse;
}
PX_ALIGN_SUFFIX(16);
/**
\brief A modifiable contact point. This has additional fields per-contact to permit modification by user.
\note Not all fields are currently exposed to the user.
*/
PX_ALIGN_PREFIX(16)
struct PxModifiableContact : public PxExtendedContact
{
/**
\brief Contact normal
*/
PX_ALIGN(16, PxVec3 normal);
/**
\brief Restitution coefficient
*/
PxReal restitution;
/**
\brief Material Flags
*/
PxU32 materialFlags;
/**
\brief Shape A's material index
*/
PxU16 materialIndex0;
/**
\brief Shape B's material index
*/
PxU16 materialIndex1;
/**
\brief static friction coefficient
*/
PxReal staticFriction;
/**
\brief dynamic friction coefficient
*/
PxReal dynamicFriction;
}
PX_ALIGN_SUFFIX(16);
/**
\brief A class to iterate over a compressed contact stream. This supports read-only access to the various contact formats.
*/
struct PxContactStreamIterator
{
enum StreamFormat
{
eSIMPLE_STREAM,
eMODIFIABLE_STREAM,
eCOMPRESSED_MODIFIABLE_STREAM
};
/**
\brief Utility zero vector to optimize functions returning zero vectors when a certain flag isn't set.
\note This allows us to return by reference instead of having to return by value. Returning by value will go via memory (registers -> stack -> registers), which can
cause performance issues on certain platforms.
*/
PxVec3 zero;
/**
\brief The patch headers.
*/
const PxContactPatch* patch;
/**
\brief The contacts
*/
const PxContact* contact;
/**
\brief The contact triangle face index
*/
const PxU32* faceIndice;
/**
\brief The total number of patches in this contact stream
*/
PxU32 totalPatches;
/**
\brief The total number of contact points in this stream
*/
PxU32 totalContacts;
/**
\brief The current contact index
*/
PxU32 nextContactIndex;
/**
\brief The current patch Index
*/
PxU32 nextPatchIndex;
/**
\brief Size of contact patch header
\note This varies whether the patch is modifiable or not.
*/
PxU32 contactPatchHeaderSize;
/**
\brief Contact point size
\note This varies whether the patch has feature indices or is modifiable.
*/
PxU32 contactPointSize;
/**
\brief The stream format
*/
StreamFormat mStreamFormat;
/**
\brief Indicates whether this stream is notify-only or not.
*/
PxU32 forceNoResponse;
/**
\brief Internal helper for stepping the contact stream iterator
*/
bool pointStepped;
/**
\brief Specifies if this contactPatch has face indices (handled as bool)
@see faceIndice
*/
PxU32 hasFaceIndices;
/**
\brief Constructor
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxContactStreamIterator(const PxU8* contactPatches, const PxU8* contactPoints, const PxU32* contactFaceIndices, PxU32 nbPatches, PxU32 nbContacts)
: zero(0.f)
{
bool modify = false;
bool compressedModify = false;
bool response = false;
bool indices = false;
PxU32 pointSize = 0;
PxU32 patchHeaderSize = sizeof(PxContactPatch);
const PxContactPatch* patches = reinterpret_cast<const PxContactPatch*>(contactPatches);
if(patches)
{
modify = (patches->internalFlags & PxContactPatch::eMODIFIABLE) != 0;
compressedModify = (patches->internalFlags & PxContactPatch::eCOMPRESSED_MODIFIED_CONTACT) != 0;
indices = (patches->internalFlags & PxContactPatch::eHAS_FACE_INDICES) != 0;
patch = patches;
contact = reinterpret_cast<const PxContact*>(contactPoints);
faceIndice = contactFaceIndices;
pointSize = compressedModify ? sizeof(PxExtendedContact) : modify ? sizeof(PxModifiableContact) : sizeof(PxContact);
response = (patch->internalFlags & PxContactPatch::eFORCE_NO_RESPONSE) == 0;
}
mStreamFormat = compressedModify ? eCOMPRESSED_MODIFIABLE_STREAM : modify ? eMODIFIABLE_STREAM : eSIMPLE_STREAM;
hasFaceIndices = PxU32(indices);
forceNoResponse = PxU32(!response);
contactPatchHeaderSize = patchHeaderSize;
contactPointSize = pointSize;
nextPatchIndex = 0;
nextContactIndex = 0;
totalContacts = nbContacts;
totalPatches = nbPatches;
pointStepped = false;
}
/**
\brief Returns whether there are more patches in this stream.
\return Whether there are more patches in this stream.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNextPatch() const
{
return nextPatchIndex < totalPatches;
}
/**
\brief Returns the total contact count.
\return Total contact count.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getTotalContactCount() const
{
return totalContacts;
}
/**
\brief Returns the total patch count.
\return Total patch count.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getTotalPatchCount() const
{
return totalPatches;
}
/**
\brief Advances iterator to next contact patch.
*/
PX_CUDA_CALLABLE PX_INLINE void nextPatch()
{
PX_ASSERT(nextPatchIndex < totalPatches);
if(nextPatchIndex)
{
if(nextContactIndex < patch->nbContacts)
{
PxU32 nbToStep = patch->nbContacts - this->nextContactIndex;
contact = reinterpret_cast<const PxContact*>(reinterpret_cast<const PxU8*>(contact) + contactPointSize * nbToStep);
}
patch = reinterpret_cast<const PxContactPatch*>(reinterpret_cast<const PxU8*>(patch) + contactPatchHeaderSize);
}
nextPatchIndex++;
nextContactIndex = 0;
}
/**
\brief Returns if the current patch has more contacts.
\return If there are more contacts in the current patch.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE bool hasNextContact() const
{
return nextContactIndex < (patch->nbContacts);
}
/**
\brief Advances to the next contact in the patch.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE void nextContact()
{
PX_ASSERT(nextContactIndex < patch->nbContacts);
if(pointStepped)
{
contact = reinterpret_cast<const PxContact*>(reinterpret_cast<const PxU8*>(contact) + contactPointSize);
faceIndice++;
}
nextContactIndex++;
pointStepped = true;
}
/**
\brief Gets the current contact's normal
\return The current contact's normal.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getContactNormal() const
{
return getContactPatch().normal;
}
/**
\brief Gets the inverse mass scale for body 0.
\return The inverse mass scale for body 0.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvMassScale0() const
{
return patch->mMassModification.linear0;
}
/**
\brief Gets the inverse mass scale for body 1.
\return The inverse mass scale for body 1.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvMassScale1() const
{
return patch->mMassModification.linear1;
}
/**
\brief Gets the inverse inertia scale for body 0.
\return The inverse inertia scale for body 0.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvInertiaScale0() const
{
return patch->mMassModification.angular0;
}
/**
\brief Gets the inverse inertia scale for body 1.
\return The inverse inertia scale for body 1.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getInvInertiaScale1() const
{
return patch->mMassModification.angular1;
}
/**
\brief Gets the contact's max impulse.
\return The contact's max impulse.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getMaxImpulse() const
{
return mStreamFormat != eSIMPLE_STREAM ? getExtendedContact().maxImpulse : PX_MAX_REAL;
}
/**
\brief Gets the contact's target velocity.
\return The contact's target velocity.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getTargetVel() const
{
return mStreamFormat != eSIMPLE_STREAM ? getExtendedContact().targetVelocity : zero;
}
/**
\brief Gets the contact's contact point.
\return The contact's contact point.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxVec3& getContactPoint() const
{
return contact->contact;
}
/**
\brief Gets the contact's separation.
\return The contact's separation.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getSeparation() const
{
return contact->separation;
}
/**
\brief Gets the contact's face index for shape 0.
\return The contact's face index for shape 0.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getFaceIndex0() const
{
return PXC_CONTACT_NO_FACE_INDEX;
}
/**
\brief Gets the contact's face index for shape 1.
\return The contact's face index for shape 1.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getFaceIndex1() const
{
return hasFaceIndices ? *faceIndice : PXC_CONTACT_NO_FACE_INDEX;
}
/**
\brief Gets the contact's static friction coefficient.
\return The contact's static friction coefficient.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getStaticFriction() const
{
return getContactPatch().staticFriction;
}
/**
\brief Gets the contact's dynamic friction coefficient.
\return The contact's dynamic friction coefficient.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getDynamicFriction() const
{
return getContactPatch().dynamicFriction;
}
/**
\brief Gets the contact's restitution coefficient.
\return The contact's restitution coefficient.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getRestitution() const
{
return getContactPatch().restitution;
}
/**
\brief Gets the contact's damping value.
\return The contact's damping value.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxReal getDamping() const
{
return getContactPatch().damping;
}
/**
\brief Gets the contact's material flags.
\return The contact's material flags.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU32 getMaterialFlags() const
{
return getContactPatch().materialFlags;
}
/**
\brief Gets the contact's material index for shape 0.
\return The contact's material index for shape 0.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex0() const
{
return PxU16(getContactPatch().materialIndex0);
}
/**
\brief Gets the contact's material index for shape 1.
\return The contact's material index for shape 1.
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE PxU16 getMaterialIndex1() const
{
return PxU16(getContactPatch().materialIndex1);
}
/**
\brief Advances the contact stream iterator to a specific contact index.
\return True if advancing was possible
*/
bool advanceToIndex(const PxU32 initialIndex)
{
PX_ASSERT(this->nextPatchIndex == 0 && this->nextContactIndex == 0);
PxU32 numToAdvance = initialIndex;
if(numToAdvance == 0)
{
PX_ASSERT(hasNextPatch());
nextPatch();
return true;
}
while(numToAdvance)
{
while(hasNextPatch())
{
nextPatch();
PxU32 patchSize = patch->nbContacts;
if(numToAdvance <= patchSize)
{
contact = reinterpret_cast<const PxContact*>(reinterpret_cast<const PxU8*>(contact) + contactPointSize * numToAdvance);
nextContactIndex += numToAdvance;
return true;
}
else
{
numToAdvance -= patchSize;
}
}
}
return false;
}
private:
/**
\brief Internal helper
*/
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxContactPatch& getContactPatch() const
{
return *static_cast<const PxContactPatch*>(patch);
}
PX_CUDA_CALLABLE PX_FORCE_INLINE const PxExtendedContact& getExtendedContact() const
{
PX_ASSERT(mStreamFormat == eMODIFIABLE_STREAM || mStreamFormat == eCOMPRESSED_MODIFIABLE_STREAM);
return *static_cast<const PxExtendedContact*>(contact);
}
};
/**
\brief Contains contact information for a contact reported by the direct-GPU contact report API. See PxScene::copyContactData().
*/
struct PxGpuContactPair
{
PxU8* contactPatches; //!< Ptr to contact patches. Type: PxContactPatch*, size: nbPatches.
PxU8* contactPoints; //!< Ptr to contact points. Type: PxContact*, size: nbContacts.
PxReal* contactForces; //!< Ptr to contact forces. Size: nbContacts.
PxU32 transformCacheRef0; //!< Ref to shape0's transform in transform cache.
PxU32 transformCacheRef1; //!< Ref to shape1's transform in transform cache.
PxNodeIndex nodeIndex0; //!< Unique Id for actor0 if the actor is dynamic.
PxNodeIndex nodeIndex1; //!< Unique Id for actor1 if the actor is dynamic.
PxActor* actor0; //!< Ptr to PxActor for actor0.
PxActor* actor1; //!< Ptr to PxActor for actor1.
PxU16 nbContacts; //!< Num contacts.
PxU16 nbPatches; //!< Num patches.
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 16,701 | C | 24.153614 | 190 | 0.726483 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationLink.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_LINK_H
#define PX_ARTICULATION_LINK_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "PxRigidBody.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A component of an articulation that represents a rigid body.
Articulation links have a restricted subset of the functionality of a PxRigidDynamic:
- They may not be kinematic, and do not support contact-force thresholds.
- Their velocity or global pose cannot be set directly, but must be set via the articulation-root and joint positions/velocities.
- Sleep state and solver iteration counts are properties of the entire articulation rather than the individual links.
@see PxArticulationReducedCoordinate, PxArticulationReducedCoordinate::createLink, PxArticulationJointReducedCoordinate, PxRigidBody
*/
class PxArticulationLink : public PxRigidBody
{
public:
/**
\brief Releases the link from the articulation.
\note Only a leaf articulation link can be released.
\note Releasing a link is not allowed while the articulation link is in a scene. In order to release a link,
remove and then re-add the corresponding articulation to the scene.
@see PxArticulationReducedCoordinate::createLink()
*/
virtual void release() = 0;
/**
\brief Gets the articulation that the link is a part of.
\return The articulation.
@see PxArticulationReducedCoordinate
*/
virtual PxArticulationReducedCoordinate& getArticulation() const = 0;
/**
\brief Gets the joint which connects this link to its parent.
\return The joint connecting the link to the parent. NULL for the root link.
@see PxArticulationJointReducedCoordinate
*/
virtual PxArticulationJointReducedCoordinate* getInboundJoint() const = 0;
/**
\brief Gets the number of degrees of freedom of the joint which connects this link to its parent.
- The root link DOF-count is defined to be 0 regardless of PxArticulationFlag::eFIX_BASE.
- The return value is only valid for articulations that are in a scene.
\return The number of degrees of freedom, or 0xFFFFFFFF if the articulation is not in a scene.
@see PxArticulationJointReducedCoordinate
*/
virtual PxU32 getInboundJointDof() const = 0;
/**
\brief Gets the number of child links.
\return The number of child links.
@see getChildren
*/
virtual PxU32 getNbChildren() const = 0;
/**
\brief Gets the low-level link index that may be used to index into members of PxArticulationCache.
The return value is only valid for articulations that are in a scene.
\return The low-level index, or 0xFFFFFFFF if the articulation is not in a scene.
@see PxArticulationCache
*/
virtual PxU32 getLinkIndex() const = 0;
/**
\brief Retrieves the child links.
\param[out] userBuffer The buffer to receive articulation link pointers.
\param[in] bufferSize The size of the provided user buffer, use getNbChildren() for sizing.
\param[in] startIndex The index of the first child pointer to be retrieved.
\return The number of articulation links written to the buffer.
@see getNbChildren
*/
virtual PxU32 getChildren(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Set the constraint-force-mixing scale term.
The cfm scale term is a stabilization term that helps avoid instabilities with over-constrained
configurations. It should be a small value that is multiplied by 1/mass internally to produce
an additional bias added to the unit response term in the solver.
\param[in] cfm The constraint-force-mixing scale term.
<b>Default:</b> 0.025
<b>Range:</b> [0, 1]
\note This call is not allowed while the simulation is running.
@see getCfmScale
*/
virtual void setCfmScale(const PxReal cfm) = 0;
/**
\brief Get the constraint-force-mixing scale term.
\return The constraint-force-mixing scale term.
@see setCfmScale
*/
virtual PxReal getCfmScale() const = 0;
/**
\brief Get the linear velocity of the link.
- For performance, prefer PxArticulationCache::linkVelocity to get link spatial velocities in a batch query.
- When the articulation state is updated via non-cache API, use PxArticulationReducedCoordinate::updateKinematic before querying velocity.
\return The linear velocity of the link.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
\note The linear velocity is reported with respect to the link's center of mass and not the actor frame origin.
@see PxRigidBody::getCMassLocalPose
*/
virtual PxVec3 getLinearVelocity() const = 0;
/**
\brief Get the angular velocity of the link.
- For performance, prefer PxArticulationCache::linkVelocity to get link spatial velocities in a batch query.
- When the articulation state is updated via non-cache API, use PxArticulationReducedCoordinate::updateKinematic before querying velocity.
\return The angular velocity of the link.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
*/
virtual PxVec3 getAngularVelocity() const = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationLink"; }
protected:
PX_INLINE PxArticulationLink(PxType concreteType, PxBaseFlags baseFlags) : PxRigidBody(concreteType, baseFlags) {}
PX_INLINE PxArticulationLink(PxBaseFlags baseFlags) : PxRigidBody(baseFlags) {}
virtual ~PxArticulationLink() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxArticulationLink", PxRigidBody); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 7,641 | C | 35.917874 | 150 | 0.758539 |
NVIDIA-Omniverse/PhysX/physx/include/PxAttachment.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_ATTACHMENT_H
#define PX_ATTACHMENT_H
#include "PxConeLimitedConstraint.h"
#include "PxFiltering.h"
#include "PxNodeIndex.h"
#include "foundation/PxVec4.h"
/** \addtogroup physics
@{
*/
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Struct to specify attachment between a particle/vertex and a rigid
*/
struct PxParticleRigidAttachment : public PxParticleRigidFilterPair
{
PxParticleRigidAttachment() {}
PxParticleRigidAttachment(const PxConeLimitedConstraint& coneLimitedConstraint, const PxVec4& localPose0):
PxParticleRigidFilterPair(PxNodeIndex().getInd(), PxNodeIndex().getInd()),
mLocalPose0(localPose0),
mConeLimitParams(coneLimitedConstraint)
{
}
PX_ALIGN(16, PxVec4 mLocalPose0); //!< local pose in body frame - except for statics, these are using world positions.
PxConeLimitParams mConeLimitParams; //!< Parameters to specify cone constraints
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,651 | C | 36.885714 | 119 | 0.765749 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleSystem.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_SYSTEM_H
#define PX_PARTICLE_SYSTEM_H
/** \addtogroup physics
@{ */
#include "foundation/PxSimpleTypes.h"
#include "PxActor.h"
#include "PxFiltering.h"
#include "PxParticleSystemFlag.h"
#include "foundation/PxArray.h"
#include "cudamanager/PxCudaTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
class PxCudaContextManager;
class PxGpuParticleSystem;
class PxParticleAndDiffuseBuffer;
class PxParticleBuffer;
class PxParticleMaterial;
/**
\brief Container to hold a pair of corresponding device and host pointers. These pointers should point to GPU / CPU mirrors of the same data, but
this is not enforced.
*/
template <typename Type>
struct PxGpuMirroredPointer
{
Type* mDevicePtr;
Type* mHostPtr;
PxGpuMirroredPointer(Type* devicePtr, Type* hostPtr) : mDevicePtr(devicePtr), mHostPtr(hostPtr) { }
};
/**
\brief Particle system callback base class to schedule work that should be done before, while or after the particle system updates.
A call to fetchResultsParticleSystem() on the PxScene will synchronize the work such that the caller knows that all tasks of this callback completed.
*/
class PxParticleSystemCallback
{
public:
/**
\brief Method gets called when dirty data from the particle system is uploated to the gpu
\param[in] gpuParticleSystem Pointers to the particle systems gpu data available as host accessible pointer and as gpu accessible pointer
\param[in] stream The stream on which all cuda kernel calls get scheduled for execution. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the task completed.
*/
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) = 0;
/**
\brief Method gets called when the simulation step of the particle system is performed
\param[in] gpuParticleSystem Pointers to the particle systems gpu data available as host accessible pointer and as gpu accessible pointer
\param[in] stream The stream on which all cuda kernel calls get scheduled for execution. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the task completed.
*/
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) = 0;
/**
\brief Method gets called after the particle system simulation step completed
\param[in] gpuParticleSystem Pointers to the particle systems gpu data available as host accessible pointer and as gpu accessible pointer
\param[in] stream The stream on which all cuda kernel calls get scheduled for execution. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the task completed.
*/
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) = 0;
/**
\brief Destructor
*/
virtual ~PxParticleSystemCallback() {}
};
/**
\brief Special callback that forwards calls to arbitrarily many sub-callbacks
*/
class PxMultiCallback : public PxParticleSystemCallback
{
private:
PxArray<PxParticleSystemCallback*> mCallbacks;
public:
PxMultiCallback() : mCallbacks(0) {}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) PX_OVERRIDE
{
for (PxU32 i = 0; i < mCallbacks.size(); ++i)
mCallbacks[i]->onPostSolve(gpuParticleSystem, stream);
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) PX_OVERRIDE
{
for (PxU32 i = 0; i < mCallbacks.size(); ++i)
mCallbacks[i]->onBegin(gpuParticleSystem, stream);
}
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream) PX_OVERRIDE
{
for (PxU32 i = 0; i < mCallbacks.size(); ++i)
mCallbacks[i]->onAdvance(gpuParticleSystem, stream);
}
/**
\brief Adds a callback
\param[in] callback The callback to add
\return True if the callback was added
*/
bool addCallback(PxParticleSystemCallback* callback)
{
if (mCallbacks.find(callback) != mCallbacks.end())
return false;
mCallbacks.pushBack(callback);
return true;
}
/**
\brief Removes a callback
\param[in] callback The callback to remove
\return True if the callback was removed
*/
bool removeCallback(const PxParticleSystemCallback* callback)
{
for (PxU32 i = 0; i < mCallbacks.size(); ++i)
{
if (mCallbacks[i] == callback)
{
mCallbacks.remove(i);
return true;
}
}
return false;
}
};
/**
\brief Flags which control the behaviour of a particle system.
See #PxParticleSystem::setParticleFlag(), #PxParticleSystem::setParticleFlags(), #PxParticleSystem::getParticleFlags()
*/
struct PxParticleFlag
{
enum Enum
{
eDISABLE_SELF_COLLISION = 1 << 0, //!< Disables particle self-collision
eDISABLE_RIGID_COLLISION = 1 << 1, //!< Disables particle-rigid body collision
eFULL_DIFFUSE_ADVECTION = 1 << 2 //!< Enables full advection of diffuse particles. By default, diffuse particles are advected only by particles in the cell they are contained. This flag enables full neighbourhood generation (more expensive).
};
};
typedef PxFlags<PxParticleFlag::Enum, PxU32> PxParticleFlags;
/**
\brief The shared base class for all particle systems
A particle system simulates a bunch of particles that interact with each other. The interactions can be simple collisions
with friction (granular material) ore more complex like fluid interactions, cloth, inflatables etc.
*/
class PxParticleSystem : public PxActor
{
public:
/**
\brief Sets the solver iteration counts for the body.
The solver iteration count determines how accurately joints and contacts are resolved.
If you are having trouble with jointed bodies oscillating and behaving erratically, then
setting a higher position iteration count may improve their stability.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations. More velocity iterations will drive the relative exit velocity of the intersecting
objects closer to the correct value given the restitution.
<b>Default:</b> 4 position iterations, 1 velocity iteration
\param[in] minPositionIters Number of position iterations the solver should perform for this body. <b>Range:</b> [1,255]
\param[in] minVelocityIters Number of velocity iterations the solver should perform for this body. <b>Range:</b> [1,255]
See #getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Retrieves the solver iteration counts.
See #setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Retrieves the collision filter settings.
\return The filter data
*/
virtual PxFilterData getSimulationFilterData() const = 0;
/**
\brief Set collision filter settings
Allows to control with which objects the particle system collides
\param[in] data The filter data
*/
virtual void setSimulationFilterData(const PxFilterData& data) = 0;
/**
\brief Set particle flag
Allows to control self collision etc.
\param[in] flag The flag to set
\param[in] val The new value of the flag
*/
virtual void setParticleFlag(PxParticleFlag::Enum flag, bool val) = 0;
/**
\brief Set particle flags
Allows to control self collision etc.
\param[in] flags The flags to set
*/
virtual void setParticleFlags(PxParticleFlags flags) = 0;
/**
\brief Retrieves the particle flags.
\return The particle flags
*/
virtual PxParticleFlags getParticleFlags() const = 0;
/**
\brief Set the maximal depenetration velocity particles can reach
Allows to limit the particles' maximal depenetration velocity to avoid that collision responses lead to very high particle velocities
\param[in] maxDepenetrationVelocity The maximal depenetration velocity
*/
virtual void setMaxDepenetrationVelocity(PxReal maxDepenetrationVelocity) = 0;
/**
\brief Retrieves maximal depenetration velocity a particle can have.
\return The maximal depenetration velocity
*/
virtual PxReal getMaxDepenetrationVelocity() = 0;
/**
\brief Set the maximal velocity particles can reach
Allows to limit the particles' maximal velocity to control the maximal distance a particle can move per frame
\param[in] maxVelocity The maximal velocity
*/
virtual void setMaxVelocity(PxReal maxVelocity) = 0;
/**
\brief Retrieves maximal velocity a particle can have.
\return The maximal velocity
*/
virtual PxReal getMaxVelocity() = 0;
/**
\brief Return the cuda context manager
\return The cuda context manager
*/
virtual PxCudaContextManager* getCudaContextManager() const = 0;
/**
\brief Set the rest offset for the collision between particles and rigids or soft bodies.
A particle and a rigid or soft body will come to rest at a distance equal to the sum of their restOffset values.
\param[in] restOffset <b>Range:</b> (0, contactOffset)
*/
virtual void setRestOffset(PxReal restOffset) = 0;
/**
\brief Return the rest offset
\return the rest offset
See #setRestOffset()
*/
virtual PxReal getRestOffset() const = 0;
/**
\brief Set the contact offset for the collision between particles and rigids or soft bodies
The contact offset needs to be larger than the rest offset.
Contact constraints are generated for a particle and a rigid or softbody below the distance equal to the sum of their contacOffset values.
\param[in] contactOffset <b>Range:</b> (restOffset, PX_MAX_F32)
*/
virtual void setContactOffset(PxReal contactOffset) = 0;
/**
\brief Return the contact offset
\return the contact offset
See #setContactOffset()
*/
virtual PxReal getContactOffset() const = 0;
/**
\brief Set the contact offset for the interactions between particles
The particle contact offset needs to be larger than the fluid rest offset and larger than the solid rest offset.
Interactions for two particles are computed if their distance is below twice the particleContactOffset value.
\param[in] particleContactOffset <b>Range:</b> (Max(solidRestOffset, fluidRestOffset), PX_MAX_F32)
*/
virtual void setParticleContactOffset(PxReal particleContactOffset) = 0;
/**
\brief Return the particle contact offset
\return the particle contact offset
See #setParticleContactOffset()
*/
virtual PxReal getParticleContactOffset() const = 0;
/**
\brief Set the solid rest offset
Two solid particles (or a solid and a fluid particle) will come to rest at a distance equal to twice the solidRestOffset value.
\param[in] solidRestOffset <b>Range:</b> (0, particleContactOffset)
*/
virtual void setSolidRestOffset(PxReal solidRestOffset) = 0;
/**
\brief Return the solid rest offset
\return the solid rest offset
See #setSolidRestOffset()
*/
virtual PxReal getSolidRestOffset() const = 0;
/**
\brief Creates a rigid attachment between a particle and a rigid actor.
This method creates a symbolic attachment between the particle system and a rigid body for the purpose of island management.
The actual attachments will be contained in the particle buffers.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The particle system keeps track of these attachments but the rigid body does not.
\param[in] actor The rigid actor used for the attachment
*/
virtual void addRigidAttachment(PxRigidActor* actor) = 0;
/**
\brief Removes a rigid attachment between a particle and a rigid body.
This method destroys a symbolic attachment between the particle system and a rigid body for the purpose of island management.
Be aware that destroying the rigid body before destroying the attachment is illegal and may cause a crash.
The particle system keeps track of these attachments but the rigid body does not.
\param[in] actor The rigid body actor used for the attachment
*/
virtual void removeRigidAttachment(PxRigidActor* actor) = 0;
/**
\brief Enable continuous collision detection for particles
\param[in] enable Boolean indicates whether continuous collision detection is enabled.
*/
virtual void enableCCD(bool enable) = 0;
/**
\brief Creates combined particle flag with particle material and particle phase flags.
\param[in] material A material instance to associate with the new particle group.
\param[in] flags The particle phase flags.
\return The combined particle group index and phase flags.
See #PxParticlePhaseFlag
*/
virtual PxU32 createPhase(PxParticleMaterial* material, PxParticlePhaseFlags flags) = 0;
/**
\brief Returns number of particle materials referenced by particle phases
\return The number of particle materials
*/
virtual PxU32 getNbParticleMaterials() const = 0;
/**
\brief Returns particle materials referenced by particle phases
\return The particle materials
*/
virtual PxU32 getParticleMaterials(PxParticleMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Sets a user notify object which receives special simulation events when they occur.
\note Do not set the callback while the simulation is running. Calls to this method while the simulation is running will be ignored.
\note A call to fetchResultsParticleSystem() on the PxScene will synchronize the work such that the caller knows that all worke done in the callback completed.
\param[in] callback User notification callback. See PxSimulationEventCallback.
See #PxParticleSystemCallback, #getParticleSystemCallback()
*/
virtual void setParticleSystemCallback(PxParticleSystemCallback* callback) = 0;
/**
\brief Retrieves the simulationEventCallback pointer set with setSimulationEventCallback().
\return The current user notify pointer. See PxSimulationEventCallback.
See #PxParticleSystemCallback, #setParticleSystemCallback()
*/
virtual PxParticleSystemCallback* getParticleSystemCallback() const = 0;
/**
\brief Add an existing particle buffer to the particle system.
\param[in] particleBuffer a PxParticleBuffer*.
See #PxParticleBuffer.
*/
virtual void addParticleBuffer(PxParticleBuffer* particleBuffer) = 0;
/**
\brief Remove particle buffer from the particle system.
\param[in] particleBuffer a PxParticleBuffer*.
See #PxParticleBuffer.
*/
virtual void removeParticleBuffer(PxParticleBuffer* particleBuffer) = 0;
/**
\brief Returns the GPU particle system index.
\return The GPU index, if the particle system is in a scene and PxSceneFlag::eENABLE_DIRECT_GPU_API is set, or 0xFFFFFFFF otherwise.
*/
virtual PxU32 getGpuParticleSystemIndex() = 0;
protected:
virtual ~PxParticleSystem() {}
PX_INLINE PxParticleSystem(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {}
PX_INLINE PxParticleSystem(PxBaseFlags baseFlags) : PxActor(baseFlags) {}
virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxParticleSystem", PxActor); }
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 17,510 | C | 33.675247 | 243 | 0.742833 |
NVIDIA-Omniverse/PhysX/physx/include/PxLineStripSkinning.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_LINE_STRIP_SKINNING_H
#define PX_LINE_STRIP_SKINNING_H
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "foundation/PxMat44.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
class PxHairSystemDesc;
/**
\brief Specifies the position and binding of a point relative to a line strip such that the point moves with the line during simulation.
*/
struct PxLineStripSkinnedVertex
{
PxVec3 mPosition; //!< The position of the vertex that should move with a line strip. Expressed in the same coordinate system as the line strip points when computing the skinning.
PxU32 mSegmentId; //!< The id of the vertex at the beginning of the line segment to which this point is connected
PxReal mSegmentLocation; //!< Parameter in the range 0...1 that specifies the location on the segment where the base coordinate system gets evaluated at runtime to update the skinned position.
PxLineStripSkinnedVertex() : mPosition(0.0f), mSegmentId(0), mSegmentLocation(0.0f)
{
}
PxLineStripSkinnedVertex(const PxVec3& position, PxU32 segmentId, PxReal segmentLocation) : mPosition(position), mSegmentId(segmentId), mSegmentLocation(segmentLocation)
{
}
};
/**
\brief Utility class to embed high resolution line strips into low resolution line strips.
No internal data is cached except a reference to the cuda context manager. Therefore,
a single instance of this class may be used for different hair systems.
*/
class PxLineStripSkinning
{
public:
/**
\brief Computes the skinning information used to update the skinned points during simulation
\note All computations in this function are happening on the CPU, therefore, all supplied pointers must point to CPU-accessible memory.
\param[in] simVertices The simulated vertices in the state in which the skinning information shall be computed. These vertices will eventually drive the skinned vertices
\param[in] simStrandPastEndIndices The index after the last strand vertex for the simulation strands (strand = line strip)
\param[in] nbLineStrips The number of line strips
\param[in] skinnedVertices The positions and segment locations of the skinned vertices in the initial frame. They will keep their position relative to the line strip segment during simulation.
\param[in] nbSkinnedVertices The total number of skinned vertices
\param[out] skinnedVertexInterpolationData Must provide space for one entry per skinned vertex. Contains the location of the skinned vertex relative to the interpolated base frame. The w component encodes the location of the base frame along the line segment.
\param[out] skinningInfoRootStrandDirections Must provide space for one entry per line strip. Contains the direction of the first line segment per line strip during the calculation of the skinning information.
\param[out] skinningInfoStrandStartIndices Must provide space for one entry per line strip. Contains the index of the first skinning vertex in the buffer for every line strip. The skinned vertices must be sorted such that vertices attached to the same line strip are adjacent to each other in the buffer.
\param[out] skinningInfoReorderMap Can be NULL if the skinning vertices are already sorted per strand segment id. Must provide space for one entry per skinned vertex. Contains a reorder map since the skinning algorithm needs to process the skinned vertices in a specific order.
\param[in] transform Optional transform that gets applied to the simVertices before computing the skinning information
\param[in] catmullRomAlpha Optional parameter in the range 0...1 that allows to control the curve interpolation.
*/
virtual void initializeInterpolatedVertices(const PxVec4* simVertices, const PxU32* simStrandPastEndIndices, PxU32 nbLineStrips, const PxLineStripSkinnedVertex* skinnedVertices, PxU32 nbSkinnedVertices,
PxVec4* skinnedVertexInterpolationData, PxVec3* skinningInfoRootStrandDirections, PxU32* skinningInfoStrandStartIndices, PxU32* skinningInfoReorderMap = NULL,
const PxMat44& transform = PxMat44(PxIdentity), PxReal catmullRomAlpha = 0.5f) = 0;
/**
\brief Evaluates and updates the skinned positions based on the interpolation data on the GPU. All input and output arrays must be accessible on the GPU.
\param[in] simVerticesD The simulation vertices (device pointer) according to which the skinned positions shall be computed.
\param[in] simStrandPastEndIndicesD Device pointer containing the index after the last strand vertex for the simulation strands (strand = line strip)
\param[in] nbSimStrands The number of line strips
\param[in] skinnedVertexInterpolationDataD Device pointer containing the location of the skinned vertex relative to the interpolated base frame. The w component encodes the location of the base frame along the line segment.
\param[in] skinningInfoStrandStartIndicesD Device pointer containing the index of the first skinning vertex in the buffer for every line strip. The skinned vertices must be sorted such that vertices attached to the same line strip are adjacent to each other in the buffer.
\param[in] skinningInfoRootStrandDirectionsD Device pointer containing the direction of the first line segment per line strip during the calculation of the skinning information.
\param[in] skinningInfoReorderMapD Can be NULL if the skinning vertices are already sorted per strand segment id. Device pointer containing the reorder map for the skinned vertices.
\param[in] nbSkinnedVertices The total number of skinned vertices
\param[out] resultD The skinned vertex positions where the updated positions will be written
\param[in] stream The cuda stream on which ther kernel call gets scheduled
\param[in] inputTransformD Optional device buffer holding a transform that gets applied to the simVertices before computing the skinning information
\param[in] outputTransformD Optional device buffer holding a transform that gets applied to result vertices
\param[in] catmullRomAlpha Optional parameter in the range 0...1 that allows to control the curve interpolation.
*/
virtual void evaluateInterpolatedVertices(const PxVec4* simVerticesD, const PxU32* simStrandPastEndIndicesD, PxU32 nbSimStrands, const PxVec4* skinnedVertexInterpolationDataD,
const PxU32* skinningInfoStrandStartIndicesD, const PxVec3* skinningInfoRootStrandDirectionsD, const PxU32* skinningInfoReorderMapD, PxU32 nbSkinnedVertices, PxVec3* resultD, CUstream stream,
const PxMat44* inputTransformD = NULL, const PxMat44* outputTransformD = NULL, PxReal catmullRomAlpha = 0.5f) = 0;
/**
\brief Destructor
*/
virtual ~PxLineStripSkinning() {}
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 8,527 | C | 65.108527 | 306 | 0.794887 |
NVIDIA-Omniverse/PhysX/physx/include/PxSoftBodyFlag.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SOFT_BODY_FLAG_H
#define PX_SOFT_BODY_FLAG_H
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Identifies the buffers of a PxSoftBody.
@see PxSoftBody::markDirty()
*/
struct PxSoftBodyDataFlag
{
enum Enum
{
eNONE = 0,
ePOSITION_INVMASS = 1 << 0, //!< The collision mesh's positions
eSIM_POSITION_INVMASS = 1 << 1, //!< The simulation mesh's positions and inverse masses
eSIM_VELOCITY = 1 << 2, //!< The simulation mesh's velocities
eREST_POSITION_INVMASS = 1 << 3, //!< The collision mesh's rest positions
eALL = ePOSITION_INVMASS | eSIM_POSITION_INVMASS | eSIM_VELOCITY | eREST_POSITION_INVMASS
};
};
typedef PxFlags<PxSoftBodyDataFlag::Enum, PxU32> PxSoftBodyDataFlags;
/**
\brief These flags determine what data is read or written when using PxScene::copySoftBodyData()
or PxScene::applySoftBodyData.
@see PxScene::copySoftBodyData, PxScene::applySoftBodyData
*/
class PxSoftBodyGpuDataFlag
{
public:
enum Enum
{
eTET_INDICES = 0, //!< The collision mesh tetrahedron indices (quadruples of int32)
eTET_REST_POSES = 1, //!< The collision mesh tetrahedron rest poses (float 3x3 matrices)
eTET_ROTATIONS = 2, //!< The collision mesh tetrahedron orientations (quaternions, quadruples of float)
eTET_POSITION_INV_MASS = 3, //!< The collision mesh vertex positions and their inverted mass in the 4th component (quadruples of float)
eSIM_TET_INDICES = 4, //!< The simulation mesh tetrahedron indices (quadruples of int32)
eSIM_TET_ROTATIONS = 5, //!< The simulation mesh tetrahedron orientations (quaternions, quadruples of float)
eSIM_VELOCITY_INV_MASS = 6, //!< The simulation mesh vertex velocities and their inverted mass in the 4th component (quadruples of float)
eSIM_POSITION_INV_MASS = 7 //!< The simulation mesh vertex positions and their inverted mass in the 4th component (quadruples of float)
};
};
#if !PX_DOXYGEN
}
#endif
#endif
| 3,704 | C | 40.629213 | 139 | 0.741361 |
NVIDIA-Omniverse/PhysX/physx/include/PxDeletionListener.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_DELETION_LISTENER_H
#define PX_DELETION_LISTENER_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Flags specifying deletion event types.
@see PxDeletionListener::onRelease PxPhysics.registerDeletionListener()
*/
struct PxDeletionEventFlag
{
enum Enum
{
eUSER_RELEASE = (1<<0), //!< The user has called release on an object.
eMEMORY_RELEASE = (1<<1) //!< The destructor of an object has been called and the memory has been released.
};
};
/**
\brief Collection of set bits defined in PxDeletionEventFlag.
@see PxDeletionEventFlag
*/
typedef PxFlags<PxDeletionEventFlag::Enum,PxU8> PxDeletionEventFlags;
PX_FLAGS_OPERATORS(PxDeletionEventFlag::Enum,PxU8)
/**
\brief interface to get notification on object deletion
*/
class PxDeletionListener
{
public:
/**
\brief Notification if an object or its memory gets released
If release() gets called on a PxBase object, an eUSER_RELEASE event will get fired immediately. The object state can be queried in the callback but
it is not allowed to change the state. Furthermore, when reading from the object it is the user's responsibility to make sure that no other thread
is writing at the same time to the object (this includes the simulation itself, i.e., #PxScene::fetchResults() must not get called at the same time).
Calling release() on a PxBase object does not necessarily trigger its destructor immediately. For example, the object can be shared and might still
be referenced by other objects or the simulation might still be running and accessing the object state. In such cases the destructor will be called
as soon as it is safe to do so. After the destruction of the object and its memory, an eMEMORY_RELEASE event will get fired. In this case it is not
allowed to dereference the object pointer in the callback.
\param[in] observed The object for which the deletion event gets fired.
\param[in] userData The user data pointer of the object for which the deletion event gets fired. Not available for all object types in which case it will be set to 0.
\param[in] deletionEvent The type of deletion event. Do not dereference the object pointer argument if the event is eMEMORY_RELEASE.
*/
virtual void onRelease(const PxBase* observed, void* userData, PxDeletionEventFlag::Enum deletionEvent) = 0;
protected:
PxDeletionListener() {}
virtual ~PxDeletionListener() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,229 | C | 39.285714 | 167 | 0.763774 |
NVIDIA-Omniverse/PhysX/physx/include/PxConstraint.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_CONSTRAINT_H
#define PX_CONSTRAINT_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxConstraintDesc.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxRigidActor;
class PxScene;
class PxConstraintConnector;
/**
\brief constraint flags
\note eBROKEN is a read only flag
*/
struct PxConstraintFlag
{
enum Enum
{
eBROKEN = 1<<0, //!< whether the constraint is broken
eCOLLISION_ENABLED = 1<<3, //!< whether contacts should be generated between the objects this constraint constrains
eVISUALIZATION = 1<<4, //!< whether this constraint should be visualized, if constraint visualization is turned on
eDRIVE_LIMITS_ARE_FORCES = 1<<5, //!< limits for drive strength are forces rather than impulses
eIMPROVED_SLERP = 1<<7, //!< perform preprocessing for improved accuracy on D6 Slerp Drive (this flag will be removed in a future release when preprocessing is no longer required)
eDISABLE_PREPROCESSING = 1<<8, //!< suppress constraint preprocessing, intended for use with rowResponseThreshold. May result in worse solver accuracy for ill-conditioned constraints.
eENABLE_EXTENDED_LIMITS = 1<<9, //!< enables extended limit ranges for angular limits (e.g., limit values > PxPi or < -PxPi)
eGPU_COMPATIBLE = 1<<10, //!< the constraint type is supported by gpu dynamics
eALWAYS_UPDATE = 1<<11, //!< updates the constraint each frame
eDISABLE_CONSTRAINT = 1<<12 //!< disables the constraint. SolverPrep functions won't be called for this constraint.
};
};
/**
\brief constraint flags
@see PxConstraintFlag
*/
typedef PxFlags<PxConstraintFlag::Enum, PxU16> PxConstraintFlags;
PX_FLAGS_OPERATORS(PxConstraintFlag::Enum, PxU16)
/**
\brief a table of function pointers for a constraint
@see PxConstraint
*/
struct PxConstraintShaderTable
{
PxConstraintSolverPrep solverPrep; //!< solver constraint generation function
PxConstraintVisualize visualize; //!< constraint visualization function
PxConstraintFlag::Enum flag; //!< constraint flags
};
/**
\brief A plugin class for implementing constraints
@see PxPhysics.createConstraint
*/
class PxConstraint : public PxBase
{
public:
/**
\brief Releases a PxConstraint instance.
\note This call does not wake up the connected rigid bodies.
@see PxPhysics.createConstraint, PxBase.release()
*/
virtual void release() = 0;
/**
\brief Retrieves the scene which this constraint belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() const = 0;
/**
\brief Retrieves the actors for this constraint.
\param[out] actor0 a reference to the pointer for the first actor
\param[out] actor1 a reference to the pointer for the second actor
@see PxActor
*/
virtual void getActors(PxRigidActor*& actor0, PxRigidActor*& actor1) const = 0;
/**
\brief Sets the actors for this constraint.
\param[in] actor0 a reference to the pointer for the first actor
\param[in] actor1 a reference to the pointer for the second actor
@see PxActor
*/
virtual void setActors(PxRigidActor* actor0, PxRigidActor* actor1) = 0;
/**
\brief Notify the scene that the constraint shader data has been updated by the application
*/
virtual void markDirty() = 0;
/**
\brief Retrieve the flags for this constraint
\return the constraint flags
@see PxConstraintFlags
*/
virtual PxConstraintFlags getFlags() const = 0;
/**
\brief Set the flags for this constraint
\param[in] flags the new constraint flags
default: PxConstraintFlag::eDRIVE_LIMITS_ARE_FORCES
@see PxConstraintFlags
*/
virtual void setFlags(PxConstraintFlags flags) = 0;
/**
\brief Set a flag for this constraint
\param[in] flag the constraint flag
\param[in] value the new value of the flag
@see PxConstraintFlags
*/
virtual void setFlag(PxConstraintFlag::Enum flag, bool value) = 0;
/**
\brief Retrieve the constraint force most recently applied to maintain this constraint.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\param[out] linear the constraint force
\param[out] angular the constraint torque
*/
virtual void getForce(PxVec3& linear, PxVec3& angular) const = 0;
/**
\brief whether the constraint is valid.
A constraint is valid if it has at least one dynamic rigid body or articulation link. A constraint that
is not valid may not be inserted into a scene, and therefore a static actor to which an invalid constraint
is attached may not be inserted into a scene.
Invalid constraints arise only when an actor to which the constraint is attached has been deleted.
*/
virtual bool isValid() const = 0;
/**
\brief Set the break force and torque thresholds for this constraint.
If either the force or torque measured at the constraint exceed these thresholds the constraint will break.
\param[in] linear the linear break threshold
\param[in] angular the angular break threshold
*/
virtual void setBreakForce(PxReal linear, PxReal angular) = 0;
/**
\brief Retrieve the constraint break force and torque thresholds
\param[out] linear the linear break threshold
\param[out] angular the angular break threshold
*/
virtual void getBreakForce(PxReal& linear, PxReal& angular) const = 0;
/**
\brief Set the minimum response threshold for a constraint row
When using mass modification for a joint or infinite inertia for a jointed body, very stiff solver constraints can be generated which
can destabilize simulation. Setting this value to a small positive value (e.g. 1e-8) will cause constraint rows to be ignored if very
large changes in impulses will generate only small changes in velocity. When setting this value, also set
PxConstraintFlag::eDISABLE_PREPROCESSING. The solver accuracy for this joint may be reduced.
\param[in] threshold the minimum response threshold
@see PxConstraintFlag::eDISABLE_PREPROCESSING
*/
virtual void setMinResponseThreshold(PxReal threshold) = 0;
/**
\brief Retrieve the constraint break force and torque thresholds
\return the minimum response threshold for a constraint row
*/
virtual PxReal getMinResponseThreshold() const = 0;
/**
\brief Fetch external owner of the constraint.
Provides a reference to the external owner of a constraint and a unique owner type ID.
\param[out] typeID Unique type identifier of the external object.
\return Reference to the external object which owns the constraint.
@see PxConstraintConnector.getExternalReference()
*/
virtual void* getExternalReference(PxU32& typeID) = 0;
/**
\brief Set the constraint functions for this constraint
\param[in] connector the constraint connector object by which the SDK communicates with the constraint.
\param[in] shaders the shader table for the constraint
@see PxConstraintConnector PxConstraintSolverPrep PxConstraintVisualize
*/
virtual void setConstraintFunctions(PxConstraintConnector& connector, const PxConstraintShaderTable& shaders) = 0;
virtual const char* getConcreteTypeName() const PX_OVERRIDE { return "PxConstraint"; }
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxConstraint(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags), userData(NULL) {}
PX_INLINE PxConstraint(PxBaseFlags baseFlags) : PxBase(baseFlags), userData(NULL) {}
virtual ~PxConstraint() {}
virtual bool isKindOf(const char* name) const PX_OVERRIDE { PX_IS_KIND_OF(name, "PxConstraint", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,559 | C | 34.276753 | 187 | 0.74558 |
NVIDIA-Omniverse/PhysX/physx/include/PxFEMSoftBodyMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FEM_SOFT_BODY_MATERIAL_H
#define PX_FEM_SOFT_BODY_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxFEMMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
struct PxFEMSoftBodyMaterialModel
{
enum Enum
{
eCO_ROTATIONAL, //!< Default model. Well suited for high stiffness. Does need tetrahedra with good shapes (no extreme slivers) in the rest pose.
eNEO_HOOKEAN //!< Well suited for lower stiffness. Robust to any tetrahedron shape.
};
};
class PxScene;
/**
\brief Material class to represent a set of softbody FEM material properties.
@see PxPhysics.createFEMSoftBodyMaterial
*/
class PxFEMSoftBodyMaterial : public PxFEMMaterial
{
public:
/**
\brief Sets material velocity damping term
\param[in] damping Material velocity damping term. <b>Range:</b> [0, PX_MAX_F32)<br>
@see getDamping
*/
virtual void setDamping(PxReal damping) = 0;
/**
\brief Retrieves velocity damping
\return The velocity damping.
@see setDamping()
*/
virtual PxReal getDamping() const = 0;
/**
\brief Sets material damping scale. A scale of 1 corresponds to default damping, a value of 0 will only apply damping to certain motions leading to special effects that look similar to water filled softbodies.
\param[in] scale Damping scale term. <b>Default:</b> 1 <b>Range:</b> [0, 1]
@see getDampingScale
*/
virtual void setDampingScale(PxReal scale) = 0;
/**
\brief Retrieves material damping scale.
\return The damping scale term.
@see setDamping()
*/
virtual PxReal getDampingScale() const = 0;
/**
\brief Sets the material model.
\param[in] model The material model
@see getMaterialModel
*/
virtual void setMaterialModel(PxFEMSoftBodyMaterialModel::Enum model) = 0;
/**
\brief Retrieves the material model.
\return The material model.
@see setMaterialModel()
*/
virtual PxFEMSoftBodyMaterialModel::Enum getMaterialModel() const = 0;
virtual const char* getConcreteTypeName() const { return "PxFEMSoftBodyMaterial"; }
protected:
PX_INLINE PxFEMSoftBodyMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxFEMMaterial(concreteType, baseFlags) {}
PX_INLINE PxFEMSoftBodyMaterial(PxBaseFlags baseFlags) : PxFEMMaterial(baseFlags) {}
virtual ~PxFEMSoftBodyMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxFEMSoftBodyMaterial", PxFEMMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,189 | C | 31.992126 | 211 | 0.736453 |
NVIDIA-Omniverse/PhysX/physx/include/PxPhysics.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_H
#define PX_PHYSICS_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "PxDeletionListener.h"
#include "foundation/PxTransform.h"
#include "PxShape.h"
#include "PxAggregate.h"
#include "PxParticleSystem.h"
#include "foundation/PxPreprocessor.h"
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
#include "PxFEMCloth.h"
#include "PxHairSystem.h"
#endif
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxScene;
class PxSceneDesc;
class PxTolerancesScale;
class PxPvd;
class PxOmniPvd;
class PxInsertionCallback;
class PxRigidActor;
class PxConstraintConnector;
struct PxConstraintShaderTable;
class PxGeometry;
class PxFoundation;
class PxPruningStructure;
class PxBVH;
class PxParticleClothBuffer;
class PxParticleRigidBuffer;
class PxSoftBodyMesh;
/**
\brief Abstract singleton factory class used for instancing objects in the Physics SDK.
In addition you can use PxPhysics to set global parameters which will effect all scenes and create
objects that can be shared across multiple scenes.
You can get an instance of this class by calling PxCreatePhysics().
@see PxCreatePhysics() PxScene
*/
class PxPhysics
{
public:
/** @name Basics
*/
//@{
virtual ~PxPhysics() {}
/**
\brief Destroys the instance it is called on.
Use this release method to destroy an instance of this class. Be sure
to not keep a reference to this object after calling release.
Avoid release calls while a scene is simulating (in between simulate() and fetchResults() calls).
Note that this must be called once for each prior call to PxCreatePhysics, as
there is a reference counter. Also note that you mustn't destroy the PxFoundation instance (holding the allocator, error callback etc.)
until after the reference count reaches 0 and the SDK is actually removed.
Releasing an SDK will also release any objects created through it (scenes, triangle meshes, convex meshes, heightfields, shapes etc.),
provided the user hasn't already done so.
\note Releasing the PxPhysics instance is a prerequisite to releasing the PxFoundation instance.
@see PxCreatePhysics() PxFoundation
*/
virtual void release() = 0;
/**
\brief Retrieves the Foundation instance.
\return A reference to the Foundation object.
*/
virtual PxFoundation& getFoundation() = 0;
/**
\brief Retrieves the PxOmniPvd instance if there is one registered with PxPhysics.
\return A pointer to a PxOmniPvd object.
*/
virtual PxOmniPvd* getOmniPvd() = 0;
/**
\brief Creates an aggregate with the specified maximum size and filtering hint.
The previous API used "bool enableSelfCollision" which should now silently evaluates
to a PxAggregateType::eGENERIC aggregate with its self-collision bit.
Use PxAggregateType::eSTATIC or PxAggregateType::eKINEMATIC for aggregates that will
only contain static or kinematic actors. This provides faster filtering when used in
combination with PxPairFilteringMode.
\param [in] maxActor The maximum number of actors that may be placed in the aggregate.
\param [in] maxShape The maximum number of shapes that may be placed in the aggregate.
\param [in] filterHint The aggregate's filtering hint.
\return The new aggregate.
@see PxAggregate PxAggregateFilterHint PxAggregateType PxPairFilteringMode
*/
virtual PxAggregate* createAggregate(PxU32 maxActor, PxU32 maxShape, PxAggregateFilterHint filterHint) = 0;
/**
\brief Returns the simulation tolerance parameters.
\return The current simulation tolerance parameters.
*/
virtual const PxTolerancesScale& getTolerancesScale() const = 0;
//@}
/** @name Meshes
*/
//@{
/**
\brief Creates a triangle mesh object.
This can then be instanced into #PxShape objects.
\param [in] stream The triangle mesh stream.
\return The new triangle mesh.
@see PxTriangleMesh PxMeshPreprocessingFlag PxTriangleMesh.release() PxInputStream PxTriangleMeshFlag
*/
virtual PxTriangleMesh* createTriangleMesh(PxInputStream& stream) = 0;
/**
\brief Return the number of triangle meshes that currently exist.
\return Number of triangle meshes.
@see getTriangleMeshes()
*/
virtual PxU32 getNbTriangleMeshes() const = 0;
/**
\brief Writes the array of triangle mesh pointers to a user buffer.
Returns the number of pointers written.
The ordering of the triangle meshes in the array is not specified.
\param [out] userBuffer The buffer to receive triangle mesh pointers.
\param [in] bufferSize The number of triangle mesh pointers which can be stored in the buffer.
\param [in] startIndex Index of first mesh pointer to be retrieved.
\return The number of triangle mesh pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbTriangleMeshes() PxTriangleMesh
*/
virtual PxU32 getTriangleMeshes(PxTriangleMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
//@}
/** @name Tetrahedron Meshes
*/
//@{
/**
\brief Creates a tetrahedron mesh object.
This can then be instanced into #PxShape objects.
\param[in] stream The tetrahedron mesh stream.
\return The new tetrahedron mesh.
@see PxTetrahedronMesh PxMeshPreprocessingFlag PxTetrahedronMesh.release() PxInputStream PxTriangleMeshFlag
*/
virtual PxTetrahedronMesh* createTetrahedronMesh(PxInputStream& stream) = 0;
/**
\brief Creates a softbody mesh object.
\param[in] stream The softbody mesh stream.
\return The new softbody mesh.
@see createTetrahedronMesh
*/
virtual PxSoftBodyMesh* createSoftBodyMesh(PxInputStream& stream) = 0;
/**
\brief Return the number of tetrahedron meshes that currently exist.
\return Number of tetrahedron meshes.
@see getTetrahedronMeshes()
*/
virtual PxU32 getNbTetrahedronMeshes() const = 0;
/**
\brief Writes the array of tetrahedron mesh pointers to a user buffer.
Returns the number of pointers written.
The ordering of the tetrahedron meshes in the array is not specified.
\param[out] userBuffer The buffer to receive tetrahedron mesh pointers.
\param[in] bufferSize The number of tetrahedron mesh pointers which can be stored in the buffer.
\param[in] startIndex Index of first mesh pointer to be retrieved.
\return The number of tetrahedron mesh pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbTetrahedronMeshes() PxTetrahedronMesh
*/
virtual PxU32 getTetrahedronMeshes(PxTetrahedronMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a heightfield object from previously cooked stream.
This can then be instanced into #PxShape objects.
\param [in] stream The heightfield mesh stream.
\return The new heightfield.
@see PxHeightField PxHeightField.release() PxInputStream
*/
virtual PxHeightField* createHeightField(PxInputStream& stream) = 0;
/**
\brief Return the number of heightfields that currently exist.
\return Number of heightfields.
@see getHeightFields()
*/
virtual PxU32 getNbHeightFields() const = 0;
/**
\brief Writes the array of heightfield pointers to a user buffer.
Returns the number of pointers written.
The ordering of the heightfields in the array is not specified.
\param [out] userBuffer The buffer to receive heightfield pointers.
\param [in] bufferSize The number of heightfield pointers which can be stored in the buffer.
\param [in] startIndex Index of first heightfield pointer to be retrieved.
\return The number of heightfield pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbHeightFields() PxHeightField
*/
virtual PxU32 getHeightFields(PxHeightField** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a convex mesh object.
This can then be instanced into #PxShape objects.
\param [in] stream The stream to load the convex mesh from.
\return The new convex mesh.
@see PxConvexMesh PxConvexMesh.release() PxInputStream createTriangleMesh() PxConvexMeshGeometry PxShape
*/
virtual PxConvexMesh* createConvexMesh(PxInputStream& stream) = 0;
/**
\brief Return the number of convex meshes that currently exist.
\return Number of convex meshes.
@see getConvexMeshes()
*/
virtual PxU32 getNbConvexMeshes() const = 0;
/**
\brief Writes the array of convex mesh pointers to a user buffer.
Returns the number of pointers written.
The ordering of the convex meshes in the array is not specified.
\param [out] userBuffer The buffer to receive convex mesh pointers.
\param [in] bufferSize The number of convex mesh pointers which can be stored in the buffer.
\param [in] startIndex Index of first convex mesh pointer to be retrieved.
\return The number of convex mesh pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbConvexMeshes() PxConvexMesh
*/
virtual PxU32 getConvexMeshes(PxConvexMesh** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a bounding volume hierarchy.
\param [in] stream The stream to load the BVH from.
\return The new BVH.
@see PxBVH PxInputStream
*/
virtual PxBVH* createBVH(PxInputStream& stream) = 0;
/**
\brief Return the number of bounding volume hierarchies that currently exist.
\return Number of bounding volume hierarchies.
@see PxBVH getBVHs()
*/
virtual PxU32 getNbBVHs() const = 0;
/**
\brief Writes the array of bounding volume hierarchy pointers to a user buffer.
Returns the number of pointers written.
The ordering of the BVHs in the array is not specified.
\param [out] userBuffer The buffer to receive BVH pointers.
\param [in] bufferSize The number of BVH pointers which can be stored in the buffer.
\param [in] startIndex Index of first BVH pointer to be retrieved.
\return The number of BVH pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbBVHs() PxBVH
*/
virtual PxU32 getBVHs(PxBVH** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
//@}
/** @name Scenes
*/
//@{
/**
\brief Creates a scene.
\note Every scene uses a Thread Local Storage slot. This imposes a platform specific limit on the
number of scenes that can be created.
\param [in] sceneDesc Scene descriptor. See #PxSceneDesc
\return The new scene object.
@see PxScene PxScene.release() PxSceneDesc
*/
virtual PxScene* createScene(const PxSceneDesc& sceneDesc) = 0;
/**
\brief Gets number of created scenes.
\return The number of scenes created.
@see getScenes()
*/
virtual PxU32 getNbScenes() const = 0;
/**
\brief Writes the array of scene pointers to a user buffer.
Returns the number of pointers written.
The ordering of the scene pointers in the array is not specified.
\param [out] userBuffer The buffer to receive scene pointers.
\param [in] bufferSize The number of scene pointers which can be stored in the buffer.
\param [in] startIndex Index of first scene pointer to be retrieved.
\return The number of scene pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbScenes() PxScene
*/
virtual PxU32 getScenes(PxScene** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
//@}
/** @name Actors
*/
//@{
/**
\brief Creates a static rigid actor with the specified pose and all other fields initialized
to their default values.
\param [in] pose The initial pose of the actor. Must be a valid transform.
@see PxRigidStatic
*/
virtual PxRigidStatic* createRigidStatic(const PxTransform& pose) = 0;
/**
\brief Creates a dynamic rigid actor with the specified pose and all other fields initialized
to their default values.
\param [in] pose The initial pose of the actor. Must be a valid transform.
@see PxRigidDynamic
*/
virtual PxRigidDynamic* createRigidDynamic(const PxTransform& pose) = 0;
/**
\brief Creates a pruning structure from actors.
\note Every provided actor needs at least one shape with the eSCENE_QUERY_SHAPE flag set.
\note Both static and dynamic actors can be provided.
\note It is not allowed to pass in actors which are already part of a scene.
\note Articulation links cannot be provided.
\param [in] actors Array of actors to add to the pruning structure. Must be non NULL.
\param [in] nbActors Number of actors in the array. Must be >0.
\return Pruning structure created from given actors, or NULL if any of the actors did not comply with the above requirements.
@see PxActor PxPruningStructure
*/
virtual PxPruningStructure* createPruningStructure(PxRigidActor*const* actors, PxU32 nbActors) = 0;
//@}
/** @name Shapes
*/
//@{
/**
\brief Creates a shape which may be attached to multiple actors
The shape will be created with a reference count of 1.
\param [in] geometry The geometry for the shape
\param [in] material The material for the shape
\param [in] isExclusive Whether this shape is exclusive to a single actor or maybe be shared
\param [in] shapeFlags The PxShapeFlags to be set
\return The shape
\note Shared shapes are not mutable when they are attached to an actor
@see PxShape
*/
PX_FORCE_INLINE PxShape* createShape( const PxGeometry& geometry,
const PxMaterial& material,
bool isExclusive = false,
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE)
{
PxMaterial* materialPtr = const_cast<PxMaterial*>(&material);
return createShape(geometry, &materialPtr, 1, isExclusive, shapeFlags);
}
/**
\brief Creates a shape which may be attached to one or more softbody actors
The shape will be created with a reference count of 1.
\param [in] geometry The geometry for the shape
\param [in] material The material for the shape
\param [in] isExclusive Whether this shape is exclusive to a single actor or maybe be shared
\param [in] shapeFlags The PxShapeFlags to be set
\return The shape
\note Shared shapes are not mutable when they are attached to an actor
@see PxShape
*/
PX_FORCE_INLINE PxShape* createShape( const PxGeometry& geometry,
const PxFEMSoftBodyMaterial& material,
bool isExclusive = false,
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE)
{
PxFEMSoftBodyMaterial* materialPtr = const_cast<PxFEMSoftBodyMaterial*>(&material);
return createShape(geometry, &materialPtr, 1, isExclusive, shapeFlags);
}
#if PX_ENABLE_FEATURES_UNDER_CONSTRUCTION
/**
\brief Creates a shape which may be attached to one or more FEMCloth actors
The shape will be created with a reference count of 1.
\param [in] geometry The geometry for the shape
\param [in] material The material for the shape
\param [in] isExclusive Whether this shape is exclusive to a single actor or maybe be shared
\param [in] shapeFlags The PxShapeFlags to be set
\return The shape
\note Shared shapes are not mutable when they are attached to an actor
@see PxShape
*/
PX_FORCE_INLINE PxShape* createShape( const PxGeometry& geometry,
const PxFEMClothMaterial& material,
bool isExclusive = false,
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE)
{
PxFEMClothMaterial* materialPtr = const_cast<PxFEMClothMaterial*>(&material);
return createShape(geometry, &materialPtr, 1, isExclusive, shapeFlags);
}
#endif
/**
\brief Creates a shape which may be attached to multiple actors
The shape will be created with a reference count of 1.
\param [in] geometry The geometry for the shape
\param [in] materials The materials for the shape
\param [in] materialCount The number of materials
\param [in] isExclusive Whether this shape is exclusive to a single actor or may be shared
\param [in] shapeFlags The PxShapeFlags to be set
\return The shape
\note Shared shapes are not mutable when they are attached to an actor
\note Shapes created from *SDF* triangle-mesh geometries do not support more than one material.
@see PxShape
*/
virtual PxShape* createShape( const PxGeometry& geometry,
PxMaterial*const * materials,
PxU16 materialCount,
bool isExclusive = false,
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) = 0;
virtual PxShape* createShape( const PxGeometry& geometry,
PxFEMSoftBodyMaterial*const * materials,
PxU16 materialCount,
bool isExclusive = false,
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) = 0;
virtual PxShape* createShape( const PxGeometry& geometry,
PxFEMClothMaterial*const * materials,
PxU16 materialCount,
bool isExclusive = false,
PxShapeFlags shapeFlags = PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSCENE_QUERY_SHAPE | PxShapeFlag::eSIMULATION_SHAPE) = 0;
/**
\brief Return the number of shapes that currently exist.
\return Number of shapes.
@see getShapes()
*/
virtual PxU32 getNbShapes() const = 0;
/**
\brief Writes the array of shape pointers to a user buffer.
Returns the number of pointers written.
The ordering of the shapes in the array is not specified.
\param [out] userBuffer The buffer to receive shape pointers.
\param [in] bufferSize The number of shape pointers which can be stored in the buffer.
\param [in] startIndex Index of first shape pointer to be retrieved
\return The number of shape pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbShapes() PxShape
*/
virtual PxU32 getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
//@}
/** @name Constraints and Articulations
*/
//@{
/**
\brief Creates a constraint shader.
\note A constraint shader will get added automatically to the scene the two linked actors belong to. Either, but not both, of actor0 and actor1 may
be NULL to denote attachment to the world.
\param [in] actor0 The first actor
\param [in] actor1 The second actor
\param [in] connector The connector object, which the SDK uses to communicate with the infrastructure for the constraint
\param [in] shaders The shader functions for the constraint
\param [in] dataSize The size of the data block for the shader
\return The new constraint shader.
@see PxConstraint
*/
virtual PxConstraint* createConstraint(PxRigidActor* actor0, PxRigidActor* actor1, PxConstraintConnector& connector, const PxConstraintShaderTable& shaders, PxU32 dataSize) = 0;
/**
\brief Creates a reduced-coordinate articulation with all fields initialized to their default values.
\return the new articulation
@see PxArticulationReducedCoordinate
*/
virtual PxArticulationReducedCoordinate* createArticulationReducedCoordinate() = 0;
/**
\brief Creates a FEM-based cloth with all fields initialized to their default values.
\warning Feature under development, only for internal usage.
\param[in] cudaContextManager The PxCudaContextManager this instance is tied to.
\return the new FEM-cloth
@see PxFEMCloth
*/
virtual PxFEMCloth* createFEMCloth(PxCudaContextManager& cudaContextManager) = 0;
/**
\brief Creates a FEM-based soft body with all fields initialized to their default values.
\param[in] cudaContextManager The PxCudaContextManager this instance is tied to.
\return the new soft body
@see PxSoftBody
*/
virtual PxSoftBody* createSoftBody(PxCudaContextManager& cudaContextManager) = 0;
/**
\brief Creates a hair system with all fields initialized to their default values.
\warning Feature under development, only for internal usage.
\param[in] cudaContextManager The PxCudaContextManager this instance is tied to.
\return the new hair system
@see PxHairSystem
*/
virtual PxHairSystem* createHairSystem(PxCudaContextManager& cudaContextManager) = 0;
/**
\brief Creates a particle system with a position-based dynamics (PBD) solver.
A PBD particle system can be used to simulate particle systems with fluid and granular particles. It also allows simulating cloth using
mass-spring constraints and rigid bodies by shape matching the bodies with particles.
\param[in] cudaContextManager The PxCudaContextManager this instance is tied to.
\param[in] maxNeighborhood The maximum number of particles considered in neighborhood-based particle interaction calculations (e.g. fluid density constraints).
\return the new particle system
@see PxPBDParticleSystem
*/
virtual PxPBDParticleSystem* createPBDParticleSystem(PxCudaContextManager& cudaContextManager, PxU32 maxNeighborhood = 96) = 0;
/**
\brief Creates a particle system with a fluid-implicit particle solver (FLIP).
\warning Feature under development, only for internal usage.
\param[in] cudaContextManager The PxCudaContextManager this instance is tied to.
\return the new particle system
@see PxFLIPParticleSystem
*/
virtual PxFLIPParticleSystem* createFLIPParticleSystem(PxCudaContextManager& cudaContextManager) = 0;
/**
\brief Creates a particle system with a material-point-method solver (MPM).
\warning Feature under development, only for internal usage.
A MPM particle system can be used to simulate fluid dynamics and deformable body effects using particles.
\param[in] cudaContextManager The PxCudaContextManager this instance is tied to.
\return the new particle system
@see PxMPMParticleSystem
*/
virtual PxMPMParticleSystem* createMPMParticleSystem(PxCudaContextManager& cudaContextManager) = 0;
/**
\brief Create particle buffer to simulate fluid/granular material.
\param[in] maxParticles The maximum number of particles in this buffer.
\param[in] maxVolumes The maximum number of volumes in this buffer. See PxParticleVolume.
\param[in] cudaContextManager The PxCudaContextManager this buffer is tied to.
\return PxParticleBuffer instance
@see PxParticleBuffer
*/
virtual PxParticleBuffer* createParticleBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxCudaContextManager* cudaContextManager) = 0;
/**
\brief Create a particle buffer for fluid dynamics with diffuse particles. Diffuse particles are used to simulate fluid effects
such as foam, spray and bubbles.
\param[in] maxParticles The maximum number of particles in this buffer.
\param[in] maxVolumes The maximum number of volumes in this buffer. See #PxParticleVolume.
\param[in] maxDiffuseParticles The max number of diffuse particles int this buffer.
\param[in] cudaContextManager The PxCudaContextManager this buffer is tied to.
\return PxParticleAndDiffuseBuffer instance
@see PxParticleAndDiffuseBuffer, PxDiffuseParticleParams
*/
virtual PxParticleAndDiffuseBuffer* createParticleAndDiffuseBuffer(PxU32 maxParticles, PxU32 maxVolumes, PxU32 maxDiffuseParticles, PxCudaContextManager* cudaContextManager) = 0;
/**
\brief Create a particle buffer to simulate particle cloth.
\param[in] maxParticles The maximum number of particles in this buffer.
\param[in] maxNumVolumes The maximum number of volumes in this buffer. See #PxParticleVolume.
\param[in] maxNumCloths The maximum number of cloths in this buffer. See #PxParticleCloth.
\param[in] maxNumTriangles The maximum number of triangles for aerodynamics.
\param[in] maxNumSprings The maximum number of springs to connect particles. See #PxParticleSpring.
\param[in] cudaContextManager The PxCudaContextManager this buffer is tied to.
\return PxParticleClothBuffer instance
@see PxParticleClothBuffer
*/
virtual PxParticleClothBuffer* createParticleClothBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumCloths, PxU32 maxNumTriangles, PxU32 maxNumSprings, PxCudaContextManager* cudaContextManager) = 0;
/**
\brief Create a particle buffer to simulate rigid bodies using shape matching with particles.
\param[in] maxParticles The maximum number of particles in this buffer.
\param[in] maxNumVolumes The maximum number of volumes in this buffer. See #PxParticleVolume.
\param[in] maxNumRigids The maximum number of rigid bodies this buffer is used to simulate.
\param[in] cudaContextManager The PxCudaContextManager this buffer is tied to.
\return PxParticleRigidBuffer instance
@see PxParticleRigidBuffer
*/
virtual PxParticleRigidBuffer* createParticleRigidBuffer(PxU32 maxParticles, PxU32 maxNumVolumes, PxU32 maxNumRigids, PxCudaContextManager* cudaContextManager) = 0;
//@}
/** @name Materials
*/
//@{
/**
\brief Creates a new rigid body material with certain default properties.
\return The new rigid body material.
\param [in] staticFriction The coefficient of static friction
\param [in] dynamicFriction The coefficient of dynamic friction
\param [in] restitution The coefficient of restitution
@see PxMaterial
*/
virtual PxMaterial* createMaterial(PxReal staticFriction, PxReal dynamicFriction, PxReal restitution) = 0;
/**
\brief Return the number of rigid body materials that currently exist.
\return Number of rigid body materials.
@see getMaterials()
*/
virtual PxU32 getNbMaterials() const = 0;
/**
\brief Writes the array of rigid body material pointers to a user buffer.
Returns the number of pointers written.
The ordering of the materials in the array is not specified.
\param [out] userBuffer The buffer to receive material pointers.
\param [in] bufferSize The number of material pointers which can be stored in the buffer.
\param [in] startIndex Index of first material pointer to be retrieved.
\return The number of material pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbMaterials() PxMaterial
*/
virtual PxU32 getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a new FEM soft body material with certain default properties.
\return The new FEM material.
\param [in] youngs The young's modulus
\param [in] poissons The poissons's ratio
\param [in] dynamicFriction The dynamic friction coefficient
@see PxFEMSoftBodyMaterial
*/
virtual PxFEMSoftBodyMaterial* createFEMSoftBodyMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction) = 0;
/**
\brief Return the number of FEM soft body materials that currently exist.
\return Number of FEM materials.
@see getFEMSoftBodyMaterials()
*/
virtual PxU32 getNbFEMSoftBodyMaterials() const = 0;
/**
\brief Writes the array of FEM soft body material pointers to a user buffer.
Returns the number of pointers written.
The ordering of the materials in the array is not specified.
\param [out] userBuffer The buffer to receive material pointers.
\param [in] bufferSize The number of material pointers which can be stored in the buffer.
\param [in] startIndex Index of first material pointer to be retrieved.
\return The number of material pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbFEMSoftBodyMaterials() PxFEMSoftBodyMaterial
*/
virtual PxU32 getFEMSoftBodyMaterials(PxFEMSoftBodyMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a new FEM cloth material with certain default properties.
\warning Feature under development, only for internal usage.
\return The new FEM material.
\param [in] youngs The young's modulus
\param [in] poissons The poissons's ratio
\param [in] dynamicFriction The dynamic friction coefficient
\param [in] thickness The cloth's thickness
@see PxFEMClothMaterial
*/
virtual PxFEMClothMaterial* createFEMClothMaterial(PxReal youngs, PxReal poissons, PxReal dynamicFriction, PxReal thickness = 0.001f) = 0;
/**
\brief Return the number of FEM cloth materials that currently exist.
\return Number of FEM cloth materials.
@see getFEMClothMaterials()
*/
virtual PxU32 getNbFEMClothMaterials() const = 0;
/**
\brief Writes the array of FEM cloth material pointers to a user buffer.
Returns the number of pointers written.
The ordering of the materials in the array is not specified.
\param [out] userBuffer The buffer to receive material pointers.
\param [in] bufferSize The number of material pointers which can be stored in the buffer.
\param [in] startIndex Index of first material pointer to be retrieved.
\return The number of material pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbFEMClothMaterials() PxFEMClothMaterial
*/
virtual PxU32 getFEMClothMaterials(PxFEMClothMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a new PBD material with certain default properties.
\param [in] friction The friction parameter
\param [in] damping The velocity damping parameter
\param [in] adhesion The adhesion parameter
\param [in] viscosity The viscosity parameter
\param [in] vorticityConfinement The vorticity confinement coefficient
\param [in] surfaceTension The surface tension coefficient
\param [in] cohesion The cohesion parameter
\param [in] lift The lift parameter
\param [in] drag The drag parameter
\param [in] cflCoefficient The Courant-Friedrichs-Lewy(cfl) coefficient
\param [in] gravityScale The gravity scale
\return The new PBD material.
@see PxPBDMaterial
*/
virtual PxPBDMaterial* createPBDMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal vorticityConfinement, PxReal surfaceTension, PxReal cohesion, PxReal lift, PxReal drag, PxReal cflCoefficient = 1.f, PxReal gravityScale = 1.f) = 0;
/**
\brief Return the number of PBD materials that currently exist.
\return Number of PBD materials.
@see getPBDMaterials()
*/
virtual PxU32 getNbPBDMaterials() const = 0;
/**
\brief Writes the array of PBD material pointers to a user buffer.
Returns the number of pointers written.
The ordering of the materials in the array is not specified.
\param [out] userBuffer The buffer to receive material pointers.
\param [in] bufferSize The number of material pointers which can be stored in the buffer.
\param [in] startIndex Index of first material pointer to be retrieved.
\return The number of material pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbPBDMaterials() PxPBDMaterial
*/
virtual PxU32 getPBDMaterials(PxPBDMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a new FLIP material with certain default properties.
\warning Feature under development, only for internal usage.
\param [in] friction The friction parameter
\param [in] damping The velocity damping parameter
\param [in] adhesion The maximum velocity magnitude of particles
\param [in] viscosity The viscosity parameter
\param [in] gravityScale The gravity scale
\return The new FLIP material.
@see PxFLIPMaterial
*/
virtual PxFLIPMaterial* createFLIPMaterial(PxReal friction, PxReal damping, PxReal adhesion, PxReal viscosity, PxReal gravityScale = 1.f) = 0;
/**
\brief Return the number of FLIP materials that currently exist.
\warning Feature under development, only for internal usage.
\return Number of FLIP materials.
@see getFLIPMaterials()
*/
virtual PxU32 getNbFLIPMaterials() const = 0;
/**
\brief Writes the array of FLIP material pointers to a user buffer.
\warning Feature under development, only for internal usage.
Returns the number of pointers written.
The ordering of the materials in the array is not specified.
\param [out] userBuffer The buffer to receive material pointers.
\param [in] bufferSize The number of material pointers which can be stored in the buffer.
\param [in] startIndex Index of first material pointer to be retrieved.
\return The number of material pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbFLIPMaterials() PxFLIPMaterial
*/
virtual PxU32 getFLIPMaterials(PxFLIPMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Creates a new MPM material with certain default properties.
\warning Feature under development, only for internal usage.
\param [in] friction The friction parameter
\param [in] damping The velocity damping parameter
\param [in] adhesion The maximum velocity magnitude of particles
\param [in] isPlastic True if plastic
\param [in] youngsModulus The Young's modulus
\param [in] poissons The Poissons's ratio
\param [in] hardening The hardening parameter
\param [in] criticalCompression The critical compression parameter
\param [in] criticalStretch The critical stretch parameter
\param [in] tensileDamageSensitivity The tensile damage sensitivity parameter
\param [in] compressiveDamageSensitivity The compressive damage sensitivity parameter
\param [in] attractiveForceResidual The attractive force residual parameter
\param [in] gravityScale The gravity scale
\return The new MPM material.
@see PxMPMMaterial
*/
virtual PxMPMMaterial* createMPMMaterial(PxReal friction, PxReal damping, PxReal adhesion, bool isPlastic, PxReal youngsModulus, PxReal poissons, PxReal hardening, PxReal criticalCompression, PxReal criticalStretch, PxReal tensileDamageSensitivity, PxReal compressiveDamageSensitivity, PxReal attractiveForceResidual, PxReal gravityScale = 1.0f) = 0;
/**
\brief Return the number of MPM materials that currently exist.
\warning Feature under development, only for internal usage.
\return Number of MPM materials.
@see getMPMMaterials()
*/
virtual PxU32 getNbMPMMaterials() const = 0;
/**
\brief Writes the array of MPM material pointers to a user buffer.
\warning Feature under development, only for internal usage.
Returns the number of pointers written.
The ordering of the materials in the array is not specified.
\param [out] userBuffer The buffer to receive material pointers.
\param [in] bufferSize The number of material pointers which can be stored in the buffer.
\param [in] startIndex Index of first material pointer to be retrieved.
\return The number of material pointers written to userBuffer, this should be less or equal to bufferSize.
@see getNbMPMMaterials() PxMPMMaterial
*/
virtual PxU32 getMPMMaterials(PxMPMMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
//@}
/** @name Deletion Listeners
*/
//@{
/**
\brief Register a deletion listener. Listeners will be called whenever an object is deleted.
It is illegal to register or unregister a deletion listener while deletions are being processed.
\note By default a registered listener will receive events from all objects. Set the restrictedObjectSet parameter to true on registration and use #registerDeletionListenerObjects to restrict the received events to specific objects.
\note The deletion events are only supported on core PhysX objects. In general, objects in extension modules do not provide this functionality, however, in the case of PxJoint objects, the underlying PxConstraint will send the events.
\param [in] observer Observer object to send notifications to.
\param [in] deletionEvents The deletion event types to get notified of.
\param [in] restrictedObjectSet If false, the deletion listener will get events from all objects, else the objects to receive events from have to be specified explicitly through #registerDeletionListenerObjects.
@see PxDeletionListener unregisterDeletionListener
*/
virtual void registerDeletionListener(PxDeletionListener& observer, const PxDeletionEventFlags& deletionEvents, bool restrictedObjectSet = false) = 0;
/**
\brief Unregister a deletion listener.
It is illegal to register or unregister a deletion listener while deletions are being processed.
\param [in] observer Observer object to stop sending notifications to.
@see PxDeletionListener registerDeletionListener
*/
virtual void unregisterDeletionListener(PxDeletionListener& observer) = 0;
/**
\brief Register specific objects for deletion events.
This method allows for a deletion listener to limit deletion events to specific objects only.
\note It is illegal to register or unregister objects while deletions are being processed.
\note The deletion listener has to be registered through #registerDeletionListener() and configured to support restricted object sets prior to this method being used.
\param [in] observer Observer object to send notifications to.
\param [in] observables List of objects for which to receive deletion events. Only PhysX core objects are supported. In the case of PxJoint objects, the underlying PxConstraint can be used to get the events.
\param [in] observableCount Size of the observables list.
@see PxDeletionListener unregisterDeletionListenerObjects
*/
virtual void registerDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) = 0;
/**
\brief Unregister specific objects for deletion events.
This method allows to clear previously registered objects for a deletion listener (see #registerDeletionListenerObjects()).
\note It is illegal to register or unregister objects while deletions are being processed.
\note The deletion listener has to be registered through #registerDeletionListener() and configured to support restricted object sets prior to this method being used.
\param [in] observer Observer object to stop sending notifications to.
\param [in] observables List of objects for which to not receive deletion events anymore.
\param [in] observableCount Size of the observables list.
@see PxDeletionListener registerDeletionListenerObjects
*/
virtual void unregisterDeletionListenerObjects(PxDeletionListener& observer, const PxBase* const* observables, PxU32 observableCount) = 0;
/**
\brief Gets PxPhysics object insertion interface.
The insertion interface is needed for PxCreateTriangleMesh, PxCooking::createTriangleMesh etc., this allows runtime mesh creation.
@see PxCreateTriangleMesh PxCreateHeightField PxCreateTetrahedronMesh PxCreateBVH
PxCooking::createTriangleMesh PxCooking::createHeightfield PxCooking::createTetrahedronMesh PxCooking::createBVH
*/
virtual PxInsertionCallback& getPhysicsInsertionCallback() = 0;
//@}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/**
\brief Creates an instance of the physics SDK.
Creates an instance of this class. May not be a class member to avoid name mangling.
Pass the constant #PX_PHYSICS_VERSION as the argument.
There may be only one instance of this class per process. Calling this method after an instance
has been created already will result in an error message and NULL will be returned.
\param version Version number we are expecting (should be #PX_PHYSICS_VERSION)
\param foundation Foundation instance (see PxFoundation)
\param scale values used to determine default tolerances for objects at creation time
\param trackOutstandingAllocations true if you want to track memory allocations
so a debugger connection partway through your physics simulation will get
an accurate map of everything that has been allocated so far. This could have a memory
and performance impact on your simulation hence it defaults to off.
\param pvd When pvd points to a valid PxPvd instance (PhysX Visual Debugger), a connection to the specified PxPvd instance is created.
If pvd is NULL no connection will be attempted.
\param omniPvd When omniPvd points to a valid PxOmniPvd instance PhysX will sample its internal structures to the defined OmniPvd output streams
set in the PxOmniPvd object.
\return PxPhysics instance on success, NULL if operation failed
@see PxPhysics
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxPhysics* PxCreatePhysics(physx::PxU32 version,
physx::PxFoundation& foundation,
const physx::PxTolerancesScale& scale,
bool trackOutstandingAllocations = false,
physx::PxPvd* pvd = NULL,
physx::PxOmniPvd* omniPvd = NULL);
/**
\brief Retrieves the Physics SDK after it has been created.
Before using this function the user must call #PxCreatePhysics().
\note The behavior of this method is undefined if the Physics SDK instance has not been created already.
*/
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wreturn-type-c-linkage"
#endif
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxPhysics& PX_CALL_CONV PxGetPhysics();
#ifdef __clang__
#pragma clang diagnostic pop
#endif
/** @} */
#endif
| 42,189 | C | 36.43567 | 351 | 0.770627 |
NVIDIA-Omniverse/PhysX/physx/include/PxImmediateMode.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_IMMEDIATE_MODE_H
#define PX_IMMEDIATE_MODE_H
/** \addtogroup immediatemode
@{ */
#include "PxPhysXConfig.h"
#include "foundation/PxMemory.h"
#include "solver/PxSolverDefs.h"
#include "collision/PxCollisionDefs.h"
#include "PxArticulationReducedCoordinate.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxCudaContextManager;
class PxBaseTask;
class PxGeometry;
#if !PX_DOXYGEN
namespace immediate
{
#endif
typedef void* PxArticulationHandle;
/**
\brief Structure to store linear and angular components of spatial vector
*/
struct PxSpatialVector
{
PxVec3 top;
PxReal pad0;
PxVec3 bottom;
PxReal pad1;
};
/**
\brief Structure to store rigid body properties
*/
struct PxRigidBodyData
{
PX_ALIGN(16, PxVec3 linearVelocity); //!< 12 Linear velocity
PxReal invMass; //!< 16 Inverse mass
PxVec3 angularVelocity; //!< 28 Angular velocity
PxReal maxDepenetrationVelocity; //!< 32 Maximum de-penetration velocity
PxVec3 invInertia; //!< 44 Mass-space inverse interia diagonal vector
PxReal maxContactImpulse; //!< 48 Maximum permissable contact impulse
PxTransform body2World; //!< 76 World space transform
PxReal linearDamping; //!< 80 Linear damping coefficient
PxReal angularDamping; //!< 84 Angular damping coefficient
PxReal maxLinearVelocitySq; //!< 88 Squared maximum linear velocity
PxReal maxAngularVelocitySq; //!< 92 Squared maximum angular velocity
PxU32 pad; //!< 96 Padding for 16-byte alignment
};
/**
\brief Callback class to record contact points produced by immediate::PxGenerateContacts
*/
class PxContactRecorder
{
public:
/**
\brief Method to record new contacts
\param [in] contactPoints The contact points produced
\param [in] nbContacts The number of contact points produced
\param [in] index The index of this pair. This is an index from 0-N-1 identifying which pair this relates to from within the array of pairs passed to PxGenerateContacts
\return a boolean to indicate if this callback successfully stored the contacts or not.
*/
virtual bool recordContacts(const PxContactPoint* contactPoints, PxU32 nbContacts, PxU32 index) = 0;
virtual ~PxContactRecorder(){}
};
/**
\brief Constructs a PxSolverBodyData structure based on rigid body properties. Applies gravity, damping and clamps maximum velocity.
\param [in] inRigidData The array rigid body properties
\param [out] outSolverBodyData The array of solverBodyData produced to represent these bodies
\param [in] nbBodies The total number of solver bodies to create
\param [in] gravity The gravity vector
\param [in] dt The timestep
\param [in] gyroscopicForces Indicates whether gyroscopic forces should be integrated
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxConstructSolverBodies(const PxRigidBodyData* inRigidData, PxSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity, PxReal dt, bool gyroscopicForces = false);
/**
\brief Constructs a PxSolverBodyData structure for a static body at a given pose.
\param [in] globalPose The pose of this static actor
\param [out] solverBodyData The solver body representation of this static actor
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxConstructStaticSolverBody(const PxTransform& globalPose, PxSolverBodyData& solverBodyData);
/**
\brief Groups together sets of independent PxSolverConstraintDesc objects to be solved using SIMD SOA approach.
\param [in] solverConstraintDescs The set of solver constraint descs to batch
\param [in] nbConstraints The number of constraints to batch
\param [in,out] solverBodies The array of solver bodies that the constraints reference. Some fields in these structures are written to as scratch memory for the batching.
\param [in] nbBodies The number of bodies
\param [out] outBatchHeaders The batch headers produced by this batching process. This array must have at least 1 entry per input constraint
\param [out] outOrderedConstraintDescs A reordered copy of the constraint descs. This array is referenced by the constraint batches. This array must have at least 1 entry per input constraint.
\param [in,out] articulations The array of articulations that the constraints reference. Some fields in these structures are written to as scratch memory for the batching.
\param [in] nbArticulations The number of articulations
\return The total number of batches produced. This should be less than or equal to nbConstraints.
\note This method considers all bodies within the range [0, nbBodies-1] to be valid dynamic bodies. A given dynamic body can only be referenced in a batch once. Static or kinematic bodies can be
referenced multiple times within a batch safely because constraints do not affect their velocities. The batching will implicitly consider any bodies outside of the range [0, nbBodies-1] to be
infinite mass (static or kinematic). This means that either appending static/kinematic to the end of the array of bodies or placing static/kinematic bodies at before the start body pointer
will ensure that the minimum number of batches are produced.
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxU32 PxBatchConstraints( const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxSolverBody* solverBodies, PxU32 nbBodies,
PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs,
PxArticulationHandle* articulations=NULL, PxU32 nbArticulations=0);
/**
\brief Creates a set of contact constraint blocks. Note that, depending the results of PxBatchConstraints, each batchHeader may refer to up to 4 solverConstraintDescs.
This function will allocate both constraint and friction patch data via the PxConstraintAllocator provided. Constraint data is only valid until PxSolveConstraints has completed.
Friction data is to be retained and provided by the application for friction correlation.
\param [in] batchHeaders Array of batch headers to process
\param [in] nbHeaders The total number of headers
\param [in] contactDescs An array of contact descs defining the pair and contact properties of each respective contacting pair
\param [in] allocator An allocator callback to allocate constraint and friction memory
\param [in] invDt The inverse timestep
\param [in] bounceThreshold The bounce threshold. Relative velocities below this will be solved by bias only. Relative velocities above this will be solved by restitution. If restitution is zero
then these pairs will always be solved by bias.
\param [in] frictionOffsetThreshold The friction offset threshold. Contacts whose separations are below this threshold can generate friction constraints.
\param [in] correlationDistance The correlation distance used by friction correlation to identify whether a friction patch is broken on the grounds of relation separation.
\param [out] Z Temporary buffer for impulse propagation.
\return a boolean to define if this method was successful or not.
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateContactConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverContactDesc* contactDescs,
PxConstraintAllocator& allocator, PxReal invDt, PxReal bounceThreshold, PxReal frictionOffsetThreshold, PxReal correlationDistance,
PxSpatialVector* Z = NULL);
/**
\brief Creates a set of joint constraint blocks. Note that, depending the results of PxBatchConstraints, the batchHeader may refer to up to 4 solverConstraintDescs
\param [in] batchHeaders The array of batch headers to be processed.
\param [in] nbHeaders The total number of batch headers to process.
\param [in] jointDescs An array of constraint prep descs defining the properties of the constraints being created.
\param [in] allocator An allocator callback to allocate constraint data.
\param [in] dt The timestep.
\param [in] invDt The inverse timestep.
\param [out] Z Temporary buffer for impulse propagation.
\return a boolean indicating if this method was successful or not.
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraints(PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxSpatialVector* Z, PxReal dt, PxReal invDt);
/**
\brief Creates a set of joint constraint blocks. This function runs joint shaders defined inside PxConstraint** param, fills in joint row information in jointDescs and then calls PxCreateJointConstraints.
\param [in] batchHeaders The set of batchHeaders to be processed.
\param [in] nbBatchHeaders The number of batch headers to process.
\param [in] constraints The set of constraints to be used to produce constraint rows.
\param [in,out] jointDescs An array of constraint prep descs defining the properties of the constraints being created.
\param [in] allocator An allocator callback to allocate constraint data.
\param [in] dt The timestep.
\param [in] invDt The inverse timestep.
\param [out] Z Temporary buffer for impulse propagation.
\return a boolean indicating if this method was successful or not.
@see PxCreateJointConstraints
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsWithShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, PxConstraint** constraints, PxSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z = NULL);
struct PxImmediateConstraint
{
PxConstraintSolverPrep prep;
const void* constantBlock;
};
/**
\brief Creates a set of joint constraint blocks. This function runs joint shaders defined inside PxImmediateConstraint* param, fills in joint row information in jointDescs and then calls PxCreateJointConstraints.
\param [in] batchHeaders The set of batchHeaders to be processed.
\param [in] nbBatchHeaders The number of batch headers to process.
\param [in] constraints The set of constraints to be used to produce constraint rows.
\param [in,out] jointDescs An array of constraint prep descs defining the properties of the constraints being created.
\param [in] allocator An allocator callback to allocate constraint data.
\param [in] dt The timestep.
\param [in] invDt The inverse timestep.
\param [out] Z Temporary buffer for impulse propagation.
\return a boolean indicating if this method was successful or not.
@see PxCreateJointConstraints
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsWithImmediateShaders(PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, PxImmediateConstraint* constraints, PxSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal invDt, PxSpatialVector* Z = NULL);
/**
\brief Iteratively solves the set of constraints defined by the provided PxConstraintBatchHeader and PxSolverConstraintDesc structures. Updates deltaVelocities inside the PxSolverBody structures. Produces resulting linear and angular motion velocities.
\param [in] batchHeaders The set of batch headers to be solved
\param [in] nbBatchHeaders The total number of batch headers to be solved
\param [in] solverConstraintDescs The reordererd set of solver constraint descs referenced by the batch headers
\param [in,out] solverBodies The set of solver bodies the bodies reference
\param [out] linearMotionVelocity The resulting linear motion velocity
\param [out] angularMotionVelocity The resulting angular motion velocity.
\param [in] nbSolverBodies The total number of solver bodies
\param [in] nbPositionIterations The number of position iterations to run
\param [in] nbVelocityIterations The number of velocity iterations to run
\param [in] dt Timestep. Only needed if articulations are sent to the function.
\param [in] invDt Inverse timestep. Only needed if articulations are sent to the function.
\param [in] nbSolverArticulations Number of articulations to solve constraints for.
\param [in] solverArticulations Array of articulations to solve constraints for.
\param [out] Z Temporary buffer for impulse propagation
\param [out] deltaV Temporary buffer for velocity change
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxSolveConstraints(const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs,
const PxSolverBody* solverBodies, PxVec3* linearMotionVelocity, PxVec3* angularMotionVelocity, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations,
float dt=0.0f, float invDt=0.0f, PxU32 nbSolverArticulations=0, PxArticulationHandle* solverArticulations=NULL, PxSpatialVector* Z = NULL, PxSpatialVector* deltaV = NULL);
/**
\brief Integrates a rigid body, returning the new velocities and transforms. After this function has been called, solverBodyData stores all the body's velocity data.
\param [in,out] solverBodyData The array of solver body data to be integrated
\param [in] solverBody The bodies' linear and angular velocities
\param [in] linearMotionVelocity The bodies' linear motion velocity array
\param [in] angularMotionState The bodies' angular motion velocity array
\param [in] nbBodiesToIntegrate The total number of bodies to integrate
\param [in] dt The timestep
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxIntegrateSolverBodies(PxSolverBodyData* solverBodyData, PxSolverBody* solverBody, const PxVec3* linearMotionVelocity, const PxVec3* angularMotionState, PxU32 nbBodiesToIntegrate, PxReal dt);
/**
\brief Performs contact generation for a given pair of geometries at the specified poses. Produced contacts are stored in the provided contact recorder. Information is cached in PxCache structure
to accelerate future contact generation between pairs. This cache data is valid only as long as the memory provided by PxCacheAllocator has not been released/re-used. Recommendation is to
retain that data for a single simulation frame, discarding cached data after 2 frames. If the cached memory has been released/re-used prior to the corresponding pair having contact generation
performed again, it is the application's responsibility to reset the PxCache.
\param [in] geom0 Array of geometries to perform collision detection on.
\param [in] geom1 Array of geometries to perform collision detection on
\param [in] pose0 Array of poses associated with the corresponding entry in the geom0 array
\param [in] pose1 Array of poses associated with the corresponding entry in the geom1 array
\param [in,out] contactCache Array of contact caches associated with each pair geom0[i] + geom1[i]
\param [in] nbPairs The total number of pairs to process
\param [out] contactRecorder A callback that is called to record contacts for each pair that detects contacts
\param [in] contactDistance The distance at which contacts begin to be generated between the pairs
\param [in] meshContactMargin The mesh contact margin.
\param [in] toleranceLength The toleranceLength. Used for scaling distance-based thresholds internally to produce appropriate results given simulations in different units
\param [in] allocator A callback to allocate memory for the contact cache
\return a boolean indicating if the function was successful or not.
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxGenerateContacts( const PxGeometry* const * geom0, const PxGeometry* const * geom1, const PxTransform* pose0, const PxTransform* pose1,
PxCache* contactCache, PxU32 nbPairs, PxContactRecorder& contactRecorder,
PxReal contactDistance, PxReal meshContactMargin, PxReal toleranceLength, PxCacheAllocator& allocator);
struct PxArticulationJointDataRC
{
PxTransform parentPose;
PxTransform childPose;
PxArticulationMotion::Enum motion[PxArticulationAxis::eCOUNT];
PxArticulationLimit limits[PxArticulationAxis::eCOUNT];
PxArticulationDrive drives[PxArticulationAxis::eCOUNT];
PxReal targetPos[PxArticulationAxis::eCOUNT];
PxReal targetVel[PxArticulationAxis::eCOUNT];
PxReal armature[PxArticulationAxis::eCOUNT];
PxReal jointPos[PxArticulationAxis::eCOUNT];
PxReal jointVel[PxArticulationAxis::eCOUNT];
PxReal frictionCoefficient;
PxReal maxJointVelocity;
PxArticulationJointType::Enum type;
void initData()
{
parentPose = PxTransform(PxIdentity);
childPose = PxTransform(PxIdentity);
frictionCoefficient = 0.05f;
maxJointVelocity = 100.0f;
type = PxArticulationJointType::eUNDEFINED; // For root
for(PxU32 i=0;i<PxArticulationAxis::eCOUNT;i++)
{
motion[i] = PxArticulationMotion::eLOCKED;
limits[i] = PxArticulationLimit(0.0f, 0.0f);
drives[i] = PxArticulationDrive(0.0f, 0.0f, 0.0f);
armature[i] = 0.0f;
jointPos[i] = 0.0f;
jointVel[i] = 0.0f;
}
PxMemSet(targetPos, 0xff, sizeof(PxReal)*PxArticulationAxis::eCOUNT);
PxMemSet(targetVel, 0xff, sizeof(PxReal)*PxArticulationAxis::eCOUNT);
}
};
struct PxArticulationDataRC
{
PxArticulationFlags flags;
};
struct PxArticulationLinkMutableDataRC
{
PxVec3 inverseInertia;
float inverseMass;
float linearDamping;
float angularDamping;
float maxLinearVelocitySq;
float maxAngularVelocitySq;
float cfmScale;
bool disableGravity;
void initData()
{
inverseInertia = PxVec3(1.0f);
inverseMass = 1.0f;
linearDamping = 0.05f;
angularDamping = 0.05f;
maxLinearVelocitySq = 100.0f * 100.0f;
maxAngularVelocitySq = 50.0f * 50.0f;
cfmScale = 0.025f;
disableGravity = false;
}
};
struct PxArticulationLinkDerivedDataRC
{
PxTransform pose;
PxVec3 linearVelocity;
PxVec3 angularVelocity;
};
struct PxArticulationLinkDataRC : PxArticulationLinkMutableDataRC
{
PxArticulationLinkDataRC() { PxArticulationLinkDataRC::initData(); }
void initData()
{
pose = PxTransform(PxIdentity);
PxArticulationLinkMutableDataRC::initData();
inboundJoint.initData();
}
PxArticulationJointDataRC inboundJoint;
PxTransform pose;
};
typedef void* PxArticulationCookie;
struct PxArticulationLinkCookie
{
PxArticulationCookie articulation;
PxU32 linkId;
};
struct PxCreateArticulationLinkCookie : PxArticulationLinkCookie
{
PX_FORCE_INLINE PxCreateArticulationLinkCookie(PxArticulationCookie art=NULL, PxU32 id=0xffffffff)
{
articulation = art;
linkId = id;
}
};
struct PxArticulationLinkHandle
{
PX_FORCE_INLINE PxArticulationLinkHandle(PxArticulationHandle art=NULL, PxU32 id=0xffffffff) : articulation(art), linkId(id) {}
PxArticulationHandle articulation;
PxU32 linkId;
};
/**
\brief Begin creation of an immediate-mode reduced-coordinate articulation.
Returned cookie must be used to add links to the articulation, and to complete creating the articulation.
The cookie is a temporary ID for the articulation, only valid until PxEndCreateArticulationRC is called.
\param [in] data Articulation data
\return Articulation cookie
@see PxAddArticulationLink PxEndCreateArticulationRC
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxArticulationCookie PxBeginCreateArticulationRC(const PxArticulationDataRC& data);
/**
\brief Add a link to the articulation.
All links must be added before the articulation is completed. It is not possible to add a new link at runtime.
Returned cookie is a temporary ID for the link, only valid until PxEndCreateArticulationRC is called.
\param [in] articulation Cookie value returned by PxBeginCreateArticulationRC
\param [in] parent Parent for the new link, or NULL if this is the root link
\param [in] data Link data
\return Link cookie
@see PxBeginCreateArticulationRC PxEndCreateArticulationRC
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxArticulationLinkCookie PxAddArticulationLink(PxArticulationCookie articulation, const PxArticulationLinkCookie* parent, const PxArticulationLinkDataRC& data);
/**
\brief End creation of an immediate-mode reduced-coordinate articulation.
This call completes the creation of the articulation. All involved cookies become unsafe to use after that point.
The links are actually created in this function, and it returns the actual link handles to users. The given buffer should be large enough
to contain as many links as created between the PxBeginCreateArticulationRC & PxEndCreateArticulationRC calls, i.e.
if N calls were made to PxAddArticulationLink, the buffer should be large enough to contain N handles.
\param [in] articulation Cookie value returned by PxBeginCreateArticulationRC
\param [out] linkHandles Articulation link handles of all created articulation links
\param [in] bufferSize Size of linkHandles buffer. Must match internal expected number of articulation links.
\return Articulation handle, or NULL if creation failed
@see PxAddArticulationLink PxEndCreateArticulationRC
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxArticulationHandle PxEndCreateArticulationRC(PxArticulationCookie articulation, PxArticulationLinkHandle* linkHandles, PxU32 bufferSize);
/**
\brief Releases an immediate-mode reduced-coordinate articulation.
\param [in] articulation Articulation handle
@see PxCreateFeatherstoneArticulation
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxReleaseArticulation(PxArticulationHandle articulation);
/**
\brief Creates an articulation cache.
\param [in] articulation Articulation handle
\return Articulation cache
@see PxReleaseArticulationCache
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxArticulationCache* PxCreateArticulationCache(PxArticulationHandle articulation);
/**
\brief Copy the internal data of the articulation to the cache
\param[in] articulation Articulation handle.
\param[in] cache Articulation data
\param[in] flag Indicates which values of the articulation system are copied to the cache
@see createCache PxApplyArticulationCache
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxCopyInternalStateToArticulationCache(PxArticulationHandle articulation, PxArticulationCache& cache, PxArticulationCacheFlags flag);
/**
\brief Apply the user defined data in the cache to the articulation system
\param[in] articulation Articulation handle.
\param[in] cache Articulation data.
\param[in] flag Defines which values in the cache will be applied to the articulation
@see createCache PxCopyInternalStateToArticulationCache
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxApplyArticulationCache(PxArticulationHandle articulation, PxArticulationCache& cache, PxArticulationCacheFlags flag);
/**
\brief Release an articulation cache
\param[in] cache The cache to release
@see PxCreateArticulationCache PxCopyInternalStateToArticulationCache PxCopyInternalStateToArticulationCache
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxReleaseArticulationCache(PxArticulationCache& cache);
/**
\brief Retrieves non-mutable link data from a link handle.
The data here is computed by the articulation code but cannot be directly changed by users.
\param [in] link Link handle
\param [out] data Link data
\return True if success
@see PxGetAllLinkData
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxGetLinkData(const PxArticulationLinkHandle& link, PxArticulationLinkDerivedDataRC& data);
/**
\brief Retrieves non-mutable link data from an articulation handle (all links).
The data here is computed by the articulation code but cannot be directly changed by users.
\param [in] articulation Articulation handle
\param [out] data Link data for N links, or NULL to just retrieve the number of links.
\return Number of links in the articulation = number of link data structure written to the data array.
@see PxGetLinkData
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxU32 PxGetAllLinkData(const PxArticulationHandle articulation, PxArticulationLinkDerivedDataRC* data);
/**
\brief Retrieves mutable link data from a link handle.
\param [in] link Link handle
\param [out] data Data for this link
\return True if success
@see PxSetMutableLinkData
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxGetMutableLinkData(const PxArticulationLinkHandle& link, PxArticulationLinkMutableDataRC& data);
/**
\brief Sets mutable link data for given link.
\param [in] link Link handle
\param [in] data Data for this link
\return True if success
@see PxGetMutableLinkData
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxSetMutableLinkData(const PxArticulationLinkHandle& link, const PxArticulationLinkMutableDataRC& data);
/**
\brief Retrieves joint data from a link handle.
\param [in] link Link handle
\param [out] data Joint data for this link
\return True if success
@see PxSetJointData
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxGetJointData(const PxArticulationLinkHandle& link, PxArticulationJointDataRC& data);
/**
\brief Sets joint data for given link.
\param [in] link Link handle
\param [in] data Joint data for this link
\return True if success
@see PxGetJointData
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxSetJointData(const PxArticulationLinkHandle& link, const PxArticulationJointDataRC& data);
/**
\brief Computes unconstrained velocities for a given articulation.
\param [in] articulation Articulation handle
\param [in] gravity Gravity vector
\param [in] dt Timestep
\param [in] invLengthScale 1/lengthScale from PxTolerancesScale.
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxComputeUnconstrainedVelocities(PxArticulationHandle articulation, const PxVec3& gravity, PxReal dt, PxReal invLengthScale);
/**
\brief Updates bodies for a given articulation.
\param [in] articulation Articulation handle
\param [in] dt Timestep
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxUpdateArticulationBodies(PxArticulationHandle articulation, PxReal dt);
/**
\brief Computes unconstrained velocities for a given articulation.
\param [in] articulation Articulation handle
\param [in] gravity Gravity vector
\param [in] dt Timestep/numPosIterations
\param [in] totalDt Timestep
\param [in] invDt 1/(Timestep/numPosIterations)
\param [in] invTotalDt 1/Timestep
\param [in] invLengthScale 1/lengthScale from PxTolerancesScale.
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxComputeUnconstrainedVelocitiesTGS( PxArticulationHandle articulation, const PxVec3& gravity, PxReal dt,
PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal invLengthScale);
/**
\brief Updates bodies for a given articulation.
\param [in] articulation Articulation handle
\param [in] dt Timestep
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxUpdateArticulationBodiesTGS(PxArticulationHandle articulation, PxReal dt);
/**
\brief Constructs a PxSolverBodyData structure based on rigid body properties. Applies gravity, damping and clamps maximum velocity.
\param [in] inRigidData The array rigid body properties
\param [out] outSolverBodyVel The array of PxTGSSolverBodyVel structures produced to represent these bodies
\param [out] outSolverBodyTxInertia The array of PxTGSSolverBodyTxInertia produced to represent these bodies
\param [out] outSolverBodyData The array of PxTGSolverBodyData produced to represent these bodies
\param [in] nbBodies The total number of solver bodies to create
\param [in] gravity The gravity vector
\param [in] dt The timestep
\param [in] gyroscopicForces Indicates whether gyroscopic forces should be integrated
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxConstructSolverBodiesTGS(const PxRigidBodyData* inRigidData, PxTGSSolverBodyVel* outSolverBodyVel, PxTGSSolverBodyTxInertia* outSolverBodyTxInertia, PxTGSSolverBodyData* outSolverBodyData, PxU32 nbBodies, const PxVec3& gravity, PxReal dt, bool gyroscopicForces = false);
/**
\brief Constructs a PxSolverBodyData structure for a static body at a given pose.
\param [in] globalPose The pose of this static actor
\param [out] solverBodyVel The velocity component of this body (will be zero)
\param [out] solverBodyTxInertia The intertia and transform delta component of this body (will be zero)
\param [out] solverBodyData The solver body representation of this static actor
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxConstructStaticSolverBodyTGS(const PxTransform& globalPose, PxTGSSolverBodyVel& solverBodyVel, PxTGSSolverBodyTxInertia& solverBodyTxInertia, PxTGSSolverBodyData& solverBodyData);
/**
\brief Groups together sets of independent PxSolverConstraintDesc objects to be solved using SIMD SOA approach.
\param [in] solverConstraintDescs The set of solver constraint descs to batch
\param [in] nbConstraints The number of constraints to batch
\param [in,out] solverBodies The array of solver bodies that the constraints reference. Some fields in these structures are written to as scratch memory for the batching.
\param [in] nbBodies The number of bodies
\param [out] outBatchHeaders The batch headers produced by this batching process. This array must have at least 1 entry per input constraint
\param [out] outOrderedConstraintDescs A reordered copy of the constraint descs. This array is referenced by the constraint batches. This array must have at least 1 entry per input constraint.
\param [in,out] articulations The array of articulations that the constraints reference. Some fields in these structures are written to as scratch memory for the batching.
\param [in] nbArticulations The number of articulations
\return The total number of batches produced. This should be less than or equal to nbConstraints.
\note This method considers all bodies within the range [0, nbBodies-1] to be valid dynamic bodies. A given dynamic body can only be referenced in a batch once. Static or kinematic bodies can be
referenced multiple times within a batch safely because constraints do not affect their velocities. The batching will implicitly consider any bodies outside of the range [0, nbBodies-1] to be
infinite mass (static or kinematic). This means that either appending static/kinematic to the end of the array of bodies or placing static/kinematic bodies at before the start body pointer
will ensure that the minimum number of batches are produced.
*/
PX_C_EXPORT PX_PHYSX_CORE_API PxU32 PxBatchConstraintsTGS( const PxSolverConstraintDesc* solverConstraintDescs, PxU32 nbConstraints, PxTGSSolverBodyVel* solverBodies, PxU32 nbBodies,
PxConstraintBatchHeader* outBatchHeaders, PxSolverConstraintDesc* outOrderedConstraintDescs,
PxArticulationHandle* articulations = NULL, PxU32 nbArticulations = 0);
/**
\brief Creates a set of contact constraint blocks. Note that, depending the results of PxBatchConstraints, each batchHeader may refer to up to 4 solverConstraintDescs.
This function will allocate both constraint and friction patch data via the PxConstraintAllocator provided. Constraint data is only valid until PxSolveConstraints has completed.
Friction data is to be retained and provided by the application for friction correlation.
\param [in] batchHeaders Array of batch headers to process
\param [in] nbHeaders The total number of headers
\param [in] contactDescs An array of contact descs defining the pair and contact properties of each respective contacting pair
\param [in] allocator An allocator callback to allocate constraint and friction memory
\param [in] invDt The inverse timestep/nbPositionIterations
\param [in] invTotalDt The inverse time-step
\param [in] bounceThreshold The bounce threshold. Relative velocities below this will be solved by bias only. Relative velocities above this will be solved by restitution. If restitution is zero
then these pairs will always be solved by bias.
\param [in] frictionOffsetThreshold The friction offset threshold. Contacts whose separations are below this threshold can generate friction constraints.
\param [in] correlationDistance The correlation distance used by friction correlation to identify whether a friction patch is broken on the grounds of relation separation.
\return a boolean to define if this method was successful or not.
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateContactConstraintsTGS( PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders, PxTGSSolverContactDesc* contactDescs,
PxConstraintAllocator& allocator, PxReal invDt, PxReal invTotalDt, PxReal bounceThreshold,
PxReal frictionOffsetThreshold, PxReal correlationDistance);
/**
\brief Creates a set of joint constraint blocks. Note that, depending the results of PxBatchConstraints, the batchHeader may refer to up to 4 solverConstraintDescs
\param [in] batchHeaders The array of batch headers to be processed
\param [in] nbHeaders The total number of batch headers to process
\param [in] jointDescs An array of constraint prep descs defining the properties of the constraints being created
\param [in] allocator An allocator callback to allocate constraint data
\param [in] dt The total time-step/nbPositionIterations
\param [in] totalDt The total time-step
\param [in] invDt The inverse (timestep/nbPositionIterations)
\param [in] invTotalDt The inverse total time-step
\param [in] lengthScale PxToleranceScale::length, i.e. a meter in simulation units
\return a boolean indicating if this method was successful or not.
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsTGS( PxConstraintBatchHeader* batchHeaders, PxU32 nbHeaders,
PxTGSSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt,
PxReal invTotalDt, PxReal lengthScale);
/**
\brief Creates a set of joint constraint blocks. This function runs joint shaders defined inside PxConstraint** param, fills in joint row information in jointDescs and then calls PxCreateJointConstraints.
\param [in] batchHeaders The set of batchHeaders to be processed
\param [in] nbBatchHeaders The number of batch headers to process.
\param [in] constraints The set of constraints to be used to produce constraint rows
\param [in,out] jointDescs An array of constraint prep descs defining the properties of the constraints being created
\param [in] allocator An allocator callback to allocate constraint data
\param [in] dt The total time-step/nbPositionIterations
\param [in] totalDt The total time-step
\param [in] invDt The inverse (timestep/nbPositionIterations)
\param [in] invTotalDt The inverse total time-step
\param [in] lengthScale PxToleranceScale::length, i.e. a meter in simulation units
\return a boolean indicating if this method was successful or not.
@see PxCreateJointConstraints
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsWithShadersTGS( PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, PxConstraint** constraints, PxTGSSolverConstraintPrepDesc* jointDescs, PxConstraintAllocator& allocator,
PxReal dt, PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal lengthScale);
/**
\brief Creates a set of joint constraint blocks. This function runs joint shaders defined inside PxImmediateConstraint* param, fills in joint row information in jointDescs and then calls PxCreateJointConstraints.
\param [in] batchHeaders The set of batchHeaders to be processed
\param [in] nbBatchHeaders The number of batch headers to process.
\param [in] constraints The set of constraints to be used to produce constraint rows
\param [in,out] jointDescs An array of constraint prep descs defining the properties of the constraints being created
\param [in] allocator An allocator callback to allocate constraint data
\param [in] dt The total time-step/nbPositionIterations
\param [in] totalDt The total time-step
\param [in] invDt The inverse (timestep/nbPositionIterations)
\param [in] invTotalDt The inverse total time-step
\param [in] lengthScale PxToleranceScale::length, i.e. a meter in simulation units
\return a boolean indicating if this method was successful or not.
@see PxCreateJointConstraints
*/
PX_C_EXPORT PX_PHYSX_CORE_API bool PxCreateJointConstraintsWithImmediateShadersTGS(PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, PxImmediateConstraint* constraints, PxTGSSolverConstraintPrepDesc* jointDescs,
PxConstraintAllocator& allocator, PxReal dt, PxReal totalDt, PxReal invDt, PxReal invTotalDt, PxReal lengthScale);
/**
\brief Iteratively solves the set of constraints defined by the provided PxConstraintBatchHeader and PxSolverConstraintDesc structures. Updates deltaVelocities inside the PxSolverBody structures. Produces resulting linear and angular motion velocities.
\param [in] batchHeaders The set of batch headers to be solved
\param [in] nbBatchHeaders The total number of batch headers to be solved
\param [in] solverConstraintDescs The reordererd set of solver constraint descs referenced by the batch headers
\param [in,out] solverBodies The set of solver bodies the bodies reference
\param [in,out] txInertias The set of solver body TxInertias the bodies reference
\param [in] nbSolverBodies The total number of solver bodies
\param [in] nbPositionIterations The number of position iterations to run
\param [in] nbVelocityIterations The number of velocity iterations to run
\param [in] dt time-step/nbPositionIterations
\param [in] invDt 1/(time-step/nbPositionIterations)
\param [in] nbSolverArticulations Number of articulations to solve constraints for.
\param [in] solverArticulations Array of articulations to solve constraints for.
\param [out] Z Temporary buffer for impulse propagation (only if articulations are used, size should be at least as large as the maximum number of links in any articulations being simulated)
\param [out] deltaV Temporary buffer for velocity change (only if articulations are used, size should be at least as large as the maximum number of links in any articulations being simulated)
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxSolveConstraintsTGS( const PxConstraintBatchHeader* batchHeaders, PxU32 nbBatchHeaders, const PxSolverConstraintDesc* solverConstraintDescs,
PxTGSSolverBodyVel* solverBodies, PxTGSSolverBodyTxInertia* txInertias, PxU32 nbSolverBodies, PxU32 nbPositionIterations, PxU32 nbVelocityIterations,
float dt, float invDt, PxU32 nbSolverArticulations = 0, PxArticulationHandle* solverArticulations = NULL, PxSpatialVector* Z = NULL, PxSpatialVector* deltaV = NULL);
/**
\brief Integrates a rigid body, returning the new velocities and transforms. After this function has been called, solverBody stores all the body's velocity data.
\param [in,out] solverBody The array of solver bodies to be integrated
\param [in] txInertia The delta pose and inertia terms
\param [in,out] poses The original poses of the bodies. Updated to be the new poses of the bodies
\param [in] nbBodiesToIntegrate The total number of bodies to integrate
\param [in] dt The timestep
*/
PX_C_EXPORT PX_PHYSX_CORE_API void PxIntegrateSolverBodiesTGS(PxTGSSolverBodyVel* solverBody, PxTGSSolverBodyTxInertia* txInertia, PxTransform* poses, PxU32 nbBodiesToIntegrate, PxReal dt);
#if !PX_DOXYGEN
}
#endif
#if !PX_DOXYGEN
}
#endif
/** @} */
#endif
| 40,881 | C | 54.02288 | 308 | 0.784325 |
NVIDIA-Omniverse/PhysX/physx/include/PxConstraintDesc.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_CONSTRAINT_DESC_H
#define PX_CONSTRAINT_DESC_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#include "foundation/PxVec3.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx { namespace pvdsdk {
#endif
class PvdDataStream;
#if !PX_DOXYGEN
}}
#endif
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Constraint row flags
These flags configure the post-processing of constraint rows and the behavior of the solver while solving constraints
*/
struct Px1DConstraintFlag
{
PX_CUDA_CALLABLE Px1DConstraintFlag(){}
enum Type
{
eSPRING = 1<<0, //!< whether the constraint is a spring. Mutually exclusive with eRESTITUTION. If set, eKEEPBIAS is ignored.
eACCELERATION_SPRING = 1<<1, //!< whether the constraint is a force or acceleration spring. Only valid if eSPRING is set.
eRESTITUTION = 1<<2, //!< whether the restitution model should be applied to generate the target velocity. Mutually exclusive with eSPRING. If restitution causes a bounces, eKEEPBIAS is ignored
eKEEPBIAS = 1<<3, //!< whether to keep the error term when solving for velocity. Ignored if restitution generates bounce, or eSPRING is set.
eOUTPUT_FORCE = 1<<4, //!< whether to accumulate the force value from this constraint in the force total that is reported for the constraint and tested for breakage
eHAS_DRIVE_LIMIT = 1<<5, //!< whether the constraint has a drive force limit (which will be scaled by dt unless PxConstraintFlag::eLIMITS_ARE_FORCES is set)
eANGULAR_CONSTRAINT = 1<<6, //!< whether this is an angular or linear constraint
eDEPRECATED_DRIVE_ROW = 1<<7 //!< whether the constraint's geometric error should drive the target velocity
};
};
typedef PxFlags<Px1DConstraintFlag::Type, PxU16> Px1DConstraintFlags;
PX_FLAGS_OPERATORS(Px1DConstraintFlag::Type, PxU16)
/**
\brief Constraint type hints which the solver uses to optimize constraint handling
*/
struct PxConstraintSolveHint
{
enum Enum
{
eNONE = 0, //!< no special properties
eACCELERATION1 = 256, //!< a group of acceleration drive constraints with the same stiffness and drive parameters
eSLERP_SPRING = 258, //!< temporary special value to identify SLERP drive rows
eACCELERATION2 = 512, //!< a group of acceleration drive constraints with the same stiffness and drive parameters
eACCELERATION3 = 768, //!< a group of acceleration drive constraints with the same stiffness and drive parameters
eROTATIONAL_EQUALITY = 1024, //!< rotational equality constraints with no force limit and no velocity target
eROTATIONAL_INEQUALITY = 1025, //!< rotational inequality constraints with (0, PX_MAX_FLT) force limits
eEQUALITY = 2048, //!< equality constraints with no force limit and no velocity target
eINEQUALITY = 2049 //!< inequality constraints with (0, PX_MAX_FLT) force limits
};
};
/**
\brief A one-dimensional constraint
A constraint is expressed as a set of 1-dimensional constraint rows which define the required constraint
on the objects' velocities.
Each constraint is either a hard constraint or a spring. We define the velocity at the constraint to be
the quantity
v = body0vel.dot(lin0,ang0) - body1vel.dot(lin1, ang1)
For a hard constraint, the solver attempts to generate
1. a set of velocities for the objects which, when integrated, respect the constraint errors:
v + (geometricError / timestep) = velocityTarget
2. a set of velocities for the objects which respect the constraints:
v = velocityTarget
Hard constraints support restitution: if the impact velocity exceeds the bounce threshold, then the target velocity
of the constraint will be set to restitution * -v
Alternatively, the solver can attempt to resolve the velocity constraint as an implicit spring:
F = stiffness * -geometricError + damping * (velocityTarget - v)
where F is the constraint force or acceleration. Springs are fully implicit: that is, the force or acceleration
is a function of the position and velocity after the solve.
All constraints support limits on the minimum or maximum impulse applied.
*/
PX_ALIGN_PREFIX(16)
struct Px1DConstraint
{
PxVec3 linear0; //!< linear component of velocity jacobian in world space
PxReal geometricError; //!< geometric error of the constraint along this axis
PxVec3 angular0; //!< angular component of velocity jacobian in world space
PxReal velocityTarget; //!< velocity target for the constraint along this axis
PxVec3 linear1; //!< linear component of velocity jacobian in world space
PxReal minImpulse; //!< minimum impulse the solver may apply to enforce this constraint
PxVec3 angular1; //!< angular component of velocity jacobian in world space
PxReal maxImpulse; //!< maximum impulse the solver may apply to enforce this constraint
union
{
struct SpringModifiers
{
PxReal stiffness; //!< spring parameter, for spring constraints
PxReal damping; //!< damping parameter, for spring constraints
} spring;
struct RestitutionModifiers
{
PxReal restitution; //!< restitution parameter for determining additional "bounce"
PxReal velocityThreshold; //!< minimum impact velocity for bounce
} bounce;
} mods;
PxReal forInternalUse; //!< for internal use only
PxU16 flags; //!< a set of Px1DConstraintFlags
PxU16 solveHint; //!< constraint optimization hint, should be an element of PxConstraintSolveHint
}
PX_ALIGN_SUFFIX(16);
/**
\brief Flags for determining which components of the constraint should be visualized.
@see PxConstraintVisualize
*/
struct PxConstraintVisualizationFlag
{
enum Enum
{
eLOCAL_FRAMES = 1, //!< visualize constraint frames
eLIMITS = 2 //!< visualize constraint limits
};
};
/**
\brief Struct for specifying mass scaling for a pair of rigids
*/
PX_ALIGN_PREFIX(16)
struct PxConstraintInvMassScale
{
PxReal linear0; //!< multiplier for inverse mass of body0
PxReal angular0; //!< multiplier for inverse MoI of body0
PxReal linear1; //!< multiplier for inverse mass of body1
PxReal angular1; //!< multiplier for inverse MoI of body1
PX_CUDA_CALLABLE PX_FORCE_INLINE PxConstraintInvMassScale(){}
PX_CUDA_CALLABLE PX_FORCE_INLINE PxConstraintInvMassScale(PxReal lin0, PxReal ang0, PxReal lin1, PxReal ang1) : linear0(lin0), angular0(ang0), linear1(lin1), angular1(ang1){}
}
PX_ALIGN_SUFFIX(16);
/**
\brief Solver constraint generation shader
This function is called by the constraint solver framework. The function must be reentrant, since it may be called simultaneously
from multiple threads, and should access only the arguments passed into it.
Developers writing custom constraints are encouraged to read the documentation in the user guide and the implementation code in PhysXExtensions.
\param[out] constraints An array of solver constraint rows to be filled in
\param[out] bodyAWorldOffset The origin point (offset from the position vector of bodyA's center of mass) at which the constraint is resolved. This value does not affect how constraints are solved, only the constraint force reported.
\param[in] maxConstraints The size of the constraint buffer. At most this many constraints rows may be written
\param[out] invMassScale The inverse mass and inertia scales for the constraint
\param[in] constantBlock The constant data block
\param[in] bodyAToWorld The center of mass frame of the first constrained body (the identity transform if the first actor is static, or if a NULL actor pointer was provided for it)
\param[in] bodyBToWorld The center of mass frame of the second constrained body (the identity transform if the second actor is static, or if a NULL actor pointer was provided for it)
\param[in] useExtendedLimits Enables limit ranges outside of (-PI, PI)
\param[out] cAtW The world space location of body A's joint frame (position only)
\param[out] cBtW The world space location of body B's joint frame (position only)
\return the number of constraint rows written.
*/
typedef PxU32 (*PxConstraintSolverPrep)(Px1DConstraint* constraints,
PxVec3p& bodyAWorldOffset,
PxU32 maxConstraints,
PxConstraintInvMassScale& invMassScale,
const void* constantBlock,
const PxTransform& bodyAToWorld,
const PxTransform& bodyBToWorld,
bool useExtendedLimits,
PxVec3p& cAtW,
PxVec3p& cBtW);
/**
\brief API used to visualize details about a constraint.
*/
class PxConstraintVisualizer
{
protected:
virtual ~PxConstraintVisualizer(){}
public:
/** \brief Visualize joint frames
\param[in] parent Parent transformation
\param[in] child Child transformation
*/
virtual void visualizeJointFrames(const PxTransform& parent, const PxTransform& child) = 0;
/** \brief Visualize joint linear limit
\param[in] t0 Base transformation
\param[in] t1 End transformation
\param[in] value Distance
*/
virtual void visualizeLinearLimit(const PxTransform& t0, const PxTransform& t1, PxReal value) = 0;
/** \brief Visualize joint angular limit
\param[in] t0 Transformation for the visualization
\param[in] lower Lower limit angle
\param[in] upper Upper limit angle
*/
virtual void visualizeAngularLimit(const PxTransform& t0, PxReal lower, PxReal upper) = 0;
/** \brief Visualize limit cone
\param[in] t Transformation for the visualization
\param[in] tanQSwingY Tangent of the quarter Y angle
\param[in] tanQSwingZ Tangent of the quarter Z angle
*/
virtual void visualizeLimitCone(const PxTransform& t, PxReal tanQSwingY, PxReal tanQSwingZ) = 0;
/** \brief Visualize joint double cone
\param[in] t Transformation for the visualization
\param[in] angle Limit angle
*/
virtual void visualizeDoubleCone(const PxTransform& t, PxReal angle) = 0;
/** \brief Visualize line
\param[in] p0 Start position
\param[in] p1 End postion
\param[in] color Color
*/
virtual void visualizeLine(const PxVec3& p0, const PxVec3& p1, PxU32 color) = 0;
};
/** \brief Solver constraint visualization function
This function is called by the constraint post-solver framework to visualize the constraint
\param[out] visualizer The render buffer to render to
\param[in] constantBlock The constant data block
\param[in] body0Transform The center of mass frame of the first constrained body (the identity if the actor is static, or a NULL pointer was provided for it)
\param[in] body1Transform The center of mass frame of the second constrained body (the identity if the actor is static, or a NULL pointer was provided for it)
\param[in] flags The visualization flags (PxConstraintVisualizationFlag)
@see PxRenderBuffer
*/
typedef void (*PxConstraintVisualize)(PxConstraintVisualizer& visualizer,
const void* constantBlock,
const PxTransform& body0Transform,
const PxTransform& body1Transform,
PxU32 flags);
/**
\brief Flags for determining how PVD should serialize a constraint update
@see PxConstraintConnector::updatePvdProperties, PvdSceneClient::updateConstraint
*/
struct PxPvdUpdateType
{
enum Enum
{
CREATE_INSTANCE, //!< triggers createPvdInstance call, creates an instance of a constraint
RELEASE_INSTANCE, //!< triggers releasePvdInstance call, releases an instance of a constraint
UPDATE_ALL_PROPERTIES, //!< triggers updatePvdProperties call, updates all properties of a constraint
UPDATE_SIM_PROPERTIES //!< triggers simUpdate call, updates all simulation properties of a constraint
};
};
/**
\brief This class connects a custom constraint to the SDK
This class connects a custom constraint to the SDK, and functions are called by the SDK
to query the custom implementation for specific information to pass on to the application
or inform the constraint when the application makes calls into the SDK which will update
the custom constraint's internal implementation
*/
class PxConstraintConnector
{
public:
/** \brief Pre-simulation data preparation
when the constraint is marked dirty, this function is called at the start of the simulation
step for the SDK to copy the constraint data block.
*/
virtual void* prepareData() = 0;
/**
\brief this function is called by the SDK to update PVD's view of it
*/
virtual bool updatePvdProperties(physx::pvdsdk::PvdDataStream& pvdConnection,
const PxConstraint* c,
PxPvdUpdateType::Enum updateType) const = 0;
/**
\brief this function is called by the SDK to update OmniPVD's view of it
*/
virtual void updateOmniPvdProperties() const = 0;
/**
\brief Constraint release callback
When the SDK deletes a PxConstraint object this function is called by the SDK. In general
custom constraints should not be deleted directly by applications: rather, the constraint
should respond to a release() request by calling PxConstraint::release(), then wait for
this call to release its own resources.
This function is also called when a PxConstraint object is deleted on cleanup due to
destruction of the PxPhysics object.
*/
virtual void onConstraintRelease() = 0;
/**
\brief Center-of-mass shift callback
This function is called by the SDK when the CoM of one of the actors is moved. Since the
API specifies constraint positions relative to actors, and the constraint shader functions
are supplied with coordinates relative to bodies, some synchronization is usually required
when the application moves an object's center of mass.
*/
virtual void onComShift(PxU32 actor) = 0;
/**
\brief Origin shift callback
This function is called by the SDK when the scene origin gets shifted and allows to adjust
custom data which contains world space transforms.
\note If the adjustments affect constraint shader data, it is necessary to call PxConstraint::markDirty()
to make sure that the data gets synced at the beginning of the next simulation step.
\param[in] shift Translation vector the origin is shifted by.
@see PxScene.shiftOrigin()
*/
virtual void onOriginShift(const PxVec3& shift) = 0;
/**
\brief Fetches external data for a constraint.
This function is used by the SDK to acquire a reference to the owner of a constraint and a unique
owner type ID. This information will be passed on when a breakable constraint breaks or when
#PxConstraint::getExternalReference() is called.
\param[out] typeID Unique type identifier of the external object. The value 0xffffffff is reserved and should not be used. Furthermore, if the PhysX extensions library is used, some other IDs are reserved already (see PxConstraintExtIDs)
\return Reference to the external object which owns the constraint.
@see PxConstraintInfo PxSimulationEventCallback.onConstraintBreak()
*/
virtual void* getExternalReference(PxU32& typeID) = 0;
/**
\brief Obtain a reference to a PxBase interface if the constraint has one.
If the constraint does not implement the PxBase interface, it should return NULL.
*/
virtual PxBase* getSerializable() = 0;
/**
\brief Obtain the shader function pointer used to prep rows for this constraint
*/
virtual PxConstraintSolverPrep getPrep() const = 0;
/**
\brief Obtain the pointer to the constraint's constant data
*/
virtual const void* getConstantBlock() const = 0;
/**
\brief Let the connector know it has been connected to a constraint.
*/
virtual void connectToConstraint(PxConstraint*) {}
/**
\brief virtual destructor
*/
virtual ~PxConstraintConnector() {}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 17,167 | C | 38.832947 | 238 | 0.759189 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationFlag.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_FLAG_H
#define PX_ARTICULATION_FLAG_H
#include "PxPhysXConfig.h"
#include "foundation/PxFlags.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A description of the types of articulation data that may be directly written to and read from the GPU using the functions
PxScene::copyArticulationData() and PxScene::applyArticulationData(). Types that are read-only may only be used in conjunction with
PxScene::copyArticulationData(). Types that are write-only may only be used in conjunction with PxScene::applyArticulationData().
A subset of data types may be used in conjunction with both PxScene::applyArticulationData() and PxScene::applyArticulationData().
@see PxArticulationCache, PxScene::copyArticulationData(), PxScene::applyArticulationData()
*/
class PxArticulationGpuDataType
{
public:
enum Enum
{
eJOINT_POSITION = 0, //!< The joint positions, read and write, see PxScene::copyArticulationData(), PxScene::applyArticulationData()
eJOINT_VELOCITY, //!< The joint velocities, read and write, see PxScene::copyArticulationData(), PxScene::applyArticulationData()
eJOINT_ACCELERATION, //!< The joint accelerations, read only, see PxScene::copyArticulationData()
eJOINT_FORCE, //!< The applied joint forces, write only, see PxScene::applyArticulationData()
eJOINT_SOLVER_FORCE, //!< @deprecated The computed joint constraint solver forces, read only, see PxScene::copyArticulationData()
eJOINT_TARGET_VELOCITY, //!< The velocity targets for the joint drives, write only, see PxScene::applyArticulationData()
eJOINT_TARGET_POSITION, //!< The position targets for the joint drives, write only, see PxScene::applyArticulationData()
eSENSOR_FORCE, //!< @deprecated The spatial sensor forces, read only, see PxScene::copyArticulationData()
eROOT_TRANSFORM, //!< The root link transform, read and write, see PxScene::copyArticulationData(), PxScene::applyArticulationData()
eROOT_VELOCITY, //!< The root link velocity, read and write, see PxScene::copyArticulationData(), PxScene::applyArticulationData()
eLINK_TRANSFORM, //!< The link transforms including root link, read only, see PxScene::copyArticulationData()
eLINK_VELOCITY, //!< The link velocities including root link, read only, see PxScene::copyArticulationData()
eLINK_ACCELERATION, //!< The link accelerations including root link, read only, see PxScene::copyArticulationData()
eLINK_INCOMING_JOINT_FORCE, //!< The link incoming joint forces including root link, read only, see PxScene::copyArticulationData()
eLINK_FORCE, //!< The forces to apply to links, write only, see PxScene::applyArticulationData()
eLINK_TORQUE, //!< The torques to apply to links, write only, see PxScene::applyArticulationData()
eFIXED_TENDON, //!< Fixed tendon data, write only, see PxScene::applyArticulationData()
eFIXED_TENDON_JOINT, //!< Fixed tendon joint data, write only, see PxScene::applyArticulationData()
eSPATIAL_TENDON, //!< Spatial tendon data, write only, see PxScene::applyArticulationData()
eSPATIAL_TENDON_ATTACHMENT //!< Spatial tendon attachment data, write only, see PxScene::applyArticulationData()
};
};
/**
\brief These flags determine what data is read or written to the internal articulation data via cache.
@see PxArticulationCache PxArticulationReducedCoordinate::copyInternalStateToCache PxArticulationReducedCoordinate::applyCache
*/
class PxArticulationCacheFlag
{
public:
enum Enum
{
eVELOCITY = (1 << 0), //!< The joint velocities, see PxArticulationCache::jointVelocity.
eACCELERATION = (1 << 1), //!< The joint accelerations, see PxArticulationCache::jointAcceleration.
ePOSITION = (1 << 2), //!< The joint positions, see PxArticulationCache::jointPosition.
eFORCE = (1 << 3), //!< The joint forces, see PxArticulationCache::jointForce.
eLINK_VELOCITY = (1 << 4), //!< The link velocities, see PxArticulationCache::linkVelocity.
eLINK_ACCELERATION = (1 << 5), //!< The link accelerations, see PxArticulationCache::linkAcceleration.
eROOT_TRANSFORM = (1 << 6), //!< Root link transform, see PxArticulationCache::rootLinkData.
eROOT_VELOCITIES = (1 << 7), //!< Root link velocities (read/write) and accelerations (read), see PxArticulationCache::rootLinkData.
eSENSOR_FORCES = (1 << 8), //!< @deprecated The spatial sensor forces, see PxArticulationCache::sensorForces.
eJOINT_SOLVER_FORCES = (1 << 9), //!< @deprecated Solver constraint joint forces, see PxArticulationCache::jointSolverForces.
eLINK_INCOMING_JOINT_FORCE = (1 << 10), //!< Link incoming joint forces, see PxArticulationCache::linkIncomingJointForce.
eJOINT_TARGET_POSITIONS = (1 << 11), //!< The joint target positions, see PxArticulationCache::jointTargetPositions.
eJOINT_TARGET_VELOCITIES = (1 << 12), //!< The joint target velocities, see PxArticulationCache::jointTargetVelocities.
eALL = (eVELOCITY | eACCELERATION | ePOSITION | eLINK_VELOCITY | eLINK_ACCELERATION | eROOT_TRANSFORM | eROOT_VELOCITIES)
};
};
typedef PxFlags<PxArticulationCacheFlag::Enum, PxU32> PxArticulationCacheFlags;
PX_FLAGS_OPERATORS(PxArticulationCacheFlag::Enum, PxU32)
#if !PX_DOXYGEN
}
#endif
#endif
| 6,977 | C | 61.303571 | 138 | 0.748316 |
NVIDIA-Omniverse/PhysX/physx/include/PxPBDMaterial.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PBD_MATERIAL_H
#define PX_PBD_MATERIAL_H
/** \addtogroup physics
@{
*/
#include "PxParticleMaterial.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxScene;
/**
\brief Material class to represent a set of PBD particle material properties.
@see #PxPhysics.createPBDMaterial
*/
class PxPBDMaterial : public PxParticleMaterial
{
public:
/**
\brief Sets viscosity
\param[in] viscosity Viscosity. <b>Range:</b> [0, PX_MAX_F32)
@see #getViscosity()
*/
virtual void setViscosity(PxReal viscosity) = 0;
/**
\brief Retrieves the viscosity value.
\return The viscosity value.
@see #setViscosity()
*/
virtual PxReal getViscosity() const = 0;
/**
\brief Sets material vorticity confinement coefficient
\param[in] vorticityConfinement Material vorticity confinement coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getVorticityConfinement()
*/
virtual void setVorticityConfinement(PxReal vorticityConfinement) = 0;
/**
\brief Retrieves the vorticity confinement coefficient.
\return The vorticity confinement coefficient.
@see #setVorticityConfinement()
*/
virtual PxReal getVorticityConfinement() const = 0;
/**
\brief Sets material surface tension coefficient
\param[in] surfaceTension Material surface tension coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getSurfaceTension()
*/
virtual void setSurfaceTension(PxReal surfaceTension) = 0;
/**
\brief Retrieves the surface tension coefficient.
\return The surface tension coefficient.
@see #setSurfaceTension()
*/
virtual PxReal getSurfaceTension() const = 0;
/**
\brief Sets material cohesion coefficient
\param[in] cohesion Material cohesion coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getCohesion()
*/
virtual void setCohesion(PxReal cohesion) = 0;
/**
\brief Retrieves the cohesion coefficient.
\return The cohesion coefficient.
@see #setCohesion()
*/
virtual PxReal getCohesion() const = 0;
/**
\brief Sets material lift coefficient
\param[in] lift Material lift coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getLift()
*/
virtual void setLift(PxReal lift) = 0;
/**
\brief Retrieves the lift coefficient.
\return The lift coefficient.
@see #setLift()
*/
virtual PxReal getLift() const = 0;
/**
\brief Sets material drag coefficient
\param[in] drag Material drag coefficient. <b>Range:</b> [0, PX_MAX_F32)
@see #getDrag()
*/
virtual void setDrag(PxReal drag) = 0;
/**
\brief Retrieves the drag coefficient.
\return The drag coefficient.
@see #setDrag()
*/
virtual PxReal getDrag() const = 0;
/**
\brief Sets the CFL coefficient.
\param[in] coefficient CFL coefficient. This coefficient scales the CFL term used to limit relative motion between fluid particles. <b>Range:</b> [1.f, PX_MAX_F32)
*/
virtual void setCFLCoefficient(PxReal coefficient) = 0;
/**
\brief Retrieves the CFL coefficient.
\return The CFL coefficient.
@see #setCFLCoefficient()
*/
virtual PxReal getCFLCoefficient() const = 0;
/**
\brief Sets material particle friction scale. This allows the application to scale up/down the frictional effect between particles independent of the friction
coefficient, which also defines frictional behavior between the particle and rigid bodies/soft bodies/cloth etc.
\param[in] scale particle friction scale. <b>Range:</b> [0, PX_MAX_F32)
@see #getParticleFrictionScale()
*/
virtual void setParticleFrictionScale(PxReal scale) = 0;
/**
\brief Retrieves the particle friction scale.
\return The particle friction scale.
@see #setParticleFrictionScale()
*/
virtual PxReal getParticleFrictionScale() const = 0;
/**
\brief Sets material particle adhesion scale value. This is the adhesive value between particles defined as a scaled multiple of the adhesion parameter.
\param[in] adhesion particle adhesion scale value. <b>Range:</b> [0, PX_MAX_F32)
@see #getParticleAdhesionScale()
*/
virtual void setParticleAdhesionScale(PxReal adhesion) = 0;
/**
\brief Retrieves the particle adhesion scale value.
\return The particle adhesion scale value.
@see #setParticleAdhesionScale()
*/
virtual PxReal getParticleAdhesionScale() const = 0;
virtual const char* getConcreteTypeName() const { return "PxPBDMaterial"; }
protected:
PX_INLINE PxPBDMaterial(PxType concreteType, PxBaseFlags baseFlags) : PxParticleMaterial(concreteType, baseFlags) {}
PX_INLINE PxPBDMaterial(PxBaseFlags baseFlags) : PxParticleMaterial(baseFlags) {}
virtual ~PxPBDMaterial() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxPBDMaterial", PxParticleMaterial); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,508 | C | 28.721461 | 165 | 0.725722 |
NVIDIA-Omniverse/PhysX/physx/include/PxPruningStructure.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_PRUNING_STRUCTURE_H
#define PX_PRUNING_STRUCTURE_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief A precomputed pruning structure to accelerate scene queries against newly added actors.
The pruning structure can be provided to #PxScene:: addActors() in which case it will get merged
directly into the scene query optimization AABB tree, thus leading to improved performance when
doing queries against the newly added actors. This applies to both static and dynamic actors.
\note PxPruningStructure objects can be added to a collection and get serialized.
\note Adding a PxPruningStructure object to a collection will also add the actors that were used to build the pruning structure.
\note PxPruningStructure must be released before its rigid actors.
\note PxRigidBody objects can be in one PxPruningStructure only.
\note Changing the bounds of PxRigidBody objects assigned to a pruning structure that has not been added to a scene yet will
invalidate the pruning structure. Same happens if shape scene query flags change or shape gets removed from an actor.
@see PxScene::addActors PxCollection
*/
class PxPruningStructure : public PxBase
{
public:
/**
\brief Release this object.
*/
virtual void release() = 0;
/**
\brief Retrieve rigid actors in the pruning structure.
You can retrieve the number of rigid actor pointers by calling #getNbRigidActors()
\param[out] userBuffer The buffer to store the actor pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first actor pointer to be retrieved
\return Number of rigid actor pointers written to the buffer.
@see PxRigidActor
*/
virtual PxU32 getRigidActors(PxRigidActor** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Returns the number of rigid actors in the pruning structure.
You can use #getRigidActors() to retrieve the rigid actor pointers.
\return Number of rigid actors in the pruning structure.
@see PxRigidActor
*/
virtual PxU32 getNbRigidActors() const = 0;
/**
\brief Gets the merge data for static actors
This is mainly called by the PxSceneQuerySystem::merge() function to merge a PxPruningStructure
with the internal data-structures of the scene-query system.
\return Implementation-dependent merge data for static actors.
@see PxSceneQuerySystem::merge()
*/
virtual const void* getStaticMergeData() const = 0;
/**
\brief Gets the merge data for dynamic actors
This is mainly called by the PxSceneQuerySystem::merge() function to merge a PxPruningStructure
with the internal data-structures of the scene-query system.
\return Implementation-dependent merge data for dynamic actors.
@see PxSceneQuerySystem::merge()
*/
virtual const void* getDynamicMergeData() const = 0;
virtual const char* getConcreteTypeName() const { return "PxPruningStructure"; }
protected:
PX_INLINE PxPruningStructure(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxPruningStructure(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
virtual ~PxPruningStructure() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxPruningStructure", PxBase); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 5,082 | C | 37.218045 | 128 | 0.766234 |
NVIDIA-Omniverse/PhysX/physx/include/PxRigidActor.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_RIGID_ACTOR_H
#define PX_RIGID_ACTOR_H
/** \addtogroup physics
@{
*/
#include "PxActor.h"
#include "PxShape.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxConstraint;
/**
\brief PxRigidActor represents a base class shared between dynamic and static rigid bodies in the physics SDK.
PxRigidActor objects specify the geometry of the object by defining a set of attached shapes (see #PxShape).
@see PxActor
*/
class PxRigidActor : public PxActor
{
public:
/**
\brief Deletes the rigid actor object.
Also releases any shapes associated with the actor.
Releasing an actor will affect any objects that are connected to the actor (constraint shaders like joints etc.).
Such connected objects will be deleted upon scene deletion, or explicitly by the user by calling release()
on these objects. It is recommended to always remove all objects that reference actors before the actors
themselves are removed. It is not possible to retrieve list of dead connected objects.
<b>Sleeping:</b> This call will awaken any sleeping actors contacting the deleted actor (directly or indirectly).
Calls #PxActor::release() so you might want to check the documentation of that method as well.
@see PxActor::release()
*/
virtual void release() = 0;
/**
\brief Returns the internal actor index.
\warning This is only defined for actors that have been added to a scene.
\return The internal actor index, or 0xffffffff if the actor is not part of a scene.
*/
virtual PxU32 getInternalActorIndex() const = 0;
/************************************************************************************************/
/** @name Global Pose Manipulation
*/
/**
\brief Retrieves the actors world space transform.
The getGlobalPose() method retrieves the actor's current actor space to world space transformation.
\note It is not allowed to use this method while the simulation is running (except during PxScene::collide(),
in PxContactModifyCallback or in contact report callbacks).
\return Global pose of object.
@see PxRigidDynamic.setGlobalPose() PxRigidStatic.setGlobalPose()
*/
virtual PxTransform getGlobalPose() const = 0;
/**
\brief Method for setting an actor's pose in the world.
This method instantaneously changes the actor space to world space transformation.
This method is mainly for dynamic rigid bodies (see #PxRigidDynamic). Calling this method on static actors is
likely to result in a performance penalty, since internal optimization structures for static actors may need to be
recomputed. In addition, moving static actors will not interact correctly with dynamic actors or joints.
To directly control an actor's position and have it correctly interact with dynamic bodies and joints, create a dynamic
body with the PxRigidBodyFlag::eKINEMATIC flag, then use the setKinematicTarget() commands to define its path.
Even when moving dynamic actors, exercise restraint in making use of this method. Where possible, avoid:
\li moving actors into other actors, thus causing overlap (an invalid physical state)
\li moving an actor that is connected by a joint to another away from the other (thus causing joint error)
\note It is not allowed to use this method if the actor is part of a #PxPruningStructure that has not been
added to a scene yet.
<b>Sleeping:</b> This call wakes dynamic actors if they are sleeping and the autowake parameter is true (default).
\param[in] pose Transformation from the actors local frame to the global frame. <b>Range:</b> rigid body transform.
\param[in] autowake whether to wake the object if it is dynamic. This parameter has no effect for static or kinematic actors. If true and the current wake counter value is smaller than #PxSceneDesc::wakeCounterResetValue it will get increased to the reset value.
@see getGlobalPose()
*/
virtual void setGlobalPose(const PxTransform& pose, bool autowake = true) = 0;
/************************************************************************************************/
/** @name Shapes
*/
/**
\brief Attach a shape to an actor
This call will increment the reference count of the shape.
\note Mass properties of dynamic rigid actors will not automatically be recomputed
to reflect the new mass distribution implied by the shape. Follow this call with a call to
the PhysX extensions method #PxRigidBodyExt::updateMassAndInertia() to do that.
Attaching a triangle mesh, heightfield or plane geometry shape configured as eSIMULATION_SHAPE is not supported for
non-kinematic PxRigidDynamic instances.
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] shape the shape to attach.
\return True if success.
*/
virtual bool attachShape(PxShape& shape) = 0;
/**
\brief Detach a shape from an actor.
This will also decrement the reference count of the PxShape, and if the reference count is zero, will cause it to be deleted.
<b>Sleeping:</b> Does <b>NOT</b> wake the actor up automatically.
\param[in] shape the shape to detach.
\param[in] wakeOnLostTouch Specifies whether touching objects from the previous frame should get woken up in the next frame. Only applies to PxArticulationReducedCoordinate and PxRigidActor types.
*/
virtual void detachShape(PxShape& shape, bool wakeOnLostTouch = true) = 0;
/**
\brief Returns the number of shapes assigned to the actor.
You can use #getShapes() to retrieve the shape pointers.
\return Number of shapes associated with this actor.
@see PxShape getShapes()
*/
virtual PxU32 getNbShapes() const = 0;
/**
\brief Retrieve all the shape pointers belonging to the actor.
These are the shapes used by the actor for collision detection.
You can retrieve the number of shape pointers by calling #getNbShapes()
Note: Removing shapes with #PxShape::release() will invalidate the pointer of the released shape.
\param[out] userBuffer The buffer to store the shape pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first shape pointer to be retrieved
\return Number of shape pointers written to the buffer.
@see PxShape getNbShapes() PxShape::release()
*/
virtual PxU32 getShapes(PxShape** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/************************************************************************************************/
/** @name Constraints
*/
/**
\brief Returns the number of constraint shaders attached to the actor.
You can use #getConstraints() to retrieve the constraint shader pointers.
\return Number of constraint shaders attached to this actor.
@see PxConstraint getConstraints()
*/
virtual PxU32 getNbConstraints() const = 0;
/**
\brief Retrieve all the constraint shader pointers belonging to the actor.
You can retrieve the number of constraint shader pointers by calling #getNbConstraints()
Note: Removing constraint shaders with #PxConstraint::release() will invalidate the pointer of the released constraint.
\param[out] userBuffer The buffer to store the constraint shader pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first constraint pointer to be retrieved
\return Number of constraint shader pointers written to the buffer.
@see PxConstraint getNbConstraints() PxConstraint::release()
*/
virtual PxU32 getConstraints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
protected:
PX_INLINE PxRigidActor(PxType concreteType, PxBaseFlags baseFlags) : PxActor(concreteType, baseFlags) {}
PX_INLINE PxRigidActor(PxBaseFlags baseFlags) : PxActor(baseFlags) {}
virtual ~PxRigidActor() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxRigidActor", PxActor); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 9,550 | C | 38.962343 | 263 | 0.739581 |
NVIDIA-Omniverse/PhysX/physx/include/PxAnisotropy.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_ANISOTROPY_H
#define PX_ANISOTROPY_H
/** \addtogroup extensions
@{
*/
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#include "PxParticleSystem.h"
#include "foundation/PxArray.h"
#include "PxParticleGpu.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
class PxgKernelLauncher;
class PxParticleNeighborhoodProvider;
/**
\brief Computes anisotropy information for a particle system to improve rendering quality
*/
class PxAnisotropyGenerator
{
public:
/**
\brief Schedules the compuation of anisotropy information on the specified cuda stream
\param[in] gpuParticleSystem A gpu pointer to access particle system data
\param[in] numParticles The number of particles
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateAnisotropy(PxGpuParticleSystem* gpuParticleSystem, PxU32 numParticles, CUstream stream) = 0;
/**
\brief Schedules the compuation of anisotropy information on the specified cuda stream
\param[in] particlePositionsGpu A gpu pointer containing the particle positions
\param[in] neighborhoodProvider A neighborhood provider object that supports fast neighborhood queries
\param[in] numParticles The number of particles
\param[in] particleContactOffset The particle contact offset
\param[in] stream The stream on which the cuda call gets scheduled
*/
virtual void generateAnisotropy(PxVec4* particlePositionsGpu, PxParticleNeighborhoodProvider& neighborhoodProvider, PxU32 numParticles, PxReal particleContactOffset, CUstream stream) = 0;
/**
\brief Set a host buffer that holds the anisotropy data after the timestep completed
\param[in] anisotropy1 A host buffer holding the first row of the anisotropy matrix with memory for all particles already allocated
\param[in] anisotropy2 A host buffer holding the second row of the anisotropy matrix with memory for all particles already allocated
\param[in] anisotropy3 A host buffer holding the third row of the anisotropy matrix with memory for all particles already allocated
*/
virtual void setResultBufferHost(PxVec4* anisotropy1, PxVec4* anisotropy2, PxVec4* anisotropy3) = 0;
/**
\brief Set a device buffer that holds the anisotrpy data after the timestep completed
\param[in] anisotropy1 A device buffer holding the first row of the anisotropy matrix with memory for all particles already allocated
\param[in] anisotropy2 A device buffer holding the second row of the anisotropy matrix with memory for all particles already allocated
\param[in] anisotropy3 A device buffer holding the third row of the anisotropy matrix with memory for all particles already allocated
*/
virtual void setResultBufferDevice(PxVec4* anisotropy1, PxVec4* anisotropy2, PxVec4* anisotropy3) = 0;
/**
\brief Sets the maximum value anisotropy can reach in any direction
\param[in] maxAnisotropy The maximum anisotropy value
*/
virtual void setAnisotropyMax(float maxAnisotropy) = 0;
/**
\brief Sets the minimum value anisotropy can reach in any direction
\param[in] minAnisotropy The minimum anisotropy value
*/
virtual void setAnisotropyMin(float minAnisotropy) = 0;
/**
\brief Sets the anisotropy scale
\param[in] anisotropyScale The anisotropy scale
*/
virtual void setAnisotropyScale(float anisotropyScale) = 0;
/**
\brief Gets the maximal number of particles
\return The maximal number of particles
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Sets the maximal number of particles
\param[in] maxParticles The maximal number of particles
*/
virtual void setMaxParticles(PxU32 maxParticles) = 0;
/**
\brief Gets the device pointer for the anisotropy in x direction. Only available after calling setResultBufferHost or setResultBufferDevice
\return The device pointer for the anisotropy x direction and scale (w component contains the scale)
*/
virtual PxVec4* getAnisotropy1DevicePointer() const = 0;
/**
\brief Gets the device pointer for the anisotropy in y direction. Only available after calling setResultBufferHost or setResultBufferDevice
\return The device pointer for the anisotropy y direction and scale (w component contains the scale)
*/
virtual PxVec4* getAnisotropy2DevicePointer() const = 0;
/**
\brief Gets the device pointer for the anisotropy in z direction. Only available after calling setResultBufferHost or setResultBufferDevice
\return The device pointer for the anisotropy z direction and scale (w component contains the scale)
*/
virtual PxVec4* getAnisotropy3DevicePointer() const = 0;
/**
\brief Enables or disables the anisotropy generator
\param[in] enabled The boolean to set the generator to enabled or disabled
*/
virtual void setEnabled(bool enabled) = 0;
/**
\brief Allows to query if the anisotropy generator is enabled
\return True if enabled, false otherwise
*/
virtual bool isEnabled() const = 0;
/**
\brief Releases the instance and its data
*/
virtual void release() = 0;
/**
\brief Destructor
*/
virtual ~PxAnisotropyGenerator() {}
};
/**
\brief Default implementation of a particle system callback to trigger anisotropy calculations. A call to fetchResultsParticleSystem() on the
PxScene will synchronize the work such that the caller knows that the post solve task completed.
*/
class PxAnisotropyCallback : public PxParticleSystemCallback
{
public:
/**
\brief Initializes the anisotropy callback
\param[in] anistropyGenerator The anisotropy generator
*/
void initialize(PxAnisotropyGenerator* anistropyGenerator)
{
mAnistropyGenerator = anistropyGenerator;
}
virtual void onPostSolve(const PxGpuMirroredPointer<PxGpuParticleSystem>& gpuParticleSystem, CUstream stream)
{
if (mAnistropyGenerator)
{
mAnistropyGenerator->generateAnisotropy(gpuParticleSystem.mDevicePtr, gpuParticleSystem.mHostPtr->mCommonData.mMaxParticles, stream);
}
}
virtual void onBegin(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
virtual void onAdvance(const PxGpuMirroredPointer<PxGpuParticleSystem>& /*gpuParticleSystem*/, CUstream /*stream*/) { }
private:
PxAnisotropyGenerator* mAnistropyGenerator;
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 8,159 | C | 35.591928 | 189 | 0.769089 |
NVIDIA-Omniverse/PhysX/physx/include/PxArrayConverter.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_ARRAY_CONVERTER_H
#define PX_ARRAY_CONVERTER_H
#include "cudamanager/PxCudaContext.h"
#include "cudamanager/PxCudaContextManager.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_SUPPORT_GPU_PHYSX
/**
\brief Utility class to convert gpu arrays to a different memory layout
*/
class PxArrayConverter
{
public:
/**
\brief Helper function to merge two separate PxVec4 arrays into one interleaved PxVec3 array
\param[in] verticesD The vertices device memory buffer
\param[in] normalsD The normals device memory buffer
\param[in] length The number of vertices and normals
\param[out] interleavedResultBufferD The resulting interleaved buffer containing 2*length elements with the format vertex0, normal0, vertex1, normal1...
\param[in] stream The cuda stream on which the conversion is processed
*/
virtual void interleaveGpuBuffers(const PxVec4* verticesD, const PxVec4* normalsD, PxU32 length, PxVec3* interleavedResultBufferD, CUstream stream) = 0;
/**
\brief Helper function to convert the hair system's strand representation to a line list. The conversion is done on the GPU.
\param[in] verticesD The strand vertices device memory buffer
\param[in] numVertices The total number of vertices
\param[in] strandPastEndIndicesD One index per strand (device memory array) to find out where the next strand starts
\param[in] numStrands the number of strands
\param[out] resultD A device memory buffer with 2*numVertices capacity describing line segment where line i extends from result[2*i] to result[2*i+1]
\param[in] stream The cuda stream on which the conversion is processed
*/
virtual void extractLinesFromStrands(const PxVec4* verticesD, PxU32 numVertices, const PxU32* strandPastEndIndicesD,
PxU32 numStrands, PxVec4* resultD, CUstream stream) = 0;
/**
\brief Helper function to convert the hair system's strand representation to a line list. The conversion is done on the GPU.
\param[in] verticesD The strand vertices device memory buffer
\param[in] numVertices The total number of vertices
\param[in] strandPastEndIndicesD One index per strand (device memory array) to find out where the next strand starts
\param[in] numStrands the number of strands
\param[out] resultD A device memory buffer with 2*numVertices capacity describing line segment where line i extends from result[2*i] to result[2*i+1]
\param[in] stream The cuda stream on which the conversion is processed
*/
virtual void extractLinesFromStrands(const PxVec3* verticesD, PxU32 numVertices, const PxU32* strandPastEndIndicesD,
PxU32 numStrands, PxVec3* resultD, CUstream stream) = 0;
/**
\brief Destructor
*/
virtual ~PxArrayConverter() {}
};
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 4,542 | C | 44.888888 | 154 | 0.768384 |
NVIDIA-Omniverse/PhysX/physx/include/PxArticulationReducedCoordinate.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ARTICULATION_RC_H
#define PX_ARTICULATION_RC_H
/** \addtogroup physics
@{ */
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#include "foundation/PxVec3.h"
#include "foundation/PxTransform.h"
#include "solver/PxSolverDefs.h"
#include "PxArticulationFlag.h"
#include "PxArticulationTendon.h"
#include "PxArticulationFlag.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
PX_ALIGN_PREFIX(16)
/**
\brief Data structure to represent spatial forces.
*/
struct PxSpatialForce
{
PxVec3 force;
PxReal pad0;
PxVec3 torque;
PxReal pad1;
}
PX_ALIGN_SUFFIX(16);
PX_ALIGN_PREFIX(16)
/**
\brief Data structure to represent spatial velocities.
*/
struct PxSpatialVelocity
{
PxVec3 linear;
PxReal pad0;
PxVec3 angular;
PxReal pad1;
}
PX_ALIGN_SUFFIX(16);
class PxConstraint;
class PxScene;
/**
\brief Data structure used to access the root link state and acceleration.
@see PxArticulationCache
*/
struct PxArticulationRootLinkData
{
PxTransform transform; //!< Actor transform
// The velocities and accelerations below are with respect to the center of mass (COM) of the root link. The COM and actor frame origin may not coincide.
PxVec3 worldLinVel; //!< Link linear velocity
PxVec3 worldAngVel; //!< Link angular velocity
PxVec3 worldLinAccel; //!< Link classical linear acceleration
PxVec3 worldAngAccel; //!< Link angular acceleration
};
/**
\brief Data structure used to read and write internal articulation data.
@see PxArticulationCacheFlag, PxArticulationReducedCoordinate::createCache, PxArticulationReducedCoordinate::applyCache,
PxArticulationReducedCoordinate::copyInternalStateToCache
*/
class PxArticulationCache
{
public:
PxArticulationCache() :
externalForces (NULL),
denseJacobian (NULL),
massMatrix (NULL),
jointVelocity (NULL),
jointAcceleration (NULL),
jointPosition (NULL),
jointForce (NULL),
jointSolverForces (NULL),
jointTargetPositions (NULL),
jointTargetVelocities (NULL),
linkVelocity (NULL),
linkAcceleration (NULL),
linkIncomingJointForce (NULL),
rootLinkData (NULL),
sensorForces (NULL),
coefficientMatrix (NULL),
lambda (NULL),
scratchMemory (NULL),
scratchAllocator (NULL),
version (0)
{}
/**
\brief Releases an articulation cache.
@see PxArticulationReducedCoordinate::createCache, PxArticulationReducedCoordinate::applyCache,
PxArticulationReducedCoordinate::copyInternalStateToCache
*/
PX_PHYSX_CORE_API void release();
/**
\brief External forces acting on the articulation links for inverse dynamics computation.
- N = getNbLinks().
- Indexing follows the low-level link indices, see PxArticulationLink::getLinkIndex.
- The forces are with respect to the center of mass of the link.
@see PxArticulationReducedCoordinate::computeGeneralizedExternalForce
*/
PxSpatialForce* externalForces;
/**
\brief Dense Jacobian data.
- N = nbRows * nbCols = (6 * getNbLinks()) * (6 + getDofs()) -> size includes possible floating-base DOFs regardless of PxArticulationFlag::eFIX_BASE flag.
- The links, i.e. rows are in order of the low-level link indices (minus one if PxArticulationFlag::eFIX_BASE is true), see PxArticulationLink::getLinkIndex.
The corresponding spatial velocities are stacked [vx; vy; vz; wx; wy; wz], where vx and wx refer to the linear and rotational velocity in world X.
- The DOFs, i.e. column indices correspond to the low-level DOF indices, see PxArticulationCache::jointVelocity.
@see PxArticulationReducedCoordinate::computeDenseJacobian
*/
PxReal* denseJacobian;
/**
\brief The generalized mass matrix that maps joint accelerations to joint forces.
- N = getDofs() * getDofs().
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
@see PxArticulationReducedCoordinate::computeGeneralizedMassMatrix
*/
PxReal* massMatrix;
/**
\brief The articulation joint DOF velocities.
- N = getDofs().
- Read/write using PxArticulationCacheFlag::eVELOCITY.
- The indexing follows the internal DOF index order. Therefore, the application should calculate the DOF data indices by summing the joint DOFs in the order of
the links' low-level indices (see the manual Section "Cache Indexing" for a snippet for this calculation):
\verbatim Low-level link index: | link 0 | link 1 | link 2 | link 3 | ... | <- PxArticulationLink::getLinkIndex() \endverbatim
\verbatim Link inbound joint DOF: | 0 | 1 | 2 | 1 | ... | <- PxArticulationLink::getInboundJointDof() \endverbatim
\verbatim Low-level DOF index: | - | 0 | 1, 2 | 3 | ... | \endverbatim
The root link always has low-level index 0 and always has zero inbound joint DOFs. The link DOF indexing follows the order in PxArticulationAxis::Enum.
For example, assume that low-level link 2 has an inbound spherical joint with two DOFs: eSWING1 and eSWING2. The corresponding low-level joint DOF indices
are therefore 1 for eSWING1 and 2 for eSWING2.
*/
PxReal* jointVelocity;
/**
\brief The articulation joint DOF accelerations.
- N = getDofs().
- Read using PxArticulationCacheFlag::eACCELERATION.
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
- Delta joint DOF velocities can be computed from acceleration * dt.
*/
PxReal* jointAcceleration;
/**
\brief The articulation joint DOF positions.
- N = getDofs().
- Read/write using PxArticulationCacheFlag::ePOSITION.
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
- For spherical joints, the joint position for each axis on the joint must be in range [-Pi, Pi].
*/
PxReal* jointPosition;
/**
\brief The articulation joint DOF forces.
- N = getDofs().
- Read/Write using PxArticulationCacheFlag::eFORCE.
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
- Applied joint forces persist and are applied each frame until changed.
*/
PxReal* jointForce;
/**
@deprecated Use linkIncomingJointForce instead.
\brief Solver constraint joint DOF forces.
- N = getDofs().
- Read using PxArticulationCacheFlag::eJOINT_SOLVER_FORCES.
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
- Raise PxArticulationFlag::eCOMPUTE_JOINT_FORCES to enable reading the solver forces.
*/
PX_DEPRECATED PxReal* jointSolverForces;
/**
\brief The articulation joint drive target positions.
- N = getDofs().
- Write using PxArticulationCacheFlag::eJOINT_TARGET_POSITIONS.
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
*/
PxReal* jointTargetPositions;
/**
\brief The articulation joint drive target velocities.
- N = getDofs().
- Write using PxArticulationCacheFlag::eJOINT_TARGET_VELOCITIES.
- The indexing follows the internal DOF index order, see PxArticulationCache::jointVelocity.
*/
PxReal* jointTargetVelocities;
/**
\brief Link spatial velocity.
- N = getNbLinks().
- Read using PxArticulationCacheFlag::eLINK_VELOCITY.
- The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex.
- The velocity is with respect to the link's center of mass.
@see PxRigidBody::getCMassLocalPose
*/
PxSpatialVelocity* linkVelocity;
/**
\brief Link classical acceleration.
- N = getNbLinks().
- Read using PxArticulationCacheFlag::eLINK_ACCELERATION.
- The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex.
- The acceleration is with respect to the link's center of mass.
@see PxArticulationReducedCoordinate::getLinkAcceleration, PxRigidBody::getCMassLocalPose
*/
PxSpatialVelocity* linkAcceleration;
/**
\brief Link incoming joint force, i.e. the total force transmitted from the parent link to this link.
- N = getNbLinks().
- Read using PxArticulationCacheFlag::eLINK_INCOMING_JOINT_FORCE.
- The indexing follows the internal link indexing, see PxArticulationLink::getLinkIndex.
- The force is reported in the child joint frame of the link's incoming joint.
@see PxArticulationJointReducedCoordinate::getChildPose
\note The root link reports a zero spatial force.
*/
PxSpatialForce* linkIncomingJointForce;
/**
\brief Root link transform, velocities, and accelerations.
- N = 1.
- Read/write using PxArticulationCacheFlag::eROOT_TRANSFORM and PxArticulationCacheFlag::eROOT_VELOCITIES (accelerations are read-only).
@see PxArticulationRootLinkData
*/
PxArticulationRootLinkData* rootLinkData;
/**
@deprecated
\brief Link sensor spatial forces.
- N = getNbSensors().
- Read using PxArticulationCacheFlag::eSENSOR_FORCES.
- For indexing, see PxArticulationSensor::getIndex.
@see PxArticulationSensor
*/
PX_DEPRECATED PxSpatialForce* sensorForces;
// Members and memory below here are not zeroed when zeroCache is called, and are not included in the size returned by PxArticulationReducedCoordinate::getCacheDataSize.
/**
\brief Constraint coefficient matrix.
- N = getCoefficentMatrixSize().
- The user needs to allocate memory and set this member to the allocated memory.
@see PxArticulationReducedCoordinate::computeCoefficientMatrix
*/
PxReal* coefficientMatrix;
/**
\brief Constraint lambda values (impulses applied by the respective constraints).
- N = getNbLoopJoints().
- The user needs to allocate memory and set this member to the allocated memory.
@see PxArticulationReducedCoordinate::computeLambda
*/
PxReal* lambda;
void* scratchMemory; //!< The scratch memory is used for internal calculations.
void* scratchAllocator; //!< The scratch allocator is used for internal calculations.
PxU32 version; //!< The cache version used internally to check compatibility with the articulation, i.e. detect if the articulation configuration changed after the cache was created.
};
/**
@deprecated
\brief Flags to configure the forces reported by articulation link sensors.
@see PxArticulationSensor::setFlag
*/
struct PX_DEPRECATED PxArticulationSensorFlag
{
enum Enum
{
eFORWARD_DYNAMICS_FORCES = 1 << 0, //!< Raise to receive forces from forward dynamics.
eCONSTRAINT_SOLVER_FORCES = 1 << 1, //!< Raise to receive forces from constraint solver.
eWORLD_FRAME = 1 << 2 //!< Raise to receive forces in the world rotation frame, otherwise they will be reported in the sensor's local frame.
};
};
typedef PX_DEPRECATED physx::PxFlags<PxArticulationSensorFlag::Enum, PxU8> PxArticulationSensorFlags;
/**
@deprecated
\brief A force sensor that can be attached to articulation links to measure spatial force.
@see PxArticulationReducedCoordinate::createSensor
*/
class PX_DEPRECATED PxArticulationSensor : public PxBase
{
public:
/**
\brief Releases the sensor.
\note Releasing a sensor is not allowed while the articulation is in a scene. In order to
release a sensor, remove and then re-add the articulation to the scene.
*/
virtual void release() = 0;
/**
\brief Returns the spatial force in the local frame of the sensor.
\return The spatial force.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
@see setRelativePose, getRelativePose
*/
virtual PxSpatialForce getForces() const = 0;
/**
\brief Returns the relative pose between this sensor and the body frame of the link that the sensor is attached to.
The link body frame is at the center of mass and aligned with the principal axes of inertia, see PxRigidBody::getCMassLocalPose.
\return The transform link body frame -> sensor frame.
@see setRelativePose
*/
virtual PxTransform getRelativePose() const = 0;
/**
\brief Sets the relative pose between this sensor and the body frame of the link that the sensor is attached to.
The link body frame is at the center of mass and aligned with the principal axes of inertia, see PxRigidBody::getCMassLocalPose.
\param[in] pose The transform link body frame -> sensor frame.
\note Setting the sensor relative pose is not allowed while the articulation is in a scene. In order to
set the pose, remove and then re-add the articulation to the scene.
@see getRelativePose
*/
virtual void setRelativePose(const PxTransform& pose) = 0;
/**
\brief Returns the link that this sensor is attached to.
\return A pointer to the link.
*/
virtual PxArticulationLink* getLink() const = 0;
/**
\brief Returns the index of this sensor inside the articulation.
The return value is only valid for sensors attached to articulations that are in a scene.
\return The low-level index, or 0xFFFFFFFF if the articulation is not in a scene.
*/
virtual PxU32 getIndex() const = 0;
/**
\brief Returns the articulation that this sensor is part of.
\return A pointer to the articulation.
*/
virtual PxArticulationReducedCoordinate* getArticulation() const = 0;
/**
\brief Returns the sensor's flags.
\return The current set of flags of the sensor.
@see PxArticulationSensorFlag
*/
virtual PxArticulationSensorFlags getFlags() const = 0;
/**
\brief Sets a flag of the sensor.
\param[in] flag The flag to set.
\param[in] enabled The value to set the flag to.
\note Setting the sensor flags is not allowed while the articulation is in a scene. In order to
set the flags, remove and then re-add the articulation to the scene.
@see PxArticulationSensorFlag
*/
virtual void setFlag(PxArticulationSensorFlag::Enum flag, bool enabled) = 0;
/**
\brief Returns the string name of the dynamic type.
\return The string name.
*/
virtual const char* getConcreteTypeName() const { return "PxArticulationSensor"; }
virtual ~PxArticulationSensor() {}
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxArticulationSensor(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationSensor(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
/**
\brief Flag that configures articulation-state updates by PxArticulationReducedCoordinate::updateKinematic.
*/
struct PxArticulationKinematicFlag
{
enum Enum
{
ePOSITION = 1 << 0, //!< Raise after any changes to the articulation root or joint positions using non-cache API calls. Updates links' positions and velocities.
eVELOCITY = 1 << 1 //!< Raise after velocity-only changes to the articulation root or joints using non-cache API calls. Updates links' velocities.
};
};
typedef physx::PxFlags<PxArticulationKinematicFlag::Enum, PxU8> PxArticulationKinematicFlags;
PX_FLAGS_OPERATORS(PxArticulationKinematicFlag::Enum, PxU8)
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
/**
\brief A tree structure of bodies connected by joints that is treated as a unit by the dynamics solver. Parametrized in reduced (joint) coordinates.
@see PxArticulationJointReducedCoordinate, PxArticulationLink, PxPhysics::createArticulationReducedCoordinate
*/
class PxArticulationReducedCoordinate : public PxBase
{
public:
/**
\brief Returns the scene which this articulation belongs to.
\return Owner Scene. NULL if not part of a scene.
@see PxScene
*/
virtual PxScene* getScene() const = 0;
/**
\brief Sets the solver iteration counts for the articulation.
The solver iteration count determines how accurately contacts, drives, and limits are resolved.
Setting a higher position iteration count may therefore help in scenarios where the articulation
is subject to many constraints; for example, a manipulator articulation with drives and joint limits
that is grasping objects, or several such articulations interacting through contacts. Other situations
where higher position iterations may improve simulation fidelity are: large mass ratios within the
articulation or between the articulation and an object in contact with it; or strong drives in the
articulation being used to manipulate a light object.
If intersecting bodies are being depenetrated too violently, increase the number of velocity
iterations. More velocity iterations will drive the relative exit velocity of the intersecting
objects closer to the correct value given the restitution.
\param[in] minPositionIters Number of position iterations the solver should perform for this articulation. <b>Range:</b> [1,255]. <b>Default:</b> 4.
\param[in] minVelocityIters Number of velocity iterations the solver should perform for this articulation. <b>Range:</b> [0,255]. <b>Default:</b> 1
\note This call may not be made during simulation.
@see getSolverIterationCounts()
*/
virtual void setSolverIterationCounts(PxU32 minPositionIters, PxU32 minVelocityIters = 1) = 0;
/**
\brief Returns the solver iteration counts.
@see setSolverIterationCounts()
*/
virtual void getSolverIterationCounts(PxU32& minPositionIters, PxU32& minVelocityIters) const = 0;
/**
\brief Returns true if this articulation is sleeping.
When an actor does not move for a period of time, it is no longer simulated in order to reduce computational cost. This state
is called sleeping. However, because the object automatically wakes up when it is either touched by an awake object,
or a sleep-affecting property is changed by the user, the entire sleep mechanism should be transparent to the user.
An articulation can only go to sleep if all links are ready for sleeping. An articulation is guaranteed to be awake
if at least one of the following holds:
\li The wake counter of any link in the articulation is positive (see #setWakeCounter()).
\li The mass-normalized energy of any link in the articulation is above a threshold (see #setSleepThreshold()).
\li A non-zero force or torque has been applied to any joint or link.
If an articulation is sleeping, the following state is guaranteed:
\li The wake counter is zero.
\li The linear and angular velocity of all links is zero.
\li There is no force update pending.
When an articulation gets inserted into a scene, it will be considered asleep if all the points above hold, else it will
be treated as awake.
If an articulation is asleep after the call to #PxScene::fetchResults() returns, it is guaranteed that the poses of the
links were not changed. You can use this information to avoid updating the transforms of associated objects.
\return True if the articulation is sleeping.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation,
except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance.
@see wakeUp() putToSleep() getSleepThreshold() setSleepThreshold()
*/
virtual bool isSleeping() const = 0;
/**
\brief Sets the mass-normalized energy threshold below which the articulation may go to sleep.
The articulation will sleep if the energy of each link is below this threshold.
\param[in] threshold Energy below which the articulation may go to sleep. <b>Range:</b> [0, PX_MAX_F32)
\note This call may not be made during simulation.
<b>Default:</b> 5e-5f * PxTolerancesScale::speed * PxTolerancesScale::speed;
@see isSleeping() getSleepThreshold() wakeUp() putToSleep()
*/
virtual void setSleepThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized energy below which the articulation may go to sleep.
\return The energy threshold for sleeping.
@see isSleeping() wakeUp() putToSleep() setSleepThreshold()
*/
virtual PxReal getSleepThreshold() const = 0;
/**
\brief Sets the mass-normalized kinetic energy threshold below which the articulation may participate in stabilization.
Articulations whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
This value has no effect if PxSceneFlag::eENABLE_STABILIZATION was not enabled on the PxSceneDesc.
<b>Default:</b> 5e-6f * PxTolerancesScale::speed * PxTolerancesScale::speed
\param[in] threshold Energy below which the articulation may participate in stabilization. <b>Range:</b> [0,inf)
\note This call may not be made during simulation.
@see getStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual void setStabilizationThreshold(PxReal threshold) = 0;
/**
\brief Returns the mass-normalized kinetic energy below which the articulation may participate in stabilization.
Articulations whose kinetic energy divided by their mass is above this threshold will not participate in stabilization.
\return The energy threshold for participating in stabilization.
@see setStabilizationThreshold() PxSceneFlag::eENABLE_STABILIZATION
*/
virtual PxReal getStabilizationThreshold() const = 0;
/**
\brief Sets the wake counter for the articulation in seconds.
- The wake counter value specifies a time threshold used to determine whether an articulation may be put to sleep.
- The articulation will be put to sleep if all links have experienced a mass-normalised energy less than a threshold for at least
a threshold time, as specified by the wake counter.
- Passing in a positive value will wake up the articulation automatically.
<b>Default:</b> 0.4s (which corresponds to 20 frames for a time step of 0.02s)
\param[in] wakeCounterValue Wake counter value in seconds. <b>Range:</b> [0, PX_MAX_F32)
\note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance.
@see isSleeping() getWakeCounter()
*/
virtual void setWakeCounter(PxReal wakeCounterValue) = 0;
/**
\brief Returns the wake counter of the articulation in seconds.
\return The wake counter of the articulation in seconds.
\note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance.
@see isSleeping() setWakeCounter()
*/
virtual PxReal getWakeCounter() const = 0;
/**
\brief Wakes up the articulation if it is sleeping.
- The articulation will be woken up and might cause other touching objects to wake up as well during the next simulation step.
- This will set the wake counter of the articulation to the value specified in #PxSceneDesc::wakeCounterResetValue.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation,
except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance.
@see isSleeping() putToSleep()
*/
virtual void wakeUp() = 0;
/**
\brief Forces the articulation to sleep.
- The articulation will stay asleep during the next simulation step if not touched by another non-sleeping actor.
- This will set any applied force, the velocity, and the wake counter of all bodies in the articulation to zero.
\note This call may not be made during simulation, and may only be made on articulations that are in a scene.
@see isSleeping() wakeUp()
*/
virtual void putToSleep() = 0;
/**
\brief Sets the limit on the magnitude of the linear velocity of the articulation's center of mass.
- The limit acts on the linear velocity of the entire articulation. The velocity is calculated from the total momentum
and the spatial inertia of the articulation.
- The limit only applies to floating-base articulations.
- A benefit of the COM velocity limit is that it is evenly applied to the whole articulation, which results in fewer visual
artifacts compared to link rigid-body damping or joint-velocity limits. However, these per-link or per-degree-of-freedom
limits may still help avoid numerical issues.
\note This call may not be made during simulation.
\param[in] maxLinearVelocity The maximal linear velocity magnitude. <b>Range:</b> [0, PX_MAX_F32); <b>Default:</b> 1e+6.
@see setMaxCOMAngularVelocity, PxRigidBody::setLinearDamping, PxRigidBody::setAngularDamping, PxArticulationJointReducedCoordinate::setMaxJointVelocity
*/
PX_DEPRECATED virtual void setMaxCOMLinearVelocity(const PxReal maxLinearVelocity) = 0;
/**
\brief Gets the limit on the magnitude of the linear velocity of the articulation's center of mass.
\return The maximal linear velocity magnitude.
@see setMaxCOMLinearVelocity
*/
PX_DEPRECATED virtual PxReal getMaxCOMLinearVelocity() const = 0;
/**
\brief Sets the limit on the magnitude of the angular velocity at the articulation's center of mass.
- The limit acts on the angular velocity of the entire articulation. The velocity is calculated from the total momentum
and the spatial inertia of the articulation.
- The limit only applies to floating-base articulations.
- A benefit of the COM velocity limit is that it is evenly applied to the whole articulation, which results in fewer visual
artifacts compared to link rigid-body damping or joint-velocity limits. However, these per-link or per-degree-of-freedom
limits may still help avoid numerical issues.
\note This call may not be made during simulation.
\param[in] maxAngularVelocity The maximal angular velocity magnitude. <b>Range:</b> [0, PX_MAX_F32); <b>Default:</b> 1e+6
@see setMaxCOMLinearVelocity, PxRigidBody::setLinearDamping, PxRigidBody::setAngularDamping, PxArticulationJointReducedCoordinate::setMaxJointVelocity
*/
PX_DEPRECATED virtual void setMaxCOMAngularVelocity(const PxReal maxAngularVelocity) = 0;
/**
\brief Gets the limit on the magnitude of the angular velocity at the articulation's center of mass.
\return The maximal angular velocity magnitude.
@see setMaxCOMAngularVelocity
*/
PX_DEPRECATED virtual PxReal getMaxCOMAngularVelocity() const = 0;
/**
\brief Adds a link to the articulation with default attribute values.
\param[in] parent The parent link in the articulation. Must be NULL if (and only if) this is the root link.
\param[in] pose The initial pose of the new link. Must be a valid transform.
\return The new link, or NULL if the link cannot be created.
\note Creating a link is not allowed while the articulation is in a scene. In order to add a link,
remove and then re-add the articulation to the scene.
\note When the articulation is added to a scene, the root link adopts the specified pose. The pose of the
root link is propagated through the ensemble of links from parent to child after accounting for each child's
inbound joint frames and the joint positions set by PxArticulationJointReducedCoordinate::setJointPosition().
As a consequence, the pose of each non-root link is automatically overwritten when adding the articulation to the scene.
@see PxArticulationLink
*/
virtual PxArticulationLink* createLink(PxArticulationLink* parent, const PxTransform& pose) = 0;
/**
\brief Releases the articulation, and all its links and corresponding joints.
Attached sensors and tendons are released automatically when the articulation is released.
\note This call may not be made during simulation.
\note This call does not release any PxArticulationCache instance that has been instantiated using #createCache()
*/
virtual void release() = 0;
/**
\brief Returns the number of links in the articulation.
\return The number of links.
*/
virtual PxU32 getNbLinks() const = 0;
/**
\brief Returns the set of links in the articulation in the order that they were added to the articulation using createLink.
\param[in] userBuffer Buffer into which to write the array of articulation link pointers.
\param[in] bufferSize The size of the buffer. If the buffer is not large enough to contain all the pointers to links,
only as many as will fit are written.
\param[in] startIndex Index of first link pointer to be retrieved.
\return The number of links written into the buffer.
@see PxArticulationLink
*/
virtual PxU32 getLinks(PxArticulationLink** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of shapes in the articulation.
\return The number of shapes.
*/
virtual PxU32 getNbShapes() const = 0;
/**
\brief Sets a name string for the articulation that can be retrieved with getName().
This is for debugging and is not used by the SDK. The string is not copied by the SDK,
only the pointer is stored.
\param[in] name A pointer to a char buffer used to specify the name of the articulation.
@see getName()
*/
virtual void setName(const char* name) = 0;
/**
\brief Returns the name string set with setName().
\return Name string associated with the articulation.
@see setName()
*/
virtual const char* getName() const = 0;
/**
\brief Returns the axis-aligned bounding box enclosing the articulation.
\param[in] inflation Scale factor for computed world bounds. Box extents are multiplied by this value.
\return The articulation's bounding box.
\note It is not allowed to use this method while the simulation is running, except in a split simulation
during #PxScene::collide() and up to #PxScene::advance(), and in PxContactModifyCallback or in contact report callbacks.
@see PxBounds3
*/
virtual PxBounds3 getWorldBounds(float inflation = 1.01f) const = 0;
/**
\brief Returns the aggregate associated with the articulation.
\return The aggregate associated with the articulation or NULL if the articulation does not belong to an aggregate.
@see PxAggregate
*/
virtual PxAggregate* getAggregate() const = 0;
/**
\brief Sets flags on the articulation.
\param[in] flags The articulation flags.
\note This call may not be made during simulation.
@see PxArticulationFlag
*/
virtual void setArticulationFlags(PxArticulationFlags flags) = 0;
/**
\brief Raises or clears a flag on the articulation.
\param[in] flag The articulation flag.
\param[in] value The value to set the flag to.
\note This call may not be made during simulation.
@see PxArticulationFlag
*/
virtual void setArticulationFlag(PxArticulationFlag::Enum flag, bool value) = 0;
/**
\brief Returns the articulation's flags.
\return The articulation's flags.
@see PxArticulationFlag
*/
virtual PxArticulationFlags getArticulationFlags() const = 0;
/**
\brief Returns the total number of joint degrees-of-freedom (DOFs) of the articulation.
- The six DOFs of the base of a floating-base articulation are not included in this count.
- Example: Both a fixed-base and a floating-base double-pendulum with two revolute joints will have getDofs() == 2.
- The return value is only valid for articulations that are in a scene.
\return The number of joint DOFs, or 0xFFFFFFFF if the articulation is not in a scene.
*/
virtual PxU32 getDofs() const = 0;
/**
\brief Creates an articulation cache that can be used to read and write internal articulation data.
- When the structure of the articulation changes (e.g. adding a link or sensor) after the cache was created,
the cache needs to be released and recreated.
- Free the memory allocated for the cache by calling the release() method on the cache.
- Caches can only be created by articulations that are in a scene.
\return The cache, or NULL if the articulation is not in a scene.
@see applyCache, copyInternalStateToCache
*/
virtual PxArticulationCache* createCache() const = 0;
/**
\brief Returns the size of the articulation cache in bytes.
- The size does not include: the user-allocated memory for the coefficient matrix or lambda values;
the scratch-related memory/members; and the cache version. See comment in #PxArticulationCache.
- The return value is only valid for articulations that are in a scene.
\return The byte size of the cache, or 0xFFFFFFFF if the articulation is not in a scene.
@see PxArticulationCache
*/
virtual PxU32 getCacheDataSize() const = 0;
/**
\brief Zeroes all data in the articulation cache, except user-provided and scratch memory, and cache version.
\note This call may only be made on articulations that are in a scene.
@see PxArticulationCache
*/
virtual void zeroCache(PxArticulationCache& cache) const = 0;
/**
\brief Applies the data in the cache to the articulation.
This call wakes the articulation if it is sleeping, and the autowake parameter is true (default) or:
- a nonzero joint velocity is applied or
- a nonzero joint force is applied or
- a nonzero root velocity is applied
\param[in] cache The articulation data.
\param[in] flags Indicate which data in the cache to apply to the articulation.
\param[in] autowake If true, the call wakes up the articulation and increases the wake counter to #PxSceneDesc::wakeCounterResetValue
if the counter value is below the reset value.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see PxArticulationCache, PxArticulationCacheFlags, createCache, copyInternalStateToCache, PxScene::applyArticulationData
*/
virtual void applyCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags, bool autowake = true) = 0;
/**
\brief Copies internal data of the articulation to the cache.
\param[in] cache The articulation data.
\param[in] flags Indicate which data to copy from the articulation to the cache.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see PxArticulationCache, PxArticulationCacheFlags, createCache, applyCache
*/
virtual void copyInternalStateToCache(PxArticulationCache& cache, const PxArticulationCacheFlags flags) const = 0;
/**
\brief Converts maximal-coordinate joint DOF data to reduced coordinates.
- Indexing into the maximal joint DOF data is via the link's low-level index minus 1 (the root link is not included).
- The reduced-coordinate data follows the cache indexing convention, see PxArticulationCache::jointVelocity.
\param[in] maximum The maximal-coordinate joint DOF data with minimum array length N = (getNbLinks() - 1) * 6
\param[out] reduced The reduced-coordinate joint DOF data with minimum array length N = getDofs()
\note The articulation must be in a scene.
\note This can be used as a helper function to prepare per joint cache data such as PxArticulationCache::jointVelocity.
@see unpackJointData
*/
virtual void packJointData(const PxReal* maximum, PxReal* reduced) const = 0;
/**
\brief Converts reduced-coordinate joint DOF data to maximal coordinates.
- Indexing into the maximal joint DOF data is via the link's low-level index minus 1 (the root link is not included).
- The reduced-coordinate data follows the cache indexing convention, see PxArticulationCache::jointVelocity.
\param[in] reduced The reduced-coordinate joint DOF data with minimum array length N = getDofs().
\param[out] maximum The maximal-coordinate joint DOF data with minimum array length N = (getNbLinks() - 1) * 6.
\note The articulation must be in a scene.
@see packJointData
*/
virtual void unpackJointData(const PxReal* reduced, PxReal* maximum) const = 0;
/**
\brief Prepares common articulation data based on articulation pose for inverse dynamics calculations.
Usage:
-# Set articulation pose (joint positions and base transform) via articulation cache and applyCache().
-# Call commonInit.
-# Call inverse dynamics computation method.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see computeGeneralizedGravityForce, computeCoriolisAndCentrifugalForce
*/
virtual void commonInit() const = 0;
/**
\brief Computes the joint DOF forces required to counteract gravitational forces for the given articulation pose.
- Inputs: Articulation pose (joint positions + base transform).
- Outputs: Joint forces to counteract gravity (in cache).
- The joint forces returned are determined purely by gravity for the articulation in the current joint and base pose, and joints at rest;
i.e. external forces, joint velocities, and joint accelerations are set to zero. Joint drives are also not considered in the computation.
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[out] cache Out: PxArticulationCache::jointForce.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit
*/
virtual void computeGeneralizedGravityForce(PxArticulationCache& cache) const = 0;
/**
\brief Computes the joint DOF forces required to counteract Coriolis and centrifugal forces for the given articulation state.
- Inputs: Articulation state (joint positions and velocities (in cache), and base transform and spatial velocity).
- Outputs: Joint forces to counteract Coriolis and centrifugal forces (in cache).
- The joint forces returned are determined purely by the articulation's state; i.e. external forces, gravity, and joint accelerations are set to zero.
Joint drives and potential damping terms, such as link angular or linear damping, or joint friction, are also not considered in the computation.
- Prior to the computation, update/set the base spatial velocity with PxArticulationCache::rootLinkData and applyCache().
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[in,out] cache In: PxArticulationCache::jointVelocity; Out: PxArticulationCache::jointForce.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit
*/
virtual void computeCoriolisAndCentrifugalForce(PxArticulationCache& cache) const = 0;
/**
\brief Computes the joint DOF forces required to counteract external spatial forces applied to articulation links.
- Inputs: External forces on links (in cache), articulation pose (joint positions + base transform).
- Outputs: Joint forces to counteract the external forces (in cache).
- Only the external spatial forces provided in the cache and the articulation pose are considered in the computation.
- The external spatial forces are with respect to the links' centers of mass, and not the actor's origin.
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[in,out] cache In: PxArticulationCache::externalForces; Out: PxArticulationCache::jointForce.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit
*/
virtual void computeGeneralizedExternalForce(PxArticulationCache& cache) const = 0;
/**
\brief Computes the joint accelerations for the given articulation state and joint forces.
- Inputs: Joint forces (in cache) and articulation state (joint positions and velocities (in cache), and base transform and spatial velocity).
- Outputs: Joint accelerations (in cache).
- The computation includes Coriolis terms and gravity. However, joint drives and potential damping terms are not considered in the computation
(for example, linear link damping or joint friction).
- Prior to the computation, update/set the base spatial velocity with PxArticulationCache::rootLinkData and applyCache().
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[in,out] cache In: PxArticulationCache::jointForce and PxArticulationCache::jointVelocity; Out: PxArticulationCache::jointAcceleration.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit
*/
virtual void computeJointAcceleration(PxArticulationCache& cache) const = 0;
/**
\brief Computes the joint forces for the given articulation state and joint accelerations, not considering gravity.
- Inputs: Joint accelerations (in cache) and articulation state (joint positions and velocities (in cache), and base transform and spatial velocity).
- Outputs: Joint forces (in cache).
- The computation includes Coriolis terms. However, joint drives and potential damping terms are not considered in the computation
(for example, linear link damping or joint friction).
- Prior to the computation, update/set the base spatial velocity with PxArticulationCache::rootLinkData and applyCache().
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[in,out] cache In: PxArticulationCache::jointAcceleration and PxArticulationCache::jointVelocity; Out: PxArticulationCache::jointForce.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit
*/
virtual void computeJointForce(PxArticulationCache& cache) const = 0;
/**
\brief Compute the dense Jacobian for the articulation in world space, including the DOFs of a potentially floating base.
This computes the dense representation of an inherently sparse matrix. Multiplication with this matrix maps
joint space velocities to world-space linear and angular (i.e. spatial) velocities of the centers of mass of the links.
\param[out] cache Sets cache.denseJacobian matrix. The matrix is indexed [nCols * row + column].
\param[out] nRows Set to number of rows in matrix, which corresponds to nbLinks() * 6, minus 6 if PxArticulationFlag::eFIX_BASE is true.
\param[out] nCols Set to number of columns in matrix, which corresponds to the number of joint DOFs, plus 6 in the case PxArticulationFlag::eFIX_BASE is false.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
*/
virtual void computeDenseJacobian(PxArticulationCache& cache, PxU32& nRows, PxU32& nCols) const = 0;
/**
\brief Computes the coefficient matrix for contact forces.
- The matrix dimension is getCoefficientMatrixSize() = getDofs() * getNbLoopJoints(), and the DOF (column) indexing follows the internal DOF order, see PxArticulationCache::jointVelocity.
- Each column in the matrix is the joint forces effected by a contact based on impulse strength 1.
- The user must allocate memory for PxArticulationCache::coefficientMatrix where the required size of the PxReal array is equal to getCoefficientMatrixSize().
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[out] cache Out: PxArticulationCache::coefficientMatrix.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit, getCoefficientMatrixSize
*/
virtual void computeCoefficientMatrix(PxArticulationCache& cache) const = 0;
/**
\brief Computes the lambda values when the test impulse is 1.
- The user must allocate memory for PxArticulationCache::lambda where the required size of the PxReal array is equal to getNbLoopJoints().
- commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[out] cache Out: PxArticulationCache::lambda.
\param[in] initialState The initial state of the articulation system.
\param[in] jointTorque M(q)*qddot + C(q,qdot) + g(q) <- calculate by summing joint forces obtained with computeJointForce and computeGeneralizedGravityForce.
\param[in] maxIter Maximum number of solver iterations to run. If the system converges, fewer iterations may be used.
\return True if convergence was achieved within maxIter; False if convergence was not achieved or the operation failed otherwise.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit, getNbLoopJoints
*/
virtual bool computeLambda(PxArticulationCache& cache, PxArticulationCache& initialState, const PxReal* const jointTorque, const PxU32 maxIter) const = 0;
/**
\brief Compute the joint-space inertia matrix that maps joint accelerations to joint forces: forces = M * accelerations.
- Inputs: Articulation pose (joint positions and base transform).
- Outputs: Mass matrix (in cache).
commonInit() must be called before the computation, and after setting the articulation pose via applyCache().
\param[out] cache Out: PxArticulationCache::massMatrix.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see commonInit
*/
virtual void computeGeneralizedMassMatrix(PxArticulationCache& cache) const = 0;
/**
\brief Adds a loop joint to the articulation system for inverse dynamics.
\param[in] joint The joint to add.
\note This call may not be made during simulation.
@see PxContactJoint, PxFixedJoint, PxSphericalJoint, PxRevoluteJoint, PxPrismaticJoint, PxDistanceJoint, PxD6Joint
*/
virtual void addLoopJoint(PxConstraint* joint) = 0;
/**
\brief Removes a loop joint from the articulation for inverse dynamics.
\note This call may not be made during simulation.
\param[in] joint The joint to remove.
*/
virtual void removeLoopJoint(PxConstraint* joint) = 0;
/**
\brief Returns the number of loop joints in the articulation for inverse dynamics.
\return The number of loop joints.
*/
virtual PxU32 getNbLoopJoints() const = 0;
/**
\brief Returns the set of loop constraints (i.e. joints) in the articulation.
\param[in] userBuffer Target buffer for the constraint pointers.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to the constraints,
only as many as will fit are written. Use getNbLoopJoints() to size the buffer for retrieving all constraints.
\param[in] startIndex Index of first constraint pointer to be retrieved.
\return The number of constraints written into the buffer.
*/
virtual PxU32 getLoopJoints(PxConstraint** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the required size of the coefficient matrix in the articulation.
\return Size of the coefficient matrix (equal to getDofs() * getNbLoopJoints()).
\note This call may only be made on articulations that are in a scene.
@see computeCoefficientMatrix
*/
virtual PxU32 getCoefficientMatrixSize() const = 0;
/**
\brief Sets the root link transform in the world frame.
- Use updateKinematic() after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] pose The new root link transform.
\param[in] autowake If true and the articulation is in a scene, the articulation will be woken up and the wake counter of
each link will be reset to #PxSceneDesc::wakeCounterResetValue.
\note This call may not be made during simulation.
\note PxArticulationCache::rootLinkData similarly allows the root link pose to be updated and potentially offers better performance
if the root link pose is to be updated along with other state variables.
@see getRootGlobalPose, updateKinematic, PxArticulationCache, applyCache
*/
virtual void setRootGlobalPose(const PxTransform& pose, bool autowake = true) = 0;
/**
\brief Returns the root link transform (world to actor frame).
\return The root link transform.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
\note PxArticulationCache::rootLinkData similarly allows the root link pose to be queried and potentially offers better performance if the root
link pose is to be queried along with other state variables.
@see setRootGlobalPose, PxArticulationCache, copyInternalStateToCache
*/
virtual PxTransform getRootGlobalPose() const = 0;
/**
\brief Sets the root link linear center-of-mass velocity.
- The linear velocity is with respect to the link's center of mass and not the actor frame origin.
- The articulation is woken up if the input velocity is nonzero (ignoring autowake) and the articulation is in a scene.
- Use updateKinematic() after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] linearVelocity The new root link center-of-mass linear velocity.
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
\note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance.
\note PxArticulationCache::rootLinkData similarly allows the root link linear velocity to be updated and potentially offers better performance
if the root link linear velocity is to be updated along with other state variables.
@see updateKinematic, getRootLinearVelocity, setRootAngularVelocity, getRootAngularVelocity, PxRigidBody::getCMassLocalPose, PxArticulationCache, applyCache
*/
virtual void setRootLinearVelocity(const PxVec3& linearVelocity, bool autowake = true) = 0;
/**
\brief Gets the root link center-of-mass linear velocity.
- The linear velocity is with respect to the link's center of mass and not the actor frame origin.
\return The root link center-of-mass linear velocity.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
\note PxArticulationCache::rootLinkData similarly allows the root link linear velocity to be queried and potentially offers better performance
if the root link linear velocity is to be queried along with other state variables.
@see setRootLinearVelocity, setRootAngularVelocity, getRootAngularVelocity, PxRigidBody::getCMassLocalPose, PxArticulationCache, applyCache
*/
virtual PxVec3 getRootLinearVelocity(void) const = 0;
/**
\brief Sets the root link angular velocity.
- The articulation is woken up if the input velocity is nonzero (ignoring autowake) and the articulation is in a scene.
- Use updateKinematic() after all state updates to the articulation via non-cache API such as this method,
in order to update link states for the next simulation frame or querying.
\param[in] angularVelocity The new root link angular velocity.
\param[in] autowake If true and the articulation is in a scene, the call wakes up the articulation and increases the wake counter
to #PxSceneDesc::wakeCounterResetValue if the counter value is below the reset value.
\note This call may not be made during simulation, except in a split simulation in-between #PxScene::fetchCollision and #PxScene::advance.
\note PxArticulationCache::rootLinkData similarly allows the root link angular velocity to be updated and potentially offers better performance
if the root link angular velocity is to be updated along with other state variables.
@see updateKinematic, getRootAngularVelocity, setRootLinearVelocity, getRootLinearVelocity, PxArticulationCache, applyCache
*/
virtual void setRootAngularVelocity(const PxVec3& angularVelocity, bool autowake = true) = 0;
/**
\brief Gets the root link angular velocity.
\return The root link angular velocity.
\note This call is not allowed while the simulation is running except in a split simulation during #PxScene::collide() and up to #PxScene::advance(),
and in PxContactModifyCallback or in contact report callbacks.
\note PxArticulationCache::rootLinkData similarly allows the root link angular velocity to be queried and potentially offers better performance
if the root link angular velocity is to be queried along with other state variables.
@see setRootAngularVelocity, setRootLinearVelocity, getRootLinearVelocity, PxArticulationCache, applyCache
*/
virtual PxVec3 getRootAngularVelocity(void) const = 0;
/**
\brief Returns the (classical) link acceleration in world space for the given low-level link index.
- The returned acceleration is not a spatial, but a classical, i.e. body-fixed acceleration (https://en.wikipedia.org/wiki/Spatial_acceleration).
- The (linear) acceleration is with respect to the link's center of mass and not the actor frame origin.
\param[in] linkId The low-level link index, see PxArticulationLink::getLinkIndex.
\return The link's center-of-mass classical acceleration, or 0 if the call is made before the articulation participated in a first simulation step.
\note This call may only be made on articulations that are in a scene. It is not allowed to use this method while the simulation
is running. The exceptions to this rule are a split simulation during #PxScene::collide() and up to #PxScene::advance();
in PxContactModifyCallback; and in contact report callbacks.
@see PxArticulationLink::getLinkIndex, PxRigidBody::getCMassLocalPose
*/
virtual PxSpatialVelocity getLinkAcceleration(const PxU32 linkId) = 0;
/**
\brief Returns the GPU articulation index.
\return The GPU index, or 0xFFFFFFFF if the articulation is not in a scene or PxSceneFlag::eENABLE_DIRECT_GPU_API is not set.
*/
virtual PxU32 getGpuArticulationIndex() = 0;
/**
\brief Creates a spatial tendon to attach to the articulation with default attribute values.
\return The new spatial tendon.
\note Creating a spatial tendon is not allowed while the articulation is in a scene. In order to
add the tendon, remove and then re-add the articulation to the scene.
\note The spatial tendon is released with PxArticulationReducedCoordinate::release()
@see PxArticulationSpatialTendon
*/
virtual PxArticulationSpatialTendon* createSpatialTendon() = 0;
/**
\brief Creates a fixed tendon to attach to the articulation with default attribute values.
\return The new fixed tendon.
\note Creating a fixed tendon is not allowed while the articulation is in a scene. In order to
add the tendon, remove and then re-add the articulation to the scene.
\note The fixed tendon is released with PxArticulationReducedCoordinate::release()
@see PxArticulationFixedTendon
*/
virtual PxArticulationFixedTendon* createFixedTendon() = 0;
/**
@deprecated
\brief Creates a force sensor attached to a link of the articulation.
\param[in] link The link to attach the sensor to.
\param[in] relativePose The sensor frame's relative pose to the link's body frame, i.e. the transform body frame -> sensor frame.
The link body frame is at the center of mass and aligned with the principal axes of inertia, see PxRigidBody::getCMassLocalPose.
\return The new sensor.
\note Creating a sensor is not allowed while the articulation is in a scene. In order to
add the sensor, remove and then re-add the articulation to the scene.
\note The sensor is released with PxArticulationReducedCoordinate::release()
@see PxArticulationSensor
*/
virtual PX_DEPRECATED PxArticulationSensor* createSensor(PxArticulationLink* link, const PxTransform& relativePose) = 0;
/**
\brief Returns the spatial tendons attached to the articulation.
The order of the tendons in the buffer is not necessarily identical to the order in which the tendons were added to the articulation.
\param[in] userBuffer The buffer into which to write the array of pointers to the tendons.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendons,
only as many as will fit are written. Use getNbSpatialTendons to size for all attached tendons.
\param[in] startIndex Index of first tendon pointer to be retrieved.
\return The number of tendons written into the buffer.
@see PxArticulationSpatialTendon, getNbSpatialTendons
*/
virtual PxU32 getSpatialTendons(PxArticulationSpatialTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of spatial tendons in the articulation.
\return The number of tendons.
*/
virtual PxU32 getNbSpatialTendons() = 0;
/**
\brief Returns the fixed tendons attached to the articulation.
The order of the tendons in the buffer is not necessarily identical to the order in which the tendons were added to the articulation.
\param[in] userBuffer The buffer into which to write the array of pointers to the tendons.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to tendons,
only as many as will fit are written. Use getNbFixedTendons to size for all attached tendons.
\param[in] startIndex Index of first tendon pointer to be retrieved.
\return The number of tendons written into the buffer.
@see PxArticulationFixedTendon, getNbFixedTendons
*/
virtual PxU32 getFixedTendons(PxArticulationFixedTendon** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Returns the number of fixed tendons in the articulation.
\return The number of tendons.
*/
virtual PxU32 getNbFixedTendons() = 0;
/**
@deprecated
\brief Returns the sensors attached to the articulation.
The order of the sensors in the buffer is not necessarily identical to the order in which the sensors were added to the articulation.
\param[in] userBuffer The buffer into which to write the array of pointers to the sensors.
\param[in] bufferSize The size of the buffer. If this is not large enough to contain all the pointers to sensors,
only as many as will fit are written. Use getNbSensors to size for all attached sensors.
\param[in] startIndex Index of first sensor pointer to be retrieved.
\return The number of sensors written into the buffer.
@see PxArticulationSensor, getNbSensors
*/
virtual PX_DEPRECATED PxU32 getSensors(PxArticulationSensor** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
@deprecated
\brief Returns the number of sensors in the articulation.
\return The number of sensors.
*/
virtual PX_DEPRECATED PxU32 getNbSensors() = 0;
/**
\brief Update link velocities and/or positions in the articulation.
An alternative that potentially offers better performance is to use the PxArticulationCache API.
If the application updates the root state (position and velocity) or joint state via any combination of
the non-cache API calls
- setRootGlobalPose(), setRootLinearVelocity(), setRootAngularVelocity()
- PxArticulationJointReducedCoordinate::setJointPosition(), PxArticulationJointReducedCoordinate::setJointVelocity()
the application needs to call this method after the state setting in order to update the link states for
the next simulation frame or querying.
Use
- PxArticulationKinematicFlag::ePOSITION after any changes to the articulation root or joint positions using non-cache API calls. Updates links' positions and velocities.
- PxArticulationKinematicFlag::eVELOCITY after velocity-only changes to the articulation root or joints using non-cache API calls. Updates links' velocities only.
\note This call may only be made on articulations that are in a scene, and may not be made during simulation.
@see PxArticulationKinematicFlags, PxArticulationCache, applyCache
*/
virtual void updateKinematic(PxArticulationKinematicFlags flags) = 0;
virtual ~PxArticulationReducedCoordinate() {}
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxArticulationReducedCoordinate(PxType concreteType, PxBaseFlags baseFlags) : PxBase(concreteType, baseFlags) {}
PX_INLINE PxArticulationReducedCoordinate(PxBaseFlags baseFlags) : PxBase(baseFlags) {}
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 62,696 | C | 40.909759 | 191 | 0.755854 |
NVIDIA-Omniverse/PhysX/physx/include/PxParticleBuffer.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_PARTICLE_BUFFER_H
#define PX_PARTICLE_BUFFER_H
/** \addtogroup physics
@{ */
#include "common/PxBase.h"
#include "common/PxPhysXCommonConfig.h"
#include "common/PxTypeInfo.h"
#include "PxParticleSystemFlag.h"
#include "foundation/PxBounds3.h"
#include "foundation/PxSimpleTypes.h"
#include "foundation/PxVec4.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4435)
#endif
class PxCudaContextManager;
struct PxParticleRigidFilterPair;
struct PxParticleRigidAttachment;
/**
\brief Particle volume structure. Used to track the bounding volume of a user-specified set of particles. The particles are required
to be laid out contiguously within the same PxParticleBuffer.
*/
PX_ALIGN_PREFIX(16)
struct PxParticleVolume
{
PxBounds3 bound; //!< The current bounds of the particles contained in this #PxParticleVolume.
PxU32 particleIndicesOffset; //!< The index into the particle list of the #PxParticleBuffer for the first particle of this volume.
PxU32 numParticles; //!< The number of particles contained in this #PxParticleVolume.
} PX_ALIGN_SUFFIX(16);
/**
\brief The shared base class for all particle buffers, can be instantiated directly to simulate granular and fluid particles.
See #PxPhysics::createParticleBuffer.
A particle buffer is a container that specifies per-particle attributes of a set of particles that will be used during the simulation
of a particle system. It exposes direct access to the underlying GPU buffers and is independent of the scene and particle system. Particle
buffers can be added/removed from a particle system at any time between simulation steps, and transferred from one particle system to another.
*/
class PxParticleBuffer : public PxBase
{
public:
/**
\brief Get positions and inverse masses for this particle buffer.
\return A pointer to a device buffer containing the positions and inverse mass packed as PxVec4(pos.x, pos.y, pos.z, inverseMass).
*/
virtual PxVec4* getPositionInvMasses() const = 0;
/**
\brief Get velocities for this particle buffer.
\return A pointer to a device buffer containing the velocities packed as PxVec4(vel.x, vel.y, vel.z, 0.0f).
*/
virtual PxVec4* getVelocities() const = 0;
/**
\brief Get phases for this particle buffer.
See #PxParticlePhase
\return A pointer to a device buffer containing the per-particle phases for this particle buffer.
*/
virtual PxU32* getPhases() const = 0;
/**
\brief Get particle volumes for this particle buffer.
See #PxParticleVolume
\return A pointer to a device buffer containing the #PxParticleVolume s for this particle buffer.
*/
virtual PxParticleVolume* getParticleVolumes() const = 0;
/**
\brief Set the number of active particles for this particle buffer.
\param[in] nbActiveParticles The number of active particles.
The number of active particles can be <= PxParticleBuffer::getMaxParticles(). The particle system will simulate the first
x particles in the #PxParticleBuffer, where x is the number of active particles.
*/
virtual void setNbActiveParticles(PxU32 nbActiveParticles) = 0;
/**
\brief Get the number of active particles for this particle buffer.
\return The number of active particles.
*/
virtual PxU32 getNbActiveParticles() const = 0;
/**
\brief Get the maximum number particles this particle buffer can hold.
The maximum number of particles is specified when creating a #PxParticleBuffer. See #PxPhysics::createParticleBuffer.
\return The maximum number of particles.
*/
virtual PxU32 getMaxParticles() const = 0;
/**
\brief Get the number of particle volumes in this particle buffer.
\return The number of #PxParticleVolume s for this particle buffer.
*/
virtual PxU32 getNbParticleVolumes() const = 0;
/**
\brief Set the number of #PxParticleVolume s for this particle buffer.
\param[in] nbParticleVolumes The number of particle volumes in this particle buffer.
*/
virtual void setNbParticleVolumes(PxU32 nbParticleVolumes) = 0;
/**
\brief Get the maximum number of particle volumes this particle buffer can hold.
See #PxParticleVolume.
\return The maximum number of particle volumes this particle buffer can hold.
*/
virtual PxU32 getMaxParticleVolumes() const = 0;
/**
\brief Set the #PxParticleRigidFilterPair s for collision filtering of particles in this buffer with rigid bodies.
See #PxParticleRigidFilterPair
\param[in] filters A device buffer containing #PxParticleRigidFilterPair s.
\param[in] nbFilters The number of particle-rigid body collision filtering pairs.
*/
virtual void setRigidFilters(PxParticleRigidFilterPair* filters, PxU32 nbFilters) = 0;
/**
\brief Set the particle-rigid body attachments for particles in this particle buffer.
See #PxParticleRigidAttachment
\param[in] attachments A device buffer containing #PxParticleRigidAttachment s.
\param[in] nbAttachments The number of particle-rigid body attachments.
*/
virtual void setRigidAttachments(PxParticleRigidAttachment* attachments, PxU32 nbAttachments) = 0;
/**
\brief Get the start index for the first particle of this particle buffer in the complete list of
particles of the particle system this buffer is used in.
The return value is only correct if the particle buffer is assigned to a particle system and at least
one call to simulate() has been performed.
\return The index of the first particle in the complete particle list.
*/
virtual PxU32 getFlatListStartIndex() const = 0;
/**
\brief Raise dirty flags on this particle buffer to communicate that the corresponding data has been updated
by the user.
\param[in] flags The flag corresponding to the data that is dirty.
See #PxParticleBufferFlag.
*/
virtual void raiseFlags(PxParticleBufferFlag::Enum flags) = 0;
/**
\brief Release this buffer and deallocate all the memory.
*/
virtual void release() = 0;
/**
\brief Cleanup helper used in case a particle system is released before the particle buffers have been removed.
*/
virtual void onParticleSystemDestroy() = 0;
/**
\brief Reserved for internal use.
*/
virtual void setInternalData(void* data) = 0;
/**
\brief Index of this buffer in the particle system it is assigned to.
*/
PxU32 bufferIndex;
/**
\brief Unique index that does not change over the lifetime of a PxParticleBuffer.
*/
const PxU32 bufferUniqueId;
protected:
virtual ~PxParticleBuffer() { }
PX_INLINE PxParticleBuffer(PxU32 uniqueId) : PxBase(PxConcreteType::ePARTICLE_BUFFER, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), bufferIndex(0xffffffff), bufferUniqueId(uniqueId){}
PX_INLINE PxParticleBuffer(PxU32 uniqueId, PxType type) : PxBase(type, PxBaseFlag::eOWNS_MEMORY | PxBaseFlag::eIS_RELEASABLE), bufferIndex(0xffffffff), bufferUniqueId(uniqueId){}
private:
PX_NOCOPY(PxParticleBuffer)
};
/**
\brief Parameters to configure the behavior of diffuse particles
*/
class PxDiffuseParticleParams
{
public:
/**
\brief Construct parameters with default values.
*/
PX_INLINE PxDiffuseParticleParams()
{
threshold = 100.0f;
lifetime = 5.0f;
airDrag = 0.0f;
bubbleDrag = 0.5f;
buoyancy = 0.8f;
kineticEnergyWeight = 0.01f;
pressureWeight = 1.0f;
divergenceWeight = 5.0f;
collisionDecay = 0.5f;
useAccurateVelocity = false;
}
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault()
{
*this = PxDiffuseParticleParams();
}
PxReal threshold; //!< Particles with potential value greater than the threshold will spawn diffuse particles
PxReal lifetime; //!< Diffuse particle will be removed after the specified lifetime
PxReal airDrag; //!< Air drag force factor for spray particles
PxReal bubbleDrag; //!< Fluid drag force factor for bubble particles
PxReal buoyancy; //!< Buoyancy force factor for bubble particles
PxReal kineticEnergyWeight; //!< Contribution from kinetic energy when deciding diffuse particle creation.
PxReal pressureWeight; //!< Contribution from pressure when deciding diffuse particle creation.
PxReal divergenceWeight; //!< Contribution from divergence when deciding diffuse particle creation.
PxReal collisionDecay; //!< Decay factor of diffuse particles' lifetime after they collide with shapes.
bool useAccurateVelocity; //!< If true, enables accurate velocity estimation when using PBD solver.
};
/**
\brief A particle buffer used to simulate diffuse particles.
See #PxPhysics::createParticleAndDiffuseBuffer.
*/
class PxParticleAndDiffuseBuffer : public PxParticleBuffer
{
public:
/**
\brief Get a device buffer of positions and remaining lifetimes for the diffuse particles.
\return A device buffer containing positions and lifetimes of diffuse particles packed as PxVec4(pos.x, pos.y, pos.z, lifetime).
*/
virtual PxVec4* getDiffusePositionLifeTime() const = 0;
/**
\brief Get number of currently active diffuse particles.
\return The number of currently active diffuse particles.
*/
virtual PxU32 getNbActiveDiffuseParticles() const = 0;
/**
\brief Set the maximum possible number of diffuse particles for this buffer.
\param[in] maxActiveDiffuseParticles the maximum number of active diffuse particles.
\note Must be in the range [0, PxParticleAndDiffuseBuffer::getMaxDiffuseParticles()]
*/
virtual void setMaxActiveDiffuseParticles(PxU32 maxActiveDiffuseParticles) = 0;
/**
\brief Get maximum possible number of diffuse particles.
\return The maximum possible number diffuse particles.
*/
virtual PxU32 getMaxDiffuseParticles() const = 0;
/**
\brief Set the parameters for diffuse particle simulation.
\param[in] params The diffuse particle parameters.
See #PxDiffuseParticleParams
*/
virtual void setDiffuseParticleParams(const PxDiffuseParticleParams& params) = 0;
/**
\brief Get the parameters currently used for diffuse particle simulation.
\return A PxDiffuseParticleParams structure.
*/
virtual PxDiffuseParticleParams getDiffuseParticleParams() const = 0;
protected:
virtual ~PxParticleAndDiffuseBuffer() {}
PX_INLINE PxParticleAndDiffuseBuffer(PxU32 uniqueId) : PxParticleBuffer(uniqueId, PxConcreteType::ePARTICLE_DIFFUSE_BUFFER){}
private:
PX_NOCOPY(PxParticleAndDiffuseBuffer)
};
/**
\brief Holds all the information for a spring constraint between two particles. Used for particle cloth simulation.
*/
struct PX_ALIGN_PREFIX(8) PxParticleSpring
{
PxU32 ind0; //!< particle index of first particle
PxU32 ind1; //!< particle index of second particle
PxReal length; //!< spring length
PxReal stiffness; //!< spring stiffness
PxReal damping; //!< spring damping factor
PxReal pad; //!< padding bytes.
} PX_ALIGN_SUFFIX(8);
/**
\brief Particle cloth structure. Holds information about a single piece of cloth that is part of a #PxParticleClothBuffer.
*/
struct PxParticleCloth
{
PxU32 startVertexIndex; //!< Index of the first particle of this cloth in the position/velocity buffers of the parent #PxParticleClothBuffer
PxU32 numVertices; //!< The number of particles of this piece of cloth
PxReal clothBlendScale; //!< Used internally.
PxReal restVolume; //!< The rest volume of this piece of cloth, used for inflatable simulation.
PxReal pressure; //!< The factor of the rest volume to specify the target volume for this piece of cloth, used for inflatable simulation.
PxU32 startTriangleIndex; //!< The index of the first triangle of this piece of cloth in the triangle list.
PxU32 numTriangles; //!< The number of triangles of this piece of cloth.
bool operator <= (const PxParticleCloth& other) const { return startVertexIndex <= other.startVertexIndex; }
bool operator >= (const PxParticleCloth& other) const { return startVertexIndex >= other.startVertexIndex; }
bool operator < (const PxParticleCloth& other) const { return startVertexIndex < other.startVertexIndex; }
bool operator > (const PxParticleCloth& other) const { return startVertexIndex > other.startVertexIndex; }
bool operator == (const PxParticleCloth& other) const { return startVertexIndex == other.startVertexIndex; }
};
/**
\brief Structure to describe the set of particle cloths in the same #PxParticleClothBuffer. Used an input for the cloth preprocessing.
*/
struct PxParticleClothDesc
{
PxParticleClothDesc() : cloths(NULL), triangles(NULL), springs(NULL), restPositions(NULL),
nbCloths(0), nbSprings(0), nbTriangles(0), nbParticles(0)
{
}
PxParticleCloth* cloths; //!< List of PxParticleCloth s, describes the individual cloths.
PxU32* triangles; //!< List of triangle indices, 3 consecutive PxU32 that map triangle vertices to particles
PxParticleSpring* springs; //!< List of PxParticleSpring s.
PxVec4* restPositions; //!< List of rest positions for all particles
PxU32 nbCloths; //!< The number of cloths in described using this cloth descriptor
PxU32 nbSprings; //!< The number of springs in this cloth descriptor
PxU32 nbTriangles; //!< The number of triangles in this cloth descriptor
PxU32 nbParticles; //!< The number of particles in this cloth descriptor
};
/**
\brief Structure to describe the output of the particle cloth preprocessing. Used as an input to specify cloth data for a #PxParticleClothBuffer.
All the pointers point to pinned host memory.
See #PxParticleClothPreProcessor
*/
struct PX_PHYSX_CORE_API PxPartitionedParticleCloth
{
PxU32* accumulatedSpringsPerPartitions; //!< The number of springs in each partition. Size: numPartitions.
PxU32* accumulatedCopiesPerParticles; //!< Start index for each particle in the accumulation buffer. Size: numParticles.
PxU32* remapOutput; //!< Index of the next copy of this particle in the next partition, or in the accumulation buffer. Size: numSprings * 2.
PxParticleSpring* orderedSprings; //!< Springs ordered by partition. Size: numSprings.
PxU32* sortedClothStartIndices; //!< The first particle index into the position buffer of the #PxParticleClothBuffer for each cloth. Cloths are sorted by start particle index. Size: numCloths.
PxParticleCloth* cloths; //!< The #PxParticleCloth s sorted by start particle index.
PxU32 remapOutputSize; //!< Size of remapOutput.
PxU32 nbPartitions; //!< The number of partitions.
PxU32 nbSprings; //!< The number of springs.
PxU32 nbCloths; //!< The number of cloths.
PxU32 maxSpringsPerPartition; //!< The maximum number of springs in a partition.
PxCudaContextManager* mCudaManager; //!< A cuda context manager.
PxPartitionedParticleCloth();
~PxPartitionedParticleCloth();
/**
\brief allocate all the buffers for this #PxPartitionedParticleCloth.
\param[in] nbParticles the number of particles this #PxPartitionedParticleCloth will be generated for.
\param[in] cudaManager a cuda context manager.
*/
void allocateBuffers(PxU32 nbParticles, PxCudaContextManager* cudaManager);
};
/**
\brief A particle buffer used to simulate particle cloth.
See #PxPhysics::createParticleClothBuffer.
*/
class PxParticleClothBuffer : public PxParticleBuffer
{
public:
/**
\brief Get rest positions for this particle buffer.
\return A pointer to a device buffer containing the rest positions packed as PxVec4(pos.x, pos.y, pos.z, 0.0f).
*/
virtual PxVec4* getRestPositions() = 0;
/**
\brief Get the triangle indices for this particle buffer.
\return A pointer to a device buffer containing the triangle indices for this cloth buffer.
*/
virtual PxU32* getTriangles() const = 0;
/**
\brief Set the number of triangles for this particle buffer.
\param[in] nbTriangles The number of triangles for this particle cloth buffer.
*/
virtual void setNbTriangles(PxU32 nbTriangles) = 0;
/**
\brief Get the number of triangles for this particle buffer.
\return The number triangles for this cloth buffer.
*/
virtual PxU32 getNbTriangles() const = 0;
/**
\brief Get the number of springs in this particle buffer.
\return The number of springs in this cloth buffer.
*/
virtual PxU32 getNbSprings() const = 0;
/**
\brief Get the springs for this particle buffer.
\return A pointer to a device buffer containing the springs for this cloth buffer.
*/
virtual PxParticleSpring* getSprings() = 0;
/**
\brief Set cloths for this particle buffer.
\param[in] cloths A pointer to a PxPartitionedParticleCloth.
See #PxPartitionedParticleCloth, #PxParticleClothPreProcessor
*/
virtual void setCloths(PxPartitionedParticleCloth& cloths) = 0;
protected:
virtual ~PxParticleClothBuffer() {}
PX_INLINE PxParticleClothBuffer(PxU32 uniqueId) : PxParticleBuffer(uniqueId, PxConcreteType::ePARTICLE_CLOTH_BUFFER) {}
private:
PX_NOCOPY(PxParticleClothBuffer)
};
/**
\brief A particle buffer used to simulate rigid bodies using shape matching with particles.
See #PxPhysics::createParticleRigidBuffer.
*/
class PxParticleRigidBuffer : public PxParticleBuffer
{
public:
/**
\brief Get the particle indices of the first particle for each shape matched rigid body.
\return A device buffer containing the list of particle start indices of each shape matched rigid body.
*/
virtual PxU32* getRigidOffsets() const = 0;
/**
\brief Get the stiffness coefficients for all shape matched rigid bodies in this buffer.
Stiffness must be in the range [0, 1].
\return A device buffer containing the list of stiffness coefficients for each rigid body.
*/
virtual PxReal* getRigidCoefficients() const = 0;
/**
\brief Get the local position of each particle relative to the rigid body's center of mass.
\return A pointer to a device buffer containing the local position for each particle.
*/
virtual PxVec4* getRigidLocalPositions() const = 0;
/**
\brief Get the world-space translations for all rigid bodies in this buffer.
\return A pointer to a device buffer containing the world-space translations for all shape-matched rigid bodies in this buffer.
*/
virtual PxVec4* getRigidTranslations() const = 0;
/**
\brief Get the world-space rotation of every shape-matched rigid body in this buffer.
Rotations are specified as quaternions.
\return A pointer to a device buffer containing the world-space rotation for every shape-matched rigid body in this buffer.
*/
virtual PxVec4* getRigidRotations() const = 0;
/**
\brief Get the local space normals for each particle relative to the shape of the corresponding rigid body.
The 4th component of every PxVec4 should be the negative signed distance of the particle inside its shape.
\return A pointer to a device buffer containing the local-space normals for each particle.
*/
virtual PxVec4* getRigidLocalNormals() const = 0;
/**
\brief Set the number of shape matched rigid bodies in this buffer.
\param[in] nbRigids The number of shape matched rigid bodies
*/
virtual void setNbRigids(PxU32 nbRigids) = 0;
/**
\brief Get the number of shape matched rigid bodies in this buffer.
\return The number of shape matched rigid bodies in this buffer.
*/
virtual PxU32 getNbRigids() const = 0;
protected:
virtual ~PxParticleRigidBuffer() {}
PX_INLINE PxParticleRigidBuffer(PxU32 uniqueId) : PxParticleBuffer(uniqueId, PxConcreteType::ePARTICLE_RIGID_BUFFER) {}
private:
PX_NOCOPY(PxParticleRigidBuffer)
};
/**
@brief Preprocessor to prepare particle cloths for simulation.
Preprocessing is done by calling #PxParticleClothPreProcessor::partitionSprings() on an instance of this class. This will allocate the memory in the
output object, partition the springs and fill all the members of the ouput object. The output can then be passed without
any further modifications to #PxParticleClothBuffer::setCloths().
See #PxCreateParticleClothPreprocessor, #PxParticleClothDesc, #PxPartitionedParticleCloth
*/
class PxParticleClothPreProcessor
{
public:
/**
\brief Release this object and deallocate all the memory.
*/
virtual void release() = 0;
/**
\brief Partition the spring constraints for particle cloth simulation.
\param[in] clothDesc Reference to a valid #PxParticleClothDesc.
\param[in] output Reference to a #PxPartitionedParticleCloth object. This is the output of the preprocessing and should be passed to a #PxParticleClothBuffer.
*/
virtual void partitionSprings(const PxParticleClothDesc& clothDesc, PxPartitionedParticleCloth& output) = 0;
protected:
virtual ~PxParticleClothPreProcessor(){}
};
#if PX_VC
#pragma warning(pop)
#endif
#if !PX_DOXYGEN
} // namespace physx
#endif
/**
\brief Create a particle cloth preprocessor.
\param[in] cudaContextManager A cuda context manager.
See #PxParticleClothDesc, #PxPartitionedParticleCloth.
*/
PX_C_EXPORT PX_PHYSX_CORE_API physx::PxParticleClothPreProcessor* PX_CALL_CONV PxCreateParticleClothPreProcessor(physx::PxCudaContextManager* cudaContextManager);
/** @} */
#endif
| 22,588 | C | 36.091954 | 200 | 0.760005 |
NVIDIA-Omniverse/PhysX/physx/include/PxActorData.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_ACTOR_DATA_H
#define PX_ACTOR_DATA_H
/** \addtogroup physics
@{
*/
#include "foundation/PxVec4.h"
#include "foundation/PxQuat.h"
#include "foundation/PxFlags.h"
#include "PxNodeIndex.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Identifies each type of information for retrieving from actor.
@see PxScene::applyActorData
*/
struct PxActorCacheFlag
{
enum Enum
{
eACTOR_DATA = (1 << 0), //include transform and velocity
eFORCE = (1 << 2),
eTORQUE = (1 << 3)
};
};
/**
\brief Collection of set bits defined in PxActorCacheFlag.
@see PxActorCacheFlag
*/
typedef PxFlags<PxActorCacheFlag::Enum, PxU16> PxActorCacheFlags;
PX_FLAGS_OPERATORS(PxActorCacheFlag::Enum, PxU16)
/**
\brief State of a body used when interfacing with the GPU rigid body pipeline
@see PxScene.copyBodyData()
*/
PX_ALIGN_PREFIX(16)
struct PxGpuBodyData
{
PxQuat quat; /*!< actor global pose quaternion in world frame */
PxVec4 pos; /*!< (x,y,z members): actor global pose position in world frame */
PxVec4 linVel; /*!< (x,y,z members): linear velocity at center of gravity in world frame */
PxVec4 angVel; /*!< (x,y,z members): angular velocity in world frame */
}
PX_ALIGN_SUFFIX(16);
/**
\brief Pair correspondence used for matching array indices with body node indices
*/
PX_ALIGN_PREFIX(8)
struct PxGpuActorPair
{
PxU32 srcIndex; //Defines which index in src array we read
PxNodeIndex nodeIndex; //Defines which actor this entry in src array is updating
}
PX_ALIGN_SUFFIX(8);
/**
\brief Maps numeric index to a data pointer.
@see PxScene::computeDenseJacobians(), PxScene::computeGeneralizedMassMatrices(), PxScene::computeGeneralizedGravityForces(), PxScene::computeCoriolisAndCentrifugalForces()
*/
struct PxIndexDataPair
{
PxU32 index;
void* data;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,608 | C | 31.223214 | 173 | 0.732816 |
NVIDIA-Omniverse/PhysX/physx/include/PxShape.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_SHAPE_H
#define PX_SHAPE_H
/** \addtogroup physics
@{
*/
#include "PxPhysXConfig.h"
#include "common/PxBase.h"
#include "geometry/PxGeometry.h"
#include "geometry/PxGeometryHelpers.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxBoxGeometry;
class PxSphereGeometry;
class PxCapsuleGeometry;
class PxPlaneGeometry;
class PxConvexMeshGeometry;
class PxTriangleMeshGeometry;
class PxTetrahedronMeshGeometry;
class PxHeightFieldGeometry;
class PxParticleSystemGeometry;
class PxHairSystemGeometry;
class PxRigidActor;
struct PxFilterData;
class PxBaseMaterial;
class PxMaterial;
class PxFEMSoftBodyMaterial;
class PxFEMClothMaterial;
/**
\brief Flags which affect the behavior of PxShapes.
@see PxShape PxShape.setFlag()
*/
struct PxShapeFlag
{
enum Enum
{
/**
\brief The shape will partake in collision in the physical simulation.
\note It is illegal to raise the eSIMULATION_SHAPE and eTRIGGER_SHAPE flags.
In the event that one of these flags is already raised the sdk will reject any
attempt to raise the other. To raise the eSIMULATION_SHAPE first ensure that
eTRIGGER_SHAPE is already lowered.
\note This flag has no effect if simulation is disabled for the corresponding actor (see #PxActorFlag::eDISABLE_SIMULATION).
@see PxSimulationEventCallback.onContact() PxScene.setSimulationEventCallback() PxShape.setFlag(), PxShape.setFlags()
*/
eSIMULATION_SHAPE = (1<<0),
/**
\brief The shape will partake in scene queries (ray casts, overlap tests, sweeps, ...).
*/
eSCENE_QUERY_SHAPE = (1<<1),
/**
\brief The shape is a trigger which can send reports whenever other shapes enter/leave its volume.
\note Triangle meshes and heightfields can not be triggers. Shape creation will fail in these cases.
\note Shapes marked as triggers do not collide with other objects. If an object should act both
as a trigger shape and a collision shape then create a rigid body with two shapes, one being a
trigger shape and the other a collision shape. It is illegal to raise the eTRIGGER_SHAPE and
eSIMULATION_SHAPE flags on a single PxShape instance. In the event that one of these flags is already
raised the sdk will reject any attempt to raise the other. To raise the eTRIGGER_SHAPE flag first
ensure that eSIMULATION_SHAPE flag is already lowered.
\note Trigger shapes will no longer send notification events for interactions with other trigger shapes.
\note Shapes marked as triggers are allowed to participate in scene queries, provided the eSCENE_QUERY_SHAPE flag is set.
\note This flag has no effect if simulation is disabled for the corresponding actor (see #PxActorFlag::eDISABLE_SIMULATION).
@see PxSimulationEventCallback.onTrigger() PxScene.setSimulationEventCallback() PxShape.setFlag(), PxShape.setFlags()
*/
eTRIGGER_SHAPE = (1<<2),
/**
\brief Enable debug renderer for this shape
@see PxScene.getRenderBuffer() PxRenderBuffer PxVisualizationParameter
*/
eVISUALIZATION = (1<<3)
};
};
/**
\brief collection of set bits defined in PxShapeFlag.
@see PxShapeFlag
*/
typedef PxFlags<PxShapeFlag::Enum,PxU8> PxShapeFlags;
PX_FLAGS_OPERATORS(PxShapeFlag::Enum,PxU8)
/**
\brief Abstract class for collision shapes.
Shapes are shared, reference counted objects.
An instance can be created by calling the createShape() method of the PxRigidActor class, or
the createShape() method of the PxPhysics class.
<h3>Visualizations</h3>
\li PxVisualizationParameter::eCOLLISION_AABBS
\li PxVisualizationParameter::eCOLLISION_SHAPES
\li PxVisualizationParameter::eCOLLISION_AXES
@see PxPhysics.createShape() PxRigidActor.createShape() PxBoxGeometry PxSphereGeometry PxCapsuleGeometry PxPlaneGeometry PxConvexMeshGeometry
PxTriangleMeshGeometry PxHeightFieldGeometry
*/
class PxShape : public PxRefCounted
{
public:
/**
\brief Decrements the reference count of a shape and releases it if the new reference count is zero.
Note that in releases prior to PhysX 3.3 this method did not have reference counting semantics and was used to destroy a shape
created with PxActor::createShape(). In PhysX 3.3 and above, this usage is deprecated, instead, use PxRigidActor::detachShape() to detach
a shape from an actor. If the shape to be detached was created with PxActor::createShape(), the actor holds the only counted reference,
and so when the shape is detached it will also be destroyed.
@see PxRigidActor::createShape() PxPhysics::createShape() PxRigidActor::attachShape() PxRigidActor::detachShape()
*/
virtual void release() = 0;
/**
\brief Adjust the geometry of the shape.
\note The type of the passed in geometry must match the geometry type of the shape.
\note It is not allowed to change the geometry type of a shape.
\note This function does not guarantee correct/continuous behavior when objects are resting on top of old or new geometry.
\param[in] geometry New geometry of the shape.
@see PxGeometry PxGeometryType getGeometryType()
*/
virtual void setGeometry(const PxGeometry& geometry) = 0;
/**
\brief Retrieve a reference to the shape's geometry.
\warning The returned reference has the same lifetime as the PxShape it comes from.
\return Reference to internal PxGeometry object.
@see PxGeometry PxGeometryType getGeometryType() setGeometry()
*/
virtual const PxGeometry& getGeometry() const = 0;
/**
\brief Retrieves the actor which this shape is associated with.
\return The actor this shape is associated with, if it is an exclusive shape, else NULL
@see PxRigidStatic, PxRigidDynamic, PxArticulationLink
*/
virtual PxRigidActor* getActor() const = 0;
/************************************************************************************************/
/** @name Pose Manipulation
*/
//@{
/**
\brief Sets the pose of the shape in actor space, i.e. relative to the actors to which they are attached.
This transformation is identity by default.
The local pose is an attribute of the shape, and so will apply to all actors to which the shape is attached.
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
<i>Note:</i> Does not automatically update the inertia properties of the owning actor (if applicable); use the
PhysX extensions method #PxRigidBodyExt::updateMassAndInertia() to do this.
<b>Default:</b> the identity transform
\param[in] pose The new transform from the actor frame to the shape frame. <b>Range:</b> rigid body transform
@see getLocalPose()
*/
virtual void setLocalPose(const PxTransform& pose) = 0;
/**
\brief Retrieves the pose of the shape in actor space, i.e. relative to the actor they are owned by.
This transformation is identity by default.
\return Pose of shape relative to the actor's frame.
@see setLocalPose()
*/
virtual PxTransform getLocalPose() const = 0;
//@}
/************************************************************************************************/
/** @name Collision Filtering
*/
//@{
/**
\brief Sets the user definable collision filter data.
<b>Sleeping:</b> Does wake up the actor if the filter data change causes a formerly suppressed
collision pair to be enabled.
<b>Default:</b> (0,0,0,0)
@see getSimulationFilterData()
*/
virtual void setSimulationFilterData(const PxFilterData& data) = 0;
/**
\brief Retrieves the shape's collision filter data.
@see setSimulationFilterData()
*/
virtual PxFilterData getSimulationFilterData() const = 0;
/**
\brief Sets the user definable query filter data.
<b>Default:</b> (0,0,0,0)
@see getQueryFilterData()
*/
virtual void setQueryFilterData(const PxFilterData& data) = 0;
/**
\brief Retrieves the shape's Query filter data.
@see setQueryFilterData()
*/
virtual PxFilterData getQueryFilterData() const = 0;
//@}
/************************************************************************************************/
/**
\brief Assigns material(s) to the shape. Will remove existing materials from the shape.
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
\param[in] materials List of material pointers to assign to the shape. See #PxMaterial
\param[in] materialCount The number of materials provided.
@see PxPhysics.createMaterial() getMaterials()
*/
virtual void setMaterials(PxMaterial*const* materials, PxU16 materialCount) = 0;
/**
\brief Assigns FEM soft body material(s) to the shape. Will remove existing materials from the shape.
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
\param[in] materials List of material pointers to assign to the shape. See #PxFEMSoftBodyMaterial
\param[in] materialCount The number of materials provided.
@see PxPhysics.createFEMSoftBodyMaterial() getSoftBodyMaterials()
*/
virtual void setSoftBodyMaterials(PxFEMSoftBodyMaterial*const* materials, PxU16 materialCount) = 0;
/**
\brief Assigns FEM cloth material(s) to the shape. Will remove existing materials from the shape.
\warning Feature under development, only for internal usage.
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
\param[in] materials List of material pointers to assign to the shape. See #PxFEMClothMaterial
\param[in] materialCount The number of materials provided.
@see PxPhysics.createFEMClothMaterial() getClothMaterials()
*/
virtual void setClothMaterials(PxFEMClothMaterial*const* materials, PxU16 materialCount) = 0;
/**
\brief Returns the number of materials assigned to the shape.
You can use #getMaterials() to retrieve the material pointers.
\return Number of materials associated with this shape.
@see PxMaterial getMaterials()
*/
virtual PxU16 getNbMaterials() const = 0;
/**
\brief Retrieve all the material pointers associated with the shape.
You can retrieve the number of material pointers by calling #getNbMaterials()
Note: The returned data may contain invalid pointers if you release materials using #PxMaterial::release().
\param[out] userBuffer The buffer to store the material pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first material pointer to be retrieved
\return Number of material pointers written to the buffer.
@see PxMaterial getNbMaterials() PxMaterial::release()
*/
virtual PxU32 getMaterials(PxMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex=0) const = 0;
/**
\brief Retrieve all the FEM soft body material pointers associated with the shape.
You can retrieve the number of material pointers by calling #getNbMaterials()
Note: The returned data may contain invalid pointers if you release materials using #PxMaterial::release().
\param[out] userBuffer The buffer to store the material pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first material pointer to be retrieved
\return Number of material pointers written to the buffer.
@see PxFEMSoftBodyMaterial getNbMaterials() PxMaterial::release()
*/
virtual PxU32 getSoftBodyMaterials(PxFEMSoftBodyMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Retrieve all the FEM cloth material pointers associated with the shape.
\warning Feature under development, only for internal usage.
You can retrieve the number of material pointers by calling #getNbMaterials()
Note: The returned data may contain invalid pointers if you release materials using #PxMaterial::release().
\param[out] userBuffer The buffer to store the material pointers.
\param[in] bufferSize Size of provided user buffer.
\param[in] startIndex Index of first material pointer to be retrieved
\return Number of material pointers written to the buffer.
@see PxFEMClothMaterial getNbMaterials() PxMaterial::release()
*/
virtual PxU32 getClothMaterials(PxFEMClothMaterial** userBuffer, PxU32 bufferSize, PxU32 startIndex = 0) const = 0;
/**
\brief Retrieve material from given triangle index.
The input index is the internal triangle index as used inside the SDK. This is the index
returned to users by various SDK functions such as raycasts.
This function is only useful for triangle meshes or heightfields, which have per-triangle
materials. For other shapes or SDF triangle meshes, the function returns the single material
associated with the shape, regardless of the index.
\param[in] faceIndex The internal triangle index whose material you want to retrieve.
\return Material from input triangle
\note If faceIndex value of 0xFFFFffff is passed as an input for mesh and heightfield shapes, this function will issue a warning and return NULL.
\note Scene queries set the value of PxQueryHit::faceIndex to 0xFFFFffff whenever it is undefined or does not apply.
@see PxMaterial getNbMaterials() PxMaterial::release()
*/
virtual PxBaseMaterial* getMaterialFromInternalFaceIndex(PxU32 faceIndex) const = 0;
/**
\brief Sets the contact offset.
Shapes whose distance is less than the sum of their contactOffset values will generate contacts. The contact offset must be positive and
greater than the rest offset. Having a contactOffset greater than than the restOffset allows the collision detection system to
predictively enforce the contact constraint even when the objects are slightly separated. This prevents jitter that would occur
if the constraint were enforced only when shapes were within the rest distance.
<b>Default:</b> 0.02f * PxTolerancesScale::length
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
\param[in] contactOffset <b>Range:</b> [maximum(0,restOffset), PX_MAX_F32)
@see getContactOffset PxTolerancesScale setRestOffset
*/
virtual void setContactOffset(PxReal contactOffset) = 0;
/**
\brief Retrieves the contact offset.
\return The contact offset of the shape.
@see setContactOffset()
*/
virtual PxReal getContactOffset() const = 0;
/**
\brief Sets the rest offset.
Two shapes will come to rest at a distance equal to the sum of their restOffset values. If the restOffset is 0, they should converge to touching
exactly. Having a restOffset greater than zero is useful to have objects slide smoothly, so that they do not get hung up on irregularities of
each others' surfaces.
<b>Default:</b> 0.0f
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
\param[in] restOffset <b>Range:</b> (-PX_MAX_F32, contactOffset)
@see getRestOffset setContactOffset
*/
virtual void setRestOffset(PxReal restOffset) = 0;
/**
\brief Retrieves the rest offset.
\return The rest offset of the shape.
@see setRestOffset()
*/
virtual PxReal getRestOffset() const = 0;
/**
\brief Sets the density used to interact with fluids.
To be physically accurate, the density of a rigid body should be computed as its mass divided by its volume. To
simplify tuning the interaction of fluid and rigid bodies, the density for fluid can differ from the real density. This
allows to create floating bodies, even if they are supposed to sink with their mass and volume.
<b>Default:</b> 800.0f
\param[in] densityForFluid <b>Range:</b> (0, PX_MAX_F32)
@see getDensityForFluid
*/
virtual void setDensityForFluid(PxReal densityForFluid) = 0;
/**
\brief Retrieves the density used to interact with fluids.
\return The density of the body when interacting with fluid.
@see setDensityForFluid()
*/
virtual PxReal getDensityForFluid() const = 0;
/**
\brief Sets torsional patch radius.
This defines the radius of the contact patch used to apply torsional friction. If the radius is 0 (and minTorsionalPatchRadius
is 0 too, see #setMinTorsionalPatchRadius), no torsional friction will be applied. If the radius is > 0, some torsional friction
will be applied. This is proportional to the penetration depth so, if the shapes are separated or penetration is zero, no
torsional friction will be applied. It is used to approximate rotational friction introduced by the compression of contacting surfaces.
\note Will only be active, if the friction patch has a single anchor point only. This is for example the case, if a contact patch
has a single contact point.
\note Only supported in combination with solver type PxSolverType::eTGS.
<b>Default:</b> 0.0
\param[in] radius <b>Range:</b> [0, PX_MAX_F32)
*/
virtual void setTorsionalPatchRadius(PxReal radius) = 0;
/**
\brief Gets torsional patch radius.
See #setTorsionalPatchRadius for more info.
\return The torsional patch radius of the shape.
*/
virtual PxReal getTorsionalPatchRadius() const = 0;
/**
\brief Sets minimum torsional patch radius.
This defines the minimum radius of the contact patch used to apply torsional friction. If the radius is 0, the amount of torsional friction
that will be applied will be entirely dependent on the value of torsionalPatchRadius.
If the radius is > 0, some torsional friction will be applied regardless of the value of torsionalPatchRadius or the amount of penetration.
\note Will only be active in certain cases, see #setTorsionalPatchRadius for details.
<b>Default:</b> 0.0
\param[in] radius <b>Range:</b> [0, PX_MAX_F32)
*/
virtual void setMinTorsionalPatchRadius(PxReal radius) = 0;
/**
\brief Gets minimum torsional patch radius.
See #setMinTorsionalPatchRadius for more info.
\return The minimum torsional patch radius of the shape.
*/
virtual PxReal getMinTorsionalPatchRadius() const = 0;
/**
\brief Gets internal shape id
The internal shape id can be used to reference a specific shape when processing data on the gpu.
\return The shape id
@see PxScene evaluateSDFDistances()
*/
virtual PxU32 getInternalShapeIndex() const = 0;
/************************************************************************************************/
/**
\brief Sets shape flags
<b>Sleeping:</b> Does <b>NOT</b> wake the associated actor up automatically.
\param[in] flag The shape flag to enable/disable. See #PxShapeFlag.
\param[in] value True to set the flag. False to clear the flag specified in flag.
<b>Default:</b> PxShapeFlag::eVISUALIZATION | PxShapeFlag::eSIMULATION_SHAPE | PxShapeFlag::eSCENE_QUERY_SHAPE
@see PxShapeFlag getFlags()
*/
virtual void setFlag(PxShapeFlag::Enum flag, bool value) = 0;
/**
\brief Sets shape flags
@see PxShapeFlag getFlags()
*/
virtual void setFlags(PxShapeFlags inFlags) = 0;
/**
\brief Retrieves shape flags.
\return The values of the shape flags.
@see PxShapeFlag setFlag()
*/
virtual PxShapeFlags getFlags() const = 0;
/**
\brief Returns true if the shape is exclusive to an actor.
@see PxPhysics::createShape()
*/
virtual bool isExclusive() const = 0;
/**
\brief Sets a name string for the object that can be retrieved with #getName().
This is for debugging and is not used by the SDK.
The string is not copied by the SDK, only the pointer is stored.
<b>Default:</b> NULL
\param[in] name The name string to set the objects name to.
@see getName()
*/
virtual void setName(const char* name) = 0;
/**
\brief retrieves the name string set with setName().
\return The name associated with the shape.
@see setName()
*/
virtual const char* getName() const = 0;
virtual const char* getConcreteTypeName() const { return "PxShape"; }
/************************************************************************************************/
void* userData; //!< user can assign this to whatever, usually to create a 1:1 relationship with a user object.
protected:
PX_INLINE PxShape(PxBaseFlags baseFlags) : PxRefCounted(baseFlags) {}
PX_INLINE PxShape(PxType concreteType, PxBaseFlags baseFlags) : PxRefCounted(concreteType, baseFlags), userData(NULL) {}
virtual ~PxShape() {}
virtual bool isKindOf(const char* name) const { PX_IS_KIND_OF(name, "PxShape", PxRefCounted); }
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 21,630 | C | 34.229642 | 146 | 0.741008 |
NVIDIA-Omniverse/PhysX/physx/include/PxQueryReport.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_QUERY_REPORT_H
#define PX_QUERY_REPORT_H
/** \addtogroup scenequery
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxFlags.h"
#include "foundation/PxAssert.h"
#include "geometry/PxGeometryHit.h"
#include "geometry/PxGeometryQueryContext.h"
#include "PxPhysXConfig.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxShape;
class PxRigidActor;
/**
\brief Combines a shape pointer and the actor the shape belongs to into one memory location.
Serves as a base class for PxQueryHit.
@see PxQueryHit
*/
struct PxActorShape
{
PX_INLINE PxActorShape() : actor(NULL), shape(NULL) {}
PX_INLINE PxActorShape(PxRigidActor* a, PxShape* s) : actor(a), shape(s) {}
PxRigidActor* actor;
PxShape* shape;
};
// Extends geom hits with Px object pointers
struct PxRaycastHit : PxGeomRaycastHit, PxActorShape {};
struct PxOverlapHit : PxGeomOverlapHit, PxActorShape {};
struct PxSweepHit : PxGeomSweepHit, PxActorShape {};
/**
\brief Describes query behavior after returning a partial query result via a callback.
If callback returns true, traversal will continue and callback can be issued again.
If callback returns false, traversal will stop, callback will not be issued again.
@see PxHitCallback
*/
typedef bool PxAgain;
/**
\brief This callback class facilitates reporting scene query hits (intersections) to the user.
User overrides the virtual processTouches function to receive hits in (possibly multiple) fixed size blocks.
\note PxHitBuffer derives from this class and is used to receive touching hits in a fixed size buffer.
\note Since the compiler doesn't look in template dependent base classes when looking for non-dependent names
\note with some compilers it will be necessary to use "this->hasBlock" notation to access a parent variable
\note in a child callback class.
\note Pre-made typedef shorthands, such as ::PxRaycastCallback can be used for raycast, overlap and sweep queries.
@see PxHitBuffer PxRaycastHit PxSweepHit PxOverlapHit PxRaycastCallback PxOverlapCallback PxSweepCallback
*/
template<typename HitType>
struct PxHitCallback : PxQueryThreadContext
{
HitType block; //!< Holds the closest blocking hit result for the query. Invalid if hasBlock is false.
bool hasBlock; //!< Set to true if there was a blocking hit during query.
HitType* touches; //!< User specified buffer for touching hits.
/**
\brief Size of the user specified touching hits buffer.
\note If set to 0 all hits will default to PxQueryHitType::eBLOCK, otherwise to PxQueryHitType::eTOUCH
\note Hit type returned from pre-filter overrides this default */
PxU32 maxNbTouches;
/**
\brief Number of touching hits returned by the query. Used with PxHitBuffer.
\note If true (PxAgain) is returned from the callback, nbTouches will be reset to 0. */
PxU32 nbTouches;
/**
\brief Initializes the class with user provided buffer.
\param[in] aTouches Optional buffer for recording PxQueryHitType::eTOUCH type hits.
\param[in] aMaxNbTouches Size of touch buffer.
\note if aTouches is NULL and aMaxNbTouches is 0, only the closest blocking hit will be recorded by the query.
\note If PxQueryFlag::eANY_HIT flag is used as a query parameter, hasBlock will be set to true and blockingHit will be used to receive the result.
\note Both eTOUCH and eBLOCK hits will be registered as hasBlock=true and stored in PxHitCallback.block when eANY_HIT flag is used.
@see PxHitCallback.hasBlock PxHitCallback.block */
PxHitCallback(HitType* aTouches, PxU32 aMaxNbTouches)
: hasBlock(false), touches(aTouches), maxNbTouches(aMaxNbTouches), nbTouches(0)
{}
/**
\brief virtual callback function used to communicate query results to the user.
This callback will always be invoked with #touches as a buffer if #touches was specified as non-NULL.
All reported touch hits are guaranteed to be closer than the closest blocking hit.
\param[in] buffer Callback will report touch hits to the user in this buffer. This pointer will be the same as #touches.
\param[in] nbHits Number of touch hits reported in buffer. This number will not exceed #maxNbTouches.
\note There is a significant performance penalty in case multiple touch callbacks are issued (up to 2x)
\note to avoid the penalty use a bigger buffer so that all touching hits can be reported in a single buffer.
\note If true (again) is returned from the callback, nbTouches will be reset to 0,
\note If false is returned, nbTouched will remain unchanged.
\note By the time processTouches is first called, the globally closest blocking hit is already determined,
\note values of hasBlock and block are final and all touch hits are guaranteed to be closer than the blocking hit.
\note touches and maxNbTouches can be modified inside of processTouches callback.
\return true to continue receiving callbacks in case there are more hits or false to stop.
@see PxAgain PxRaycastHit PxSweepHit PxOverlapHit */
virtual PxAgain processTouches(const HitType* buffer, PxU32 nbHits) = 0;
virtual void finalizeQuery() {} //!< Query finalization callback, called after the last processTouches callback.
virtual ~PxHitCallback() {}
/** \brief Returns true if any blocking or touching hits were encountered during a query. */
PX_FORCE_INLINE bool hasAnyHits() { return (hasBlock || (nbTouches > 0)); }
};
/**
\brief Returns scene query hits (intersections) to the user in a preallocated buffer.
Will clip touch hits to maximum buffer capacity. When clipped, an arbitrary subset of touching hits will be discarded.
Overflow does not trigger warnings or errors. block and hasBlock will be valid in finalizeQuery callback and after query completion.
Touching hits are guaranteed to have closer or same distance ( <= condition) as the globally nearest blocking hit at the time any processTouches()
callback is issued.
\note Pre-made typedef shorthands, such as ::PxRaycastBuffer can be used for raycast, overlap and sweep queries.
@see PxHitCallback
@see PxRaycastBuffer PxOverlapBuffer PxSweepBuffer PxRaycastBufferN PxOverlapBufferN PxSweepBufferN
*/
template<typename HitType>
struct PxHitBuffer : public PxHitCallback<HitType>
{
/**
\brief Initializes the buffer with user memory.
The buffer is initialized with 0 touch hits by default => query will only report a single closest blocking hit.
Use PxQueryFlag::eANY_HIT to tell the query to abort and return any first hit encoutered as blocking.
\param[in] aTouches Optional buffer for recording PxQueryHitType::eTOUCH type hits.
\param[in] aMaxNbTouches Size of touch buffer.
@see PxHitCallback */
PxHitBuffer(HitType* aTouches = NULL, PxU32 aMaxNbTouches = 0) : PxHitCallback<HitType>(aTouches, aMaxNbTouches) {}
/** \brief Computes the number of any hits in this result, blocking or touching. */
PX_INLINE PxU32 getNbAnyHits() const { return getNbTouches() + PxU32(this->hasBlock); }
/** \brief Convenience iterator used to access any hits in this result, blocking or touching. */
PX_INLINE const HitType& getAnyHit(const PxU32 index) const { PX_ASSERT(index < getNbTouches() + PxU32(this->hasBlock));
return index < getNbTouches() ? getTouches()[index] : this->block; }
PX_INLINE PxU32 getNbTouches() const { return this->nbTouches; }
PX_INLINE const HitType* getTouches() const { return this->touches; }
PX_INLINE const HitType& getTouch(const PxU32 index) const { PX_ASSERT(index < getNbTouches()); return getTouches()[index]; }
PX_INLINE PxU32 getMaxNbTouches() const { return this->maxNbTouches; }
virtual ~PxHitBuffer() {}
protected:
// stops after the first callback
virtual PxAgain processTouches(const HitType* buffer, PxU32 nbHits) { PX_UNUSED(buffer); PX_UNUSED(nbHits); return false; }
};
/** \brief Raycast query callback. */
typedef PxHitCallback<PxRaycastHit> PxRaycastCallback;
/** \brief Overlap query callback. */
typedef PxHitCallback<PxOverlapHit> PxOverlapCallback;
/** \brief Sweep query callback. */
typedef PxHitCallback<PxSweepHit> PxSweepCallback;
/** \brief Raycast query buffer. */
typedef PxHitBuffer<PxRaycastHit> PxRaycastBuffer;
/** \brief Overlap query buffer. */
typedef PxHitBuffer<PxOverlapHit> PxOverlapBuffer;
/** \brief Sweep query buffer. */
typedef PxHitBuffer<PxSweepHit> PxSweepBuffer;
/** \brief Returns touching raycast hits to the user in a fixed size array embedded in the buffer class. **/
template <int N>
struct PxRaycastBufferN : public PxHitBuffer<PxRaycastHit>
{
PxRaycastHit hits[N];
PxRaycastBufferN() : PxHitBuffer<PxRaycastHit>(hits, N) {}
};
/** \brief Returns touching overlap hits to the user in a fixed size array embedded in the buffer class. **/
template <int N>
struct PxOverlapBufferN : public PxHitBuffer<PxOverlapHit>
{
PxOverlapHit hits[N];
PxOverlapBufferN() : PxHitBuffer<PxOverlapHit>(hits, N) {}
};
/** \brief Returns touching sweep hits to the user in a fixed size array embedded in the buffer class. **/
template <int N>
struct PxSweepBufferN : public PxHitBuffer<PxSweepHit>
{
PxSweepHit hits[N];
PxSweepBufferN() : PxHitBuffer<PxSweepHit>(hits, N) {}
};
/**
\brief single hit cache for scene queries.
If a cache object is supplied to a scene query, the cached actor/shape pair is checked for intersection first.
\note Filters are not executed for the cached shape.
\note If intersection is found, the hit is treated as blocking.
\note Typically actor and shape from the last PxHitCallback.block query result is used as a cached actor/shape pair.
\note Using past touching hits as cache will produce incorrect behavior since the cached hit will always be treated as blocking.
\note Cache is only used if no touch buffer was provided, for single nearest blocking hit queries and queries using eANY_HIT flag.
\note if non-zero touch buffer was provided, cache will be ignored
\note It is the user's responsibility to ensure that the shape and actor are valid, so care must be taken
when deleting shapes to invalidate cached references.
The faceIndex field is an additional hint for a mesh or height field which is not currently used.
@see PxScene.raycast
*/
struct PxQueryCache
{
/**
\brief constructor sets to default
*/
PX_INLINE PxQueryCache() : shape(NULL), actor(NULL), faceIndex(0xffffffff) {}
/**
\brief constructor to set properties
*/
PX_INLINE PxQueryCache(PxShape* s, PxU32 findex) : shape(s), actor(NULL), faceIndex(findex) {}
PxShape* shape; //!< Shape to test for intersection first
PxRigidActor* actor; //!< Actor to which the shape belongs
PxU32 faceIndex; //!< Triangle index to test first - NOT CURRENTLY SUPPORTED
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 12,332 | C | 42.122377 | 147 | 0.766137 |
NVIDIA-Omniverse/PhysX/physx/include/filebuf/PxFileBuf.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 PSFILEBUFFER_PXFILEBUF_H
#define PSFILEBUFFER_PXFILEBUF_H
#include "foundation/PxSimpleTypes.h"
/** \addtogroup foundation
@{
*/
#if !PX_DOXYGEN
namespace physx
{
namespace general_PxIOStream2
{
#endif
PX_PUSH_PACK_DEFAULT
/**
\brief Callback class for data serialization.
The user needs to supply an PxFileBuf implementation to a number of methods to allow the SDK to read or write
chunks of binary data. This allows flexibility for the source/destination of the data. For example the PxFileBuf
could store data in a file, memory buffer or custom file format.
\note It is the users responsibility to ensure that the data is written to the appropriate offset.
*/
class PxFileBuf
{
public:
enum EndianMode
{
ENDIAN_NONE = 0, // do no conversion for endian mode
ENDIAN_BIG = 1, // always read/write data as natively big endian (Power PC, etc.)
ENDIAN_LITTLE = 2 // always read/write data as natively little endian (Intel, etc.) Default Behavior!
};
PxFileBuf(EndianMode mode=ENDIAN_LITTLE)
{
setEndianMode(mode);
}
virtual ~PxFileBuf(void)
{
}
/**
\brief Declares a constant to seek to the end of the stream.
*
* Does not support streams longer than 32 bits
*/
static const uint32_t STREAM_SEEK_END=0xFFFFFFFF;
enum OpenMode
{
OPEN_FILE_NOT_FOUND,
OPEN_READ_ONLY, // open file buffer stream for read only access
OPEN_WRITE_ONLY, // open file buffer stream for write only access
OPEN_READ_WRITE_NEW, // open a new file for both read/write access
OPEN_READ_WRITE_EXISTING // open an existing file for both read/write access
};
virtual OpenMode getOpenMode(void) const = 0;
bool isOpen(void) const
{
return getOpenMode()!=OPEN_FILE_NOT_FOUND;
}
enum SeekType
{
SEEKABLE_NO = 0,
SEEKABLE_READ = 0x1,
SEEKABLE_WRITE = 0x2,
SEEKABLE_READWRITE = 0x3
};
virtual SeekType isSeekable(void) const = 0;
void setEndianMode(EndianMode e)
{
mEndianMode = e;
if ( (e==ENDIAN_BIG && !isBigEndian() ) ||
(e==ENDIAN_LITTLE && isBigEndian() ) )
{
mEndianSwap = true;
}
else
{
mEndianSwap = false;
}
}
EndianMode getEndianMode(void) const
{
return mEndianMode;
}
virtual uint32_t getFileLength(void) const = 0;
/**
\brief Seeks the stream to a particular location for reading
*
* If the location passed exceeds the length of the stream, then it will seek to the end.
* Returns the location it ended up at (useful if you seek to the end) to get the file position
*/
virtual uint32_t seekRead(uint32_t loc) = 0;
/**
\brief Seeks the stream to a particular location for writing
*
* If the location passed exceeds the length of the stream, then it will seek to the end.
* Returns the location it ended up at (useful if you seek to the end) to get the file position
*/
virtual uint32_t seekWrite(uint32_t loc) = 0;
/**
\brief Reads from the stream into a buffer.
\param[out] mem The buffer to read the stream into.
\param[in] len The number of bytes to stream into the buffer
\return Returns the actual number of bytes read. If not equal to the length requested, then reached end of stream.
*/
virtual uint32_t read(void *mem,uint32_t len) = 0;
/**
\brief Reads from the stream into a buffer but does not advance the read location.
\param[out] mem The buffer to read the stream into.
\param[in] len The number of bytes to stream into the buffer
\return Returns the actual number of bytes read. If not equal to the length requested, then reached end of stream.
*/
virtual uint32_t peek(void *mem,uint32_t len) = 0;
/**
\brief Writes a buffer of memory to the stream
\param[in] mem The address of a buffer of memory to send to the stream.
\param[in] len The number of bytes to send to the stream.
\return Returns the actual number of bytes sent to the stream. If not equal to the length specific, then the stream is full or unable to write for some reason.
*/
virtual uint32_t write(const void *mem,uint32_t len) = 0;
/**
\brief Reports the current stream location read aqccess.
\return Returns the current stream read location.
*/
virtual uint32_t tellRead(void) const = 0;
/**
\brief Reports the current stream location for write access.
\return Returns the current stream write location.
*/
virtual uint32_t tellWrite(void) const = 0;
/**
\brief Causes any temporarily cached data to be flushed to the stream.
*/
virtual void flush(void) = 0;
/**
\brief Close the stream.
*/
virtual void close(void) {}
void release(void)
{
PX_DELETE_THIS;
}
static PX_INLINE bool isBigEndian()
{
int32_t i = 1;
return *(reinterpret_cast<char*>(&i))==0;
}
PX_INLINE void swap2Bytes(void* _data) const
{
char *data = static_cast<char *>(_data);
char one_byte;
one_byte = data[0]; data[0] = data[1]; data[1] = one_byte;
}
PX_INLINE void swap4Bytes(void* _data) const
{
char *data = static_cast<char *>(_data);
char one_byte;
one_byte = data[0]; data[0] = data[3]; data[3] = one_byte;
one_byte = data[1]; data[1] = data[2]; data[2] = one_byte;
}
PX_INLINE void swap8Bytes(void *_data) const
{
char *data = static_cast<char *>(_data);
char one_byte;
one_byte = data[0]; data[0] = data[7]; data[7] = one_byte;
one_byte = data[1]; data[1] = data[6]; data[6] = one_byte;
one_byte = data[2]; data[2] = data[5]; data[5] = one_byte;
one_byte = data[3]; data[3] = data[4]; data[4] = one_byte;
}
PX_INLINE void storeDword(uint32_t v)
{
if ( mEndianSwap )
swap4Bytes(&v);
write(&v,sizeof(v));
}
PX_INLINE void storeFloat(float v)
{
if ( mEndianSwap )
swap4Bytes(&v);
write(&v,sizeof(v));
}
PX_INLINE void storeDouble(double v)
{
if ( mEndianSwap )
swap8Bytes(&v);
write(&v,sizeof(v));
}
PX_INLINE void storeByte(uint8_t b)
{
write(&b,sizeof(b));
}
PX_INLINE void storeWord(uint16_t w)
{
if ( mEndianSwap )
swap2Bytes(&w);
write(&w,sizeof(w));
}
uint8_t readByte(void)
{
uint8_t v=0;
read(&v,sizeof(v));
return v;
}
uint16_t readWord(void)
{
uint16_t v=0;
read(&v,sizeof(v));
if ( mEndianSwap )
swap2Bytes(&v);
return v;
}
uint32_t readDword(void)
{
uint32_t v=0;
read(&v,sizeof(v));
if ( mEndianSwap )
swap4Bytes(&v);
return v;
}
float readFloat(void)
{
float v=0;
read(&v,sizeof(v));
if ( mEndianSwap )
swap4Bytes(&v);
return v;
}
double readDouble(void)
{
double v=0;
read(&v,sizeof(v));
if ( mEndianSwap )
swap8Bytes(&v);
return v;
}
private:
bool mEndianSwap; // whether or not the endian should be swapped on the current platform
EndianMode mEndianMode; // the current endian mode behavior for the stream
};
PX_POP_PACK
#if !PX_DOXYGEN
} // end of namespace
using namespace general_PxIOStream2;
namespace general_PxIOStream = general_PxIOStream2;
} // end of namespace
#endif
/** @} */
#endif // PSFILEBUFFER_PXFILEBUF_H
| 8,643 | C | 24.498525 | 161 | 0.693162 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxConvexMeshDesc.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_CONVEX_MESH_DESC_H
#define PX_CONVEX_MESH_DESC_H
/** \addtogroup cooking
@{
*/
#include "foundation/PxVec3.h"
#include "foundation/PxFlags.h"
#include "common/PxCoreUtilityTypes.h"
#include "geometry/PxConvexMesh.h"
#include "PxSDFDesc.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Flags which describe the format and behavior of a convex mesh.
*/
struct PxConvexFlag
{
enum Enum
{
/**
Denotes the use of 16-bit vertex indices in PxConvexMeshDesc::triangles or PxConvexMeshDesc::polygons.
(otherwise, 32-bit indices are assumed)
@see #PxConvexMeshDesc.indices
*/
e16_BIT_INDICES = (1<<0),
/**
Automatically recomputes the hull from the vertices. If this flag is not set, you must provide the entire geometry manually.
\note There are two different algorithms for hull computation, please see PxConvexMeshCookingType.
@see PxConvexMeshCookingType
*/
eCOMPUTE_CONVEX = (1<<1),
/**
\brief Checks and removes almost zero-area triangles during convex hull computation.
The rejected area size is specified in PxCookingParams::areaTestEpsilon
\note This flag is only used in combination with eCOMPUTE_CONVEX.
@see PxCookingParams PxCookingParams::areaTestEpsilon
*/
eCHECK_ZERO_AREA_TRIANGLES = (1<<2),
/**
\brief Quantizes the input vertices using the k-means clustering
\note The input vertices are quantized to PxConvexMeshDesc::quantizedCount
see http://en.wikipedia.org/wiki/K-means_clustering
*/
eQUANTIZE_INPUT = (1 << 3),
/**
\brief Disables the convex mesh validation to speed-up hull creation. Please use separate validation
function in checked/debug builds. Creating a convex mesh with invalid input data without prior validation
may result in undefined behavior.
@see PxCooking::validateConvexMesh
*/
eDISABLE_MESH_VALIDATION = (1 << 4),
/**
\brief Enables plane shifting vertex limit algorithm.
Plane shifting is an alternative algorithm for the case when the computed hull has more vertices
than the specified vertex limit.
The default algorithm computes the full hull, and an OBB around the input vertices. This OBB is then sliced
with the hull planes until the vertex limit is reached.The default algorithm requires the vertex limit
to be set to at least 8, and typically produces results that are much better quality than are produced
by plane shifting.
When plane shifting is enabled, the hull computation stops when vertex limit is reached. The hull planes
are then shifted to contain all input vertices, and the new plane intersection points are then used to
generate the final hull with the given vertex limit.Plane shifting may produce sharp edges to vertices
very far away from the input cloud, and does not guarantee that all input vertices are inside the resulting
hull.However, it can be used with a vertex limit as low as 4.
*/
ePLANE_SHIFTING = (1 << 5),
/**
\brief Inertia tensor computation is faster using SIMD code, but the precision is lower, which may result
in incorrect inertia for very thin hulls.
*/
eFAST_INERTIA_COMPUTATION = (1 << 6),
/**
\brief Convex hulls are created with respect to GPU simulation limitations. Vertex limit and polygon limit
is set to 64 and vertex limit per face is internally set to 32.
\note Can be used only with eCOMPUTE_CONVEX flag.
@deprecated since PhysX 5.2. Setting #PxCookingParams::buildGPUData to true always cooks GPU-compatible meshes.
*/
eGPU_COMPATIBLE PX_DEPRECATED = (1 << 7),
/**
\brief Convex hull input vertices are shifted to be around origin to provide better computation stability.
It is recommended to provide input vertices around the origin, otherwise use this flag to improve
numerical stability.
\note Is used only with eCOMPUTE_CONVEX flag.
*/
eSHIFT_VERTICES = (1 << 8)
};
};
/**
\brief collection of set bits defined in PxConvexFlag.
@see PxConvexFlag
*/
typedef PxFlags<PxConvexFlag::Enum,PxU16> PxConvexFlags;
PX_FLAGS_OPERATORS(PxConvexFlag::Enum,PxU16)
/**
\brief Descriptor class for #PxConvexMesh.
\note The number of vertices and the number of convex polygons in a cooked convex mesh is limited to 256.
\note The number of vertices and the number of convex polygons in a GPU compatible convex mesh is limited to 64,
and the number of faces per vertex is limited to 32.
@see PxConvexMesh PxConvexMeshGeometry PxShape PxPhysics.createConvexMesh()
*/
class PxConvexMeshDesc
{
public:
/**
\brief Vertex positions data in PxBoundedData format.
<b>Default:</b> NULL
*/
PxBoundedData points;
/**
\brief Polygons data in PxBoundedData format.
<p>Pointer to first polygon. </p>
<b>Default:</b> NULL
@see PxHullPolygon
*/
PxBoundedData polygons;
/**
\brief Polygon indices data in PxBoundedData format.
<p>Pointer to first index.</p>
<b>Default:</b> NULL
<p>This is declared as a void pointer because it is actually either an PxU16 or a PxU32 pointer.</p>
@see PxHullPolygon PxConvexFlag::e16_BIT_INDICES
*/
PxBoundedData indices;
/**
\brief Flags bits, combined from values of the enum ::PxConvexFlag
<b>Default:</b> 0
*/
PxConvexFlags flags;
/**
\brief Limits the number of vertices of the result convex mesh. Hard maximum limit is 255
and minimum limit is 4 if PxConvexFlag::ePLANE_SHIFTING is used, otherwise the minimum
limit is 8.
\note The please see PxConvexFlag::ePLANE_SHIFTING for algorithm explanation
\note The maximum limit for GPU compatible convex meshes is 64.
@see PxConvexFlag::ePLANE_SHIFTING
<b>Range:</b> [4, 255]<br>
<b>Default:</b> 255
*/
PxU16 vertexLimit;
/**
\brief Limits the number of polygons of the result convex mesh. Hard maximum limit is 255
and minimum limit is 4.
\note The maximum limit for GPU compatible convex meshes is 64.
<b>Range:</b> [4, 255]<br>
<b>Default:</b> 255
*/
PxU16 polygonLimit;
/**
\brief Maximum number of vertices after quantization. The quantization is done during the vertex cleaning phase.
The quantization is applied when PxConvexFlag::eQUANTIZE_INPUT is specified.
@see PxConvexFlag::eQUANTIZE_INPUT
<b>Range:</b> [4, 65535]<br>
<b>Default:</b> 255
*/
PxU16 quantizedCount;
/**
\brief SDF descriptor. When this descriptor is set, signed distance field is calculated for this convex mesh.
<b>Default:</b> NULL
*/
PxSDFDesc* sdfDesc;
/**
\brief constructor sets to default.
*/
PX_INLINE PxConvexMeshDesc();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief Returns true if the descriptor is valid.
\return True if the current settings are valid
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxConvexMeshDesc::PxConvexMeshDesc() //constructor sets to default
: vertexLimit(255), polygonLimit(255), quantizedCount(255), sdfDesc(NULL)
{
}
PX_INLINE void PxConvexMeshDesc::setToDefault()
{
*this = PxConvexMeshDesc();
}
PX_INLINE bool PxConvexMeshDesc::isValid() const
{
// Check geometry
if(points.count < 3 || //at least 1 trig's worth of points
(points.count > 0xffff && flags & PxConvexFlag::e16_BIT_INDICES))
return false;
if(!points.data)
return false;
if(points.stride < sizeof(PxVec3)) //should be at least one point's worth of data
return false;
if (quantizedCount < 4)
return false;
// Check topology
if(polygons.data)
{
if(polygons.count < 4) // we require 2 neighbors for each vertex - 4 polygons at least
return false;
if(!indices.data) // indices must be provided together with polygons
return false;
PxU32 limit = (flags & PxConvexFlag::e16_BIT_INDICES) ? sizeof(PxU16) : sizeof(PxU32);
if(indices.stride < limit)
return false;
limit = sizeof(PxHullPolygon);
if(polygons.stride < limit)
return false;
}
else
{
// We can compute the hull from the vertices
if(!(flags & PxConvexFlag::eCOMPUTE_CONVEX))
return false; // If the mesh is convex and we're not allowed to compute the hull,
// you have to provide it completely (geometry & topology).
}
if((flags & PxConvexFlag::ePLANE_SHIFTING) && vertexLimit < 4)
{
return false;
}
if (!(flags & PxConvexFlag::ePLANE_SHIFTING) && vertexLimit < 8)
{
return false;
}
if(vertexLimit > 255)
{
return false;
}
if (polygonLimit < 4)
{
return false;
}
if (polygonLimit > 255)
{
return false;
}
if (sdfDesc && !sdfDesc->isValid())
{
return false;
}
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 10,175 | C | 28.325648 | 126 | 0.733759 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxCooking.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_COOKING_H
#define PX_COOKING_H
/** \addtogroup cooking
@{
*/
#include "common/PxPhysXCommonConfig.h"
#include "common/PxTolerancesScale.h"
#include "cooking/Pxc.h"
#include "cooking/PxConvexMeshDesc.h"
#include "cooking/PxTriangleMeshDesc.h"
#include "cooking/PxTetrahedronMeshDesc.h"
#include "cooking/PxMidphaseDesc.h"
#include "cooking/PxBVHDesc.h"
#include "geometry/PxTriangleMesh.h"
#include "geometry/PxTetrahedronMesh.h"
#include "geometry/PxBVH.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxInsertionCallback;
class PxFoundation;
class PxAllocatorCallback;
class PxHeightFieldDesc;
/**
\brief Result from convex cooking.
*/
struct PxConvexMeshCookingResult
{
enum Enum
{
/**
\brief Convex mesh cooking succeeded.
*/
eSUCCESS,
/**
\brief Convex mesh cooking failed, algorithm couldn't find 4 initial vertices without a small triangle.
@see PxCookingParams::areaTestEpsilon PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES
*/
eZERO_AREA_TEST_FAILED,
/**
\brief Convex mesh cooking succeeded, but the algorithm has reached the 255 polygons limit.
The produced hull does not contain all input vertices. Try to simplify the input vertices
or try to use the eINFLATE_CONVEX or the eQUANTIZE_INPUT flags.
@see PxConvexFlag::eINFLATE_CONVEX PxConvexFlag::eQUANTIZE_INPUT
*/
ePOLYGONS_LIMIT_REACHED,
/**
\brief Something unrecoverable happened. Check the error stream to find out what.
*/
eFAILURE,
/**
\brief Convex mesh cooking succeeded, but the algorithm could not make the mesh GPU compatible because the
in-sphere radius is more than 100x smaller than the largest extent. Collision detection for any pair involving
this convex mesh will fall back to CPU.
*/
eNON_GPU_COMPATIBLE
};
};
/** \brief Enumeration for convex mesh cooking algorithms. */
struct PxConvexMeshCookingType
{
enum Enum
{
/**
\brief The Quickhull algorithm constructs the hull from the given input points. The resulting hull
will only contain a subset of the input points.
*/
eQUICKHULL
};
};
/**
\brief Result from triangle mesh cooking
*/
struct PxTriangleMeshCookingResult
{
enum Enum
{
/**
\brief Everything is A-OK.
*/
eSUCCESS = 0,
/**
\brief A triangle is too large for well-conditioned results. Tessellate the mesh for better behavior, see the user guide section on cooking for more details.
*/
eLARGE_TRIANGLE,
/**
\brief The mesh cleaning operation removed all triangles, resulting in an empty mesh.
*/
eEMPTY_MESH,
/**
\brief Something unrecoverable happened. Check the error stream to find out what.
*/
eFAILURE
};
};
/**
\brief Enum for the set of mesh pre-processing parameters.
*/
struct PxMeshPreprocessingFlag
{
enum Enum
{
/**
\brief When set, mesh welding is performed. See PxCookingParams::meshWeldTolerance. Mesh cleaning must be enabled.
*/
eWELD_VERTICES = 1 << 0,
/**
\brief When set, mesh cleaning is disabled. This makes cooking faster.
When mesh cleaning is disabled, mesh welding is also disabled.
It is recommended to use only meshes that passed during validateTriangleMesh.
*/
eDISABLE_CLEAN_MESH = 1 << 1,
/**
\brief When set, active edges are not computed and just enabled for all edges. This makes cooking faster but contact generation slower.
*/
eDISABLE_ACTIVE_EDGES_PRECOMPUTE = 1 << 2,
/**
\brief When set, 32-bit indices will always be created regardless of triangle count.
\note By default mesh will be created with 16-bit indices for triangle count <= 0xFFFF and 32-bit otherwise.
*/
eFORCE_32BIT_INDICES = 1 << 3,
/**
\brief When set, a list of triangles will be created for each associated vertex in the mesh.
*/
eENABLE_VERT_MAPPING = 1 << 4,
/**
\brief When set, inertia tensor is calculated for the mesh.
*/
eENABLE_INERTIA = 1 << 5
};
};
typedef PxFlags<PxMeshPreprocessingFlag::Enum,PxU32> PxMeshPreprocessingFlags;
/**
\brief Structure describing parameters affecting mesh cooking.
@see PxSetCookingParams() PxGetCookingParams()
*/
struct PxCookingParams
{
/**
\brief Zero-size area epsilon used in convex hull computation.
If the area of a triangle of the hull is below this value, the triangle will be rejected. This test
is done only if PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES is used.
@see PxConvexFlag::eCHECK_ZERO_AREA_TRIANGLES
<b>Default value:</b> 0.06f*PxTolerancesScale.length*PxTolerancesScale.length
<b>Range:</b> (0.0f, PX_MAX_F32)
*/
float areaTestEpsilon;
/**
\brief Plane tolerance used in convex hull computation.
The value is used during hull construction. When a new point is about to be added to the hull it
gets dropped when the point is closer to the hull than the planeTolerance. The planeTolerance
is increased according to the hull size.
If 0.0f is set all points are accepted when the convex hull is created. This may lead to edge cases
where the new points may be merged into an existing polygon and the polygons plane equation might
slightly change therefore. This might lead to failures during polygon merging phase in the hull computation.
It is recommended to use the default value, however if it is required that all points needs to be
accepted or huge thin convexes are created, it might be required to lower the default value.
\note The plane tolerance is used only within PxConvexMeshCookingType::eQUICKHULL algorithm.
<b>Default value:</b> 0.0007f
<b>Range:</b> <0.0f, PX_MAX_F32)
*/
float planeTolerance;
/**
\brief Convex hull creation algorithm.
<b>Default value:</b> PxConvexMeshCookingType::eQUICKHULL
@see PxConvexMeshCookingType
*/
PxConvexMeshCookingType::Enum convexMeshCookingType;
/**
\brief When true, the face remap table is not created. This saves a significant amount of memory, but the SDK will
not be able to provide the remap information for internal mesh triangles returned by collisions,
sweeps or raycasts hits.
<b>Default value:</b> false
*/
bool suppressTriangleMeshRemapTable;
/**
\brief When true, the triangle adjacency information is created. You can get the adjacency triangles
for a given triangle from getTriangle.
<b>Default value:</b> false
*/
bool buildTriangleAdjacencies;
/**
\brief When true, addigional information required for GPU-accelerated rigid body simulation is created. This can increase memory usage and cooking times for convex meshes and triangle meshes.
<b>Default value:</b> false
*/
bool buildGPUData;
/**
\brief Tolerance scale is used to check if cooked triangles are not too huge. This check will help with simulation stability.
\note The PxTolerancesScale values have to match the values used when creating a PxPhysics or PxScene instance.
@see PxTolerancesScale
*/
PxTolerancesScale scale;
/**
\brief Mesh pre-processing parameters. Used to control options like whether the mesh cooking performs vertex welding before cooking.
<b>Default value:</b> 0
*/
PxMeshPreprocessingFlags meshPreprocessParams;
/**
\brief Mesh weld tolerance. If mesh welding is enabled, this controls the distance at which vertices are welded.
If mesh welding is not enabled, this value defines the acceptance distance for mesh validation. Provided no two vertices are within this distance, the mesh is considered to be
clean. If not, a warning will be emitted. Having a clean, welded mesh is required to achieve the best possible performance.
The default vertex welding uses a snap-to-grid approach. This approach effectively truncates each vertex to integer values using meshWeldTolerance.
Once these snapped vertices are produced, all vertices that snap to a given vertex on the grid are remapped to reference a single vertex. Following this,
all triangles' indices are remapped to reference this subset of clean vertices. It should be noted that the vertices that we do not alter the
position of the vertices; the snap-to-grid is only performed to identify nearby vertices.
The mesh validation approach also uses the same snap-to-grid approach to identify nearby vertices. If more than one vertex snaps to a given grid coordinate,
we ensure that the distance between the vertices is at least meshWeldTolerance. If this is not the case, a warning is emitted.
<b>Default value:</b> 0.0
*/
PxReal meshWeldTolerance;
/**
\brief "Zero-area" epsilon used in mesh cleaning.
This is similar to areaTestEpsilon, but for the mesh cleaning operation.
If the area of a triangle is below this value, the triangle will be removed. This is only done when mesh cleaning is enabled,
i.e. when PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH is not set.
Default value is 0.0f to be consistent with previous PhysX versions, which only removed triangles whose area
was exactly zero.
@see PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH
<b>Default value:</b> 0.0f
<b>Range:</b> (0.0f, PX_MAX_F32)
*/
PxReal meshAreaMinLimit;
/**
\brief Maximum edge length.
If an edge of a triangle is above this value, a warning is sent to the error stream. This is only a check,
corresponding triangles are not removed.
This is only done when mesh cleaning is enabled, i.e. when PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH is not set.
Default value is 500.0f to be consistent with previous PhysX versions. This value is internally multiplied by
PxTolerancesScale::length before being used. Use 0.0f to disable the checks.
@see PxMeshPreprocessingFlag::eDISABLE_CLEAN_MESH
<b>Default value:</b> 500.0f
<b>Range:</b> (0.0f, PX_MAX_F32)
*/
PxReal meshEdgeLengthMaxLimit;
/**
\brief Controls the desired midphase desc structure for triangle meshes.
@see PxBVH33MidphaseDesc, PxBVH34MidphaseDesc, PxMidphaseDesc
<b>Default value:</b> PxMeshMidPhase::eBVH34
*/
PxMidphaseDesc midphaseDesc;
/**
\brief Vertex limit beyond which additional acceleration structures are computed for each convex mesh. Increase that limit to reduce memory usage.
Computing the extra structures all the time does not guarantee optimal performance. There is a per-platform break-even point below which the
extra structures actually hurt performance.
<b>Default value:</b> 32
*/
PxU32 gaussMapLimit;
/**
\brief Maximum mass ratio allowed on vertices touched by a single tet. If a any tetrahedron exceeds the mass ratio, the masses will get smoothed locally
until the maximum mass ratio is matched. Value should not be below 1. Smoothing might not fully converge for values <1.5. The smaller the maximum
allowed ratio, the better the stability during simulation.
<b>Default value:</b> FLT_MAX
*/
PxReal maxWeightRatioInTet;
PxCookingParams(const PxTolerancesScale& sc):
areaTestEpsilon (0.06f*sc.length*sc.length),
planeTolerance (0.0007f),
convexMeshCookingType (PxConvexMeshCookingType::eQUICKHULL),
suppressTriangleMeshRemapTable (false),
buildTriangleAdjacencies (false),
buildGPUData (false),
scale (sc),
meshPreprocessParams (0),
meshWeldTolerance (0.0f),
meshAreaMinLimit (0.0f),
meshEdgeLengthMaxLimit (500.0f),
gaussMapLimit (32),
maxWeightRatioInTet (FLT_MAX)
{
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
// Immediate cooking
/**
\brief Gets standalone object insertion interface.
This interface allows the creation of standalone objects that can exist without a PxPhysics or PxScene object.
@see PxCreateTriangleMesh PxCreateHeightfield PxCreateTetrahedronMesh PxCreateBVH
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxInsertionCallback* PxGetStandaloneInsertionCallback();
// ==== BVH ====
/**
\brief Cooks a bounding volume hierarchy. The results are written to the stream.
PxCookBVH() allows a BVH description to be cooked into a binary stream
suitable for loading and performing BVH detection at runtime.
\param[in] desc The BVH descriptor.
\param[in] stream User stream to output the cooked data.
\return true on success.
@see PxBVH PxRigidActorExt::getRigidActorShapeLocalBoundsList
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookBVH(const physx::PxBVHDesc& desc, physx::PxOutputStream& stream);
/**
\brief Cooks and creates a bounding volume hierarchy without going through a stream.
\note This method does the same as PxCookBVH, but the produced BVH is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback()
or PxGetStandaloneInsertionCallback().
\param[in] desc The BVH descriptor.
\param[in] insertionCallback The insertion interface.
\return PxBVH pointer on success
@see PxCookBVH() PxInsertionCallback
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxBVH* PxCreateBVH(const physx::PxBVHDesc& desc, physx::PxInsertionCallback& insertionCallback);
/**
\brief Cooks and creates a bounding volume hierarchy without going through a stream. Convenience function for standalone objects.
\note This method does the same as PxCookBVH, but the produced BVH is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\param[in] desc The BVH descriptor.
\return PxBVH pointer on success
@see PxCookBVH() PxInsertionCallback
*/
PX_FORCE_INLINE physx::PxBVH* PxCreateBVH(const physx::PxBVHDesc& desc)
{
return PxCreateBVH(desc, *PxGetStandaloneInsertionCallback());
}
// ==== Heightfield ====
/**
\brief Cooks a heightfield. The results are written to the stream.
To create a heightfield object there is an option to precompute some of calculations done while loading the heightfield data.
PxCookHeightField() allows a heightfield description to be cooked into a binary stream
suitable for loading and performing collision detection at runtime.
\param[in] desc The heightfield descriptor to read the HF from.
\param[in] stream User stream to output the cooked data.
\return true on success
@see PxPhysics.createHeightField()
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookHeightField(const physx::PxHeightFieldDesc& desc, physx::PxOutputStream& stream);
/**
\brief Cooks and creates a heightfield mesh and inserts it into PxPhysics.
\param[in] desc The heightfield descriptor to read the HF from.
\param[in] insertionCallback The insertion interface from PxPhysics.
\return PxHeightField pointer on success
@see PxCookHeightField() PxPhysics.createHeightField() PxInsertionCallback
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxHeightField* PxCreateHeightField(const physx::PxHeightFieldDesc& desc, physx::PxInsertionCallback& insertionCallback);
/**
\brief Cooks and creates a heightfield mesh and inserts it into PxPhysics. Convenience function for standalone objects.
\param[in] desc The heightfield descriptor to read the HF from.
\return PxHeightField pointer on success
@see PxCookHeightField() PxPhysics.createHeightField() PxInsertionCallback
*/
PX_FORCE_INLINE physx::PxHeightField* PxCreateHeightField(const physx::PxHeightFieldDesc& desc)
{
return PxCreateHeightField(desc, *PxGetStandaloneInsertionCallback());
}
// ==== Convex meshes ====
/**
\brief Cooks a convex mesh. The results are written to the stream.
To create a triangle mesh object it is necessary to first 'cook' the mesh data into
a form which allows the SDK to perform efficient collision detection.
PxCookConvexMesh() allows a mesh description to be cooked into a binary stream
suitable for loading and performing collision detection at runtime.
\note The number of vertices and the number of convex polygons in a cooked convex mesh is limited to 255.
\note If those limits are exceeded in either the user-provided data or the final cooked mesh, an error is reported.
\param[in] params The cooking parameters
\param[in] desc The convex mesh descriptor to read the mesh from.
\param[in] stream User stream to output the cooked data.
\param[out] condition Result from convex mesh cooking.
\return true on success.
@see PxCookTriangleMesh() PxConvexMeshCookingResult::Enum
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc, physx::PxOutputStream& stream, physx::PxConvexMeshCookingResult::Enum* condition=NULL);
/**
\brief Cooks and creates a convex mesh without going through a stream.
\note This method does the same as PxCookConvexMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback()
or PxGetStandaloneInsertionCallback().
\param[in] params The cooking parameters
\param[in] desc The convex mesh descriptor to read the mesh from.
\param[in] insertionCallback The insertion interface from PxPhysics.
\param[out] condition Result from convex mesh cooking.
\return PxConvexMesh pointer on success
@see PxCookConvexMesh() PxInsertionCallback
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxConvexMesh* PxCreateConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc, physx::PxInsertionCallback& insertionCallback, physx::PxConvexMeshCookingResult::Enum* condition=NULL);
/**
\brief Cooks and creates a convex mesh without going through a stream. Convenience function for standalone objects.
\note This method does the same as cookConvexMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\param[in] params The cooking parameters
\param[in] desc The convex mesh descriptor to read the mesh from.
\return PxConvexMesh pointer on success
@see PxCookConvexMesh() PxInsertionCallback
*/
PX_FORCE_INLINE physx::PxConvexMesh* PxCreateConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc)
{
return PxCreateConvexMesh(params, desc, *PxGetStandaloneInsertionCallback());
}
/**
\brief Verifies if the convex mesh is valid. Prints an error message for each inconsistency found.
The convex mesh descriptor must contain an already created convex mesh - the vertices, indices and polygons must be provided.
\note This function should be used if PxConvexFlag::eDISABLE_MESH_VALIDATION is planned to be used in release builds.
\param[in] params The cooking parameters
\param[in] desc The convex mesh descriptor to read the mesh from.
\return true if all the validity conditions hold, false otherwise.
@see PxCookConvexMesh()
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxValidateConvexMesh(const physx::PxCookingParams& params, const physx::PxConvexMeshDesc& desc);
/**
\brief Compute hull polygons from given vertices and triangles. Polygons are needed for PxConvexMeshDesc rather than triangles.
Please note that the resulting polygons may have different number of vertices. Some vertices may be removed.
The output vertices, indices and polygons must be used to construct a hull.
The provided PxAllocatorCallback does allocate the out arrays. It is the user responsibility to deallocated those arrays.
\param[in] params The cooking parameters
\param[in] mesh Simple triangle mesh containing vertices and triangles used to compute polygons.
\param[in] inCallback Memory allocator for out array allocations.
\param[out] nbVerts Number of vertices used by polygons.
\param[out] vertices Vertices array used by polygons.
\param[out] nbIndices Number of indices used by polygons.
\param[out] indices Indices array used by polygons.
\param[out] nbPolygons Number of created polygons.
\param[out] hullPolygons Polygons array.
\return true on success
@see PxCookConvexMesh() PxConvexFlags PxConvexMeshDesc PxSimpleTriangleMesh
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxComputeHullPolygons(const physx::PxCookingParams& params, const physx::PxSimpleTriangleMesh& mesh, physx::PxAllocatorCallback& inCallback, physx::PxU32& nbVerts, physx::PxVec3*& vertices,
physx::PxU32& nbIndices, physx::PxU32*& indices, physx::PxU32& nbPolygons, physx::PxHullPolygon*& hullPolygons);
// ==== Triangle meshes ====
/**
\brief Verifies if the triangle mesh is valid. Prints an error message for each inconsistency found.
The following conditions are true for a valid triangle mesh:
1. There are no duplicate vertices (within specified vertexWeldTolerance. See PxCookingParams::meshWeldTolerance)
2. There are no large triangles (within specified PxTolerancesScale.)
\param[in] params The cooking parameters
\param[in] desc The triangle mesh descriptor to read the mesh from.
\return true if all the validity conditions hold, false otherwise.
@see PxCookTriangleMesh()
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxValidateTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc);
/**
\brief Cooks a triangle mesh. The results are written to the stream.
To create a triangle mesh object it is necessary to first 'cook' the mesh data into
a form which allows the SDK to perform efficient collision detection.
PxCookTriangleMesh() allows a mesh description to be cooked into a binary stream
suitable for loading and performing collision detection at runtime.
\param[in] params The cooking parameters
\param[in] desc The triangle mesh descriptor to read the mesh from.
\param[in] stream User stream to output the cooked data.
\param[out] condition Result from triangle mesh cooking.
\return true on success
@see PxCookConvexMesh() PxPhysics.createTriangleMesh() PxTriangleMeshCookingResult::Enum
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc, physx::PxOutputStream& stream, physx::PxTriangleMeshCookingResult::Enum* condition=NULL);
/**
\brief Cooks and creates a triangle mesh without going through a stream.
\note This method does the same as PxCookTriangleMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback()
or PxGetStandaloneInsertionCallback().
\param[in] params The cooking parameters
\param[in] desc The triangle mesh descriptor to read the mesh from.
\param[in] insertionCallback The insertion interface from PxPhysics.
\param[out] condition Result from triangle mesh cooking.
\return PxTriangleMesh pointer on success.
@see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxTriangleMesh* PxCreateTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc, physx::PxInsertionCallback& insertionCallback, physx::PxTriangleMeshCookingResult::Enum* condition=NULL);
/**
\brief Cooks and creates a triangle mesh without going through a stream. Convenience function for standalone objects.
\note This method does the same as cookTriangleMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\return PxTriangleMesh pointer on success.
\param[in] params The cooking parameters
\param[in] desc The triangle mesh descriptor to read the mesh from.
@see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback
*/
PX_FORCE_INLINE physx::PxTriangleMesh* PxCreateTriangleMesh(const physx::PxCookingParams& params, const physx::PxTriangleMeshDesc& desc)
{
return PxCreateTriangleMesh(params, desc, *PxGetStandaloneInsertionCallback());
}
// ==== Tetrahedron & soft body meshes ====
/**
\brief Cooks a tetrahedron mesh. The results are written to the stream.
To create a tetrahedron mesh object it is necessary to first 'cook' the mesh data into
a form which allows the SDK to perform efficient collision detection.
PxCookTetrahedronMesh() allows a mesh description to be cooked into a binary stream
suitable for loading and performing collision detection at runtime.
\param[in] params The cooking parameters
\param[in] meshDesc The tetrahedron mesh descriptor to read the mesh from.
\param[in] stream User stream to output the cooked data.
\return true on success
@see PxCookConvexMesh() PxPhysics.createTetrahedronMesh()
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookTetrahedronMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& meshDesc, physx::PxOutputStream& stream);
/**
\brief Cooks and creates a tetrahedron mesh without going through a stream.
\note This method does the same as PxCookTetrahedronMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback()
or PxGetStandaloneInsertionCallback().
\param[in] params The cooking parameters
\param[in] meshDesc The tetrahedron mesh descriptor to read the mesh from.
\param[in] insertionCallback The insertion interface from PxPhysics.
\return PxTetrahedronMesh pointer on success.
@see PxCookTetrahedronMesh() PxInsertionCallback
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxTetrahedronMesh* PxCreateTetrahedronMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& meshDesc, physx::PxInsertionCallback& insertionCallback);
/**
\brief Cooks and creates a tetrahedron mesh without going through a stream. Convenience function for standalone objects.
\note This method does the same as PxCookTetrahedronMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\param[in] params The cooking parameters
\param[in] meshDesc The tetrahedron mesh descriptor to read the mesh from.
\return PxTetrahedronMesh pointer on success.
@see PxCookTetrahedronMesh() PxInsertionCallback
*/
PX_FORCE_INLINE physx::PxTetrahedronMesh* PxCreateTetrahedronMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& meshDesc)
{
return PxCreateTetrahedronMesh(params, meshDesc, *PxGetStandaloneInsertionCallback());
}
/**
\brief Cooks a softbody mesh. The results are written to the stream.
To create a softbody mesh object it is necessary to first 'cook' the mesh data into
a form which allows the SDK to perform efficient collision detection and to store data
used during the FEM calculations.
PxCookSoftBodyMesh() allows a mesh description to be cooked into a binary stream
suitable for loading and performing collision detection at runtime.
\param[in] params The cooking parameters
\param[in] simulationMeshDesc The tetrahedron mesh descriptor to read the simulation mesh from.
\param[in] collisionMeshDesc The tetrahedron mesh descriptor to read the collision mesh from.
\param[in] softbodyDataDesc The softbody data descriptor to read mapping information from.
\param[in] stream User stream to output the cooked data.
\return true on success
@see PxCookConvexMesh() PxPhysics.createTriangleMesh() PxTriangleMeshCookingResult::Enum
*/
PX_C_EXPORT PX_PHYSX_COOKING_API bool PxCookSoftBodyMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc,
const physx::PxSoftBodySimulationDataDesc& softbodyDataDesc, physx::PxOutputStream& stream);
/**
\brief Cooks and creates a softbody mesh without going through a stream.
\note This method does the same as PxCookSoftBodyMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\note PxInsertionCallback can be obtained through PxPhysics::getPhysicsInsertionCallback()
or PxGetStandaloneInsertionCallback().
\param[in] params The cooking parameters
\param[in] simulationMeshDesc The tetrahedron mesh descriptor to read the simulation mesh from.
\param[in] collisionMeshDesc The tetrahedron mesh descriptor to read the collision mesh from.
\param[in] softbodyDataDesc The softbody data descriptor to read mapping information from.
\param[in] insertionCallback The insertion interface from PxPhysics.
\return PxSoftBodyMesh pointer on success.
@see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxSoftBodyMesh* PxCreateSoftBodyMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc,
const physx::PxSoftBodySimulationDataDesc& softbodyDataDesc, physx::PxInsertionCallback& insertionCallback);
/**
\brief Cooks and creates a softbody mesh without going through a stream. Convenience function for standalone objects.
\note This method does the same as PxCookSoftBodyMesh, but the produced mesh is not stored
into a stream but is either directly inserted in PxPhysics, or created as a standalone
object. Use this method if you are unable to cook offline.
\param[in] params The cooking parameters
\param[in] simulationMeshDesc The tetrahedron mesh descriptor to read the simulation mesh from.
\param[in] collisionMeshDesc The tetrahedron mesh descriptor to read the collision mesh from.
\param[in] softbodyDataDesc The softbody data descriptor to read mapping information from.
\return PxSoftBodyMesh pointer on success.
@see PxCookTriangleMesh() PxPhysics.createTriangleMesh() PxInsertionCallback
*/
PX_FORCE_INLINE physx::PxSoftBodyMesh* PxCreateSoftBodyMesh(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& simulationMeshDesc, const physx::PxTetrahedronMeshDesc& collisionMeshDesc,
const physx::PxSoftBodySimulationDataDesc& softbodyDataDesc)
{
return PxCreateSoftBodyMesh(params, simulationMeshDesc, collisionMeshDesc, softbodyDataDesc, *PxGetStandaloneInsertionCallback());
}
/**
\brief Computes the mapping between collision and simulation mesh
The softbody deformation is computed on the simulation mesh. To deform the collision mesh accordingly
it needs to be specified how its vertices need to be placed and updated inside the deformation mesh.
This method computes that embedding information.
\param[in] params The cooking parameters
\param[in] simulationMesh A tetrahedral mesh that defines the shape of the simulation mesh which is used to compute the body's deformation
\param[in] collisionMesh A tetrahedral mesh that defines the shape of the collision mesh which is used for collision detection
\param[in] collisionData A data container that contains acceleration structures and surface information of the collision mesh
\param[in] vertexToTet Optional indices (array of integers) that specifies the index of the tetrahedron in the simulation mesh that
contains a collision mesh vertex. If not provided, the embedding will be computed internally. If the simulation mesh is obtained from
PxTetMaker::createVoxelTetrahedronMesh, then the vertexToTet map createVoxelTetrahedronMesh returned should be used here.
\return PxCollisionMeshMappingData pointer that describes how the collision mesh is embedded into the simulation mesh
@see PxTetMaker::createVoxelTetrahedronMesh
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxCollisionMeshMappingData* PxComputeModelsMapping(const physx::PxCookingParams& params, physx::PxTetrahedronMeshData& simulationMesh, const physx::PxTetrahedronMeshData& collisionMesh,
const physx::PxSoftBodyCollisionData& collisionData, const physx::PxBoundedData* vertexToTet = NULL);
/**
\brief Computes data to accelerate collision detection of tetrahedral meshes
Computes data structures to speed up collision detection with tetrahedral meshes.
\param[in] params The cooking parameters
\param[in] collisionMeshDesc Raw tetrahedral mesh descriptor wich will be used for collision detection
\return PxCollisionTetrahedronMeshData pointer that describes the collision mesh
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxCollisionTetrahedronMeshData* PxComputeCollisionData(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& collisionMeshDesc);
/**
\brief Computes data to accelerate collision detection of tetrahedral meshes
Computes data to compute and store a softbody's deformation using FEM.
\param[in] params The cooking parameters
\param[in] simulationMeshDesc Raw tetrahedral mesh descriptor wich will be used for FEM simulation
\return PxSimulationTetrahedronMeshData pointer that describes the simulation mesh
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxSimulationTetrahedronMeshData* PxComputeSimulationData(const physx::PxCookingParams& params, const physx::PxTetrahedronMeshDesc& simulationMeshDesc);
/**
\brief Bundles all data required for softbody simulation
Creates a container that provides everything to create a PxSoftBody
\param[in] simulationMesh The geometry (tetrahedral mesh) to be used as simulation mesh
\param[in] simulationData Additional non-tetmesh data that contains mass information etc. for the simulation mesh
\param[in] collisionMesh The geometry (tetrahedral mesh) to be used for collision detection
\param[in] collisionData Additional non-tetmesh data that contains surface information, acceleration structures etc. for the simulation mesh
\param[in] mappingData Mapping that describes how the collision mesh's vertices are embedded into the simulation mesh
\param[in] insertionCallback The insertion interface from PxPhysics.
\return PxSoftBodyMesh pointer that represents a softbody mesh bundling all data (simulation mesh, collision mesh etc.)
@see PxSoftBody createSoftBody()
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxSoftBodyMesh* PxAssembleSoftBodyMesh(physx::PxTetrahedronMeshData& simulationMesh, physx::PxSoftBodySimulationData& simulationData, physx::PxTetrahedronMeshData& collisionMesh,
physx::PxSoftBodyCollisionData& collisionData, physx::PxCollisionMeshMappingData& mappingData, physx::PxInsertionCallback& insertionCallback);
/**
\brief Bundles all data required for softbody simulation
Creates a container that provides everything to create a PxSoftBody
\param[in] simulationMesh Container that provides all information about the simulation mesh (geometry, mass distribution etc.)
\param[in] collisionMesh Container that provides all information about the collision mesh (geometry, surface information, acceleration structures etc.)
\param[in] mappingData Mapping that describes how the collision mesh's vertices are embedded into the simulation mesh
\param[in] insertionCallback The insertion interface from PxPhysics.
\return PxSoftBodyMesh pointer that represents a softbody mesh bundling all data (simulation mesh, collision mesh etc.)
@see PxSoftBody createSoftBody()
*/
PX_C_EXPORT PX_PHYSX_COOKING_API physx::PxSoftBodyMesh* PxAssembleSoftBodyMesh_Sim(physx::PxSimulationTetrahedronMeshData& simulationMesh, physx::PxCollisionTetrahedronMeshData& collisionMesh,
physx::PxCollisionMeshMappingData& mappingData, physx::PxInsertionCallback& insertionCallback);
/** @} */
#endif
| 37,173 | C | 41.876586 | 259 | 0.788718 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxTetrahedronMeshDesc.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_TETRAHEDRON_MESH_DESC_H
#define PX_TETRAHEDRON_MESH_DESC_H
/** \addtogroup cooking
@{
*/
#include "PxPhysXConfig.h"
#include "foundation/PxVec3.h"
#include "foundation/PxFlags.h"
#include "common/PxCoreUtilityTypes.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "foundation/PxArray.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Descriptor class for #PxTetrahedronMesh (contains only pure geometric data).
@see PxTetrahedronMesh PxShape
*/
class PxTetrahedronMeshDesc
{
public:
/**
\brief Defines the tetrahedron structure of a mesh.
*/
enum PxMeshFormat
{
eTET_MESH, //!< Normal tetmesh with arbitrary tetrahedra
eHEX_MESH //!< 6 tetrahedra in a row will form a hexahedron
};
/**
Optional pointer to first material index, or NULL. There are PxTetrahedronMesh::numTriangles indices in total.
Caller may add materialIndexStride bytes to the pointer to access the next triangle.
When a tetrahedron mesh collides with another object, a material is required at the collision point.
If materialIndices is NULL, then the material of the PxShape instance is used.
Otherwise, if the point of contact is on a tetrahedron with index i, then the material index is determined as:
PxFEMMaterialTableIndex index = *(PxFEMMaterialTableIndex *)(((PxU8*)materialIndices) + materialIndexStride * i);
If the contact point falls on a vertex or an edge, a tetrahedron adjacent to the vertex or edge is selected, and its index
used to look up a material. The selection is arbitrary but consistent over time.
<b>Default:</b> NULL
@see materialIndexStride
*/
PxTypedStridedData<PxFEMMaterialTableIndex> materialIndices;
/**
\brief Pointer to first vertex point.
*/
PxBoundedData points;
/**
\brief Pointer to first tetrahedron.
Caller may add tetrhedronStrideBytes bytes to the pointer to access the next tetrahedron.
These are quadruplets of 0 based indices:
vert0 vert1 vert2 vert3
vert0 vert1 vert2 vert3
vert0 vert1 vert2 vert3
...
where vertex is either a 32 or 16 bit unsigned integer. There are numTetrahedrons*4 indices.
This is declared as a void pointer because it is actually either an PxU16 or a PxU32 pointer.
*/
PxBoundedData tetrahedrons;
/**
\brief Flags bits, combined from values of the enum ::PxMeshFlag
*/
PxMeshFlags flags;
/**
\brief Used for simulation meshes only. Defines if this tet mesh should be simulated as a tet mesh,
or if a set of tetrahedra should be used to represent another shape, e.g. a hexahedral mesh constructed
from 6 elements.
*/
PxU16 tetsPerElement;
/**
\brief Constructor to build an empty tetmesh description
*/
PxTetrahedronMeshDesc()
{
points.count = 0;
points.stride = 0;
points.data = NULL;
tetrahedrons.count = 0;
tetrahedrons.stride = 0;
tetrahedrons.data = NULL;
tetsPerElement = 1;
}
/**
\brief Constructor to build a tetmeshdescription that links to the vertices and indices provided
*/
PxTetrahedronMeshDesc(physx::PxArray<physx::PxVec3>& meshVertices, physx::PxArray<physx::PxU32>& meshTetIndices,
const PxTetrahedronMeshDesc::PxMeshFormat meshFormat = eTET_MESH, PxU16 numberOfTetsPerHexElement = 5)
{
points.count = meshVertices.size();
points.stride = sizeof(float) * 3;
points.data = meshVertices.begin();
tetrahedrons.count = meshTetIndices.size() / 4;
tetrahedrons.stride = sizeof(int) * 4;
tetrahedrons.data = meshTetIndices.begin();
if (meshFormat == eTET_MESH)
tetsPerElement = 1;
else
tetsPerElement = numberOfTetsPerHexElement;
}
PX_INLINE bool isValid() const
{
// Check geometry of the collision mesh
if (points.count < 4) //at least 1 tetrahedron's worth of points
return false;
if ((!tetrahedrons.data) && (points.count % 4)) // Non-indexed mesh => we must ensure the geometry defines an implicit number of tetrahedrons // i.e. numVertices can't be divided by 4
return false;
if (points.count > 0xffff && flags & PxMeshFlag::e16_BIT_INDICES)
return false;
if (!points.data)
return false;
if (points.stride < sizeof(PxVec3)) //should be at least one point's worth of data
return false;
//add more validity checks here
if (materialIndices.data && materialIndices.stride < sizeof(PxFEMMaterialTableIndex))
return false;
// The tetrahedrons pointer is not mandatory
if (tetrahedrons.data)
{
// Indexed collision mesh
PxU32 limit = (flags & PxMeshFlag::e16_BIT_INDICES) ? sizeof(PxU16) * 4 : sizeof(PxU32) * 4;
if (tetrahedrons.stride < limit)
return false;
}
//The model can only be either a tetmesh (1 tet per element), or have 5 or 6 tets per hex element, otherwise invalid.
if (tetsPerElement != 1 && tetsPerElement != 5 && tetsPerElement != 6)
return false;
return true;
}
};
///**
//\brief Descriptor class for #PxSoftBodyMesh (contains only additional data used for softbody simulation).
//@see PxSoftBodyMesh PxShape
//*/
class PxSoftBodySimulationDataDesc
{
public:
/**
\brief Pointer to first index of tetrahedron that contains the vertex at the same location in the vertex buffer.
if left unassigned it will be computed automatically. If a point is inside multiple tetrahedra (ambiguous case), the frist one found will be taken.
*/
PxBoundedData vertexToTet;
/**
\brief Constructor to build an empty simulation description
*/
PxSoftBodySimulationDataDesc()
{
vertexToTet.count = 0;
vertexToTet.stride = 0;
vertexToTet.data = NULL;
}
/**
\brief Constructor to build a simulation description with a defined vertex to tetrahedron mapping
*/
PxSoftBodySimulationDataDesc(physx::PxArray<physx::PxI32>& vertToTet)
{
vertexToTet.count = vertToTet.size();
vertexToTet.stride = sizeof(PxI32);
vertexToTet.data = vertToTet.begin();
}
PX_INLINE bool isValid() const
{
return true;
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 7,718 | C | 31.846808 | 187 | 0.728686 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxBVH33MidphaseDesc.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_BVH_33_MIDPHASE_DESC_H
#define PX_BVH_33_MIDPHASE_DESC_H
/** \addtogroup cooking
@{
*/
#include "foundation/PxPreprocessor.h"
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
* \brief Enumeration for mesh cooking hints.
* @deprecated
*/
struct PX_DEPRECATED PxMeshCookingHint
{
enum Enum
{
eSIM_PERFORMANCE = 0, //!< Default value. Favors higher quality hierarchy with higher runtime performance over cooking speed.
eCOOKING_PERFORMANCE = 1 //!< Enables fast cooking path at the expense of somewhat lower quality hierarchy construction.
};
};
/**
\brief Structure describing parameters affecting BVH33 midphase mesh structure.
@see PxCookingParams, PxMidphaseDesc
@deprecated
*/
struct PX_DEPRECATED PxBVH33MidphaseDesc
{
/**
\brief Controls the trade-off between mesh size and runtime performance.
Using a value of 1.0 will produce a larger cooked mesh with generally higher runtime performance,
using 0.0 will produce a smaller cooked mesh, with generally lower runtime performance.
Values outside of [0,1] range will be clamped and cause a warning when any mesh gets cooked.
<b>Default value:</b> 0.55
<b>Range:</b> [0.0f, 1.0f]
*/
PxF32 meshSizePerformanceTradeOff;
/**
\brief Mesh cooking hint. Used to specify mesh hierarchy construction preference.
<b>Default value:</b> PxMeshCookingHint::eSIM_PERFORMANCE
*/
PxMeshCookingHint::Enum meshCookingHint;
/**
\brief Desc initialization to default value.
*/
void setToDefault()
{
meshSizePerformanceTradeOff = 0.55f;
meshCookingHint = PxMeshCookingHint::eSIM_PERFORMANCE;
}
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
bool isValid() const
{
if(meshSizePerformanceTradeOff < 0.0f || meshSizePerformanceTradeOff > 1.0f)
return false;
return true;
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,653 | C | 31.052631 | 128 | 0.748152 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxTriangleMeshDesc.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_TRIANGLE_MESH_DESC_H
#define PX_TRIANGLE_MESH_DESC_H
/** \addtogroup cooking
@{
*/
#include "PxPhysXConfig.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "PxSDFDesc.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Descriptor class for #PxTriangleMesh.
Note that this class is derived from PxSimpleTriangleMesh which contains the members that describe the basic mesh.
The mesh data is *copied* when an PxTriangleMesh object is created from this descriptor. After the call the
user may discard the triangle data.
@see PxTriangleMesh PxTriangleMeshGeometry PxShape
*/
class PxTriangleMeshDesc : public PxSimpleTriangleMesh
{
public:
/**
Optional pointer to first material index, or NULL. There are PxSimpleTriangleMesh::numTriangles indices in total.
Caller may add materialIndexStride bytes to the pointer to access the next triangle.
When a triangle mesh collides with another object, a material is required at the collision point.
If materialIndices is NULL, then the material of the PxShape instance is used.
Otherwise, if the point of contact is on a triangle with index i, then the material index is determined as:
PxMaterialTableIndex index = *(PxMaterialTableIndex *)(((PxU8*)materialIndices) + materialIndexStride * i);
If the contact point falls on a vertex or an edge, a triangle adjacent to the vertex or edge is selected, and its index
used to look up a material. The selection is arbitrary but consistent over time.
<b>Default:</b> NULL
@see materialIndexStride
*/
PxTypedStridedData<PxMaterialTableIndex> materialIndices;
/**
\brief SDF descriptor. When this descriptor is set, signed distance field is calculated for this convex mesh.
<b>Default:</b> NULL
*/
PxSDFDesc* sdfDesc;
/**
\brief Constructor sets to default.
*/
PX_INLINE PxTriangleMeshDesc();
/**
\brief (re)sets the structure to the default.
*/
PX_INLINE void setToDefault();
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxTriangleMeshDesc::PxTriangleMeshDesc() //constructor sets to default
{
PxSimpleTriangleMesh::setToDefault();
sdfDesc = NULL;
}
PX_INLINE void PxTriangleMeshDesc::setToDefault()
{
*this = PxTriangleMeshDesc();
}
PX_INLINE bool PxTriangleMeshDesc::isValid() const
{
if(points.count < 3) //at least 1 trig's worth of points
return false;
if ((!triangles.data) && (points.count%3)) // Non-indexed mesh => we must ensure the geometry defines an implicit number of triangles // i.e. numVertices can't be divided by 3
return false;
//add more validity checks here
if (materialIndices.data && materialIndices.stride < sizeof(PxMaterialTableIndex))
return false;
if (sdfDesc && !sdfDesc->isValid())
return false;
return PxSimpleTriangleMesh::isValid();
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,610 | C | 33.155555 | 177 | 0.757701 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxBVH34MidphaseDesc.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_BVH_34_MIDPHASE_DESC_H
#define PX_BVH_34_MIDPHASE_DESC_H
/** \addtogroup cooking
@{
*/
#include "foundation/PxPreprocessor.h"
#include "foundation/PxSimpleTypes.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Desired build strategy for PxMeshMidPhase::eBVH34
*/
struct PxBVH34BuildStrategy
{
enum Enum
{
eFAST = 0, //!< Fast build strategy. Fast build speed, good runtime performance in most cases. Recommended for runtime mesh cooking.
eDEFAULT = 1, //!< Default build strategy. Medium build speed, good runtime performance in all cases.
eSAH = 2, //!< SAH build strategy. Slower builds, slightly improved runtime performance in some cases.
eLAST
};
};
/**
\brief Structure describing parameters affecting BVH34 midphase mesh structure.
@see PxCookingParams, PxMidphaseDesc
*/
struct PxBVH34MidphaseDesc
{
/**
\brief Mesh cooking hint for max primitives per leaf limit.
Less primitives per leaf produces larger meshes with better runtime performance
and worse cooking performance. More triangles per leaf results in faster cooking speed and
smaller mesh sizes, but with worse runtime performance.
<b>Default value:</b> 4
<b>Range:</b> <2, 15>
*/
PxU32 numPrimsPerLeaf;
/**
\brief Desired build strategy for the BVH
<b>Default value:</b> eDEFAULT
*/
PxBVH34BuildStrategy::Enum buildStrategy;
/**
\brief Whether the tree should be quantized or not
Quantized trees use up less memory, but the runtime dequantization (to retrieve the node bounds) might have
a measurable performance cost. In most cases the cost is too small to matter, and using less memory is more
important. Hence, the default is true.
One important use case for non-quantized trees is deformable meshes. The refit function for the BVH is not
supported for quantized trees.
<b>Default value:</b> true
*/
bool quantized;
/**
\brief Desc initialization to default value.
*/
void setToDefault()
{
numPrimsPerLeaf = 4;
buildStrategy = PxBVH34BuildStrategy::eDEFAULT;
quantized = true;
}
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
bool isValid() const
{
if(numPrimsPerLeaf < 2 || numPrimsPerLeaf > 15)
return false;
return true;
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 4,031 | C | 30.255814 | 135 | 0.745473 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxSDFDesc.h | // Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of NVIDIA CORPORATION nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008-2023 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_SDF_DESC_H
#define PX_SDF_DESC_H
/** \addtogroup cooking
@{
*/
#include "PxPhysXConfig.h"
#include "geometry/PxSimpleTriangleMesh.h"
#include "foundation/PxBounds3.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
class PxSDFBuilder;
/**
\brief A helper structure to define dimensions in 3D
*/
struct PxDim3
{
PxU32 x, y, z;
};
/**
\brief Defines the number of bits per subgrid pixel
*/
class PxSdfBitsPerSubgridPixel
{
public:
enum Enum
{
e8_BIT_PER_PIXEL = 1, //!< 8 bit per subgrid pixel (values will be stored as normalized integers)
e16_BIT_PER_PIXEL = 2, //!< 16 bit per subgrid pixel (values will be stored as normalized integers)
e32_BIT_PER_PIXEL = 4 //!< 32 bit per subgrid pixel (values will be stored as floats in world scale units)
};
};
/**
\brief A structure describing signed distance field for mesh.
*/
class PxSDFDesc
{
public:
/**
\brief Pointer to first sdf array element.
*/
PxBoundedData sdf;
/**
\brief Dimensions of sdf
*/
PxDim3 dims;
/**
\brief The Lower bound of the original mesh
*/
PxVec3 meshLower;
/**
\brief The spacing of each sdf voxel
*/
PxReal spacing;
/**
\brief The number of cells in a sparse subgrid block (full block has subgridSize^3 cells and (subgridSize+1)^3 samples). If set to zero, this indicates that only a dense background grid SDF is used without sparse blocks
*/
PxU32 subgridSize;
/**
\brief Enumeration that defines the number of bits per subgrid pixel (either 32, 16 or 8bits)
*/
PxSdfBitsPerSubgridPixel::Enum bitsPerSubgridPixel;
/**
\brief Number of subgrid blocks in the 3d texture. The full texture dimension will be sdfSubgrids3DTexBlockDim*(subgridSize+1).
*/
PxDim3 sdfSubgrids3DTexBlockDim;
/**
\brief The data to create the 3d texture containg the packed subgrid blocks. Stored as PxU8 to support multiple formats (8, 16 and 32 bits per pixel)
*/
PxBoundedData sdfSubgrids;
/**
\brief Array with start indices into the subgrid texture for every subgrid block. 10bits for z coordinate, 10bits for y and 10bits for x. Encoding is as follows: slot = (z << 20) | (y << 10) | x
*/
PxBoundedData sdfStartSlots;
/**
\brief The minimum value over all subgrid blocks. Used if normalized textures are used which is the case for 8 and 16bit formats
*/
PxReal subgridsMinSdfValue;
/**
\brief The maximum value over all subgrid blocks. Used if normalized textures are used which is the case for 8 and 16bit formats
*/
PxReal subgridsMaxSdfValue;
/**
\brief The bounds of the sdf. If left unassigned (empty), the bounds of the mesh will be used
*/
PxBounds3 sdfBounds;
/**
\brief Narrow band thickness as a fraction of the bounds diagonal length. Every subgrid block that
overlaps with the narrow band around the mesh surface will be kept providing high resultion around the mesh surface.
The valid range of this parameter is (0, 1). The higher the value, the more subgrids will get created, the more memory will be required.
*/
PxReal narrowBandThicknessRelativeToSdfBoundsDiagonal;
/**
\brief The number of threads that are launched to compute the signed distance field
*/
PxU32 numThreadsForSdfConstruction;
/**
\brief Optional pointer to the geometry of the mesh that is used to compute the SDF. If it is not set, the geometry of the mesh, that this descriptor is passed to during cooking, will be taken.
The mesh data must only be available during cooking. It can be released once cooking completed.
*/
PxSimpleTriangleMesh baseMesh;
/**
\brief Optional pointer to an instance of a SDF builder. This siginificantly speeds up the construction of the SDF since the default sdf builer will do almost all computations directly on the GPU.
The user must release the instance of the sdfBuilder once cooking completed.
*/
PxSDFBuilder* sdfBuilder;
/**
\brief Constructor
*/
PX_INLINE PxSDFDesc();
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid
*/
PX_INLINE bool isValid() const;
};
PX_INLINE PxSDFDesc::PxSDFDesc()
{
sdf.data = NULL;
dims.x = 0;
dims.y = 0;
dims.z = 0;
spacing = 0;
meshLower = PxVec3(PxZero);
subgridSize = 0;
subgridsMinSdfValue = 0.0f;
subgridsMaxSdfValue = 0.0f;
sdfBounds = PxBounds3::empty();
bitsPerSubgridPixel = PxSdfBitsPerSubgridPixel::e16_BIT_PER_PIXEL;
narrowBandThicknessRelativeToSdfBoundsDiagonal = 0.01f;
numThreadsForSdfConstruction = 1;
sdfBuilder = NULL;
}
PX_INLINE bool PxSDFDesc::isValid() const
{
// Check validity of user's input(if any)
if (sdf.data)
{
if (dims.x < 1 || dims.y < 1 || dims.z < 1)
return false;
if (!meshLower.isFinite())
return false;
if (spacing <= 0)
return false;
}
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 6,608 | C | 30.322275 | 221 | 0.723517 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxMidphaseDesc.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_MIDPHASE_DESC_H
#define PX_MIDPHASE_DESC_H
/** \addtogroup cooking
@{
*/
#include "geometry/PxTriangleMesh.h"
#include "cooking/PxBVH33MidphaseDesc.h"
#include "cooking/PxBVH34MidphaseDesc.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Structure describing parameters affecting midphase mesh structure.
@see PxCookingParams, PxBVH33MidphaseDesc, PxBVH34MidphaseDesc
*/
class PxMidphaseDesc
{
public:
PX_FORCE_INLINE PxMidphaseDesc() { setToDefault(PxMeshMidPhase::eBVH34); }
/**
\brief Returns type of midphase mesh structure.
\return PxMeshMidPhase::Enum
@see PxMeshMidPhase::Enum
*/
PX_FORCE_INLINE PxMeshMidPhase::Enum getType() const { return mType; }
/**
\brief Midphase descriptors union
@see PxBV33MidphaseDesc, PxBV34MidphaseDesc
*/
union {
PxBVH33MidphaseDesc mBVH33Desc;
PxBVH34MidphaseDesc mBVH34Desc;
};
/**
\brief Initialize the midphase mesh structure descriptor
\param[in] type Midphase mesh structure descriptor
@see PxBV33MidphaseDesc, PxBV34MidphaseDesc
*/
void setToDefault(PxMeshMidPhase::Enum type)
{
mType = type;
if(type==PxMeshMidPhase::eBVH33)
mBVH33Desc.setToDefault();
else if(type==PxMeshMidPhase::eBVH34)
mBVH34Desc.setToDefault();
}
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
bool isValid() const
{
if(mType==PxMeshMidPhase::eBVH33)
return mBVH33Desc.isValid();
else if(mType==PxMeshMidPhase::eBVH34)
return mBVH34Desc.isValid();
return false;
}
/**
\brief Assignment operator
\return this
*/
PX_FORCE_INLINE PxMidphaseDesc& operator=(PxMeshMidPhase::Enum descType)
{
setToDefault(descType);
return *this;
}
protected:
PxMeshMidPhase::Enum mType;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,518 | C | 27.609756 | 75 | 0.749289 |
NVIDIA-Omniverse/PhysX/physx/include/cooking/PxBVHDesc.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_BVH_DESC_H
#define PX_BVH_DESC_H
/** \addtogroup cooking
@{
*/
#include "common/PxCoreUtilityTypes.h"
#include "foundation/PxTransform.h"
#include "foundation/PxBounds3.h"
#include "geometry/PxBVHBuildStrategy.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief Descriptor class for #PxBVH.
@see PxBVH
*/
class PxBVHDesc
{
public:
PX_INLINE PxBVHDesc();
/**
\brief Pointer to first bounding box.
*/
PxBoundedData bounds;
/**
\brief Bounds enlargement
Passed bounds are slightly enlarged before creating the BVH. This is done to avoid numerical issues when
e.g. raycasts just graze the bounds. The performed operation is:
extents = (bounds.maximum - bounds.minimum)/2
enlagedBounds.minimum = passedBounds.minium - extents * enlargement
enlagedBounds.maximum = passedBounds.maxium + extents * enlargement
Users can pass pre-enlarged bounds to the BVH builder, in which case just set the enlargement value to zero.
<b>Default value:</b> 0.01
*/
float enlargement;
/**
\brief Max primitives per leaf limit.
<b>Range:</b> [0, 16)<br>
<b>Default value:</b> 4
*/
PxU32 numPrimsPerLeaf;
/**
\brief Desired build strategy for the BVH
<b>Default value:</b> eDEFAULT
*/
PxBVHBuildStrategy::Enum buildStrategy;
/**
\brief Initialize the BVH descriptor
*/
PX_INLINE void setToDefault();
/**
\brief Returns true if the descriptor is valid.
\return true if the current settings are valid.
*/
PX_INLINE bool isValid() const;
protected:
};
PX_INLINE PxBVHDesc::PxBVHDesc() : enlargement(0.01f), numPrimsPerLeaf(4), buildStrategy(PxBVHBuildStrategy::eDEFAULT)
{
}
PX_INLINE void PxBVHDesc::setToDefault()
{
*this = PxBVHDesc();
}
PX_INLINE bool PxBVHDesc::isValid() const
{
// Check BVH desc data
if(!bounds.data)
return false;
if(bounds.stride < sizeof(PxBounds3)) //should be at least one bounds' worth of data
return false;
if(bounds.count == 0)
return false;
if(enlargement<0.0f)
return false;
if(numPrimsPerLeaf>=16)
return false;
return true;
}
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 3,787 | C | 26.057143 | 118 | 0.738843 |
NVIDIA-Omniverse/PhysX/physx/include/foundation/PxHashMap.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_HASHMAP_H
#define PX_HASHMAP_H
#include "foundation/PxHashInternals.h"
// TODO: make this doxy-format
//
// This header defines two hash maps. Hash maps
// * support custom initial table sizes (rounded up internally to power-of-2)
// * support custom static allocator objects
// * auto-resize, based on a load factor (i.e. a 64-entry .75 load factor hash will resize
// when the 49th element is inserted)
// * are based on open hashing
// * have O(1) contains, erase
//
// Maps have STL-like copying semantics, and properly initialize and destruct copies of objects
//
// There are two forms of map: coalesced and uncoalesced. Coalesced maps keep the entries in the
// initial segment of an array, so are fast to iterate over; however deletion is approximately
// twice as expensive.
//
// HashMap<T>:
// bool insert(const Key& k, const Value& v) O(1) amortized (exponential resize policy)
// Value & operator[](const Key& k) O(1) for existing objects, else O(1) amortized
// const Entry * find(const Key& k); O(1)
// bool erase(const T& k); O(1)
// uint32_t size(); constant
// void reserve(uint32_t size); O(MAX(currentOccupancy,size))
// void clear(); O(currentOccupancy) (with zero constant for objects
// without
// destructors)
// Iterator getIterator();
//
// operator[] creates an entry if one does not exist, initializing with the default constructor.
// CoalescedHashMap<T> does not support getIterator, but instead supports
// const Key *getEntries();
//
// Use of iterators:
//
// for(HashMap::Iterator iter = test.getIterator(); !iter.done(); ++iter)
// myFunction(iter->first, iter->second);
#if !PX_DOXYGEN
namespace physx
{
#endif
template <class Key, class Value, class HashFn = PxHash<Key>, class Allocator = PxAllocator>
class PxHashMap : public physx::PxHashMapBase<Key, Value, HashFn, Allocator>
{
public:
typedef physx::PxHashMapBase<Key, Value, HashFn, Allocator> HashMapBase;
typedef typename HashMapBase::Iterator Iterator;
PxHashMap(uint32_t initialTableSize = 64, float loadFactor = 0.75f) : HashMapBase(initialTableSize, loadFactor)
{
}
PxHashMap(uint32_t initialTableSize, float loadFactor, const Allocator& alloc)
: HashMapBase(initialTableSize, loadFactor, alloc)
{
}
PxHashMap(const Allocator& alloc) : HashMapBase(64, 0.75f, alloc)
{
}
Iterator getIterator()
{
return Iterator(HashMapBase::mBase);
}
};
template <class Key, class Value, class HashFn = PxHash<Key>, class Allocator = PxAllocator>
class PxCoalescedHashMap : public physx::PxHashMapBase<Key, Value, HashFn, Allocator>
{
public:
typedef physx::PxHashMapBase<Key, Value, HashFn, Allocator> HashMapBase;
PxCoalescedHashMap(uint32_t initialTableSize = 64, float loadFactor = 0.75f)
: HashMapBase(initialTableSize, loadFactor)
{
}
const PxPair<const Key, Value>* getEntries() const
{
return HashMapBase::mBase.getEntries();
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#endif
| 4,719 | C | 38.333333 | 112 | 0.729816 |
NVIDIA-Omniverse/PhysX/physx/include/foundation/PxHash.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_HASH_H
#define PX_HASH_H
#include "foundation/PxBasicTemplates.h"
#include "foundation/PxString.h"
#if PX_VC
#pragma warning(push)
#pragma warning(disable : 4302)
#endif
#if PX_LINUX
#include "foundation/PxSimpleTypes.h"
#endif
/*!
Central definition of hash functions
*/
#if !PX_DOXYGEN
namespace physx
{
#endif
// Hash functions
// Thomas Wang's 32 bit mix
// http://www.cris.com/~Ttwang/tech/inthash.htm
PX_FORCE_INLINE uint32_t PxComputeHash(const uint32_t key)
{
uint32_t k = key;
k += ~(k << 15);
k ^= (k >> 10);
k += (k << 3);
k ^= (k >> 6);
k += ~(k << 11);
k ^= (k >> 16);
return uint32_t(k);
}
PX_FORCE_INLINE uint32_t PxComputeHash(const int32_t key)
{
return PxComputeHash(uint32_t(key));
}
// Thomas Wang's 64 bit mix
// http://www.cris.com/~Ttwang/tech/inthash.htm
PX_FORCE_INLINE uint32_t PxComputeHash(const uint64_t key)
{
uint64_t k = key;
k += ~(k << 32);
k ^= (k >> 22);
k += ~(k << 13);
k ^= (k >> 8);
k += (k << 3);
k ^= (k >> 15);
k += ~(k << 27);
k ^= (k >> 31);
return uint32_t(UINT32_MAX & k);
}
#if PX_APPLE_FAMILY
// hash for size_t, to make gcc happy
PX_INLINE uint32_t PxComputeHash(const size_t key)
{
#if PX_P64_FAMILY
return PxComputeHash(uint64_t(key));
#else
return PxComputeHash(uint32_t(key));
#endif
}
#endif
// Hash function for pointers
PX_INLINE uint32_t PxComputeHash(const void* ptr)
{
#if PX_P64_FAMILY
return PxComputeHash(uint64_t(ptr));
#else
return PxComputeHash(uint32_t(UINT32_MAX & size_t(ptr)));
#endif
}
// Hash function for pairs
template <typename F, typename S>
PX_INLINE uint32_t PxComputeHash(const PxPair<F, S>& p)
{
uint32_t seed = 0x876543;
uint32_t m = 1000007;
return PxComputeHash(p.second) ^ (m * (PxComputeHash(p.first) ^ (m * seed)));
}
// hash object for hash map template parameter
template <class Key>
struct PxHash
{
uint32_t operator()(const Key& k) const
{
return PxComputeHash(k);
}
bool equal(const Key& k0, const Key& k1) const
{
return k0 == k1;
}
};
// specialization for strings
template <>
struct PxHash<const char*>
{
public:
uint32_t operator()(const char* _string) const
{
// "DJB" string hash
const uint8_t* string = reinterpret_cast<const uint8_t*>(_string);
uint32_t h = 5381;
for(const uint8_t* ptr = string; *ptr; ptr++)
h = ((h << 5) + h) ^ uint32_t(*ptr);
return h;
}
bool equal(const char* string0, const char* string1) const
{
return !Pxstrcmp(string0, string1);
}
};
#if !PX_DOXYGEN
} // namespace physx
#endif
#if PX_VC
#pragma warning(pop)
#endif
#endif
| 4,232 | C | 24.810975 | 78 | 0.698724 |
NVIDIA-Omniverse/PhysX/physx/include/foundation/PxErrorCallback.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_ERROR_CALLBACK_H
#define PX_ERROR_CALLBACK_H
/** \addtogroup foundation
@{
*/
#include "foundation/PxErrors.h"
#if !PX_DOXYGEN
namespace physx
{
#endif
/**
\brief User defined interface class. Used by the library to emit debug information.
\note The SDK state should not be modified from within any error reporting functions.
<b>Threading:</b> The SDK sequences its calls to the output stream using a mutex, so the class need not
be implemented in a thread-safe manner if the SDK is the only client.
*/
class PxErrorCallback
{
public:
virtual ~PxErrorCallback()
{
}
/**
\brief Reports an error code.
\param code Error code, see #PxErrorCode
\param message Message to display.
\param file File error occured in.
\param line Line number error occured on.
*/
virtual void reportError(PxErrorCode::Enum code, const char* message, const char* file, int line) = 0;
};
#if !PX_DOXYGEN
} // namespace physx
#endif
/** @} */
#endif
| 2,653 | C | 34.864864 | 103 | 0.752733 |
Subsets and Splits